src/Pure/PIDE/document.scala
author wenzelm
Tue Apr 08 15:12:54 2014 +0200 (2014-04-08)
changeset 56468 30128d1acfbc
parent 56462 b64b0cb845fe
child 56470 8eda56033203
permissions -rw-r--r--
tuned signature -- moved Command.Chunk to Text.Chunk;
     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: Text.Chunk.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 = 256
   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 iterator(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_iterator(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   257       _commands.iterator(i)
   258 
   259     def command_iterator(range: Text.Range): Iterator[(Command, Text.Offset)] =
   260       command_iterator(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_iterator.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 iterator: Iterator[(Node.Name, Node)] =
   294       graph.iterator.map({ case (name, (node, _)) => (name, node) })
   295 
   296     def load_commands(file_name: Node.Name): List[Command] =
   297       (for {
   298         (_, node) <- iterator
   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: Option[Prover.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: Option[Prover.Syntax] = None,
   327     val nodes: Nodes = Nodes.empty)
   328   {
   329     override def toString: String = "Version(" + id + ")"
   330   }
   331 
   332 
   333   /* changes of plain text, eventually resulting in document edits */
   334 
   335   object Change
   336   {
   337     val init: Change = new Change()
   338 
   339     def make(previous: Future[Version], edits: List[Edit_Text], version: Future[Version]): Change =
   340       new Change(Some(previous), edits, version)
   341   }
   342 
   343   final class Change private(
   344     val previous: Option[Future[Version]] = Some(Future.value(Version.init)),
   345     val edits: List[Edit_Text] = Nil,
   346     val version: Future[Version] = Future.value(Version.init))
   347   {
   348     def is_finished: Boolean =
   349       (previous match { case None => true case Some(future) => future.is_finished }) &&
   350       version.is_finished
   351 
   352     def truncate: Change = new Change(None, Nil, version)
   353   }
   354 
   355 
   356   /* history navigation */
   357 
   358   object History
   359   {
   360     val init: History = new History()
   361   }
   362 
   363   final class History private(
   364     val undo_list: List[Change] = List(Change.init))  // non-empty list
   365   {
   366     def tip: Change = undo_list.head
   367     def + (change: Change): History = new History(change :: undo_list)
   368 
   369     def prune(check: Change => Boolean, retain: Int): Option[(List[Change], History)] =
   370     {
   371       val n = undo_list.iterator.zipWithIndex.find(p => check(p._1)).get._2 + 1
   372       val (retained, dropped) = undo_list.splitAt(n max retain)
   373 
   374       retained.splitAt(retained.length - 1) match {
   375         case (prefix, List(last)) => Some(dropped, new History(prefix ::: List(last.truncate)))
   376         case _ => None
   377       }
   378     }
   379   }
   380 
   381 
   382   /* markup elements */
   383 
   384   object Elements
   385   {
   386     def apply(elems: Set[String]): Elements = new Elements(elems)
   387     def apply(elems: String*): Elements = apply(Set(elems: _*))
   388     val empty: Elements = apply()
   389     val full: Elements = new Full_Elements
   390   }
   391 
   392   sealed class Elements private[Document](private val rep: Set[String])
   393   {
   394     def apply(elem: String): Boolean = rep.contains(elem)
   395     def + (elem: String): Elements = new Elements(rep + elem)
   396     def ++ (elems: Elements): Elements = new Elements(rep ++ elems.rep)
   397     override def toString: String = rep.mkString("Elements(", ",", ")")
   398   }
   399 
   400   private class Full_Elements extends Elements(Set.empty)
   401   {
   402     override def apply(elem: String): Boolean = true
   403     override def toString: String = "Full_Elements()"
   404   }
   405 
   406 
   407   /* snapshot */
   408 
   409   object Snapshot
   410   {
   411     val init = State.init.snapshot()
   412   }
   413 
   414   abstract class Snapshot
   415   {
   416     val state: State
   417     val version: Version
   418     val is_outdated: Boolean
   419 
   420     def convert(i: Text.Offset): Text.Offset
   421     def revert(i: Text.Offset): Text.Offset
   422     def convert(range: Text.Range): Text.Range
   423     def revert(range: Text.Range): Text.Range
   424 
   425     val node_name: Node.Name
   426     val node: Node
   427     val load_commands: List[Command]
   428     def is_loaded: Boolean
   429     def eq_content(other: Snapshot): Boolean
   430 
   431     def cumulate[A](
   432       range: Text.Range,
   433       info: A,
   434       elements: Elements,
   435       result: List[Command.State] => (A, Text.Markup) => Option[A],
   436       status: Boolean = false): List[Text.Info[A]]
   437 
   438     def select[A](
   439       range: Text.Range,
   440       elements: Elements,
   441       result: List[Command.State] => Text.Markup => Option[A],
   442       status: Boolean = false): List[Text.Info[A]]
   443   }
   444 
   445 
   446 
   447   /** global state -- document structure, execution process, editing history **/
   448 
   449   type Assign_Update =
   450     List[(Document_ID.Command, List[Document_ID.Exec])]  // update of exec state assignment
   451 
   452   object State
   453   {
   454     class Fail(state: State) extends Exception
   455 
   456     object Assignment
   457     {
   458       val init: Assignment = new Assignment()
   459     }
   460 
   461     final class Assignment private(
   462       val command_execs: Map[Document_ID.Command, List[Document_ID.Exec]] = Map.empty,
   463       val is_finished: Boolean = false)
   464     {
   465       def check_finished: Assignment = { require(is_finished); this }
   466       def unfinished: Assignment = new Assignment(command_execs, false)
   467 
   468       def assign(update: Assign_Update): Assignment =
   469       {
   470         require(!is_finished)
   471         val command_execs1 =
   472           (command_execs /: update) {
   473             case (res, (command_id, exec_ids)) =>
   474               if (exec_ids.isEmpty) res - command_id
   475               else res + (command_id -> exec_ids)
   476           }
   477         new Assignment(command_execs1, true)
   478       }
   479     }
   480 
   481     val init: State =
   482       State().define_version(Version.init, Assignment.init).assign(Version.init.id, Nil)._2
   483   }
   484 
   485   final case class State private(
   486     val versions: Map[Document_ID.Version, Version] = Map.empty,
   487     val blobs: Set[SHA1.Digest] = Set.empty,   // inlined files
   488     val commands: Map[Document_ID.Command, Command.State] = Map.empty,  // static markup from define_command
   489     val execs: Map[Document_ID.Exec, Command.State] = Map.empty,  // dynamic markup from execution
   490     val assignments: Map[Document_ID.Version, State.Assignment] = Map.empty,
   491     val history: History = History.init)
   492   {
   493     private def fail[A]: A = throw new State.Fail(this)
   494 
   495     def define_version(version: Version, assignment: State.Assignment): State =
   496     {
   497       val id = version.id
   498       copy(versions = versions + (id -> version),
   499         assignments = assignments + (id -> assignment.unfinished))
   500     }
   501 
   502     def define_blob(digest: SHA1.Digest): State = copy(blobs = blobs + digest)
   503     def defined_blob(digest: SHA1.Digest): Boolean = blobs.contains(digest)
   504 
   505     def define_command(command: Command): State =
   506     {
   507       val id = command.id
   508       copy(commands = commands + (id -> command.init_state))
   509     }
   510 
   511     def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
   512 
   513     def find_command(version: Version, id: Document_ID.Generic): Option[(Node, Command)] =
   514       commands.get(id) orElse execs.get(id) match {
   515         case None => None
   516         case Some(st) =>
   517           val command = st.command
   518           val node = version.nodes(command.node_name)
   519           if (node.commands.contains(command)) Some((node, command)) else None
   520       }
   521 
   522     def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
   523     def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
   524     def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
   525     def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
   526 
   527     def valid_id(st: Command.State)(id: Document_ID.Generic): Boolean =
   528       id == st.command.id ||
   529       (execs.get(id) match { case Some(st1) => st1.command.id == st.command.id case None => false })
   530 
   531     def accumulate(id: Document_ID.Generic, message: XML.Elem): (Command.State, State) =
   532       execs.get(id) match {
   533         case Some(st) =>
   534           val new_st = st + (valid_id(st), message)
   535           (new_st, copy(execs = execs + (id -> new_st)))
   536         case None =>
   537           commands.get(id) match {
   538             case Some(st) =>
   539               val new_st = st + (valid_id(st), message)
   540               (new_st, copy(commands = commands + (id -> new_st)))
   541             case None => fail
   542           }
   543       }
   544 
   545     def assign(id: Document_ID.Version, update: Assign_Update): (List[Command], State) =
   546     {
   547       val version = the_version(id)
   548 
   549       def upd(exec_id: Document_ID.Exec, st: Command.State)
   550           : Option[(Document_ID.Exec, Command.State)] =
   551         if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
   552 
   553       val (changed_commands, new_execs) =
   554         ((Nil: List[Command], execs) /: update) {
   555           case ((commands1, execs1), (command_id, exec)) =>
   556             val st = the_static_state(command_id)
   557             val command = st.command
   558             val commands2 = command :: commands1
   559             val execs2 =
   560               exec match {
   561                 case Nil => execs1
   562                 case eval_id :: print_ids =>
   563                   execs1 ++ upd(eval_id, st) ++
   564                     (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
   565               }
   566             (commands2, execs2)
   567         }
   568       val new_assignment = the_assignment(version).assign(update)
   569       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   570 
   571       (changed_commands, new_state)
   572     }
   573 
   574     def is_assigned(version: Version): Boolean =
   575       assignments.get(version.id) match {
   576         case Some(assgn) => assgn.is_finished
   577         case None => false
   578       }
   579 
   580     def is_stable(change: Change): Boolean =
   581       change.is_finished && is_assigned(change.version.get_finished)
   582 
   583     def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
   584     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   585     def tip_stable: Boolean = is_stable(history.tip)
   586     def tip_version: Version = history.tip.version.get_finished
   587 
   588     def continue_history(
   589         previous: Future[Version],
   590         edits: List[Edit_Text],
   591         version: Future[Version]): (Change, State) =
   592     {
   593       val change = Change.make(previous, edits, version)
   594       (change, copy(history = history + change))
   595     }
   596 
   597     def prune_history(retain: Int = 0): (List[Version], State) =
   598     {
   599       history.prune(is_stable, retain) match {
   600         case Some((dropped, history1)) =>
   601           val dropped_versions = dropped.map(change => change.version.get_finished)
   602           val state1 = copy(history = history1)
   603           (dropped_versions, state1)
   604         case None => fail
   605       }
   606     }
   607 
   608     def removed_versions(removed: List[Document_ID.Version]): State =
   609     {
   610       val versions1 = versions -- removed
   611       val assignments1 = assignments -- removed
   612       var blobs1 = Set.empty[SHA1.Digest]
   613       var commands1 = Map.empty[Document_ID.Command, Command.State]
   614       var execs1 = Map.empty[Document_ID.Exec, Command.State]
   615       for {
   616         (version_id, version) <- versions1.iterator
   617         command_execs = assignments1(version_id).command_execs
   618         (_, node) <- version.nodes.iterator
   619         command <- node.commands.iterator
   620       } {
   621         for (digest <- command.blobs_digests; if !blobs1.contains(digest))
   622           blobs1 += digest
   623 
   624         if (!commands1.isDefinedAt(command.id))
   625           commands.get(command.id).foreach(st => commands1 += (command.id -> st))
   626 
   627         for (exec_id <- command_execs.getOrElse(command.id, Nil)) {
   628           if (!execs1.isDefinedAt(exec_id))
   629             execs.get(exec_id).foreach(st => execs1 += (exec_id -> st))
   630         }
   631       }
   632       copy(versions = versions1, blobs = blobs1, commands = commands1, execs = execs1,
   633         assignments = assignments1)
   634     }
   635 
   636     def command_states(version: Version, command: Command): List[Command.State] =
   637     {
   638       require(is_assigned(version))
   639       try {
   640         the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil)
   641           .map(the_dynamic_state(_)) match {
   642             case Nil => fail
   643             case states => states
   644           }
   645       }
   646       catch {
   647         case _: State.Fail =>
   648           try { List(the_static_state(command.id)) }
   649           catch { case _: State.Fail => List(command.init_state) }
   650       }
   651     }
   652 
   653     def command_results(version: Version, command: Command): Command.Results =
   654       Command.State.merge_results(command_states(version, command))
   655 
   656     def command_markup(version: Version, command: Command, index: Command.Markup_Index,
   657         range: Text.Range, elements: Elements): Markup_Tree =
   658       Command.State.merge_markup(command_states(version, command), index, range, elements)
   659 
   660     def markup_to_XML(version: Version, node: Node, elements: Elements): XML.Body =
   661       (for {
   662         command <- node.commands.iterator
   663         markup =
   664           command_markup(version, command, Command.Markup_Index.markup, command.range, elements)
   665         tree <- markup.to_XML(command.range, command.source, elements)
   666       } yield tree).toList
   667 
   668     // persistent user-view
   669     def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
   670       : Snapshot =
   671     {
   672       val stable = recent_stable
   673       val latest = history.tip
   674 
   675       // FIXME proper treatment of removed nodes
   676       val edits =
   677         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   678             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   679       lazy val reverse_edits = edits.reverse
   680 
   681       new Snapshot
   682       {
   683         /* global information */
   684 
   685         val state = State.this
   686         val version = stable.version.get_finished
   687         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   688 
   689 
   690         /* local node content */
   691 
   692         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   693         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   694         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   695         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   696 
   697         val node_name = name
   698         val node = version.nodes(name)
   699 
   700         val load_commands: List[Command] =
   701           if (node_name.is_theory) Nil
   702           else version.nodes.load_commands(node_name)
   703 
   704         val is_loaded: Boolean = node_name.is_theory || !load_commands.isEmpty
   705 
   706         def eq_content(other: Snapshot): Boolean =
   707         {
   708           def eq_commands(commands: (Command, Command)): Boolean =
   709           {
   710             val states1 = state.command_states(version, commands._1)
   711             val states2 = other.state.command_states(other.version, commands._2)
   712             states1.length == states2.length &&
   713             (states1 zip states2).forall({ case (st1, st2) => st1 eq_content st2 })
   714           }
   715 
   716           !is_outdated && !other.is_outdated &&
   717           node.commands.size == other.node.commands.size &&
   718           (node.commands.iterator zip other.node.commands.iterator).forall(eq_commands) &&
   719           load_commands.length == other.load_commands.length &&
   720           (load_commands zip other.load_commands).forall(eq_commands)
   721         }
   722 
   723 
   724         /* cumulate markup */
   725 
   726         def cumulate[A](
   727           range: Text.Range,
   728           info: A,
   729           elements: Elements,
   730           result: List[Command.State] => (A, Text.Markup) => Option[A],
   731           status: Boolean = false): List[Text.Info[A]] =
   732         {
   733           val former_range = revert(range)
   734           val (chunk_name, command_iterator) =
   735             load_commands match {
   736               case command :: _ => (Text.Chunk.File_Name(node_name.node), Iterator((command, 0)))
   737               case _ => (Text.Chunk.Default, node.command_iterator(former_range))
   738             }
   739           val markup_index = Command.Markup_Index(status, chunk_name)
   740           (for {
   741             (command, command_start) <- command_iterator
   742             chunk <- command.chunks.get(chunk_name).iterator
   743             states = state.command_states(version, command)
   744             res = result(states)
   745             range = (former_range - command_start).restrict(chunk.range)
   746             markup = Command.State.merge_markup(states, markup_index, range, elements)
   747             Text.Info(r0, a) <- markup.cumulate[A](range, info, elements,
   748               {
   749                 case (a, Text.Info(r0, b)) => res(a, Text.Info(convert(r0 + command_start), b))
   750               }).iterator
   751           } yield Text.Info(convert(r0 + command_start), a)).toList
   752         }
   753 
   754         def select[A](
   755           range: Text.Range,
   756           elements: Elements,
   757           result: List[Command.State] => Text.Markup => Option[A],
   758           status: Boolean = false): List[Text.Info[A]] =
   759         {
   760           def result1(states: List[Command.State]): (Option[A], Text.Markup) => Option[Option[A]] =
   761           {
   762             val res = result(states)
   763             (_: Option[A], x: Text.Markup) =>
   764               res(x) match {
   765                 case None => None
   766                 case some => Some(some)
   767               }
   768           }
   769           for (Text.Info(r, Some(x)) <- cumulate(range, None, elements, result1 _, status))
   770             yield Text.Info(r, x)
   771         }
   772 
   773 
   774         /* output */
   775 
   776         override def toString: String =
   777           "Snapshot(node = " + node_name.node + ", version = " + version.id +
   778             (if (is_outdated) ", outdated" else "") + ")"
   779       }
   780     }
   781   }
   782 }
   783