src/Pure/PIDE/document.scala
author wenzelm
Tue Aug 12 18:36:43 2014 +0200 (2014-08-12)
changeset 57916 2c2c24dbf0a4
parent 57842 8e4ae2db1849
child 57976 bf99106b6672
permissions -rw-r--r--
generic process wrapping in Prover;
clarified module arrangement;
     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   {
   504     private def fail[A]: A = throw new State.Fail(this)
   505 
   506     def define_version(version: Version, assignment: State.Assignment): State =
   507     {
   508       val id = version.id
   509       copy(versions = versions + (id -> version),
   510         assignments = assignments + (id -> assignment.unfinished))
   511     }
   512 
   513     def define_blob(digest: SHA1.Digest): State = copy(blobs = blobs + digest)
   514     def defined_blob(digest: SHA1.Digest): Boolean = blobs.contains(digest)
   515 
   516     def define_command(command: Command): State =
   517     {
   518       val id = command.id
   519       copy(commands = commands + (id -> command.init_state))
   520     }
   521 
   522     def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
   523 
   524     def find_command(version: Version, id: Document_ID.Generic): Option[(Node, Command)] =
   525       commands.get(id) orElse execs.get(id) match {
   526         case None => None
   527         case Some(st) =>
   528           val command = st.command
   529           val node = version.nodes(command.node_name)
   530           if (node.commands.contains(command)) Some((node, command)) else None
   531       }
   532 
   533     def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
   534     def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
   535     def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
   536     def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
   537 
   538     private def self_id(st: Command.State)(id: Document_ID.Generic): Boolean =
   539       id == st.command.id ||
   540       (execs.get(id) match { case Some(st1) => st1.command.id == st.command.id case None => false })
   541 
   542     private def other_id(id: Document_ID.Generic)
   543       : Option[(Symbol.Text_Chunk.Id, Symbol.Text_Chunk)] = None
   544     /* FIXME
   545       (execs.get(id) orElse commands.get(id)).map(st =>
   546         ((Symbol.Text_Chunk.Id(st.command.id), st.command.chunk)))
   547     */
   548 
   549     private def redirection(st: Command.State): Graph[Document_ID.Command, Unit] =
   550       (commands_redirection /: st.markups.redirection_iterator)({ case (graph, id) =>
   551         graph.default_node(id, ()).default_node(st.command.id, ()).add_edge(id, st.command.id) })
   552 
   553     def accumulate(id: Document_ID.Generic, message: XML.Elem): (Command.State, State) =
   554     {
   555       execs.get(id) match {
   556         case Some(st) =>
   557           val new_st = st.accumulate(self_id(st), other_id _, message)
   558           val execs1 = execs + (id -> new_st)
   559           (new_st, copy(execs = execs1, commands_redirection = redirection(new_st)))
   560         case None =>
   561           commands.get(id) match {
   562             case Some(st) =>
   563               val new_st = st.accumulate(self_id(st), other_id _, message)
   564               val commands1 = commands + (id -> new_st)
   565               (new_st, copy(commands = commands1, commands_redirection = redirection(new_st)))
   566             case None => fail
   567           }
   568       }
   569     }
   570 
   571     def assign(id: Document_ID.Version, update: Assign_Update): (List[Command], State) =
   572     {
   573       val version = the_version(id)
   574 
   575       def upd(exec_id: Document_ID.Exec, st: Command.State)
   576           : Option[(Document_ID.Exec, Command.State)] =
   577         if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
   578 
   579       val (changed_commands, new_execs) =
   580         ((Nil: List[Command], execs) /: update) {
   581           case ((commands1, execs1), (command_id, exec)) =>
   582             val st = the_static_state(command_id)
   583             val command = st.command
   584             val commands2 = command :: commands1
   585             val execs2 =
   586               exec match {
   587                 case Nil => execs1
   588                 case eval_id :: print_ids =>
   589                   execs1 ++ upd(eval_id, st) ++
   590                     (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
   591               }
   592             (commands2, execs2)
   593         }
   594       val new_assignment = the_assignment(version).assign(update)
   595       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   596 
   597       (changed_commands, new_state)
   598     }
   599 
   600     def is_assigned(version: Version): Boolean =
   601       assignments.get(version.id) match {
   602         case Some(assgn) => assgn.is_finished
   603         case None => false
   604       }
   605 
   606     def is_stable(change: Change): Boolean =
   607       change.is_finished && is_assigned(change.version.get_finished)
   608 
   609     def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
   610     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   611     def tip_stable: Boolean = is_stable(history.tip)
   612     def tip_version: Version = history.tip.version.get_finished
   613 
   614     def continue_history(
   615       previous: Future[Version],
   616       edits: List[Edit_Text],
   617       version: Future[Version]): State =
   618     {
   619       val change = Change.make(previous, edits, version)
   620       copy(history = history + change)
   621     }
   622 
   623     def prune_history(retain: Int = 0): (List[Version], State) =
   624     {
   625       history.prune(is_stable, retain) match {
   626         case Some((dropped, history1)) =>
   627           val dropped_versions = dropped.map(change => change.version.get_finished)
   628           val state1 = copy(history = history1)
   629           (dropped_versions, state1)
   630         case None => fail
   631       }
   632     }
   633 
   634     def removed_versions(removed: List[Document_ID.Version]): State =
   635     {
   636       val versions1 = versions -- removed
   637       val assignments1 = assignments -- removed
   638       var blobs1 = Set.empty[SHA1.Digest]
   639       var commands1 = Map.empty[Document_ID.Command, Command.State]
   640       var execs1 = Map.empty[Document_ID.Exec, Command.State]
   641       for {
   642         (version_id, version) <- versions1.iterator
   643         command_execs = assignments1(version_id).command_execs
   644         (_, node) <- version.nodes.iterator
   645         command <- node.commands.iterator
   646       } {
   647         for ((_, digest) <- command.blobs_defined; if !blobs1.contains(digest))
   648           blobs1 += digest
   649 
   650         if (!commands1.isDefinedAt(command.id))
   651           commands.get(command.id).foreach(st => commands1 += (command.id -> st))
   652 
   653         for (exec_id <- command_execs.getOrElse(command.id, Nil)) {
   654           if (!execs1.isDefinedAt(exec_id))
   655             execs.get(exec_id).foreach(st => execs1 += (exec_id -> st))
   656         }
   657       }
   658       copy(
   659         versions = versions1,
   660         blobs = blobs1,
   661         commands = commands1,
   662         execs = execs1,
   663         commands_redirection = commands_redirection.restrict(commands1.isDefinedAt(_)),
   664         assignments = assignments1)
   665     }
   666 
   667     private def command_states_self(version: Version, command: Command)
   668       : List[(Document_ID.Generic, Command.State)] =
   669     {
   670       require(is_assigned(version))
   671       try {
   672         the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil)
   673           .map(id => id -> the_dynamic_state(id)) match {
   674             case Nil => fail
   675             case res => res
   676           }
   677       }
   678       catch {
   679         case _: State.Fail =>
   680           try { List(command.id -> the_static_state(command.id)) }
   681           catch { case _: State.Fail => List(command.id -> command.init_state) }
   682       }
   683     }
   684 
   685     def command_states(version: Version, command: Command): List[Command.State] =
   686     {
   687       val self = command_states_self(version, command)
   688       val others =
   689         if (commands_redirection.defined(command.id)) {
   690           (for {
   691             command_id <- commands_redirection.imm_succs(command.id).iterator
   692             (id, st) <- command_states_self(version, the_static_state(command_id).command)
   693             if !self.exists(_._1 == id)
   694           } yield (id, st)).toMap.valuesIterator.toList
   695         }
   696         else Nil
   697       self.map(_._2) ::: others.flatMap(_.redirect(command))
   698     }
   699 
   700     def command_results(version: Version, command: Command): Command.Results =
   701       Command.State.merge_results(command_states(version, command))
   702 
   703     def command_markup(version: Version, command: Command, index: Command.Markup_Index,
   704         range: Text.Range, elements: Markup.Elements): Markup_Tree =
   705       Command.State.merge_markup(command_states(version, command), index, range, elements)
   706 
   707     def markup_to_XML(version: Version, node: Node, elements: Markup.Elements): XML.Body =
   708       (for {
   709         command <- node.commands.iterator
   710         markup =
   711           command_markup(version, command, Command.Markup_Index.markup, command.range, elements)
   712         tree <- markup.to_XML(command.range, command.source, elements)
   713       } yield tree).toList
   714 
   715     // persistent user-view
   716     def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
   717       : Snapshot =
   718     {
   719       val stable = recent_stable
   720       val latest = history.tip
   721 
   722 
   723       /* pending edits and unstable changes */
   724 
   725       val rev_pending_changes =
   726         for {
   727           change <- history.undo_list.takeWhile(_ != stable)
   728           (a, edits) <- change.rev_edits
   729           if a == name
   730         } yield edits
   731 
   732       val is_cleared = rev_pending_changes.exists({ case Node.Clear() => true case _ => false })
   733       val edits =
   734         if (is_cleared) Nil
   735         else
   736           (pending_edits /: rev_pending_changes)({
   737             case (edits, Node.Edits(es)) => es ::: edits
   738             case (edits, _) => edits
   739           })
   740       lazy val reverse_edits = edits.reverse
   741 
   742       new Snapshot
   743       {
   744         /* global information */
   745 
   746         val state = State.this
   747         val version = stable.version.get_finished
   748         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   749 
   750 
   751         /* local node content */
   752 
   753         def convert(offset: Text.Offset) =
   754           if (is_cleared) 0 else (offset /: edits)((i, edit) => edit.convert(i))
   755         def revert(offset: Text.Offset) =
   756           if (is_cleared) 0 else (offset /: reverse_edits)((i, edit) => edit.revert(i))
   757 
   758         def convert(range: Text.Range) = range.map(convert(_))
   759         def revert(range: Text.Range) = range.map(revert(_))
   760 
   761         val node_name = name
   762         val node = version.nodes(name)
   763 
   764         val load_commands: List[Command] =
   765           if (node_name.is_theory) Nil
   766           else version.nodes.load_commands(node_name)
   767 
   768         val is_loaded: Boolean = node_name.is_theory || !load_commands.isEmpty
   769 
   770         def eq_content(other: Snapshot): Boolean =
   771         {
   772           def eq_commands(commands: (Command, Command)): Boolean =
   773           {
   774             val states1 = state.command_states(version, commands._1)
   775             val states2 = other.state.command_states(other.version, commands._2)
   776             states1.length == states2.length &&
   777             (states1 zip states2).forall({ case (st1, st2) => st1 eq_content st2 })
   778           }
   779 
   780           !is_outdated && !other.is_outdated &&
   781           node.commands.size == other.node.commands.size &&
   782           (node.commands.iterator zip other.node.commands.iterator).forall(eq_commands) &&
   783           load_commands.length == other.load_commands.length &&
   784           (load_commands zip other.load_commands).forall(eq_commands)
   785         }
   786 
   787 
   788         /* cumulate markup */
   789 
   790         def cumulate[A](
   791           range: Text.Range,
   792           info: A,
   793           elements: Markup.Elements,
   794           result: List[Command.State] => (A, Text.Markup) => Option[A],
   795           status: Boolean = false): List[Text.Info[A]] =
   796         {
   797           val former_range = revert(range).inflate_singularity
   798           val (chunk_name, command_iterator) =
   799             load_commands match {
   800               case command :: _ => (Symbol.Text_Chunk.File(node_name.node), Iterator((command, 0)))
   801               case _ => (Symbol.Text_Chunk.Default, node.command_iterator(former_range))
   802             }
   803           val markup_index = Command.Markup_Index(status, chunk_name)
   804           (for {
   805             (command, command_start) <- command_iterator
   806             chunk <- command.chunks.get(chunk_name).iterator
   807             states = state.command_states(version, command)
   808             res = result(states)
   809             markup_range <- (former_range - command_start).try_restrict(chunk.range).iterator
   810             markup = Command.State.merge_markup(states, markup_index, markup_range, elements)
   811             Text.Info(r0, a) <- markup.cumulate[A](markup_range, info, elements,
   812               {
   813                 case (a, Text.Info(r0, b)) => res(a, Text.Info(convert(r0 + command_start), b))
   814               }).iterator
   815             r1 <- convert(r0 + command_start).try_restrict(range).iterator
   816           } yield Text.Info(r1, a)).toList
   817         }
   818 
   819         def select[A](
   820           range: Text.Range,
   821           elements: Markup.Elements,
   822           result: List[Command.State] => Text.Markup => Option[A],
   823           status: Boolean = false): List[Text.Info[A]] =
   824         {
   825           def result1(states: List[Command.State]): (Option[A], Text.Markup) => Option[Option[A]] =
   826           {
   827             val res = result(states)
   828             (_: Option[A], x: Text.Markup) =>
   829               res(x) match {
   830                 case None => None
   831                 case some => Some(some)
   832               }
   833           }
   834           for (Text.Info(r, Some(x)) <- cumulate(range, None, elements, result1 _, status))
   835             yield Text.Info(r, x)
   836         }
   837 
   838 
   839         /* output */
   840 
   841         override def toString: String =
   842           "Snapshot(node = " + node_name.node + ", version = " + version.id +
   843             (if (is_outdated) ", outdated" else "") + ")"
   844       }
   845     }
   846   }
   847 }
   848