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