src/Pure/PIDE/document.scala
author wenzelm
Wed Jul 23 16:56:03 2014 +0200 (2014-07-23)
changeset 57621 caa37976801f
parent 57620 c30ab960875e
child 57842 8e4ae2db1849
permissions -rw-r--r--
more frugal edits;
     1 /*  Title:      Pure/PIDE/document.scala
     2     Author:     Makarius
     3 
     4 Document as collection of named nodes, each consisting of an editable
     5 list of commands, associated with asynchronous execution process.
     6 */
     7 
     8 package isabelle
     9 
    10 
    11 import scala.collection.mutable
    12 
    13 
    14 object Document
    15 {
    16   /** document structure **/
    17 
    18   /* overlays -- print functions with arguments */
    19 
    20   object Overlays
    21   {
    22     val empty = new Overlays(Map.empty)
    23   }
    24 
    25   final class Overlays private(rep: Map[Node.Name, Node.Overlays])
    26   {
    27     def apply(name: Document.Node.Name): Node.Overlays =
    28       rep.getOrElse(name, Node.Overlays.empty)
    29 
    30     private def update(name: Node.Name, f: Node.Overlays => Node.Overlays): Overlays =
    31     {
    32       val node_overlays = f(apply(name))
    33       new Overlays(if (node_overlays.is_empty) rep - name else rep + (name -> node_overlays))
    34     }
    35 
    36     def insert(command: Command, fn: String, args: List[String]): Overlays =
    37       update(command.node_name, _.insert(command, fn, args))
    38 
    39     def remove(command: Command, fn: String, args: List[String]): Overlays =
    40       update(command.node_name, _.remove(command, fn, args))
    41 
    42     override def toString: String = rep.mkString("Overlays(", ",", ")")
    43   }
    44 
    45 
    46   /* document blobs: auxiliary files */
    47 
    48   sealed case class Blob(bytes: Bytes, chunk: Symbol.Text_Chunk, changed: Boolean)
    49   {
    50     def unchanged: Blob = copy(changed = false)
    51   }
    52 
    53   object Blobs
    54   {
    55     def apply(blobs: Map[Node.Name, Blob]): Blobs = new Blobs(blobs)
    56     val empty: Blobs = apply(Map.empty)
    57   }
    58 
    59   final class Blobs private(blobs: Map[Node.Name, Blob])
    60   {
    61     private lazy val digests: Map[SHA1.Digest, Blob] =
    62       for ((_, blob) <- blobs) yield (blob.bytes.sha1_digest, blob)
    63 
    64     def get(digest: SHA1.Digest): Option[Blob] = digests.get(digest)
    65     def get(name: Node.Name): Option[Blob] = blobs.get(name)
    66 
    67     def changed(name: Node.Name): Boolean =
    68       get(name) match {
    69         case Some(blob) => blob.changed
    70         case None => false
    71       }
    72 
    73     override def toString: String = blobs.mkString("Blobs(", ",", ")")
    74   }
    75 
    76 
    77   /* document nodes: theories and auxiliary files */
    78 
    79   type Edit[A, B] = (Node.Name, Node.Edit[A, B])
    80   type Edit_Text = Edit[Text.Edit, Text.Perspective]
    81   type Edit_Command = Edit[Command.Edit, Command.Perspective]
    82 
    83   object Node
    84   {
    85     /* header and name */
    86 
    87     sealed case class Header(
    88       imports: List[Name],
    89       keywords: Thy_Header.Keywords,
    90       errors: List[String])
    91     {
    92       def error(msg: String): Header = copy(errors = errors ::: List(msg))
    93 
    94       def cat_errors(msg2: String): Header =
    95         copy(errors = errors.map(msg1 => Library.cat_message(msg1, msg2)))
    96     }
    97 
    98     val no_header = Header(Nil, Nil, Nil)
    99     def bad_header(msg: String): Header = Header(Nil, Nil, List(msg))
   100 
   101     object Name
   102     {
   103       val empty = Name("")
   104 
   105       object Ordering extends scala.math.Ordering[Name]
   106       {
   107         def compare(name1: Name, name2: Name): Int = name1.node compare name2.node
   108       }
   109     }
   110 
   111     sealed case class Name(node: String, master_dir: String = "", theory: String = "")
   112     {
   113       override def hashCode: Int = node.hashCode
   114       override def equals(that: Any): Boolean =
   115         that match {
   116           case other: Name => node == other.node
   117           case _ => false
   118         }
   119 
   120       def is_theory: Boolean = !theory.isEmpty
   121       override def toString: String = if (is_theory) theory else node
   122 
   123       def map(f: String => String): Name = copy(f(node), f(master_dir), theory)
   124     }
   125 
   126 
   127     /* node overlays */
   128 
   129     object Overlays
   130     {
   131       val empty = new Overlays(Multi_Map.empty)
   132     }
   133 
   134     final class Overlays private(rep: Multi_Map[Command, (String, List[String])])
   135     {
   136       def commands: Set[Command] = rep.keySet
   137       def is_empty: Boolean = rep.isEmpty
   138       def dest: List[(Command, (String, List[String]))] = rep.iterator.toList
   139       def insert(cmd: Command, fn: String, args: List[String]): Overlays =
   140         new Overlays(rep.insert(cmd, (fn, args)))
   141       def remove(cmd: Command, fn: String, args: List[String]): Overlays =
   142         new Overlays(rep.remove(cmd, (fn, args)))
   143 
   144       override def toString: String = rep.mkString("Node.Overlays(", ",", ")")
   145     }
   146 
   147 
   148     /* edits */
   149 
   150     sealed abstract class Edit[A, B]
   151     {
   152       def foreach(f: A => Unit)
   153       {
   154         this match {
   155           case Edits(es) => es.foreach(f)
   156           case _ =>
   157         }
   158       }
   159 
   160       def is_void: Boolean =
   161         this match {
   162           case Edits(Nil) => true
   163           case _ => false
   164         }
   165     }
   166     case class Clear[A, B]() extends Edit[A, B]
   167     case class Blob[A, B](blob: Document.Blob) extends Edit[A, B]
   168 
   169     case class Edits[A, B](edits: List[A]) extends Edit[A, B]
   170     case class Deps[A, B](header: Header) extends Edit[A, B]
   171     case class Perspective[A, B](required: Boolean, visible: B, overlays: Overlays) extends Edit[A, B]
   172 
   173 
   174     /* perspective */
   175 
   176     type Perspective_Text = Perspective[Text.Edit, Text.Perspective]
   177     type Perspective_Command = Perspective[Command.Edit, Command.Perspective]
   178 
   179     val no_perspective_text: Perspective_Text =
   180       Perspective(false, Text.Perspective.empty, Overlays.empty)
   181 
   182     val no_perspective_command: Perspective_Command =
   183       Perspective(false, Command.Perspective.empty, Overlays.empty)
   184 
   185     def is_no_perspective_command(perspective: Perspective_Command): Boolean =
   186       !perspective.required &&
   187       perspective.visible.is_empty &&
   188       perspective.overlays.is_empty
   189 
   190 
   191     /* commands */
   192 
   193     object Commands
   194     {
   195       def apply(commands: Linear_Set[Command]): Commands = new Commands(commands)
   196       val empty: Commands = apply(Linear_Set.empty)
   197 
   198       def starts(commands: Iterator[Command], offset: Text.Offset = 0)
   199         : Iterator[(Command, Text.Offset)] =
   200       {
   201         var i = offset
   202         for (command <- commands) yield {
   203           val start = i
   204           i += command.length
   205           (command, start)
   206         }
   207       }
   208 
   209       private val block_size = 256
   210     }
   211 
   212     final class Commands private(val commands: Linear_Set[Command])
   213     {
   214       lazy val load_commands: List[Command] =
   215         commands.iterator.filter(cmd => !cmd.blobs.isEmpty).toList
   216 
   217       private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
   218       {
   219         val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
   220         var next_block = 0
   221         var last_stop = 0
   222         for ((command, start) <- Commands.starts(commands.iterator)) {
   223           last_stop = start + command.length
   224           while (last_stop + 1 > next_block) {
   225             blocks += (command -> start)
   226             next_block += Commands.block_size
   227           }
   228         }
   229         (blocks.toArray, Text.Range(0, last_stop))
   230       }
   231 
   232       private def full_range: Text.Range = full_index._2
   233 
   234       def iterator(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   235       {
   236         if (!commands.isEmpty && full_range.contains(i)) {
   237           val (cmd0, start0) = full_index._1(i / Commands.block_size)
   238           Node.Commands.starts(commands.iterator(cmd0), start0) dropWhile {
   239             case (cmd, start) => start + cmd.length <= i }
   240         }
   241         else Iterator.empty
   242       }
   243     }
   244 
   245     val empty: Node = new Node()
   246   }
   247 
   248   final class Node private(
   249     val get_blob: Option[Document.Blob] = None,
   250     val header: Node.Header = Node.no_header,
   251     val perspective: Node.Perspective_Command = Node.no_perspective_command,
   252     _commands: Node.Commands = Node.Commands.empty)
   253   {
   254     def is_empty: Boolean =
   255       get_blob.isEmpty &&
   256       header == Node.no_header &&
   257       Node.is_no_perspective_command(perspective) &&
   258       commands.isEmpty
   259 
   260     def commands: Linear_Set[Command] = _commands.commands
   261     def load_commands: List[Command] = _commands.load_commands
   262 
   263     def clear: Node = new Node(header = header)
   264 
   265     def init_blob(blob: Document.Blob): Node = new Node(Some(blob.unchanged))
   266 
   267     def update_header(new_header: Node.Header): Node =
   268       new Node(get_blob, new_header, perspective, _commands)
   269 
   270     def update_perspective(new_perspective: Node.Perspective_Command): Node =
   271       new Node(get_blob, header, 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, 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 
   352     def make(syntax: Option[Prover.Syntax], nodes: Nodes): Version =
   353       new Version(Document_ID.make(), syntax, nodes)
   354   }
   355 
   356   final class Version private(
   357     val id: Document_ID.Version = Document_ID.none,
   358     val syntax: Option[Prover.Syntax] = None,
   359     val nodes: Nodes = Nodes.empty)
   360   {
   361     override def toString: String = "Version(" + id + ")"
   362   }
   363 
   364 
   365   /* changes of plain text, eventually resulting in document edits */
   366 
   367   object Change
   368   {
   369     val init: Change = new Change()
   370 
   371     def make(previous: Future[Version], edits: List[Edit_Text], version: Future[Version]): Change =
   372       new Change(Some(previous), edits.reverse, version)
   373   }
   374 
   375   final class Change private(
   376     val previous: Option[Future[Version]] = Some(Future.value(Version.init)),
   377     val rev_edits: List[Edit_Text] = Nil,
   378     val version: Future[Version] = Future.value(Version.init))
   379   {
   380     def is_finished: Boolean =
   381       (previous match { case None => true case Some(future) => future.is_finished }) &&
   382       version.is_finished
   383 
   384     def truncate: Change = new Change(None, Nil, version)
   385   }
   386 
   387 
   388   /* history navigation */
   389 
   390   object History
   391   {
   392     val init: History = new History()
   393   }
   394 
   395   final class History private(
   396     val undo_list: List[Change] = List(Change.init))  // non-empty list
   397   {
   398     def tip: Change = undo_list.head
   399     def + (change: Change): History = new History(change :: undo_list)
   400 
   401     def prune(check: Change => Boolean, retain: Int): Option[(List[Change], History)] =
   402     {
   403       val n = undo_list.iterator.zipWithIndex.find(p => check(p._1)).get._2 + 1
   404       val (retained, dropped) = undo_list.splitAt(n max retain)
   405 
   406       retained.splitAt(retained.length - 1) match {
   407         case (prefix, List(last)) => Some(dropped, new History(prefix ::: List(last.truncate)))
   408         case _ => None
   409       }
   410     }
   411   }
   412 
   413 
   414   /* snapshot */
   415 
   416   object Snapshot
   417   {
   418     val init = State.init.snapshot()
   419   }
   420 
   421   abstract class Snapshot
   422   {
   423     val state: State
   424     val version: Version
   425     val is_outdated: Boolean
   426 
   427     def convert(i: Text.Offset): Text.Offset
   428     def revert(i: Text.Offset): Text.Offset
   429     def convert(range: Text.Range): Text.Range
   430     def revert(range: Text.Range): Text.Range
   431 
   432     val node_name: Node.Name
   433     val node: Node
   434     val load_commands: List[Command]
   435     def is_loaded: Boolean
   436     def eq_content(other: Snapshot): Boolean
   437 
   438     def cumulate[A](
   439       range: Text.Range,
   440       info: A,
   441       elements: Markup.Elements,
   442       result: List[Command.State] => (A, Text.Markup) => Option[A],
   443       status: Boolean = false): List[Text.Info[A]]
   444 
   445     def select[A](
   446       range: Text.Range,
   447       elements: Markup.Elements,
   448       result: List[Command.State] => Text.Markup => Option[A],
   449       status: Boolean = false): List[Text.Info[A]]
   450   }
   451 
   452 
   453 
   454   /** global state -- document structure, execution process, editing history **/
   455 
   456   type Assign_Update =
   457     List[(Document_ID.Command, List[Document_ID.Exec])]  // update of exec state assignment
   458 
   459   object State
   460   {
   461     class Fail(state: State) extends Exception
   462 
   463     object Assignment
   464     {
   465       val init: Assignment = new Assignment()
   466     }
   467 
   468     final class Assignment private(
   469       val command_execs: Map[Document_ID.Command, List[Document_ID.Exec]] = Map.empty,
   470       val is_finished: Boolean = false)
   471     {
   472       def check_finished: Assignment = { require(is_finished); this }
   473       def unfinished: Assignment = new Assignment(command_execs, false)
   474 
   475       def assign(update: Assign_Update): Assignment =
   476       {
   477         require(!is_finished)
   478         val command_execs1 =
   479           (command_execs /: update) {
   480             case (res, (command_id, exec_ids)) =>
   481               if (exec_ids.isEmpty) res - command_id
   482               else res + (command_id -> exec_ids)
   483           }
   484         new Assignment(command_execs1, true)
   485       }
   486     }
   487 
   488     val init: State =
   489       State().define_version(Version.init, Assignment.init).assign(Version.init.id, Nil)._2
   490   }
   491 
   492   final case class State private(
   493     /*reachable versions*/
   494     val versions: Map[Document_ID.Version, Version] = Map.empty,
   495     /*inlined auxiliary files*/
   496     val blobs: Set[SHA1.Digest] = Set.empty,
   497     /*static markup from define_command*/
   498     val commands: Map[Document_ID.Command, Command.State] = Map.empty,
   499     /*dynamic markup from execution*/
   500     val execs: Map[Document_ID.Exec, Command.State] = Map.empty,
   501     /*command-exec assignment for each version*/
   502     val assignments: Map[Document_ID.Version, State.Assignment] = Map.empty,
   503     /*commands with markup produced by other commands (imm_succs)*/
   504     val commands_redirection: Graph[Document_ID.Command, Unit] = Graph.long,
   505     /*explicit (linear) history*/
   506     val history: History = History.init)
   507   {
   508     private def fail[A]: A = throw new State.Fail(this)
   509 
   510     def define_version(version: Version, assignment: State.Assignment): State =
   511     {
   512       val id = version.id
   513       copy(versions = versions + (id -> version),
   514         assignments = assignments + (id -> assignment.unfinished))
   515     }
   516 
   517     def define_blob(digest: SHA1.Digest): State = copy(blobs = blobs + digest)
   518     def defined_blob(digest: SHA1.Digest): Boolean = blobs.contains(digest)
   519 
   520     def define_command(command: Command): State =
   521     {
   522       val id = command.id
   523       copy(commands = commands + (id -> command.init_state))
   524     }
   525 
   526     def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
   527 
   528     def find_command(version: Version, id: Document_ID.Generic): Option[(Node, Command)] =
   529       commands.get(id) orElse execs.get(id) match {
   530         case None => None
   531         case Some(st) =>
   532           val command = st.command
   533           val node = version.nodes(command.node_name)
   534           if (node.commands.contains(command)) Some((node, command)) else None
   535       }
   536 
   537     def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
   538     def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
   539     def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
   540     def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
   541 
   542     private def self_id(st: Command.State)(id: Document_ID.Generic): Boolean =
   543       id == st.command.id ||
   544       (execs.get(id) match { case Some(st1) => st1.command.id == st.command.id case None => false })
   545 
   546     private def other_id(id: Document_ID.Generic)
   547       : Option[(Symbol.Text_Chunk.Id, Symbol.Text_Chunk)] = None
   548     /* FIXME
   549       (execs.get(id) orElse commands.get(id)).map(st =>
   550         ((Symbol.Text_Chunk.Id(st.command.id), st.command.chunk)))
   551     */
   552 
   553     private def redirection(st: Command.State): Graph[Document_ID.Command, Unit] =
   554       (commands_redirection /: st.markups.redirection_iterator)({ case (graph, id) =>
   555         graph.default_node(id, ()).default_node(st.command.id, ()).add_edge(id, st.command.id) })
   556 
   557     def accumulate(id: Document_ID.Generic, message: XML.Elem): (Command.State, State) =
   558     {
   559       execs.get(id) match {
   560         case Some(st) =>
   561           val new_st = st.accumulate(self_id(st), other_id _, message)
   562           val execs1 = execs + (id -> new_st)
   563           (new_st, copy(execs = execs1, commands_redirection = redirection(new_st)))
   564         case None =>
   565           commands.get(id) match {
   566             case Some(st) =>
   567               val new_st = st.accumulate(self_id(st), other_id _, message)
   568               val commands1 = commands + (id -> new_st)
   569               (new_st, copy(commands = commands1, commands_redirection = redirection(new_st)))
   570             case None => fail
   571           }
   572       }
   573     }
   574 
   575     def assign(id: Document_ID.Version, update: Assign_Update): (List[Command], State) =
   576     {
   577       val version = the_version(id)
   578 
   579       def upd(exec_id: Document_ID.Exec, st: Command.State)
   580           : Option[(Document_ID.Exec, Command.State)] =
   581         if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
   582 
   583       val (changed_commands, new_execs) =
   584         ((Nil: List[Command], execs) /: update) {
   585           case ((commands1, execs1), (command_id, exec)) =>
   586             val st = the_static_state(command_id)
   587             val command = st.command
   588             val commands2 = command :: commands1
   589             val execs2 =
   590               exec match {
   591                 case Nil => execs1
   592                 case eval_id :: print_ids =>
   593                   execs1 ++ upd(eval_id, st) ++
   594                     (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
   595               }
   596             (commands2, execs2)
   597         }
   598       val new_assignment = the_assignment(version).assign(update)
   599       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   600 
   601       (changed_commands, new_state)
   602     }
   603 
   604     def is_assigned(version: Version): Boolean =
   605       assignments.get(version.id) match {
   606         case Some(assgn) => assgn.is_finished
   607         case None => false
   608       }
   609 
   610     def is_stable(change: Change): Boolean =
   611       change.is_finished && is_assigned(change.version.get_finished)
   612 
   613     def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
   614     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   615     def tip_stable: Boolean = is_stable(history.tip)
   616     def tip_version: Version = history.tip.version.get_finished
   617 
   618     def continue_history(
   619       previous: Future[Version],
   620       edits: List[Edit_Text],
   621       version: Future[Version]): State =
   622     {
   623       val change = Change.make(previous, edits, version)
   624       copy(history = history + change)
   625     }
   626 
   627     def prune_history(retain: Int = 0): (List[Version], State) =
   628     {
   629       history.prune(is_stable, retain) match {
   630         case Some((dropped, history1)) =>
   631           val dropped_versions = dropped.map(change => change.version.get_finished)
   632           val state1 = copy(history = history1)
   633           (dropped_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_digests; 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     }
   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