src/Pure/PIDE/document.scala
author wenzelm
Wed Jul 23 15:00:46 2014 +0200 (2014-07-23)
changeset 57617 335750d989a3
parent 57616 50ab1db5c0fd
child 57619 dcd69422b953
permissions -rw-r--r--
clarified display;
     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 is_maximal(name: Node.Name): Boolean =
   300       graph.default_node(name, Node.empty).is_maximal(name)
   301 
   302     def + (entry: (Node.Name, Node)): Nodes =
   303     {
   304       val (name, node) = entry
   305       val imports = node.header.imports
   306       val graph1 =
   307         (graph.default_node(name, Node.empty) /: imports)((g, p) => g.default_node(p, Node.empty))
   308       val graph2 = (graph1 /: graph1.imm_preds(name))((g, dep) => g.del_edge(dep, name))
   309       val graph3 = (graph2 /: imports)((g, dep) => g.add_edge(dep, name))
   310       new Nodes(
   311         if (graph3.is_maximal(name) && node.is_empty) graph3.del_node(name)
   312         else graph3.map_node(name, _ => node)
   313       )
   314     }
   315 
   316     def iterator: Iterator[(Node.Name, Node)] =
   317       graph.iterator.map({ case (name, (node, _)) => (name, node) })
   318 
   319     def load_commands(file_name: Node.Name): List[Command] =
   320       (for {
   321         (_, node) <- iterator
   322         cmd <- node.load_commands.iterator
   323         name <- cmd.blobs_names.iterator
   324         if name == file_name
   325       } yield cmd).toList
   326 
   327     def descendants(names: List[Node.Name]): List[Node.Name] = graph.all_succs(names)
   328     def topological_order: List[Node.Name] = graph.topological_order
   329 
   330     override def toString: String = topological_order.mkString("Nodes(", ",", ")")
   331   }
   332 
   333 
   334 
   335   /** versioning **/
   336 
   337   /* particular document versions */
   338 
   339   object Version
   340   {
   341     val init: Version = new Version()
   342 
   343     def make(syntax: Option[Prover.Syntax], nodes: Nodes): Version =
   344       new Version(Document_ID.make(), syntax, nodes)
   345   }
   346 
   347   final class Version private(
   348     val id: Document_ID.Version = Document_ID.none,
   349     val syntax: Option[Prover.Syntax] = None,
   350     val nodes: Nodes = Nodes.empty)
   351   {
   352     override def toString: String = "Version(" + id + ")"
   353   }
   354 
   355 
   356   /* changes of plain text, eventually resulting in document edits */
   357 
   358   object Change
   359   {
   360     val init: Change = new Change()
   361 
   362     def make(previous: Future[Version], edits: List[Edit_Text], version: Future[Version]): Change =
   363       new Change(Some(previous), edits, version)
   364   }
   365 
   366   final class Change private(
   367     val previous: Option[Future[Version]] = Some(Future.value(Version.init)),
   368     val edits: List[Edit_Text] = Nil,
   369     val version: Future[Version] = Future.value(Version.init))
   370   {
   371     def is_finished: Boolean =
   372       (previous match { case None => true case Some(future) => future.is_finished }) &&
   373       version.is_finished
   374 
   375     def truncate: Change = new Change(None, Nil, version)
   376   }
   377 
   378 
   379   /* history navigation */
   380 
   381   object History
   382   {
   383     val init: History = new History()
   384   }
   385 
   386   final class History private(
   387     val undo_list: List[Change] = List(Change.init))  // non-empty list
   388   {
   389     def tip: Change = undo_list.head
   390     def + (change: Change): History = new History(change :: undo_list)
   391 
   392     def prune(check: Change => Boolean, retain: Int): Option[(List[Change], History)] =
   393     {
   394       val n = undo_list.iterator.zipWithIndex.find(p => check(p._1)).get._2 + 1
   395       val (retained, dropped) = undo_list.splitAt(n max retain)
   396 
   397       retained.splitAt(retained.length - 1) match {
   398         case (prefix, List(last)) => Some(dropped, new History(prefix ::: List(last.truncate)))
   399         case _ => None
   400       }
   401     }
   402   }
   403 
   404 
   405   /* snapshot */
   406 
   407   object Snapshot
   408   {
   409     val init = State.init.snapshot()
   410   }
   411 
   412   abstract class Snapshot
   413   {
   414     val state: State
   415     val version: Version
   416     val is_outdated: Boolean
   417 
   418     def convert(i: Text.Offset): Text.Offset
   419     def revert(i: Text.Offset): Text.Offset
   420     def convert(range: Text.Range): Text.Range
   421     def revert(range: Text.Range): Text.Range
   422 
   423     val node_name: Node.Name
   424     val node: Node
   425     val load_commands: List[Command]
   426     def is_loaded: Boolean
   427     def eq_content(other: Snapshot): Boolean
   428 
   429     def cumulate[A](
   430       range: Text.Range,
   431       info: A,
   432       elements: Markup.Elements,
   433       result: List[Command.State] => (A, Text.Markup) => Option[A],
   434       status: Boolean = false): List[Text.Info[A]]
   435 
   436     def select[A](
   437       range: Text.Range,
   438       elements: Markup.Elements,
   439       result: List[Command.State] => Text.Markup => Option[A],
   440       status: Boolean = false): List[Text.Info[A]]
   441   }
   442 
   443 
   444 
   445   /** global state -- document structure, execution process, editing history **/
   446 
   447   type Assign_Update =
   448     List[(Document_ID.Command, List[Document_ID.Exec])]  // update of exec state assignment
   449 
   450   object State
   451   {
   452     class Fail(state: State) extends Exception
   453 
   454     object Assignment
   455     {
   456       val init: Assignment = new Assignment()
   457     }
   458 
   459     final class Assignment private(
   460       val command_execs: Map[Document_ID.Command, List[Document_ID.Exec]] = Map.empty,
   461       val is_finished: Boolean = false)
   462     {
   463       def check_finished: Assignment = { require(is_finished); this }
   464       def unfinished: Assignment = new Assignment(command_execs, false)
   465 
   466       def assign(update: Assign_Update): Assignment =
   467       {
   468         require(!is_finished)
   469         val command_execs1 =
   470           (command_execs /: update) {
   471             case (res, (command_id, exec_ids)) =>
   472               if (exec_ids.isEmpty) res - command_id
   473               else res + (command_id -> exec_ids)
   474           }
   475         new Assignment(command_execs1, true)
   476       }
   477     }
   478 
   479     val init: State =
   480       State().define_version(Version.init, Assignment.init).assign(Version.init.id, Nil)._2
   481   }
   482 
   483   final case class State private(
   484     /*reachable versions*/
   485     val versions: Map[Document_ID.Version, Version] = Map.empty,
   486     /*inlined auxiliary files*/
   487     val blobs: Set[SHA1.Digest] = Set.empty,
   488     /*static markup from define_command*/
   489     val commands: Map[Document_ID.Command, Command.State] = Map.empty,
   490     /*dynamic markup from execution*/
   491     val execs: Map[Document_ID.Exec, Command.State] = Map.empty,
   492     /*command-exec assignment for each version*/
   493     val assignments: Map[Document_ID.Version, State.Assignment] = Map.empty,
   494     /*commands with markup produced by other commands (imm_succs)*/
   495     val commands_redirection: Graph[Document_ID.Command, Unit] = Graph.long,
   496     /*explicit (linear) history*/
   497     val history: History = History.init)
   498   {
   499     private def fail[A]: A = throw new State.Fail(this)
   500 
   501     def define_version(version: Version, assignment: State.Assignment): State =
   502     {
   503       val id = version.id
   504       copy(versions = versions + (id -> version),
   505         assignments = assignments + (id -> assignment.unfinished))
   506     }
   507 
   508     def define_blob(digest: SHA1.Digest): State = copy(blobs = blobs + digest)
   509     def defined_blob(digest: SHA1.Digest): Boolean = blobs.contains(digest)
   510 
   511     def define_command(command: Command): State =
   512     {
   513       val id = command.id
   514       copy(commands = commands + (id -> command.init_state))
   515     }
   516 
   517     def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
   518 
   519     def find_command(version: Version, id: Document_ID.Generic): Option[(Node, Command)] =
   520       commands.get(id) orElse execs.get(id) match {
   521         case None => None
   522         case Some(st) =>
   523           val command = st.command
   524           val node = version.nodes(command.node_name)
   525           if (node.commands.contains(command)) Some((node, command)) else None
   526       }
   527 
   528     def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
   529     def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
   530     def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
   531     def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
   532 
   533     private def self_id(st: Command.State)(id: Document_ID.Generic): Boolean =
   534       id == st.command.id ||
   535       (execs.get(id) match { case Some(st1) => st1.command.id == st.command.id case None => false })
   536 
   537     private def other_id(id: Document_ID.Generic)
   538       : Option[(Symbol.Text_Chunk.Id, Symbol.Text_Chunk)] = None
   539     /* FIXME
   540       (execs.get(id) orElse commands.get(id)).map(st =>
   541         ((Symbol.Text_Chunk.Id(st.command.id), st.command.chunk)))
   542     */
   543 
   544     private def redirection(st: Command.State): Graph[Document_ID.Command, Unit] =
   545       (commands_redirection /: st.markups.redirection_iterator)({ case (graph, id) =>
   546         graph.default_node(id, ()).default_node(st.command.id, ()).add_edge(id, st.command.id) })
   547 
   548     def accumulate(id: Document_ID.Generic, message: XML.Elem): (Command.State, State) =
   549     {
   550       execs.get(id) match {
   551         case Some(st) =>
   552           val new_st = st.accumulate(self_id(st), other_id _, message)
   553           val execs1 = execs + (id -> new_st)
   554           (new_st, copy(execs = execs1, commands_redirection = redirection(new_st)))
   555         case None =>
   556           commands.get(id) match {
   557             case Some(st) =>
   558               val new_st = st.accumulate(self_id(st), other_id _, message)
   559               val commands1 = commands + (id -> new_st)
   560               (new_st, copy(commands = commands1, commands_redirection = redirection(new_st)))
   561             case None => fail
   562           }
   563       }
   564     }
   565 
   566     def assign(id: Document_ID.Version, update: Assign_Update): (List[Command], State) =
   567     {
   568       val version = the_version(id)
   569 
   570       def upd(exec_id: Document_ID.Exec, st: Command.State)
   571           : Option[(Document_ID.Exec, Command.State)] =
   572         if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
   573 
   574       val (changed_commands, new_execs) =
   575         ((Nil: List[Command], execs) /: update) {
   576           case ((commands1, execs1), (command_id, exec)) =>
   577             val st = the_static_state(command_id)
   578             val command = st.command
   579             val commands2 = command :: commands1
   580             val execs2 =
   581               exec match {
   582                 case Nil => execs1
   583                 case eval_id :: print_ids =>
   584                   execs1 ++ upd(eval_id, st) ++
   585                     (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
   586               }
   587             (commands2, execs2)
   588         }
   589       val new_assignment = the_assignment(version).assign(update)
   590       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   591 
   592       (changed_commands, new_state)
   593     }
   594 
   595     def is_assigned(version: Version): Boolean =
   596       assignments.get(version.id) match {
   597         case Some(assgn) => assgn.is_finished
   598         case None => false
   599       }
   600 
   601     def is_stable(change: Change): Boolean =
   602       change.is_finished && is_assigned(change.version.get_finished)
   603 
   604     def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
   605     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   606     def tip_stable: Boolean = is_stable(history.tip)
   607     def tip_version: Version = history.tip.version.get_finished
   608 
   609     def continue_history(
   610       previous: Future[Version],
   611       edits: List[Edit_Text],
   612       version: Future[Version]): State =
   613     {
   614       val change = Change.make(previous, edits, version)
   615       copy(history = history + change)
   616     }
   617 
   618     def prune_history(retain: Int = 0): (List[Version], State) =
   619     {
   620       history.prune(is_stable, retain) match {
   621         case Some((dropped, history1)) =>
   622           val dropped_versions = dropped.map(change => change.version.get_finished)
   623           val state1 = copy(history = history1)
   624           (dropped_versions, state1)
   625         case None => fail
   626       }
   627     }
   628 
   629     def removed_versions(removed: List[Document_ID.Version]): State =
   630     {
   631       val versions1 = versions -- removed
   632       val assignments1 = assignments -- removed
   633       var blobs1 = Set.empty[SHA1.Digest]
   634       var commands1 = Map.empty[Document_ID.Command, Command.State]
   635       var execs1 = Map.empty[Document_ID.Exec, Command.State]
   636       for {
   637         (version_id, version) <- versions1.iterator
   638         command_execs = assignments1(version_id).command_execs
   639         (_, node) <- version.nodes.iterator
   640         command <- node.commands.iterator
   641       } {
   642         for (digest <- command.blobs_digests; if !blobs1.contains(digest))
   643           blobs1 += digest
   644 
   645         if (!commands1.isDefinedAt(command.id))
   646           commands.get(command.id).foreach(st => commands1 += (command.id -> st))
   647 
   648         for (exec_id <- command_execs.getOrElse(command.id, Nil)) {
   649           if (!execs1.isDefinedAt(exec_id))
   650             execs.get(exec_id).foreach(st => execs1 += (exec_id -> st))
   651         }
   652       }
   653       copy(
   654         versions = versions1,
   655         blobs = blobs1,
   656         commands = commands1,
   657         execs = execs1,
   658         commands_redirection = commands_redirection.restrict(commands1.isDefinedAt(_)),
   659         assignments = assignments1)
   660     }
   661 
   662     private def command_states_self(version: Version, command: Command)
   663       : List[(Document_ID.Generic, Command.State)] =
   664     {
   665       require(is_assigned(version))
   666       try {
   667         the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil)
   668           .map(id => id -> the_dynamic_state(id)) match {
   669             case Nil => fail
   670             case res => res
   671           }
   672       }
   673       catch {
   674         case _: State.Fail =>
   675           try { List(command.id -> the_static_state(command.id)) }
   676           catch { case _: State.Fail => List(command.id -> command.init_state) }
   677       }
   678     }
   679 
   680     def command_states(version: Version, command: Command): List[Command.State] =
   681     {
   682       val self = command_states_self(version, command)
   683       val others =
   684         if (commands_redirection.defined(command.id)) {
   685           (for {
   686             command_id <- commands_redirection.imm_succs(command.id).iterator
   687             (id, st) <- command_states_self(version, the_static_state(command_id).command)
   688             if !self.exists(_._1 == id)
   689           } yield (id, st)).toMap.valuesIterator.toList
   690         }
   691         else Nil
   692       self.map(_._2) ::: others.flatMap(_.redirect(command))
   693     }
   694 
   695     def command_results(version: Version, command: Command): Command.Results =
   696       Command.State.merge_results(command_states(version, command))
   697 
   698     def command_markup(version: Version, command: Command, index: Command.Markup_Index,
   699         range: Text.Range, elements: Markup.Elements): Markup_Tree =
   700       Command.State.merge_markup(command_states(version, command), index, range, elements)
   701 
   702     def markup_to_XML(version: Version, node: Node, elements: Markup.Elements): XML.Body =
   703       (for {
   704         command <- node.commands.iterator
   705         markup =
   706           command_markup(version, command, Command.Markup_Index.markup, command.range, elements)
   707         tree <- markup.to_XML(command.range, command.source, elements)
   708       } yield tree).toList
   709 
   710     // persistent user-view
   711     def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
   712       : Snapshot =
   713     {
   714       val stable = recent_stable
   715       val latest = history.tip
   716 
   717       // FIXME proper treatment of removed nodes
   718       val edits =
   719         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   720             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   721       lazy val reverse_edits = edits.reverse
   722 
   723       new Snapshot
   724       {
   725         /* global information */
   726 
   727         val state = State.this
   728         val version = stable.version.get_finished
   729         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   730 
   731 
   732         /* local node content */
   733 
   734         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   735         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   736         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   737         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   738 
   739         val node_name = name
   740         val node = version.nodes(name)
   741 
   742         val load_commands: List[Command] =
   743           if (node_name.is_theory) Nil
   744           else version.nodes.load_commands(node_name)
   745 
   746         val is_loaded: Boolean = node_name.is_theory || !load_commands.isEmpty
   747 
   748         def eq_content(other: Snapshot): Boolean =
   749         {
   750           def eq_commands(commands: (Command, Command)): Boolean =
   751           {
   752             val states1 = state.command_states(version, commands._1)
   753             val states2 = other.state.command_states(other.version, commands._2)
   754             states1.length == states2.length &&
   755             (states1 zip states2).forall({ case (st1, st2) => st1 eq_content st2 })
   756           }
   757 
   758           !is_outdated && !other.is_outdated &&
   759           node.commands.size == other.node.commands.size &&
   760           (node.commands.iterator zip other.node.commands.iterator).forall(eq_commands) &&
   761           load_commands.length == other.load_commands.length &&
   762           (load_commands zip other.load_commands).forall(eq_commands)
   763         }
   764 
   765 
   766         /* cumulate markup */
   767 
   768         def cumulate[A](
   769           range: Text.Range,
   770           info: A,
   771           elements: Markup.Elements,
   772           result: List[Command.State] => (A, Text.Markup) => Option[A],
   773           status: Boolean = false): List[Text.Info[A]] =
   774         {
   775           val former_range = revert(range).inflate_singularity
   776           val (chunk_name, command_iterator) =
   777             load_commands match {
   778               case command :: _ => (Symbol.Text_Chunk.File(node_name.node), Iterator((command, 0)))
   779               case _ => (Symbol.Text_Chunk.Default, node.command_iterator(former_range))
   780             }
   781           val markup_index = Command.Markup_Index(status, chunk_name)
   782           (for {
   783             (command, command_start) <- command_iterator
   784             chunk <- command.chunks.get(chunk_name).iterator
   785             states = state.command_states(version, command)
   786             res = result(states)
   787             markup_range <- (former_range - command_start).try_restrict(chunk.range).iterator
   788             markup = Command.State.merge_markup(states, markup_index, markup_range, elements)
   789             Text.Info(r0, a) <- markup.cumulate[A](markup_range, info, elements,
   790               {
   791                 case (a, Text.Info(r0, b)) => res(a, Text.Info(convert(r0 + command_start), b))
   792               }).iterator
   793             r1 <- convert(r0 + command_start).try_restrict(range).iterator
   794           } yield Text.Info(r1, a)).toList
   795         }
   796 
   797         def select[A](
   798           range: Text.Range,
   799           elements: Markup.Elements,
   800           result: List[Command.State] => Text.Markup => Option[A],
   801           status: Boolean = false): List[Text.Info[A]] =
   802         {
   803           def result1(states: List[Command.State]): (Option[A], Text.Markup) => Option[Option[A]] =
   804           {
   805             val res = result(states)
   806             (_: Option[A], x: Text.Markup) =>
   807               res(x) match {
   808                 case None => None
   809                 case some => Some(some)
   810               }
   811           }
   812           for (Text.Info(r, Some(x)) <- cumulate(range, None, elements, result1 _, status))
   813             yield Text.Info(r, x)
   814         }
   815 
   816 
   817         /* output */
   818 
   819         override def toString: String =
   820           "Snapshot(node = " + node_name.node + ", version = " + version.id +
   821             (if (is_outdated) ", outdated" else "") + ")"
   822       }
   823     }
   824   }
   825 }
   826