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