src/Pure/PIDE/document.scala
author wenzelm
Sat May 03 22:47:43 2014 +0200 (2014-05-03 ago)
changeset 56843 b2bfcd8cda80
parent 56801 8dd9df88f647
child 57610 518e28a7c74b
permissions -rw-r--r--
support for path completion based on file-system content;
     1 /*  Title:      Pure/PIDE/document.scala
     2     Author:     Makarius
     3 
     4 Document as collection of named nodes, each consisting of an editable
     5 list of commands, associated with asynchronous execution process.
     6 */
     7 
     8 package isabelle
     9 
    10 
    11 import scala.collection.mutable
    12 
    13 
    14 object Document
    15 {
    16   /** document structure **/
    17 
    18   /* overlays -- print functions with arguments */
    19 
    20   object Overlays
    21   {
    22     val empty = new Overlays(Map.empty)
    23   }
    24 
    25   final class Overlays private(rep: Map[Node.Name, Node.Overlays])
    26   {
    27     def apply(name: Document.Node.Name): Node.Overlays =
    28       rep.getOrElse(name, Node.Overlays.empty)
    29 
    30     private def update(name: Node.Name, f: Node.Overlays => Node.Overlays): Overlays =
    31     {
    32       val node_overlays = f(apply(name))
    33       new Overlays(if (node_overlays.is_empty) rep - name else rep + (name -> node_overlays))
    34     }
    35 
    36     def insert(command: Command, fn: String, args: List[String]): Overlays =
    37       update(command.node_name, _.insert(command, fn, args))
    38 
    39     def remove(command: Command, fn: String, args: List[String]): Overlays =
    40       update(command.node_name, _.remove(command, fn, args))
    41 
    42     override def toString: String = rep.mkString("Overlays(", ",", ")")
    43   }
    44 
    45 
    46   /* document blobs: auxiliary files */
    47 
    48   sealed case class Blob(bytes: Bytes, chunk: Symbol.Text_Chunk, changed: Boolean)
    49   {
    50     def unchanged: Blob = copy(changed = false)
    51   }
    52 
    53   object Blobs
    54   {
    55     def apply(blobs: Map[Node.Name, Blob]): Blobs = new Blobs(blobs)
    56     val empty: Blobs = apply(Map.empty)
    57   }
    58 
    59   final class Blobs private(blobs: Map[Node.Name, Blob])
    60   {
    61     private lazy val digests: Map[SHA1.Digest, Blob] =
    62       for ((_, blob) <- blobs) yield (blob.bytes.sha1_digest, blob)
    63 
    64     def get(digest: SHA1.Digest): Option[Blob] = digests.get(digest)
    65     def get(name: Node.Name): Option[Blob] = blobs.get(name)
    66 
    67     def changed(name: Node.Name): Boolean =
    68       get(name) match {
    69         case Some(blob) => blob.changed
    70         case None => false
    71       }
    72 
    73     override def toString: String = blobs.mkString("Blobs(", ",", ")")
    74   }
    75 
    76 
    77   /* document nodes: theories and auxiliary files */
    78 
    79   type Edit[A, B] = (Node.Name, Node.Edit[A, B])
    80   type Edit_Text = Edit[Text.Edit, Text.Perspective]
    81   type Edit_Command = Edit[Command.Edit, Command.Perspective]
    82 
    83   object Node
    84   {
    85     val empty: Node = new Node()
    86 
    87 
    88     /* header and name */
    89 
    90     sealed case class Header(
    91       imports: List[Name],
    92       keywords: Thy_Header.Keywords,
    93       errors: List[String] = Nil)
    94     {
    95       def error(msg: String): Header = copy(errors = errors ::: List(msg))
    96 
    97       def cat_errors(msg2: String): Header =
    98         copy(errors = errors.map(msg1 => Library.cat_message(msg1, msg2)))
    99     }
   100 
   101     def bad_header(msg: String): Header = Header(Nil, Nil, List(msg))
   102 
   103     val no_header = bad_header("No theory header")
   104 
   105     object Name
   106     {
   107       val empty = Name("")
   108 
   109       object Ordering extends scala.math.Ordering[Name]
   110       {
   111         def compare(name1: Name, name2: Name): Int = name1.node compare name2.node
   112       }
   113     }
   114 
   115     sealed case class Name(node: String, master_dir: String = "", theory: String = "")
   116     {
   117       override def hashCode: Int = node.hashCode
   118       override def equals(that: Any): Boolean =
   119         that match {
   120           case other: Name => node == other.node
   121           case _ => false
   122         }
   123 
   124       def is_theory: Boolean = !theory.isEmpty
   125       override def toString: String = if (is_theory) theory else node
   126 
   127       def map(f: String => String): Name = copy(f(node), f(master_dir), theory)
   128     }
   129 
   130 
   131     /* node overlays */
   132 
   133     object Overlays
   134     {
   135       val empty = new Overlays(Multi_Map.empty)
   136     }
   137 
   138     final class Overlays private(rep: Multi_Map[Command, (String, List[String])])
   139     {
   140       def commands: Set[Command] = rep.keySet
   141       def is_empty: Boolean = rep.isEmpty
   142       def dest: List[(Command, (String, List[String]))] = rep.iterator.toList
   143       def insert(cmd: Command, fn: String, args: List[String]): Overlays =
   144         new Overlays(rep.insert(cmd, (fn, args)))
   145       def remove(cmd: Command, fn: String, args: List[String]): Overlays =
   146         new Overlays(rep.remove(cmd, (fn, args)))
   147 
   148       override def toString: String = rep.mkString("Node.Overlays(", ",", ")")
   149     }
   150 
   151 
   152     /* edits */
   153 
   154     sealed abstract class Edit[A, B]
   155     {
   156       def foreach(f: A => Unit)
   157       {
   158         this match {
   159           case Edits(es) => es.foreach(f)
   160           case _ =>
   161         }
   162       }
   163     }
   164     case class Clear[A, B]() extends Edit[A, B]
   165     case class Blob[A, B](blob: Document.Blob) extends Edit[A, B]
   166 
   167     case class Edits[A, B](edits: List[A]) extends Edit[A, B]
   168     case class Deps[A, B](header: Header) extends Edit[A, B]
   169     case class Perspective[A, B](required: Boolean, visible: B, overlays: Overlays) extends Edit[A, B]
   170     type Perspective_Text = Perspective[Text.Edit, Text.Perspective]
   171     type Perspective_Command = Perspective[Command.Edit, Command.Perspective]
   172 
   173 
   174     /* commands */
   175 
   176     object Commands
   177     {
   178       def apply(commands: Linear_Set[Command]): Commands = new Commands(commands)
   179       val empty: Commands = apply(Linear_Set.empty)
   180 
   181       def starts(commands: Iterator[Command], offset: Text.Offset = 0)
   182         : Iterator[(Command, Text.Offset)] =
   183       {
   184         var i = offset
   185         for (command <- commands) yield {
   186           val start = i
   187           i += command.length
   188           (command, start)
   189         }
   190       }
   191 
   192       private val block_size = 256
   193     }
   194 
   195     final class Commands private(val commands: Linear_Set[Command])
   196     {
   197       lazy val load_commands: List[Command] =
   198         commands.iterator.filter(cmd => !cmd.blobs.isEmpty).toList
   199 
   200       private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
   201       {
   202         val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
   203         var next_block = 0
   204         var last_stop = 0
   205         for ((command, start) <- Commands.starts(commands.iterator)) {
   206           last_stop = start + command.length
   207           while (last_stop + 1 > next_block) {
   208             blocks += (command -> start)
   209             next_block += Commands.block_size
   210           }
   211         }
   212         (blocks.toArray, Text.Range(0, last_stop))
   213       }
   214 
   215       private def full_range: Text.Range = full_index._2
   216 
   217       def iterator(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   218       {
   219         if (!commands.isEmpty && full_range.contains(i)) {
   220           val (cmd0, start0) = full_index._1(i / Commands.block_size)
   221           Node.Commands.starts(commands.iterator(cmd0), start0) dropWhile {
   222             case (cmd, start) => start + cmd.length <= i }
   223         }
   224         else Iterator.empty
   225       }
   226     }
   227   }
   228 
   229   final class Node private(
   230     val get_blob: Option[Document.Blob] = None,
   231     val header: Node.Header = Node.bad_header("Bad theory header"),
   232     val perspective: Node.Perspective_Command =
   233       Node.Perspective(false, Command.Perspective.empty, Node.Overlays.empty),
   234     _commands: Node.Commands = Node.Commands.empty)
   235   {
   236     def clear: Node = new Node(header = header)
   237 
   238     def init_blob(blob: Document.Blob): Node = new Node(Some(blob.unchanged))
   239 
   240     def update_header(new_header: Node.Header): Node =
   241       new Node(get_blob, new_header, perspective, _commands)
   242 
   243     def update_perspective(new_perspective: Node.Perspective_Command): Node =
   244       new Node(get_blob, header, new_perspective, _commands)
   245 
   246     def same_perspective(other_perspective: Node.Perspective_Command): Boolean =
   247       perspective.required == other_perspective.required &&
   248       perspective.visible.same(other_perspective.visible) &&
   249       perspective.overlays == other_perspective.overlays
   250 
   251     def commands: Linear_Set[Command] = _commands.commands
   252     def load_commands: List[Command] = _commands.load_commands
   253 
   254     def update_commands(new_commands: Linear_Set[Command]): Node =
   255       if (new_commands eq _commands.commands) this
   256       else new Node(get_blob, header, perspective, Node.Commands(new_commands))
   257 
   258     def command_iterator(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   259       _commands.iterator(i)
   260 
   261     def command_iterator(range: Text.Range): Iterator[(Command, Text.Offset)] =
   262       command_iterator(range.start) takeWhile { case (_, start) => start < range.stop }
   263 
   264     def command_start(cmd: Command): Option[Text.Offset] =
   265       Node.Commands.starts(commands.iterator).find(_._1 == cmd).map(_._2)
   266   }
   267 
   268 
   269   /* development graph */
   270 
   271   object Nodes
   272   {
   273     val empty: Nodes = new Nodes(Graph.empty(Node.Name.Ordering))
   274   }
   275 
   276   final class Nodes private(graph: Graph[Node.Name, Node])
   277   {
   278     def get_name(s: String): Option[Node.Name] =
   279       graph.keys_iterator.find(name => name.node == s)
   280 
   281     def apply(name: Node.Name): Node =
   282       graph.default_node(name, Node.empty).get_node(name)
   283 
   284     def + (entry: (Node.Name, Node)): Nodes =
   285     {
   286       val (name, node) = entry
   287       val imports = node.header.imports
   288       val graph1 =
   289         (graph.default_node(name, Node.empty) /: imports)((g, p) => g.default_node(p, Node.empty))
   290       val graph2 = (graph1 /: graph1.imm_preds(name))((g, dep) => g.del_edge(dep, name))
   291       val graph3 = (graph2 /: imports)((g, dep) => g.add_edge(dep, name))
   292       new Nodes(graph3.map_node(name, _ => node))
   293     }
   294 
   295     def iterator: Iterator[(Node.Name, Node)] =
   296       graph.iterator.map({ case (name, (node, _)) => (name, node) })
   297 
   298     def load_commands(file_name: Node.Name): List[Command] =
   299       (for {
   300         (_, node) <- iterator
   301         cmd <- node.load_commands.iterator
   302         name <- cmd.blobs_names.iterator
   303         if name == file_name
   304       } yield cmd).toList
   305 
   306     def descendants(names: List[Node.Name]): List[Node.Name] = graph.all_succs(names)
   307     def topological_order: List[Node.Name] = graph.topological_order
   308 
   309     override def toString: String = topological_order.mkString("Nodes(", ",", ")")
   310   }
   311 
   312 
   313 
   314   /** versioning **/
   315 
   316   /* particular document versions */
   317 
   318   object Version
   319   {
   320     val init: Version = new Version()
   321 
   322     def make(syntax: Option[Prover.Syntax], nodes: Nodes): Version =
   323       new Version(Document_ID.make(), syntax, nodes)
   324   }
   325 
   326   final class Version private(
   327     val id: Document_ID.Version = Document_ID.none,
   328     val syntax: Option[Prover.Syntax] = None,
   329     val nodes: Nodes = Nodes.empty)
   330   {
   331     override def toString: String = "Version(" + id + ")"
   332   }
   333 
   334 
   335   /* changes of plain text, eventually resulting in document edits */
   336 
   337   object Change
   338   {
   339     val init: Change = new Change()
   340 
   341     def make(previous: Future[Version], edits: List[Edit_Text], version: Future[Version]): Change =
   342       new Change(Some(previous), edits, version)
   343   }
   344 
   345   final class Change private(
   346     val previous: Option[Future[Version]] = Some(Future.value(Version.init)),
   347     val edits: List[Edit_Text] = Nil,
   348     val version: Future[Version] = Future.value(Version.init))
   349   {
   350     def is_finished: Boolean =
   351       (previous match { case None => true case Some(future) => future.is_finished }) &&
   352       version.is_finished
   353 
   354     def truncate: Change = new Change(None, Nil, version)
   355   }
   356 
   357 
   358   /* history navigation */
   359 
   360   object History
   361   {
   362     val init: History = new History()
   363   }
   364 
   365   final class History private(
   366     val undo_list: List[Change] = List(Change.init))  // non-empty list
   367   {
   368     def tip: Change = undo_list.head
   369     def + (change: Change): History = new History(change :: undo_list)
   370 
   371     def prune(check: Change => Boolean, retain: Int): Option[(List[Change], History)] =
   372     {
   373       val n = undo_list.iterator.zipWithIndex.find(p => check(p._1)).get._2 + 1
   374       val (retained, dropped) = undo_list.splitAt(n max retain)
   375 
   376       retained.splitAt(retained.length - 1) match {
   377         case (prefix, List(last)) => Some(dropped, new History(prefix ::: List(last.truncate)))
   378         case _ => None
   379       }
   380     }
   381   }
   382 
   383 
   384   /* snapshot */
   385 
   386   object Snapshot
   387   {
   388     val init = State.init.snapshot()
   389   }
   390 
   391   abstract class Snapshot
   392   {
   393     val state: State
   394     val version: Version
   395     val is_outdated: Boolean
   396 
   397     def convert(i: Text.Offset): Text.Offset
   398     def revert(i: Text.Offset): Text.Offset
   399     def convert(range: Text.Range): Text.Range
   400     def revert(range: Text.Range): Text.Range
   401 
   402     val node_name: Node.Name
   403     val node: Node
   404     val load_commands: List[Command]
   405     def is_loaded: Boolean
   406     def eq_content(other: Snapshot): Boolean
   407 
   408     def cumulate[A](
   409       range: Text.Range,
   410       info: A,
   411       elements: Markup.Elements,
   412       result: List[Command.State] => (A, Text.Markup) => Option[A],
   413       status: Boolean = false): List[Text.Info[A]]
   414 
   415     def select[A](
   416       range: Text.Range,
   417       elements: Markup.Elements,
   418       result: List[Command.State] => Text.Markup => Option[A],
   419       status: Boolean = false): List[Text.Info[A]]
   420   }
   421 
   422 
   423 
   424   /** global state -- document structure, execution process, editing history **/
   425 
   426   type Assign_Update =
   427     List[(Document_ID.Command, List[Document_ID.Exec])]  // update of exec state assignment
   428 
   429   object State
   430   {
   431     class Fail(state: State) extends Exception
   432 
   433     object Assignment
   434     {
   435       val init: Assignment = new Assignment()
   436     }
   437 
   438     final class Assignment private(
   439       val command_execs: Map[Document_ID.Command, List[Document_ID.Exec]] = Map.empty,
   440       val is_finished: Boolean = false)
   441     {
   442       def check_finished: Assignment = { require(is_finished); this }
   443       def unfinished: Assignment = new Assignment(command_execs, false)
   444 
   445       def assign(update: Assign_Update): Assignment =
   446       {
   447         require(!is_finished)
   448         val command_execs1 =
   449           (command_execs /: update) {
   450             case (res, (command_id, exec_ids)) =>
   451               if (exec_ids.isEmpty) res - command_id
   452               else res + (command_id -> exec_ids)
   453           }
   454         new Assignment(command_execs1, true)
   455       }
   456     }
   457 
   458     val init: State =
   459       State().define_version(Version.init, Assignment.init).assign(Version.init.id, Nil)._2
   460   }
   461 
   462   final case class State private(
   463     /*reachable versions*/
   464     val versions: Map[Document_ID.Version, Version] = Map.empty,
   465     /*inlined auxiliary files*/
   466     val blobs: Set[SHA1.Digest] = Set.empty,
   467     /*static markup from define_command*/
   468     val commands: Map[Document_ID.Command, Command.State] = Map.empty,
   469     /*dynamic markup from execution*/
   470     val execs: Map[Document_ID.Exec, Command.State] = Map.empty,
   471     /*command-exec assignment for each version*/
   472     val assignments: Map[Document_ID.Version, State.Assignment] = Map.empty,
   473     /*commands with markup produced by other commands (imm_succs)*/
   474     val commands_redirection: Graph[Document_ID.Command, Unit] = Graph.long,
   475     /*explicit (linear) history*/
   476     val history: History = History.init)
   477   {
   478     private def fail[A]: A = throw new State.Fail(this)
   479 
   480     def define_version(version: Version, assignment: State.Assignment): State =
   481     {
   482       val id = version.id
   483       copy(versions = versions + (id -> version),
   484         assignments = assignments + (id -> assignment.unfinished))
   485     }
   486 
   487     def define_blob(digest: SHA1.Digest): State = copy(blobs = blobs + digest)
   488     def defined_blob(digest: SHA1.Digest): Boolean = blobs.contains(digest)
   489 
   490     def define_command(command: Command): State =
   491     {
   492       val id = command.id
   493       copy(commands = commands + (id -> command.init_state))
   494     }
   495 
   496     def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
   497 
   498     def find_command(version: Version, id: Document_ID.Generic): Option[(Node, Command)] =
   499       commands.get(id) orElse execs.get(id) match {
   500         case None => None
   501         case Some(st) =>
   502           val command = st.command
   503           val node = version.nodes(command.node_name)
   504           if (node.commands.contains(command)) Some((node, command)) else None
   505       }
   506 
   507     def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
   508     def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
   509     def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
   510     def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
   511 
   512     private def self_id(st: Command.State)(id: Document_ID.Generic): Boolean =
   513       id == st.command.id ||
   514       (execs.get(id) match { case Some(st1) => st1.command.id == st.command.id case None => false })
   515 
   516     private def other_id(id: Document_ID.Generic)
   517       : Option[(Symbol.Text_Chunk.Id, Symbol.Text_Chunk)] = None
   518     /* FIXME
   519       (execs.get(id) orElse commands.get(id)).map(st =>
   520         ((Symbol.Text_Chunk.Id(st.command.id), st.command.chunk)))
   521     */
   522 
   523     private def redirection(st: Command.State): Graph[Document_ID.Command, Unit] =
   524       (commands_redirection /: st.markups.redirection_iterator)({ case (graph, id) =>
   525         graph.default_node(id, ()).default_node(st.command.id, ()).add_edge(id, st.command.id) })
   526 
   527     def accumulate(id: Document_ID.Generic, message: XML.Elem): (Command.State, State) =
   528     {
   529       execs.get(id) match {
   530         case Some(st) =>
   531           val new_st = st.accumulate(self_id(st), other_id _, message)
   532           val execs1 = execs + (id -> new_st)
   533           (new_st, copy(execs = execs1, commands_redirection = redirection(new_st)))
   534         case None =>
   535           commands.get(id) match {
   536             case Some(st) =>
   537               val new_st = st.accumulate(self_id(st), other_id _, message)
   538               val commands1 = commands + (id -> new_st)
   539               (new_st, copy(commands = commands1, commands_redirection = redirection(new_st)))
   540             case None => fail
   541           }
   542       }
   543     }
   544 
   545     def assign(id: Document_ID.Version, update: Assign_Update): (List[Command], State) =
   546     {
   547       val version = the_version(id)
   548 
   549       def upd(exec_id: Document_ID.Exec, st: Command.State)
   550           : Option[(Document_ID.Exec, Command.State)] =
   551         if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
   552 
   553       val (changed_commands, new_execs) =
   554         ((Nil: List[Command], execs) /: update) {
   555           case ((commands1, execs1), (command_id, exec)) =>
   556             val st = the_static_state(command_id)
   557             val command = st.command
   558             val commands2 = command :: commands1
   559             val execs2 =
   560               exec match {
   561                 case Nil => execs1
   562                 case eval_id :: print_ids =>
   563                   execs1 ++ upd(eval_id, st) ++
   564                     (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
   565               }
   566             (commands2, execs2)
   567         }
   568       val new_assignment = the_assignment(version).assign(update)
   569       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   570 
   571       (changed_commands, new_state)
   572     }
   573 
   574     def is_assigned(version: Version): Boolean =
   575       assignments.get(version.id) match {
   576         case Some(assgn) => assgn.is_finished
   577         case None => false
   578       }
   579 
   580     def is_stable(change: Change): Boolean =
   581       change.is_finished && is_assigned(change.version.get_finished)
   582 
   583     def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
   584     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   585     def tip_stable: Boolean = is_stable(history.tip)
   586     def tip_version: Version = history.tip.version.get_finished
   587 
   588     def continue_history(
   589       previous: Future[Version],
   590       edits: List[Edit_Text],
   591       version: Future[Version]): State =
   592     {
   593       val change = Change.make(previous, edits, version)
   594       copy(history = history + change)
   595     }
   596 
   597     def prune_history(retain: Int = 0): (List[Version], State) =
   598     {
   599       history.prune(is_stable, retain) match {
   600         case Some((dropped, history1)) =>
   601           val dropped_versions = dropped.map(change => change.version.get_finished)
   602           val state1 = copy(history = history1)
   603           (dropped_versions, state1)
   604         case None => fail
   605       }
   606     }
   607 
   608     def removed_versions(removed: List[Document_ID.Version]): State =
   609     {
   610       val versions1 = versions -- removed
   611       val assignments1 = assignments -- removed
   612       var blobs1 = Set.empty[SHA1.Digest]
   613       var commands1 = Map.empty[Document_ID.Command, Command.State]
   614       var execs1 = Map.empty[Document_ID.Exec, Command.State]
   615       for {
   616         (version_id, version) <- versions1.iterator
   617         command_execs = assignments1(version_id).command_execs
   618         (_, node) <- version.nodes.iterator
   619         command <- node.commands.iterator
   620       } {
   621         for (digest <- command.blobs_digests; if !blobs1.contains(digest))
   622           blobs1 += digest
   623 
   624         if (!commands1.isDefinedAt(command.id))
   625           commands.get(command.id).foreach(st => commands1 += (command.id -> st))
   626 
   627         for (exec_id <- command_execs.getOrElse(command.id, Nil)) {
   628           if (!execs1.isDefinedAt(exec_id))
   629             execs.get(exec_id).foreach(st => execs1 += (exec_id -> st))
   630         }
   631       }
   632       copy(
   633         versions = versions1,
   634         blobs = blobs1,
   635         commands = commands1,
   636         execs = execs1,
   637         commands_redirection = commands_redirection.restrict(commands1.isDefinedAt(_)),
   638         assignments = assignments1)
   639     }
   640 
   641     private def command_states_self(version: Version, command: Command)
   642       : List[(Document_ID.Generic, Command.State)] =
   643     {
   644       require(is_assigned(version))
   645       try {
   646         the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil)
   647           .map(id => id -> the_dynamic_state(id)) match {
   648             case Nil => fail
   649             case res => res
   650           }
   651       }
   652       catch {
   653         case _: State.Fail =>
   654           try { List(command.id -> the_static_state(command.id)) }
   655           catch { case _: State.Fail => List(command.id -> command.init_state) }
   656       }
   657     }
   658 
   659     def command_states(version: Version, command: Command): List[Command.State] =
   660     {
   661       val self = command_states_self(version, command)
   662       val others =
   663         if (commands_redirection.defined(command.id)) {
   664           (for {
   665             command_id <- commands_redirection.imm_succs(command.id).iterator
   666             (id, st) <- command_states_self(version, the_static_state(command_id).command)
   667             if !self.exists(_._1 == id)
   668           } yield (id, st)).toMap.valuesIterator.toList
   669         }
   670         else Nil
   671       self.map(_._2) ::: others.flatMap(_.redirect(command))
   672     }
   673 
   674     def command_results(version: Version, command: Command): Command.Results =
   675       Command.State.merge_results(command_states(version, command))
   676 
   677     def command_markup(version: Version, command: Command, index: Command.Markup_Index,
   678         range: Text.Range, elements: Markup.Elements): Markup_Tree =
   679       Command.State.merge_markup(command_states(version, command), index, range, elements)
   680 
   681     def markup_to_XML(version: Version, node: Node, elements: Markup.Elements): XML.Body =
   682       (for {
   683         command <- node.commands.iterator
   684         markup =
   685           command_markup(version, command, Command.Markup_Index.markup, command.range, elements)
   686         tree <- markup.to_XML(command.range, command.source, elements)
   687       } yield tree).toList
   688 
   689     // persistent user-view
   690     def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
   691       : Snapshot =
   692     {
   693       val stable = recent_stable
   694       val latest = history.tip
   695 
   696       // FIXME proper treatment of removed nodes
   697       val edits =
   698         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   699             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   700       lazy val reverse_edits = edits.reverse
   701 
   702       new Snapshot
   703       {
   704         /* global information */
   705 
   706         val state = State.this
   707         val version = stable.version.get_finished
   708         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   709 
   710 
   711         /* local node content */
   712 
   713         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   714         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   715         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   716         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   717 
   718         val node_name = name
   719         val node = version.nodes(name)
   720 
   721         val load_commands: List[Command] =
   722           if (node_name.is_theory) Nil
   723           else version.nodes.load_commands(node_name)
   724 
   725         val is_loaded: Boolean = node_name.is_theory || !load_commands.isEmpty
   726 
   727         def eq_content(other: Snapshot): Boolean =
   728         {
   729           def eq_commands(commands: (Command, Command)): Boolean =
   730           {
   731             val states1 = state.command_states(version, commands._1)
   732             val states2 = other.state.command_states(other.version, commands._2)
   733             states1.length == states2.length &&
   734             (states1 zip states2).forall({ case (st1, st2) => st1 eq_content st2 })
   735           }
   736 
   737           !is_outdated && !other.is_outdated &&
   738           node.commands.size == other.node.commands.size &&
   739           (node.commands.iterator zip other.node.commands.iterator).forall(eq_commands) &&
   740           load_commands.length == other.load_commands.length &&
   741           (load_commands zip other.load_commands).forall(eq_commands)
   742         }
   743 
   744 
   745         /* cumulate markup */
   746 
   747         def cumulate[A](
   748           range: Text.Range,
   749           info: A,
   750           elements: Markup.Elements,
   751           result: List[Command.State] => (A, Text.Markup) => Option[A],
   752           status: Boolean = false): List[Text.Info[A]] =
   753         {
   754           val former_range = revert(range).inflate_singularity
   755           val (chunk_name, command_iterator) =
   756             load_commands match {
   757               case command :: _ => (Symbol.Text_Chunk.File(node_name.node), Iterator((command, 0)))
   758               case _ => (Symbol.Text_Chunk.Default, node.command_iterator(former_range))
   759             }
   760           val markup_index = Command.Markup_Index(status, chunk_name)
   761           (for {
   762             (command, command_start) <- command_iterator
   763             chunk <- command.chunks.get(chunk_name).iterator
   764             states = state.command_states(version, command)
   765             res = result(states)
   766             markup_range <- (former_range - command_start).try_restrict(chunk.range).iterator
   767             markup = Command.State.merge_markup(states, markup_index, markup_range, elements)
   768             Text.Info(r0, a) <- markup.cumulate[A](markup_range, info, elements,
   769               {
   770                 case (a, Text.Info(r0, b)) => res(a, Text.Info(convert(r0 + command_start), b))
   771               }).iterator
   772             r1 <- convert(r0 + command_start).try_restrict(range).iterator
   773           } yield Text.Info(r1, a)).toList
   774         }
   775 
   776         def select[A](
   777           range: Text.Range,
   778           elements: Markup.Elements,
   779           result: List[Command.State] => Text.Markup => Option[A],
   780           status: Boolean = false): List[Text.Info[A]] =
   781         {
   782           def result1(states: List[Command.State]): (Option[A], Text.Markup) => Option[Option[A]] =
   783           {
   784             val res = result(states)
   785             (_: Option[A], x: Text.Markup) =>
   786               res(x) match {
   787                 case None => None
   788                 case some => Some(some)
   789               }
   790           }
   791           for (Text.Info(r, Some(x)) <- cumulate(range, None, elements, result1 _, status))
   792             yield Text.Info(r, x)
   793         }
   794 
   795 
   796         /* output */
   797 
   798         override def toString: String =
   799           "Snapshot(node = " + node_name.node + ", version = " + version.id +
   800             (if (is_outdated) ", outdated" else "") + ")"
   801       }
   802     }
   803   }
   804 }
   805