channel.txt 58 KB

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