src/Pure/PIDE/document.scala
author wenzelm
Mon Mar 13 21:37:35 2017 +0100 (2017-03-13 ago)
changeset 65214 a2ec0db555c7
parent 65199 6bd7081f8319
child 65221 6af51a47545b
permissions -rw-r--r--
clarified modules;
     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: 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     def get(name: Node.Name): Option[Blob] = blobs.get(name)
    62 
    63     def changed(name: Node.Name): Boolean =
    64       get(name) match {
    65         case Some(blob) => blob.changed
    66         case None => false
    67       }
    68 
    69     override def toString: String = blobs.mkString("Blobs(", ",", ")")
    70   }
    71 
    72 
    73   /* document nodes: theories and auxiliary files */
    74 
    75   type Edit[A, B] = (Node.Name, Node.Edit[A, B])
    76   type Edit_Text = Edit[Text.Edit, Text.Perspective]
    77   type Edit_Command = Edit[Command.Edit, Command.Perspective]
    78 
    79   object Node
    80   {
    81     /* header and name */
    82 
    83     sealed case class Header(
    84       imports: List[(Name, Position.T)] = Nil,
    85       keywords: Thy_Header.Keywords = Nil,
    86       abbrevs: Thy_Header.Abbrevs = Nil,
    87       errors: List[String] = Nil)
    88     {
    89       def error(msg: String): Header = copy(errors = errors ::: List(msg))
    90 
    91       def cat_errors(msg2: String): Header =
    92         copy(errors = errors.map(msg1 => Exn.cat_message(msg1, msg2)))
    93     }
    94 
    95     val no_header = Header()
    96     def bad_header(msg: String): Header = Header(errors = List(msg))
    97 
    98     object Name
    99     {
   100       val empty = Name("")
   101 
   102       object Ordering extends scala.math.Ordering[Name]
   103       {
   104         def compare(name1: Name, name2: Name): Int = name1.node compare name2.node
   105       }
   106     }
   107 
   108     sealed case class Name(node: String, master_dir: String = "", theory: String = "")
   109     {
   110       override def hashCode: Int = node.hashCode
   111       override def equals(that: Any): Boolean =
   112         that match {
   113           case other: Name => node == other.node
   114           case _ => false
   115         }
   116 
   117       def is_theory: Boolean = theory.nonEmpty
   118       override def toString: String = if (is_theory) theory else node
   119 
   120       def map(f: String => String): Name = copy(f(node), f(master_dir), theory)
   121     }
   122 
   123 
   124     /* node overlays */
   125 
   126     object Overlays
   127     {
   128       val empty = new Overlays(Multi_Map.empty)
   129     }
   130 
   131     final class Overlays private(rep: Multi_Map[Command, (String, List[String])])
   132     {
   133       def commands: Set[Command] = rep.keySet
   134       def is_empty: Boolean = rep.isEmpty
   135       def dest: List[(Command, (String, List[String]))] = rep.iterator.toList
   136       def insert(cmd: Command, fn: String, args: List[String]): Overlays =
   137         new Overlays(rep.insert(cmd, (fn, args)))
   138       def remove(cmd: Command, fn: String, args: List[String]): Overlays =
   139         new Overlays(rep.remove(cmd, (fn, args)))
   140 
   141       override def toString: String = rep.mkString("Node.Overlays(", ",", ")")
   142     }
   143 
   144 
   145     /* edits */
   146 
   147     sealed abstract class Edit[A, B]
   148     {
   149       def foreach(f: A => Unit)
   150       {
   151         this match {
   152           case Edits(es) => es.foreach(f)
   153           case _ =>
   154         }
   155       }
   156 
   157       def is_void: Boolean =
   158         this match {
   159           case Edits(Nil) => true
   160           case _ => false
   161         }
   162     }
   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 
   169 
   170     /* perspective */
   171 
   172     type Perspective_Text = Perspective[Text.Edit, Text.Perspective]
   173     type Perspective_Command = Perspective[Command.Edit, Command.Perspective]
   174 
   175     val no_perspective_text: Perspective_Text =
   176       Perspective(false, Text.Perspective.empty, Overlays.empty)
   177 
   178     val no_perspective_command: Perspective_Command =
   179       Perspective(false, Command.Perspective.empty, Overlays.empty)
   180 
   181     def is_no_perspective_text(perspective: Perspective_Text): Boolean =
   182       !perspective.required &&
   183       perspective.visible.is_empty &&
   184       perspective.overlays.is_empty
   185 
   186     def is_no_perspective_command(perspective: Perspective_Command): Boolean =
   187       !perspective.required &&
   188       perspective.visible.is_empty &&
   189       perspective.overlays.is_empty
   190 
   191 
   192     /* commands */
   193 
   194     object Commands
   195     {
   196       def apply(commands: Linear_Set[Command]): Commands = new Commands(commands)
   197       val empty: Commands = apply(Linear_Set.empty)
   198 
   199       def starts(commands: Iterator[Command], offset: Text.Offset = 0)
   200         : Iterator[(Command, Text.Offset)] =
   201       {
   202         var i = offset
   203         for (command <- commands) yield {
   204           val start = i
   205           i += command.length
   206           (command, start)
   207         }
   208       }
   209 
   210       private val block_size = 256
   211     }
   212 
   213     final class Commands private(val commands: Linear_Set[Command])
   214     {
   215       lazy val load_commands: List[Command] =
   216         commands.iterator.filter(cmd => cmd.blobs.nonEmpty).toList
   217 
   218       private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
   219       {
   220         val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
   221         var next_block = 0
   222         var last_stop = 0
   223         for ((command, start) <- Commands.starts(commands.iterator)) {
   224           last_stop = start + command.length
   225           while (last_stop + 1 > next_block) {
   226             blocks += (command -> start)
   227             next_block += Commands.block_size
   228           }
   229         }
   230         (blocks.toArray, Text.Range(0, last_stop))
   231       }
   232 
   233       private def full_range: Text.Range = full_index._2
   234 
   235       def iterator(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   236       {
   237         if (commands.nonEmpty && full_range.contains(i)) {
   238           val (cmd0, start0) = full_index._1(i / Commands.block_size)
   239           Node.Commands.starts(commands.iterator(cmd0), start0) dropWhile {
   240             case (cmd, start) => start + cmd.length <= i }
   241         }
   242         else Iterator.empty
   243       }
   244     }
   245 
   246     val empty: Node = new Node()
   247   }
   248 
   249   final class Node private(
   250     val get_blob: Option[Document.Blob] = None,
   251     val header: Node.Header = Node.no_header,
   252     val syntax: Option[Outer_Syntax] = None,
   253     val text_perspective: Text.Perspective = Text.Perspective.empty,
   254     val perspective: Node.Perspective_Command = Node.no_perspective_command,
   255     _commands: Node.Commands = Node.Commands.empty)
   256   {
   257     def is_empty: Boolean =
   258       get_blob.isEmpty &&
   259       header == Node.no_header &&
   260       text_perspective.is_empty &&
   261       Node.is_no_perspective_command(perspective) &&
   262       commands.isEmpty
   263 
   264     def has_header: Boolean = header != Node.no_header
   265 
   266     def commands: Linear_Set[Command] = _commands.commands
   267     def load_commands: List[Command] = _commands.load_commands
   268     def load_commands_changed(doc_blobs: Blobs): Boolean =
   269       load_commands.exists(_.blobs_changed(doc_blobs))
   270 
   271     def init_blob(blob: Blob): Node = new Node(get_blob = Some(blob.unchanged))
   272 
   273     def update_header(new_header: Node.Header): Node =
   274       new Node(get_blob, new_header, syntax, text_perspective, perspective, _commands)
   275 
   276     def update_syntax(new_syntax: Option[Outer_Syntax]): Node =
   277       new Node(get_blob, header, new_syntax, text_perspective, perspective, _commands)
   278 
   279     def update_perspective(
   280         new_text_perspective: Text.Perspective,
   281         new_perspective: Node.Perspective_Command): Node =
   282       new Node(get_blob, header, syntax, new_text_perspective, new_perspective, _commands)
   283 
   284     def edit_perspective: Node.Edit[Text.Edit, Text.Perspective] =
   285       Node.Perspective(perspective.required, text_perspective, perspective.overlays)
   286 
   287     def same_perspective(
   288         other_text_perspective: Text.Perspective,
   289         other_perspective: Node.Perspective_Command): Boolean =
   290       text_perspective == other_text_perspective &&
   291       perspective.required == other_perspective.required &&
   292       perspective.visible.same(other_perspective.visible) &&
   293       perspective.overlays == other_perspective.overlays
   294 
   295     def update_commands(new_commands: Linear_Set[Command]): Node =
   296       if (new_commands eq _commands.commands) this
   297       else
   298         new Node(get_blob, header, syntax, text_perspective, perspective,
   299           Node.Commands(new_commands))
   300 
   301     def command_iterator(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   302       _commands.iterator(i)
   303 
   304     def command_iterator(range: Text.Range): Iterator[(Command, Text.Offset)] =
   305       command_iterator(range.start) takeWhile { case (_, start) => start < range.stop }
   306 
   307     def command_start(cmd: Command): Option[Text.Offset] =
   308       Node.Commands.starts(commands.iterator).find(_._1 == cmd).map(_._2)
   309   }
   310 
   311 
   312   /* development graph */
   313 
   314   object Nodes
   315   {
   316     val empty: Nodes = new Nodes(Graph.empty(Node.Name.Ordering))
   317   }
   318 
   319   final class Nodes private(graph: Graph[Node.Name, Node])
   320   {
   321     def apply(name: Node.Name): Node =
   322       graph.default_node(name, Node.empty).get_node(name)
   323 
   324     def is_hidden(name: Node.Name): Boolean =
   325     {
   326       val graph1 = graph.default_node(name, Node.empty)
   327       graph1.is_maximal(name) && graph1.get_node(name).is_empty
   328     }
   329 
   330     def + (entry: (Node.Name, Node)): Nodes =
   331     {
   332       val (name, node) = entry
   333       val imports = node.header.imports.map(_._1)
   334       val graph1 =
   335         (graph.default_node(name, Node.empty) /: imports)((g, p) => g.default_node(p, Node.empty))
   336       val graph2 = (graph1 /: graph1.imm_preds(name))((g, dep) => g.del_edge(dep, name))
   337       val graph3 = (graph2 /: imports)((g, dep) => g.add_edge(dep, name))
   338       new Nodes(
   339         if (graph3.is_maximal(name) && node.is_empty) graph3.del_node(name)
   340         else graph3.map_node(name, _ => node)
   341       )
   342     }
   343 
   344     def iterator: Iterator[(Node.Name, Node)] =
   345       graph.iterator.map({ case (name, (node, _)) => (name, node) })
   346 
   347     def commands_loading(file_name: Node.Name): List[Command] =
   348       (for {
   349         (_, node) <- iterator
   350         cmd <- node.load_commands.iterator
   351         name <- cmd.blobs_names.iterator
   352         if name == file_name
   353       } yield cmd).toList
   354 
   355     def descendants(names: List[Node.Name]): List[Node.Name] = graph.all_succs(names)
   356     def topological_order: List[Node.Name] = graph.topological_order
   357 
   358     override def toString: String = topological_order.mkString("Nodes(", ",", ")")
   359   }
   360 
   361 
   362 
   363   /** versioning **/
   364 
   365   /* particular document versions */
   366 
   367   object Version
   368   {
   369     val init: Version = new Version()
   370     def make(nodes: Nodes): Version = new Version(Document_ID.make(), nodes)
   371   }
   372 
   373   final class Version private(
   374     val id: Document_ID.Version = Document_ID.none,
   375     val nodes: Nodes = Nodes.empty)
   376   {
   377     override def toString: String = "Version(" + id + ")"
   378   }
   379 
   380 
   381   /* changes of plain text, eventually resulting in document edits */
   382 
   383   object Change
   384   {
   385     val init: Change = new Change()
   386 
   387     def make(previous: Future[Version], edits: List[Edit_Text], version: Future[Version]): Change =
   388       new Change(Some(previous), edits.reverse, version)
   389   }
   390 
   391   final class Change private(
   392     val previous: Option[Future[Version]] = Some(Future.value(Version.init)),
   393     val rev_edits: List[Edit_Text] = Nil,
   394     val version: Future[Version] = Future.value(Version.init))
   395   {
   396     def is_finished: Boolean =
   397       (previous match { case None => true case Some(future) => future.is_finished }) &&
   398       version.is_finished
   399 
   400     def truncate: Change = new Change(None, Nil, version)
   401   }
   402 
   403 
   404   /* history navigation */
   405 
   406   object History
   407   {
   408     val init: History = new History()
   409   }
   410 
   411   final class History private(
   412     val undo_list: List[Change] = List(Change.init))  // non-empty list
   413   {
   414     def tip: Change = undo_list.head
   415     def + (change: Change): History = new History(change :: undo_list)
   416 
   417     def prune(check: Change => Boolean, retain: Int): Option[(List[Change], History)] =
   418     {
   419       val n = undo_list.iterator.zipWithIndex.find(p => check(p._1)).get._2 + 1
   420       val (retained, dropped) = undo_list.splitAt(n max retain)
   421 
   422       retained.splitAt(retained.length - 1) match {
   423         case (prefix, List(last)) => Some(dropped, new History(prefix ::: List(last.truncate)))
   424         case _ => None
   425       }
   426     }
   427   }
   428 
   429 
   430   /* snapshot */
   431 
   432   object Snapshot
   433   {
   434     val init = State.init.snapshot()
   435   }
   436 
   437   abstract class Snapshot
   438   {
   439     def state: State
   440     def version: Version
   441     def is_outdated: Boolean
   442 
   443     def convert(i: Text.Offset): Text.Offset
   444     def revert(i: Text.Offset): Text.Offset
   445     def convert(range: Text.Range): Text.Range
   446     def revert(range: Text.Range): Text.Range
   447 
   448     def node_name: Node.Name
   449     def node: Node
   450     def commands_loading: List[Command]
   451     def commands_loading_ranges(pred: Node.Name => Boolean): List[Text.Range]
   452     def command_results(command: Command): Command.Results
   453     def current_command(other_node_name: Node.Name, offset: Text.Offset): Option[Command]
   454 
   455     def find_command(id: Document_ID.Generic): Option[(Node, Command)]
   456     def find_command_position(id: Document_ID.Generic, offset: Symbol.Offset)
   457       : Option[Line.Node_Position]
   458 
   459     def cumulate[A](
   460       range: Text.Range,
   461       info: A,
   462       elements: Markup.Elements,
   463       result: List[Command.State] => (A, Text.Markup) => Option[A],
   464       status: Boolean = false): List[Text.Info[A]]
   465 
   466     def select[A](
   467       range: Text.Range,
   468       elements: Markup.Elements,
   469       result: List[Command.State] => Text.Markup => Option[A],
   470       status: Boolean = false): List[Text.Info[A]]
   471   }
   472 
   473 
   474   /* model */
   475 
   476   trait Model
   477   {
   478     def session: Session
   479     def is_stable: Boolean
   480     def snapshot(): Snapshot
   481 
   482     def node_name: Document.Node.Name
   483     def is_theory: Boolean = node_name.is_theory
   484     override def toString: String = node_name.toString
   485 
   486     def node_required: Boolean
   487     def get_blob: Option[Document.Blob]
   488 
   489     def node_edits(
   490       node_header: Node.Header,
   491       text_edits: List[Text.Edit],
   492       perspective: Node.Perspective_Text): List[Edit_Text] =
   493     {
   494       val edits: List[Node.Edit[Text.Edit, Text.Perspective]] =
   495         get_blob match {
   496           case None =>
   497             List(
   498               Document.Node.Deps(
   499                 if (session.resources.base.loaded_theories(node_name.theory))
   500                   node_header.error("Cannot update finished theory " + quote(node_name.theory))
   501                 else node_header),
   502               Document.Node.Edits(text_edits), perspective)
   503           case Some(blob) =>
   504             List(Document.Node.Blob(blob), Document.Node.Edits(text_edits))
   505         }
   506       edits.flatMap(edit => if (edit.is_void) None else Some(node_name -> edit))
   507     }
   508   }
   509 
   510 
   511   /** global state -- document structure, execution process, editing history **/
   512 
   513   type Assign_Update =
   514     List[(Document_ID.Command, List[Document_ID.Exec])]  // update of exec state assignment
   515 
   516   object State
   517   {
   518     class Fail(state: State) extends Exception
   519 
   520     object Assignment
   521     {
   522       val init: Assignment = new Assignment()
   523     }
   524 
   525     final class Assignment private(
   526       val command_execs: Map[Document_ID.Command, List[Document_ID.Exec]] = Map.empty,
   527       val is_finished: Boolean = false)
   528     {
   529       def check_finished: Assignment = { require(is_finished); this }
   530       def unfinished: Assignment = new Assignment(command_execs, false)
   531 
   532       def assign(update: Assign_Update): Assignment =
   533       {
   534         require(!is_finished)
   535         val command_execs1 =
   536           (command_execs /: update) {
   537             case (res, (command_id, exec_ids)) =>
   538               if (exec_ids.isEmpty) res - command_id
   539               else res + (command_id -> exec_ids)
   540           }
   541         new Assignment(command_execs1, true)
   542       }
   543     }
   544 
   545     val init: State =
   546       State().define_version(Version.init, Assignment.init).assign(Version.init.id, Nil)._2
   547   }
   548 
   549   final case class State private(
   550     /*reachable versions*/
   551     versions: Map[Document_ID.Version, Version] = Map.empty,
   552     /*inlined auxiliary files*/
   553     blobs: Set[SHA1.Digest] = Set.empty,
   554     /*static markup from define_command*/
   555     commands: Map[Document_ID.Command, Command.State] = Map.empty,
   556     /*dynamic markup from execution*/
   557     execs: Map[Document_ID.Exec, Command.State] = Map.empty,
   558     /*command-exec assignment for each version*/
   559     assignments: Map[Document_ID.Version, State.Assignment] = Map.empty,
   560     /*commands with markup produced by other commands (imm_succs)*/
   561     commands_redirection: Graph[Document_ID.Command, Unit] = Graph.long,
   562     /*explicit (linear) history*/
   563     history: History = History.init,
   564     /*intermediate state between remove_versions/removed_versions*/
   565     removing_versions: Boolean = false)
   566   {
   567     private def fail[A]: A = throw new State.Fail(this)
   568 
   569     def define_version(version: Version, assignment: State.Assignment): State =
   570     {
   571       val id = version.id
   572       copy(versions = versions + (id -> version),
   573         assignments = assignments + (id -> assignment.unfinished))
   574     }
   575 
   576     def define_blob(digest: SHA1.Digest): State = copy(blobs = blobs + digest)
   577     def defined_blob(digest: SHA1.Digest): Boolean = blobs.contains(digest)
   578 
   579     def define_command(command: Command): State =
   580     {
   581       val id = command.id
   582       copy(commands = commands + (id -> command.init_state))
   583     }
   584 
   585     def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
   586 
   587     def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
   588     def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
   589     def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
   590     def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
   591 
   592     private def self_id(st: Command.State)(id: Document_ID.Generic): Boolean =
   593       id == st.command.id ||
   594       (execs.get(id) match { case Some(st1) => st1.command.id == st.command.id case None => false })
   595 
   596     private def other_id(id: Document_ID.Generic)
   597       : Option[(Symbol.Text_Chunk.Id, Symbol.Text_Chunk)] =
   598       (execs.get(id) orElse commands.get(id)).map(st =>
   599         ((Symbol.Text_Chunk.Id(st.command.id), st.command.chunk)))
   600 
   601     private def redirection(st: Command.State): Graph[Document_ID.Command, Unit] =
   602       (commands_redirection /: st.markups.redirection_iterator)({ case (graph, id) =>
   603         graph.default_node(id, ()).default_node(st.command.id, ()).add_edge(id, st.command.id) })
   604 
   605     def accumulate(id: Document_ID.Generic, message: XML.Elem): (Command.State, State) =
   606     {
   607       execs.get(id) match {
   608         case Some(st) =>
   609           val new_st = st.accumulate(self_id(st), other_id _, message)
   610           val execs1 = execs + (id -> new_st)
   611           (new_st, copy(execs = execs1, commands_redirection = redirection(new_st)))
   612         case None =>
   613           commands.get(id) match {
   614             case Some(st) =>
   615               val new_st = st.accumulate(self_id(st), other_id _, message)
   616               val commands1 = commands + (id -> new_st)
   617               (new_st, copy(commands = commands1, commands_redirection = redirection(new_st)))
   618             case None => fail
   619           }
   620       }
   621     }
   622 
   623     def assign(id: Document_ID.Version, update: Assign_Update): (List[Command], State) =
   624     {
   625       val version = the_version(id)
   626 
   627       def upd(exec_id: Document_ID.Exec, st: Command.State)
   628           : Option[(Document_ID.Exec, Command.State)] =
   629         if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
   630 
   631       val (changed_commands, new_execs) =
   632         ((Nil: List[Command], execs) /: update) {
   633           case ((commands1, execs1), (command_id, exec)) =>
   634             val st = the_static_state(command_id)
   635             val command = st.command
   636             val commands2 = command :: commands1
   637             val execs2 =
   638               exec match {
   639                 case Nil => execs1
   640                 case eval_id :: print_ids =>
   641                   execs1 ++ upd(eval_id, st) ++
   642                     (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
   643               }
   644             (commands2, execs2)
   645         }
   646       val new_assignment = the_assignment(version).assign(update)
   647       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   648 
   649       (changed_commands, new_state)
   650     }
   651 
   652     def is_assigned(version: Version): Boolean =
   653       assignments.get(version.id) match {
   654         case Some(assgn) => assgn.is_finished
   655         case None => false
   656       }
   657 
   658     def is_stable(change: Change): Boolean =
   659       change.is_finished && is_assigned(change.version.get_finished)
   660 
   661     def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
   662     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   663     def stable_tip_version: Option[Version] =
   664       if (is_stable(history.tip)) Some(history.tip.version.get_finished) else None
   665 
   666     def continue_history(
   667       previous: Future[Version],
   668       edits: List[Edit_Text],
   669       version: Future[Version]): State =
   670     {
   671       val change = Change.make(previous, edits, version)
   672       copy(history = history + change)
   673     }
   674 
   675     def remove_versions(retain: Int = 0): (List[Version], State) =
   676     {
   677       history.prune(is_stable, retain) match {
   678         case Some((dropped, history1)) =>
   679           val old_versions = dropped.map(change => change.version.get_finished)
   680           val removing = old_versions.nonEmpty
   681           val state1 = copy(history = history1, removing_versions = removing)
   682           (old_versions, state1)
   683         case None => fail
   684       }
   685     }
   686 
   687     def removed_versions(removed: List[Document_ID.Version]): State =
   688     {
   689       val versions1 = versions -- removed
   690       val assignments1 = assignments -- removed
   691       var blobs1 = Set.empty[SHA1.Digest]
   692       var commands1 = Map.empty[Document_ID.Command, Command.State]
   693       var execs1 = Map.empty[Document_ID.Exec, Command.State]
   694       for {
   695         (version_id, version) <- versions1.iterator
   696         command_execs = assignments1(version_id).command_execs
   697         (_, node) <- version.nodes.iterator
   698         command <- node.commands.iterator
   699       } {
   700         for ((_, digest) <- command.blobs_defined; if !blobs1.contains(digest))
   701           blobs1 += digest
   702 
   703         if (!commands1.isDefinedAt(command.id))
   704           commands.get(command.id).foreach(st => commands1 += (command.id -> st))
   705 
   706         for (exec_id <- command_execs.getOrElse(command.id, Nil)) {
   707           if (!execs1.isDefinedAt(exec_id))
   708             execs.get(exec_id).foreach(st => execs1 += (exec_id -> st))
   709         }
   710       }
   711       copy(
   712         versions = versions1,
   713         blobs = blobs1,
   714         commands = commands1,
   715         execs = execs1,
   716         commands_redirection = commands_redirection.restrict(commands1.isDefinedAt(_)),
   717         assignments = assignments1,
   718         removing_versions = false)
   719     }
   720 
   721     private def command_states_self(version: Version, command: Command)
   722       : List[(Document_ID.Generic, Command.State)] =
   723     {
   724       require(is_assigned(version))
   725       try {
   726         the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil)
   727           .map(id => id -> the_dynamic_state(id)) match {
   728             case Nil => fail
   729             case res => res
   730           }
   731       }
   732       catch {
   733         case _: State.Fail =>
   734           try { List(command.id -> the_static_state(command.id)) }
   735           catch { case _: State.Fail => List(command.id -> command.init_state) }
   736       }
   737     }
   738 
   739     def command_states(version: Version, command: Command): List[Command.State] =
   740     {
   741       val self = command_states_self(version, command)
   742       val others =
   743         if (commands_redirection.defined(command.id)) {
   744           (for {
   745             command_id <- commands_redirection.imm_succs(command.id).iterator
   746             (id, st) <- command_states_self(version, the_static_state(command_id).command)
   747             if !self.exists(_._1 == id)
   748           } yield (id, st)).toMap.valuesIterator.toList
   749         }
   750         else Nil
   751       self.map(_._2) ::: others.flatMap(_.redirect(command))
   752     }
   753 
   754     def command_results(version: Version, command: Command): Command.Results =
   755       Command.State.merge_results(command_states(version, command))
   756 
   757     def command_markup(version: Version, command: Command, index: Command.Markup_Index,
   758         range: Text.Range, elements: Markup.Elements): Markup_Tree =
   759       Command.State.merge_markup(command_states(version, command), index, range, elements)
   760 
   761     def markup_to_XML(version: Version, node: Node, elements: Markup.Elements): XML.Body =
   762       (for {
   763         command <- node.commands.iterator
   764         markup =
   765           command_markup(version, command, Command.Markup_Index.markup, command.range, elements)
   766         tree <- markup.to_XML(command.range, command.source, elements)
   767       } yield tree).toList
   768 
   769     // persistent user-view
   770     def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
   771       : Snapshot =
   772     {
   773       val stable = recent_stable
   774       val latest = history.tip
   775 
   776 
   777       /* pending edits and unstable changes */
   778 
   779       val rev_pending_changes =
   780         for {
   781           change <- history.undo_list.takeWhile(_ != stable)
   782           (a, edits) <- change.rev_edits
   783           if a == name
   784         } yield edits
   785 
   786       val edits =
   787         (pending_edits /: rev_pending_changes)({
   788           case (edits, Node.Edits(es)) => es ::: edits
   789           case (edits, _) => edits
   790         })
   791       lazy val reverse_edits = edits.reverse
   792 
   793       new Snapshot
   794       {
   795         /* global information */
   796 
   797         val state: State = State.this
   798         val version: Version = stable.version.get_finished
   799         val is_outdated: Boolean = pending_edits.nonEmpty || latest != stable
   800 
   801 
   802         /* local node content */
   803 
   804         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
   805         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
   806 
   807         def convert(range: Text.Range) = range.map(convert(_))
   808         def revert(range: Text.Range) = range.map(revert(_))
   809 
   810         val node_name: Node.Name = name
   811         val node: Node = version.nodes(name)
   812 
   813         val commands_loading: List[Command] =
   814           if (node_name.is_theory) Nil
   815           else version.nodes.commands_loading(node_name)
   816 
   817         def commands_loading_ranges(pred: Node.Name => Boolean): List[Text.Range] =
   818           (for {
   819             cmd <- node.load_commands.iterator
   820             blob_name <- cmd.blobs_names.iterator
   821             if pred(blob_name)
   822             start <- node.command_start(cmd)
   823           } yield convert(cmd.proper_range + start)).toList
   824 
   825         def command_results(command: Command): Command.Results =
   826           state.command_results(version, command)
   827 
   828         def current_command(other_node_name: Node.Name, offset: Text.Offset): Option[Command] =
   829           if (other_node_name.is_theory) {
   830             val other_node = version.nodes(other_node_name)
   831             val iterator = other_node.command_iterator(revert(offset) max 0)
   832             if (iterator.hasNext) {
   833               val (command0, _) = iterator.next
   834               other_node.commands.reverse.iterator(command0).find(command => !command.is_ignored)
   835             }
   836             else other_node.commands.reverse.iterator.find(command => !command.is_ignored)
   837           }
   838           else version.nodes.commands_loading(other_node_name).headOption
   839 
   840 
   841         /* find command */
   842 
   843         def find_command(id: Document_ID.Generic): Option[(Node, Command)] =
   844           state.commands.get(id) orElse state.execs.get(id) match {
   845             case None => None
   846             case Some(st) =>
   847               val command = st.command
   848               val node = version.nodes(command.node_name)
   849               if (node.commands.contains(command)) Some((node, command)) else None
   850           }
   851 
   852         def find_command_position(id: Document_ID.Generic, offset: Symbol.Offset)
   853             : Option[Line.Node_Position] =
   854           for ((node, command) <- find_command(id))
   855           yield {
   856             val name = command.node_name.node
   857             val sources_iterator =
   858               node.commands.iterator.takeWhile(_ != command).map(_.source) ++
   859                 (if (offset == 0) Iterator.empty
   860                  else Iterator.single(command.source(Text.Range(0, command.chunk.decode(offset)))))
   861             val pos = (Line.Position.zero /: sources_iterator)(_.advance(_))
   862             Line.Node_Position(name, pos)
   863           }
   864 
   865 
   866         /* cumulate markup */
   867 
   868         def cumulate[A](
   869           range: Text.Range,
   870           info: A,
   871           elements: Markup.Elements,
   872           result: List[Command.State] => (A, Text.Markup) => Option[A],
   873           status: Boolean = false): List[Text.Info[A]] =
   874         {
   875           val former_range = revert(range).inflate_singularity
   876           val (chunk_name, command_iterator) =
   877             commands_loading.headOption match {
   878               case None => (Symbol.Text_Chunk.Default, node.command_iterator(former_range))
   879               case Some(command) => (Symbol.Text_Chunk.File(node_name.node), Iterator((command, 0)))
   880             }
   881           val markup_index = Command.Markup_Index(status, chunk_name)
   882           (for {
   883             (command, command_start) <- command_iterator
   884             chunk <- command.chunks.get(chunk_name).iterator
   885             states = state.command_states(version, command)
   886             res = result(states)
   887             markup_range <- (former_range - command_start).try_restrict(chunk.range).iterator
   888             markup = Command.State.merge_markup(states, markup_index, markup_range, elements)
   889             Text.Info(r0, a) <- markup.cumulate[A](markup_range, info, elements,
   890               {
   891                 case (a, Text.Info(r0, b)) => res(a, Text.Info(convert(r0 + command_start), b))
   892               }).iterator
   893             r1 <- convert(r0 + command_start).try_restrict(range).iterator
   894           } yield Text.Info(r1, a)).toList
   895         }
   896 
   897         def select[A](
   898           range: Text.Range,
   899           elements: Markup.Elements,
   900           result: List[Command.State] => Text.Markup => Option[A],
   901           status: Boolean = false): List[Text.Info[A]] =
   902         {
   903           def result1(states: List[Command.State]): (Option[A], Text.Markup) => Option[Option[A]] =
   904           {
   905             val res = result(states)
   906             (_: Option[A], x: Text.Markup) =>
   907               res(x) match {
   908                 case None => None
   909                 case some => Some(some)
   910               }
   911           }
   912           for (Text.Info(r, Some(x)) <- cumulate(range, None, elements, result1 _, status))
   913             yield Text.Info(r, x)
   914         }
   915 
   916 
   917         /* output */
   918 
   919         override def toString: String =
   920           "Snapshot(node = " + node_name.node + ", version = " + version.id +
   921             (if (is_outdated) ", outdated" else "") + ")"
   922       }
   923     }
   924   }
   925 }