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