src/Pure/PIDE/document.scala
author wenzelm
Wed Aug 07 20:32:54 2013 +0200 (2013-08-07)
changeset 52901 8be75f53db82
parent 52900 d29bf6db8a2d
child 52918 038458a4d11b
permissions -rw-r--r--
maintain commands together with index -- avoid redundant reconstruction of full_index;
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@46723
    18
  /* individual nodes */
wenzelm@38424
    19
wenzelm@44615
    20
  type Edit[A, B] = (Node.Name, Node.Edit[A, B])
wenzelm@44384
    21
  type Edit_Text = Edit[Text.Edit, Text.Perspective]
wenzelm@52849
    22
  type Edit_Command = Edit[Command.Edit, Command.Perspective]
wenzelm@38151
    23
wenzelm@38151
    24
  object Node
wenzelm@38151
    25
  {
wenzelm@52887
    26
    val empty: Node = new Node()
wenzelm@52887
    27
wenzelm@52887
    28
wenzelm@52887
    29
    /* header and name */
wenzelm@52887
    30
wenzelm@48707
    31
    sealed case class Header(
wenzelm@46938
    32
      imports: List[Name],
wenzelm@48706
    33
      keywords: Thy_Header.Keywords,
wenzelm@48707
    34
      errors: List[String] = Nil)
wenzelm@48707
    35
    {
wenzelm@48707
    36
      def error(msg: String): Header = copy(errors = errors ::: List(msg))
wenzelm@48707
    37
    }
wenzelm@48707
    38
wenzelm@51294
    39
    def bad_header(msg: String): Header = Header(Nil, Nil, List(msg))
wenzelm@46737
    40
wenzelm@44957
    41
    object Name
wenzelm@44957
    42
    {
wenzelm@44957
    43
      val empty = Name("", "", "")
wenzelm@46723
    44
wenzelm@46723
    45
      object Ordering extends scala.math.Ordering[Name]
wenzelm@46723
    46
      {
wenzelm@46723
    47
        def compare(name1: Name, name2: Name): Int = name1.node compare name2.node
wenzelm@46723
    48
      }
wenzelm@44957
    49
    }
wenzelm@52887
    50
wenzelm@44616
    51
    sealed case class Name(node: String, dir: String, theory: String)
wenzelm@44615
    52
    {
wenzelm@44615
    53
      override def hashCode: Int = node.hashCode
wenzelm@44615
    54
      override def equals(that: Any): Boolean =
wenzelm@44615
    55
        that match {
wenzelm@44615
    56
          case other: Name => node == other.node
wenzelm@44615
    57
          case _ => false
wenzelm@44615
    58
        }
wenzelm@44642
    59
      override def toString: String = theory
wenzelm@44615
    60
    }
wenzelm@44615
    61
wenzelm@52887
    62
wenzelm@52887
    63
    /* overlays -- print functions with arguments */
wenzelm@52887
    64
wenzelm@52887
    65
    type Overlay = (Command, (String, List[String]))
wenzelm@52887
    66
wenzelm@52887
    67
    object Overlays
wenzelm@52887
    68
    {
wenzelm@52887
    69
      val empty = new Overlays(Map.empty)
wenzelm@52887
    70
    }
wenzelm@52887
    71
wenzelm@52887
    72
    final class Overlays private(rep: Map[Command, List[(String, List[String])]])
wenzelm@52887
    73
    {
wenzelm@52887
    74
      def commands: Set[Command] = rep.keySet
wenzelm@52887
    75
      def is_empty: Boolean = rep.isEmpty
wenzelm@52887
    76
wenzelm@52887
    77
      def insert(cmd: Command, over: (String, List[String])): Overlays =
wenzelm@52887
    78
      {
wenzelm@52887
    79
        val overs = rep.getOrElse(cmd, Nil)
wenzelm@52887
    80
        if (overs.contains(over)) this
wenzelm@52887
    81
        else new Overlays(rep + (cmd -> (over :: overs)))
wenzelm@52887
    82
      }
wenzelm@52887
    83
wenzelm@52887
    84
      def remove(cmd: Command, over: (String, List[String])): Overlays =
wenzelm@52887
    85
        rep.get(cmd) match {
wenzelm@52887
    86
          case Some(overs) =>
wenzelm@52887
    87
            if (overs.contains(over)) {
wenzelm@52887
    88
              overs.filterNot(_ == over) match {
wenzelm@52887
    89
                case Nil => new Overlays(rep - cmd)
wenzelm@52887
    90
                case overs1 => new Overlays(rep + (cmd -> overs1))
wenzelm@52887
    91
              }
wenzelm@52887
    92
            }
wenzelm@52887
    93
            else this
wenzelm@52887
    94
          case None => this
wenzelm@52887
    95
        }
wenzelm@52887
    96
wenzelm@52887
    97
      def dest: List[Overlay] =
wenzelm@52887
    98
        (for {
wenzelm@52887
    99
          (cmd, overs) <- rep.iterator
wenzelm@52887
   100
          over <- overs
wenzelm@52887
   101
        } yield (cmd, over)).toList
wenzelm@52887
   102
    }
wenzelm@52887
   103
wenzelm@52887
   104
wenzelm@52887
   105
    /* edits */
wenzelm@52887
   106
wenzelm@44384
   107
    sealed abstract class Edit[A, B]
wenzelm@44156
   108
    {
wenzelm@44383
   109
      def foreach(f: A => Unit)
wenzelm@44383
   110
      {
wenzelm@44156
   111
        this match {
wenzelm@44383
   112
          case Edits(es) => es.foreach(f)
wenzelm@44383
   113
          case _ =>
wenzelm@44156
   114
        }
wenzelm@44383
   115
      }
wenzelm@44156
   116
    }
wenzelm@44384
   117
    case class Clear[A, B]() extends Edit[A, B]
wenzelm@44384
   118
    case class Edits[A, B](edits: List[A]) extends Edit[A, B]
wenzelm@48707
   119
    case class Deps[A, B](header: Header) extends Edit[A, B]
wenzelm@52849
   120
    case class Perspective[A, B](required: Boolean, visible: B, overlays: Overlays) extends Edit[A, B]
wenzelm@52808
   121
    type Perspective_Text = Perspective[Text.Edit, Text.Perspective]
wenzelm@52849
   122
    type Perspective_Command = Perspective[Command.Edit, Command.Perspective]
wenzelm@44156
   123
wenzelm@52887
   124
wenzelm@52887
   125
    /* commands */
wenzelm@52887
   126
wenzelm@52901
   127
    object Commands
wenzelm@52901
   128
    {
wenzelm@52901
   129
      def apply(commands: Linear_Set[Command]): Commands = new Commands(commands)
wenzelm@52901
   130
      val empty: Commands = apply(Linear_Set.empty)
wenzelm@52901
   131
wenzelm@52901
   132
      def starts(commands: Iterator[Command], offset: Text.Offset = 0)
wenzelm@52901
   133
        : Iterator[(Command, Text.Offset)] =
wenzelm@52901
   134
      {
wenzelm@52901
   135
        var i = offset
wenzelm@52901
   136
        for (command <- commands) yield {
wenzelm@52901
   137
          val start = i
wenzelm@52901
   138
          i += command.length
wenzelm@52901
   139
          (command, start)
wenzelm@52901
   140
        }
wenzelm@52901
   141
      }
wenzelm@52901
   142
wenzelm@52901
   143
      private val block_size = 1024
wenzelm@52901
   144
    }
wenzelm@52901
   145
wenzelm@52901
   146
    final class Commands private(val commands: Linear_Set[Command])
wenzelm@38227
   147
    {
wenzelm@52901
   148
      private lazy val full_index: (Array[(Command, Text.Offset)], Text.Range) =
wenzelm@52901
   149
      {
wenzelm@52901
   150
        val blocks = new mutable.ListBuffer[(Command, Text.Offset)]
wenzelm@52901
   151
        var next_block = 0
wenzelm@52901
   152
        var last_stop = 0
wenzelm@52901
   153
        for ((command, start) <- Commands.starts(commands.iterator)) {
wenzelm@52901
   154
          last_stop = start + command.length
wenzelm@52901
   155
          while (last_stop + 1 > next_block) {
wenzelm@52901
   156
            blocks += (command -> start)
wenzelm@52901
   157
            next_block += Commands.block_size
wenzelm@52901
   158
          }
wenzelm@52901
   159
        }
wenzelm@52901
   160
        (blocks.toArray, Text.Range(0, last_stop))
wenzelm@52901
   161
      }
wenzelm@52901
   162
wenzelm@52901
   163
      private def full_range: Text.Range = full_index._2
wenzelm@52901
   164
wenzelm@52901
   165
      def range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
wenzelm@52901
   166
      {
wenzelm@52901
   167
        if (!commands.isEmpty && full_range.contains(i)) {
wenzelm@52901
   168
          val (cmd0, start0) = full_index._1(i / Commands.block_size)
wenzelm@52901
   169
          Node.Commands.starts(commands.iterator(cmd0), start0) dropWhile {
wenzelm@52901
   170
            case (cmd, start) => start + cmd.length <= i }
wenzelm@52901
   171
        }
wenzelm@52901
   172
        else Iterator.empty
wenzelm@38227
   173
      }
wenzelm@38227
   174
    }
wenzelm@38151
   175
  }
wenzelm@38151
   176
wenzelm@46712
   177
  final class Node private(
wenzelm@48707
   178
    val header: Node.Header = Node.bad_header("Bad theory header"),
wenzelm@52849
   179
    val perspective: Node.Perspective_Command =
wenzelm@52887
   180
      Node.Perspective(false, Command.Perspective.empty, Node.Overlays.empty),
wenzelm@52901
   181
    _commands: Node.Commands = Node.Commands.empty)
wenzelm@38151
   182
  {
wenzelm@46680
   183
    def clear: Node = new Node(header = header)
wenzelm@46680
   184
wenzelm@48707
   185
    def update_header(new_header: Node.Header): Node =
wenzelm@52901
   186
      new Node(new_header, perspective, _commands)
wenzelm@46680
   187
wenzelm@52849
   188
    def update_perspective(new_perspective: Node.Perspective_Command): Node =
wenzelm@52901
   189
      new Node(header, new_perspective, _commands)
wenzelm@46680
   190
wenzelm@52849
   191
    def same_perspective(other_perspective: Node.Perspective_Command): Boolean =
wenzelm@52849
   192
      perspective.required == other_perspective.required &&
wenzelm@52849
   193
      perspective.visible.same(other_perspective.visible) &&
wenzelm@52849
   194
      perspective.overlays == other_perspective.overlays
wenzelm@52808
   195
wenzelm@52901
   196
    def commands: Linear_Set[Command] = _commands.commands
wenzelm@43697
   197
wenzelm@52901
   198
    def update_commands(new_commands: Linear_Set[Command]): Node =
wenzelm@52901
   199
      if (new_commands eq _commands) this
wenzelm@52901
   200
      else new Node(header, perspective, Node.Commands(new_commands))
wenzelm@38151
   201
wenzelm@38569
   202
    def command_range(i: Text.Offset = 0): Iterator[(Command, Text.Offset)] =
wenzelm@52901
   203
      _commands.range(i)
wenzelm@38151
   204
wenzelm@38569
   205
    def command_range(range: Text.Range): Iterator[(Command, Text.Offset)] =
wenzelm@38569
   206
      command_range(range.start) takeWhile { case (_, start) => start < range.stop }
wenzelm@38151
   207
wenzelm@38426
   208
    def command_at(i: Text.Offset): Option[(Command, Text.Offset)] =
wenzelm@38151
   209
    {
wenzelm@38151
   210
      val range = command_range(i)
wenzelm@38151
   211
      if (range.hasNext) Some(range.next) else None
wenzelm@38151
   212
    }
wenzelm@38151
   213
wenzelm@38879
   214
    def command_start(cmd: Command): Option[Text.Offset] =
wenzelm@52901
   215
      Node.Commands.starts(commands.iterator).find(_._1 == cmd).map(_._2)
wenzelm@38151
   216
  }
wenzelm@38151
   217
wenzelm@38151
   218
wenzelm@46723
   219
  /* development graph */
wenzelm@46723
   220
wenzelm@46723
   221
  object Nodes
wenzelm@46723
   222
  {
wenzelm@46723
   223
    val empty: Nodes = new Nodes(Graph.empty(Node.Name.Ordering))
wenzelm@46723
   224
  }
wenzelm@46723
   225
wenzelm@46723
   226
  final class Nodes private(graph: Graph[Node.Name, Node])
wenzelm@46723
   227
  {
wenzelm@46723
   228
    def get_name(s: String): Option[Node.Name] =
wenzelm@46723
   229
      graph.keys.find(name => name.node == s)
wenzelm@46723
   230
wenzelm@46723
   231
    def apply(name: Node.Name): Node =
wenzelm@46723
   232
      graph.default_node(name, Node.empty).get_node(name)
wenzelm@46723
   233
wenzelm@46723
   234
    def + (entry: (Node.Name, Node)): Nodes =
wenzelm@46723
   235
    {
wenzelm@46723
   236
      val (name, node) = entry
wenzelm@48707
   237
      val imports = node.header.imports
wenzelm@46723
   238
      val graph1 =
wenzelm@46739
   239
        (graph.default_node(name, Node.empty) /: imports)((g, p) => g.default_node(p, Node.empty))
wenzelm@46723
   240
      val graph2 = (graph1 /: graph1.imm_preds(name))((g, dep) => g.del_edge(dep, name))
wenzelm@46739
   241
      val graph3 = (graph2 /: imports)((g, dep) => g.add_edge(dep, name))
wenzelm@46723
   242
      new Nodes(graph3.map_node(name, _ => node))
wenzelm@46723
   243
    }
wenzelm@46723
   244
wenzelm@46723
   245
    def entries: Iterator[(Node.Name, Node)] =
wenzelm@46723
   246
      graph.entries.map({ case (name, (node, _)) => (name, node) })
wenzelm@46723
   247
wenzelm@46942
   248
    def descendants(names: List[Node.Name]): List[Node.Name] = graph.all_succs(names)
wenzelm@46723
   249
    def topological_order: List[Node.Name] = graph.topological_order
wenzelm@46723
   250
  }
wenzelm@46723
   251
wenzelm@46723
   252
wenzelm@38424
   253
wenzelm@38424
   254
  /** versioning **/
wenzelm@38424
   255
wenzelm@38424
   256
  /* particular document versions */
wenzelm@34485
   257
wenzelm@38417
   258
  object Version
wenzelm@38417
   259
  {
wenzelm@46681
   260
    val init: Version = new Version()
wenzelm@46681
   261
wenzelm@46941
   262
    def make(syntax: Outer_Syntax, nodes: Nodes): Version =
wenzelm@52530
   263
      new Version(Document_ID.make(), syntax, nodes)
wenzelm@38417
   264
  }
wenzelm@38417
   265
wenzelm@46712
   266
  final class Version private(
wenzelm@52530
   267
    val id: Document_ID.Version = Document_ID.none,
wenzelm@46941
   268
    val syntax: Outer_Syntax = Outer_Syntax.empty,
wenzelm@46723
   269
    val nodes: Nodes = Nodes.empty)
wenzelm@46941
   270
  {
wenzelm@52530
   271
    def is_init: Boolean = id == Document_ID.none
wenzelm@46941
   272
  }
immler@34660
   273
wenzelm@34859
   274
wenzelm@38424
   275
  /* changes of plain text, eventually resulting in document edits */
wenzelm@38227
   276
wenzelm@38227
   277
  object Change
wenzelm@38227
   278
  {
wenzelm@46678
   279
    val init: Change = new Change()
wenzelm@46678
   280
wenzelm@46678
   281
    def make(previous: Future[Version], edits: List[Edit_Text], version: Future[Version]): Change =
wenzelm@46678
   282
      new Change(Some(previous), edits, version)
wenzelm@38227
   283
  }
wenzelm@38227
   284
wenzelm@46712
   285
  final class Change private(
wenzelm@46677
   286
    val previous: Option[Future[Version]] = Some(Future.value(Version.init)),
wenzelm@46677
   287
    val edits: List[Edit_Text] = Nil,
wenzelm@46677
   288
    val version: Future[Version] = Future.value(Version.init))
wenzelm@38227
   289
  {
wenzelm@44672
   290
    def is_finished: Boolean =
wenzelm@44672
   291
      (previous match { case None => true case Some(future) => future.is_finished }) &&
wenzelm@44672
   292
      version.is_finished
wenzelm@44672
   293
wenzelm@46678
   294
    def truncate: Change = new Change(None, Nil, version)
wenzelm@38227
   295
  }
wenzelm@38227
   296
wenzelm@38227
   297
wenzelm@38841
   298
  /* history navigation */
wenzelm@38841
   299
wenzelm@38841
   300
  object History
wenzelm@38841
   301
  {
wenzelm@46679
   302
    val init: History = new History()
wenzelm@38841
   303
  }
wenzelm@38841
   304
wenzelm@46712
   305
  final class History private(
wenzelm@46679
   306
    val undo_list: List[Change] = List(Change.init))  // non-empty list
wenzelm@38841
   307
  {
wenzelm@46679
   308
    def tip: Change = undo_list.head
wenzelm@46679
   309
    def + (change: Change): History = new History(change :: undo_list)
wenzelm@38841
   310
wenzelm@46679
   311
    def prune(check: Change => Boolean, retain: Int): Option[(List[Change], History)] =
wenzelm@46679
   312
    {
wenzelm@46679
   313
      val n = undo_list.iterator.zipWithIndex.find(p => check(p._1)).get._2 + 1
wenzelm@46679
   314
      val (retained, dropped) = undo_list.splitAt(n max retain)
wenzelm@46679
   315
wenzelm@46679
   316
      retained.splitAt(retained.length - 1) match {
wenzelm@46679
   317
        case (prefix, List(last)) => Some(dropped, new History(prefix ::: List(last.truncate)))
wenzelm@46679
   318
        case _ => None
wenzelm@46679
   319
      }
wenzelm@46679
   320
    }
wenzelm@38841
   321
  }
wenzelm@38841
   322
wenzelm@38841
   323
wenzelm@38841
   324
wenzelm@38841
   325
  /** global state -- document structure, execution process, editing history **/
wenzelm@38424
   326
wenzelm@38424
   327
  abstract class Snapshot
wenzelm@38424
   328
  {
wenzelm@44582
   329
    val state: State
wenzelm@38424
   330
    val version: Version
wenzelm@48923
   331
    val node_name: Node.Name
wenzelm@38424
   332
    val node: Node
wenzelm@38424
   333
    val is_outdated: Boolean
wenzelm@38427
   334
    def convert(i: Text.Offset): Text.Offset
wenzelm@52889
   335
    def revert(i: Text.Offset): Text.Offset
wenzelm@39177
   336
    def convert(range: Text.Range): Text.Range
wenzelm@39177
   337
    def revert(range: Text.Range): Text.Range
wenzelm@51494
   338
    def eq_content(other: Snapshot): Boolean
wenzelm@52508
   339
    def cumulate_markup[A](
wenzelm@52508
   340
      range: Text.Range,
wenzelm@52508
   341
      info: A,
wenzelm@52508
   342
      elements: Option[Set[String]],
wenzelm@52900
   343
      result: Command.State => (A, Text.Markup) => Option[A]): List[Text.Info[A]]
wenzelm@52508
   344
    def select_markup[A](
wenzelm@52508
   345
      range: Text.Range,
wenzelm@52508
   346
      elements: Option[Set[String]],
wenzelm@52900
   347
      result: Command.State => Text.Markup => Option[A]): List[Text.Info[A]]
wenzelm@38424
   348
  }
wenzelm@38424
   349
wenzelm@52563
   350
  type Assign_Update =
wenzelm@52563
   351
    List[(Document_ID.Command, List[Document_ID.Exec])]  // update of exec state assignment
wenzelm@44476
   352
wenzelm@38370
   353
  object State
wenzelm@38370
   354
  {
wenzelm@38373
   355
    class Fail(state: State) extends Exception
wenzelm@38373
   356
wenzelm@44479
   357
    object Assignment
wenzelm@44479
   358
    {
wenzelm@46683
   359
      val init: Assignment = new Assignment()
wenzelm@44479
   360
    }
wenzelm@38370
   361
wenzelm@46712
   362
    final class Assignment private(
wenzelm@52530
   363
      val command_execs: Map[Document_ID.Command, List[Document_ID.Exec]] = Map.empty,
wenzelm@46677
   364
      val is_finished: Boolean = false)
wenzelm@38370
   365
    {
wenzelm@44477
   366
      def check_finished: Assignment = { require(is_finished); this }
wenzelm@47388
   367
      def unfinished: Assignment = new Assignment(command_execs, false)
wenzelm@44479
   368
wenzelm@52563
   369
      def assign(update: Assign_Update): Assignment =
wenzelm@38370
   370
      {
wenzelm@38976
   371
        require(!is_finished)
wenzelm@44479
   372
        val command_execs1 =
wenzelm@52563
   373
          (command_execs /: update) {
wenzelm@52563
   374
            case (res, (command_id, exec_ids)) =>
wenzelm@52563
   375
              if (exec_ids.isEmpty) res - command_id
wenzelm@52563
   376
              else res + (command_id -> exec_ids)
wenzelm@44479
   377
          }
wenzelm@47388
   378
        new Assignment(command_execs1, true)
wenzelm@38150
   379
      }
wenzelm@38370
   380
    }
wenzelm@46682
   381
wenzelm@46682
   382
    val init: State =
wenzelm@52563
   383
      State().define_version(Version.init, Assignment.init).assign(Version.init.id, Nil)._2
wenzelm@38370
   384
  }
wenzelm@38370
   385
wenzelm@46712
   386
  final case class State private(
wenzelm@52530
   387
    val versions: Map[Document_ID.Version, Version] = Map.empty,
wenzelm@52530
   388
    val commands: Map[Document_ID.Command, Command.State] = Map.empty,  // static markup from define_command
wenzelm@52530
   389
    val execs: Map[Document_ID.Exec, Command.State] = Map.empty,  // dynamic markup from execution
wenzelm@52530
   390
    val assignments: Map[Document_ID.Version, State.Assignment] = Map.empty,
wenzelm@38841
   391
    val history: History = History.init)
wenzelm@38370
   392
  {
wenzelm@38373
   393
    private def fail[A]: A = throw new State.Fail(this)
wenzelm@38370
   394
wenzelm@44479
   395
    def define_version(version: Version, assignment: State.Assignment): State =
wenzelm@38370
   396
    {
wenzelm@38417
   397
      val id = version.id
wenzelm@38417
   398
      copy(versions = versions + (id -> version),
wenzelm@44479
   399
        assignments = assignments + (id -> assignment.unfinished))
wenzelm@38370
   400
    }
wenzelm@38370
   401
wenzelm@38373
   402
    def define_command(command: Command): State =
wenzelm@38373
   403
    {
wenzelm@38373
   404
      val id = command.id
wenzelm@49414
   405
      copy(commands = commands + (id -> command.init_state))
wenzelm@38373
   406
    }
wenzelm@38373
   407
wenzelm@52530
   408
    def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
wenzelm@44582
   409
wenzelm@52531
   410
    def find_command(version: Version, id: Document_ID.Generic): Option[(Node, Command)] =
wenzelm@44582
   411
      commands.get(id) orElse execs.get(id) match {
wenzelm@44582
   412
        case None => None
wenzelm@44582
   413
        case Some(st) =>
wenzelm@44582
   414
          val command = st.command
wenzelm@46681
   415
          val node = version.nodes(command.node_name)
wenzelm@46681
   416
          Some((node, command))
wenzelm@44582
   417
      }
wenzelm@38373
   418
wenzelm@52530
   419
    def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
wenzelm@52564
   420
    def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
wenzelm@52564
   421
    def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
wenzelm@52563
   422
    def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
wenzelm@38370
   423
wenzelm@52531
   424
    def accumulate(id: Document_ID.Generic, message: XML.Elem): (Command.State, State) =
wenzelm@38370
   425
      execs.get(id) match {
wenzelm@44446
   426
        case Some(st) =>
wenzelm@49527
   427
          val new_st = st + (id, message)
wenzelm@44446
   428
          (new_st, copy(execs = execs + (id -> new_st)))
wenzelm@38370
   429
        case None =>
wenzelm@38370
   430
          commands.get(id) match {
wenzelm@38370
   431
            case Some(st) =>
wenzelm@49527
   432
              val new_st = st + (id, message)
wenzelm@38370
   433
              (new_st, copy(commands = commands + (id -> new_st)))
wenzelm@38370
   434
            case None => fail
wenzelm@38370
   435
          }
wenzelm@38370
   436
      }
wenzelm@38370
   437
wenzelm@52563
   438
    def assign(id: Document_ID.Version, update: Assign_Update): (List[Command], State) =
wenzelm@38370
   439
    {
wenzelm@38417
   440
      val version = the_version(id)
wenzelm@38370
   441
wenzelm@52566
   442
      def upd(exec_id: Document_ID.Exec, st: Command.State)
wenzelm@52566
   443
          : Option[(Document_ID.Exec, Command.State)] =
wenzelm@52566
   444
        if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
wenzelm@52566
   445
wenzelm@44543
   446
      val (changed_commands, new_execs) =
wenzelm@52563
   447
        ((Nil: List[Command], execs) /: update) {
wenzelm@52566
   448
          case ((commands1, execs1), (command_id, exec)) =>
wenzelm@52566
   449
            val st = the_static_state(command_id)
wenzelm@52566
   450
            val command = st.command
wenzelm@52527
   451
            val commands2 = command :: commands1
wenzelm@44543
   452
            val execs2 =
wenzelm@44543
   453
              exec match {
wenzelm@52527
   454
                case Nil => execs1
wenzelm@52527
   455
                case eval_id :: print_ids =>
wenzelm@52566
   456
                  execs1 ++ upd(eval_id, st) ++
wenzelm@52566
   457
                    (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
wenzelm@44543
   458
              }
wenzelm@44543
   459
            (commands2, execs2)
wenzelm@38370
   460
        }
wenzelm@52563
   461
      val new_assignment = the_assignment(version).assign(update)
wenzelm@43722
   462
      val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
wenzelm@44476
   463
wenzelm@44543
   464
      (changed_commands, new_state)
wenzelm@38370
   465
    }
wenzelm@38370
   466
wenzelm@38417
   467
    def is_assigned(version: Version): Boolean =
wenzelm@43722
   468
      assignments.get(version.id) match {
wenzelm@38370
   469
        case Some(assgn) => assgn.is_finished
wenzelm@38370
   470
        case None => false
wenzelm@38370
   471
      }
wenzelm@38370
   472
wenzelm@44436
   473
    def is_stable(change: Change): Boolean =
wenzelm@44436
   474
      change.is_finished && is_assigned(change.version.get_finished)
wenzelm@44436
   475
wenzelm@46944
   476
    def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
wenzelm@44672
   477
    def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
wenzelm@44436
   478
    def tip_stable: Boolean = is_stable(history.tip)
wenzelm@44475
   479
    def tip_version: Version = history.tip.version.get_finished
wenzelm@44436
   480
wenzelm@44446
   481
    def continue_history(
wenzelm@44446
   482
        previous: Future[Version],
wenzelm@40479
   483
        edits: List[Edit_Text],
wenzelm@43722
   484
        version: Future[Version]): (Change, State) =
wenzelm@38841
   485
    {
wenzelm@46678
   486
      val change = Change.make(previous, edits, version)
wenzelm@38841
   487
      (change, copy(history = history + change))
wenzelm@38841
   488
    }
wenzelm@38841
   489
wenzelm@44672
   490
    def prune_history(retain: Int = 0): (List[Version], State) =
wenzelm@44672
   491
    {
wenzelm@46679
   492
      history.prune(is_stable, retain) match {
wenzelm@46679
   493
        case Some((dropped, history1)) =>
wenzelm@44672
   494
          val dropped_versions = dropped.map(change => change.version.get_finished)
wenzelm@46679
   495
          val state1 = copy(history = history1)
wenzelm@44672
   496
          (dropped_versions, state1)
wenzelm@46679
   497
        case None => fail
wenzelm@44672
   498
      }
wenzelm@44672
   499
    }
wenzelm@44672
   500
wenzelm@52530
   501
    def removed_versions(removed: List[Document_ID.Version]): State =
wenzelm@44676
   502
    {
wenzelm@44676
   503
      val versions1 = versions -- removed
wenzelm@44676
   504
      val assignments1 = assignments -- removed
wenzelm@52530
   505
      var commands1 = Map.empty[Document_ID.Command, Command.State]
wenzelm@52530
   506
      var execs1 = Map.empty[Document_ID.Exec, Command.State]
wenzelm@44676
   507
      for {
wenzelm@44676
   508
        (version_id, version) <- versions1.iterator
wenzelm@46997
   509
        command_execs = assignments1(version_id).command_execs
wenzelm@46723
   510
        (_, node) <- version.nodes.entries
wenzelm@44676
   511
        command <- node.commands.iterator
wenzelm@44676
   512
      } {
wenzelm@52568
   513
        if (!commands1.isDefinedAt(command.id))
wenzelm@52568
   514
          commands.get(command.id).foreach(st => commands1 += (command.id -> st))
wenzelm@52568
   515
        for (exec_id <- command_execs.getOrElse(command.id, Nil)) {
wenzelm@52527
   516
          if (!execs1.isDefinedAt(exec_id))
wenzelm@52527
   517
            execs.get(exec_id).foreach(st => execs1 += (exec_id -> st))
wenzelm@44676
   518
        }
wenzelm@44676
   519
      }
wenzelm@44676
   520
      copy(versions = versions1, commands = commands1, execs = execs1, assignments = assignments1)
wenzelm@44676
   521
    }
wenzelm@44676
   522
wenzelm@44613
   523
    def command_state(version: Version, command: Command): Command.State =
wenzelm@44613
   524
    {
wenzelm@44613
   525
      require(is_assigned(version))
wenzelm@44613
   526
      try {
wenzelm@52527
   527
        the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil)
wenzelm@52564
   528
          .map(the_dynamic_state(_)) match {
wenzelm@52527
   529
            case eval_state :: print_states => (eval_state /: print_states)(_ ++ _)
wenzelm@52527
   530
            case Nil => fail
wenzelm@52527
   531
          }
wenzelm@44613
   532
      }
wenzelm@47395
   533
      catch {
wenzelm@47395
   534
        case _: State.Fail =>
wenzelm@52564
   535
          try { the_static_state(command.id) }
wenzelm@49414
   536
          catch { case _: State.Fail => command.init_state }
wenzelm@47395
   537
      }
wenzelm@44613
   538
    }
wenzelm@44613
   539
wenzelm@49645
   540
    def markup_to_XML(version: Version, node: Node, filter: XML.Elem => Boolean): XML.Body =
wenzelm@49645
   541
      node.commands.toList.map(cmd => command_state(version, cmd).markup_to_XML(filter)).flatten
wenzelm@38841
   542
wenzelm@38841
   543
    // persistent user-view
wenzelm@49346
   544
    def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
wenzelm@49346
   545
      : Snapshot =
wenzelm@38370
   546
    {
wenzelm@44672
   547
      val stable = recent_stable
wenzelm@44436
   548
      val latest = history.tip
wenzelm@38841
   549
wenzelm@44156
   550
      // FIXME proper treatment of removed nodes
wenzelm@38841
   551
      val edits =
wenzelm@38841
   552
        (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
wenzelm@44156
   553
            (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
wenzelm@38841
   554
      lazy val reverse_edits = edits.reverse
wenzelm@38841
   555
wenzelm@38841
   556
      new Snapshot
wenzelm@38841
   557
      {
wenzelm@44582
   558
        val state = State.this
wenzelm@39698
   559
        val version = stable.version.get_finished
wenzelm@48923
   560
        val node_name = name
wenzelm@38841
   561
        val node = version.nodes(name)
wenzelm@38841
   562
        val is_outdated = !(pending_edits.isEmpty && latest == stable)
wenzelm@38841
   563
wenzelm@38841
   564
        def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
wenzelm@38841
   565
        def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
wenzelm@43425
   566
        def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
wenzelm@43425
   567
        def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
wenzelm@39177
   568
wenzelm@51494
   569
        def eq_content(other: Snapshot): Boolean =
wenzelm@49346
   570
          !is_outdated && !other.is_outdated &&
wenzelm@49346
   571
            node.commands.size == other.node.commands.size &&
wenzelm@49346
   572
            ((node.commands.iterator zip other.node.commands.iterator) forall {
wenzelm@49346
   573
              case (cmd1, cmd2) =>
wenzelm@51494
   574
                state.command_state(version, cmd1) eq_content
wenzelm@51494
   575
                  other.state.command_state(other.version, cmd2)
wenzelm@49346
   576
            })
wenzelm@49346
   577
wenzelm@46178
   578
        def cumulate_markup[A](range: Text.Range, info: A, elements: Option[Set[String]],
wenzelm@52900
   579
          result: Command.State => (A, Text.Markup) => Option[A]): List[Text.Info[A]] =
wenzelm@45459
   580
        {
wenzelm@45467
   581
          val former_range = revert(range)
wenzelm@52900
   582
          (for {
wenzelm@52900
   583
            (command, command_start) <- node.command_range(former_range)
wenzelm@50500
   584
            st = state.command_state(version, command)
wenzelm@50500
   585
            res = result(st)
wenzelm@52889
   586
            Text.Info(r0, a) <- st.markup.cumulate[A](
wenzelm@52889
   587
              (former_range - command_start).restrict(command.range), info, elements,
wenzelm@52900
   588
              { case (a, Text.Info(r0, b)) => res(a, Text.Info(convert(r0 + command_start), b)) }
wenzelm@52900
   589
            ).iterator
wenzelm@52900
   590
          } yield Text.Info(convert(r0 + command_start), a)).toList
wenzelm@45459
   591
        }
wenzelm@45459
   592
wenzelm@46178
   593
        def select_markup[A](range: Text.Range, elements: Option[Set[String]],
wenzelm@52900
   594
          result: Command.State => Text.Markup => Option[A]): List[Text.Info[A]] =
wenzelm@38845
   595
        {
wenzelm@52889
   596
          def result1(st: Command.State): (Option[A], Text.Markup) => Option[Option[A]] =
wenzelm@50500
   597
          {
wenzelm@50500
   598
            val res = result(st)
wenzelm@52889
   599
            (_: Option[A], x: Text.Markup) =>
wenzelm@52889
   600
              res(x) match {
wenzelm@52889
   601
                case None => None
wenzelm@52889
   602
                case some => Some(some)
wenzelm@52889
   603
              }
wenzelm@50500
   604
          }
wenzelm@46198
   605
          for (Text.Info(r, Some(x)) <- cumulate_markup(range, None, elements, result1))
wenzelm@46198
   606
            yield Text.Info(r, x)
wenzelm@38845
   607
        }
wenzelm@38841
   608
      }
wenzelm@38150
   609
    }
wenzelm@34485
   610
  }
wenzelm@34840
   611
}
wenzelm@34840
   612