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