scoop:scoop.readline:0.1.0
src/editing/session.scoop
Selected production source · src/editing/session.scoop
1
package scoop.readline3
import scoop.readline.history.*4
import scoop.terminal.event.*5
import scoop.text.*7
internal class SearchState(8
val original: BufferState,9
val originalIndex: Long,10
var direction: SearchDirection11
) {12
var query: String = ""13
var index: Long = originalIndex14
}16
internal class CompletionState(val original: BufferState, val result: Completions) {17
var index: Long = -1L18
}20
internal struct KeyBinding(val keys: Array<KeyEvent>, val handler: (LineBuffer, Context) -> Command)22
/** The production editor core, driven by terminal events or application-provided events. */23
public class EditingSession public constructor(24
public val config: Config = readlineConfig(),25
public val history: History = FileHistory(config),26
initial: String = "",27
cursor: Long = initial.charLength,28
public val completer: Completer = NoCompleter,29
public val hinter: Hinter = NoHinter,30
public val highlighter: Highlighter = PlainHighlighter,31
public val validator: Validator = AcceptAll32
) {33
public val buffer: LineBuffer = LineBuffer(initial, cursor)34
internal val keys: KeyMap = KeyMap(config.editMode)35
internal val undo: UndoHistory = UndoHistory()36
internal var kills: KillRing = KillRing()37
internal var historyPosition: Long = history.size38
internal var draft: BufferState = buffer.state()39
internal var search: SearchState? = None40
internal var lastSearch: String = ""41
internal var completion: CompletionState? = None42
internal var fuzzy: FuzzyCompletion? = None43
internal var quoted: Boolean = false44
internal var lastYank: (Long, Long)? = None45
internal var lastChange: Command? = None46
internal var viChange: ViChange? = None47
internal var replaying: Boolean = false48
internal var printer: ExternalPrinter? = None49
internal var messageValue: String? = None50
internal var bellValue: Boolean = false51
internal var clearValue: Boolean = false52
internal var displayedCandidates: Array<Candidate> = []53
internal val bindings: ArrayList<KeyBinding> = ArrayList<KeyBinding>()54
private val sequence: ArrayList<KeyEvent> = ArrayList<KeyEvent>()55
private var finished: Boolean = false57
public val line: String get() = buffer.text58
public val cursor: Long get() = buffer.cursor59
public val historyIndex: Long get() = historyPosition60
public val viMode: ViMode get() = keys.mode61
public val message: String? get() = messageValue62
public val candidates: Array<Candidate> get() = displayedCandidates63
public val hasPendingSequence: Boolean get() = sequence.size > 0L64
public val context: Context get() = Context(history, historyPosition)65
public val hint: Hint? get() =66
if (67
(68
when (search) {69
case Some(_) -> true;70
case None -> false71
}72
) ||73
(74
when (fuzzy) {75
case Some(_) -> true;76
case None -> false77
}78
) ||79
finished80
)81
None82
else83
hinter.hint(line, cursor, context)85
/** Installs or replaces a literal key binding; key release events never trigger bindings. */86
public fun bind(key: KeyEvent, command: Command) {87
bindSequence([key]) { _, _ -> command }88
}89
/** Installs an ordered key sequence with an application-selected command. */90
public fun bindSequence(keys: Array<KeyEvent>, handler: (LineBuffer, Context) -> Command) {91
if (keys.size == 0L)92
throw IllegalArgumentException(Some("empty key sequence"))93
var index = 0L94
while (index < bindings.size) {95
if (sameKeys(bindings[index].keys, keys)) {96
bindings.removeAt(index);97
break98
}99
index += 1L100
}101
bindings.add(KeyBinding(keys.toArray(), handler))102
}104
/** Removes an exact custom key sequence, returning whether it was present. */105
public fun unbindSequence(keys: Array<KeyEvent>): Boolean = removeBinding(bindings, keys)107
/** Processes a terminal event, preserving edit state across resize and paste events. */108
public fun handle(event: Event): EditResult {109
if (finished)110
throw IllegalStateException(Some("editing session has finished"))111
bellValue = false112
clearValue = false113
displayedCandidates = []114
return when (event) {115
case Key(val key) -> handleKey(key)116
case Paste(val text) -> {117
val normalized = text.replace("\r\n", "\n").replace("\r", "\n")118
when (fuzzy) {119
case Some(val state) -> {120
state.query += normalized;121
updateFuzzy();122
EditResult.Continue123
}124
case None -> execute(Command.Insert(normalized))125
}126
}127
else -> EditResult.Continue128
}129
}131
private fun handleKey(key: KeyEvent): EditResult {132
if (key.kind == KeyEventKind.Release)133
return EditResult.Continue134
if (135
(136
when (fuzzy) {137
case Some(_) -> true;138
case None -> false139
}140
)141
)142
return handleFuzzyKey(key)143
if (quoted) {144
quoted = false145
val character = keyCharacter(key)146
val text =147
if (character != None) {148
if (key.modifiers.has(KeyModifier.Control))149
(character!!.code and 31).toChar().toString()150
else151
character!!.toString()152
} else153
when (key.code) {154
case Enter -> "\n";155
case Tab -> "\t";156
case Esc -> "\u001b"157
case Backspace -> "\u007f";158
case Null -> "\u0000";159
else -> ""160
}161
return execute(Command.Insert(text))162
}163
if (164
(165
when (search) {166
case Some(_) -> true;167
case None -> false168
}169
)170
)171
return handleSearchKey(key)172
sequence.add(key)173
return resolveSequence(false)174
}176
/** Resolves an incomplete custom sequence through the normal key map after its timeout. */177
public fun flushPendingSequence(): EditResult = resolveSequence(true)179
private fun resolveSequence(force: Boolean): EditResult {180
while (sequence.size > 0L) {181
var prefix = false182
var matched = -1L183
var length = 0L184
var index = 0L185
while (index < bindings.size) {186
val binding = bindings[index]187
if (binding.keys.size > sequence.size && keysPrefix(sequence, binding.keys))188
prefix = true189
if (190
binding.keys.size <=191
sequence.size &&192
binding.keys.size >193
length &&194
keysPrefix(binding.keys, sequence)195
) {196
matched = index197
length = binding.keys.size198
}199
index += 1L200
}201
if (prefix && !force)202
return EditResult.Continue203
val result =204
if (matched >= 0L) {205
var removed = 0L206
while (removed < length) {207
sequence.removeAt(0L);208
removed += 1L209
}210
execute(bindings[matched].handler(buffer, context))211
} else {212
val key = sequence.removeAt(0L)213
var command = keys.command(key)214
val suggestion = hint215
if (216
key.code ==217
KeyCode.Right &&218
cursor ==219
buffer.length &&220
suggestion !=221
None &&222
suggestion!!.completion !=223
None224
)225
command = Command.CompleteHint226
execute(command)227
}228
if (result != EditResult.Continue)229
return result230
}231
return EditResult.Continue232
}234
/** Executes a command using exactly the same path as keyboard input. */235
public fun execute(command: Command): EditResult {236
if (finished)237
throw IllegalStateException(Some("editing session has finished"))238
val reverting =239
when (command) {240
case Undo(_) -> true;241
case Redo(_) -> true;242
else -> false243
}244
if (reverting)245
finishViChange()246
val before = buffer.state()247
val previousMode = keys.mode248
val result = applyCommand(command)249
val recordsUndo =250
when (command) {251
case Undo(_) -> false252
case Redo(_) -> false253
case RepeatLastChange(_) -> false254
else -> true255
}256
if (recordsUndo && config.editMode == EditMode.Vi && !replaying) {257
recordViChange(command, before, previousMode, result)258
} else259
if (recordsUndo) {260
val insertion =261
when (command) {262
case Insert(val text, val count) -> text.charLength == 1L && count == 1L;263
else -> false264
}265
undo.record(before, buffer.state(), insertion)266
}267
if (before.text != line && !replaying && recordsUndo && config.editMode != EditMode.Vi)268
lastChange = Some(command)269
val killing =270
when (command) {271
case Kill(_) -> true;272
case Change(_) -> true;273
case Copy(_) -> true;274
else -> false275
}276
if (!killing)277
kills.boundary()278
val yanking =279
when (command) {280
case Yank(_, _) -> true;281
case YankPop -> true;282
else -> false283
}284
if (!yanking)285
lastYank = None286
val completing =287
when (command) {288
case Complete -> true;289
case CompleteBackward -> true;290
else -> false291
}292
if (!completing)293
completion = None294
if (result != EditResult.Continue && result != EditResult.Suspended)295
finished = true296
return result297
}299
/** Consumes pending bell feedback. */300
public fun takeBell(): Boolean {301
val result = bellValue;302
bellValue = false;303
return result304
}305
/** Consumes a request to clear the screen. */306
public fun takeClearScreen(): Boolean {307
val result = clearValue;308
clearValue = false;309
return result310
}311
}313
private fun keysPrefix(prefix: List<KeyEvent>, keys: List<KeyEvent>): Boolean {314
if (prefix.size > keys.size)315
return false316
var index = 0L317
while (index < prefix.size) {318
if (319
prefix[index].code !=320
keys[index].code ||321
prefix[index].modifiers.bits !=322
keys[index].modifiers.bits323
)324
return false325
index += 1L326
}327
return true328
}330
internal fun sameKeys(left: List<KeyEvent>, right: List<KeyEvent>): Boolean =331
left.size == right.size && keysPrefix(left, right)333
internal fun removeBinding(bindings: ArrayList<KeyBinding>, keys: Array<KeyEvent>): Boolean {334
var index = 0L335
while (index < bindings.size) {336
if (sameKeys(bindings[index].keys, keys)) {337
bindings.removeAt(index);338
return true339
}340
index += 1L341
}342
return false343
}