src/Pure/PIDE/document.scala
author wenzelm
Sat Apr 26 13:07:20 2014 +0200 (2014-04-26)
changeset 56743 81370dfadb1d
parent 56711 ef3d00153e3b
child 56746 d37a5d09a277
permissions -rw-r--r--
tuned signature;
     1 /*  Title:      Pure/PIDE/document.scala
     2     Author:     Makarius
     3 
     4 Document as collection of named nodes, each consisting of an editable
     5 list of commands, associated with asynchronous execution process.
     6 */
     7 
     8 package isabelle
     9 
    10 
    11 import scala.collection.mutable
    12 
    13 
    14 object Document
    15 {
    16   /** document structure **/
    17 
    18   /* overlays -- print functions with arguments */
    19 
    20   object Overlays
    21   {
    22     val empty = new Overlays(Map.empty)
    23   }
    24 
    25   final class Overlays private(rep: Map[Node.Name, Node.Overlays])
    26   {
    27     def apply(name: Document.Node.Name): Node.Overlays =
    28       rep.getOrElse(name, Node.Overlays.empty)
    29 
    30     private def update(name: Node.Name, f: Node.Overlays => Node.Overlays): Overlays =
    31     {
    32       val node_overlays = f(apply(name))
    33       new Overlays(if (node_overlays.is_empty) rep - name else rep + (name -> node_overlays))
    34     }
    35 
    36     def insert(command: Command, fn: String, args: List[String]): Overlays =
    37       update(command.node_name, _.insert(command, fn, args))
    38 
    39     def remove(command: Command, fn: String, args: List[String]): Overlays =
    40       update(command.node_name, _.remove(command, fn, args))
    41 
    42     override def toString: String = rep.mkString("Overlays(", ",", ")")
    43   }
    44 
    45 
    46   /* document blobs: auxiliary files */
    47 
    48   sealed case class Blob(bytes: Bytes, chunk: Text.Chunk, changed: Boolean)
    49   {
    50     def unchanged: Blob = copy(changed = false)
    51   }
    52 
    53   object Blobs
    54   {
    55     def apply(blobs: Map[Node.Name, Blob]): Blobs = new Blobs(blobs)
    56     val empty: Blobs = apply(Map.empty)
    57   }
    58 
    59   final class Blobs private(blobs: Map[Node.Name, Blob])
    60   {
    61     private lazy val digests: Map[SHA1.Digest, Blob] =
    62       for ((_, blob) <- blobs) yield (blob.bytes.sha1_digest, blob)
    63 
    64     def get(digest: SHA1.Digest): Option[Blob] = digests.get(digest)
    65     def get(name: Node.Name): Option[Blob] = blobs.get(name)
    66 
    67     def changed(name: Node.Name): Boolean =
    68       get(name) match {
    69         case Some(blob) => blob.changed
    70         case None => false
    71       }
    72 
    73     override def toString: String = blobs.mkString("Blobs(", ",", ")")
    74   }
    75 
    76 
    77   /* document nodes: theories and auxiliary files */
    78 
    79   type Edit[A, B] = (Node.Name, Node.Edit[A, B])
    80   type Edit_Text = Edit[Text.Edit, Text.Perspective]
    81   type Edit_Command = Edit[Command.Edit, Command.Perspective]
    82 
    83   object Node
    84   {
    85     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   /* snapshot */
   383 
   384   object Snapshot
   385   {
   386     val init = State.init.snapshot()
   387   }
   388 
   389   abstract class Snapshot
   390   {
   391     val state: State
   392     val version: Version
   393     val is_outdated: Boolean
   394 
   395     def convert(i: Text.Offset): Text.Offset
   396     def revert(i: Text.Offset): Text.Offset
   397     def convert(range: Text.Range): Text.Range
   398     def revert(range: Text.Range): Text.Range
   399 
   400     val node_name: Node.Name
   401     val node: Node
   402     val load_commands: List[Command]
   403     def is_loaded: Boolean
   404     def eq_content(other: Snapshot): Boolean
   405 
   406     def cumulate[A](
   407       range: Text.Range,
   408       info: A,
   409       elements: Markup.Elements,
   410       result: List[Command.State] => (A, Text.Markup) => Option[A],
   411       status: Boolean = false): List[Text.Info[A]]
   412 
   413     def select[A](
   414       range: Text.Range,
   415       elements: Markup.Elements,
   416       result: List[Command.State] => Text.Markup => Option[A],
   417       status: Boolean = false): List[Text.Info[A]]
   418   }
   419 
   420 
   421 
   422   /** global state -- document structure, execution process, editing history **/
   423 
   424   type Assign_Update =
   425     List[(Document_ID.Command, List[Document_ID.Exec])]  // update of exec state assignment
   426 
   427   object State
   428   {
   429     class Fail(state: State) extends Exception
   430 
   431     object Assignment
   432     {
   433       val init: Assignment = new Assignment()
   434     }
   435 
   436     final class Assignment private(
   437       val command_execs: Map[Document_ID.Command, List[Document_ID.Exec]] = Map.empty,
   438       val is_finished: Boolean = false)
   439     {
   440       def check_finished: Assignment = { require(is_finished); this }
   441       def unfinished: Assignment = new Assignment(command_execs, false)
   442 
   443       def assign(update: Assign_Update): Assignment =
   444       {
   445         require(!is_finished)
   446         val command_execs1 =
   447           (command_execs /: update) {
   448             case (res, (command_id, exec_ids)) =>
   449               if (exec_ids.isEmpty) res - command_id
   450               else res + (command_id -> exec_ids)
   451           }
   452         new Assignment(command_execs1, true)
   453       }
   454     }
   455 
   456     val init: State =
   457       State().define_version(Version.init, Assignment.init).assign(Version.init.id, Nil)._2
   458   }
   459 
   460   final case class State private(
   461     /*reachable versions*/
   462     val versions: Map[Document_ID.Version, Version] = Map.empty,
   463     /*inlined auxiliary files*/
   464     val blobs: Set[SHA1.Digest] = Set.empty,
   465     /*static markup from define_command*/
   466     val commands: Map[Document_ID.Command, Command.State] = Map.empty,
   467     /*dynamic markup from execution*/
   468     val execs: Map[Document_ID.Exec, Command.State] = Map.empty,
   469     /*command-exec assignment for each version*/
   470     val assignments: Map[Document_ID.Version, State.Assignment] = Map.empty,
   471     /*commands with markup produced by other commands (imm_succs)*/
   472     val commands_redirection: Graph[Document_ID.Command, Unit] = Graph.long,
   473     /*explicit (linear) history*/
   474     val history: History = History.init)
   475   {
   476     private def fail[A]: A = throw new State.Fail(this)
   477 
   478     def define_version(version: Version, assignment: State.Assignment): State =
   479     {
   480       val id = version.id
   481       copy(versions = versions + (id -> version),
   482         assignments = assignments + (id -> assignment.unfinished))
   483     }
   484 
   485     def define_blob(digest: SHA1.Digest): State = copy(blobs = blobs + digest)
   486     def defined_blob(digest: SHA1.Digest): Boolean = blobs.contains(digest)
   487 
   488     def define_command(command: Command): State =
   489     {
   490       val id = command.id
   491       copy(commands = commands + (id -> command.init_state))
   492     }
   493 
   494     def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
   495 
   496     def find_command(version: Version, id: Document_ID.Generic): Option[(Node, Command)] =
   497       commands.get(id) orElse execs.get(id) match {
   498         case None => None
   499         case Some(st) =>
   500           val command = st.command
   501           val node = version.nodes(command.node_name)
   502           if (node.commands.contains(command)) Some((node, command)) else None
   503       }
   504 
   505     def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
   506     def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
   507     def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
   508     def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
   509 
   510     private def self_id(st: Command.State)(id: Document_ID.Generic): Boolean =
   511       id == st.command.id ||
   512       (execs.get(id) match { case Some(st1) => st1.command.id == st.command.id case None => false })
   513 
   514     private def other_id(id: Document_ID.Generic): Option[(Text.Chunk.Id, Text.Chunk)] = None
   515     /* FIXME
   516       (execs.get(id) orElse commands.get(id)).map(st =>
   517         ((Text.Chunk.Id(st.command.id), st.command.chunk)))
   518     */
   519 
   520     private def redirection(st: Command.State): Graph[Document_ID.Command, Unit] =
   521       (commands_redirection /: st.markups.redirection_iterator)({ case (graph, id) =>
   522         graph.default_node(id, ()).default_node(st.command.id, ()).add_edge(id, st.command.id) })
   523 
   524     def accumulate(id: Document_ID.Generic, message: XML.Elem): (Command.State, State) =
   525     {
   526       execs.get(id) match {
   527         case Some(st) =>
   528           val new_st = st.accumulate(self_id(st), other_id _, message)
   529           val execs1 = execs + (id -> new_st)
   530           (new_st, copy(execs = execs1, commands_redirection = redirection(new_st)))
   531         case None =>
   532           commands.get(id) match {
   533             case Some(st) =>
   534               val new_st = st.accumulate(self_id(st), other_id _, message)
   535               val commands1 = commands + (id -> new_st)
   536               (new_st, copy(commands = commands1, commands_redirection = redirection(new_st)))
   537             case None => fail
   538           }
   539       }
   540     }
   541 
   542     def assign(id: Document_ID.Version, update: Assign_Update): (List[Command], State) =
   543     {
   544       val version = the_version(id)
   545 
   546       def upd(exec_id: Document_ID.Exec, st: Command.State)
   547           : Option[(Document_ID.Exec, Command.State)] =
   548         if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
   549 
   550       val (changed_commands, new_execs) =
   551         ((Nil: List[Command], execs) /: update) {
   552           case ((commands1, execs1), (command_id, exec)) =>
   553             val st = the_static_state(command_id)
   554             val command = st.command
   555             val commands2 = command :: commands1
   556             val execs2 =
   557               exec match {
   558                 case Nil => execs1
   559                 case eval_id :: print_ids =>
   560                   execs1 ++ upd(eval_id, st) ++
   561                     (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
   562               }
   563             (commands2, execs2)
   564         }
   565       val new_assignment = the_assignment(version).assign(update)
   566       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   567 
   568       (changed_commands, new_state)
   569     }
   570 
   571     def is_assigned(version: Version): Boolean =
   572       assignments.get(version.id) match {
   573         case Some(assgn) => assgn.is_finished
   574         case None => false
   575       }
   576 
   577     def is_stable(change: Change): Boolean =
   578       change.is_finished && is_assigned(change.version.get_finished)
   579 
   580     def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
   581     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   582     def tip_stable: Boolean = is_stable(history.tip)
   583     def tip_version: Version = history.tip.version.get_finished
   584 
   585     def continue_history(
   586       previous: Future[Version],
   587       edits: List[Edit_Text],
   588       version: Future[Version]): State =
   589     {
   590       val change = Change.make(previous, edits, version)
   591       copy(history = history + change)
   592     }
   593 
   594     def prune_history(retain: Int = 0): (List[Version], State) =
   595     {
   596       history.prune(is_stable, retain) match {
   597         case Some((dropped, history1)) =>
   598           val dropped_versions = dropped.map(change => change.version.get_finished)
   599           val state1 = copy(history = history1)
   600           (dropped_versions, state1)
   601         case None => fail
   602       }
   603     }
   604 
   605     def removed_versions(removed: List[Document_ID.Version]): State =
   606     {
   607       val versions1 = versions -- removed
   608       val assignments1 = assignments -- removed
   609       var blobs1 = Set.empty[SHA1.Digest]
   610       var commands1 = Map.empty[Document_ID.Command, Command.State]
   611       var execs1 = Map.empty[Document_ID.Exec, Command.State]
   612       for {
   613         (version_id, version) <- versions1.iterator
   614         command_execs = assignments1(version_id).command_execs
   615         (_, node) <- version.nodes.iterator
   616         command <- node.commands.iterator
   617       } {
   618         for (digest <- command.blobs_digests; if !blobs1.contains(digest))
   619           blobs1 += digest
   620 
   621         if (!commands1.isDefinedAt(command.id))
   622           commands.get(command.id).foreach(st => commands1 += (command.id -> st))
   623 
   624         for (exec_id <- command_execs.getOrElse(command.id, Nil)) {
   625           if (!execs1.isDefinedAt(exec_id))
   626             execs.get(exec_id).foreach(st => execs1 += (exec_id -> st))
   627         }
   628       }
   629       copy(
   630         versions = versions1,
   631         blobs = blobs1,
   632         commands = commands1,
   633         execs = execs1,
   634         commands_redirection = commands_redirection.restrict(commands1.isDefinedAt(_)),
   635         assignments = assignments1)
   636     }
   637 
   638     private def command_states_self(version: Version, command: Command)
   639       : List[(Document_ID.Generic, Command.State)] =
   640     {
   641       require(is_assigned(version))
   642       try {
   643         the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil)
   644           .map(id => id -> the_dynamic_state(id)) match {
   645             case Nil => fail
   646             case res => res
   647           }
   648       }
   649       catch {
   650         case _: State.Fail =>
   651           try { List(command.id -> the_static_state(command.id)) }
   652           catch { case _: State.Fail => List(command.id -> command.init_state) }
   653       }
   654     }
   655 
   656     def command_states(version: Version, command: Command): List[Command.State] =
   657     {
   658       val self = command_states_self(version, command)
   659       val others =
   660         if (commands_redirection.defined(command.id)) {
   661           (for {
   662             command_id <- commands_redirection.imm_succs(command.id).iterator
   663             (id, st) <- command_states_self(version, the_static_state(command_id).command)
   664             if !self.exists(_._1 == id)
   665           } yield (id, st)).toMap.valuesIterator.toList
   666         }
   667         else Nil
   668       self.map(_._2) ::: others.flatMap(_.redirect(command))
   669     }
   670 
   671     def command_results(version: Version, command: Command): Command.Results =
   672       Command.State.merge_results(command_states(version, command))
   673 
   674     def command_markup(version: Version, command: Command, index: Command.Markup_Index,
   675         range: Text.Range, elements: Markup.Elements): Markup_Tree =
   676       Command.State.merge_markup(command_states(version, command), index, range, elements)
   677 
   678     def markup_to_XML(version: Version, node: Node, elements: Markup.Elements): XML.Body =
   679       (for {
   680         command <- node.commands.iterator
   681         markup =
   682           command_markup(version, command, Command.Markup_Index.markup, command.range, elements)
   683         tree <- markup.to_XML(command.range, command.source, elements)
   684       } yield tree).toList
   685 
   686     // persistent user-view
   687     def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
   688       : Snapshot =
   689     {
   690       val stable = recent_stable
   691       val latest = history.tip
   692 
   693       // FIXME proper treatment of removed nodes
   694       val edits =
   695         (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
   696             (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
   697       lazy val reverse_edits = edits.reverse
   698 
   699       new Snapshot
   700       {
   701         /* global information */
   702 
   703         val state = State.this
   704         val version = stable.version.get_finished
   705         val is_outdated = !(pending_edits.isEmpty && latest == stable)
   706 
   707 
   708         /* local node content */
   709 
   710         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   711         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   712         def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
   713         def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
   714 
   715         val node_name = name
   716         val node = version.nodes(name)
   717 
   718         val load_commands: List[Command] =
   719           if (node_name.is_theory) Nil
   720           else version.nodes.load_commands(node_name)
   721 
   722         val is_loaded: Boolean = node_name.is_theory || !load_commands.isEmpty
   723 
   724         def eq_content(other: Snapshot): Boolean =
   725         {
   726           def eq_commands(commands: (Command, Command)): Boolean =
   727           {
   728             val states1 = state.command_states(version, commands._1)
   729             val states2 = other.state.command_states(other.version, commands._2)
   730             states1.length == states2.length &&
   731             (states1 zip states2).forall({ case (st1, st2) => st1 eq_content st2 })
   732           }
   733 
   734           !is_outdated && !other.is_outdated &&
   735           node.commands.size == other.node.commands.size &&
   736           (node.commands.iterator zip other.node.commands.iterator).forall(eq_commands) &&
   737           load_commands.length == other.load_commands.length &&
   738           (load_commands zip other.load_commands).forall(eq_commands)
   739         }
   740 
   741 
   742         /* cumulate markup */
   743 
   744         def cumulate[A](
   745           range: Text.Range,
   746           info: A,
   747           elements: Markup.Elements,
   748           result: List[Command.State] => (A, Text.Markup) => Option[A],
   749           status: Boolean = false): List[Text.Info[A]] =
   750         {
   751           val former_range = revert(range).inflate_singularity
   752           val (chunk_name, command_iterator) =
   753             load_commands match {
   754               case command :: _ => (Text.Chunk.File(node_name.node), Iterator((command, 0)))
   755               case _ => (Text.Chunk.Default, node.command_iterator(former_range))
   756             }
   757           val markup_index = Command.Markup_Index(status, chunk_name)
   758           (for {
   759             (command, command_start) <- command_iterator
   760             chunk <- command.chunks.get(chunk_name).iterator
   761             states = state.command_states(version, command)
   762             res = result(states)
   763             markup_range <- (former_range - command_start).try_restrict(chunk.range).iterator
   764             markup = Command.State.merge_markup(states, markup_index, markup_range, elements)
   765             Text.Info(r0, a) <- markup.cumulate[A](markup_range, info, elements,
   766               {
   767                 case (a, Text.Info(r0, b)) => res(a, Text.Info(convert(r0 + command_start), b))
   768               }).iterator
   769             r1 <- convert(r0 + command_start).try_restrict(range).iterator
   770           } yield Text.Info(r1, a)).toList
   771         }
   772 
   773         def select[A](
   774           range: Text.Range,
   775           elements: Markup.Elements,
   776           result: List[Command.State] => Text.Markup => Option[A],
   777           status: Boolean = false): List[Text.Info[A]] =
   778         {
   779           def result1(states: List[Command.State]): (Option[A], Text.Markup) => Option[Option[A]] =
   780           {
   781             val res = result(states)
   782             (_: Option[A], x: Text.Markup) =>
   783               res(x) match {
   784                 case None => None
   785                 case some => Some(some)
   786               }
   787           }
   788           for (Text.Info(r, Some(x)) <- cumulate(range, None, elements, result1 _, status))
   789             yield Text.Info(r, x)
   790         }
   791 
   792 
   793         /* output */
   794 
   795         override def toString: String =
   796           "Snapshot(node = " + node_name.node + ", version = " + version.id +
   797             (if (is_outdated) ", outdated" else "") + ")"
   798       }
   799     }
   800   }
   801 }
   802