Scoop API

scoop:scoop.readline:0.1.0

src/editing/session.scoop

Selected production source · src/editing/session.scoop

1package scoop.readline
3import scoop.readline.history.*
4import scoop.terminal.event.*
5import scoop.text.*
7internal class SearchState(
8 val original: BufferState,
9 val originalIndex: Long,
10 var direction: SearchDirection
11) {
12 var query: String = ""
13 var index: Long = originalIndex
16internal class CompletionState(val original: BufferState, val result: Completions) {
17 var index: Long = -1L
20internal struct KeyBinding(val keys: Array<KeyEvent>, val handler: (LineBuffer, Context) -> Command)
22/** The production editor core, driven by terminal events or application-provided events. */
23public 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 = AcceptAll
32) {
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.size
38 internal var draft: BufferState = buffer.state()
39 internal var search: SearchState? = None
40 internal var lastSearch: String = ""
41 internal var completion: CompletionState? = None
42 internal var fuzzy: FuzzyCompletion? = None
43 internal var quoted: Boolean = false
44 internal var lastYank: (Long, Long)? = None
45 internal var lastChange: Command? = None
46 internal var viChange: ViChange? = None
47 internal var replaying: Boolean = false
48 internal var printer: ExternalPrinter? = None
49 internal var messageValue: String? = None
50 internal var bellValue: Boolean = false
51 internal var clearValue: Boolean = false
52 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 = false
57 public val line: String get() = buffer.text
58 public val cursor: Long get() = buffer.cursor
59 public val historyIndex: Long get() = historyPosition
60 public val viMode: ViMode get() = keys.mode
61 public val message: String? get() = messageValue
62 public val candidates: Array<Candidate> get() = displayedCandidates
63 public val hasPendingSequence: Boolean get() = sequence.size > 0L
64 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 -> false
71 }
72 ) ||
73 (
74 when (fuzzy) {
75 case Some(_) -> true;
76 case None -> false
77 }
78 ) ||
79 finished
80 )
81 None
82 else
83 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 = 0L
94 while (index < bindings.size) {
95 if (sameKeys(bindings[index].keys, keys)) {
96 bindings.removeAt(index);
97 break
98 }
99 index += 1L
100 }
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 = false
112 clearValue = false
113 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.Continue
123 }
124 case None -> execute(Command.Insert(normalized))
125 }
126 }
127 else -> EditResult.Continue
128 }
129 }
131 private fun handleKey(key: KeyEvent): EditResult {
132 if (key.kind == KeyEventKind.Release)
133 return EditResult.Continue
134 if (
135 (
136 when (fuzzy) {
137 case Some(_) -> true;
138 case None -> false
139 }
140 )
141 )
142 return handleFuzzyKey(key)
143 if (quoted) {
144 quoted = false
145 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 else
151 character!!.toString()
152 } else
153 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 -> false
168 }
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 = false
182 var matched = -1L
183 var length = 0L
184 var index = 0L
185 while (index < bindings.size) {
186 val binding = bindings[index]
187 if (binding.keys.size > sequence.size && keysPrefix(sequence, binding.keys))
188 prefix = true
189 if (
190 binding.keys.size <=
191 sequence.size &&
192 binding.keys.size >
193 length &&
194 keysPrefix(binding.keys, sequence)
195 ) {
196 matched = index
197 length = binding.keys.size
198 }
199 index += 1L
200 }
201 if (prefix && !force)
202 return EditResult.Continue
203 val result =
204 if (matched >= 0L) {
205 var removed = 0L
206 while (removed < length) {
207 sequence.removeAt(0L);
208 removed += 1L
209 }
210 execute(bindings[matched].handler(buffer, context))
211 } else {
212 val key = sequence.removeAt(0L)
213 var command = keys.command(key)
214 val suggestion = hint
215 if (
216 key.code ==
217 KeyCode.Right &&
218 cursor ==
219 buffer.length &&
220 suggestion !=
221 None &&
222 suggestion!!.completion !=
223 None
224 )
225 command = Command.CompleteHint
226 execute(command)
227 }
228 if (result != EditResult.Continue)
229 return result
230 }
231 return EditResult.Continue
232 }
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 -> false
243 }
244 if (reverting)
245 finishViChange()
246 val before = buffer.state()
247 val previousMode = keys.mode
248 val result = applyCommand(command)
249 val recordsUndo =
250 when (command) {
251 case Undo(_) -> false
252 case Redo(_) -> false
253 case RepeatLastChange(_) -> false
254 else -> true
255 }
256 if (recordsUndo && config.editMode == EditMode.Vi && !replaying) {
257 recordViChange(command, before, previousMode, result)
258 } else
259 if (recordsUndo) {
260 val insertion =
261 when (command) {
262 case Insert(val text, val count) -> text.charLength == 1L && count == 1L;
263 else -> false
264 }
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 -> false
275 }
276 if (!killing)
277 kills.boundary()
278 val yanking =
279 when (command) {
280 case Yank(_, _) -> true;
281 case YankPop -> true;
282 else -> false
283 }
284 if (!yanking)
285 lastYank = None
286 val completing =
287 when (command) {
288 case Complete -> true;
289 case CompleteBackward -> true;
290 else -> false
291 }
292 if (!completing)
293 completion = None
294 if (result != EditResult.Continue && result != EditResult.Suspended)
295 finished = true
296 return result
297 }
299 /** Consumes pending bell feedback. */
300 public fun takeBell(): Boolean {
301 val result = bellValue;
302 bellValue = false;
303 return result
304 }
305 /** Consumes a request to clear the screen. */
306 public fun takeClearScreen(): Boolean {
307 val result = clearValue;
308 clearValue = false;
309 return result
310 }
313private fun keysPrefix(prefix: List<KeyEvent>, keys: List<KeyEvent>): Boolean {
314 if (prefix.size > keys.size)
315 return false
316 var index = 0L
317 while (index < prefix.size) {
318 if (
319 prefix[index].code !=
320 keys[index].code ||
321 prefix[index].modifiers.bits !=
322 keys[index].modifiers.bits
323 )
324 return false
325 index += 1L
326 }
327 return true
330internal fun sameKeys(left: List<KeyEvent>, right: List<KeyEvent>): Boolean =
331 left.size == right.size && keysPrefix(left, right)
333internal fun removeBinding(bindings: ArrayList<KeyBinding>, keys: Array<KeyEvent>): Boolean {
334 var index = 0L
335 while (index < bindings.size) {
336 if (sameKeys(bindings[index].keys, keys)) {
337 bindings.removeAt(index);
338 return true
339 }
340 index += 1L
341 }
342 return false