blob: 01a9e3695dbe99dba3cce76b1497a314af47c3b5 [file] [log] [blame]
Bram Moolenaar75ab5902022-04-18 15:36:40 +01001*channel.txt* For Vim version 8.2. Last change: 2022 Apr 16
Bram Moolenaar3b5f9292016-01-28 22:37:01 +01002
3
4 VIM REFERENCE MANUAL by Bram Moolenaar
5
6
7 Inter-process communication *channel*
8
Bram Moolenaar3b5f9292016-01-28 22:37:01 +01009Vim uses channels to communicate with other processes.
Bram Moolenaar269f5952016-07-15 22:54:41 +020010A channel uses a socket or pipes. *socket-interface*
Bram Moolenaar38a55632016-02-15 22:07:32 +010011Jobs can be used to start processes and communicate with them.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +010012The Netbeans interface also uses a channel. |netbeans|
13
Bram Moolenaar38a55632016-02-15 22:07:32 +0100141. Overview |job-channel-overview|
152. Channel demo |channel-demo|
163. Opening a channel |channel-open|
174. Using a JSON or JS channel |channel-use|
185. Channel commands |channel-commands|
196. Using a RAW or NL channel |channel-raw|
207. More channel functions |channel-more|
Bram Moolenaar54775062019-07-31 21:07:14 +0200218. Channel functions details |channel-functions-details|
Bram Moolenaared997ad2019-07-21 16:42:00 +0200229. Starting a job with a channel |job-start|
2310. Starting a job without a channel |job-start-nochannel|
2411. Job functions |job-functions-details|
2512. Job options |job-options|
2613. Controlling a job |job-control|
2714. Using a prompt buffer |prompt-buffer|
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +01002815. Language Server Protocol |language-server-protocol|
Bram Moolenaar3b5f9292016-01-28 22:37:01 +010029
Bram Moolenaar38a55632016-02-15 22:07:32 +010030{only when compiled with the |+channel| feature for channel stuff}
Bram Moolenaarf37506f2016-08-31 22:22:10 +020031 You can check this with: `has('channel')`
Bram Moolenaar38a55632016-02-15 22:07:32 +010032{only when compiled with the |+job| feature for job stuff}
Bram Moolenaarf37506f2016-08-31 22:22:10 +020033 You can check this with: `has('job')`
Bram Moolenaar3b5f9292016-01-28 22:37:01 +010034
35==============================================================================
Bram Moolenaar38a55632016-02-15 22:07:32 +0100361. Overview *job-channel-overview*
37
38There are four main types of jobs:
Bram Moolenaar50ba5262016-09-22 22:33:02 +0200391. A daemon, serving several Vim instances.
Bram Moolenaar38a55632016-02-15 22:07:32 +010040 Vim connects to it with a socket.
412. One job working with one Vim instance, asynchronously.
42 Uses a socket or pipes.
433. A job performing some work for a short time, asynchronously.
44 Uses a socket or pipes.
454. Running a filter, synchronously.
46 Uses pipes.
47
Bram Moolenaar77cdfd12016-03-12 12:57:59 +010048For when using sockets See |job-start|, |job-start-nochannel| and
49|channel-open|. For 2 and 3, one or more jobs using pipes, see |job-start|.
Bram Moolenaar38a55632016-02-15 22:07:32 +010050For 4 use the ":{range}!cmd" command, see |filter|.
51
52Over the socket and pipes these protocols are available:
53RAW nothing known, Vim cannot tell where a message ends
54NL every message ends in a NL (newline) character
55JSON JSON encoding |json_encode()|
56JS JavaScript style JSON-like encoding |js_encode()|
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +010057LSP Language Server Protocol encoding |language-server-protocol|
Bram Moolenaar38a55632016-02-15 22:07:32 +010058
59Common combination are:
60- Using a job connected through pipes in NL mode. E.g., to run a style
61 checker and receive errors and warnings.
Bram Moolenaar7dda86f2018-04-20 22:36:41 +020062- Using a daemon, connecting over a socket in JSON mode. E.g. to lookup
Bram Moolenaar09521312016-08-12 22:54:35 +020063 cross-references in a database.
Bram Moolenaar38a55632016-02-15 22:07:32 +010064
65==============================================================================
Bram Moolenaar26852122016-05-24 20:02:38 +0200662. Channel demo *channel-demo* *demoserver.py*
Bram Moolenaar3b5f9292016-01-28 22:37:01 +010067
68This requires Python. The demo program can be found in
69$VIMRUNTIME/tools/demoserver.py
70Run it in one terminal. We will call this T1.
71
72Run Vim in another terminal. Connect to the demo server with: >
Bram Moolenaar38a55632016-02-15 22:07:32 +010073 let channel = ch_open('localhost:8765')
Bram Moolenaar3b5f9292016-01-28 22:37:01 +010074
75In T1 you should see:
76 === socket opened === ~
77
78You can now send a message to the server: >
Bram Moolenaar8b1862a2016-02-27 19:21:24 +010079 echo ch_evalexpr(channel, 'hello!')
Bram Moolenaar3b5f9292016-01-28 22:37:01 +010080
81The message is received in T1 and a response is sent back to Vim.
82You can see the raw messages in T1. What Vim sends is:
83 [1,"hello!"] ~
84And the response is:
85 [1,"got it"] ~
86The number will increase every time you send a message.
87
88The server can send a command to Vim. Type this on T1 (literally, including
Bram Moolenaarfb1f6262016-01-31 20:24:32 +010089the quotes):
90 ["ex","echo 'hi there'"] ~
91And you should see the message in Vim. You can move the cursor a word forward:
92 ["normal","w"] ~
Bram Moolenaar3b5f9292016-01-28 22:37:01 +010093
94To handle asynchronous communication a callback needs to be used: >
Bram Moolenaar38a55632016-02-15 22:07:32 +010095 func MyHandler(channel, msg)
Bram Moolenaarc51cf032022-02-26 12:25:45 +000096 echo "from the handler: " .. a:msg
Bram Moolenaar3b5f9292016-01-28 22:37:01 +010097 endfunc
Bram Moolenaar02e83b42016-02-21 20:10:26 +010098 call ch_sendexpr(channel, 'hello!', {'callback': "MyHandler"})
Bram Moolenaar38a55632016-02-15 22:07:32 +010099Vim will not wait for a response. Now the server can send the response later
100and MyHandler will be invoked.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100101
102Instead of giving a callback with every send call, it can also be specified
103when opening the channel: >
Bram Moolenaar38a55632016-02-15 22:07:32 +0100104 call ch_close(channel)
105 let channel = ch_open('localhost:8765', {'callback': "MyHandler"})
Bram Moolenaar47003982021-12-05 21:54:04 +0000106 call ch_sendexpr(channel, 'hello channel!')
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100107
Bram Moolenaar328da0d2016-03-04 22:22:32 +0100108When trying out channels it's useful to see what is going on. You can tell
109Vim to write lines in log file: >
110 call ch_logfile('channellog', 'w')
111See |ch_logfile()|.
112
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100113==============================================================================
Bram Moolenaar38a55632016-02-15 22:07:32 +01001143. Opening a channel *channel-open*
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100115
Bram Moolenaar681baaf2016-02-04 20:57:07 +0100116To open a channel: >
Bram Moolenaar38a55632016-02-15 22:07:32 +0100117 let channel = ch_open({address} [, {options}])
Bram Moolenaar02e83b42016-02-21 20:10:26 +0100118 if ch_status(channel) == "open"
119 " use the channel
Bram Moolenaar38a55632016-02-15 22:07:32 +0100120
121Use |ch_status()| to see if the channel could be opened.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100122
LemonBoycc766a82022-04-04 15:46:58 +0100123 *channel-address*
124{address} can be a domain name or an IP address, followed by a port number, or
125a Unix-domain socket path prefixed by "unix:". E.g. >
126 www.example.com:80 " domain + port
127 127.0.0.1:1234 " IPv4 + port
128 [2001:db8::1]:8765 " IPv6 + port
129 unix:/tmp/my-socket " Unix-domain socket path
Bram Moolenaarbfe13cc2020-04-12 17:53:12 +0200130
Bram Moolenaar4f3f6682016-03-26 23:01:59 +0100131{options} is a dictionary with optional entries: *channel-open-options*
Bram Moolenaar4d919d72016-02-05 22:36:41 +0100132
133"mode" can be: *channel-mode*
134 "json" - Use JSON, see below; most convenient way. Default.
Bram Moolenaar910b8aa2016-02-16 21:03:07 +0100135 "js" - Use JS (JavaScript) encoding, more efficient than JSON.
Bram Moolenaar38a55632016-02-15 22:07:32 +0100136 "nl" - Use messages that end in a NL character
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100137 "raw" - Use raw messages
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +0100138 "lsp" - Use language server protocol encoding
Bram Moolenaard6c2f052016-03-14 23:22:59 +0100139 *channel-callback* *E921*
Bram Moolenaar38a55632016-02-15 22:07:32 +0100140"callback" A function that is called when a message is received that is
Bram Moolenaar47003982021-12-05 21:54:04 +0000141 not handled otherwise (e.g. a JSON message with ID zero). It
142 gets two arguments: the channel and the received message.
143 Example: >
Bram Moolenaar38a55632016-02-15 22:07:32 +0100144 func Handle(channel, msg)
Bram Moolenaarc51cf032022-02-26 12:25:45 +0000145 echo 'Received: ' .. a:msg
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100146 endfunc
Bram Moolenaar38a55632016-02-15 22:07:32 +0100147 let channel = ch_open("localhost:8765", {"callback": "Handle"})
148<
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +0100149 When "mode" is "json" or "js" or "lsp" the "msg" argument is
150 the body of the received message, converted to Vim types.
Bram Moolenaar02e83b42016-02-21 20:10:26 +0100151 When "mode" is "nl" the "msg" argument is one message,
152 excluding the NL.
153 When "mode" is "raw" the "msg" argument is the whole message
154 as a string.
Bram Moolenaare18c0b32016-03-20 21:08:34 +0100155
156 For all callbacks: Use |function()| to bind it to arguments
Bram Moolenaar4f3f6682016-03-26 23:01:59 +0100157 and/or a Dictionary. Or use the form "dict.function" to bind
158 the Dictionary.
Bram Moolenaar06d2d382016-05-20 17:24:11 +0200159
160 Callbacks are only called at a "safe" moment, usually when Vim
161 is waiting for the user to type a character. Vim does not use
162 multi-threading.
163
Bram Moolenaard6c2f052016-03-14 23:22:59 +0100164 *close_cb*
165"close_cb" A function that is called when the channel gets closed, other
Bram Moolenaar38a55632016-02-15 22:07:32 +0100166 than by calling ch_close(). It should be defined like this: >
167 func MyCloseHandler(channel)
Bram Moolenaar06d2d382016-05-20 17:24:11 +0200168< Vim will invoke callbacks that handle data before invoking
169 close_cb, thus when this function is called no more data will
Bram Moolenaar68e65602019-05-26 21:33:31 +0200170 be passed to the callbacks. However, if a callback causes Vim
171 to check for messages, the close_cb may be invoked while still
172 in the callback. The plugin must handle this somehow, it can
173 be useful to know that no more data is coming.
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +0100174 If it is not known if there is a message to be read, use a
175 try/catch block: >
176 try
177 let msg = ch_readraw(a:channel)
178 catch
179 let msg = 'no message'
180 endtry
181 try
182 let err = ch_readraw(a:channel, #{part: 'err'})
183 catch
184 let err = 'no error'
185 endtry
186< *channel-drop*
Bram Moolenaar958dc692016-12-01 15:34:12 +0100187"drop" Specifies when to drop messages:
188 "auto" When there is no callback to handle a message.
189 The "close_cb" is also considered for this.
190 "never" All messages will be kept.
191
Bram Moolenaar0b146882018-09-06 16:27:24 +0200192 *channel-noblock*
193"noblock" Same effect as |job-noblock|. Only matters for writing.
194
Bram Moolenaar06d2d382016-05-20 17:24:11 +0200195 *waittime*
Bram Moolenaar38a55632016-02-15 22:07:32 +0100196"waittime" The time to wait for the connection to be made in
Bram Moolenaarf3913272016-02-25 00:00:01 +0100197 milliseconds. A negative number waits forever.
198
199 The default is zero, don't wait, which is useful if a local
200 server is supposed to be running already. On Unix Vim
201 actually uses a 1 msec timeout, that is required on many
202 systems. Use a larger value for a remote server, e.g. 10
203 msec at least.
Bram Moolenaar4f3f6682016-03-26 23:01:59 +0100204 *channel-timeout*
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100205"timeout" The time to wait for a request when blocking, E.g. when using
Bram Moolenaar8b1862a2016-02-27 19:21:24 +0100206 ch_evalexpr(). In milliseconds. The default is 2000 (2
Bram Moolenaar38a55632016-02-15 22:07:32 +0100207 seconds).
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100208
Bram Moolenaar595e64e2016-02-07 19:19:53 +0100209When "mode" is "json" or "js" the "callback" is optional. When omitted it is
210only possible to receive a message after sending one.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100211
Bram Moolenaar02e83b42016-02-21 20:10:26 +0100212To change the channel options after opening it use |ch_setoptions()|. The
213arguments are similar to what is passed to |ch_open()|, but "waittime" cannot
214be given, since that only applies to opening the channel.
Bram Moolenaar4d919d72016-02-05 22:36:41 +0100215
Bram Moolenaar02e83b42016-02-21 20:10:26 +0100216For example, the handler can be added or changed: >
Bram Moolenaar38a55632016-02-15 22:07:32 +0100217 call ch_setoptions(channel, {'callback': callback})
218When "callback" is empty (zero or an empty string) the handler is removed.
219
Bram Moolenaar328da0d2016-03-04 22:22:32 +0100220After a callback has been invoked Vim will update the screen and put the
221cursor back where it belongs. Thus the callback should not need to do
222`:redraw`.
223
Bram Moolenaar38a55632016-02-15 22:07:32 +0100224The timeout can be changed: >
225 call ch_setoptions(channel, {'timeout': msec})
226<
Bram Moolenaar02e83b42016-02-21 20:10:26 +0100227 *channel-close* *E906*
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100228Once done with the channel, disconnect it like this: >
Bram Moolenaar38a55632016-02-15 22:07:32 +0100229 call ch_close(channel)
230When a socket is used this will close the socket for both directions. When
231pipes are used (stdin/stdout/stderr) they are all closed. This might not be
232what you want! Stopping the job with job_stop() might be better.
Bram Moolenaar187db502016-02-27 14:44:26 +0100233All readahead is discarded, callbacks will no longer be invoked.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100234
Bram Moolenaar4f3f6682016-03-26 23:01:59 +0100235Note that a channel is closed in three stages:
236 - The I/O ends, log message: "Closing channel". There can still be queued
237 messages to read or callbacks to invoke.
238 - The readahead is cleared, log message: "Clearing channel". Some variables
239 may still reference the channel.
240 - The channel is freed, log message: "Freeing channel".
241
Bram Moolenaarcbebd482016-02-07 23:02:56 +0100242When the channel can't be opened you will get an error message. There is a
243difference between MS-Windows and Unix: On Unix when the port doesn't exist
244ch_open() fails quickly. On MS-Windows "waittime" applies.
Bram Moolenaaraa3b15d2016-04-21 08:53:19 +0200245*E898* *E901* *E902*
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100246
247If there is an error reading or writing a channel it will be closed.
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100248*E630* *E631*
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100249
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100250==============================================================================
Bram Moolenaar38a55632016-02-15 22:07:32 +01002514. Using a JSON or JS channel *channel-use*
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100252
Bram Moolenaar910b8aa2016-02-16 21:03:07 +0100253If mode is JSON then a message can be sent synchronously like this: >
Bram Moolenaar8b1862a2016-02-27 19:21:24 +0100254 let response = ch_evalexpr(channel, {expr})
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100255This awaits a response from the other side.
256
Bram Moolenaar910b8aa2016-02-16 21:03:07 +0100257When mode is JS this works the same, except that the messages use
Bram Moolenaar38a55632016-02-15 22:07:32 +0100258JavaScript encoding. See |js_encode()| for the difference.
Bram Moolenaar595e64e2016-02-07 19:19:53 +0100259
Bram Moolenaar02e83b42016-02-21 20:10:26 +0100260To send a message, without handling a response or letting the channel callback
261handle the response: >
Bram Moolenaar8b1862a2016-02-27 19:21:24 +0100262 call ch_sendexpr(channel, {expr})
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100263
264To send a message and letting the response handled by a specific function,
265asynchronously: >
Bram Moolenaar02e83b42016-02-21 20:10:26 +0100266 call ch_sendexpr(channel, {expr}, {'callback': Handler})
Bram Moolenaar38a55632016-02-15 22:07:32 +0100267
268Vim will match the response with the request using the message ID. Once the
269response is received the callback will be invoked. Further responses with the
270same ID will be ignored. If your server sends back multiple responses you
271need to send them with ID zero, they will be passed to the channel callback.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100272
273The {expr} is converted to JSON and wrapped in an array. An example of the
274message that the receiver will get when {expr} is the string "hello":
275 [12,"hello"] ~
276
277The format of the JSON sent is:
278 [{number},{expr}]
279
280In which {number} is different every time. It must be used in the response
281(if any):
282
283 [{number},{response}]
284
285This way Vim knows which sent message matches with which received message and
286can call the right handler. Also when the messages arrive out of order.
287
Bram Moolenaarf1f07922016-08-26 17:58:53 +0200288A newline character is terminating the JSON text. This can be used to
289separate the read text. For example, in Python:
290 splitidx = read_text.find('\n')
291 message = read_text[:splitidx]
292 rest = read_text[splitidx + 1:]
293
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100294The sender must always send valid JSON to Vim. Vim can check for the end of
295the message by parsing the JSON. It will only accept the message if the end
Bram Moolenaarf1f07922016-08-26 17:58:53 +0200296was received. A newline after the message is optional.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100297
298When the process wants to send a message to Vim without first receiving a
299message, it must use the number zero:
300 [0,{response}]
301
302Then channel handler will then get {response} converted to Vim types. If the
303channel does not have a handler the message is dropped.
304
Bram Moolenaar8b1862a2016-02-27 19:21:24 +0100305It is also possible to use ch_sendraw() and ch_evalraw() on a JSON or JS
306channel. The caller is then completely responsible for correct encoding and
307decoding.
Bram Moolenaarcbebd482016-02-07 23:02:56 +0100308
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100309==============================================================================
Bram Moolenaar38a55632016-02-15 22:07:32 +01003105. Channel commands *channel-commands*
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100311
Bram Moolenaar910b8aa2016-02-16 21:03:07 +0100312With a JSON channel the process can send commands to Vim that will be
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100313handled by Vim internally, it does not require a handler for the channel.
314
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100315Possible commands are: *E903* *E904* *E905*
Bram Moolenaar220adb12016-09-12 12:17:26 +0200316 ["redraw", {forced}]
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100317 ["ex", {Ex command}]
318 ["normal", {Normal mode command}]
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100319 ["expr", {expression}, {number}]
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100320 ["expr", {expression}]
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100321 ["call", {func name}, {argument list}, {number}]
322 ["call", {func name}, {argument list}]
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100323
324With all of these: Be careful what these commands do! You can easily
325interfere with what the user is doing. To avoid trouble use |mode()| to check
326that the editor is in the expected state. E.g., to send keys that must be
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100327inserted as text, not executed as a command:
328 ["ex","if mode() == 'i' | call feedkeys('ClassName') | endif"] ~
329
330Errors in these commands are normally not reported to avoid them messing up
331the display. If you do want to see them, set the 'verbose' option to 3 or
332higher.
333
334
335Command "redraw" ~
336
Bram Moolenaar63b74a82019-03-24 15:09:13 +0100337The other commands do not explicitly update the screen, so that you can send a
338sequence of commands without the cursor moving around. A redraw can happen as
339a side effect of some commands. You must end with the "redraw" command to
340show any changed text and show the cursor where it belongs.
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100341
342The argument is normally an empty string:
343 ["redraw", ""] ~
344To first clear the screen pass "force":
345 ["redraw", "force"] ~
346
347
348Command "ex" ~
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100349
350The "ex" command is executed as any Ex command. There is no response for
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100351completion or error. You could use functions in an |autoload| script:
352 ["ex","call myscript#MyFunc(arg)"]
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100353
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100354You can also use "call |feedkeys()|" to insert any key sequence.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100355
Bram Moolenaar4f3f6682016-03-26 23:01:59 +0100356When there is an error a message is written to the channel log, if it exists,
357and v:errmsg is set to the error.
358
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100359
360Command "normal" ~
361
Bram Moolenaar681baaf2016-02-04 20:57:07 +0100362The "normal" command is executed like with ":normal!", commands are not
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100363mapped. Example to open the folds under the cursor:
364 ["normal" "zO"]
365
366
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100367Command "expr" with response ~
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100368
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100369The "expr" command can be used to get the result of an expression. For
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100370example, to get the number of lines in the current buffer:
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100371 ["expr","line('$')", -2] ~
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100372
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100373It will send back the result of the expression:
Bram Moolenaare0fa3742016-02-20 15:47:01 +0100374 [-2, "last line"] ~
375The format is:
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100376 [{number}, {result}]
Bram Moolenaar187db502016-02-27 14:44:26 +0100377
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100378Here {number} is the same as what was in the request. Use a negative number
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100379to avoid confusion with message that Vim sends. Use a different number on
380every request to be able to match the request with the response.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100381
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100382{result} is the result of the evaluation and is JSON encoded. If the
Bram Moolenaar595e64e2016-02-07 19:19:53 +0100383evaluation fails or the result can't be encoded in JSON it is the string
384"ERROR".
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100385
386
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100387Command "expr" without a response ~
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100388
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100389This command is similar to "expr" above, but does not send back any response.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100390Example:
Bram Moolenaarfb1f6262016-01-31 20:24:32 +0100391 ["expr","setline('$', ['one', 'two', 'three'])"] ~
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100392There is no third argument in the request.
393
394
395Command "call" ~
396
397This is similar to "expr", but instead of passing the whole expression as a
398string this passes the name of a function and a list of arguments. This
399avoids the conversion of the arguments to a string and escaping and
400concatenating them. Example:
401 ["call", "line", ["$"], -2] ~
402
403Leave out the fourth argument if no response is to be sent:
404 ["call", "setline", ["$", ["one", "two", "three"]]] ~
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100405
406==============================================================================
Bram Moolenaar38a55632016-02-15 22:07:32 +01004076. Using a RAW or NL channel *channel-raw*
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100408
Bram Moolenaarc0514bf2016-11-17 14:50:09 +0100409If mode is RAW or NL then a message can be sent like this: >
Bram Moolenaar8b1862a2016-02-27 19:21:24 +0100410 let response = ch_evalraw(channel, {string})
Bram Moolenaar910b8aa2016-02-16 21:03:07 +0100411
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100412The {string} is sent as-is. The response will be what can be read from the
413channel right away. Since Vim doesn't know how to recognize the end of the
Bram Moolenaar38a55632016-02-15 22:07:32 +0100414message you need to take care of it yourself. The timeout applies for reading
415the first byte, after that it will not wait for anything more.
416
Bram Moolenaar910b8aa2016-02-16 21:03:07 +0100417If mode is "nl" you can send a message in a similar way. You are expected
Bram Moolenaar38a55632016-02-15 22:07:32 +0100418to put in the NL after each message. Thus you can also send several messages
419ending in a NL at once. The response will be the text up to and including the
420first NL. This can also be just the NL for an empty response.
421If no NL was read before the channel timeout an empty string is returned.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100422
423To send a message, without expecting a response: >
Bram Moolenaar8b1862a2016-02-27 19:21:24 +0100424 call ch_sendraw(channel, {string})
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100425The process can send back a response, the channel handler will be called with
426it.
427
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +0100428 *channel-onetime-callback*
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100429To send a message and letting the response handled by a specific function,
430asynchronously: >
Bram Moolenaar8b1862a2016-02-27 19:21:24 +0100431 call ch_sendraw(channel, {string}, {'callback': 'MyHandler'})
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100432
Bram Moolenaar38a55632016-02-15 22:07:32 +0100433This {string} can also be JSON, use |json_encode()| to create it and
434|json_decode()| to handle a received JSON message.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100435
Bram Moolenaar8b1862a2016-02-27 19:21:24 +0100436It is not possible to use |ch_evalexpr()| or |ch_sendexpr()| on a raw channel.
Bram Moolenaarcbebd482016-02-07 23:02:56 +0100437
Bram Moolenaar818078d2016-08-27 21:58:42 +0200438A String in Vim cannot contain NUL bytes. To send or receive NUL bytes read
439or write from a buffer. See |in_io-buffer| and |out_io-buffer|.
440
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100441==============================================================================
Bram Moolenaar38a55632016-02-15 22:07:32 +01004427. More channel functions *channel-more*
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100443
Bram Moolenaar38a55632016-02-15 22:07:32 +0100444To obtain the status of a channel: ch_status(channel). The possible results
445are:
446 "fail" Failed to open the channel.
447 "open" The channel can be used.
Bram Moolenaar06481422016-04-30 15:13:38 +0200448 "buffered" The channel was closed but there is data to read.
Bram Moolenaar38a55632016-02-15 22:07:32 +0100449 "closed" The channel was closed.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100450
Bram Moolenaar187db502016-02-27 14:44:26 +0100451To obtain the job associated with a channel: ch_getjob(channel)
Bram Moolenaar3b5f9292016-01-28 22:37:01 +0100452
Bram Moolenaar38a55632016-02-15 22:07:32 +0100453To read one message from a channel: >
454 let output = ch_read(channel)
455This uses the channel timeout. To read without a timeout, just get any
456message that is available: >
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100457 let output = ch_read(channel, {'timeout': 0})
Bram Moolenaar38a55632016-02-15 22:07:32 +0100458When no message was available then the result is v:none for a JSON or JS mode
Bram Moolenaar4b785f62016-11-29 21:54:44 +0100459channels, an empty string for a RAW or NL channel. You can use |ch_canread()|
460to check if there is something to read.
461
Bram Moolenaar05aafed2017-08-11 19:12:11 +0200462Note that when there is no callback, messages are dropped. To avoid that add
463a close callback to the channel.
Bram Moolenaar38a55632016-02-15 22:07:32 +0100464
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +0100465To read all normal output from a RAW channel that is available: >
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100466 let output = ch_readraw(channel)
Bram Moolenaar38a55632016-02-15 22:07:32 +0100467To read the error output: >
Bram Moolenaardecb14d2016-02-20 23:32:02 +0100468 let output = ch_readraw(channel, {"part": "err"})
Bram Moolenaar38a55632016-02-15 22:07:32 +0100469
Bram Moolenaar4f3f6682016-03-26 23:01:59 +0100470ch_read() and ch_readraw() use the channel timeout. When there is nothing to
471read within that time an empty string is returned. To specify a different
472timeout in msec use the "timeout" option:
473 {"timeout": 123} ~
474To read from the error output use the "part" option:
475 {"part": "err"} ~
476To read a message with a specific ID, on a JS or JSON channel:
477 {"id": 99} ~
478When no ID is specified or the ID is -1, the first message is returned. This
479overrules any callback waiting for this message.
480
481For a RAW channel this returns whatever is available, since Vim does not know
482where a message ends.
483For a NL channel this returns one message.
484For a JS or JSON channel this returns one decoded message.
485This includes any sequence number.
486
Bram Moolenaar38a55632016-02-15 22:07:32 +0100487==============================================================================
Bram Moolenaar54775062019-07-31 21:07:14 +02004888. Channel functions details *channel-functions-details*
Bram Moolenaared997ad2019-07-21 16:42:00 +0200489
490ch_canread({handle}) *ch_canread()*
491 Return non-zero when there is something to read from {handle}.
492 {handle} can be a Channel or a Job that has a Channel.
493
494 This is useful to read from a channel at a convenient time,
495 e.g. from a timer.
496
497 Note that messages are dropped when the channel does not have
498 a callback. Add a close callback to avoid that.
499
Bram Moolenaar570497a2019-08-22 22:55:13 +0200500 Can also be used as a |method|: >
501 GetChannel()->ch_canread()
Bram Moolenaared997ad2019-07-21 16:42:00 +0200502
503ch_close({handle}) *ch_close()*
504 Close {handle}. See |channel-close|.
505 {handle} can be a Channel or a Job that has a Channel.
506 A close callback is not invoked.
507
Bram Moolenaar570497a2019-08-22 22:55:13 +0200508 Can also be used as a |method|: >
509 GetChannel()->ch_close()
Bram Moolenaared997ad2019-07-21 16:42:00 +0200510
511ch_close_in({handle}) *ch_close_in()*
512 Close the "in" part of {handle}. See |channel-close-in|.
513 {handle} can be a Channel or a Job that has a Channel.
514 A close callback is not invoked.
515
Bram Moolenaar570497a2019-08-22 22:55:13 +0200516 Can also be used as a |method|: >
517 GetChannel()->ch_close_in()
518
Bram Moolenaared997ad2019-07-21 16:42:00 +0200519
520ch_evalexpr({handle}, {expr} [, {options}]) *ch_evalexpr()*
521 Send {expr} over {handle}. The {expr} is encoded
522 according to the type of channel. The function cannot be used
523 with a raw channel. See |channel-use|.
524 {handle} can be a Channel or a Job that has a Channel.
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +0100525 When using the "lsp" channel mode, {expr} must be a |Dict|.
Bram Moolenaared997ad2019-07-21 16:42:00 +0200526 *E917*
527 {options} must be a Dictionary. It must not have a "callback"
528 entry. It can have a "timeout" entry to specify the timeout
529 for this specific request.
530
531 ch_evalexpr() waits for a response and returns the decoded
532 expression. When there is an error or timeout it returns an
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +0100533 empty |String| or, when using the "lsp" channel mode, returns an
534 empty |Dict|.
Bram Moolenaared997ad2019-07-21 16:42:00 +0200535
Bram Moolenaar8fe10002019-09-11 22:56:44 +0200536 Note that while waiting for the response, Vim handles other
537 messages. You need to make sure this doesn't cause trouble.
538
Bram Moolenaar570497a2019-08-22 22:55:13 +0200539 Can also be used as a |method|: >
540 GetChannel()->ch_evalexpr(expr)
541
Bram Moolenaared997ad2019-07-21 16:42:00 +0200542
543ch_evalraw({handle}, {string} [, {options}]) *ch_evalraw()*
544 Send {string} over {handle}.
545 {handle} can be a Channel or a Job that has a Channel.
546
547 Works like |ch_evalexpr()|, but does not encode the request or
548 decode the response. The caller is responsible for the
549 correct contents. Also does not add a newline for a channel
550 in NL mode, the caller must do that. The NL in the response
551 is removed.
552 Note that Vim does not know when the text received on a raw
553 channel is complete, it may only return the first part and you
554 need to use |ch_readraw()| to fetch the rest.
555 See |channel-use|.
556
Bram Moolenaar570497a2019-08-22 22:55:13 +0200557 Can also be used as a |method|: >
558 GetChannel()->ch_evalraw(rawstring)
Bram Moolenaared997ad2019-07-21 16:42:00 +0200559
560ch_getbufnr({handle}, {what}) *ch_getbufnr()*
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200561 Get the buffer number that {handle} is using for String {what}.
Bram Moolenaared997ad2019-07-21 16:42:00 +0200562 {handle} can be a Channel or a Job that has a Channel.
563 {what} can be "err" for stderr, "out" for stdout or empty for
564 socket output.
565 Returns -1 when there is no buffer.
566
Bram Moolenaar570497a2019-08-22 22:55:13 +0200567 Can also be used as a |method|: >
568 GetChannel()->ch_getbufnr(what)
Bram Moolenaared997ad2019-07-21 16:42:00 +0200569
570ch_getjob({channel}) *ch_getjob()*
571 Get the Job associated with {channel}.
572 If there is no job calling |job_status()| on the returned Job
573 will result in "fail".
574
Bram Moolenaar570497a2019-08-22 22:55:13 +0200575 Can also be used as a |method|: >
576 GetChannel()->ch_getjob()
577
Bram Moolenaared997ad2019-07-21 16:42:00 +0200578
579ch_info({handle}) *ch_info()*
580 Returns a Dictionary with information about {handle}. The
581 items are:
582 "id" number of the channel
583 "status" "open", "buffered" or "closed", like
584 ch_status()
585 When opened with ch_open():
586 "hostname" the hostname of the address
587 "port" the port of the address
LemonBoycc766a82022-04-04 15:46:58 +0100588 "path" the path of the Unix-domain socket
Bram Moolenaared997ad2019-07-21 16:42:00 +0200589 "sock_status" "open" or "closed"
590 "sock_mode" "NL", "RAW", "JSON" or "JS"
591 "sock_io" "socket"
592 "sock_timeout" timeout in msec
LemonBoycc766a82022-04-04 15:46:58 +0100593
Bram Moolenaarcbaff5e2022-04-08 17:45:08 +0100594 Note that "path" is only present for Unix-domain sockets, for
LemonBoycc766a82022-04-04 15:46:58 +0100595 regular ones "hostname" and "port" are present instead.
596
Bram Moolenaared997ad2019-07-21 16:42:00 +0200597 When opened with job_start():
598 "out_status" "open", "buffered" or "closed"
599 "out_mode" "NL", "RAW", "JSON" or "JS"
600 "out_io" "null", "pipe", "file" or "buffer"
601 "out_timeout" timeout in msec
602 "err_status" "open", "buffered" or "closed"
603 "err_mode" "NL", "RAW", "JSON" or "JS"
604 "err_io" "out", "null", "pipe", "file" or "buffer"
605 "err_timeout" timeout in msec
606 "in_status" "open" or "closed"
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +0100607 "in_mode" "NL", "RAW", "JSON", "JS" or "LSP"
Bram Moolenaared997ad2019-07-21 16:42:00 +0200608 "in_io" "null", "pipe", "file" or "buffer"
609 "in_timeout" timeout in msec
610
Bram Moolenaar570497a2019-08-22 22:55:13 +0200611 Can also be used as a |method|: >
612 GetChannel()->ch_info()
613
Bram Moolenaared997ad2019-07-21 16:42:00 +0200614
615ch_log({msg} [, {handle}]) *ch_log()*
Bram Moolenaar6aa57292021-08-14 21:25:52 +0200616 Write String {msg} in the channel log file, if it was opened
617 with |ch_logfile()|.
Bram Moolenaared997ad2019-07-21 16:42:00 +0200618 When {handle} is passed the channel number is used for the
619 message.
620 {handle} can be a Channel or a Job that has a Channel. The
621 Channel must be open for the channel number to be used.
622
Bram Moolenaar570497a2019-08-22 22:55:13 +0200623 Can also be used as a |method|: >
624 'did something'->ch_log()
625
Bram Moolenaared997ad2019-07-21 16:42:00 +0200626
627ch_logfile({fname} [, {mode}]) *ch_logfile()*
628 Start logging channel activity to {fname}.
629 When {fname} is an empty string: stop logging.
630
631 When {mode} is omitted or "a" append to the file.
632 When {mode} is "w" start with an empty file.
633
634 Use |ch_log()| to write log messages. The file is flushed
635 after every message, on Unix you can use "tail -f" to see what
636 is going on in real time.
637
Bram Moolenaar077cc7a2020-09-04 16:35:35 +0200638 To enable the log very early, to see what is received from a
Bram Moolenaarc9a9a0a2022-04-12 15:09:23 +0100639 terminal during startup, use |--log|: >
640 vim --log logfile
Bram Moolenaar077cc7a2020-09-04 16:35:35 +0200641<
Bram Moolenaared997ad2019-07-21 16:42:00 +0200642 This function is not available in the |sandbox|.
643 NOTE: the channel communication is stored in the file, be
644 aware that this may contain confidential and privacy sensitive
645 information, e.g. a password you type in a terminal window.
646
Bram Moolenaar570497a2019-08-22 22:55:13 +0200647 Can also be used as a |method|: >
648 'logfile'->ch_logfile('w')
649
Bram Moolenaared997ad2019-07-21 16:42:00 +0200650
651ch_open({address} [, {options}]) *ch_open()*
652 Open a channel to {address}. See |channel|.
653 Returns a Channel. Use |ch_status()| to check for failure.
654
LemonBoycc766a82022-04-04 15:46:58 +0100655 {address} is a String, see |channel-address| for the possible
656 accepted forms.
Bram Moolenaarbfe13cc2020-04-12 17:53:12 +0200657
Bram Moolenaared997ad2019-07-21 16:42:00 +0200658 If {options} is given it must be a |Dictionary|.
659 See |channel-open-options|.
660
Bram Moolenaar570497a2019-08-22 22:55:13 +0200661 Can also be used as a |method|: >
662 GetAddress()->ch_open()
663
Bram Moolenaared997ad2019-07-21 16:42:00 +0200664
665ch_read({handle} [, {options}]) *ch_read()*
666 Read from {handle} and return the received message.
667 {handle} can be a Channel or a Job that has a Channel.
668 For a NL channel this waits for a NL to arrive, except when
669 there is nothing more to read (channel was closed).
670 See |channel-more|.
671
Bram Moolenaar570497a2019-08-22 22:55:13 +0200672 Can also be used as a |method|: >
673 GetChannel()->ch_read()
674
Bram Moolenaared997ad2019-07-21 16:42:00 +0200675
676ch_readblob({handle} [, {options}]) *ch_readblob()*
677 Like ch_read() but reads binary data and returns a |Blob|.
678 See |channel-more|.
679
Bram Moolenaar570497a2019-08-22 22:55:13 +0200680 Can also be used as a |method|: >
681 GetChannel()->ch_readblob()
682
Bram Moolenaared997ad2019-07-21 16:42:00 +0200683
684ch_readraw({handle} [, {options}]) *ch_readraw()*
685 Like ch_read() but for a JS and JSON channel does not decode
686 the message. For a NL channel it does not block waiting for
687 the NL to arrive, but otherwise works like ch_read().
688 See |channel-more|.
689
Bram Moolenaar570497a2019-08-22 22:55:13 +0200690 Can also be used as a |method|: >
691 GetChannel()->ch_readraw()
692
Bram Moolenaared997ad2019-07-21 16:42:00 +0200693
694ch_sendexpr({handle}, {expr} [, {options}]) *ch_sendexpr()*
695 Send {expr} over {handle}. The {expr} is encoded
696 according to the type of channel. The function cannot be used
697 with a raw channel.
698 See |channel-use|. *E912*
699 {handle} can be a Channel or a Job that has a Channel.
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +0100700 When using the "lsp" channel mode, {expr} must be a |Dict|.
Bram Moolenaared997ad2019-07-21 16:42:00 +0200701
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +0100702 If the channel mode is "lsp", then returns a Dict. Otherwise
703 returns an empty String. If the "callback" item is present in
704 {options}, then the returned Dict contains the ID of the
705 request message. The ID can be used to send a cancellation
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +0100706 request to the LSP server (if needed). Returns an empty Dict
707 on error.
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +0100708
709 If a response message is not expected for {expr}, then don't
710 specify the "callback" item in {options}.
711
Bram Moolenaar570497a2019-08-22 22:55:13 +0200712 Can also be used as a |method|: >
713 GetChannel()->ch_sendexpr(expr)
714
Bram Moolenaared997ad2019-07-21 16:42:00 +0200715
716ch_sendraw({handle}, {expr} [, {options}]) *ch_sendraw()*
717 Send |String| or |Blob| {expr} over {handle}.
718 Works like |ch_sendexpr()|, but does not encode the request or
719 decode the response. The caller is responsible for the
720 correct contents. Also does not add a newline for a channel
721 in NL mode, the caller must do that. The NL in the response
722 is removed.
723 See |channel-use|.
724
Bram Moolenaar570497a2019-08-22 22:55:13 +0200725 Can also be used as a |method|: >
726 GetChannel()->ch_sendraw(rawexpr)
727
Bram Moolenaared997ad2019-07-21 16:42:00 +0200728
729ch_setoptions({handle}, {options}) *ch_setoptions()*
730 Set options on {handle}:
731 "callback" the channel callback
732 "timeout" default read timeout in msec
733 "mode" mode for the whole channel
734 See |ch_open()| for more explanation.
735 {handle} can be a Channel or a Job that has a Channel.
736
737 Note that changing the mode may cause queued messages to be
738 lost.
739
740 These options cannot be changed:
741 "waittime" only applies to |ch_open()|
742
Bram Moolenaar570497a2019-08-22 22:55:13 +0200743 Can also be used as a |method|: >
744 GetChannel()->ch_setoptions(options)
745
Bram Moolenaared997ad2019-07-21 16:42:00 +0200746
747ch_status({handle} [, {options}]) *ch_status()*
748 Return the status of {handle}:
749 "fail" failed to open the channel
750 "open" channel can be used
751 "buffered" channel can be read, not written to
752 "closed" channel can not be used
753 {handle} can be a Channel or a Job that has a Channel.
754 "buffered" is used when the channel was closed but there is
755 still data that can be obtained with |ch_read()|.
756
757 If {options} is given it can contain a "part" entry to specify
758 the part of the channel to return the status for: "out" or
759 "err". For example, to get the error status: >
760 ch_status(job, {"part": "err"})
761<
Bram Moolenaar570497a2019-08-22 22:55:13 +0200762 Can also be used as a |method|: >
763 GetChannel()->ch_status()
Bram Moolenaared997ad2019-07-21 16:42:00 +0200764
765==============================================================================
7669. Starting a job with a channel *job-start* *job*
Bram Moolenaar38a55632016-02-15 22:07:32 +0100767
768To start a job and open a channel for stdin/stdout/stderr: >
769 let job = job_start(command, {options})
770
771You can get the channel with: >
772 let channel = job_getchannel(job)
773
774The channel will use NL mode. If you want another mode it's best to specify
775this in {options}. When changing the mode later some text may have already
776been received and not parsed correctly.
777
778If the command produces a line of output that you want to deal with, specify
779a handler for stdout: >
Bram Moolenaard6c2f052016-03-14 23:22:59 +0100780 let job = job_start(command, {"out_cb": "MyHandler"})
Bram Moolenaar38a55632016-02-15 22:07:32 +0100781The function will be called with the channel and a message. You would define
782it like this: >
783 func MyHandler(channel, msg)
784
Bram Moolenaar02e83b42016-02-21 20:10:26 +0100785Without the handler you need to read the output with |ch_read()| or
Bram Moolenaar06481422016-04-30 15:13:38 +0200786|ch_readraw()|. You can do this in the close callback, see |read-in-close-cb|.
Bram Moolenaar38a55632016-02-15 22:07:32 +0100787
Bram Moolenaar1ccd8ff2017-08-11 19:50:37 +0200788Note that if the job exits before you read the output, the output may be lost.
789This depends on the system (on Unix this happens because closing the write end
790of a pipe causes the read end to get EOF). To avoid this make the job sleep
791for a short while before it exits.
792
Bram Moolenaard6c2f052016-03-14 23:22:59 +0100793The handler defined for "out_cb" will not receive stderr. If you want to
794handle that separately, add an "err_cb" handler: >
795 let job = job_start(command, {"out_cb": "MyHandler",
796 \ "err_cb": "ErrHandler"})
Bram Moolenaar38a55632016-02-15 22:07:32 +0100797
Bram Moolenaar02e83b42016-02-21 20:10:26 +0100798If you want to handle both stderr and stdout with one handler use the
799"callback" option: >
Bram Moolenaar664f3cf2019-12-07 16:03:51 +0100800 let job = job_start(command, {"callback": "MyHandler"})
Bram Moolenaar02e83b42016-02-21 20:10:26 +0100801
Bram Moolenaar3ec574f2017-06-13 18:12:01 +0200802Depending on the system, starting a job can put Vim in the background, the
803started job gets the focus. To avoid that, use the `foreground()` function.
804This might not always work when called early, put in the callback handler or
805use a timer to call it after the job has started.
806
Bram Moolenaar8b1862a2016-02-27 19:21:24 +0100807You can send a message to the command with ch_evalraw(). If the channel is in
808JSON or JS mode you can use ch_evalexpr().
Bram Moolenaar38a55632016-02-15 22:07:32 +0100809
810There are several options you can use, see |job-options|.
Bram Moolenaar187db502016-02-27 14:44:26 +0100811For example, to start a job and write its output in buffer "dummy": >
812 let logjob = job_start("tail -f /tmp/log",
Bram Moolenaard6c2f052016-03-14 23:22:59 +0100813 \ {'out_io': 'buffer', 'out_name': 'dummy'})
Bram Moolenaar187db502016-02-27 14:44:26 +0100814 sbuf dummy
Bram Moolenaar38a55632016-02-15 22:07:32 +0100815
Bram Moolenaar5f148ec2016-03-07 22:59:26 +0100816
817Job input from a buffer ~
Bram Moolenaar818078d2016-08-27 21:58:42 +0200818 *in_io-buffer*
Bram Moolenaar328da0d2016-03-04 22:22:32 +0100819To run a job that reads from a buffer: >
820 let job = job_start({command},
Bram Moolenaard6c2f052016-03-14 23:22:59 +0100821 \ {'in_io': 'buffer', 'in_name': 'mybuffer'})
Bram Moolenaar328da0d2016-03-04 22:22:32 +0100822<
823 *E915* *E918*
824The buffer is found by name, similar to |bufnr()|. The buffer must exist and
825be loaded when job_start() is called.
826
Bram Moolenaard6c2f052016-03-14 23:22:59 +0100827By default this reads the whole buffer. This can be changed with the "in_top"
828and "in_bot" options.
Bram Moolenaar328da0d2016-03-04 22:22:32 +0100829
Bram Moolenaard6c2f052016-03-14 23:22:59 +0100830A special mode is when "in_top" is set to zero and "in_bot" is not set: Every
Bram Moolenaar74675a62017-07-15 13:53:23 +0200831time a line is added to the buffer, the last-but-one line will be sent to the
Bram Moolenaar5f148ec2016-03-07 22:59:26 +0100832job stdin. This allows for editing the last line and sending it when pressing
833Enter.
Bram Moolenaar0874a832016-09-01 15:11:51 +0200834 *channel-close-in*
835When not using the special mode the pipe or socket will be closed after the
836last line has been written. This signals the reading end that the input
837finished. You can also use |ch_close_in()| to close it sooner.
Bram Moolenaar328da0d2016-03-04 22:22:32 +0100838
Bram Moolenaar063b9d12016-07-09 20:21:48 +0200839NUL bytes in the text will be passed to the job (internally Vim stores these
840as NL bytes).
841
Bram Moolenaar06481422016-04-30 15:13:38 +0200842
843Reading job output in the close callback ~
844 *read-in-close-cb*
845If the job can take some time and you don't need intermediate results, you can
846add a close callback and read the output there: >
847
848 func! CloseHandler(channel)
Bram Moolenaar2ec618c2016-10-01 14:47:05 +0200849 while ch_status(a:channel, {'part': 'out'}) == 'buffered'
Bram Moolenaar06481422016-04-30 15:13:38 +0200850 echomsg ch_read(a:channel)
851 endwhile
852 endfunc
853 let job = job_start(command, {'close_cb': 'CloseHandler'})
854
855You will want to do something more useful than "echomsg".
856
Bram Moolenaar38a55632016-02-15 22:07:32 +0100857==============================================================================
Bram Moolenaared997ad2019-07-21 16:42:00 +020085810. Starting a job without a channel *job-start-nochannel*
Bram Moolenaar38a55632016-02-15 22:07:32 +0100859
860To start another process without creating a channel: >
Bram Moolenaar328da0d2016-03-04 22:22:32 +0100861 let job = job_start(command,
Bram Moolenaar51628222016-12-01 23:03:28 +0100862 \ {"in_io": "null", "out_io": "null", "err_io": "null"})
Bram Moolenaar38a55632016-02-15 22:07:32 +0100863
864This starts {command} in the background, Vim does not wait for it to finish.
865
Bram Moolenaar38a55632016-02-15 22:07:32 +0100866When Vim sees that neither stdin, stdout or stderr are connected, no channel
867will be created. Often you will want to include redirection in the command to
868avoid it getting stuck.
869
870There are several options you can use, see |job-options|.
871
Bram Moolenaar77cdfd12016-03-12 12:57:59 +0100872 *job-start-if-needed*
873To start a job only when connecting to an address does not work, do something
874like this: >
Bram Moolenaar38a55632016-02-15 22:07:32 +0100875 let channel = ch_open(address, {"waittime": 0})
876 if ch_status(channel) == "fail"
877 let job = job_start(command)
878 let channel = ch_open(address, {"waittime": 1000})
Bram Moolenaar38a55632016-02-15 22:07:32 +0100879 endif
Bram Moolenaar77cdfd12016-03-12 12:57:59 +0100880
881Note that the waittime for ch_open() gives the job one second to make the port
882available.
Bram Moolenaar38a55632016-02-15 22:07:32 +0100883
884==============================================================================
Bram Moolenaared997ad2019-07-21 16:42:00 +020088511. Job functions *job-functions-details*
886
887job_getchannel({job}) *job_getchannel()*
888 Get the channel handle that {job} is using.
889 To check if the job has no channel: >
Yegappan Lakshmanan1a71d312021-07-15 12:49:58 +0200890 if string(job_getchannel(job)) == 'channel fail'
Bram Moolenaared997ad2019-07-21 16:42:00 +0200891<
Bram Moolenaar570497a2019-08-22 22:55:13 +0200892 Can also be used as a |method|: >
893 GetJob()->job_getchannel()
Bram Moolenaared997ad2019-07-21 16:42:00 +0200894
895job_info([{job}]) *job_info()*
896 Returns a Dictionary with information about {job}:
897 "status" what |job_status()| returns
898 "channel" what |job_getchannel()| returns
899 "cmd" List of command arguments used to start the job
900 "process" process ID
901 "tty_in" terminal input name, empty when none
902 "tty_out" terminal output name, empty when none
903 "exitval" only valid when "status" is "dead"
904 "exit_cb" function to be called on exit
905 "stoponexit" |job-stoponexit|
906
907 Only in Unix:
908 "termsig" the signal which terminated the process
909 (See |job_stop()| for the values)
910 only valid when "status" is "dead"
911
912 Only in MS-Windows:
913 "tty_type" Type of virtual console in use.
914 Values are "winpty" or "conpty".
915 See 'termwintype'.
916
917 Without any arguments, returns a List with all Job objects.
918
Bram Moolenaar570497a2019-08-22 22:55:13 +0200919 Can also be used as a |method|: >
920 GetJob()->job_info()
921
Bram Moolenaared997ad2019-07-21 16:42:00 +0200922
923job_setoptions({job}, {options}) *job_setoptions()*
924 Change options for {job}. Supported are:
925 "stoponexit" |job-stoponexit|
926 "exit_cb" |job-exit_cb|
927
Bram Moolenaar570497a2019-08-22 22:55:13 +0200928 Can also be used as a |method|: >
929 GetJob()->job_setoptions(options)
930
Bram Moolenaared997ad2019-07-21 16:42:00 +0200931
932job_start({command} [, {options}]) *job_start()*
933 Start a job and return a Job object. Unlike |system()| and
934 |:!cmd| this does not wait for the job to finish.
935 To start a job in a terminal window see |term_start()|.
936
937 If the job fails to start then |job_status()| on the returned
938 Job object results in "fail" and none of the callbacks will be
939 invoked.
940
941 {command} can be a String. This works best on MS-Windows. On
942 Unix it is split up in white-separated parts to be passed to
943 execvp(). Arguments in double quotes can contain white space.
944
945 {command} can be a List, where the first item is the executable
946 and further items are the arguments. All items are converted
947 to String. This works best on Unix.
948
949 On MS-Windows, job_start() makes a GUI application hidden. If
950 want to show it, Use |:!start| instead.
951
952 The command is executed directly, not through a shell, the
953 'shell' option is not used. To use the shell: >
954 let job = job_start(["/bin/sh", "-c", "echo hello"])
955< Or: >
956 let job = job_start('/bin/sh -c "echo hello"')
957< Note that this will start two processes, the shell and the
958 command it executes. If you don't want this use the "exec"
959 shell command.
960
961 On Unix $PATH is used to search for the executable only when
962 the command does not contain a slash.
963
964 The job will use the same terminal as Vim. If it reads from
965 stdin the job and Vim will be fighting over input, that
966 doesn't work. Redirect stdin and stdout to avoid problems: >
967 let job = job_start(['sh', '-c', "myserver </dev/null >/dev/null"])
968<
969 The returned Job object can be used to get the status with
970 |job_status()| and stop the job with |job_stop()|.
971
972 Note that the job object will be deleted if there are no
973 references to it. This closes the stdin and stderr, which may
974 cause the job to fail with an error. To avoid this keep a
975 reference to the job. Thus instead of: >
976 call job_start('my-command')
977< use: >
978 let myjob = job_start('my-command')
979< and unlet "myjob" once the job is not needed or is past the
980 point where it would fail (e.g. when it prints a message on
981 startup). Keep in mind that variables local to a function
982 will cease to exist if the function returns. Use a
983 script-local variable if needed: >
984 let s:myjob = job_start('my-command')
985<
986 {options} must be a Dictionary. It can contain many optional
987 items, see |job-options|.
988
Bram Moolenaar570497a2019-08-22 22:55:13 +0200989 Can also be used as a |method|: >
990 BuildCommand()->job_start()
991
Bram Moolenaared997ad2019-07-21 16:42:00 +0200992
993job_status({job}) *job_status()* *E916*
994 Returns a String with the status of {job}:
995 "run" job is running
996 "fail" job failed to start
997 "dead" job died or was stopped after running
998
999 On Unix a non-existing command results in "dead" instead of
1000 "fail", because a fork happens before the failure can be
1001 detected.
1002
Bram Moolenaarcb80aa22020-10-26 21:12:46 +01001003 If in Vim9 script a variable is declared with type "job" but
1004 never assigned to, passing that variable to job_status()
1005 returns "fail".
1006
Bram Moolenaared997ad2019-07-21 16:42:00 +02001007 If an exit callback was set with the "exit_cb" option and the
1008 job is now detected to be "dead" the callback will be invoked.
1009
1010 For more information see |job_info()|.
1011
Bram Moolenaar570497a2019-08-22 22:55:13 +02001012 Can also be used as a |method|: >
1013 GetJob()->job_status()
1014
Bram Moolenaared997ad2019-07-21 16:42:00 +02001015
1016job_stop({job} [, {how}]) *job_stop()*
1017 Stop the {job}. This can also be used to signal the job.
1018
1019 When {how} is omitted or is "term" the job will be terminated.
1020 For Unix SIGTERM is sent. On MS-Windows the job will be
1021 terminated forcedly (there is no "gentle" way).
1022 This goes to the process group, thus children may also be
1023 affected.
1024
1025 Effect for Unix:
1026 "term" SIGTERM (default)
1027 "hup" SIGHUP
1028 "quit" SIGQUIT
1029 "int" SIGINT
1030 "kill" SIGKILL (strongest way to stop)
1031 number signal with that number
1032
1033 Effect for MS-Windows:
1034 "term" terminate process forcedly (default)
1035 "hup" CTRL_BREAK
1036 "quit" CTRL_BREAK
1037 "int" CTRL_C
1038 "kill" terminate process forcedly
1039 Others CTRL_BREAK
1040
1041 On Unix the signal is sent to the process group. This means
1042 that when the job is "sh -c command" it affects both the shell
1043 and the command.
1044
1045 The result is a Number: 1 if the operation could be executed,
1046 0 if "how" is not supported on the system.
1047 Note that even when the operation was executed, whether the
1048 job was actually stopped needs to be checked with
1049 |job_status()|.
1050
1051 If the status of the job is "dead", the signal will not be
1052 sent. This is to avoid to stop the wrong job (esp. on Unix,
1053 where process numbers are recycled).
1054
1055 When using "kill" Vim will assume the job will die and close
1056 the channel.
1057
Bram Moolenaar570497a2019-08-22 22:55:13 +02001058 Can also be used as a |method|: >
1059 GetJob()->job_stop()
1060
Bram Moolenaared997ad2019-07-21 16:42:00 +02001061
1062==============================================================================
106312. Job options *job-options*
Bram Moolenaar38a55632016-02-15 22:07:32 +01001064
1065The {options} argument in job_start() is a dictionary. All entries are
Bram Moolenaar02e83b42016-02-21 20:10:26 +01001066optional. Some options can be used after the job has started, using
1067job_setoptions(job, {options}). Many options can be used with the channel
1068related to the job, using ch_setoptions(channel, {options}).
1069See |job_setoptions()| and |ch_setoptions()|.
Bram Moolenaar38a55632016-02-15 22:07:32 +01001070
Bram Moolenaar4f3f6682016-03-26 23:01:59 +01001071 *in_mode* *out_mode* *err_mode*
1072"in_mode" mode specifically for stdin, only when using pipes
1073"out_mode" mode specifically for stdout, only when using pipes
1074"err_mode" mode specifically for stderr, only when using pipes
1075 See |channel-mode| for the values.
1076
1077 Note: when setting "mode" the part specific mode is
1078 overwritten. Therefore set "mode" first and the part
1079 specific mode later.
1080
1081 Note: when writing to a file or buffer and when
1082 reading from a buffer NL mode is used by default.
1083
Bram Moolenaar0b146882018-09-06 16:27:24 +02001084 *job-noblock*
1085"noblock": 1 When writing use a non-blocking write call. This
1086 avoids getting stuck if Vim should handle other
1087 messages in between, e.g. when a job sends back data
1088 to Vim. It implies that when `ch_sendraw()` returns
1089 not all data may have been written yet.
1090 This option was added in patch 8.1.0350, test with: >
1091 if has("patch-8.1.350")
1092 let options['noblock'] = 1
1093 endif
1094<
Bram Moolenaardecb14d2016-02-20 23:32:02 +01001095 *job-callback*
1096"callback": handler Callback for something to read on any part of the
1097 channel.
Bram Moolenaar4f3f6682016-03-26 23:01:59 +01001098 *job-out_cb* *out_cb*
Bram Moolenaard6c2f052016-03-14 23:22:59 +01001099"out_cb": handler Callback for when there is something to read on
Bram Moolenaar4f3f6682016-03-26 23:01:59 +01001100 stdout. Only for when the channel uses pipes. When
1101 "out_cb" wasn't set the channel callback is used.
Bram Moolenaar269f5952016-07-15 22:54:41 +02001102 The two arguments are the channel and the message.
Bram Moolenaar4f3f6682016-03-26 23:01:59 +01001103
1104 *job-err_cb* *err_cb*
Bram Moolenaard6c2f052016-03-14 23:22:59 +01001105"err_cb": handler Callback for when there is something to read on
Bram Moolenaar4f3f6682016-03-26 23:01:59 +01001106 stderr. Only for when the channel uses pipes. When
1107 "err_cb" wasn't set the channel callback is used.
Bram Moolenaar269f5952016-07-15 22:54:41 +02001108 The two arguments are the channel and the message.
Bram Moolenaard6c2f052016-03-14 23:22:59 +01001109 *job-close_cb*
1110"close_cb": handler Callback for when the channel is closed. Same as
Bram Moolenaar82af8712016-06-04 20:20:29 +02001111 "close_cb" on |ch_open()|, see |close_cb|.
Bram Moolenaarbc2eada2017-01-02 21:27:47 +01001112 *job-drop*
Bram Moolenaarb6e0ec62017-07-23 22:12:20 +02001113"drop": when Specifies when to drop messages. Same as "drop" on
Bram Moolenaar51628222016-12-01 23:03:28 +01001114 |ch_open()|, see |channel-drop|. For "auto" the
1115 exit_cb is not considered.
Bram Moolenaarbc2eada2017-01-02 21:27:47 +01001116 *job-exit_cb*
Bram Moolenaard6c2f052016-03-14 23:22:59 +01001117"exit_cb": handler Callback for when the job ends. The arguments are the
Bram Moolenaar38a55632016-02-15 22:07:32 +01001118 job and the exit status.
Bram Moolenaarb4ada792016-10-30 21:55:26 +01001119 Vim checks up to 10 times per second for jobs that
1120 ended. The check can also be triggered by calling
1121 |job_status()|, which may then invoke the exit_cb
1122 handler.
Bram Moolenaar06d2d382016-05-20 17:24:11 +02001123 Note that data can be buffered, callbacks may still be
1124 called after the process ends.
Bram Moolenaar4f3f6682016-03-26 23:01:59 +01001125 *job-timeout*
Bram Moolenaarb6e0ec62017-07-23 22:12:20 +02001126"timeout": time The time to wait for a request when blocking, E.g.
Bram Moolenaar4f3f6682016-03-26 23:01:59 +01001127 when using ch_evalexpr(). In milliseconds. The
1128 default is 2000 (2 seconds).
1129 *out_timeout* *err_timeout*
Bram Moolenaarb6e0ec62017-07-23 22:12:20 +02001130"out_timeout": time Timeout for stdout. Only when using pipes.
1131"err_timeout": time Timeout for stderr. Only when using pipes.
Bram Moolenaar4f3f6682016-03-26 23:01:59 +01001132 Note: when setting "timeout" the part specific mode is
1133 overwritten. Therefore set "timeout" first and the
1134 part specific mode later.
1135
Bram Moolenaar02e83b42016-02-21 20:10:26 +01001136 *job-stoponexit*
1137"stoponexit": {signal} Send {signal} to the job when Vim exits. See
1138 |job_stop()| for possible values.
1139"stoponexit": "" Do not stop the job when Vim exits.
1140 The default is "term".
1141
Bram Moolenaar77cdfd12016-03-12 12:57:59 +01001142 *job-term*
Bram Moolenaarb6e0ec62017-07-23 22:12:20 +02001143"term": "open" Start a terminal in a new window and connect the job
1144 stdin/stdout/stderr to it. Similar to using
1145 `:terminal`.
Bram Moolenaar77cdfd12016-03-12 12:57:59 +01001146 NOTE: Not implemented yet!
Bram Moolenaar38a55632016-02-15 22:07:32 +01001147
Bram Moolenaar77cdfd12016-03-12 12:57:59 +01001148"channel": {channel} Use an existing channel instead of creating a new one.
1149 The parts of the channel that get used for the new job
1150 will be disconnected from what they were used before.
Bram Moolenaar51628222016-12-01 23:03:28 +01001151 If the channel was still used by another job this may
Bram Moolenaar77cdfd12016-03-12 12:57:59 +01001152 cause I/O errors.
1153 Existing callbacks and other settings remain.
1154
Bram Moolenaarb6e0ec62017-07-23 22:12:20 +02001155"pty": 1 Use a pty (pseudo-tty) instead of a pipe when
1156 possible. This is most useful in combination with a
1157 terminal window, see |terminal|.
1158 {only on Unix and Unix-like systems}
1159
Bram Moolenaard6c2f052016-03-14 23:22:59 +01001160 *job-in_io* *in_top* *in_bot* *in_name* *in_buf*
1161"in_io": "null" disconnect stdin (read from /dev/null)
1162"in_io": "pipe" stdin is connected to the channel (default)
1163"in_io": "file" stdin reads from a file
1164"in_io": "buffer" stdin reads from a buffer
1165"in_top": number when using "buffer": first line to send (default: 1)
1166"in_bot": number when using "buffer": last line to send (default: last)
1167"in_name": "/path/file" the name of the file or buffer to read from
1168"in_buf": number the number of the buffer to read from
Bram Moolenaar38a55632016-02-15 22:07:32 +01001169
Bram Moolenaard6c2f052016-03-14 23:22:59 +01001170 *job-out_io* *out_name* *out_buf*
1171"out_io": "null" disconnect stdout (goes to /dev/null)
1172"out_io": "pipe" stdout is connected to the channel (default)
1173"out_io": "file" stdout writes to a file
Bram Moolenaar51628222016-12-01 23:03:28 +01001174"out_io": "buffer" stdout appends to a buffer (see below)
Bram Moolenaard6c2f052016-03-14 23:22:59 +01001175"out_name": "/path/file" the name of the file or buffer to write to
1176"out_buf": number the number of the buffer to write to
Bram Moolenaar9f5842e2016-05-29 16:17:08 +02001177"out_modifiable": 0 when writing to a buffer, 'modifiable' will be off
1178 (see below)
Bram Moolenaar169ebb02016-09-07 23:32:23 +02001179"out_msg": 0 when writing to a new buffer, the first line will be
1180 set to "Reading from channel output..."
Bram Moolenaar38a55632016-02-15 22:07:32 +01001181
Bram Moolenaard6c2f052016-03-14 23:22:59 +01001182 *job-err_io* *err_name* *err_buf*
1183"err_io": "out" stderr messages to go to stdout
1184"err_io": "null" disconnect stderr (goes to /dev/null)
1185"err_io": "pipe" stderr is connected to the channel (default)
1186"err_io": "file" stderr writes to a file
Bram Moolenaar51628222016-12-01 23:03:28 +01001187"err_io": "buffer" stderr appends to a buffer (see below)
Bram Moolenaard6c2f052016-03-14 23:22:59 +01001188"err_name": "/path/file" the name of the file or buffer to write to
1189"err_buf": number the number of the buffer to write to
Bram Moolenaar9f5842e2016-05-29 16:17:08 +02001190"err_modifiable": 0 when writing to a buffer, 'modifiable' will be off
1191 (see below)
Bram Moolenaar169ebb02016-09-07 23:32:23 +02001192"err_msg": 0 when writing to a new buffer, the first line will be
1193 set to "Reading from channel error..."
Bram Moolenaar77cdfd12016-03-12 12:57:59 +01001194
Bram Moolenaar7db8f6f2016-03-29 23:12:46 +02001195"block_write": number only for testing: pretend every other write to stdin
1196 will block
1197
Bram Moolenaar05aafed2017-08-11 19:12:11 +02001198"env": dict environment variables for the new process
1199"cwd": "/path/to/dir" current working directory for the new process;
1200 if the directory does not exist an error is given
1201
Bram Moolenaar77cdfd12016-03-12 12:57:59 +01001202
1203Writing to a buffer ~
Bram Moolenaar818078d2016-08-27 21:58:42 +02001204 *out_io-buffer*
Bram Moolenaard6c2f052016-03-14 23:22:59 +01001205When the out_io or err_io mode is "buffer" and there is a callback, the text
Bram Moolenaar5f148ec2016-03-07 22:59:26 +01001206is appended to the buffer before invoking the callback.
1207
1208When a buffer is used both for input and output, the output lines are put
1209above the last line, since the last line is what is written to the channel
Bram Moolenaar77cdfd12016-03-12 12:57:59 +01001210input. Otherwise lines are appended below the last line.
Bram Moolenaarc7f0ebc2016-02-27 21:10:09 +01001211
Bram Moolenaar328da0d2016-03-04 22:22:32 +01001212When using JS or JSON mode with "buffer", only messages with zero or negative
1213ID will be added to the buffer, after decoding + encoding. Messages with a
1214positive number will be handled by a callback, commands are handled as usual.
1215
Bram Moolenaar82af8712016-06-04 20:20:29 +02001216The name of the buffer from "out_name" or "err_name" is compared the full name
1217of existing buffers, also after expanding the name for the current directory.
1218E.g., when a buffer was created with ":edit somename" and the buffer name is
1219"somename" it will use that buffer.
1220
1221If there is no matching buffer a new buffer is created. Use an empty name to
1222always create a new buffer. |ch_getbufnr()| can then be used to get the
1223buffer number.
Bram Moolenaarc7f0ebc2016-02-27 21:10:09 +01001224
1225For a new buffer 'buftype' is set to "nofile" and 'bufhidden' to "hide". If
1226you prefer other settings, create the buffer first and pass the buffer number.
Bram Moolenaar169ebb02016-09-07 23:32:23 +02001227 *out_modifiable* *err_modifiable*
Bram Moolenaar9f5842e2016-05-29 16:17:08 +02001228The "out_modifiable" and "err_modifiable" options can be used to set the
1229'modifiable' option off, or write to a buffer that has 'modifiable' off. That
1230means that lines will be appended to the buffer, but the user can't easily
1231change the buffer.
Bram Moolenaar169ebb02016-09-07 23:32:23 +02001232 *out_msg* *err_msg*
1233The "out_msg" option can be used to specify whether a new buffer will have the
1234first line set to "Reading from channel output...". The default is to add the
1235message. "err_msg" does the same for channel error.
1236
Bram Moolenaar9f5842e2016-05-29 16:17:08 +02001237When an existing buffer is to be written where 'modifiable' is off and the
1238"out_modifiable" or "err_modifiable" options is not zero, an error is given
1239and the buffer will not be written to.
1240
Bram Moolenaar187db502016-02-27 14:44:26 +01001241When the buffer written to is displayed in a window and the cursor is in the
1242first column of the last line, the cursor will be moved to the newly added
1243line and the window is scrolled up to show the cursor if needed.
1244
Bram Moolenaar063b9d12016-07-09 20:21:48 +02001245Undo is synced for every added line. NUL bytes are accepted (internally Vim
1246stores these as NL bytes).
Bram Moolenaar38a55632016-02-15 22:07:32 +01001247
Bram Moolenaar77cdfd12016-03-12 12:57:59 +01001248
1249Writing to a file ~
Bram Moolenaard6c2f052016-03-14 23:22:59 +01001250 *E920*
Bram Moolenaar77cdfd12016-03-12 12:57:59 +01001251The file is created with permissions 600 (read-write for the user, not
1252accessible for others). Use |setfperm()| to change this.
1253
1254If the file already exists it is truncated.
1255
Bram Moolenaar38a55632016-02-15 22:07:32 +01001256==============================================================================
Bram Moolenaared997ad2019-07-21 16:42:00 +0200125713. Controlling a job *job-control*
Bram Moolenaar38a55632016-02-15 22:07:32 +01001258
1259To get the status of a job: >
1260 echo job_status(job)
1261
1262To make a job stop running: >
1263 job_stop(job)
1264
1265This is the normal way to end a job. On Unix it sends a SIGTERM to the job.
1266It is possible to use other ways to stop the job, or even send arbitrary
1267signals. E.g. to force a job to stop, "kill it": >
1268 job_stop(job, "kill")
1269
1270For more options see |job_stop()|.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +01001271
Bram Moolenaarf2732452018-06-03 14:47:35 +02001272==============================================================================
Bram Moolenaared997ad2019-07-21 16:42:00 +0200127314. Using a prompt buffer *prompt-buffer*
Bram Moolenaarf2732452018-06-03 14:47:35 +02001274
1275If you want to type input for the job in a Vim window you have a few options:
1276- Use a normal buffer and handle all possible commands yourself.
1277 This will be complicated, since there are so many possible commands.
1278- Use a terminal window. This works well if what you type goes directly to
1279 the job and the job output is directly displayed in the window.
1280 See |terminal-window|.
Bram Moolenaaracc22402020-06-07 21:07:18 +02001281- Use a window with a prompt buffer. This works well when entering a line for
1282 the job in Vim while displaying (possibly filtered) output from the job.
Bram Moolenaarf2732452018-06-03 14:47:35 +02001283
1284A prompt buffer is created by setting 'buftype' to "prompt". You would
1285normally only do that in a newly created buffer.
1286
1287The user can edit and enter one line of text at the very last line of the
1288buffer. When pressing Enter in the prompt line the callback set with
1289|prompt_setcallback()| is invoked. It would normally send the line to a job.
1290Another callback would receive the output from the job and display it in the
1291buffer, below the prompt (and above the next prompt).
1292
1293Only the text in the last line, after the prompt, is editable. The rest of the
1294buffer is not modifiable with Normal mode commands. It can be modified by
1295calling functions, such as |append()|. Using other commands may mess up the
1296buffer.
1297
1298After setting 'buftype' to "prompt" Vim does not automatically start Insert
1299mode, use `:startinsert` if you want to enter Insert mode, so that the user
1300can start typing a line.
1301
Bram Moolenaar077cc7a2020-09-04 16:35:35 +02001302The text of the prompt can be set with the |prompt_setprompt()| function. If
1303no prompt is set with |prompt_setprompt()|, "% " is used. You can get the
1304effective prompt text for a buffer, with |prompt_getprompt()|.
Bram Moolenaarf2732452018-06-03 14:47:35 +02001305
1306The user can go to Normal mode and navigate through the buffer. This can be
Bram Moolenaar7ff78462020-07-10 22:00:53 +02001307useful to see older output or copy text.
Bram Moolenaarf2732452018-06-03 14:47:35 +02001308
Bram Moolenaard2f3a8b2018-06-19 14:35:59 +02001309The CTRL-W key can be used to start a window command, such as CTRL-W w to
1310switch to the next window. This also works in Insert mode (use Shift-CTRL-W
1311to delete a word). When leaving the window Insert mode will be stopped. When
1312coming back to the prompt window Insert mode will be restored.
1313
Bram Moolenaarf2732452018-06-03 14:47:35 +02001314Any command that starts Insert mode, such as "a", "i", "A" and "I", will move
Bram Moolenaard2f3a8b2018-06-19 14:35:59 +02001315the cursor to the last line. "A" will move to the end of the line, "I" to the
1316start of the line.
Bram Moolenaarf2732452018-06-03 14:47:35 +02001317
Bram Moolenaaracc22402020-06-07 21:07:18 +02001318Here is an example for Unix. It starts a shell in the background and prompts
1319for the next shell command. Output from the shell is displayed above the
1320prompt. >
1321
1322 " Create a channel log so we can see what happens.
1323 call ch_logfile('logfile', 'w')
1324
Bram Moolenaar1588bc82022-03-08 21:35:07 +00001325 " Function handling a line of text that has been typed.
Bram Moolenaaracc22402020-06-07 21:07:18 +02001326 func TextEntered(text)
1327 " Send the text to a shell with Enter appended.
1328 call ch_sendraw(g:shell_job, a:text .. "\n")
1329 endfunc
Bram Moolenaarcb80aa22020-10-26 21:12:46 +01001330
Bram Moolenaar1588bc82022-03-08 21:35:07 +00001331 " Function handling output from the shell: Add it above the prompt.
Bram Moolenaaracc22402020-06-07 21:07:18 +02001332 func GotOutput(channel, msg)
Bram Moolenaarc51cf032022-02-26 12:25:45 +00001333 call append(line("$") - 1, "- " .. a:msg)
Bram Moolenaaracc22402020-06-07 21:07:18 +02001334 endfunc
1335
Bram Moolenaar1588bc82022-03-08 21:35:07 +00001336 " Function handling the shell exits: close the window.
Bram Moolenaaracc22402020-06-07 21:07:18 +02001337 func JobExit(job, status)
1338 quit!
1339 endfunc
1340
1341 " Start a shell in the background.
1342 let shell_job = job_start(["/bin/sh"], #{
1343 \ out_cb: function('GotOutput'),
1344 \ err_cb: function('GotOutput'),
1345 \ exit_cb: function('JobExit'),
1346 \ })
Bram Moolenaaracc22402020-06-07 21:07:18 +02001347
1348 new
1349 set buftype=prompt
1350 let buf = bufnr('')
1351 call prompt_setcallback(buf, function("TextEntered"))
1352 eval prompt_setprompt(buf, "shell command: ")
1353
1354 " start accepting shell commands
1355 startinsert
1356<
Bram Moolenaar1588bc82022-03-08 21:35:07 +00001357The same in |Vim9| script: >
1358
1359 vim9script
1360
1361 # Create a channel log so we can see what happens.
1362 ch_logfile('logfile', 'w')
1363
1364 var shell_job: job
1365
1366 # Function handling a line of text that has been typed.
1367 def TextEntered(text: string)
1368 # Send the text to a shell with Enter appended.
1369 ch_sendraw(shell_job, text .. "\n")
1370 enddef
1371
1372 # Function handling output from the shell: Add it above the prompt.
1373 def GotOutput(channel: channel, msg: string)
1374 append(line("$") - 1, "- " .. msg)
1375 enddef
1376
1377 # Function handling the shell exits: close the window.
1378 def JobExit(job: job, status: number)
1379 quit!
1380 enddef
1381
1382 # Start a shell in the background.
1383 shell_job = job_start(["/bin/sh"], {
1384 out_cb: GotOutput,
1385 err_cb: GotOutput,
1386 exit_cb: JobExit,
1387 })
1388
1389 new
1390 set buftype=prompt
1391 var buf = bufnr('')
1392 prompt_setcallback(buf, TextEntered)
1393 prompt_setprompt(buf, "shell command: ")
1394
1395 # start accepting shell commands
1396 startinsert
Bram Moolenaaracc22402020-06-07 21:07:18 +02001397
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001398==============================================================================
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +0100139915. Language Server Protocol *language-server-protocol*
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001400
1401The language server protocol specification is available at:
1402
1403 https://microsoft.github.io/language-server-protocol/specification
1404
1405Each LSP protocol message starts with a simple HTTP header followed by the
1406payload encoded in JSON-RPC format. This is described in:
1407
1408 https://www.jsonrpc.org/specification
1409
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +01001410To encode and send a LSP request/notification message in a Vim |Dict| into a
1411LSP JSON-RPC message and to receive and decode a LSP JSON-RPC
1412response/notification message into a Vim |Dict|, connect to the LSP server
1413with the |channel-mode| set to "lsp".
1414
1415For messages received on a channel with |channel-mode| set to "lsp", Vim will
1416process the HTTP header and decode the JSON-RPC payload into a Vim |Dict| type
1417and call the |channel-callback| function or the specified
1418|channel-onetime-callback| function. When sending messages on a channel using
1419the |ch_evalexpr()| or |ch_sendexpr()| functions, Vim will add the HTTP header
1420and encode the Vim expression into JSON. Refer to |json_encode()| and
1421|json_decode()| for more information about how Vim encodes and decodes the
1422builtin types into JSON.
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001423
1424To open a channel using the 'lsp' mode, set the 'mode' item in the |ch_open()|
1425{options} argument to 'lsp'. Example: >
1426
1427 let ch = ch_open(..., #{mode: 'lsp'})
1428
1429To open a channel using the 'lsp' mode with a job, set the 'in_mode' and
1430'out_mode' items in the |job_start()| {options} argument to 'lsp'. Example: >
1431
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +01001432 let cmd = ['clangd', '--background-index', '--clang-tidy']
1433 let opts = {}
1434 let opts.in_mode = 'lsp'
1435 let opts.out_mode = 'lsp'
Yegappan Lakshmanan03cca292022-04-18 14:07:46 +01001436 let opts.err_mode = 'nl'
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +01001437 let opts.out_cb = function('LspOutCallback')
1438 let opts.err_cb = function('LspErrCallback')
1439 let opts.exit_cb = function('LspExitCallback')
1440 let job = job_start(cmd, opts)
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001441
Yegappan Lakshmanan03cca292022-04-18 14:07:46 +01001442Note that if a job outputs LSP messages on stdout and non-LSP messages on
1443stderr, then the channel-callback function should handle both the message
1444formats appropriately or you should use a separate callback function for
1445"out_cb" and "err_cb" to handle them as shown above.
1446
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +01001447To synchronously send a JSON-RPC request to the server, use the
1448|ch_evalexpr()| function. This function will wait and return the decoded
1449response message from the server. You can use either the |channel-timeout| or
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001450the 'timeout' field in the {options} argument to control the response wait
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +01001451time. If the request times out, then an empty |Dict| is returned. Example: >
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001452
1453 let req = {}
1454 let req.method = 'textDocument/definition'
1455 let req.params = {}
1456 let req.params.textDocument = #{uri: 'a.c'}
1457 let req.params.position = #{line: 10, character: 3}
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +01001458 let defs = ch_evalexpr(ch, req, #{timeout: 100})
1459 if defs->empty()
1460 ... <handle failure>
1461 endif
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001462
1463Note that in the request message the 'id' field should not be specified. If it
1464is specified, then Vim will overwrite the value with an internally generated
1465identifier. Vim currently supports only a number type for the 'id' field.
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +01001466The callback function will be invoked for both a successful and a failed RPC
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +01001467request.
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001468
1469To send a JSON-RPC request to the server and asynchronously process the
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +01001470response, use the |ch_sendexpr()| function and supply a callback function. If
1471the "id" field is present in the request message, then Vim will overwrite it
1472with an internally generated number. This function returns a Dict with the
1473identifier used for the message. This can be used to send cancellation
1474request to the LSP server (if needed). Example: >
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001475
1476 let req = {}
1477 let req.method = 'textDocument/hover'
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +01001478 let req.id = 200
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001479 let req.params = {}
1480 let req.params.textDocument = #{uri: 'a.c'}
1481 let req.params.position = #{line: 10, character: 3}
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +01001482 let resp = ch_sendexpr(ch, req, #{callback: 'HoverFunc'})
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001483
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +01001484To cancel an outstanding asynchronous LSP request sent to the server using the
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +01001485|ch_sendexpr()| function, send a cancelation message to the server using the
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +01001486|ch_sendexpr()| function with the ID returned by the |ch_sendexpr()| function
1487for the request. Example: >
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +01001488
1489 " send a completion request
1490 let req = {}
1491 let req.method = 'textDocument/completion'
1492 let req.params = {}
1493 let req.params.textDocument = #{uri: 'a.c'}
1494 let req.params.position = #{line: 10, character: 3}
Yegappan Lakshmanane0805b82022-04-16 15:18:23 +01001495 let reqstatus = ch_sendexpr(ch, req, #{callback: 'LspComplete'})
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +01001496 " send a cancellation notification
1497 let notif = {}
1498 let notif.method = '$/cancelRequest'
1499 let notif.id = reqstatus.id
1500 call ch_sendexpr(ch, notif)
1501
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001502To send a JSON-RPC notification message to the server, use the |ch_sendexpr()|
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +01001503function. As the server will not send a response message to the notification,
1504don't specify the "callback" item. Example: >
Yegappan Lakshmanan9247a222022-03-30 10:16:05 +01001505
1506 call ch_sendexpr(ch, #{method: 'initialized'})
1507
1508To respond to a JSON-RPC request message from the server, use the
1509|ch_sendexpr()| function. In the response message, copy the 'id' field value
1510from the server request message. Example: >
1511
1512 let resp = {}
1513 let resp.id = req.id
1514 let resp.result = 1
1515 call ch_sendexpr(ch, resp)
1516
1517The JSON-RPC notification messages from the server are delivered through the
1518|channel-callback| function.
Bram Moolenaar3b5f9292016-01-28 22:37:01 +01001519
Yegappan Lakshmanan3b470ae2022-04-16 10:41:27 +01001520Depending on the use case, you can use the ch_evalexpr(), ch_sendexpr() and
1521ch_sendraw() functions on the same channel.
1522
1523A LSP request message has the following format (expressed as a Vim Dict). The
1524"params" field is optional: >
1525
1526 {
1527 "jsonrpc": "2.0",
1528 "id": <number>,
1529 "method": <string>,
1530 "params": <list|dict>
1531 }
1532
1533A LSP reponse message has the following format (expressed as a Vim Dict). The
1534"result" and "error" fields are optional: >
1535
1536 {
1537 "jsonrpc": "2.0",
1538 "id": <number>,
1539 "result": <vim type>
1540 "error": <dict>
1541 }
1542
1543A LSP notification message has the following format (expressed as a Vim Dict).
1544The "params" field is optional: >
1545
1546 {
1547 "jsonrpc": "2.0",
1548 "method": <string>,
1549 "params": <list|dict>
1550 }
1551
1552Depending on the use case, you can use the ch_evalexpr(), ch_sendexpr() and
1553ch_sendraw() functions on the same channel.
1554
1555A LSP request message has the following format (expressed as a Vim Dict). The
1556"params" field is optional: >
1557
1558 {
1559 "jsonrpc": "2.0",
1560 "id": <number>,
1561 "method": <string>,
1562 "params": <list|dict>
1563 }
1564
1565A LSP reponse message has the following format (expressed as a Vim Dict). The
1566"result" and "error" fields are optional: >
1567
1568 {
1569 "jsonrpc": "2.0",
1570 "id": <number>,
1571 "result": <vim type>
1572 "error": <dict>
1573 }
1574
1575A LSP notification message has the following format (expressed as a Vim Dict).
1576The "params" field is optional: >
1577
1578 {
1579 "jsonrpc": "2.0",
1580 "method": <string>,
1581 "params": <list|dict>
1582 }
1583
Bram Moolenaar91f84f62018-07-29 15:07:52 +02001584 vim:tw=78:ts=8:noet:ft=help:norl: