src/Pure/PIDE/document.scala
author wenzelm
Sun May 19 18:10:45 2019 +0200 (5 months ago)
changeset 70284 3e17c3a5fd39
parent 69633 3d91a7a58113
child 70539 30b3c58a1933
permissions -rw-r--r--
more thorough assignment, e.g. when "purge" removes commands that were not assigned;
     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, source: String, 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 append_errors(msgs: List[String]): Header =
    90         copy(errors = errors ::: msgs)
    91 
    92       def cat_errors(msg2: String): Header =
    93         copy(errors = errors.map(msg1 => Exn.cat_message(msg1, msg2)))
    94     }
    95 
    96     val no_header = Header()
    97     def bad_header(msg: String): Header = Header(errors = List(msg))
    98 
    99     object Name
   100     {
   101       val empty = Name("")
   102 
   103       def loaded_theory(theory: String): Name = Name(theory, "", theory)
   104 
   105       object Ordering extends scala.math.Ordering[Name]
   106       {
   107         def compare(name1: Name, name2: Name): Int = name1.node compare name2.node
   108       }
   109     }
   110 
   111     sealed case class Name(node: String, master_dir: String = "", theory: String = "")
   112     {
   113       override def hashCode: Int = node.hashCode
   114       override def equals(that: Any): Boolean =
   115         that match {
   116           case other: Name => node == other.node
   117           case _ => false
   118         }
   119 
   120       def path: Path = Path.explode(File.standard_path(node))
   121 
   122       def is_theory: Boolean = theory.nonEmpty
   123 
   124       def theory_base_name: String = Long_Name.base_name(theory)
   125 
   126       override def toString: String = if (is_theory) theory else node
   127 
   128       def map(f: String => String): Name = copy(f(node), f(master_dir), theory)
   129       def map_theory(f: String => String): Name = copy(node, master_dir, f(theory))
   130 
   131       def json: JSON.Object.T =
   132         JSON.Object("node_name" -> node, "theory_name" -> theory)
   133     }
   134 
   135     sealed case class Entry(name: Node.Name, header: Node.Header)
   136     {
   137       def map(f: String => String): Entry = copy(name = name.map(f))
   138 
   139       override def toString: String = name.toString
   140     }
   141 
   142 
   143     /* node overlays */
   144 
   145     object Overlays
   146     {
   147       val empty = new Overlays(Multi_Map.empty)
   148     }
   149 
   150     final class Overlays private(rep: Multi_Map[Command, (String, List[String])])
   151     {
   152       def commands: Set[Command] = rep.keySet
   153       def is_empty: Boolean = rep.isEmpty
   154       def dest: List[(Command, (String, List[String]))] = rep.iterator.toList
   155       def insert(cmd: Command, fn: String, args: List[String]): Overlays =
   156         new Overlays(rep.insert(cmd, (fn, args)))
   157       def remove(cmd: Command, fn: String, args: List[String]): Overlays =
   158         new Overlays(rep.remove(cmd, (fn, args)))
   159 
   160       override def toString: String = rep.mkString("Node.Overlays(", ",", ")")
   161     }
   162 
   163 
   164     /* edits */
   165 
   166     sealed abstract class Edit[A, B]
   167     {
   168       def foreach(f: A => Unit)
   169       {
   170         this match {
   171           case Edits(es) => es.foreach(f)
   172           case _ =>
   173         }
   174       }
   175 
   176       def is_void: Boolean =
   177         this match {
   178           case Edits(Nil) => true
   179           case _ => false
   180         }
   181     }
   182     case class Blob[A, B](blob: Document.Blob) extends Edit[A, B]
   183 
   184     case class Edits[A, B](edits: List[A]) extends Edit[A, B]
   185     case class Deps[A, B](header: Header) extends Edit[A, B]
   186     case class Perspective[A, B](required: Boolean, visible: B, overlays: Overlays) extends Edit[A, B]
   187 
   188 
   189     /* perspective */
   190 
   191     type Perspective_Text = Perspective[Text.Edit, Text.Perspective]
   192     type Perspective_Command = Perspective[Command.Edit, Command.Perspective]
   193 
   194     val no_perspective_text: Perspective_Text =
   195       Perspective(false, Text.Perspective.empty, Overlays.empty)
   196 
   197     val no_perspective_command: Perspective_Command =
   198       Perspective(false, Command.Perspective.empty, Overlays.empty)
   199 
   200     def is_no_perspective_text(perspective: Perspective_Text): Boolean =
   201       !perspective.required &&
   202       perspective.visible.is_empty &&
   203       perspective.overlays.is_empty
   204 
   205     def is_no_perspective_command(perspective: Perspective_Command): Boolean =
   206       !perspective.required &&
   207       perspective.visible.is_empty &&
   208       perspective.overlays.is_empty
   209 
   210 
   211     /* commands */
   212 
   213     object Commands
   214     {
   215       def apply(commands: Linear_Set[Command]): Commands = new Commands(commands)
   216       val empty: Commands = apply(Linear_Set.empty)
   217 
   218       def starts(commands: Iterator[Command], offset: Text.Offset = 0)
   219         : Iterator[(Command, Text.Offset)] =
   220       {
   221         var i = offset
   222         for (command <- commands) yield {
   223           val start = i
   224           i += command.length
   225           (command, start)
   226         }
   227       }
   228 
   229       def starts_pos(commands: Iterator[Command], pos: Token.Pos = Token.Pos.start)
   230         : Iterator[(Command, Token.Pos)] =
   231       {
   232         var p = pos
   233         for (command <- commands) yield {
   234           val start = p
   235           p = (p /: command.span.content)(_.advance(_))
   236           (command, start)
   237         }
   238       }
   239 
   240       private val block_size = 256
   241     }
   242 
   243     final class Commands private(val commands: Linear_Set[Command])
   244     {
   245       lazy val load_commands: List[Command] =
   246         commands.iterator.filter(cmd => cmd.blobs.nonEmpty).toList
   247 
   248       private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
   249       {
   250         val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
   251         var next_block = 0
   252         var last_stop = 0
   253         for ((command, start) <- Commands.starts(commands.iterator)) {
   254           last_stop = start + command.length
   255           while (last_stop + 1 > next_block) {
   256             blocks += (command -> start)
   257             next_block += Commands.block_size
   258           }
   259         }
   260         (blocks.toArray, Text.Range(0, last_stop))
   261       }
   262 
   263       private def full_range: Text.Range = full_index._2
   264 
   265       def iterator(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   266       {
   267         if (commands.nonEmpty && full_range.contains(i)) {
   268           val (cmd0, start0) = full_index._1(i / Commands.block_size)
   269           Node.Commands.starts(commands.iterator(cmd0), start0) dropWhile {
   270             case (cmd, start) => start + cmd.length <= i }
   271         }
   272         else Iterator.empty
   273       }
   274     }
   275 
   276     val empty: Node = new Node()
   277   }
   278 
   279   final class Node private(
   280     val get_blob: Option[Document.Blob] = None,
   281     val header: Node.Header = Node.no_header,
   282     val syntax: Option[Outer_Syntax] = None,
   283     val text_perspective: Text.Perspective = Text.Perspective.empty,
   284     val perspective: Node.Perspective_Command = Node.no_perspective_command,
   285     _commands: Node.Commands = Node.Commands.empty)
   286   {
   287     def is_empty: Boolean =
   288       get_blob.isEmpty &&
   289       header == Node.no_header &&
   290       text_perspective.is_empty &&
   291       Node.is_no_perspective_command(perspective) &&
   292       commands.isEmpty
   293 
   294     def has_header: Boolean = header != Node.no_header
   295 
   296     override def toString: String =
   297       if (is_empty) "empty"
   298       else if (get_blob.isDefined) "blob"
   299       else "node"
   300 
   301     def commands: Linear_Set[Command] = _commands.commands
   302     def load_commands: List[Command] = _commands.load_commands
   303     def load_commands_changed(doc_blobs: Blobs): Boolean =
   304       load_commands.exists(_.blobs_changed(doc_blobs))
   305 
   306     def init_blob(blob: Blob): Node = new Node(get_blob = Some(blob.unchanged))
   307 
   308     def update_header(new_header: Node.Header): Node =
   309       new Node(get_blob, new_header, syntax, text_perspective, perspective, _commands)
   310 
   311     def update_syntax(new_syntax: Option[Outer_Syntax]): Node =
   312       new Node(get_blob, header, new_syntax, text_perspective, perspective, _commands)
   313 
   314     def update_perspective(
   315         new_text_perspective: Text.Perspective,
   316         new_perspective: Node.Perspective_Command): Node =
   317       new Node(get_blob, header, syntax, new_text_perspective, new_perspective, _commands)
   318 
   319     def edit_perspective: Node.Edit[Text.Edit, Text.Perspective] =
   320       Node.Perspective(perspective.required, text_perspective, perspective.overlays)
   321 
   322     def same_perspective(
   323         other_text_perspective: Text.Perspective,
   324         other_perspective: Node.Perspective_Command): Boolean =
   325       text_perspective == other_text_perspective &&
   326       perspective.required == other_perspective.required &&
   327       perspective.visible.same(other_perspective.visible) &&
   328       perspective.overlays == other_perspective.overlays
   329 
   330     def update_commands(new_commands: Linear_Set[Command]): Node =
   331       if (new_commands eq _commands.commands) this
   332       else
   333         new Node(get_blob, header, syntax, text_perspective, perspective,
   334           Node.Commands(new_commands))
   335 
   336     def command_iterator(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
   337       _commands.iterator(i)
   338 
   339     def command_iterator(range: Text.Range): Iterator[(Command, Text.Offset)] =
   340       command_iterator(range.start) takeWhile { case (_, start) => start < range.stop }
   341 
   342     def command_start(cmd: Command): Option[Text.Offset] =
   343       Node.Commands.starts(commands.iterator).find(_._1 == cmd).map(_._2)
   344 
   345     def source: String =
   346       get_blob match {
   347         case Some(blob) => blob.source
   348         case None => command_iterator(0).map({ case (cmd, _) => cmd.source }).mkString
   349       }
   350   }
   351 
   352 
   353   /* development graph */
   354 
   355   object Nodes
   356   {
   357     val empty: Nodes = new Nodes(Graph.empty(Node.Name.Ordering))
   358   }
   359 
   360   final class Nodes private(graph: Graph[Node.Name, Node])
   361   {
   362     def apply(name: Node.Name): Node =
   363       graph.default_node(name, Node.empty).get_node(name)
   364 
   365     def is_suppressed(name: Node.Name): Boolean =
   366     {
   367       val graph1 = graph.default_node(name, Node.empty)
   368       graph1.is_maximal(name) && graph1.get_node(name).is_empty
   369     }
   370 
   371     def purge_suppressed: Option[Nodes] =
   372       graph.keys_iterator.filter(is_suppressed(_)).toList match {
   373         case Nil => None
   374         case del => Some(new Nodes((graph /: del)(_.del_node(_))))
   375       }
   376 
   377     def + (entry: (Node.Name, Node)): Nodes =
   378     {
   379       val (name, node) = entry
   380       val imports = node.header.imports.map(_._1)
   381       val graph1 =
   382         (graph.default_node(name, Node.empty) /: imports)((g, p) => g.default_node(p, Node.empty))
   383       val graph2 = (graph1 /: graph1.imm_preds(name))((g, dep) => g.del_edge(dep, name))
   384       val graph3 = (graph2 /: imports)((g, dep) => g.add_edge(dep, name))
   385       new Nodes(graph3.map_node(name, _ => node))
   386     }
   387 
   388     def domain: Set[Node.Name] = graph.domain
   389 
   390     def iterator: Iterator[(Node.Name, Node)] =
   391       graph.iterator.map({ case (name, (node, _)) => (name, node) })
   392 
   393     def commands_loading(file_name: Node.Name): List[Command] =
   394       (for {
   395         (_, node) <- iterator
   396         cmd <- node.load_commands.iterator
   397         name <- cmd.blobs_names.iterator
   398         if name == file_name
   399       } yield cmd).toList
   400 
   401     def descendants(names: List[Node.Name]): List[Node.Name] = graph.all_succs(names)
   402     def topological_order: List[Node.Name] = graph.topological_order
   403 
   404     override def toString: String = topological_order.mkString("Nodes(", ",", ")")
   405   }
   406 
   407 
   408 
   409   /** versioning **/
   410 
   411   /* particular document versions */
   412 
   413   object Version
   414   {
   415     val init: Version = new Version()
   416     def make(nodes: Nodes): Version = new Version(Document_ID.make(), nodes)
   417 
   418     def purge_future(versions: Map[Document_ID.Version, Version], future: Future[Version])
   419       : Future[Version] =
   420     {
   421       if (future.is_finished) {
   422         val version = future.join
   423         versions.get(version.id) match {
   424           case Some(version1) if !(version eq version1) => Future.value(version1)
   425           case _ => future
   426         }
   427       }
   428       else future
   429     }
   430 
   431     def purge_suppressed(
   432       versions: Map[Document_ID.Version, Version]): Map[Document_ID.Version, Version] =
   433     {
   434       (versions /:
   435         (for ((id, v) <- versions.iterator; v1 <- v.purge_suppressed) yield (id, v1)))(_ + _)
   436     }
   437   }
   438 
   439   final class Version private(
   440     val id: Document_ID.Version = Document_ID.none,
   441     val nodes: Nodes = Nodes.empty)
   442   {
   443     override def toString: String = "Version(" + id + ")"
   444 
   445     def purge_suppressed: Option[Version] =
   446       nodes.purge_suppressed.map(new Version(id, _))
   447   }
   448 
   449 
   450   /* changes of plain text, eventually resulting in document edits */
   451 
   452   object Change
   453   {
   454     val init: Change = new Change()
   455 
   456     def make(previous: Future[Version], edits: List[Edit_Text], version: Future[Version]): Change =
   457       new Change(Some(previous), edits.reverse, version)
   458   }
   459 
   460   final class Change private(
   461     val previous: Option[Future[Version]] = Some(Future.value(Version.init)),
   462     val rev_edits: List[Edit_Text] = Nil,
   463     val version: Future[Version] = Future.value(Version.init))
   464   {
   465     def is_finished: Boolean =
   466       (previous match { case None => true case Some(future) => future.is_finished }) &&
   467       version.is_finished
   468 
   469     def truncate: Change = new Change(None, Nil, version)
   470 
   471     def purge(versions: Map[Document_ID.Version, Version]): Option[Change] =
   472     {
   473       val previous1 = previous.map(Version.purge_future(versions, _))
   474       val version1 = Version.purge_future(versions, version)
   475       if ((previous eq previous1) && (version eq version1)) None
   476       else Some(new Change(previous1, rev_edits, version1))
   477     }
   478   }
   479 
   480 
   481   /* history navigation */
   482 
   483   object History
   484   {
   485     val init: History = new History()
   486   }
   487 
   488   final class History private(
   489     val undo_list: List[Change] = List(Change.init))  // non-empty list
   490   {
   491     override def toString: String = "History(" + undo_list.length + ")"
   492 
   493     def tip: Change = undo_list.head
   494     def + (change: Change): History = new History(change :: undo_list)
   495 
   496     def prune(check: Change => Boolean, retain: Int): Option[(List[Change], History)] =
   497     {
   498       val n = undo_list.iterator.zipWithIndex.find(p => check(p._1)).get._2 + 1
   499       val (retained, dropped) = undo_list.splitAt(n max retain)
   500 
   501       retained.splitAt(retained.length - 1) match {
   502         case (prefix, List(last)) => Some(dropped, new History(prefix ::: List(last.truncate)))
   503         case _ => None
   504       }
   505     }
   506 
   507     def purge(versions: Map[Document_ID.Version, Version]): History =
   508     {
   509       val undo_list1 = undo_list.map(_.purge(versions))
   510       if (undo_list1.forall(_.isEmpty)) this
   511       else new History(for ((a, b) <- undo_list1 zip undo_list) yield a.getOrElse(b))
   512     }
   513   }
   514 
   515 
   516   /* snapshot */
   517 
   518   object Snapshot
   519   {
   520     val init = State.init.snapshot()
   521   }
   522 
   523   abstract class Snapshot
   524   {
   525     def state: State
   526     def version: Version
   527     def is_outdated: Boolean
   528 
   529     def convert(i: Text.Offset): Text.Offset
   530     def revert(i: Text.Offset): Text.Offset
   531     def convert(range: Text.Range): Text.Range
   532     def revert(range: Text.Range): Text.Range
   533 
   534     def node_name: Node.Name
   535     def node: Node
   536     def nodes: List[(Node.Name, Node)]
   537 
   538     def commands_loading: List[Command]
   539     def commands_loading_ranges(pred: Node.Name => Boolean): List[Text.Range]
   540     def current_command(other_node_name: Node.Name, offset: Text.Offset): Option[Command]
   541 
   542     def markup_to_XML(range: Text.Range, elements: Markup.Elements): XML.Body
   543     def messages: List[(XML.Tree, Position.T)]
   544     def exports: List[Export.Entry]
   545     def exports_map: Map[String, Export.Entry]
   546 
   547     def find_command(id: Document_ID.Generic): Option[(Node, Command)]
   548     def find_command_position(id: Document_ID.Generic, offset: Symbol.Offset)
   549       : Option[Line.Node_Position]
   550 
   551     def cumulate[A](
   552       range: Text.Range,
   553       info: A,
   554       elements: Markup.Elements,
   555       result: List[Command.State] => (A, Text.Markup) => Option[A],
   556       status: Boolean = false): List[Text.Info[A]]
   557 
   558     def select[A](
   559       range: Text.Range,
   560       elements: Markup.Elements,
   561       result: List[Command.State] => Text.Markup => Option[A],
   562       status: Boolean = false): List[Text.Info[A]]
   563 
   564     def command_results(range: Text.Range): Command.Results
   565     def command_results(command: Command): Command.Results
   566 
   567     def command_id_map: Map[Document_ID.Generic, Command]
   568   }
   569 
   570 
   571   /* model */
   572 
   573   trait Session
   574   {
   575     def resources: Resources
   576   }
   577 
   578   trait Model
   579   {
   580     def session: Session
   581     def is_stable: Boolean
   582     def snapshot(): Snapshot
   583 
   584     def node_name: Node.Name
   585     def is_theory: Boolean = node_name.is_theory
   586     override def toString: String = node_name.toString
   587 
   588     def get_text(range: Text.Range): Option[String]
   589 
   590     def node_required: Boolean
   591     def get_blob: Option[Blob]
   592     def bibtex_entries: List[Text.Info[String]]
   593 
   594     def node_edits(
   595       node_header: Node.Header,
   596       text_edits: List[Text.Edit],
   597       perspective: Node.Perspective_Text): List[Edit_Text] =
   598     {
   599       val edits: List[Node.Edit[Text.Edit, Text.Perspective]] =
   600         get_blob match {
   601           case None =>
   602             List(
   603               Node.Deps(
   604                 if (session.resources.session_base.loaded_theory(node_name)) {
   605                   node_header.append_errors(
   606                     List("Cannot update finished theory " + quote(node_name.theory)))
   607                 }
   608                 else node_header),
   609               Node.Edits(text_edits), perspective)
   610           case Some(blob) => List(Node.Blob(blob), Node.Edits(text_edits))
   611         }
   612       edits.flatMap(edit => if (edit.is_void) None else Some(node_name -> edit))
   613     }
   614   }
   615 
   616 
   617   /** global state -- document structure, execution process, editing history **/
   618 
   619   type Assign_Update =
   620     List[(Document_ID.Command, List[Document_ID.Exec])]  // update of exec state assignment
   621 
   622   object State
   623   {
   624     class Fail(state: State) extends Exception
   625 
   626     object Assignment
   627     {
   628       val init: Assignment = new Assignment()
   629     }
   630 
   631     final class Assignment private(
   632       val command_execs: Map[Document_ID.Command, List[Document_ID.Exec]] = Map.empty,
   633       val is_finished: Boolean = false)
   634     {
   635       override def toString: String = "Assignment(" + command_execs.size + "," + is_finished + ")"
   636 
   637       def check_finished: Assignment = { require(is_finished); this }
   638       def unfinished: Assignment = new Assignment(command_execs, false)
   639 
   640       def assign(update: Assign_Update): Assignment =
   641       {
   642         require(!is_finished)
   643         val command_execs1 =
   644           (command_execs /: update) {
   645             case (res, (command_id, exec_ids)) =>
   646               if (exec_ids.isEmpty) res - command_id
   647               else res + (command_id -> exec_ids)
   648           }
   649         new Assignment(command_execs1, true)
   650       }
   651     }
   652 
   653     val init: State =
   654       State().define_version(Version.init, Assignment.init).assign(Version.init.id, Nil, Nil)._2
   655   }
   656 
   657   final case class State private(
   658     /*reachable versions*/
   659     versions: Map[Document_ID.Version, Version] = Map.empty,
   660     /*inlined auxiliary files*/
   661     blobs: Set[SHA1.Digest] = Set.empty,
   662     /*static markup from define_command*/
   663     commands: Map[Document_ID.Command, Command.State] = Map.empty,
   664     /*dynamic markup from execution*/
   665     execs: Map[Document_ID.Exec, Command.State] = Map.empty,
   666     /*command-exec assignment for each version*/
   667     assignments: Map[Document_ID.Version, State.Assignment] = Map.empty,
   668     /*commands with markup produced by other commands (imm_succs)*/
   669     commands_redirection: Graph[Document_ID.Command, Unit] = Graph.long,
   670     /*explicit (linear) history*/
   671     history: History = History.init,
   672     /*intermediate state between remove_versions/removed_versions*/
   673     removing_versions: Boolean = false)
   674   {
   675     override def toString: String =
   676       "State(versions = " + versions.size +
   677       ", blobs = " + blobs.size +
   678       ", commands = " + commands.size +
   679       ", execs = " + execs.size +
   680       ", assignments = " + assignments.size +
   681       ", commands_redirection = " + commands_redirection.size +
   682       ", history = " + history.undo_list.size +
   683       ", removing_versions = " + removing_versions + ")"
   684 
   685     private def fail[A]: A = throw new State.Fail(this)
   686 
   687     def define_version(version: Version, assignment: State.Assignment): State =
   688     {
   689       val id = version.id
   690       copy(versions = versions + (id -> version),
   691         assignments = assignments + (id -> assignment.unfinished))
   692     }
   693 
   694     def define_blob(digest: SHA1.Digest): State = copy(blobs = blobs + digest)
   695     def defined_blob(digest: SHA1.Digest): Boolean = blobs.contains(digest)
   696 
   697     def define_command(command: Command): State =
   698     {
   699       val id = command.id
   700       copy(commands = commands + (id -> command.init_state))
   701     }
   702 
   703     def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
   704 
   705     def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
   706     def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
   707     def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
   708     def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
   709 
   710     def lookup_id(id: Document_ID.Generic): Option[Command.State] =
   711       commands.get(id) orElse execs.get(id)
   712 
   713     private def self_id(st: Command.State)(id: Document_ID.Generic): Boolean =
   714       id == st.command.id ||
   715       (execs.get(id) match { case Some(st1) => st1.command.id == st.command.id case None => false })
   716 
   717     private def other_id(id: Document_ID.Generic)
   718       : Option[(Symbol.Text_Chunk.Id, Symbol.Text_Chunk)] =
   719       lookup_id(id).map(st => ((Symbol.Text_Chunk.Id(st.command.id), st.command.chunk)))
   720 
   721     private def redirection(st: Command.State): Graph[Document_ID.Command, Unit] =
   722       (commands_redirection /: st.markups.redirection_iterator)({ case (graph, id) =>
   723         graph.default_node(id, ()).default_node(st.command.id, ()).add_edge(id, st.command.id) })
   724 
   725     def accumulate(id: Document_ID.Generic, message: XML.Elem, xml_cache: XML.Cache)
   726       : (Command.State, State) =
   727     {
   728       execs.get(id) match {
   729         case Some(st) =>
   730           val new_st = st.accumulate(self_id(st), other_id _, message, xml_cache)
   731           val execs1 = execs + (id -> new_st)
   732           (new_st, copy(execs = execs1, commands_redirection = redirection(new_st)))
   733         case None =>
   734           commands.get(id) match {
   735             case Some(st) =>
   736               val new_st = st.accumulate(self_id(st), other_id _, message, xml_cache)
   737               val commands1 = commands + (id -> new_st)
   738               (new_st, copy(commands = commands1, commands_redirection = redirection(new_st)))
   739             case None => fail
   740           }
   741       }
   742     }
   743 
   744     def add_export(id: Document_ID.Generic, entry: Command.Exports.Entry): (Command.State, State) =
   745     {
   746       execs.get(id) match {
   747         case Some(st) =>
   748           st.add_export(entry) match {
   749             case Some(new_st) => (new_st, copy(execs = execs + (id -> new_st)))
   750             case None => fail
   751           }
   752         case None =>
   753           commands.get(id) match {
   754             case Some(st) =>
   755               st.add_export(entry) match {
   756                 case Some(new_st) => (new_st, copy(commands = commands + (id -> new_st)))
   757                 case None => fail
   758               }
   759             case None => fail
   760           }
   761       }
   762     }
   763 
   764     def node_exports(version: Version, node_name: Node.Name): Command.Exports =
   765       Command.Exports.merge(
   766         for {
   767           command <- version.nodes(node_name).commands.iterator
   768           st <- command_states(version, command).iterator
   769         } yield st.exports)
   770 
   771     def assign(id: Document_ID.Version, edited: List[String], update: Assign_Update)
   772       : ((List[Node.Name], List[Command]), State) =
   773     {
   774       val version = the_version(id)
   775 
   776       val edited_set = edited.toSet
   777       val edited_nodes =
   778         (for { (name, _) <- version.nodes.iterator if edited_set(name.node) } yield name).toList
   779 
   780       def upd(exec_id: Document_ID.Exec, st: Command.State)
   781           : Option[(Document_ID.Exec, Command.State)] =
   782         if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
   783 
   784       val (changed_commands, new_execs) =
   785         ((Nil: List[Command], execs) /: update) {
   786           case ((commands1, execs1), (command_id, exec)) =>
   787             val st = the_static_state(command_id)
   788             val command = st.command
   789             val commands2 = command :: commands1
   790             val execs2 =
   791               exec match {
   792                 case Nil => execs1
   793                 case eval_id :: print_ids =>
   794                   execs1 ++ upd(eval_id, st) ++
   795                     (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
   796               }
   797             (commands2, execs2)
   798         }
   799       val new_assignment = the_assignment(version).assign(update)
   800       val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
   801 
   802       ((edited_nodes, changed_commands), new_state)
   803     }
   804 
   805     def is_assigned(version: Version): Boolean =
   806       assignments.get(version.id) match {
   807         case Some(assgn) => assgn.is_finished
   808         case None => false
   809       }
   810 
   811     def is_stable(change: Change): Boolean =
   812       change.is_finished && is_assigned(change.version.get_finished)
   813 
   814     def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
   815     def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
   816     def stable_tip_version: Option[Version] =
   817       if (is_stable(history.tip)) Some(history.tip.version.get_finished) else None
   818 
   819     def continue_history(
   820       previous: Future[Version],
   821       edits: List[Edit_Text],
   822       version: Future[Version]): State =
   823     {
   824       val change = Change.make(previous, edits, version)
   825       copy(history = history + change)
   826     }
   827 
   828     def remove_versions(retain: Int = 0): (List[Version], State) =
   829     {
   830       history.prune(is_stable, retain) match {
   831         case Some((dropped, history1)) =>
   832           val old_versions = dropped.map(change => change.version.get_finished)
   833           val removing = old_versions.nonEmpty
   834           val state1 = copy(history = history1, removing_versions = removing)
   835           (old_versions, state1)
   836         case None => fail
   837       }
   838     }
   839 
   840     def removed_versions(removed: List[Document_ID.Version]): State =
   841     {
   842       val versions1 = Version.purge_suppressed(versions -- removed)
   843 
   844       val assignments1 = assignments -- removed
   845       var blobs1_names = Set.empty[Node.Name]
   846       var blobs1 = Set.empty[SHA1.Digest]
   847       var commands1 = Map.empty[Document_ID.Command, Command.State]
   848       var execs1 = Map.empty[Document_ID.Exec, Command.State]
   849       for {
   850         (version_id, version) <- versions1.iterator
   851         command_execs = assignments1(version_id).command_execs
   852         (_, node) <- version.nodes.iterator
   853         command <- node.commands.iterator
   854       } {
   855         for ((name, digest) <- command.blobs_defined) {
   856           blobs1_names += name
   857           blobs1 += digest
   858         }
   859 
   860         if (!commands1.isDefinedAt(command.id))
   861           commands.get(command.id).foreach(st => commands1 += (command.id -> st))
   862 
   863         for (exec_id <- command_execs.getOrElse(command.id, Nil)) {
   864           if (!execs1.isDefinedAt(exec_id))
   865             execs.get(exec_id).foreach(st => execs1 += (exec_id -> st))
   866         }
   867       }
   868 
   869       copy(
   870         versions = versions1,
   871         blobs = blobs1,
   872         commands = commands1,
   873         execs = execs1,
   874         commands_redirection = commands_redirection.restrict(commands1.isDefinedAt(_)),
   875         assignments = assignments1,
   876         history = history.purge(versions1),
   877         removing_versions = false)
   878     }
   879 
   880     def command_id_map(version: Version, commands: Iterable[Command])
   881       : Map[Document_ID.Generic, Command] =
   882     {
   883       require(is_assigned(version))
   884       val assignment = the_assignment(version).check_finished
   885       (for {
   886         command <- commands.iterator
   887         id <- (command.id :: assignment.command_execs.getOrElse(command.id, Nil)).iterator
   888       } yield (id -> command)).toMap
   889     }
   890 
   891     def command_state_eval(version: Version, command: Command): Option[Command.State] =
   892     {
   893       require(is_assigned(version))
   894       try {
   895         the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil) match {
   896           case eval_id :: _ => Some(the_dynamic_state(eval_id))
   897           case Nil => None
   898         }
   899       }
   900       catch { case _: State.Fail => None }
   901     }
   902 
   903     private def command_states_self(version: Version, command: Command)
   904       : List[(Document_ID.Generic, Command.State)] =
   905     {
   906       require(is_assigned(version))
   907       try {
   908         the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil)
   909           .map(id => id -> the_dynamic_state(id)) match {
   910             case Nil => fail
   911             case res => res
   912           }
   913       }
   914       catch {
   915         case _: State.Fail =>
   916           try { List(command.id -> the_static_state(command.id)) }
   917           catch { case _: State.Fail => List(command.id -> command.init_state) }
   918       }
   919     }
   920 
   921     def command_states(version: Version, command: Command): List[Command.State] =
   922     {
   923       val self = command_states_self(version, command)
   924       val others =
   925         if (commands_redirection.defined(command.id)) {
   926           (for {
   927             command_id <- commands_redirection.imm_succs(command.id).iterator
   928             (id, st) <- command_states_self(version, the_static_state(command_id).command)
   929             if !self.exists(_._1 == id)
   930           } yield (id, st)).toMap.valuesIterator.toList
   931         }
   932         else Nil
   933       self.map(_._2) ::: others.flatMap(_.redirect(command))
   934     }
   935 
   936     def command_results(version: Version, command: Command): Command.Results =
   937       Command.State.merge_results(command_states(version, command))
   938 
   939     def command_markup(version: Version, command: Command, index: Command.Markup_Index,
   940         range: Text.Range, elements: Markup.Elements): Markup_Tree =
   941       Command.State.merge_markup(command_states(version, command), index, range, elements)
   942 
   943     def markup_to_XML(
   944       version: Version,
   945       node_name: Node.Name,
   946       range: Text.Range,
   947       elements: Markup.Elements): XML.Body =
   948     {
   949       val node = version.nodes(node_name)
   950       if (node_name.is_theory) {
   951         val markup_index = Command.Markup_Index.markup
   952         (for {
   953           command <- node.commands.iterator
   954           command_range <- command.range.try_restrict(range).iterator
   955           markup = command_markup(version, command, markup_index, command_range, elements)
   956           tree <- markup.to_XML(command_range, command.source, elements).iterator
   957         } yield tree).toList
   958       }
   959       else {
   960         val node_source = node.source
   961         Text.Range(0, node_source.length).try_restrict(range) match {
   962           case None => Nil
   963           case Some(node_range) =>
   964             val markup =
   965               version.nodes.commands_loading(node_name).headOption match {
   966                 case None => Markup_Tree.empty
   967                 case Some(command) =>
   968                   val chunk_name = Symbol.Text_Chunk.File(node_name.node)
   969                   val markup_index = Command.Markup_Index(false, chunk_name)
   970                   command_markup(version, command, markup_index, node_range, elements)
   971               }
   972             markup.to_XML(node_range, node_source, elements)
   973         }
   974       }
   975     }
   976 
   977     def node_initialized(version: Version, name: Node.Name): Boolean =
   978       name.is_theory &&
   979       (version.nodes(name).commands.iterator.find(_.potentially_initialized) match {
   980         case None => false
   981         case Some(command) => command_states(version, command).headOption.exists(_.initialized)
   982       })
   983 
   984     def node_maybe_consolidated(version: Version, name: Node.Name): Boolean =
   985       name.is_theory &&
   986       {
   987         version.nodes(name).commands.reverse.iterator.forall(command =>
   988           command_state_eval(version, command) match {
   989             case None => false
   990             case Some(st) => st.maybe_consolidated
   991           })
   992       }
   993 
   994     def node_consolidated(version: Version, name: Node.Name): Boolean =
   995       !name.is_theory ||
   996       {
   997         val it = version.nodes(name).commands.reverse.iterator
   998         it.hasNext && command_states(version, it.next).exists(_.consolidated)
   999       }
  1000 
  1001     // persistent user-view
  1002     def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
  1003       : Snapshot =
  1004     {
  1005       val stable = recent_stable
  1006       val latest = history.tip
  1007 
  1008 
  1009       /* pending edits and unstable changes */
  1010 
  1011       val rev_pending_changes =
  1012         for {
  1013           change <- history.undo_list.takeWhile(_ != stable)
  1014           (a, edits) <- change.rev_edits
  1015           if a == name
  1016         } yield edits
  1017 
  1018       val edits =
  1019         (pending_edits /: rev_pending_changes)({
  1020           case (edits, Node.Edits(es)) => es ::: edits
  1021           case (edits, _) => edits
  1022         })
  1023       lazy val reverse_edits = edits.reverse
  1024 
  1025       new Snapshot
  1026       {
  1027         /* global information */
  1028 
  1029         val state: State = State.this
  1030         val version: Version = stable.version.get_finished
  1031         val is_outdated: Boolean = pending_edits.nonEmpty || latest != stable
  1032 
  1033 
  1034         /* local node content */
  1035 
  1036         def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
  1037         def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
  1038 
  1039         def convert(range: Text.Range) = range.map(convert(_))
  1040         def revert(range: Text.Range) = range.map(revert(_))
  1041 
  1042         val node_name: Node.Name = name
  1043         val node: Node = version.nodes(name)
  1044 
  1045         def nodes: List[(Node.Name, Node)] =
  1046           (node_name :: node.load_commands.flatMap(_.blobs_names)).
  1047             map(name => (name, version.nodes(name)))
  1048 
  1049         val commands_loading: List[Command] =
  1050           if (node_name.is_theory) Nil
  1051           else version.nodes.commands_loading(node_name)
  1052 
  1053         def commands_loading_ranges(pred: Node.Name => Boolean): List[Text.Range] =
  1054           (for {
  1055             cmd <- node.load_commands.iterator
  1056             blob_name <- cmd.blobs_names.iterator
  1057             if pred(blob_name)
  1058             start <- node.command_start(cmd)
  1059           } yield convert(cmd.core_range + start)).toList
  1060 
  1061         def current_command(other_node_name: Node.Name, offset: Text.Offset): Option[Command] =
  1062           if (other_node_name.is_theory) {
  1063             val other_node = version.nodes(other_node_name)
  1064             val iterator = other_node.command_iterator(revert(offset) max 0)
  1065             if (iterator.hasNext) {
  1066               val (command0, _) = iterator.next
  1067               other_node.commands.reverse.iterator(command0).find(command => !command.is_ignored)
  1068             }
  1069             else other_node.commands.reverse.iterator.find(command => !command.is_ignored)
  1070           }
  1071           else version.nodes.commands_loading(other_node_name).headOption
  1072 
  1073         def markup_to_XML(range: Text.Range, elements: Markup.Elements): XML.Body =
  1074           state.markup_to_XML(version, node_name, range, elements)
  1075 
  1076         lazy val messages: List[(XML.Tree, Position.T)] =
  1077           (for {
  1078             (command, start) <-
  1079               Document.Node.Commands.starts_pos(
  1080                 node.commands.iterator, Token.Pos.file(node_name.node))
  1081             pos = command.span.keyword_pos(start).position(command.span.name)
  1082             (_, tree) <- state.command_results(version, command).iterator
  1083            } yield (tree, pos)).toList
  1084 
  1085         lazy val exports: List[Export.Entry] =
  1086           state.node_exports(version, node_name).iterator.map(_._2).toList
  1087 
  1088         lazy val exports_map: Map[String, Export.Entry] =
  1089           (for (entry <- exports.iterator) yield (entry.name, entry)).toMap
  1090 
  1091 
  1092         /* find command */
  1093 
  1094         def find_command(id: Document_ID.Generic): Option[(Node, Command)] =
  1095           state.lookup_id(id) match {
  1096             case None => None
  1097             case Some(st) =>
  1098               val command = st.command
  1099               val node = version.nodes(command.node_name)
  1100               if (node.commands.contains(command)) Some((node, command)) else None
  1101           }
  1102 
  1103         def find_command_position(id: Document_ID.Generic, offset: Symbol.Offset)
  1104             : Option[Line.Node_Position] =
  1105           for ((node, command) <- find_command(id))
  1106           yield {
  1107             val name = command.node_name.node
  1108             val sources_iterator =
  1109               node.commands.iterator.takeWhile(_ != command).map(_.source) ++
  1110                 (if (offset == 0) Iterator.empty
  1111                  else Iterator.single(command.source(Text.Range(0, command.chunk.decode(offset)))))
  1112             val pos = (Line.Position.zero /: sources_iterator)(_.advance(_))
  1113             Line.Node_Position(name, pos)
  1114           }
  1115 
  1116 
  1117         /* cumulate markup */
  1118 
  1119         def cumulate[A](
  1120           range: Text.Range,
  1121           info: A,
  1122           elements: Markup.Elements,
  1123           result: List[Command.State] => (A, Text.Markup) => Option[A],
  1124           status: Boolean = false): List[Text.Info[A]] =
  1125         {
  1126           val former_range = revert(range).inflate_singularity
  1127           val (chunk_name, command_iterator) =
  1128             commands_loading.headOption match {
  1129               case None => (Symbol.Text_Chunk.Default, node.command_iterator(former_range))
  1130               case Some(command) => (Symbol.Text_Chunk.File(node_name.node), Iterator((command, 0)))
  1131             }
  1132           val markup_index = Command.Markup_Index(status, chunk_name)
  1133           (for {
  1134             (command, command_start) <- command_iterator
  1135             chunk <- command.chunks.get(chunk_name).iterator
  1136             states = state.command_states(version, command)
  1137             res = result(states)
  1138             markup_range <- (former_range - command_start).try_restrict(chunk.range).iterator
  1139             markup = Command.State.merge_markup(states, markup_index, markup_range, elements)
  1140             Text.Info(r0, a) <- markup.cumulate[A](markup_range, info, elements,
  1141               {
  1142                 case (a, Text.Info(r0, b)) => res(a, Text.Info(convert(r0 + command_start), b))
  1143               }).iterator
  1144             r1 <- convert(r0 + command_start).try_restrict(range).iterator
  1145           } yield Text.Info(r1, a)).toList
  1146         }
  1147 
  1148         def select[A](
  1149           range: Text.Range,
  1150           elements: Markup.Elements,
  1151           result: List[Command.State] => Text.Markup => Option[A],
  1152           status: Boolean = false): List[Text.Info[A]] =
  1153         {
  1154           def result1(states: List[Command.State]): (Option[A], Text.Markup) => Option[Option[A]] =
  1155           {
  1156             val res = result(states)
  1157             (_: Option[A], x: Text.Markup) =>
  1158               res(x) match {
  1159                 case None => None
  1160                 case some => Some(some)
  1161               }
  1162           }
  1163           for (Text.Info(r, Some(x)) <- cumulate(range, None, elements, result1 _, status))
  1164             yield Text.Info(r, x)
  1165         }
  1166 
  1167 
  1168         /* command results */
  1169 
  1170         def command_results(range: Text.Range): Command.Results =
  1171           Command.State.merge_results(
  1172             select[List[Command.State]](range, Markup.Elements.full, command_states =>
  1173               { case _ => Some(command_states) }).flatMap(_.info))
  1174 
  1175         def command_results(command: Command): Command.Results =
  1176           state.command_results(version, command)
  1177 
  1178 
  1179         /* command ids: static and dynamic */
  1180 
  1181         def command_id_map: Map[Document_ID.Generic, Command] =
  1182           state.command_id_map(version, version.nodes(node_name).commands)
  1183 
  1184 
  1185         /* output */
  1186 
  1187         override def toString: String =
  1188           "Snapshot(node = " + node_name.node + ", version = " + version.id +
  1189             (if (is_outdated) ", outdated" else "") + ")"
  1190       }
  1191     }
  1192   }
  1193 }