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