robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

Tomas Slusnyfeat(prompt): support 'scrollback' option in prompt-buffers #39793a0637e0c4e

master
10.6 KiB270 linesraw
1*channel.txt*    Nvim
2
3
4		 NVIM REFERENCE MANUAL    by Thiago de Arruda
5
6
7Nvim asynchronous IO					*channel*
8
9				      Type |gO| to see the table of contents.
10
11==============================================================================
121. Introduction						    *channel-intro*
13
14Channels are Nvim's way of communicating with external processes.
15
16There are several ways to open a channel:
17
181. Through stdin/stdout when `nvim` is started with `--headless` and a startup
19   script or `--cmd` command opens the stdio channel using |stdioopen()|.
202. Through stdin, stdout and stderr of a process spawned by |jobstart()|.
213. Through the PTY master end opened with `jobstart(…, {'pty': v:true})`.
224. By connecting to a TCP/IP socket or named pipe with |sockconnect()|.
235. By another process connecting to a socket listened to by Nvim. This only
24   supports RPC channels, see |rpc-connecting|.
25
26Channels support multiple modes or protocols. In the most basic
27mode of operation, raw bytes are read and written to the channel.
28The |RPC| protocol, based on the msgpack-rpc standard, enables nvim and the
29process at the other end to send remote calls and events to each other.
30The builtin |terminal-emulator| is also implemented on top of PTY channels.
31
32Channel Id						*channel-id*
33
34Each channel is identified by an integer id, unique for the life of the
35current Nvim session. Functions like |stdioopen()| return channel ids;
36functions like |chansend()| consume channel ids.
37
38==============================================================================
392. Reading and writing raw bytes			      *channel-bytes*
40
41Channels opened by Vimscript functions operate with raw bytes by default. For
42a job channel using RPC, bytes can still be read over its stderr. Similarly,
43only bytes can be written to Nvim's own stderr.
44
45					*channel-callback* *E904* *E906* *E921* *E5407*
46- on_stdout({chan-id}, {data}, {name})		*on_stdout*
47- on_stderr({chan-id}, {data}, {name})		*on_stderr*
48- on_stdin({chan-id}, {data}, {name})		*on_stdin*
49- on_data({chan-id}, {data}, {name})		*on_data*
50
51    Scripts can react to channel activity (received data) via callback
52    functions assigned to the `on_stdout`, `on_stderr`, `on_stdin`, or
53    `on_data` option keys. Callbacks should be fast: avoid potentially
54    slow/expensive work.
55
56    Parameters: ~
57      - {chan-id}   Channel handle. |channel-id|
58      - {data}	    Raw data (|readfile()|-style list of strings) read from
59		    the channel. EOF is a single-item list: `['']`. First and
60		    last items may be partial lines! |channel-lines|
61      - {name}	    Stream name (string) like "stdout", so the same function
62		    can handle multiple streams. Event names depend on how the
63		    channel was opened and in what mode/protocol.
64
65						*channel-buffered*
66    The callback is invoked immediately as data is available, where
67    a single-item list `['']` indicates EOF (stream closed).  Alternatively
68    set the `stdout_buffered`, `stderr_buffered`, `stdin_buffered`, or
69    `data_buffered` option keys to invoke the callback only after all output
70    was gathered and the stream was closed.
71						*E5210*
72    If a buffering mode is used without a callback, the data is saved in the
73    stream {name} key of the options dict. It is an error if the key exists.
74
75							      *channel-lines*
76    Stream event handlers receive data as it becomes available from the OS,
77    thus the first and last items in the {data} list may be partial lines.
78    Empty string completes the previous partial line. Examples (not including
79    the final `['']` emitted at EOF):
80      - `foobar` may arrive as `['fo'], ['obar']`
81      - `foo\nbar` may arrive as
82	- `['foo','bar']`
83	- or `['foo',''], ['bar']`
84	- or `['foo'], ['','bar']`
85	- or `['fo'], ['o','bar']`
86
87    There are two ways to deal with this:
88    - 1. To wait for the entire output, use |channel-buffered| mode.
89    - 2. To read line-by-line, use the following code: >vim
90	let s:lines = ['']
91	func! s:on_event(job_id, data, event) dict
92	  let eof = (a:data == [''])
93	  " Complete the previous line.
94	  let s:lines[-1] .= a:data[0]
95	  " Append (last item may be a partial line, until EOF).
96	  call extend(s:lines, a:data[1:])
97	endf
98<
99
100If the callback functions are |Dictionary-function|s, |self| refers to the
101options dictionary containing the callbacks. |Partial|s can also be used as
102callbacks.
103
104Data can be sent to the channel using the |chansend()| function. Here is a
105simple example, echoing some data through a cat-process:
106>vim
107    function! s:OnEvent(id, data, event) dict
108      let str = join(a:data, "\n")
109      echomsg str
110    endfunction
111    let id = jobstart(['cat'], {'on_stdout': function('s:OnEvent') } )
112    call chansend(id, "hello!")
113<
114
115Here is an example of setting a buffer to the result of grep, but only after
116all data has been processed:
117>vim
118    function! s:OnEvent(id, data, event) dict
119      call nvim_buf_set_lines(2, 0, -1, v:true, a:data)
120    endfunction
121    let id = jobstart(['grep', '^[0-9]'], { 'on_stdout': function('s:OnEvent'),
122					  \ 'stdout_buffered':v:true } )
123
124    call chansend(id, "stuff\n10 PRINT \"NVIM\"\nxx")
125    " no output is received, buffer is empty
126
127    call chansend(id, "xx\n20 GOTO 10\nzz\n")
128    call chanclose(id, 'stdin')
129    " now buffer has result
130<
131For additional examples with jobs, see |job-control|.
132
133							      *channel-pty*
134Special case: PTY channels opened with `jobstart(..., {'pty': v:true})` do not
135preprocess ANSI escape sequences, these will be sent raw to the callback.
136However, change of PTY size can be signaled to the slave using |jobresize()|.
137See also |terminal-emulator|.
138
139Terminal characteristics (termios) for |:terminal| and PTY channels are copied
140from the host TTY, or if Nvim is |--headless| it uses default values: >vim
141    :echo system('nvim --headless +"te stty -a" +"sleep 1" +"1,/^$/print" +q')
142
143==============================================================================
1443. Communicating with msgpack RPC			      *channel-rpc*
145
146When channels are opened with the `rpc` option set to true, the channel can be
147used for remote method calls in both directions, see |msgpack-rpc|. Note that
148rpc channels are implicitly trusted and the process at the other end can
149invoke any |API| function!
150
151==============================================================================
1524. Standard IO channel					    *channel-stdio*
153
154Nvim uses stdin/stdout to interact with the user over the terminal interface
155(TUI). If Nvim is |--headless| the TUI is not started and stdin/stdout can be
156used as a channel. See also |--embed|.
157
158Call |stdioopen()| during |startup| to open the stdio channel as |channel-id| 1.
159Nvim's stderr is always available as |v:stderr|, a write-only bytes channel.
160
161Example: >vim
162    func! OnEvent(id, data, event)
163      if a:data == [""]
164        quit
165      end
166      call chansend(a:id, map(a:data, {i,v -> toupper(v)}))
167    endfunc
168    call stdioopen({'on_stdin': 'OnEvent'})
169<
170Put this in `uppercase.vim` and run:  >bash
171    nvim --headless --cmd "source uppercase.vim"
172
173==============================================================================
1745. Using a prompt buffer                                   *repl* *prompt-buffer*
175
176Prompt buffers provide a "prompt" interface: they are like regular buffers,
177except only the last section of the buffer is editable, and the user can
178"submit" the prompt by hitting Enter. The 'scrollback' option can be used
179to limit the number of history lines kept above the prompt. Useful for
180implementing:
181
182- chat UI
183- REPL or shell plugins
184- advanced "picker" plugins
185
186A prompt buffer is created by setting 'buftype' to "prompt". You would
187normally only do that in a new, empty buffer: >vim
188
189    :set buftype=prompt
190
191Prompt buffers do not implicitly set 'modified' on user input or other
192changes. But a user or plugin can set 'modified' explicitly, to prevent the
193buffer from being easily closed.
194
195The user can edit and input text at the end of the buffer. Pressing Enter in
196the input section invokes the |prompt_setcallback()| callback, which is
197typically expected to process the prompt and show results by appending to the
198buffer. To input multiline text, use *Shift-<Enter>* to add a new line without
199submitting the prompt, or just |put| or |paste| multiline text.
200
201Only the section starting with the mark |':| of the buffer (after the prompt)
202is editable. The rest of the buffer is not modifiable with Normal mode
203commands, though it can be modified by functions such as |append()|.  Using
204other commands may mess up the buffer.
205
206After setting `buftype=prompt`:
207- Nvim unsets the 'comments' option.
208- Nvim does not automatically start Insert mode (use `:startinsert` if you
209  want to enter Insert mode)
210
211The prompt prefix defaults to "% ", but can be set with |prompt_setprompt()|.
212You can get the effective prompt prefix for with |prompt_getprompt()|.
213
214The user can go to Normal mode and navigate through the buffer.  This can be
215useful to see older output or copy text.
216
217By default during prompt insert-mode, the CTRL-W key can be used to start
218a window command, such as CTRL-W w to switch to the next window. (Use
219Shift-CTRL-W to delete a word). When leaving the window Insert mode will be
220stopped. When coming back to the prompt window Insert mode will be restored.
221
222Any command that starts Insert mode, such as "a", "i", "A" and "I", will move
223the cursor to the last line.  "A" will move to the end of the line, "I" to the
224start of the line.
225
226                                                                *emacs-eshell*
227Example: The following code snippet implements a "shell buffer" similar to
228Emacs "eshell". Because the interface is a prompt-buffer, you can edit the
229prompt using normal Nvim commands, unlike a |:terminal| shell. Each prompt is
230sent to the shell process started by |jobstart()|, and appended to the buffer
231when output is received: >lua
232
233    local shell_job
234
235    -- Handles a line of user input.
236    local function on_submit(text)
237      -- Send the text to the shell with Enter appended.
238      vim.api.nvim_chan_send(shell_job, text .. "\n")
239    end
240
241    -- Handles output from the shell.
242    local function on_output(_, msg, _)
243      -- Add shell output above the prompt.
244      local buf = vim.api.nvim_get_current_buf()
245      vim.fn.prompt_appendbuf(buf, msg)
246    end
247
248    -- Handles the shell exit.
249    local function on_exit(_, _, _)
250      vim.cmd("quit!")
251    end
252
253    -- Start a shell in the background.
254    shell_job = vim.fn.jobstart({ "/bin/sh" }, {
255      on_stdout = on_output,
256      on_stderr = on_output,
257      on_exit = on_exit,
258    })
259
260    vim.cmd("new")
261    vim.bo.buftype = "prompt"
262    local buf = vim.api.nvim_get_current_buf()
263    vim.fn.prompt_setcallback(buf, on_submit)
264    vim.fn.prompt_setprompt(buf, "shell command: ")
265
266    -- Start accepting shell commands.
267    vim.cmd("startinsert")
268<
269
270 vim:tw=78:ts=8:et:sw=4:ft=help:norl: