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