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