channel.txt (64874B)
1 *channel.txt* For Vim version 9.2. Last change: 2026 Sep 08 2 3 4 VIM REFERENCE MANUAL by Bram Moolenaar 5 6 7 Inter-process communication *channel* 8 9 Vim uses channels to communicate with other processes. 10 A channel uses a socket or pipes. *socket-interface* 11 Jobs can be used to start processes and communicate with them. 12 The Netbeans interface also uses a channel. |netbeans| 13 14 1. Overview |job-channel-overview| 15 2. Channel demo |channel-demo| 16 3. Opening a channel |channel-open| 17 4. Using a JSON or JS channel |channel-use| 18 5. Channel commands |channel-commands| 19 6. Using a RAW or NL channel |channel-raw| 20 7. More channel functions |channel-more| 21 8. Channel functions details |channel-functions-details| 22 9. Starting a job with a channel |job-start| 23 10. Starting a job without a channel |job-start-nochannel| 24 11. Job functions |job-functions-details| 25 12. Job options |job-options| 26 13. Controlling a job |job-control| 27 14. Using a prompt buffer |prompt-buffer| 28 15. Language Server Protocol |language-server-protocol| 29 16. Debug Adapter Protocol |debug-adapter-protocol| 30 31 *E1277* 32 {only when compiled with the |+channel| feature for channel stuff} 33 You can check this with: `has('channel')` 34 {only when compiled with the |+job| feature for job stuff} 35 You can check this with: `has('job')` 36 37 ============================================================================== 38 1. Overview *job-channel-overview* 39 40 There are four main types of jobs: 41 1. A daemon, serving several Vim instances. 42 Vim connects to it with a socket. 43 2. One job working with one Vim instance, asynchronously. 44 Uses a socket or pipes. 45 3. A job performing some work for a short time, asynchronously. 46 Uses a socket or pipes. 47 4. Running a filter, synchronously. 48 Uses pipes. 49 50 For when using sockets See |job-start|, |job-start-nochannel| and 51 |channel-open|. For 2 and 3, one or more jobs using pipes, see |job-start|. 52 For 4 use the ":{range}!cmd" command, see |filter|. 53 54 Over the socket and pipes these protocols are available: 55 RAW nothing known, Vim cannot tell where a message ends 56 NL every message ends in a NL (newline) character 57 JSON JSON encoding |json_encode()| 58 JS JavaScript style JSON-like encoding |js_encode()| 59 LSP Language Server Protocol encoding |language-server-protocol| 60 DAP Debug Adapter Protocol encoding |debug-adapter-protocol| 61 62 Common combination are: 63 - Using a job connected through pipes in NL mode. E.g., to run a style 64 checker and receive errors and warnings. 65 - Using a daemon, connecting over a socket in JSON mode. E.g. to lookup 66 cross-references in a database. 67 68 ============================================================================== 69 2. Channel demo *channel-demo* *demoserver.py* 70 71 This requires Python. The demo program can be found in 72 $VIMRUNTIME/tools/demoserver.py 73 Run it in one terminal. We will call this T1. 74 75 Run Vim in another terminal. Connect to the demo server with: > 76 let channel = ch_open('localhost:8765') 77 78 In T1 you should see: 79 === socket opened === ~ 80 81 You can now send a message to the server: > 82 echo ch_evalexpr(channel, 'hello!') 83 84 The message is received in T1 and a response is sent back to Vim. 85 You can see the raw messages in T1. What Vim sends is: 86 [1,"hello!"] ~ 87 And the response is: 88 [1,"got it"] ~ 89 The number will increase every time you send a message. 90 91 The server can send a command to Vim. Type this on T1 (literally, including 92 the quotes): 93 ["ex","echo 'hi there'"] ~ 94 And you should see the message in Vim. You can move the cursor a word 95 forward: 96 ["normal","w"] ~ 97 98 To handle asynchronous communication a callback needs to be used: > 99 func MyHandler(channel, msg) 100 echo "from the handler: " .. a:msg 101 endfunc 102 call ch_sendexpr(channel, 'hello!', {'callback': "MyHandler"}) 103 Vim will not wait for a response. Now the server can send the response later 104 and MyHandler will be invoked. 105 106 Instead of giving a callback with every send call, it can also be specified 107 when opening the channel: > 108 call ch_close(channel) 109 let channel = ch_open('localhost:8765', {'callback': "MyHandler"}) 110 call ch_sendexpr(channel, 'hello channel!') 111 112 When trying out channels it's useful to see what is going on. You can tell 113 Vim to write lines in log file: > 114 call ch_logfile('channellog', 'w') 115 See |ch_logfile()|. 116 117 You can also make Vim act as a server using |ch_listen()|. This does not 118 require an external server program. 119 120 *channel-listen-demo* 121 Start Vim and create a listening channel: > 122 func OnAccept(channel, clientaddr) 123 " Log the connection 124 echomsg "Accepted connection from " .. a:clientaddr 125 126 " Get current time and send it to the client 127 let current_time = strftime("%Y-%m-%d %H:%M:%S") 128 call ch_sendraw(a:channel, "Vim Server Time: " .. current_time .. "\n") 129 130 " Optional: close immediately if you only want to provide the time 131 call ch_close(a:channel) 132 endfunc 133 134 " Start listening on port 8765 135 let server = ch_listen('8765', {"callback": "OnAccept"}) 136 137 From another Vim instance (or any program) you can connect to it: > 138 let channel = ch_open('localhost:8765') 139 140 When done, close the server channel: > 141 call ch_close(server) 142 < 143 *channel-stdio* 144 Vim can also be the other end of a channel on its own stdin and stdout, like a 145 language server that is started by an editor. Start Vim with 146 |--stdio-channel| and a script that opens the channel: > 147 vim --stdio-channel -S server.vim 148 And in server.vim: > 149 func OnMessage(ch, msg) 150 ... 151 endfunc 152 let ch = ch_open('stdio', #{mode: 'lsp', callback: 'OnMessage'}) 153 < 154 *E1582* *E1583* 155 The address "stdio" can only be used when Vim was started with 156 |--stdio-channel|, and only once. The stdin and stdout of Vim are then 157 redirected to the null device, so that messages from Vim and from the commands 158 it starts do not get into the channel. Stderr is left alone and can be used 159 for error messages. 160 161 ============================================================================== 162 3. Opening a channel *channel-open* 163 164 To open a channel: > 165 let channel = ch_open({address} [, {options}]) 166 if ch_status(channel) == "open" 167 " use the channel 168 169 Use |ch_status()| to see if the channel could be opened. 170 171 *channel-address* 172 {address} can be a domain name or an IP address, followed by a port number, or 173 a Unix-domain socket path prefixed by "unix:", or "stdio". E.g. > 174 www.example.com:80 " domain + port 175 127.0.0.1:1234 " IPv4 + port 176 [2001:db8::1]:8765 " IPv6 + port 177 unix:/tmp/my-socket " Unix-domain socket path 178 stdio " stdin and stdout of Vim, see |channel-stdio| 179 180 When a domain name resolves to multiple addresses (e.g., both IPv6 and IPv4), 181 Vim tries each address in order. If a connection is slow or unreachable, it 182 quickly falls back to the next address. This helps when IPv6 or IPv4 is 183 unreachable on the network. 184 185 {options} is a dictionary with optional entries: *channel-open-options* 186 187 "mode" can be: *channel-mode* 188 "json" - Use JSON, see below; most convenient way. Default. 189 "js" - Use JS (JavaScript) encoding, more efficient than JSON. 190 "nl" - Use messages that end in a NL character 191 "raw" - Use raw messages 192 "blob" - Use raw messages and pass callback data as a |Blob| 193 "lsp" - Use language server protocol encoding 194 "dap" - Use debug adapter protocol encoding 195 *channel-callback* *E921* 196 "callback" A function that is called when a message is received that is 197 not handled otherwise (e.g. a JSON message with ID zero). It 198 gets two arguments: the channel and the received message. 199 Example: > 200 func Handle(channel, msg) 201 echo 'Received: ' .. a:msg 202 endfunc 203 let channel = ch_open("localhost:8765", {"callback": "Handle"}) 204 < 205 When "mode" is any of "json", "js", "lsp" or "dap" the "msg" 206 argument is the body of the received message, converted to Vim 207 types. 208 When "mode" is "nl" the "msg" argument is one message, 209 excluding the NL. 210 When "mode" is "raw" the "msg" argument is the whole message 211 as a string. 212 When "mode" is "blob" the "msg" argument is the whole message 213 as a |Blob|. 214 215 For all callbacks: Use |function()| to bind it to arguments 216 and/or a Dictionary. Or use the form "dict.function" to bind 217 the Dictionary. 218 219 Callbacks are only called at a "safe" moment, usually when Vim 220 is waiting for the user to type a character. Vim does not use 221 multi-threading. 222 223 *close_cb* 224 "close_cb" A function that is called when the channel gets closed, other 225 than by calling ch_close(). It should be defined like this: > 226 func MyCloseHandler(channel) 227 < Vim will invoke callbacks that handle data before invoking 228 close_cb, thus when this function is called no more data will 229 be passed to the callbacks. However, if a callback causes Vim 230 to check for messages, the close_cb may be invoked while still 231 in the callback. The plugin must handle this somehow, it can 232 be useful to know that no more data is coming. 233 If it is not known if there is a message to be read, use a 234 try/catch block: > 235 try 236 let msg = ch_readraw(a:channel) 237 catch 238 let msg = 'no message' 239 endtry 240 try 241 let err = ch_readraw(a:channel, #{part: 'err'}) 242 catch 243 let err = 'no error' 244 endtry 245 < *channel-drop* 246 "drop" Specifies when to drop messages: 247 "auto" When there is no callback to handle a message. 248 The "close_cb" is also considered for this. 249 "never" All messages will be kept. 250 251 *channel-noblock* 252 "noblock" Same effect as |job-noblock|. Only matters for writing. 253 254 *waittime* 255 "waittime" The time to wait for the connection to be made in 256 milliseconds. A negative number waits forever. 257 258 The default is zero, don't wait, which is useful if a local 259 server is supposed to be running already. On Unix Vim 260 actually uses a 1 msec timeout, that is required on many 261 systems. Use a larger value for a remote server, e.g. 10 262 msec at least. 263 *channel-timeout* 264 "timeout" The time to wait for a request when blocking, E.g. when using 265 ch_evalexpr(). In milliseconds. The default is 2000 (2 266 seconds). 267 268 When "mode" is "json" or "js" the "callback" is optional. When omitted it is 269 only possible to receive a message after sending one. 270 271 To change the channel options after opening it use |ch_setoptions()|. The 272 arguments are similar to what is passed to |ch_open()|, but "waittime" cannot 273 be given, since that only applies to opening the channel. 274 275 For example, the handler can be added or changed: > 276 call ch_setoptions(channel, {'callback': callback}) 277 When "callback" is empty (zero or an empty string) the handler is removed. 278 279 After a callback has been invoked Vim will update the screen and put the 280 cursor back where it belongs. Thus the callback should not need to do 281 `:redraw`. 282 283 The timeout can be changed: > 284 call ch_setoptions(channel, {'timeout': msec}) 285 < 286 *channel-close* *E906* 287 Once done with the channel, disconnect it like this: > 288 call ch_close(channel) 289 When a socket is used this will close the socket for both directions. When 290 pipes are used (stdin/stdout/stderr) they are all closed. This might not be 291 what you want! Stopping the job with job_stop() might be better. 292 All readahead is discarded, callbacks will no longer be invoked. 293 294 Note that a channel is closed in three stages: 295 - The I/O ends, log message: "Closing channel". There can still be queued 296 messages to read or callbacks to invoke. 297 - The readahead is cleared, log message: "Clearing channel". Some variables 298 may still reference the channel. 299 - The channel is freed, log message: "Freeing channel". 300 301 When the channel can't be opened you will get an error message. There is a 302 difference between MS-Windows and Unix: On Unix when the port doesn't exist 303 ch_open() fails quickly. On MS-Windows "waittime" applies. 304 *E898* *E901* *E902* 305 306 If there is an error reading or writing a channel it will be closed. 307 *E630* *E631* 308 309 ============================================================================== 310 4. Using a JSON or JS channel *channel-use* 311 312 If mode is JSON then a message can be sent synchronously like this: > 313 let response = ch_evalexpr(channel, {expr}) 314 This awaits a response from the other side. 315 316 When mode is JS this works the same, except that the messages use 317 JavaScript encoding. See |js_encode()| for the difference. 318 319 To send a message, without handling a response or letting the channel callback 320 handle the response: > 321 call ch_sendexpr(channel, {expr}) 322 323 To send a message and letting the response handled by a specific function, 324 asynchronously: > 325 call ch_sendexpr(channel, {expr}, {'callback': Handler}) 326 327 Vim will match the response with the request using the message ID. Once the 328 response is received the callback will be invoked. Further responses with the 329 same ID will be ignored. If your server sends back multiple responses you 330 need to send them with ID zero, they will be passed to the channel callback. 331 332 The {expr} is converted to JSON and wrapped in an array. An example of the 333 message that the receiver will get when {expr} is the string "hello": 334 [12,"hello"] ~ 335 336 The format of the JSON sent is: 337 [{number},{expr}] 338 339 In which {number} is different every time. It must be used in the response 340 (if any): 341 342 [{number},{response}] 343 344 This way Vim knows which sent message matches with which received message and 345 can call the right handler. Also when the messages arrive out of order. 346 347 A newline character is terminating the JSON text. This can be used to 348 separate the read text. For example, in Python: 349 splitidx = read_text.find('\n') 350 message = read_text[:splitidx] 351 rest = read_text[splitidx + 1:] 352 353 The sender must always send valid JSON to Vim. Vim can check for the end of 354 the message by parsing the JSON. It will only accept the message if the end 355 was received. A newline after the message is optional. 356 357 When the process wants to send a message to Vim without first receiving a 358 message, it must use the number zero: 359 [0,{response}] 360 361 Then channel handler will then get {response} converted to Vim types. If the 362 channel does not have a handler the message is dropped. 363 364 It is also possible to use ch_sendraw() and ch_evalraw() on a JSON or JS 365 channel. The caller is then completely responsible for correct encoding and 366 decoding. 367 368 ============================================================================== 369 5. Channel commands *channel-commands* 370 371 With a JSON channel the process can send commands to Vim that will be 372 handled by Vim internally, it does not require a handler for the channel. 373 374 Possible commands are: *E903* *E904* *E905* 375 ["redraw", {forced}] 376 ["ex", {Ex command}] 377 ["normal", {Normal mode command}] 378 ["expr", {expression}, {number}] 379 ["expr", {expression}] 380 ["call", {func name}, {argument list}, {number}] 381 ["call", {func name}, {argument list}] 382 383 With all of these: Be careful what these commands do! You can easily 384 interfere with what the user is doing. To avoid trouble use |mode()| to check 385 that the editor is in the expected state. E.g., to send keys that must be 386 inserted as text, not executed as a command: 387 ["ex","if mode() == 'i' | call feedkeys('ClassName') | endif"] ~ 388 389 Errors in these commands are normally not reported to avoid them messing up 390 the display. If you do want to see them, set the 'verbose' option to 3 or 391 higher. 392 393 394 Command "redraw" ~ 395 396 The other commands do not explicitly update the screen, so that you can send a 397 sequence of commands without the cursor moving around. A redraw can happen as 398 a side effect of some commands. You must end with the "redraw" command to 399 show any changed text and show the cursor where it belongs. 400 401 The argument is normally an empty string: 402 ["redraw", ""] ~ 403 To first clear the screen pass "force": 404 ["redraw", "force"] ~ 405 406 407 Command "ex" ~ 408 409 The "ex" command is executed as any Ex command. There is no response for 410 completion or error. You could use functions in an |autoload| script: 411 ["ex","call myscript#MyFunc(arg)"] 412 413 You can also use "call |feedkeys()|" to insert any key sequence. 414 415 When there is an error a message is written to the channel log, if it exists, 416 and v:errmsg is set to the error. 417 418 419 Command "normal" ~ 420 421 The "normal" command is executed like with ":normal!", commands are not 422 mapped. Example to open the folds under the cursor: 423 ["normal" "zO"] 424 425 426 Command "expr" with response ~ 427 428 The "expr" command can be used to get the result of an expression. For 429 example, to get the number of lines in the current buffer: 430 ["expr","line('$')", -2] ~ 431 432 It will send back the result of the expression: 433 [-2, "last line"] ~ 434 The format is: 435 [{number}, {result}] 436 437 Here {number} is the same as what was in the request. Use a negative number 438 to avoid confusion with message that Vim sends. Use a different number on 439 every request to be able to match the request with the response. 440 441 {result} is the result of the evaluation and is JSON encoded. If the 442 evaluation fails or the result can't be encoded in JSON it is the string 443 "ERROR". 444 445 446 Command "expr" without a response ~ 447 448 This command is similar to "expr" above, but does not send back any response. 449 Example: 450 ["expr","setline('$', ['one', 'two', 'three'])"] ~ 451 There is no third argument in the request. 452 453 454 Command "call" ~ 455 456 This is similar to "expr", but instead of passing the whole expression as a 457 string this passes the name of a function and a list of arguments. This 458 avoids the conversion of the arguments to a string and escaping and 459 concatenating them. Example: 460 ["call", "line", ["$"], -2] ~ 461 462 Leave out the fourth argument if no response is to be sent: 463 ["call", "setline", ["$", ["one", "two", "three"]]] ~ 464 465 ============================================================================== 466 6. Using a RAW or NL channel *channel-raw* 467 468 If mode is RAW or NL then a message can be sent like this: > 469 let response = ch_evalraw(channel, {string}) 470 471 The {string} is sent as-is. The response will be what can be read from the 472 channel right away. Since Vim doesn't know how to recognize the end of the 473 message you need to take care of it yourself. The timeout applies for reading 474 the first byte, after that it will not wait for anything more. 475 476 If mode is "nl" you can send a message in a similar way. You are expected 477 to put in the NL after each message. Thus you can also send several messages 478 ending in a NL at once. The response will be the text up to and including the 479 first NL. This can also be just the NL for an empty response. 480 If no NL was read before the channel timeout an empty string is returned. 481 482 To send a message, without expecting a response: > 483 call ch_sendraw(channel, {string}) 484 The process can send back a response, the channel handler will be called with 485 it. 486 487 *channel-onetime-callback* 488 To send a message and letting the response handled by a specific function, 489 asynchronously: > 490 call ch_sendraw(channel, {string}, {'callback': 'MyHandler'}) 491 492 This {string} can also be JSON, use |json_encode()| to create it and 493 |json_decode()| to handle a received JSON message. 494 495 It is not possible to use |ch_evalexpr()| or |ch_sendexpr()| on a raw channel. 496 497 A String in Vim cannot contain NUL bytes. To send or receive NUL bytes read 498 or write from a buffer. See |in_io-buffer| and |out_io-buffer|. 499 500 ============================================================================== 501 7. More channel functions *channel-more* 502 503 To obtain the status of a channel: ch_status(channel). The possible results 504 are: 505 "fail" Failed to open the channel. 506 "open" The channel can be used. 507 "buffered" The channel was closed but there is data to read. 508 "closed" The channel was closed. 509 510 To obtain the job associated with a channel: ch_getjob(channel) 511 512 To read one message from a channel: > 513 let output = ch_read(channel) 514 This uses the channel timeout. To read without a timeout, just get any 515 message that is available: > 516 let output = ch_read(channel, {'timeout': 0}) 517 When no message was available then the result is v:none for a JSON or JS mode 518 channels, an empty string for a RAW or NL channel. You can use |ch_canread()| 519 to check if there is something to read. 520 521 Note that when there is no callback, messages are dropped. To avoid that add 522 a close callback to the channel. 523 524 To read all normal output from a RAW channel that is available: > 525 let output = ch_readraw(channel) 526 To read all error output from a RAW channel that is available: > 527 let output = ch_readraw(channel, {"part": "err"}) 528 Note that if the channel is in NL mode, ch_readraw() will only return one line 529 for each call. 530 531 ch_read() and ch_readraw() use the channel timeout. When there is nothing to 532 read within that time an empty string is returned. To specify a different 533 timeout in msec use the "timeout" option: 534 {"timeout": 123} ~ 535 To read from the error output use the "part" option: 536 {"part": "err"} ~ 537 To read a message with a specific ID, on a JS or JSON channel: 538 {"id": 99} ~ 539 When no ID is specified or the ID is -1, the first message is returned. This 540 overrules any callback waiting for this message. 541 542 For a RAW channel this returns whatever is available, since Vim does not know 543 where a message ends. 544 For a NL channel this returns one message. 545 For a JS or JSON channel this returns one decoded message. 546 This includes any sequence number. 547 548 ============================================================================== 549 8. Channel functions details *channel-functions-details* 550 551 ch_canread({handle}) *ch_canread()* 552 Return non-zero when there is something to read from {handle}. 553 {handle} can be a Channel or a Job that has a Channel. 554 555 This is useful to read from a channel at a convenient time, 556 e.g. from a timer. 557 558 Note that messages are dropped when the channel does not have 559 a callback. Add a close callback to avoid that. 560 561 Can also be used as a |method|: > 562 GetChannel()->ch_canread() 563 < 564 Return type: |Number| 565 566 ch_close({handle}) *ch_close()* 567 Close {handle}. See |channel-close|. 568 {handle} can be a Channel or a Job that has a Channel. 569 A close callback is not invoked. 570 571 Can also be used as a |method|: > 572 GetChannel()->ch_close() 573 < 574 Return type: void 575 576 ch_close_in({handle}) *ch_close_in()* 577 Close the "in" part of {handle}. See |channel-close-in|. 578 {handle} can be a Channel or a Job that has a Channel. 579 A close callback is not invoked. 580 581 Can also be used as a |method|: > 582 GetChannel()->ch_close_in() 583 < 584 Return type: void 585 586 587 ch_evalexpr({handle}, {expr} [, {options}]) *ch_evalexpr()* 588 Send {expr} over {handle}. The {expr} is encoded 589 according to the type of channel. The function cannot be used 590 with a raw channel. See |channel-use|. 591 {handle} can be a Channel or a Job that has a Channel. 592 When using the "lsp" or "dap" channel mode, {expr} must be a 593 |Dict|. 594 *E917* 595 {options} must be a Dictionary. It must not have a "callback" 596 entry. It can have a "timeout" entry to specify the timeout 597 for this specific request. 598 599 ch_evalexpr() waits for a response and returns the decoded 600 expression. When there is an error or timeout it returns an 601 empty |String| or, when using the "lsp" or "dap" channel mode, 602 returns an empty |Dict|. 603 604 Note that while waiting for the response, Vim handles other 605 messages. You need to make sure this doesn't cause trouble. 606 607 Can also be used as a |method|: > 608 GetChannel()->ch_evalexpr(expr) 609 < 610 Return type: dict<any> or |String| 611 612 613 ch_evalraw({handle}, {string} [, {options}]) *ch_evalraw()* 614 Send {string} over {handle}. 615 {handle} can be a Channel or a Job that has a Channel. 616 617 Works like |ch_evalexpr()|, but does not encode the request or 618 decode the response. The caller is responsible for the 619 correct contents. Also does not add a newline for a channel 620 in NL mode, the caller must do that. The NL in the response 621 is removed. 622 Note that Vim does not know when the text received on a raw 623 channel is complete, it may only return the first part and you 624 need to use |ch_readraw()| to fetch the rest. 625 See |channel-use|. 626 627 Can also be used as a |method|: > 628 GetChannel()->ch_evalraw(rawstring) 629 < 630 Return type: dict<any> or |String| 631 632 ch_getbufnr({handle}, {what}) *ch_getbufnr()* 633 Get the buffer number that {handle} is using for String 634 {what}. 635 {handle} can be a Channel or a Job that has a Channel. 636 {what} can be "err" for stderr, "out" for stdout or empty for 637 socket output. 638 Returns -1 when there is no buffer. 639 640 Can also be used as a |method|: > 641 GetChannel()->ch_getbufnr(what) 642 < 643 Return type: |Number| 644 645 ch_getjob({channel}) *ch_getjob()* 646 Get the Job associated with {channel}. 647 If there is no job calling |job_status()| on the returned Job 648 will result in "fail". 649 650 Can also be used as a |method|: > 651 GetChannel()->ch_getjob() 652 < 653 Return type: |job| or |String| 654 655 ch_info({handle}) *ch_info()* 656 Returns a Dictionary with information about {handle}. The 657 items are: 658 "id" number of the channel 659 "status" "open", "buffered" or "closed", like 660 ch_status() 661 When opened with ch_open(): 662 "port" the port on loopback 663 "path" the path of the Unix-domain socket 664 "sock_status" "open" or "closed" 665 "sock_mode" "NL", "RAW", "JSON" or "JS" 666 "sock_io" "socket" 667 "sock_timeout" timeout in msec 668 669 Note that "path" is only present for Unix-domain sockets, for 670 regular ones "hostname" and "port" are present instead. 671 672 When opened with job_start(): 673 "out_status" "open", "buffered" or "closed" 674 "out_mode" "NL", "RAW", "JSON" or "JS" 675 "out_io" "null", "pipe", "file" or "buffer" 676 "out_timeout" timeout in msec 677 "err_status" "open", "buffered" or "closed" 678 "err_mode" "NL", "RAW", "JSON" or "JS" 679 "err_io" "out", "null", "pipe", "file" or "buffer" 680 "err_timeout" timeout in msec 681 "in_status" "open" or "closed" 682 "in_mode" "NL", "RAW", "JSON", "JS" or "LSP" or "DAP" 683 "in_io" "null", "pipe", "file" or "buffer" 684 "in_timeout" timeout in msec 685 686 Can also be used as a |method|: > 687 GetChannel()->ch_info() 688 < 689 Return type: dict<any> 690 691 ch_listen({address} [, {options}]) *E1573* *E1574* *ch_listen()* 692 Listen on {address} - port on loopback or UNIX domain socket 693 for incoming channel connections. This creates a server-side 694 channel, unlike |ch_open()| which connects to an existing 695 server. 696 Returns a Channel. Use |ch_status()| to check for failure. 697 698 {address} is a String, see |channel-address| for the possible 699 accepted forms, however in case of TCP sockets it allows to 700 set only a port and binds to loopback address for security 701 reasons. 702 Note: IPv6 is not yet supported. 703 704 If {options} is given it must be a |Dictionary|. 705 See |channel-open-options|. 706 The "callback" in {options} is invoked when a new connection 707 is accepted. It receives two arguments: the new Channel and 708 the client address as a String (e.g. "127.0.0.1:12345"). 709 710 Use |ch_open()| to connect to an existing server instead. 711 712 See |channel-listen-demo| for an example. 713 714 Can also be used as a |method|: > 715 GetAddress()->ch_listen() 716 < 717 {only available when compiled with the |+channel| feature} 718 719 Return type: channel 720 721 ch_log({msg} [, {handle}]) *ch_log()* 722 Write String {msg} in the channel log file, if it was opened 723 with |ch_logfile()|. 724 The text "ch_log():" is prepended to the message to make clear 725 it came from this function call and make it easier to find in 726 the log file. 727 When {handle} is passed the channel number is used for the 728 message. 729 {handle} can be a Channel or a Job that has a Channel. The 730 Channel must be open for the channel number to be used. 731 732 Can also be used as a |method|: > 733 'did something'->ch_log() 734 < 735 Return type: void 736 737 ch_logfile({fname} [, {mode}]) *ch_logfile()* 738 Start logging channel activity to {fname}. 739 When {fname} is an empty string: stop logging. 740 741 When {mode} is omitted or contains "a" or is "o" then append 742 to the file. 743 When {mode} contains "w" and not "a" start with an empty file. 744 When {mode} contains "o" then log all terminal output. 745 Otherwise only some interesting terminal output is logged. 746 747 Use |ch_log()| to write log messages. The file is flushed 748 after every message, on Unix you can use "tail -f" to see what 749 is going on in real time. 750 751 To enable the log very early, to see what is received from a 752 terminal during startup, use |--log| (this uses mode "ao"): > 753 vim --log logfile 754 < 755 This function is not available in the |sandbox|. 756 NOTE: the channel communication is stored in the file, be 757 aware that this may contain confidential and privacy sensitive 758 information, e.g. a password you type in a terminal window. 759 760 Can also be used as a |method|: > 761 'logfile'->ch_logfile('w') 762 < 763 Return type: void 764 765 ch_open({address} [, {options}]) *ch_open()* 766 Open a channel to {address}. See |channel|. 767 Returns a Channel. Use |ch_status()| to check for failure. 768 769 {address} is a String, see |channel-address| for the possible 770 accepted forms. 771 772 If {options} is given it must be a |Dictionary|. 773 See |channel-open-options|. 774 775 Use |ch_listen()| to listen for incoming connections 776 instead. 777 778 Can also be used as a |method|: > 779 GetAddress()->ch_open() 780 < 781 Return type: |channel| 782 783 ch_read({handle} [, {options}]) *ch_read()* 784 Read from {handle} and return the received message. 785 {handle} can be a Channel or a Job that has a Channel. 786 For a NL channel this waits for a NL to arrive, except when 787 there is nothing more to read (channel was closed). 788 See |channel-more|. 789 790 Can also be used as a |method|: > 791 GetChannel()->ch_read() 792 < 793 Return type: |String| 794 795 ch_readblob({handle} [, {options}]) *ch_readblob()* 796 Like ch_read() but reads binary data and returns a |Blob|. 797 See |channel-more|. 798 799 Can also be used as a |method|: > 800 GetChannel()->ch_readblob() 801 < 802 Return type: |Blob| 803 804 ch_readraw({handle} [, {options}]) *ch_readraw()* 805 Like ch_read() but for a JS and JSON channel does not decode 806 the message. For a NL channel it does not block waiting for 807 the NL to arrive, but otherwise works like ch_read(). 808 See |channel-more|. 809 810 Can also be used as a |method|: > 811 GetChannel()->ch_readraw() 812 < 813 Return type: |String| 814 815 ch_sendexpr({handle}, {expr} [, {options}]) *ch_sendexpr()* 816 Send {expr} over {handle}. The {expr} is encoded 817 according to the type of channel. The function cannot be used 818 with a raw channel. 819 See |channel-use|. *E912* 820 {handle} can be a Channel or a Job that has a Channel. 821 When using the "lsp" or "dap" channel mode, {expr} must be a 822 |Dict|. 823 824 If the channel mode is "lsp" or "dap", then returns a Dict. 825 Otherwise returns an empty String. If the "callback" item is 826 present in {options}, then the returned Dict contains the ID 827 of the request message. The ID can be used to send a 828 cancellation request to the LSP server or debug adapter (if 829 needed). Returns an empty Dict on error. 830 831 If a response message is not expected for {expr}, then don't 832 specify the "callback" item in {options}. 833 834 In "lsp" mode an "id" item in {expr} is sent as it is when no 835 response is expected, which is how a request from the server 836 is answered; it may be of any type the server used. When a 837 response is expected, with |ch_evalexpr()| or with the 838 "callback" item, Vim assigns the ID itself and the item must 839 be a |Number|. 840 841 Can also be used as a |method|: > 842 GetChannel()->ch_sendexpr(expr) 843 < 844 Return type: dict<any> or |String| 845 846 847 ch_sendraw({handle}, {expr} [, {options}]) *ch_sendraw()* 848 Send |String| or |Blob| {expr} over {handle}. 849 Works like |ch_sendexpr()|, but does not encode the request or 850 decode the response. The caller is responsible for the 851 correct contents. Also does not add a newline for a channel 852 in NL mode, the caller must do that. The NL in the response 853 is removed. 854 See |channel-use|. 855 856 Can also be used as a |method|: > 857 GetChannel()->ch_sendraw(rawexpr) 858 < 859 Return type: void 860 861 ch_setoptions({handle}, {options}) *ch_setoptions()* 862 Set options on {handle}: 863 "callback" the channel callback 864 "timeout" default read timeout in msec 865 "mode" mode for the whole channel 866 See |ch_open()| for more explanation. 867 {handle} can be a Channel or a Job that has a Channel. 868 869 Note that changing the mode may cause queued messages to be 870 lost. 871 872 These options cannot be changed: 873 "waittime" only applies to |ch_open()| 874 875 Can also be used as a |method|: > 876 GetChannel()->ch_setoptions(options) 877 < 878 Return type: void 879 880 ch_status({handle} [, {options}]) *ch_status()* 881 Return the status of {handle}: 882 "fail" failed to open the channel 883 "open" channel can be used 884 "buffered" channel can be read, not written to 885 "closed" channel can not be used 886 {handle} can be a Channel or a Job that has a Channel. 887 "buffered" is used when the channel was closed but there is 888 still data that can be obtained with |ch_read()|. 889 890 If {options} is given it can contain a "part" entry to specify 891 the part of the channel to return the status for: "out" or 892 "err". For example, to get the error status: > 893 ch_status(job, {"part": "err"}) 894 < 895 Can also be used as a |method|: > 896 GetChannel()->ch_status() 897 < 898 Return type: |String| 899 900 ============================================================================== 901 9. Starting a job with a channel *job-start* *job* 902 903 To start a job and open a channel for stdin/stdout/stderr: > 904 let job = job_start(command, {options}) 905 906 You can get the channel with: > 907 let channel = job_getchannel(job) 908 909 The channel will use NL mode. If you want another mode it's best to specify 910 this in {options}. When changing the mode later some text may have already 911 been received and not parsed correctly. 912 913 If the command produces a line of output that you want to deal with, specify 914 a handler for stdout: > 915 let job = job_start(command, {"out_cb": "MyHandler"}) 916 The function will be called with the channel and a message. You would define 917 it like this: > 918 func MyHandler(channel, msg) 919 920 Without the handler you need to read the output with |ch_read()| or 921 |ch_readraw()|. You can do this in the close callback, see |read-in-close-cb|. 922 923 Note that if the job exits before you read the output, the output may be lost. 924 This depends on the system (on Unix this happens because closing the write end 925 of a pipe causes the read end to get EOF). To avoid this make the job sleep 926 for a short while before it exits. 927 928 The handler defined for "out_cb" will not receive stderr. If you want to 929 handle that separately, add an "err_cb" handler: > 930 let job = job_start(command, {"out_cb": "MyHandler", 931 \ "err_cb": "ErrHandler"}) 932 933 If you want to handle both stderr and stdout with one handler use the 934 "callback" option: > 935 let job = job_start(command, {"callback": "MyHandler"}) 936 937 Depending on the system, starting a job can put Vim in the background, the 938 started job gets the focus. To avoid that, use the `foreground()` function. 939 This might not always work when called early, put in the callback handler or 940 use a timer to call it after the job has started. 941 942 You can send a message to the command with ch_evalraw(). If the channel is in 943 JSON or JS mode you can use ch_evalexpr(). 944 945 There are several options you can use, see |job-options|. 946 For example, to start a job and write its output in buffer "dummy": > 947 let logjob = job_start("tail -f /tmp/log", 948 \ {'out_io': 'buffer', 'out_name': 'dummy'}) 949 sbuf dummy 950 951 952 Job input from a buffer ~ 953 *in_io-buffer* 954 To run a job that reads from a buffer: > 955 let job = job_start({command}, 956 \ {'in_io': 'buffer', 'in_name': 'mybuffer'}) 957 < 958 *E915* *E918* 959 The buffer is found by name, similar to |bufnr()|. The buffer must exist and 960 be loaded when job_start() is called. 961 962 By default this reads the whole buffer. This can be changed with the "in_top" 963 and "in_bot" options. 964 965 A special mode is when "in_top" is set to zero and "in_bot" is not set: Every 966 time a line is added to the buffer, the last-but-one line will be sent to the 967 job stdin. This allows for editing the last line and sending it when pressing 968 Enter. 969 *channel-close-in* 970 When not using the special mode the pipe or socket will be closed after the 971 last line has been written. This signals the reading end that the input 972 finished. You can also use |ch_close_in()| to close it sooner. 973 974 NUL bytes in the text will be passed to the job (internally Vim stores these 975 as NL bytes). 976 977 978 Reading job output in the close callback ~ 979 *read-in-close-cb* 980 If the job can take some time and you don't need intermediate results, you can 981 add a close callback and read the output there: > 982 983 func! CloseHandler(channel) 984 while ch_status(a:channel, {'part': 'out'}) == 'buffered' 985 echomsg ch_read(a:channel) 986 endwhile 987 endfunc 988 let job = job_start(command, {'close_cb': 'CloseHandler'}) 989 990 You will want to do something more useful than "echomsg". 991 992 ============================================================================== 993 10. Starting a job without a channel *job-start-nochannel* 994 995 To start another process without creating a channel: > 996 let job = job_start(command, 997 \ {"in_io": "null", "out_io": "null", "err_io": "null"}) 998 999 This starts {command} in the background, Vim does not wait for it to finish. 1000 1001 When Vim sees that neither stdin, stdout or stderr are connected, no channel 1002 will be created. Often you will want to include redirection in the command to 1003 avoid it getting stuck. 1004 1005 There are several options you can use, see |job-options|. 1006 1007 *job-start-if-needed* 1008 To start a job only when connecting to an address does not work, do something 1009 like this: > 1010 let channel = ch_open(address, {"waittime": 0}) 1011 if ch_status(channel) == "fail" 1012 let job = job_start(command) 1013 let channel = ch_open(address, {"waittime": 1000}) 1014 endif 1015 1016 Note that the waittime for ch_open() gives the job one second to make the port 1017 available. 1018 1019 ============================================================================== 1020 11. Job functions *job-functions-details* 1021 1022 job_getchannel({job}) *job_getchannel()* 1023 Get the channel handle that {job} is using. 1024 To check if the job has no channel: > 1025 if string(job_getchannel(job)) == 'channel fail' 1026 < 1027 Can also be used as a |method|: > 1028 GetJob()->job_getchannel() 1029 < 1030 Return type: |channel| 1031 1032 job_info([{job}]) *job_info()* 1033 Returns a Dictionary with information about {job}: 1034 "status" what |job_status()| returns 1035 "channel" what |job_getchannel()| returns 1036 "cmd" List of command arguments used to start the 1037 job 1038 "process" process ID 1039 "tty_in" terminal input name, empty when none 1040 "tty_out" terminal output name, empty when none 1041 "exitval" only valid when "status" is "dead" 1042 "exit_cb" function to be called on exit 1043 "stoponexit" |job-stoponexit| 1044 1045 Only in Unix: 1046 "termsig" the signal which terminated the process 1047 (See |job_stop()| for the values) 1048 only valid when "status" is "dead" 1049 1050 Only in MS-Windows: 1051 "tty_type" Type of virtual console in use. 1052 Values are "winpty" or "conpty". 1053 See 'termwintype'. 1054 1055 Without any arguments, returns a List with all Job objects. 1056 1057 Can also be used as a |method|: > 1058 GetJob()->job_info() 1059 < 1060 Return type: dict<any> or list<job> depending on whether {job} 1061 was given 1062 1063 1064 job_setoptions({job}, {options}) *job_setoptions()* 1065 Change options for {job}. Supported are: 1066 "stoponexit" |job-stoponexit| 1067 "exit_cb" |job-exit_cb| 1068 1069 Can also be used as a |method|: > 1070 GetJob()->job_setoptions(options) 1071 < 1072 Return type: void 1073 1074 1075 job_start({command} [, {options}]) *job_start()* 1076 Start a job and return a Job object. Unlike |system()| and 1077 |:!cmd| this does not wait for the job to finish. 1078 To start a job in a terminal window see |term_start()|. 1079 1080 If the job fails to start then |job_status()| on the returned 1081 Job object results in "fail" and none of the callbacks will be 1082 invoked. 1083 1084 {command} can be a String. This works best on MS-Windows. On 1085 Unix it is split up in white space separated parts to be 1086 passed to execvp(). Arguments in double quotes can contain 1087 white space. 1088 1089 {command} can be a List, where the first item is the 1090 executable and further items are the arguments. All items are 1091 converted to String. This works best on Unix. 1092 1093 On MS-Windows, job_start() makes a GUI application hidden. If 1094 you want to show it, use |:!start| instead. 1095 1096 The command is executed directly, not through a shell, the 1097 'shell' option is not used. To use the shell: > 1098 let job = job_start(["/bin/sh", "-c", "echo hello"]) 1099 < Or: > 1100 let job = job_start('/bin/sh -c "echo hello"') 1101 < Note that this will start two processes, the shell and the 1102 command it executes. If you don't want this use the "exec" 1103 shell command. 1104 1105 On Unix $PATH is used to search for the executable only when 1106 the command does not contain a slash. 1107 1108 The job will use the same terminal as Vim. If it reads from 1109 stdin the job and Vim will be fighting over input, that 1110 doesn't work. Redirect stdin and stdout to avoid problems: > 1111 let job = job_start(['sh', '-c', "myserver </dev/null >/dev/null"]) 1112 < 1113 The returned Job object can be used to get the status with 1114 |job_status()| and stop the job with |job_stop()|. 1115 1116 Note that the job object will be deleted if there are no 1117 references to it. This closes the stdin and stderr, which may 1118 cause the job to fail with an error. To avoid this keep a 1119 reference to the job. Thus instead of: > 1120 call job_start('my-command') 1121 < use: > 1122 let myjob = job_start('my-command') 1123 < and unlet "myjob" once the job is not needed or is past the 1124 point where it would fail (e.g. when it prints a message on 1125 startup). Keep in mind that variables local to a function 1126 will cease to exist if the function returns. Use a 1127 script-local variable if needed: > 1128 let s:myjob = job_start('my-command') 1129 < 1130 {options} must be a Dictionary. It can contain many optional 1131 items, see |job-options|. 1132 1133 Can also be used as a |method|: > 1134 BuildCommand()->job_start() 1135 < 1136 Return type: |job| 1137 1138 1139 job_status({job}) *job_status()* *E916* 1140 Returns a String with the status of {job}: 1141 "run" job is running 1142 "fail" job failed to start 1143 "dead" job died or was stopped after running 1144 1145 On Unix a non-existing command results in "dead" instead of 1146 "fail", because a fork happens before the failure can be 1147 detected. 1148 1149 If in Vim9 script a variable is declared with type "job" but 1150 never assigned to, passing that variable to job_status() 1151 returns "fail". 1152 1153 If an exit callback was set with the "exit_cb" option and the 1154 job is now detected to be "dead" the callback will be invoked. 1155 1156 For more information see |job_info()|. 1157 1158 Can also be used as a |method|: > 1159 GetJob()->job_status() 1160 < 1161 Return type: |String| 1162 1163 1164 job_stop({job} [, {how}]) *job_stop()* 1165 Stop the {job}. This can also be used to signal the job. 1166 1167 When {how} is omitted or is "term" the job will be terminated. 1168 For Unix SIGTERM is sent. On MS-Windows the job will be 1169 terminated forcedly (there is no "gentle" way). 1170 This goes to the process group, thus children may also be 1171 affected. 1172 1173 Effect for Unix: 1174 "term" SIGTERM (default) 1175 "hup" SIGHUP 1176 "quit" SIGQUIT 1177 "int" SIGINT 1178 "kill" SIGKILL (strongest way to stop) 1179 number signal with that number 1180 1181 Effect for MS-Windows: 1182 "term" terminate process forcedly (default) 1183 "hup" CTRL_BREAK 1184 "quit" CTRL_BREAK 1185 "int" CTRL_C 1186 "kill" terminate process forcedly 1187 Others CTRL_BREAK 1188 1189 On Unix the signal is sent to the process group. This means 1190 that when the job is "sh -c command" it affects both the shell 1191 and the command. 1192 1193 The result is a Number: 1 if the operation could be executed, 1194 0 if "how" is not supported on the system. 1195 Note that even when the operation was executed, whether the 1196 job was actually stopped needs to be checked with 1197 |job_status()|. 1198 1199 If the status of the job is "dead", the signal will not be 1200 sent. This is to avoid to stop the wrong job (esp. on Unix, 1201 where process numbers are recycled). 1202 1203 When using "kill" Vim will assume the job will die and close 1204 the channel. 1205 1206 Can also be used as a |method|: > 1207 GetJob()->job_stop() 1208 < 1209 Return type: |Number| 1210 1211 1212 ============================================================================== 1213 12. Job options *job-options* 1214 1215 The {options} argument in job_start() is a dictionary. All entries are 1216 optional. Some options can be used after the job has started, using 1217 job_setoptions(job, {options}). Many options can be used with the channel 1218 related to the job, using ch_setoptions(channel, {options}). 1219 See |job_setoptions()| and |ch_setoptions()|. 1220 1221 *in_mode* *out_mode* *err_mode* 1222 "in_mode" mode specifically for stdin, only when using pipes 1223 "out_mode" mode specifically for stdout, only when using pipes 1224 "err_mode" mode specifically for stderr, only when using pipes 1225 See |channel-mode| for the values. 1226 1227 Note: when setting "mode" the part specific mode is 1228 overwritten. Therefore set "mode" first and the part 1229 specific mode later. 1230 1231 Note: when writing to a file or buffer and when 1232 reading from a buffer NL mode is used by default. 1233 1234 *job-noblock* 1235 "noblock": 1 When writing use a non-blocking write call. This 1236 avoids getting stuck if Vim should handle other 1237 messages in between, e.g. when a job sends back data 1238 to Vim. It implies that when `ch_sendraw()` returns 1239 not all data may have been written yet. 1240 This option was added in patch 8.1.0350, test with: > 1241 if has("patch-8.1.350") 1242 let options['noblock'] = 1 1243 endif 1244 < 1245 *job-callback* 1246 "callback": handler Callback for something to read on any part of the 1247 channel. 1248 *job-out_cb* *out_cb* 1249 "out_cb": handler Callback for when there is something to read on 1250 stdout. Only for when the channel uses pipes. When 1251 "out_cb" wasn't set the channel callback is used. 1252 The two arguments are the channel and the message. 1253 1254 *job-err_cb* *err_cb* 1255 "err_cb": handler Callback for when there is something to read on 1256 stderr. Only for when the channel uses pipes. When 1257 "err_cb" wasn't set the channel callback is used. 1258 The two arguments are the channel and the message. 1259 *job-close_cb* 1260 "close_cb": handler Callback for when the channel is closed. Same as 1261 "close_cb" on |ch_open()|, see |close_cb|. 1262 *job-drop* 1263 "drop": when Specifies when to drop messages. Same as "drop" on 1264 |ch_open()|, see |channel-drop|. For "auto" the 1265 exit_cb is not considered. 1266 *job-exit_cb* 1267 "exit_cb": handler Callback for when the job ends. The arguments are the 1268 job and the exit status. 1269 Vim checks up to 10 times per second for jobs that 1270 ended. The check can also be triggered by calling 1271 |job_status()|, which may then invoke the exit_cb 1272 handler. 1273 Note that data can be buffered, callbacks may still be 1274 called after the process ends. 1275 *job-timeout* 1276 "timeout": time The time to wait for a request when blocking, E.g. 1277 when using ch_evalexpr(). In milliseconds. The 1278 default is 2000 (2 seconds). 1279 *out_timeout* *err_timeout* 1280 "out_timeout": time Timeout for stdout. Only when using pipes. 1281 "err_timeout": time Timeout for stderr. Only when using pipes. 1282 Note: when setting "timeout" the part specific mode is 1283 overwritten. Therefore set "timeout" first and the 1284 part specific mode later. 1285 1286 *job-stoponexit* 1287 "stoponexit": {signal} Send {signal} to the job when Vim exits. See 1288 |job_stop()| for possible values. 1289 "stoponexit": "" Do not stop the job when Vim exits. 1290 The default is "term". 1291 1292 *job-term* 1293 "term": "open" Start a terminal in a new window and connect the job 1294 stdin/stdout/stderr to it. Similar to using 1295 `:terminal`. 1296 NOTE: Not implemented yet! 1297 1298 "channel": {channel} Use an existing channel instead of creating a new one. 1299 The parts of the channel that get used for the new job 1300 will be disconnected from what they were used before. 1301 If the channel was still used by another job this may 1302 cause I/O errors. 1303 Existing callbacks and other settings remain. 1304 1305 "pty": 1 Use a pty (pseudo-tty) instead of a pipe when 1306 possible. This is most useful in combination with a 1307 terminal window, see |terminal|. 1308 {only on Unix and Unix-like systems} 1309 1310 *job-in_io* *in_top* *in_bot* *in_name* *in_buf* 1311 "in_io": "null" disconnect stdin (read from /dev/null) 1312 "in_io": "pipe" stdin is connected to the channel (default) 1313 "in_io": "file" stdin reads from a file 1314 "in_io": "buffer" stdin reads from a buffer 1315 "in_top": number when using "buffer": first line to send (default: 1) 1316 "in_bot": number when using "buffer": last line to send (default: last) 1317 "in_name": "/path/file" the name of the file or buffer to read from 1318 "in_buf": number the number of the buffer to read from 1319 1320 *job-out_io* *out_name* *out_buf* 1321 "out_io": "null" disconnect stdout (goes to /dev/null) 1322 "out_io": "pipe" stdout is connected to the channel (default) 1323 "out_io": "file" stdout writes to a file 1324 "out_io": "buffer" stdout appends to a buffer (see below) 1325 "out_name": "/path/file" the name of the file or buffer to write to 1326 "out_buf": number the number of the buffer to write to 1327 "out_modifiable": 0 when writing to a buffer, 'modifiable' will be off 1328 (see below) 1329 "out_msg": 0 when writing to a new buffer, the first line will be 1330 set to "Reading from channel output..." 1331 1332 *job-err_io* *err_name* *err_buf* 1333 "err_io": "out" stderr messages to go to stdout 1334 "err_io": "null" disconnect stderr (goes to /dev/null) 1335 "err_io": "pipe" stderr is connected to the channel (default) 1336 "err_io": "file" stderr writes to a file 1337 "err_io": "buffer" stderr appends to a buffer (see below) 1338 "err_name": "/path/file" the name of the file or buffer to write to 1339 "err_buf": number the number of the buffer to write to 1340 "err_modifiable": 0 when writing to a buffer, 'modifiable' will be off 1341 (see below) 1342 "err_msg": 0 when writing to a new buffer, the first line will be 1343 set to "Reading from channel error..." 1344 1345 "block_write": number only for testing: pretend every other write to stdin 1346 will block 1347 1348 "env": dict environment variables for the new process 1349 "cwd": "/path/to/dir" current working directory for the new process; 1350 if the directory does not exist an error is given 1351 1352 1353 Writing to a buffer ~ 1354 *out_io-buffer* 1355 When the out_io or err_io mode is "buffer" and there is a callback, the text 1356 is appended to the buffer before invoking the callback. 1357 1358 When a buffer is used both for input and output, the output lines are put 1359 above the last line, since the last line is what is written to the channel 1360 input. Otherwise lines are appended below the last line. 1361 1362 When using JS or JSON mode with "buffer", only messages with zero or negative 1363 ID will be added to the buffer, after decoding + encoding. Messages with a 1364 positive number will be handled by a callback, commands are handled as usual. 1365 1366 The name of the buffer from "out_name" or "err_name" is compared the full name 1367 of existing buffers, also after expanding the name for the current directory. 1368 E.g., when a buffer was created with ":edit somename" and the buffer name is 1369 "somename" it will use that buffer. 1370 1371 If there is no matching buffer a new buffer is created. Use an empty name to 1372 always create a new buffer. |ch_getbufnr()| can then be used to get the 1373 buffer number. 1374 1375 For a new buffer 'buftype' is set to "nofile" and 'bufhidden' to "hide". If 1376 you prefer other settings, create the buffer first and pass the buffer number. 1377 *out_modifiable* *err_modifiable* 1378 The "out_modifiable" and "err_modifiable" options can be used to set the 1379 'modifiable' option off, or write to a buffer that has 'modifiable' off. That 1380 means that lines will be appended to the buffer, but the user can't easily 1381 change the buffer. 1382 *out_msg* *err_msg* 1383 The "out_msg" option can be used to specify whether a new buffer will have the 1384 first line set to "Reading from channel output...". The default is to add the 1385 message. "err_msg" does the same for channel error. 1386 1387 When an existing buffer is to be written where 'modifiable' is off and the 1388 "out_modifiable" or "err_modifiable" options is not zero, an error is given 1389 and the buffer will not be written to. 1390 1391 When the buffer written to is displayed in a window and the cursor is in the 1392 first column of the last line, the cursor will be moved to the newly added 1393 line and the window is scrolled up to show the cursor if needed. 1394 1395 Undo is synced for every added line. NUL bytes are accepted (internally Vim 1396 stores these as NL bytes). 1397 1398 1399 Writing to a file ~ 1400 *E920* 1401 The file is created with permissions 600 (read-write for the user, not 1402 accessible for others). Use |setfperm()| to change this. 1403 1404 If the file already exists it is truncated. 1405 1406 ============================================================================== 1407 13. Controlling a job *job-control* 1408 1409 To get the status of a job: > 1410 echo job_status(job) 1411 1412 To make a job stop running: > 1413 job_stop(job) 1414 1415 This is the normal way to end a job. On Unix it sends a SIGTERM to the job. 1416 It is possible to use other ways to stop the job, or even send arbitrary 1417 signals. E.g. to force a job to stop, "kill it": > 1418 job_stop(job, "kill") 1419 1420 For more options see |job_stop()|. 1421 1422 ============================================================================== 1423 14. Using a prompt buffer *prompt-buffer* 1424 1425 If you want to type input for the job in a Vim window you have a few options: 1426 - Use a normal buffer and handle all possible commands yourself. 1427 This will be complicated, since there are so many possible commands. 1428 - Use a terminal window. This works well if what you type goes directly to 1429 the job and the job output is directly displayed in the window. 1430 See |terminal-window|. 1431 - Use a window with a prompt buffer. This works well when entering a line for 1432 the job in Vim while displaying (possibly filtered) output from the job. 1433 1434 A prompt buffer is created by setting 'buftype' to "prompt". You would 1435 normally only do that in a newly created buffer. 1436 1437 The user can edit and enter one line of text at the very last line of the 1438 buffer. When pressing Enter in the prompt line the callback set with 1439 |prompt_setcallback()| is invoked. It would normally send the line to a job. 1440 Another callback would receive the output from the job and display it in the 1441 buffer, below the prompt (and above the next prompt). 1442 1443 Only the text in the last line, after the prompt, is editable. The rest of 1444 the buffer is not modifiable with Normal mode commands. It can be modified by 1445 calling functions, such as |append()|. Using other commands may mess up the 1446 buffer. 1447 1448 After setting 'buftype' to "prompt" Vim does not automatically start Insert 1449 mode, use `:startinsert` if you want to enter Insert mode, so that the user 1450 can start typing a line. 1451 1452 The text of the prompt can be set with the |prompt_setprompt()| function. If 1453 no prompt is set with |prompt_setprompt()|, "% " is used. You can get the 1454 effective prompt text for a buffer, with |prompt_getprompt()|. 1455 1456 The user can go to Normal mode and navigate through the buffer. This can be 1457 useful to see older output or copy text. 1458 1459 The CTRL-W key can be used to start a window command, such as CTRL-W w to 1460 switch to the next window. This also works in Insert mode (use Shift-CTRL-W 1461 to delete a word). When leaving the window Insert mode will be stopped. When 1462 coming back to the prompt window Insert mode will be restored. 1463 1464 Any command that starts Insert mode, such as "a", "i", "A" and "I", will move 1465 the cursor to the last line. "A" will move to the end of the line, "I" to the 1466 start of the line. 1467 1468 Here is an example for Unix. It starts a shell in the background and prompts 1469 for the next shell command. Output from the shell is displayed above the 1470 prompt. > 1471 1472 " Create a channel log so we can see what happens. 1473 call ch_logfile('logfile', 'w') 1474 1475 " Function handling a line of text that has been typed. 1476 func TextEntered(text) 1477 " Send the text to a shell with Enter appended. 1478 call ch_sendraw(g:shell_job, a:text .. "\n") 1479 endfunc 1480 1481 " Function handling output from the shell: Add it above the prompt. 1482 func GotOutput(channel, msg) 1483 call append(line("$") - 1, "- " .. a:msg) 1484 endfunc 1485 1486 " Function handling the shell exits: close the window. 1487 func JobExit(job, status) 1488 quit! 1489 endfunc 1490 1491 " Start a shell in the background. 1492 let shell_job = job_start(["/bin/sh"], #{ 1493 \ out_cb: function('GotOutput'), 1494 \ err_cb: function('GotOutput'), 1495 \ exit_cb: function('JobExit'), 1496 \ }) 1497 1498 new 1499 set buftype=prompt 1500 let buf = bufnr('') 1501 call prompt_setcallback(buf, function("TextEntered")) 1502 eval prompt_setprompt(buf, "shell command: ") 1503 1504 " start accepting shell commands 1505 startinsert 1506 < 1507 The same in |Vim9| script: > 1508 1509 vim9script 1510 1511 # Create a channel log so we can see what happens. 1512 ch_logfile('logfile', 'w') 1513 1514 var shell_job: job 1515 1516 # Function handling a line of text that has been typed. 1517 def TextEntered(text: string) 1518 # Send the text to a shell with Enter appended. 1519 ch_sendraw(shell_job, text .. "\n") 1520 enddef 1521 1522 # Function handling output from the shell: Add it above the prompt. 1523 def GotOutput(channel: channel, msg: string) 1524 append(line("$") - 1, "- " .. msg) 1525 enddef 1526 1527 # Function handling the shell exits: close the window. 1528 def JobExit(job: job, status: number) 1529 quit! 1530 enddef 1531 1532 # Start a shell in the background. 1533 shell_job = job_start(["/bin/sh"], { 1534 out_cb: GotOutput, 1535 err_cb: GotOutput, 1536 exit_cb: JobExit, 1537 }) 1538 1539 new 1540 set buftype=prompt 1541 var buf = bufnr('') 1542 prompt_setcallback(buf, TextEntered) 1543 prompt_setprompt(buf, "shell command: ") 1544 1545 # start accepting shell commands 1546 startinsert 1547 1548 ============================================================================== 1549 15. Language Server Protocol *language-server-protocol* 1550 1551 The language server protocol specification is available at: 1552 1553 https://microsoft.github.io/language-server-protocol/specification 1554 1555 Each LSP protocol message starts with a simple HTTP header followed by the 1556 payload encoded in JSON-RPC format. This is described in: 1557 1558 https://www.jsonrpc.org/specification 1559 1560 To encode and send a LSP request/notification message in a Vim |Dict| into a 1561 LSP JSON-RPC message and to receive and decode a LSP JSON-RPC 1562 response/notification message into a Vim |Dict|, connect to the LSP server 1563 with the |channel-mode| set to "lsp". 1564 1565 For messages received on a channel with |channel-mode| set to "lsp", Vim will 1566 process the HTTP header and decode the JSON-RPC payload into a Vim |Dict| type 1567 and call the |channel-callback| function or the specified 1568 |channel-onetime-callback| function. When sending messages on a channel using 1569 the |ch_evalexpr()| or |ch_sendexpr()| functions, Vim will add the HTTP header 1570 and encode the Vim expression into JSON. Refer to |json_encode()| and 1571 |json_decode()| for more information about how Vim encodes and decodes the 1572 builtin types into JSON. 1573 1574 To open a channel using the "lsp" mode, set the "mode" item in the |ch_open()| 1575 {options} argument to "lsp". Example: > 1576 1577 let ch = ch_open(..., #{mode: 'lsp'}) 1578 1579 To open a channel using the "lsp" mode with a job, set the "in_mode" and 1580 "out_mode" items in the |job_start()| {options} argument to "lsp". Example: > 1581 1582 let cmd = ['clangd', '--background-index', '--clang-tidy'] 1583 let opts = {} 1584 let opts.in_mode = 'lsp' 1585 let opts.out_mode = 'lsp' 1586 let opts.err_mode = 'nl' 1587 let opts.out_cb = function('LspOutCallback') 1588 let opts.err_cb = function('LspErrCallback') 1589 let opts.exit_cb = function('LspExitCallback') 1590 let job = job_start(cmd, opts) 1591 1592 Note that if a job outputs LSP messages on stdout and non-LSP messages on 1593 stderr, then the channel-callback function should handle both the message 1594 formats appropriately or you should use a separate callback function for 1595 "out_cb" and "err_cb" to handle them as shown above. 1596 1597 To synchronously send a JSON-RPC request to the server, use the 1598 |ch_evalexpr()| function. This function will wait and return the decoded 1599 response message from the server. You can use either the |channel-timeout| or 1600 the "timeout" field in the {options} argument to control the response wait 1601 time. If the request times out, then an empty |Dict| is returned. Example: > 1602 1603 let req = {} 1604 let req.method = 'textDocument/definition' 1605 let req.params = {} 1606 let req.params.textDocument = #{uri: 'a.c'} 1607 let req.params.position = #{line: 10, character: 3} 1608 let defs = ch_evalexpr(ch, req, #{timeout: 100}) 1609 if defs->empty() 1610 ... <handle failure> 1611 endif 1612 1613 Note that in the request message the "id" field should not be specified. If 1614 it is specified, then Vim will overwrite the value with an internally 1615 generated identifier. Vim currently supports only a number type for the "id" 1616 field. 1617 The callback function will be invoked for both a successful and a failed RPC 1618 request. 1619 1620 To send a JSON-RPC request to the server and asynchronously process the 1621 response, use the |ch_sendexpr()| function and supply a callback function. If 1622 the "id" field is present in the request message, then Vim will overwrite it 1623 with an internally generated number. This function returns a Dict with the 1624 identifier used for the message. This can be used to send cancellation 1625 request to the LSP server (if needed). Example: > 1626 1627 let req = {} 1628 let req.method = 'textDocument/hover' 1629 let req.id = 200 1630 let req.params = {} 1631 let req.params.textDocument = #{uri: 'a.c'} 1632 let req.params.position = #{line: 10, character: 3} 1633 let resp = ch_sendexpr(ch, req, #{callback: 'HoverFunc'}) 1634 1635 To cancel an outstanding asynchronous LSP request sent to the server using the 1636 |ch_sendexpr()| function, send a cancellation message to the server using the 1637 |ch_sendexpr()| function with the ID returned by the |ch_sendexpr()| function 1638 for the request. Example: > 1639 1640 " send a completion request 1641 let req = {} 1642 let req.method = 'textDocument/completion' 1643 let req.params = {} 1644 let req.params.textDocument = #{uri: 'a.c'} 1645 let req.params.position = #{line: 10, character: 3} 1646 let reqstatus = ch_sendexpr(ch, req, #{callback: 'LspComplete'}) 1647 " send a cancellation notification 1648 let notif = {} 1649 let notif.method = '$/cancelRequest' 1650 let notif.id = reqstatus.id 1651 call ch_sendexpr(ch, notif) 1652 1653 To send a JSON-RPC notification message to the server, use the |ch_sendexpr()| 1654 function. As the server will not send a response message to the notification, 1655 don't specify the "callback" item. Example: > 1656 1657 call ch_sendexpr(ch, #{method: 'initialized'}) 1658 1659 To respond to a JSON-RPC request message from the server, use the 1660 |ch_sendexpr()| function. In the response message, copy the "id" field value 1661 from the server request message. Example: > 1662 1663 let resp = {} 1664 let resp.id = req.id 1665 let resp.result = 1 1666 call ch_sendexpr(ch, resp) 1667 1668 The JSON-RPC notification messages from the server are delivered through the 1669 |channel-callback| function. 1670 1671 Depending on the use case, you can use the ch_evalexpr(), ch_sendexpr() and 1672 ch_sendraw() functions on the same channel. 1673 1674 A LSP request message has the following format (expressed as a Vim Dict). The 1675 "params" field is optional: > 1676 1677 { 1678 "jsonrpc": "2.0", 1679 "id": <number>, 1680 "method": <string>, 1681 "params": <list|dict> 1682 } 1683 1684 A LSP response message has the following format (expressed as a Vim Dict). 1685 The "result" and "error" fields are optional: > 1686 1687 { 1688 "jsonrpc": "2.0", 1689 "id": <number>, 1690 "result": <vim type> 1691 "error": <dict> 1692 } 1693 1694 A LSP notification message has the following format (expressed as a Vim Dict). 1695 The "params" field is optional: > 1696 1697 { 1698 "jsonrpc": "2.0", 1699 "method": <string>, 1700 "params": <list|dict> 1701 } 1702 1703 ============================================================================== 1704 16. Debug Adapter Protocol *debug-adapter-protocol* 1705 1706 The debug adapter protocol is very similar to the language server protocol, 1707 with the main difference being that it does not use the JSON-RPC format. The 1708 specification can be found here: 1709 1710 https://microsoft.github.io/debug-adapter-protocol/specification 1711 1712 The protocol uses the same header format as the LSP protocol. 1713 1714 To encode and send a DAP request/notification message in a Vim |Dict| into a 1715 JSON message and to receive and decode a DAP JSON response/notification 1716 message into a Vim |Dict|, connect to the debug adapter with the 1717 |channel-mode| set to "dap". 1718 1719 For messages received on a channel with |channel-mode| set to "dap", Vim will 1720 process the HTTP header and decode the JSON payload into a Vim |Dict| type. 1721 When sending messages on a channel using the |ch_evalexpr()| or 1722 |ch_sendexpr()| functions, Vim will add the HTTP header and encode the Vim 1723 expression into JSON. 1724 1725 Vim will automatically add the "seq" field to the JSON DAP message, and manage 1726 the "request_seq" field as well for responses. However it will not add the 1727 "type" field, it should be manually specified in the |Dict|. 1728 1729 Otherwise the behaviour is the same as how Vim handles the "lsp" channel mode 1730 |language-server-protocol|. 1731 1732 vim:tw=78:ts=8:noet:ft=help:norl: