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