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