src/Tools/VSCode/src/server.scala
author wenzelm
Mon Sep 18 18:19:06 2017 +0200 (22 months ago)
changeset 66676 39db5bb7eb0a
parent 66675 6f4613dbfef6
child 66677 fa70edfcb6fa
permissions -rw-r--r--
recode Unicode text on the spot, e.g. from copy-paste of output;
wenzelm@64605
     1
/*  Title:      Tools/VSCode/src/server.scala
wenzelm@64605
     2
    Author:     Makarius
wenzelm@64605
     3
wenzelm@65160
     4
Server for VS Code Language Server Protocol 2.0/3.0, see also
wenzelm@64605
     5
https://github.com/Microsoft/language-server-protocol
wenzelm@64605
     6
https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md
wenzelm@65160
     7
wenzelm@65160
     8
PIDE protocol extensions depend on system option "vscode_pide_extensions".
wenzelm@64605
     9
*/
wenzelm@64605
    10
wenzelm@64605
    11
package isabelle.vscode
wenzelm@64605
    12
wenzelm@64605
    13
wenzelm@64605
    14
import isabelle._
wenzelm@64605
    15
wenzelm@64710
    16
import java.io.{PrintStream, OutputStream, File => JFile}
wenzelm@64605
    17
wenzelm@64605
    18
import scala.annotation.tailrec
wenzelm@65234
    19
import scala.collection.mutable
wenzelm@64605
    20
wenzelm@64605
    21
wenzelm@64605
    22
object Server
wenzelm@64605
    23
{
wenzelm@66100
    24
  type Editor = isabelle.Editor[Unit]
wenzelm@66100
    25
wenzelm@66100
    26
wenzelm@64605
    27
  /* Isabelle tool wrapper */
wenzelm@64605
    28
wenzelm@64605
    29
  private lazy val default_logic = Isabelle_System.getenv("ISABELLE_LOGIC")
wenzelm@64605
    30
wenzelm@64605
    31
  val isabelle_tool = Isabelle_Tool("vscode_server", "VSCode Language Server for PIDE", args =>
wenzelm@64605
    32
  {
wenzelm@64644
    33
    try {
wenzelm@66241
    34
      var all_known = false
wenzelm@64644
    35
      var log_file: Option[Path] = None
wenzelm@64644
    36
      var dirs: List[Path] = Nil
wenzelm@64644
    37
      var logic = default_logic
wenzelm@64644
    38
      var modes: List[String] = Nil
wenzelm@64644
    39
      var options = Options.init()
wenzelm@64733
    40
      var system_mode = false
wenzelm@65922
    41
      var verbose = false
wenzelm@64605
    42
wenzelm@64644
    43
      val getopts = Getopts("""
wenzelm@64605
    44
Usage: isabelle vscode_server [OPTIONS]
wenzelm@64605
    45
wenzelm@64605
    46
  Options are:
wenzelm@66241
    47
    -A           explore theory name space of all known sessions (potentially slow)
wenzelm@64605
    48
    -L FILE      enable logging on FILE
wenzelm@64605
    49
    -d DIR       include session directory
wenzelm@64737
    50
    -l NAME      logic session name (default ISABELLE_LOGIC=""" + quote(default_logic) + """)
wenzelm@64605
    51
    -m MODE      add print mode for output
wenzelm@64605
    52
    -o OPTION    override Isabelle system OPTION (via NAME=VAL or NAME)
wenzelm@64733
    53
    -s           system build mode for session image
wenzelm@65922
    54
    -v           verbose logging
wenzelm@64605
    55
wenzelm@64605
    56
  Run the VSCode Language Server protocol (JSON RPC) over stdin/stdout.
wenzelm@64605
    57
""",
wenzelm@66241
    58
        "A" -> (_ => all_known = true),
wenzelm@64755
    59
        "L:" -> (arg => log_file = Some(Path.explode(File.standard_path(arg)))),
wenzelm@64755
    60
        "d:" -> (arg => dirs = dirs ::: List(Path.explode(File.standard_path(arg)))),
wenzelm@64644
    61
        "l:" -> (arg => logic = arg),
wenzelm@64644
    62
        "m:" -> (arg => modes = arg :: modes),
wenzelm@64733
    63
        "o:" -> (arg => options = options + arg),
wenzelm@65922
    64
        "s" -> (_ => system_mode = true),
wenzelm@65922
    65
        "v" -> (_ => verbose = true))
wenzelm@64605
    66
wenzelm@64644
    67
      val more_args = getopts(args)
wenzelm@64644
    68
      if (more_args.nonEmpty) getopts.usage()
wenzelm@64644
    69
wenzelm@64717
    70
      val log = Logger.make(log_file)
wenzelm@65922
    71
      val channel = new Channel(System.in, System.out, log, verbose)
wenzelm@66241
    72
      val server =
wenzelm@66241
    73
        new Server(channel, options, session_name = logic, session_dirs = dirs,
wenzelm@66241
    74
          all_known = all_known, modes = modes, system_mode = system_mode, log = log)
wenzelm@64605
    75
wenzelm@64644
    76
      // prevent spurious garbage on the main protocol channel
wenzelm@64644
    77
      val orig_out = System.out
wenzelm@64644
    78
      try {
wenzelm@64644
    79
        System.setOut(new PrintStream(new OutputStream { def write(n: Int) {} }))
wenzelm@64644
    80
        server.start()
wenzelm@64644
    81
      }
wenzelm@64644
    82
      finally { System.setOut(orig_out) }
wenzelm@64605
    83
    }
wenzelm@64644
    84
    catch {
wenzelm@64644
    85
      case exn: Throwable =>
wenzelm@64717
    86
        val channel = new Channel(System.in, System.out, No_Logger)
wenzelm@64644
    87
        channel.error_message(Exn.message(exn))
wenzelm@64644
    88
        throw(exn)
wenzelm@64644
    89
    }
wenzelm@64605
    90
  })
wenzelm@64605
    91
}
wenzelm@64605
    92
wenzelm@64605
    93
class Server(
wenzelm@65191
    94
  val channel: Channel,
wenzelm@64605
    95
  options: Options,
wenzelm@64605
    96
  session_name: String = Server.default_logic,
wenzelm@64605
    97
  session_dirs: List[Path] = Nil,
wenzelm@66241
    98
  all_known: Boolean = false,
wenzelm@64717
    99
  modes: List[String] = Nil,
wenzelm@64733
   100
  system_mode: Boolean = false,
wenzelm@64717
   101
  log: Logger = No_Logger)
wenzelm@64605
   102
{
wenzelm@66085
   103
  server =>
wenzelm@66085
   104
wenzelm@66085
   105
wenzelm@64725
   106
  /* prover session */
wenzelm@64605
   107
wenzelm@64703
   108
  private val session_ = Synchronized(None: Option[Session])
wenzelm@64703
   109
  def session: Session = session_.value getOrElse error("Server inactive")
wenzelm@64623
   110
  def resources: VSCode_Resources = session.resources.asInstanceOf[VSCode_Resources]
wenzelm@64605
   111
wenzelm@64651
   112
  def rendering_offset(node_pos: Line.Node_Position): Option[(VSCode_Rendering, Text.Offset)] =
wenzelm@64649
   113
    for {
wenzelm@64777
   114
      model <- resources.get_model(new JFile(node_pos.name))
wenzelm@64704
   115
      rendering = model.rendering()
wenzelm@64830
   116
      offset <- model.content.doc.offset(node_pos.pos)
wenzelm@64649
   117
    } yield (rendering, offset)
wenzelm@64649
   118
wenzelm@66085
   119
  private val dynamic_output = Dynamic_Output(server)
wenzelm@65191
   120
wenzelm@64605
   121
wenzelm@64725
   122
  /* input from client or file-system */
wenzelm@64725
   123
wenzelm@64800
   124
  private val delay_input: Standard_Thread.Delay =
wenzelm@64810
   125
    Standard_Thread.delay_last(options.seconds("vscode_input_delay"), channel.Error_Logger)
wenzelm@66676
   126
    { resources.flush_input(session, channel) }
wenzelm@64725
   127
wenzelm@64800
   128
  private val delay_load: Standard_Thread.Delay =
wenzelm@64810
   129
    Standard_Thread.delay_last(options.seconds("vscode_load_delay"), channel.Error_Logger) {
wenzelm@66100
   130
      val (invoke_input, invoke_load) =
wenzelm@66100
   131
        resources.resolve_dependencies(session, editor, file_watcher)
wenzelm@64800
   132
      if (invoke_input) delay_input.invoke()
wenzelm@64800
   133
      if (invoke_load) delay_load.invoke
wenzelm@64800
   134
    }
wenzelm@64727
   135
wenzelm@64857
   136
  private val file_watcher =
wenzelm@64727
   137
    File_Watcher(sync_documents(_), options.seconds("vscode_load_delay"))
wenzelm@64725
   138
wenzelm@65111
   139
  private def close_document(file: JFile)
wenzelm@65111
   140
  {
wenzelm@65111
   141
    if (resources.close_model(file)) {
wenzelm@65111
   142
      file_watcher.register_parent(file)
wenzelm@65116
   143
      sync_documents(Set(file))
wenzelm@65116
   144
      delay_input.invoke()
wenzelm@65116
   145
      delay_output.invoke()
wenzelm@65111
   146
    }
wenzelm@65111
   147
  }
wenzelm@65111
   148
wenzelm@65116
   149
  private def sync_documents(changed: Set[JFile])
wenzelm@65116
   150
  {
wenzelm@65116
   151
    resources.sync_models(changed)
wenzelm@65116
   152
    delay_input.invoke()
wenzelm@65116
   153
    delay_output.invoke()
wenzelm@65116
   154
  }
wenzelm@64679
   155
wenzelm@66674
   156
  private def change_document(file: JFile, version: Long, changes: List[Protocol.TextDocumentChange])
wenzelm@65160
   157
  {
wenzelm@65234
   158
    val norm_changes = new mutable.ListBuffer[Protocol.TextDocumentChange]
wenzelm@65234
   159
    @tailrec def norm(chs: List[Protocol.TextDocumentChange])
wenzelm@65234
   160
    {
wenzelm@65234
   161
      if (chs.nonEmpty) {
wenzelm@65234
   162
        val (full_texts, rest1) = chs.span(_.range.isEmpty)
wenzelm@65234
   163
        val (edits, rest2) = rest1.span(_.range.nonEmpty)
wenzelm@65234
   164
        norm_changes ++= full_texts
wenzelm@65234
   165
        norm_changes ++= edits.sortBy(_.range.get.start)(Line.Position.Ordering).reverse
wenzelm@65234
   166
        norm(rest2)
wenzelm@65234
   167
      }
wenzelm@65234
   168
    }
wenzelm@65234
   169
    norm(changes)
wenzelm@65234
   170
    norm_changes.foreach(change =>
wenzelm@66674
   171
      resources.change_model(session, editor, file, version, change.text, change.range))
wenzelm@65234
   172
wenzelm@64679
   173
    delay_input.invoke()
wenzelm@65111
   174
    delay_output.invoke()
wenzelm@64679
   175
  }
wenzelm@64679
   176
wenzelm@64710
   177
wenzelm@65189
   178
  /* caret handling */
wenzelm@65189
   179
wenzelm@65189
   180
  private val delay_caret_update: Standard_Thread.Delay =
wenzelm@65189
   181
    Standard_Thread.delay_last(options.seconds("vscode_input_delay"), channel.Error_Logger)
wenzelm@65189
   182
    { session.caret_focus.post(Session.Caret_Focus) }
wenzelm@65189
   183
wenzelm@65189
   184
  private def update_caret(caret: Option[(JFile, Line.Position)])
wenzelm@65189
   185
  {
wenzelm@65189
   186
    resources.update_caret(caret)
wenzelm@65189
   187
    delay_caret_update.invoke()
wenzelm@65926
   188
    delay_input.invoke()
wenzelm@65189
   189
  }
wenzelm@65189
   190
wenzelm@64679
   191
wenzelm@65983
   192
  /* preview */
wenzelm@65983
   193
wenzelm@66098
   194
  private lazy val preview_panel = new Preview_Panel(resources)
wenzelm@65983
   195
wenzelm@65983
   196
  private lazy val delay_preview: Standard_Thread.Delay =
wenzelm@65983
   197
    Standard_Thread.delay_last(options.seconds("vscode_output_delay"), channel.Error_Logger)
wenzelm@65983
   198
    {
wenzelm@66098
   199
      if (preview_panel.flush(channel)) delay_preview.invoke()
wenzelm@65983
   200
    }
wenzelm@65983
   201
wenzelm@65983
   202
  private def request_preview(file: JFile, column: Int)
wenzelm@65983
   203
  {
wenzelm@66098
   204
    preview_panel.request(file, column)
wenzelm@65983
   205
    delay_preview.invoke()
wenzelm@65983
   206
  }
wenzelm@65983
   207
wenzelm@65983
   208
wenzelm@64679
   209
  /* output to client */
wenzelm@64679
   210
wenzelm@64691
   211
  private val delay_output: Standard_Thread.Delay =
wenzelm@64810
   212
    Standard_Thread.delay_last(options.seconds("vscode_output_delay"), channel.Error_Logger)
wenzelm@64703
   213
    {
wenzelm@65232
   214
      if (resources.flush_output(channel)) delay_output.invoke()
wenzelm@64679
   215
    }
wenzelm@64679
   216
wenzelm@66138
   217
  def update_output(changed_nodes: Traversable[JFile])
wenzelm@66138
   218
  {
wenzelm@66138
   219
    resources.update_output(changed_nodes)
wenzelm@66138
   220
    delay_output.invoke()
wenzelm@66138
   221
  }
wenzelm@66138
   222
wenzelm@66138
   223
  def update_output_visible()
wenzelm@66138
   224
  {
wenzelm@66138
   225
    resources.update_output_visible()
wenzelm@66138
   226
    delay_output.invoke()
wenzelm@66138
   227
  }
wenzelm@66138
   228
wenzelm@64725
   229
  private val prover_output =
wenzelm@64725
   230
    Session.Consumer[Session.Commands_Changed](getClass.getName) {
wenzelm@65119
   231
      case changed =>
wenzelm@66138
   232
        update_output(changed.nodes.toList.map(resources.node_file(_)))
wenzelm@64725
   233
    }
wenzelm@64710
   234
wenzelm@66389
   235
  private val syslog_messages =
wenzelm@66389
   236
    Session.Consumer[Prover.Output](getClass.getName) {
wenzelm@66389
   237
      case output => channel.log_writeln(resources.output_xml(output.message))
wenzelm@64692
   238
    }
wenzelm@64692
   239
wenzelm@64692
   240
wenzelm@64605
   241
  /* init and exit */
wenzelm@64605
   242
wenzelm@64641
   243
  def init(id: Protocol.Id)
wenzelm@64605
   244
  {
wenzelm@64641
   245
    def reply(err: String)
wenzelm@64641
   246
    {
wenzelm@64641
   247
      channel.write(Protocol.Initialize.reply(id, err))
wenzelm@64642
   248
      if (err == "")
wenzelm@64642
   249
        channel.writeln("Welcome to Isabelle/" + session_name + " (" + Distribution.version + ")")
wenzelm@64642
   250
      else channel.error_message(err)
wenzelm@64641
   251
    }
wenzelm@64641
   252
wenzelm@64643
   253
    val try_session =
wenzelm@64643
   254
      try {
wenzelm@64733
   255
        if (!Build.build(options = options, build_heap = true, no_build = true,
wenzelm@64733
   256
              system_mode = system_mode, dirs = session_dirs, sessions = List(session_name)).ok)
wenzelm@64733
   257
        {
wenzelm@64733
   258
          val start_msg = "Build started for Isabelle/" + session_name + " ..."
wenzelm@64733
   259
          val fail_msg = "Session build failed -- prover process remains inactive!"
wenzelm@64733
   260
wenzelm@64733
   261
          val progress = channel.make_progress(verbose = true)
wenzelm@64733
   262
          progress.echo(start_msg); channel.writeln(start_msg)
wenzelm@64733
   263
wenzelm@64733
   264
          if (!Build.build(options = options, progress = progress, build_heap = true,
wenzelm@64733
   265
              system_mode = system_mode, dirs = session_dirs, sessions = List(session_name)).ok)
wenzelm@64733
   266
          {
wenzelm@64733
   267
            progress.echo(fail_msg); error(fail_msg)
wenzelm@64733
   268
          }
wenzelm@64733
   269
        }
wenzelm@64733
   270
wenzelm@65512
   271
        val session_base =
wenzelm@66241
   272
          Sessions.session_base(options, session_name, dirs = session_dirs, all_known = all_known)
wenzelm@65361
   273
        val resources = new VSCode_Resources(options, session_base, log)
wenzelm@64854
   274
          {
wenzelm@64727
   275
            override def commit(change: Session.Change): Unit =
wenzelm@64800
   276
              if (change.deps_changed || undefined_blobs(change.version.nodes).nonEmpty)
wenzelm@64800
   277
                delay_load.invoke()
wenzelm@64727
   278
          }
wenzelm@64605
   279
wenzelm@65272
   280
        val session_options = options.bool("editor_output_state") = true
wenzelm@65272
   281
        Some(new Session(session_options, resources))
wenzelm@64605
   282
      }
wenzelm@64643
   283
      catch { case ERROR(msg) => reply(msg); None }
wenzelm@64605
   284
wenzelm@64643
   285
    for (session <- try_session) {
wenzelm@65191
   286
      session_.change(_ => Some(session))
wenzelm@65191
   287
wenzelm@65227
   288
      session.commands_changed += prover_output
wenzelm@66389
   289
      session.syslog_messages += syslog_messages
wenzelm@65227
   290
wenzelm@65227
   291
      dynamic_output.init()
wenzelm@65227
   292
wenzelm@64643
   293
      var session_phase: Session.Consumer[Session.Phase] = null
wenzelm@64643
   294
      session_phase =
wenzelm@64643
   295
        Session.Consumer(getClass.getName) {
wenzelm@64643
   296
          case Session.Ready =>
wenzelm@64643
   297
            session.phase_changed -= session_phase
wenzelm@64643
   298
            reply("")
wenzelm@65317
   299
          case Session.Terminated(result) if !result.ok =>
wenzelm@64643
   300
            session.phase_changed -= session_phase
wenzelm@65317
   301
            reply("Prover startup failed: return code " + result.rc)
wenzelm@64643
   302
          case _ =>
wenzelm@64643
   303
        }
wenzelm@64643
   304
      session.phase_changed += session_phase
wenzelm@64605
   305
wenzelm@65216
   306
      Isabelle_Process.start(session, options,
wenzelm@65216
   307
        logic = session_name, dirs = session_dirs, modes = modes)
wenzelm@64643
   308
    }
wenzelm@64605
   309
  }
wenzelm@64605
   310
wenzelm@64641
   311
  def shutdown(id: Protocol.Id)
wenzelm@64605
   312
  {
wenzelm@64641
   313
    def reply(err: String): Unit = channel.write(Protocol.Shutdown.reply(id, err))
wenzelm@64641
   314
wenzelm@64703
   315
    session_.change({
wenzelm@64703
   316
      case Some(session) =>
wenzelm@65228
   317
        session.commands_changed -= prover_output
wenzelm@66389
   318
        session.syslog_messages -= syslog_messages
wenzelm@65228
   319
wenzelm@65191
   320
        dynamic_output.exit()
wenzelm@65228
   321
wenzelm@65228
   322
        delay_load.revoke()
wenzelm@65228
   323
        file_watcher.shutdown()
wenzelm@64703
   324
        delay_input.revoke()
wenzelm@64703
   325
        delay_output.revoke()
wenzelm@65228
   326
        delay_caret_update.revoke()
wenzelm@65983
   327
        delay_preview.revoke()
wenzelm@65228
   328
wenzelm@65228
   329
        val rc = session.stop()
wenzelm@65231
   330
        if (rc == 0) reply("") else reply("Prover shutdown failed: return code " + rc)
wenzelm@64703
   331
        None
wenzelm@64703
   332
      case None =>
wenzelm@64703
   333
        reply("Prover inactive")
wenzelm@64703
   334
        None
wenzelm@64703
   335
    })
wenzelm@64605
   336
  }
wenzelm@64605
   337
wenzelm@64646
   338
  def exit() {
wenzelm@64717
   339
    log("\n")
wenzelm@64703
   340
    sys.exit(if (session_.value.isDefined) 1 else 0)
wenzelm@64646
   341
  }
wenzelm@64605
   342
wenzelm@64605
   343
wenzelm@64877
   344
  /* completion */
wenzelm@64877
   345
wenzelm@64877
   346
  def completion(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64877
   347
  {
wenzelm@64877
   348
    val result =
wenzelm@64877
   349
      (for ((rendering, offset) <- rendering_offset(node_pos))
wenzelm@66054
   350
        yield rendering.completion(node_pos.pos, offset)) getOrElse Nil
wenzelm@64877
   351
    channel.write(Protocol.Completion.reply(id, result))
wenzelm@64877
   352
  }
wenzelm@64877
   353
wenzelm@64877
   354
wenzelm@66138
   355
  /* spell-checker dictionary */
wenzelm@66138
   356
wenzelm@66138
   357
  def update_dictionary(include: Boolean, permanent: Boolean)
wenzelm@66138
   358
  {
wenzelm@66138
   359
    for {
wenzelm@66138
   360
      spell_checker <- resources.spell_checker.get
wenzelm@66138
   361
      caret <- resources.get_caret()
wenzelm@66138
   362
      rendering = caret.model.rendering()
wenzelm@66138
   363
      range = rendering.before_caret_range(caret.offset)
wenzelm@66138
   364
      Text.Info(_, word) <- Spell_Checker.current_word(rendering, range)
wenzelm@66138
   365
    } {
wenzelm@66138
   366
      spell_checker.update(word, include, permanent)
wenzelm@66138
   367
      update_output_visible()
wenzelm@66138
   368
    }
wenzelm@66138
   369
  }
wenzelm@66138
   370
wenzelm@66138
   371
  def reset_dictionary()
wenzelm@66138
   372
  {
wenzelm@66138
   373
    for (spell_checker <- resources.spell_checker.get)
wenzelm@66138
   374
    {
wenzelm@66138
   375
      spell_checker.reset()
wenzelm@66138
   376
      update_output_visible()
wenzelm@66138
   377
    }
wenzelm@66138
   378
  }
wenzelm@66138
   379
wenzelm@66138
   380
wenzelm@64622
   381
  /* hover */
wenzelm@64605
   382
wenzelm@64651
   383
  def hover(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64641
   384
  {
wenzelm@64641
   385
    val result =
wenzelm@64641
   386
      for {
wenzelm@64651
   387
        (rendering, offset) <- rendering_offset(node_pos)
wenzelm@65134
   388
        info <- rendering.tooltips(VSCode_Rendering.tooltip_elements, Text.Range(offset, offset + 1))
wenzelm@64641
   389
      } yield {
wenzelm@65197
   390
        val range = rendering.model.content.doc.range(info.range)
wenzelm@64748
   391
        val contents =
wenzelm@65107
   392
          info.info.map(t => Protocol.MarkedString(resources.output_pretty_tooltip(List(t))))
wenzelm@64748
   393
        (range, contents)
wenzelm@64641
   394
      }
wenzelm@64641
   395
    channel.write(Protocol.Hover.reply(id, result))
wenzelm@64641
   396
  }
wenzelm@64605
   397
wenzelm@64605
   398
wenzelm@64648
   399
  /* goto definition */
wenzelm@64648
   400
wenzelm@64651
   401
  def goto_definition(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64648
   402
  {
wenzelm@64648
   403
    val result =
wenzelm@64651
   404
      (for ((rendering, offset) <- rendering_offset(node_pos))
wenzelm@64649
   405
        yield rendering.hyperlinks(Text.Range(offset, offset + 1))) getOrElse Nil
wenzelm@64648
   406
    channel.write(Protocol.GotoDefinition.reply(id, result))
wenzelm@64648
   407
  }
wenzelm@64648
   408
wenzelm@64648
   409
wenzelm@64767
   410
  /* document highlights */
wenzelm@64767
   411
wenzelm@64767
   412
  def document_highlights(id: Protocol.Id, node_pos: Line.Node_Position)
wenzelm@64767
   413
  {
wenzelm@64767
   414
    val result =
wenzelm@64767
   415
      (for ((rendering, offset) <- rendering_offset(node_pos))
wenzelm@64767
   416
        yield {
wenzelm@65197
   417
          val model = rendering.model
wenzelm@65197
   418
          rendering.caret_focus_ranges(Text.Range(offset, offset + 1), model.content.text_range)
wenzelm@65197
   419
            .map(r => Protocol.DocumentHighlight.text(model.content.doc.range(r)))
wenzelm@64767
   420
        }) getOrElse Nil
wenzelm@64767
   421
    channel.write(Protocol.DocumentHighlights.reply(id, result))
wenzelm@64767
   422
  }
wenzelm@64767
   423
wenzelm@64767
   424
wenzelm@64605
   425
  /* main loop */
wenzelm@64605
   426
wenzelm@64605
   427
  def start()
wenzelm@64605
   428
  {
wenzelm@64717
   429
    log("Server started " + Date.now())
wenzelm@64605
   430
wenzelm@64605
   431
    def handle(json: JSON.T)
wenzelm@64605
   432
    {
wenzelm@64605
   433
      try {
wenzelm@64605
   434
        json match {
wenzelm@64641
   435
          case Protocol.Initialize(id) => init(id)
wenzelm@65229
   436
          case Protocol.Initialized(()) =>
wenzelm@64641
   437
          case Protocol.Shutdown(id) => shutdown(id)
wenzelm@64645
   438
          case Protocol.Exit(()) => exit()
wenzelm@66674
   439
          case Protocol.DidOpenTextDocument(file, _, version, text) =>
wenzelm@66674
   440
            change_document(file, version, List(Protocol.TextDocumentChange(None, text)))
wenzelm@66674
   441
          case Protocol.DidChangeTextDocument(file, version, changes) =>
wenzelm@66674
   442
            change_document(file, version, changes)
wenzelm@65160
   443
          case Protocol.DidCloseTextDocument(file) => close_document(file)
wenzelm@64877
   444
          case Protocol.Completion(id, node_pos) => completion(id, node_pos)
wenzelm@66138
   445
          case Protocol.Include_Word(()) => update_dictionary(true, false)
wenzelm@66138
   446
          case Protocol.Include_Word_Permanently(()) => update_dictionary(true, true)
wenzelm@66138
   447
          case Protocol.Exclude_Word(()) => update_dictionary(false, false)
wenzelm@66138
   448
          case Protocol.Exclude_Word_Permanently(()) => update_dictionary(false, true)
wenzelm@66138
   449
          case Protocol.Reset_Words(()) => reset_dictionary()
wenzelm@64651
   450
          case Protocol.Hover(id, node_pos) => hover(id, node_pos)
wenzelm@64651
   451
          case Protocol.GotoDefinition(id, node_pos) => goto_definition(id, node_pos)
wenzelm@64767
   452
          case Protocol.DocumentHighlights(id, node_pos) => document_highlights(id, node_pos)
wenzelm@65189
   453
          case Protocol.Caret_Update(caret) => update_caret(caret)
wenzelm@66098
   454
          case Protocol.State_Init(()) => State_Panel.init(server)
wenzelm@66098
   455
          case Protocol.State_Exit(id) => State_Panel.exit(id)
wenzelm@66098
   456
          case Protocol.State_Locate(id) => State_Panel.locate(id)
wenzelm@66098
   457
          case Protocol.State_Update(id) => State_Panel.update(id)
wenzelm@66211
   458
          case Protocol.State_Auto_Update(id, enabled) => State_Panel.auto_update(id, enabled)
wenzelm@65983
   459
          case Protocol.Preview_Request(file, column) => request_preview(file, column)
wenzelm@66052
   460
          case Protocol.Symbols_Request(()) => channel.write(Protocol.Symbols())
wenzelm@66675
   461
          case _ => if (!Protocol.ResponseMessage.is_empty(json)) log("### IGNORED")
wenzelm@64605
   462
        }
wenzelm@64605
   463
      }
wenzelm@64687
   464
      catch { case exn: Throwable => channel.log_error_message(Exn.message(exn)) }
wenzelm@64605
   465
    }
wenzelm@64605
   466
wenzelm@64605
   467
    @tailrec def loop()
wenzelm@64605
   468
    {
wenzelm@64605
   469
      channel.read() match {
wenzelm@64605
   470
        case Some(json) =>
wenzelm@64605
   471
          json match {
wenzelm@64605
   472
            case bulk: List[_] => bulk.foreach(handle(_))
wenzelm@64605
   473
            case _ => handle(json)
wenzelm@64605
   474
          }
wenzelm@64605
   475
          loop()
wenzelm@64717
   476
        case None => log("### TERMINATE")
wenzelm@64605
   477
      }
wenzelm@64605
   478
    }
wenzelm@64605
   479
    loop()
wenzelm@64605
   480
  }
wenzelm@66085
   481
wenzelm@66085
   482
wenzelm@66085
   483
  /* abstract editor operations */
wenzelm@66085
   484
wenzelm@66100
   485
  object editor extends Server.Editor
wenzelm@66085
   486
  {
wenzelm@66101
   487
    /* session */
wenzelm@66101
   488
wenzelm@66085
   489
    override def session: Session = server.session
wenzelm@66676
   490
    override def flush(): Unit = resources.flush_input(session, channel)
wenzelm@66085
   491
    override def invoke(): Unit = delay_input.invoke()
wenzelm@66085
   492
wenzelm@66101
   493
wenzelm@66101
   494
    /* current situation */
wenzelm@66101
   495
wenzelm@66085
   496
    override def current_node(context: Unit): Option[Document.Node.Name] =
wenzelm@66086
   497
      resources.get_caret().map(_.model.node_name)
wenzelm@66085
   498
    override def current_node_snapshot(context: Unit): Option[Document.Snapshot] =
wenzelm@66086
   499
      resources.get_caret().map(_.model.snapshot())
wenzelm@66086
   500
wenzelm@66085
   501
    override def node_snapshot(name: Document.Node.Name): Document.Snapshot =
wenzelm@66085
   502
    {
wenzelm@66085
   503
      resources.get_model(name) match {
wenzelm@66085
   504
        case Some(model) => model.snapshot()
wenzelm@66085
   505
        case None => session.snapshot(name)
wenzelm@66085
   506
      }
wenzelm@66085
   507
    }
wenzelm@66085
   508
wenzelm@66085
   509
    def current_command(snapshot: Document.Snapshot): Option[Command] =
wenzelm@66085
   510
    {
wenzelm@66085
   511
      resources.get_caret() match {
wenzelm@66086
   512
        case Some(caret) => snapshot.current_command(caret.node_name, caret.offset)
wenzelm@66085
   513
        case None => None
wenzelm@66085
   514
      }
wenzelm@66085
   515
    }
wenzelm@66085
   516
    override def current_command(context: Unit, snapshot: Document.Snapshot): Option[Command] =
wenzelm@66085
   517
      current_command(snapshot)
wenzelm@66085
   518
wenzelm@66101
   519
wenzelm@66101
   520
    /* overlays */
wenzelm@66101
   521
wenzelm@66101
   522
    override def node_overlays(name: Document.Node.Name): Document.Node.Overlays =
wenzelm@66101
   523
      resources.node_overlays(name)
wenzelm@66101
   524
wenzelm@66101
   525
    override def insert_overlay(command: Command, fn: String, args: List[String]): Unit =
wenzelm@66101
   526
      resources.insert_overlay(command, fn, args)
wenzelm@66101
   527
wenzelm@66101
   528
    override def remove_overlay(command: Command, fn: String, args: List[String]): Unit =
wenzelm@66101
   529
      resources.remove_overlay(command, fn, args)
wenzelm@66101
   530
wenzelm@66101
   531
wenzelm@66101
   532
    /* hyperlinks */
wenzelm@66101
   533
wenzelm@66085
   534
    override def hyperlink_command(
wenzelm@66215
   535
      focus: Boolean, snapshot: Document.Snapshot, id: Document_ID.Generic,
wenzelm@66215
   536
      offset: Symbol.Offset = 0): Option[Hyperlink] =
wenzelm@66215
   537
    {
wenzelm@66215
   538
      if (snapshot.is_outdated) None
wenzelm@66216
   539
      else
wenzelm@66216
   540
        snapshot.find_command_position(id, offset).map(node_pos =>
wenzelm@66216
   541
          new Hyperlink {
wenzelm@66216
   542
            def follow(unit: Unit) { channel.write(Protocol.Caret_Update(node_pos, focus)) }
wenzelm@66216
   543
          })
wenzelm@66215
   544
    }
wenzelm@66094
   545
wenzelm@66101
   546
wenzelm@66101
   547
    /* dispatcher thread */
wenzelm@66101
   548
wenzelm@66094
   549
    override def assert_dispatcher[A](body: => A): A = session.assert_dispatcher(body)
wenzelm@66094
   550
    override def require_dispatcher[A](body: => A): A = session.require_dispatcher(body)
wenzelm@66094
   551
    override def send_dispatcher(body: => Unit): Unit = session.send_dispatcher(body)
wenzelm@66094
   552
    override def send_wait_dispatcher(body: => Unit): Unit = session.send_wait_dispatcher(body)
wenzelm@66085
   553
  }
wenzelm@64605
   554
}