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