scoop:scoop.readline:0.1.0
src/editor.scoop
Selected production source · src/editor.scoop
1
package scoop.readline3
import scoop.readline.history.*4
import scoop.platform.fs.Path5
import scoop.platform.io.*6
import scoop.platform.env.environmentVariable7
import scoop.terminal.TerminalSession8
import scoop.terminal.StandardStream9
import scoop.terminal.isTerminal10
import scoop.terminal.event.KeyEvent11
import scoop.time.Duration13
/** A reusable Unix line editor with pluggable history and independent extension callbacks. */14
public class Editor public constructor(15
public val config: Config = readlineConfig(),16
public val history: History = FileHistory(config)17
) {18
public var completer: Completer = NoCompleter19
public var hinter: Hinter = NoHinter20
public var highlighter: Highlighter = PlainHighlighter21
public var validator: Validator = AcceptAll22
private val bindings: ArrayList<KeyBinding> = ArrayList<KeyBinding>()23
private val killRing: KillRing = KillRing()24
private var active: Boolean = false25
private var printer: ExternalPrinter? = None27
/** Creates a printer that can be shared with worker threads before reading begins. */28
public fun createExternalPrinter(): ExternalPrinter {29
when (printer) {30
case Some(val value) -> return value31
case None -> {32
val value = ExternalPrinter()33
printer = Some(value)34
return value35
}36
}37
}39
/** Creates the event-driven editor used by the terminal adapter. */40
public fun start(initial: String = "", cursor: Long = initial.charLength): EditingSession {41
val session =42
EditingSession(43
config,44
history,45
initial,46
cursor,47
completer,48
hinter,49
highlighter,50
validator51
)52
session.kills = killRing53
session.printer = printer54
for (binding in bindings)55
session.bindSequence(binding.keys, binding.handler)56
return session57
}59
/** Binds one logical key. */60
public fun bind(key: KeyEvent, command: Command) {61
bindSequence([key]) { _, _ -> command }62
}63
/** Binds a literal key sequence to a context-dependent command. */64
public fun bindSequence(keys: Array<KeyEvent>, handler: (LineBuffer, Context) -> Command) {65
if (keys.size == 0L)66
throw IllegalArgumentException(Some("empty key sequence"))67
removeBinding(bindings, keys)68
bindings.add(KeyBinding(keys.toArray(), handler))69
}71
/** Removes an exact custom key sequence from subsequent editing sessions. */72
public fun unbindSequence(keys: Array<KeyEvent>): Boolean = removeBinding(bindings, keys)74
/** Reads a line, selecting terminal editing or redirected-stream input automatically. */75
public fun readLine(76
prompt: String = "",77
initial: String = "",78
cursor: Long = initial.charLength79
): String {80
if (active)81
throw IllegalStateException(Some("editor is already reading"))82
active = true83
try {84
val term = environmentVariable("TERM")85
val dumb = term != None && term!!.display() == "dumb"86
if (!isTerminal(StandardStream.Input) || dumb) {87
return readLineFrom(88
standardInput,89
standardOutput,90
if (dumb)91
prompt92
else93
""94
)95
}96
return TerminalSession.open(97
Duration.milliseconds(config.keySequenceTimeoutMilliseconds)98
).use { terminal -> readTerminal(terminal, prompt, start(initial, cursor)) }99
} finally {100
active = false101
}102
}104
/** Reads UTF-8 lines from borrowed streams, applying validation and optional automatic history. */105
public fun readLineFrom(source: ByteSource, output: ByteSink, prompt: String = ""): String {106
if (prompt.byteLength > 0L) {107
output.writeText(prompt);108
output.flush()109
}110
val buffer = LineBuffer()111
while (true) {112
val input = source.readLine()113
if (input == None)114
throw ReadlineEofException()115
for (character in input!!) {116
if (character == '\b' || character == '\u007f') {117
buffer.replace(buffer.previous(buffer.cursor), buffer.cursor, "")118
} else119
buffer.insert(character.toString())120
}121
when (val result = validator.validate(buffer.text)) {122
case Valid(val message) -> {123
if (message != None) {124
output.writeText(message!!);125
output.flush()126
}127
if (config.autoAddHistory)128
history.add(buffer.text)129
return buffer.text130
}131
case Invalid(val message) -> {132
if (message != None) {133
output.writeText(message!!);134
output.flush()135
}136
}137
case Incomplete -> buffer.insert("\n")138
}139
}140
}142
/** Loads history when the selected backend exposes persistence. */143
public fun loadHistory(path: Path) {144
persistentHistory().load(path)145
}146
/** Saves history when the selected backend exposes persistence. */147
public fun saveHistory(path: Path) {148
persistentHistory().save(path)149
}150
/** Appends unsaved history when the selected backend exposes persistence. */151
public fun appendHistory(path: Path) {152
persistentHistory().append(path)153
}155
private fun persistentHistory(): PersistentHistory {156
val backend = history157
if (backend is PersistentHistory)158
return backend159
throw IllegalStateException(Some("history backend has no persistence capability"))160
}161
}