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