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