Scoop API

scoop:scoop.readline:0.1.0

src/editor.scoop

Selected production source · src/editor.scoop

1package scoop.readline
3import scoop.readline.history.*
4import scoop.platform.fs.Path
5import scoop.platform.io.*
6import scoop.platform.env.environmentVariable
7import scoop.terminal.TerminalSession
8import scoop.terminal.StandardStream
9import scoop.terminal.isTerminal
10import scoop.terminal.event.KeyEvent
11import scoop.time.Duration
13/** A reusable Unix line editor with pluggable history and independent extension callbacks. */
14public class Editor public constructor(
15 public val config: Config = readlineConfig(),
16 public val history: History = FileHistory(config)
17) {
18 public var completer: Completer = NoCompleter
19 public var hinter: Hinter = NoHinter
20 public var highlighter: Highlighter = PlainHighlighter
21 public var validator: Validator = AcceptAll
22 private val bindings: ArrayList<KeyBinding> = ArrayList<KeyBinding>()
23 private val killRing: KillRing = KillRing()
24 private var active: Boolean = false
25 private var printer: ExternalPrinter? = None
27 /** 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 value
31 case None -> {
32 val value = ExternalPrinter()
33 printer = Some(value)
34 return value
35 }
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 validator
51 )
52 session.kills = killRing
53 session.printer = printer
54 for (binding in bindings)
55 session.bindSequence(binding.keys, binding.handler)
56 return session
57 }
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.charLength
79 ): String {
80 if (active)
81 throw IllegalStateException(Some("editor is already reading"))
82 active = true
83 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 prompt
92 else
93 ""
94 )
95 }
96 return TerminalSession.open(
97 Duration.milliseconds(config.keySequenceTimeoutMilliseconds)
98 ).use { terminal -> readTerminal(terminal, prompt, start(initial, cursor)) }
99 } finally {
100 active = false
101 }
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 } else
119 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.text
130 }
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 = history
157 if (backend is PersistentHistory)
158 return backend
159 throw IllegalStateException(Some("history backend has no persistence capability"))
160 }