src/Pure/PIDE/document.scala
author wenzelm
Mon Aug 12 11:49:58 2013 +0200 (2013-08-12)
changeset 52972 8fd8e1c14988
parent 52918 038458a4d11b
child 52976 c3d82d58beaf
permissions -rw-r--r--
tuned signature;
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@52918
   199
      if (new_commands eq _commands.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@52972
   327
  object Snapshot
wenzelm@52972
   328
  {
wenzelm@52972
   329
    val init = State.init.snapshot()
wenzelm@52972
   330
  }
wenzelm@52972
   331
wenzelm@38424
   332
  abstract class Snapshot
wenzelm@38424
   333
  {
wenzelm@44582
   334
    val state: State
wenzelm@38424
   335
    val version: Version
wenzelm@38424
   336
    val is_outdated: Boolean
wenzelm@38427
   337
    def convert(i: Text.Offset): Text.Offset
wenzelm@52889
   338
    def revert(i: Text.Offset): Text.Offset
wenzelm@39177
   339
    def convert(range: Text.Range): Text.Range
wenzelm@39177
   340
    def revert(range: Text.Range): Text.Range
wenzelm@52972
   341
wenzelm@52972
   342
    val node_name: Node.Name
wenzelm@52972
   343
    val node: Node
wenzelm@51494
   344
    def eq_content(other: Snapshot): Boolean
wenzelm@52508
   345
    def cumulate_markup[A](
wenzelm@52508
   346
      range: Text.Range,
wenzelm@52508
   347
      info: A,
wenzelm@52508
   348
      elements: Option[Set[String]],
wenzelm@52900
   349
      result: Command.State => (A, Text.Markup) => Option[A]): List[Text.Info[A]]
wenzelm@52508
   350
    def select_markup[A](
wenzelm@52508
   351
      range: Text.Range,
wenzelm@52508
   352
      elements: Option[Set[String]],
wenzelm@52900
   353
      result: Command.State => Text.Markup => Option[A]): List[Text.Info[A]]
wenzelm@38424
   354
  }
wenzelm@38424
   355
wenzelm@52563
   356
  type Assign_Update =
wenzelm@52563
   357
    List[(Document_ID.Command, List[Document_ID.Exec])]  // update of exec state assignment
wenzelm@44476
   358
wenzelm@38370
   359
  object State
wenzelm@38370
   360
  {
wenzelm@38373
   361
    class Fail(state: State) extends Exception
wenzelm@38373
   362
wenzelm@44479
   363
    object Assignment
wenzelm@44479
   364
    {
wenzelm@46683
   365
      val init: Assignment = new Assignment()
wenzelm@44479
   366
    }
wenzelm@38370
   367
wenzelm@46712
   368
    final class Assignment private(
wenzelm@52530
   369
      val command_execs: Map[Document_ID.Command, List[Document_ID.Exec]] = Map.empty,
wenzelm@46677
   370
      val is_finished: Boolean = false)
wenzelm@38370
   371
    {
wenzelm@44477
   372
      def check_finished: Assignment = { require(is_finished); this }
wenzelm@47388
   373
      def unfinished: Assignment = new Assignment(command_execs, false)
wenzelm@44479
   374
wenzelm@52563
   375
      def assign(update: Assign_Update): Assignment =
wenzelm@38370
   376
      {
wenzelm@38976
   377
        require(!is_finished)
wenzelm@44479
   378
        val command_execs1 =
wenzelm@52563
   379
          (command_execs /: update) {
wenzelm@52563
   380
            case (res, (command_id, exec_ids)) =>
wenzelm@52563
   381
              if (exec_ids.isEmpty) res - command_id
wenzelm@52563
   382
              else res + (command_id -> exec_ids)
wenzelm@44479
   383
          }
wenzelm@47388
   384
        new Assignment(command_execs1, true)
wenzelm@38150
   385
      }
wenzelm@38370
   386
    }
wenzelm@46682
   387
wenzelm@46682
   388
    val init: State =
wenzelm@52563
   389
      State().define_version(Version.init, Assignment.init).assign(Version.init.id, Nil)._2
wenzelm@38370
   390
  }
wenzelm@38370
   391
wenzelm@46712
   392
  final case class State private(
wenzelm@52530
   393
    val versions: Map[Document_ID.Version, Version] = Map.empty,
wenzelm@52530
   394
    val commands: Map[Document_ID.Command, Command.State] = Map.empty,  // static markup from define_command
wenzelm@52530
   395
    val execs: Map[Document_ID.Exec, Command.State] = Map.empty,  // dynamic markup from execution
wenzelm@52530
   396
    val assignments: Map[Document_ID.Version, State.Assignment] = Map.empty,
wenzelm@38841
   397
    val history: History = History.init)
wenzelm@38370
   398
  {
wenzelm@38373
   399
    private def fail[A]: A = throw new State.Fail(this)
wenzelm@38370
   400
wenzelm@44479
   401
    def define_version(version: Version, assignment: State.Assignment): State =
wenzelm@38370
   402
    {
wenzelm@38417
   403
      val id = version.id
wenzelm@38417
   404
      copy(versions = versions + (id -> version),
wenzelm@44479
   405
        assignments = assignments + (id -> assignment.unfinished))
wenzelm@38370
   406
    }
wenzelm@38370
   407
wenzelm@38373
   408
    def define_command(command: Command): State =
wenzelm@38373
   409
    {
wenzelm@38373
   410
      val id = command.id
wenzelm@49414
   411
      copy(commands = commands + (id -> command.init_state))
wenzelm@38373
   412
    }
wenzelm@38373
   413
wenzelm@52530
   414
    def defined_command(id: Document_ID.Command): Boolean = commands.isDefinedAt(id)
wenzelm@44582
   415
wenzelm@52531
   416
    def find_command(version: Version, id: Document_ID.Generic): Option[(Node, Command)] =
wenzelm@44582
   417
      commands.get(id) orElse execs.get(id) match {
wenzelm@44582
   418
        case None => None
wenzelm@44582
   419
        case Some(st) =>
wenzelm@44582
   420
          val command = st.command
wenzelm@46681
   421
          val node = version.nodes(command.node_name)
wenzelm@46681
   422
          Some((node, command))
wenzelm@44582
   423
      }
wenzelm@38373
   424
wenzelm@52530
   425
    def the_version(id: Document_ID.Version): Version = versions.getOrElse(id, fail)
wenzelm@52564
   426
    def the_static_state(id: Document_ID.Command): Command.State = commands.getOrElse(id, fail)
wenzelm@52564
   427
    def the_dynamic_state(id: Document_ID.Exec): Command.State = execs.getOrElse(id, fail)
wenzelm@52563
   428
    def the_assignment(version: Version): State.Assignment = assignments.getOrElse(version.id, fail)
wenzelm@38370
   429
wenzelm@52531
   430
    def accumulate(id: Document_ID.Generic, message: XML.Elem): (Command.State, State) =
wenzelm@38370
   431
      execs.get(id) match {
wenzelm@44446
   432
        case Some(st) =>
wenzelm@49527
   433
          val new_st = st + (id, message)
wenzelm@44446
   434
          (new_st, copy(execs = execs + (id -> new_st)))
wenzelm@38370
   435
        case None =>
wenzelm@38370
   436
          commands.get(id) match {
wenzelm@38370
   437
            case Some(st) =>
wenzelm@49527
   438
              val new_st = st + (id, message)
wenzelm@38370
   439
              (new_st, copy(commands = commands + (id -> new_st)))
wenzelm@38370
   440
            case None => fail
wenzelm@38370
   441
          }
wenzelm@38370
   442
      }
wenzelm@38370
   443
wenzelm@52563
   444
    def assign(id: Document_ID.Version, update: Assign_Update): (List[Command], State) =
wenzelm@38370
   445
    {
wenzelm@38417
   446
      val version = the_version(id)
wenzelm@38370
   447
wenzelm@52566
   448
      def upd(exec_id: Document_ID.Exec, st: Command.State)
wenzelm@52566
   449
          : Option[(Document_ID.Exec, Command.State)] =
wenzelm@52566
   450
        if (execs.isDefinedAt(exec_id)) None else Some(exec_id -> st)
wenzelm@52566
   451
wenzelm@44543
   452
      val (changed_commands, new_execs) =
wenzelm@52563
   453
        ((Nil: List[Command], execs) /: update) {
wenzelm@52566
   454
          case ((commands1, execs1), (command_id, exec)) =>
wenzelm@52566
   455
            val st = the_static_state(command_id)
wenzelm@52566
   456
            val command = st.command
wenzelm@52527
   457
            val commands2 = command :: commands1
wenzelm@44543
   458
            val execs2 =
wenzelm@44543
   459
              exec match {
wenzelm@52527
   460
                case Nil => execs1
wenzelm@52527
   461
                case eval_id :: print_ids =>
wenzelm@52566
   462
                  execs1 ++ upd(eval_id, st) ++
wenzelm@52566
   463
                    (for (id <- print_ids; up <- upd(id, command.empty_state)) yield up)
wenzelm@44543
   464
              }
wenzelm@44543
   465
            (commands2, execs2)
wenzelm@38370
   466
        }
wenzelm@52563
   467
      val new_assignment = the_assignment(version).assign(update)
wenzelm@43722
   468
      val new_state = copy(assignments = assignments + (id -> new_assignment), execs = new_execs)
wenzelm@44476
   469
wenzelm@44543
   470
      (changed_commands, new_state)
wenzelm@38370
   471
    }
wenzelm@38370
   472
wenzelm@38417
   473
    def is_assigned(version: Version): Boolean =
wenzelm@43722
   474
      assignments.get(version.id) match {
wenzelm@38370
   475
        case Some(assgn) => assgn.is_finished
wenzelm@38370
   476
        case None => false
wenzelm@38370
   477
      }
wenzelm@38370
   478
wenzelm@44436
   479
    def is_stable(change: Change): Boolean =
wenzelm@44436
   480
      change.is_finished && is_assigned(change.version.get_finished)
wenzelm@44436
   481
wenzelm@46944
   482
    def recent_finished: Change = history.undo_list.find(_.is_finished) getOrElse fail
wenzelm@44672
   483
    def recent_stable: Change = history.undo_list.find(is_stable) getOrElse fail
wenzelm@44436
   484
    def tip_stable: Boolean = is_stable(history.tip)
wenzelm@44475
   485
    def tip_version: Version = history.tip.version.get_finished
wenzelm@44436
   486
wenzelm@44446
   487
    def continue_history(
wenzelm@44446
   488
        previous: Future[Version],
wenzelm@40479
   489
        edits: List[Edit_Text],
wenzelm@43722
   490
        version: Future[Version]): (Change, State) =
wenzelm@38841
   491
    {
wenzelm@46678
   492
      val change = Change.make(previous, edits, version)
wenzelm@38841
   493
      (change, copy(history = history + change))
wenzelm@38841
   494
    }
wenzelm@38841
   495
wenzelm@44672
   496
    def prune_history(retain: Int = 0): (List[Version], State) =
wenzelm@44672
   497
    {
wenzelm@46679
   498
      history.prune(is_stable, retain) match {
wenzelm@46679
   499
        case Some((dropped, history1)) =>
wenzelm@44672
   500
          val dropped_versions = dropped.map(change => change.version.get_finished)
wenzelm@46679
   501
          val state1 = copy(history = history1)
wenzelm@44672
   502
          (dropped_versions, state1)
wenzelm@46679
   503
        case None => fail
wenzelm@44672
   504
      }
wenzelm@44672
   505
    }
wenzelm@44672
   506
wenzelm@52530
   507
    def removed_versions(removed: List[Document_ID.Version]): State =
wenzelm@44676
   508
    {
wenzelm@44676
   509
      val versions1 = versions -- removed
wenzelm@44676
   510
      val assignments1 = assignments -- removed
wenzelm@52530
   511
      var commands1 = Map.empty[Document_ID.Command, Command.State]
wenzelm@52530
   512
      var execs1 = Map.empty[Document_ID.Exec, Command.State]
wenzelm@44676
   513
      for {
wenzelm@44676
   514
        (version_id, version) <- versions1.iterator
wenzelm@46997
   515
        command_execs = assignments1(version_id).command_execs
wenzelm@46723
   516
        (_, node) <- version.nodes.entries
wenzelm@44676
   517
        command <- node.commands.iterator
wenzelm@44676
   518
      } {
wenzelm@52568
   519
        if (!commands1.isDefinedAt(command.id))
wenzelm@52568
   520
          commands.get(command.id).foreach(st => commands1 += (command.id -> st))
wenzelm@52568
   521
        for (exec_id <- command_execs.getOrElse(command.id, Nil)) {
wenzelm@52527
   522
          if (!execs1.isDefinedAt(exec_id))
wenzelm@52527
   523
            execs.get(exec_id).foreach(st => execs1 += (exec_id -> st))
wenzelm@44676
   524
        }
wenzelm@44676
   525
      }
wenzelm@44676
   526
      copy(versions = versions1, commands = commands1, execs = execs1, assignments = assignments1)
wenzelm@44676
   527
    }
wenzelm@44676
   528
wenzelm@44613
   529
    def command_state(version: Version, command: Command): Command.State =
wenzelm@44613
   530
    {
wenzelm@44613
   531
      require(is_assigned(version))
wenzelm@44613
   532
      try {
wenzelm@52527
   533
        the_assignment(version).check_finished.command_execs.getOrElse(command.id, Nil)
wenzelm@52564
   534
          .map(the_dynamic_state(_)) match {
wenzelm@52527
   535
            case eval_state :: print_states => (eval_state /: print_states)(_ ++ _)
wenzelm@52527
   536
            case Nil => fail
wenzelm@52527
   537
          }
wenzelm@44613
   538
      }
wenzelm@47395
   539
      catch {
wenzelm@47395
   540
        case _: State.Fail =>
wenzelm@52564
   541
          try { the_static_state(command.id) }
wenzelm@49414
   542
          catch { case _: State.Fail => command.init_state }
wenzelm@47395
   543
      }
wenzelm@44613
   544
    }
wenzelm@44613
   545
wenzelm@49645
   546
    def markup_to_XML(version: Version, node: Node, filter: XML.Elem => Boolean): XML.Body =
wenzelm@49645
   547
      node.commands.toList.map(cmd => command_state(version, cmd).markup_to_XML(filter)).flatten
wenzelm@38841
   548
wenzelm@38841
   549
    // persistent user-view
wenzelm@49346
   550
    def snapshot(name: Node.Name = Node.Name.empty, pending_edits: List[Text.Edit] = Nil)
wenzelm@49346
   551
      : Snapshot =
wenzelm@38370
   552
    {
wenzelm@44672
   553
      val stable = recent_stable
wenzelm@44436
   554
      val latest = history.tip
wenzelm@38841
   555
wenzelm@44156
   556
      // FIXME proper treatment of removed nodes
wenzelm@38841
   557
      val edits =
wenzelm@38841
   558
        (pending_edits /: history.undo_list.takeWhile(_ != stable))((edits, change) =>
wenzelm@44156
   559
            (for ((a, Node.Edits(es)) <- change.edits if a == name) yield es).flatten ::: edits)
wenzelm@38841
   560
      lazy val reverse_edits = edits.reverse
wenzelm@38841
   561
wenzelm@38841
   562
      new Snapshot
wenzelm@38841
   563
      {
wenzelm@52972
   564
        /* global information */
wenzelm@52972
   565
wenzelm@44582
   566
        val state = State.this
wenzelm@39698
   567
        val version = stable.version.get_finished
wenzelm@38841
   568
        val is_outdated = !(pending_edits.isEmpty && latest == stable)
wenzelm@38841
   569
wenzelm@38841
   570
        def convert(offset: Text.Offset) = (offset /: edits)((i, edit) => edit.convert(i))
wenzelm@38841
   571
        def revert(offset: Text.Offset) = (offset /: reverse_edits)((i, edit) => edit.revert(i))
wenzelm@43425
   572
        def convert(range: Text.Range) = (range /: edits)((r, edit) => edit.convert(r))
wenzelm@43425
   573
        def revert(range: Text.Range) = (range /: reverse_edits)((r, edit) => edit.revert(r))
wenzelm@39177
   574
wenzelm@52972
   575
wenzelm@52972
   576
        /* local node content */
wenzelm@52972
   577
wenzelm@52972
   578
        val node_name = name
wenzelm@52972
   579
        val node = version.nodes(name)
wenzelm@52972
   580
wenzelm@51494
   581
        def eq_content(other: Snapshot): Boolean =
wenzelm@49346
   582
          !is_outdated && !other.is_outdated &&
wenzelm@49346
   583
            node.commands.size == other.node.commands.size &&
wenzelm@49346
   584
            ((node.commands.iterator zip other.node.commands.iterator) forall {
wenzelm@49346
   585
              case (cmd1, cmd2) =>
wenzelm@51494
   586
                state.command_state(version, cmd1) eq_content
wenzelm@51494
   587
                  other.state.command_state(other.version, cmd2)
wenzelm@49346
   588
            })
wenzelm@49346
   589
wenzelm@46178
   590
        def cumulate_markup[A](range: Text.Range, info: A, elements: Option[Set[String]],
wenzelm@52900
   591
          result: Command.State => (A, Text.Markup) => Option[A]): List[Text.Info[A]] =
wenzelm@45459
   592
        {
wenzelm@45467
   593
          val former_range = revert(range)
wenzelm@52900
   594
          (for {
wenzelm@52900
   595
            (command, command_start) <- node.command_range(former_range)
wenzelm@50500
   596
            st = state.command_state(version, command)
wenzelm@50500
   597
            res = result(st)
wenzelm@52889
   598
            Text.Info(r0, a) <- st.markup.cumulate[A](
wenzelm@52889
   599
              (former_range - command_start).restrict(command.range), info, elements,
wenzelm@52900
   600
              { case (a, Text.Info(r0, b)) => res(a, Text.Info(convert(r0 + command_start), b)) }
wenzelm@52900
   601
            ).iterator
wenzelm@52900
   602
          } yield Text.Info(convert(r0 + command_start), a)).toList
wenzelm@45459
   603
        }
wenzelm@45459
   604
wenzelm@46178
   605
        def select_markup[A](range: Text.Range, elements: Option[Set[String]],
wenzelm@52900
   606
          result: Command.State => Text.Markup => Option[A]): List[Text.Info[A]] =
wenzelm@38845
   607
        {
wenzelm@52889
   608
          def result1(st: Command.State): (Option[A], Text.Markup) => Option[Option[A]] =
wenzelm@50500
   609
          {
wenzelm@50500
   610
            val res = result(st)
wenzelm@52889
   611
            (_: Option[A], x: Text.Markup) =>
wenzelm@52889
   612
              res(x) match {
wenzelm@52889
   613
                case None => None
wenzelm@52889
   614
                case some => Some(some)
wenzelm@52889
   615
              }
wenzelm@50500
   616
          }
wenzelm@46198
   617
          for (Text.Info(r, Some(x)) <- cumulate_markup(range, None, elements, result1))
wenzelm@46198
   618
            yield Text.Info(r, x)
wenzelm@38845
   619
        }
wenzelm@38841
   620
      }
wenzelm@38150
   621
    }
wenzelm@34485
   622
  }
wenzelm@34840
   623
}
wenzelm@34840
   624