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