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