1
1
package org.jetbrains.kotlin.jupyter
2
2
3
3
import jupyter.kotlin.textResult
4
+ import org.jetbrains.kotlin.jupyter.repl.completion.CompletionResult
5
+ import org.jetbrains.kotlin.jupyter.repl.completion.KotlinCompleter
6
+ import org.jetbrains.kotlin.jupyter.repl.completion.ListErrorsResult
7
+ import org.jetbrains.kotlin.jupyter.repl.completion.SourceCodeImpl
8
+ import kotlin.script.experimental.api.ScriptDiagnostic
9
+ import kotlin.script.experimental.api.SourceCode
10
+ import kotlin.script.experimental.api.SourceCodeCompletionVariant
11
+ import kotlin.script.experimental.jvm.util.toSourceCodePosition
4
12
5
13
enum class ReplCommands (val desc : String ) {
6
14
help(" display help" ),
@@ -9,17 +17,43 @@ enum class ReplCommands(val desc: String) {
9
17
10
18
fun isCommand (code : String ): Boolean = code.startsWith(" :" )
11
19
20
+ fun getCommand (string : String ): ReplCommands ? {
21
+ return try {
22
+ ReplCommands .valueOf(string)
23
+ } catch (e: IllegalArgumentException ) {
24
+ null
25
+ }
26
+ }
27
+
12
28
fun <T > Iterable<T>.joinToStringIndented (transform : ((T ) -> CharSequence )? = null) = joinToString(" \n " , prefix = " " , transform = transform)
13
29
30
+ fun reportCommandErrors (code : String ): ListErrorsResult {
31
+ val commandString = code.trim().substring(1 )
32
+ val command = getCommand(commandString)
33
+ if (command != null ) return ListErrorsResult (code)
34
+
35
+ val sourceCode = SourceCodeImpl (0 , code)
36
+ val location = SourceCode .Location (
37
+ 0 .toSourceCodePosition(sourceCode),
38
+ (commandString.length + 1 ).toSourceCodePosition(sourceCode)
39
+ )
40
+ return ListErrorsResult (code, sequenceOf(
41
+ ScriptDiagnostic (ScriptDiagnostic .unspecifiedError, " Unknown command" , location = location)
42
+ ))
43
+ }
44
+
45
+ fun doCommandCompletion (code : String , cursor : Int ): CompletionResult {
46
+ val prefix = code.substring(1 , cursor)
47
+ val suitableCommands = ReplCommands .values().filter { it.name.startsWith(prefix) }
48
+ val completions = suitableCommands.map {
49
+ SourceCodeCompletionVariant (it.name, it.name, " command" , " command" )
50
+ }
51
+ return KotlinCompleter .getResult(code, cursor, completions)
52
+ }
53
+
14
54
fun runCommand (code : String , repl : ReplForJupyter ? ): Response {
15
55
val args = code.trim().substring(1 ).split(" " )
16
- val cmd =
17
- try {
18
- ReplCommands .valueOf(args[0 ])
19
- }
20
- catch (e: IllegalArgumentException ) {
21
- return AbortResponseWithMessage (textResult(" Failed!" ), " unknown command: $code \n to see available commands, enter :help" )
22
- }
56
+ val cmd = getCommand(args[0 ]) ? : return AbortResponseWithMessage (textResult(" Failed!" ), " unknown command: $code \n to see available commands, enter :help" )
23
57
return when (cmd) {
24
58
ReplCommands .classpath -> {
25
59
val cp = repl!! .currentClasspath
0 commit comments