codekingpro/portable-devtools
114k
1*terminal.txt* For Vim version 9.2. Last change: 2026 Apr 062 3 4 VIM REFERENCE MANUAL by Bram Moolenaar5 6 7Terminal window support *terminal* *terminal-window*8 9 10The terminal feature is optional, use this to check if your Vim has it: >11 echo has('terminal')12If the result is "1" you have it.13 14 151. Basic use |terminal-use|16 Typing |terminal-typing|17 Size and color |terminal-size-color|18 Command syntax |:terminal|19 Resizing |terminal-resizing|20 Terminal Modes |Terminal-mode|21 Cursor style |terminal-cursor-style|22 Session |terminal-session|23 Special keys |terminal-special-keys|24 Unix |terminal-unix|25 MS-Windows |terminal-ms-windows|262. Terminal functions |terminal-function-details|273. Terminal communication |terminal-communication|28 Vim to job: term_sendkeys() |terminal-to-job|29 Job to Vim: JSON API |terminal-api|30 Using the client-server feature |terminal-client-server|314. Remote testing |terminal-testing|325. Diffing screen dumps |terminal-diff|33 Writing a screen dump test for Vim |terminal-dumptest|34 Creating a screen dump |terminal-screendump|35 Comparing screen dumps |terminal-diffscreendump|366. Debugging |terminal-debug|37 Starting |termdebug-starting|38 Example session |termdebug-example|39 Stepping through code |termdebug-stepping|40 Inspecting variables |termdebug-variables|41 Navigating stack frames |termdebug-frames|42 Other commands |termdebug-commands|43 Events |termdebug-events|44 Prompt mode |termdebug-prompt|45 Mappings |termdebug-mappings|46 Communication |termdebug-communication|47 Remote Debugging |termdebug-remote|48 Customizing |termdebug-customizing|49 50{only available when compiled with the |+terminal| feature}51The terminal feature requires the |+job| and |+channel| features.52 53==============================================================================541. Basic use *terminal-use*55 56This feature is for running a terminal emulator in a Vim window. A job can be57started connected to the terminal emulator. For example, to run a shell: >58 :term bash59 60Or to run build command: >61 :term make myprogram62 63The job runs asynchronously from Vim, the window will be updated to show64output from the job, also while editing in another window.65 66 67Typing ~68 *terminal-typing*69When the keyboard focus is in the terminal window, typed keys will be sent to70the job. This uses a pty when possible. You can click outside of the71terminal window to move keyboard focus elsewhere.72 73 *t_CTRL-W_CTRL-W* *t_CTRL-W_:*74CTRL-W can be used to navigate between windows and other CTRL-W commands,75e.g.:76 CTRL-W CTRL-W move focus to the next window77 CTRL-W : enter an Ex command78See |CTRL-W| for more commands.79 80Special in the terminal window: *t_CTRL-W_.* *t_CTRL-W_N*81 CTRL-W . send a CTRL-W to the job in the terminal82 CTRL-W CTRL-\ send a CTRL-\ to the job in the terminal83 CTRL-W N go to Terminal-Normal mode, see |Terminal-mode|84 CTRL-\ CTRL-N go to Terminal-Normal mode, see |Terminal-mode|85 CTRL-W " {reg} paste register {reg} *t_CTRL-W_quote*86 Also works with the = register to insert the result of87 evaluating an expression.88 CTRL-W CTRL-C ends the job, see below |t_CTRL-W_CTRL-C|89 CTRL-W gt go to next tabpage, same as `gt` *t_CTRL-W_gt*90 CTRL-W gT go to previous tabpage, same as `gT` *t_CTRL-W_gT*91 92See option 'termwinkey' for specifying another key instead of CTRL-W that93will work like CTRL-W. However, typing 'termwinkey' twice sends 'termwinkey'94to the job. For example:95 'termwinkey' CTRL-W move focus to the next window96 'termwinkey' : enter an Ex command97 'termwinkey' 'termwinkey' send 'termwinkey' to the job in the terminal98 'termwinkey' . send 'termwinkey' to the job in the terminal99 'termwinkey' CTRL-\ send a CTRL-\ to the job in the terminal100 'termwinkey' N go to terminal Normal mode, see below101 'termwinkey' CTRL-N same as CTRL-W N |t_CTRL-W_N|102 'termwinkey' CTRL-C same as CTRL-W CTRL-C |t_CTRL-W_CTRL-C|103 *t_CTRL-\_CTRL-N*104The special key combination CTRL-\ CTRL-N can be used to switch to Normal105mode, just like this works in any other mode.106 *t_CTRL-W_CTRL-C*107CTRL-W CTRL-C can be typed to forcefully end the job. On MS-Windows a108CTRL-Break will also kill the job.109 110If you type CTRL-C the effect depends on what the pty has been configured to111do. For simple commands this causes a SIGINT to be sent to the job, which112would end it. Other commands may ignore the SIGINT or handle the CTRL-C113themselves (like Vim does).114 115To change the keys you type use terminal mode mappings, see |:tmap|.116These are defined like any mapping, but apply only when typing keys that are117sent to the job running in the terminal. For example, to make F1 switch118to Terminal-Normal mode: >119 tnoremap <F1> <C-W>N120You can use Esc, but you need to make sure it won't cause other keys to121break (cursor keys start with an Esc, so they may break), this probably only122works in the GUI: >123 tnoremap <Esc> <C-W>N124 set notimeout ttimeout timeoutlen=100125 126You can also create menus similar to terminal mode mappings, but you have to127use |:tlmenu| instead of |:tmenu|.128 129 *options-in-terminal*130After opening the terminal window and setting 'buftype' to "terminal" the131|TerminalWinOpen| autocommand event is triggered. This makes it possible to set132options specifically for the terminal window and buffer. Example: >133 au TerminalWinOpen * setlocal bufhidden=hide134This only works properly if the terminal is not hidden.135 136For both hidden and non-hidden terminals this works, both for buffer-local and137window-local options: >138 au TerminalWinOpen,BufWinEnter * if &buftype == 'terminal'139 \ | setlocal bufhidden=hide colorcolumn=123140 \ | endif141Note that for a hidden terminal the options are not set until the terminal is142no longer hidden.143 144There is also the |TerminalOpen| event. Keep in mind this may be triggered145for a hidden terminal, then the current window and buffer are not that of the146new terminal.147You need to use <abuf>, which is set to the terminal buffer. Example: >148 au TerminalOpen * call setbufvar(expand('<abuf>')->str2nr(),149 \ '&termwinscroll', 1000)150For a window-local option, you need to delay setting the option until the151terminal window has been created (this only works for a hidden terminal): >152 au TerminalOpen * exe printf(153 \ 'au BufWinEnter <buffer=%d> ++once setlocal colorcolumn=%d',154 \ expand('<abuf>')->str2nr(), 123)155For a non-hidden terminal use |TerminalWinOpen|.156 157Mouse events (click and drag) are passed to the terminal. Mouse move events158are only passed when Vim itself is receiving them. For a terminal that is159when 'balloonevalterm' is enabled.160 161 162Size and color ~163 *terminal-size-color*164See option 'termwinsize' for controlling the size of the terminal window.165(TODO: scrolling when the terminal is larger than the window)166 167The job running in the terminal can change the colors. The default foreground168and background colors are taken from Vim, the Normal highlight group.169 170For a color terminal the 'background' option is used to decide whether the171terminal window will start with a white or black background.172 173To use a different color the Terminal highlight group can be used, for174example: >175 hi Terminal ctermbg=lightgrey ctermfg=blue guibg=lightgrey guifg=blue176Instead of Terminal another group can be specified with the "term_highlight"177option for `term_start()`.178 179 *g:terminal_ansi_colors*180In GUI mode or with 'termguicolors', the 16 ANSI colors used by default in new181terminal windows may be configured using the variable182`g:terminal_ansi_colors`, which should be a list of 16 color names or183hexadecimal color codes, similar to those accepted by |highlight-guifg|. When184not using GUI colors, the terminal window always uses the 16 ANSI colors of185the underlying terminal.186When using `term_start()` the colors can be set with the "ansi_colors" option.187The |term_setansicolors()| function can be used to change the colors, and188|term_getansicolors()| to get the currently used colors.189 190 191Command syntax ~192 193:[range]ter[minal] [options] [command] *:ter* *:terminal*194 Open a new terminal window.195 196 If [command] is provided run it as a job and connect197 the input and output to the terminal.198 If [command] is not given the 'shell' option is used.199 if [command] is NONE no job is started, the pty of the200 terminal can be used by a command like gdb.201 202 If [command] outputs NUL bytes, those will be203 converted to new lines |NL-used-for-Nul|.204 205 *terminal-nospecial*206 Vim itself only recognizes |cmdline-special|207 characters inside [command]. Everything else will be208 passed untouched. When needed to expand wildcards,209 environment variables or other shell specials consider210 |term++shell| option.211 212 If [command] is missing the default behavior is to213 close the terminal when the shell exits. This can be214 changed with the ++noclose argument.215 If [command] is present the default behavior is to216 keep the terminal open in Terminal-Normal mode. This217 can be changed with the ++close argument.218 219 No Vim command can follow, any | is included in220 [command]. Use `:execute` if you must have a Vim221 command following in the same line.222 223 *terminal-bufname*224 A new buffer will be created, using [command] or225 'shell' as the name, prefixed with a "!". If a buffer226 by this name already exists a number is added in227 parentheses. E.g. if "gdb" exists the second terminal228 buffer will use "!gdb (1)".229 230 If [range] is given the specified lines are used as231 input for the job. It will not be possible to type232 keys in the terminal window. For MS-Windows see the233 ++eof argument below.234 235 *term++close* *term++open*236 Supported [options] are:237 ++close The terminal window will close238 automatically when the job terminates.239 |terminal-close|240 ++noclose The terminal window will NOT close241 automatically when the job terminates.242 ++open When the job terminates and no window243 shows it, a window will be opened.244 Note that this can be interruptive.245 The last of ++close, ++noclose and ++open246 matters and rules out earlier arguments.247 248 ++curwin Open the terminal in the current249 window, do not split the current250 window. Fails if the current buffer251 cannot be |abandon|ed.252 ++hidden Open the terminal in a hidden buffer,253 no window will be used.254 ++norestore Do not include this terminal window255 in a session file.256 257 *term++shell*258 ++shell Instead of executing {command}259 directly, use a shell, like with260 `:!command` *E279*261 {only works on Unix and MS-Windows}262 The resulting command will look like263 'shell' 'shellcmdflag' [command]264 Other options related to `:!command`265 have no effect.266 ++kill={how} When trying to close the terminal267 window kill the job with {how}. See268 |term_setkill()| for the values.269 ++rows={height} Use {height} for the terminal window270 height. If the terminal uses the full271 Vim height (no window above or below272 the terminal window) the command line273 height will be reduced as needed.274 ++cols={width} Use {width} for the terminal window275 width. If the terminal uses the full276 Vim width (no window left or right of277 the terminal window) this value is278 ignored.279 ++eof={text} When using [range]: text to send after280 the last line was written. Cannot281 contain white space. A CR is282 appended. For MS-Windows the default283 is to send CTRL-D.284 E.g. for a shell use "++eof=exit" and285 for Python "++eof=exit()". Special286 codes can be used like with `:map`,287 e.g. "<C-Z>" for CTRL-Z.288 ++type={pty} (MS-Windows only): Use {pty} as the289 virtual console. See 'termwintype'290 for the values.291 ++api={expr} Permit the function name starting with292 {expr} to be called as |terminal-api|293 function. If {expr} is empty then no294 function can be called.295 296 If you want to use more options use the |term_start()|297 function.298 If you want to split the window vertically, use: >299 :vertical terminal300< Or short: >301 :vert ter302 303When the buffer associated with the terminal is forcibly unloaded or wiped out304the job is killed, similar to calling `job_stop(job, "kill")` .305Closing the window normally results in |E947|. When a kill method was set306with "++kill={how}" or |term_setkill()| then closing the window will use that307way to kill or interrupt the job. For example: >308 :term ++kill=term tail -f /tmp/log309 310So long as the job is running the window behaves like it contains a modified311buffer. Trying to close the window with `CTRL-W :quit` fails. When using312`CTRL-W :quit!` the job is ended. The text in the window is lost, the buffer313is deleted. With `CTRL-W :bunload!` the buffer remains but will be empty.314 315Trying to close the window with `CTRL-W :close` also fails. Using316`CTRL-W :close!` will close the window and make the buffer hidden.317 318You can use `CTRL-W :hide` to close the terminal window and make the buffer319hidden, the job keeps running. The `:buffer` command can be used to turn the320current window into a terminal window. If there are unsaved changes this321fails, use ! to force, as usual.322 323 *terminal-close*324When the terminal job finishes and no [command] was given (e.g. the 'shell'325command was executed), the terminal window will be closed by default (unless326the buffer in next window receiving the space has the 'nobuflisted' option327set, in which case the terminal window would not be closed automatically, but328a new empty buffer would be opened in that window).329 330When the terminal window is closed, e.g. when the shell exits and "++close"331argument was used, and this is the last normal Vim window, then Vim will exit.332This is like using |:quit| in a normal window. Help and preview windows are333not counted.334 335To have a background job run without a window, and open the window when it's336done, use options like this: >337 :term ++hidden ++open make338Note that the window will open at an unexpected moment, this will interrupt339what you are doing.340 341 *E947* *E948*342So long as the job is running, the buffer is considered modified and Vim343cannot be quit easily, see |abandon|.344 345When the job has finished and no changes were made to the buffer: closing the346window will wipe out the buffer.347 348Before changes can be made to a terminal buffer, the 'modifiable' option must349be set. This is only possible when the job has finished. At the first change350the buffer will become a normal buffer and the highlighting is removed.351You may want to change the buffer name with |:file| to be able to write, since352the buffer name will still be set to the command.353 354 355Resizing ~356 *terminal-resizing*357The size of the terminal can be in one of three modes:358 3591. The 'termwinsize' option is empty: The terminal size follows the window360 size. The minimal size is 2 screen lines with 10 cells.361 3622. The 'termwinsize' option is "rows*cols", where "rows" is the minimal number363 of screen rows and "cols" is the minimal number of cells.364 3653. The 'termwinsize' option is "rowsXcols" (where the x is upper or lower366 case). The terminal size is fixed to the specified number of screen lines367 and cells. If the window is bigger there will be unused empty space.368 369If the window is smaller than the terminal size, only part of the terminal can370be seen (the lower-left part).371 372The |term_getsize()| function can be used to get the current size of the373terminal. |term_setsize()| can be used only when in the first or second mode,374not when 'termwinsize' is "rowsXcols".375 376 377Terminal-Job and Terminal-Normal mode ~378 *Terminal-mode* *Terminal-Job*379When the job is running the contents of the terminal is under control of the380job. That includes the cursor position. Typed keys are sent to the job.381The terminal contents can change at any time. This is called Terminal-Job382mode.383 384Use CTRL-W N (or 'termwinkey' N) to switch to Terminal-Normal mode. Now the385contents of the terminal window is under control of Vim, the job output is386suspended. CTRL-\ CTRL-N does the same.387 388Terminal-Job mode is where |:tmap| mappings are applied. Keys sent by389|term_sendkeys()| are not subject to tmap, but keys from |feedkeys()| are.390 391It is not possible to enter Insert mode from Terminal-Job mode.392 393 *Terminal-Normal* *E946*394In Terminal-Normal mode you can move the cursor around with the usual Vim395commands, Visually mark text, yank text, etc. But you cannot change the396contents of the buffer. The commands that would start insert mode, such as397'i' and 'a', return to Terminal-Job mode. The window will be updated to show398the contents of the terminal. |:startinsert| is ineffective.399 400In Terminal-Normal mode the statusline and window title show "(Terminal)". If401the job ends while in Terminal-Normal mode this changes to402"(Terminal-finished)".403 404When the job outputs lines in the terminal, such that the contents scrolls off405the top, those lines are remembered and can be seen in Terminal-Normal mode.406The number of lines is limited by the 'termwinscroll' option. When going over407this limit, the first 10% of the scrolled lines are deleted and are lost.408 409 410Cursor style ~411 *terminal-cursor-style*412By default the cursor in the terminal window uses a not blinking block. The413normal xterm escape sequences can be used to change the blinking state and the414shape. Once focus leaves the terminal window Vim will restore the original415cursor.416 417An exception is when xterm is started with the "-bc" argument, or another way418that causes the cursor to blink. This actually means that the blinking flag419is inverted. Since Vim cannot detect this, the terminal window cursor420blinking will also be inverted.421 422 423Session ~424 *terminal-session*425A terminal window will be restored when using a session file, if possible and426wanted.427 428If "terminal" was removed from 'sessionoptions' then no terminal windows will429be restored.430 431If the job in the terminal was finished the window will not be restored.432 433If the terminal can be restored, the command that was used to open it will be434used again. To change this use the |term_setrestore()| function. This can435also be used to not restore a specific terminal by setting the command to436"NONE".437 438 439Special keys ~440 *terminal-special-keys*441Since the terminal emulator simulates an xterm, only escape sequences that442both Vim and xterm recognize will be available in the terminal window. If you443want to pass on other escape sequences to the job running in the terminal you444need to set up forwarding. Example: >445 tmap <expr> <Esc>]b SendToTerm("\<Esc>]b")446 func SendToTerm(what)447 call term_sendkeys('', a:what)448 return ''449 endfunc450 451 452Unix ~453 *terminal-unix*454On Unix a pty is used to make it possible to run all kinds of commands. You455can even run Vim in the terminal! That's used for debugging, see below.456 457Environment variables are used to pass information to the running job:458 TERM the name of the terminal, from the 'term' option or459 $TERM in the GUI; falls back to "xterm" if it does not460 start with "xterm"461 ROWS number of rows in the terminal initially462 LINES same as ROWS463 COLUMNS number of columns in the terminal initially464 COLORS number of colors, 't_Co' (256*256*256 in the GUI)465 VIM_SERVERNAME v:servername466 VIM_TERMINAL v:version467 468 469MS-Windows ~470 *terminal-ms-windows*471On MS-Windows winpty is used to make it possible to run all kind of commands.472Obviously, they must be commands that run in a terminal, not open their own473window.474 475You need the following two files from winpty:476 477 winpty.dll478 winpty-agent.exe479 480You can download them from the following page:481 482 https://github.com/rprichard/winpty483 484Just put the files somewhere in your PATH. You can set the 'winptydll' option485to point to the right file, if needed. If you have both the 32-bit and 64-bit486version, rename to winpty32.dll and winpty64.dll to match the way Vim was487build.488 *ConPTY* *E982*489On more recent versions of MS-Windows 10 (beginning with the "October 2018490Update"), winpty is no longer required. On those versions, |:terminal| will use491Windows' built-in support for hosting terminal applications, "ConPTY". When492ConPTY is in use, there may be rendering artifacts regarding ambiguous-width493characters. If you encounter any such issues, install "winpty". ConPTY494support is considered stable with the first release of Windows 11.495 496Environment variables are used to pass information to the running job:497 VIM_SERVERNAME v:servername498 499 *git-vimdumps*500There exists a git-difftool extension called `git-vimdumps` that can be used501to conveniently inspect screendump files and diff them. Please see in the Vim502Repository the file `src/testdir/commondumps.vim` on how to create and use503this git extension.504 505==============================================================================5062. Terminal functions *terminal-function-details*507 508 *term_dumpdiff()*509term_dumpdiff({filename}, {filename} [, {options}])510 Open a new window displaying the difference between the two511 files. The files must have been created with512 |term_dumpwrite()|.513 Returns the buffer number or zero when the diff fails.514 Also see |terminal-diff|.515 NOTE: this does not work with double-width characters yet.516 517 The top part of the buffer contains the contents of the first518 file, the bottom part of the buffer contains the contents of519 the second file. The middle part shows the differences.520 The parts are separated by a line of equals.521 522 If the {options} argument is present, it must be a Dict with523 these possible members:524 "term_name" name to use for the buffer name, instead525 of the first file name.526 "term_rows" vertical size to use for the terminal,527 instead of using 'termwinsize', but528 respecting the minimal size; valid range529 is from 0 to 1000530 "term_cols" horizontal size to use for the terminal,531 instead of using 'termwinsize', but532 respecting the minimal size; valid range533 is from 0 to 1000534 "vertical" split the window vertically535 "curwin" use the current window, do not split the536 window; fails if the current buffer537 cannot be |abandon|ed538 "bufnr" do not create a new buffer, use the539 existing buffer "bufnr". This buffer540 must have been previously created with541 term_dumpdiff() or term_dumpload() and542 visible in a window.543 "norestore" do not add the terminal window to a544 session file545 546 Each character in the middle part indicates a difference. If547 there are multiple differences only the first in this list is548 used:549 X different character550 w different width551 f different foreground color552 b different background color553 a different attribute554 + missing position in first file555 - missing position in second file556 > cursor position in first file, not in second557 < cursor position in second file, not in first558 559 Using the "s" key the top and bottom parts are swapped. This560 makes it easy to spot a difference.561 562 Can also be used as a |method|: >563 GetFilename()->term_dumpdiff(otherfile)564<565 Return type: |Number|566 567 568term_dumpload({filename} [, {options}]) *term_dumpload()*569 Open a new window displaying the contents of {filename}570 The file must have been created with |term_dumpwrite()|.571 Returns the buffer number or zero when it fails.572 Also see |terminal-diff|.573 574 For {options} see |term_dumpdiff()|.575 576 Can also be used as a |method|: >577 GetFilename()->term_dumpload()578<579 Return type: |Number|580 581 582term_dumpwrite({buf}, {filename} [, {options}]) *term_dumpwrite()*583 Dump the contents of the terminal screen of {buf} in the file584 {filename}. This uses a format that can be used with585 |term_dumpload()| and |term_dumpdiff()|.586 If the job in the terminal already finished an error is given:587 *E958*588 If {filename} already exists an error is given: *E953*589 Also see |terminal-diff|.590 591 {options} is a dictionary with these optional entries:592 "rows" maximum number of rows to dump593 "columns" maximum number of columns to dump594 595 Can also be used as a |method|, the base is used for the file596 name: >597 GetFilename()->term_dumpwrite(bufnr)598<599 Return type: void600 601 602term_getaltscreen({buf}) *term_getaltscreen()*603 Returns 1 if the terminal of {buf} is using the alternate604 screen.605 {buf} is used as with |term_getsize()|.606 607 Can also be used as a |method|: >608 GetBufnr()->term_getaltscreen()609<610 Return type: |Number|611 612 613term_getansicolors({buf}) *term_getansicolors()*614 Get the ANSI color palette in use by terminal {buf}.615 Returns a List of length 16 where each element is a String616 representing a color in hexadecimal "#rrggbb" format.617 Also see |term_setansicolors()| and |g:terminal_ansi_colors|.618 If neither was used returns the default colors.619 620 {buf} is used as with |term_getsize()|. If the buffer does not621 exist or is not a terminal window, an empty list is returned.622 623 Can also be used as a |method|: >624 GetBufnr()->term_getansicolors()625<626 Return type: list<string> or list<any>627 628 {only available when compiled with GUI enabled and/or the629 |+termguicolors| feature}630 631term_getattr({attr}, {what}) *term_getattr()*632 Given {attr}, a value returned by term_scrape() in the "attr"633 item, return whether {what} is on. {what} can be one of:634 bold635 italic636 underline637 strike638 reverse639 640 Can also be used as a |method|: >641 GetAttr()->term_getattr()642<643 Return type: |Number|644 645 646term_getcursor({buf}) *term_getcursor()*647 Get the cursor position of terminal {buf}. Returns a list648 with two numbers and a dictionary: [row, col, dict].649 650 "row" and "col" are one based, the first screen cell is row651 1, column 1. This is the cursor position of the terminal652 itself, not of the Vim window.653 654 "dict" can have these members:655 "visible" one when the cursor is visible, zero when it656 is hidden.657 "blink" one when the cursor is blinking, zero when it658 is not blinking.659 "shape" 1 for a block cursor, 2 for underline and 3660 for a vertical bar.661 "color" color of the cursor, e.g. "green"662 663 {buf} must be the buffer number of a terminal window. If the664 buffer does not exist or is not a terminal window, an empty665 list is returned.666 667 Can also be used as a |method|: >668 GetBufnr()->term_getcursor()669<670 Return type: list<any>671 672 673term_getjob({buf}) *term_getjob()*674 Get the Job associated with terminal window {buf}.675 {buf} is used as with |term_getsize()|.676 Returns |v:null| when there is no job. In Vim9 script, return677 |null_job| when there is no job.678 679 Can also be used as a |method|: >680 GetBufnr()->term_getjob()681<682 Return type: |job|683 684 685term_getline({buf}, {row}) *term_getline()*686 Get a line of text from the terminal window of {buf}.687 {buf} is used as with |term_getsize()|.688 689 The first line has {row} one. When {row} is "." the cursor690 line is used. When {row} is invalid an empty string is691 returned.692 693 To get attributes of each character use |term_scrape()|.694 695 Can also be used as a |method|: >696 GetBufnr()->term_getline(row)697<698 Return type: |String|699 700 701term_getscrolled({buf}) *term_getscrolled()*702 Return the number of lines that scrolled to above the top of703 terminal {buf}. This is the offset between the row number704 used for |term_getline()| and |getline()|, so that: >705 term_getline(buf, N)706< is equal to: >707 getline(N + term_getscrolled(buf))708< (if that line exists).709 710 {buf} is used as with |term_getsize()|.711 712 Can also be used as a |method|: >713 GetBufnr()->term_getscrolled()714<715 Return type: |Number|716 717 718term_getsize({buf}) *term_getsize()*719 Get the size of terminal {buf}. Returns a list with two720 numbers: [rows, cols]. This is the size of the terminal, not721 the window containing the terminal.722 723 {buf} must be the buffer number of a terminal window. Use an724 empty string for the current buffer. If the buffer does not725 exist or is not a terminal window, an empty list is returned.726 727 Can also be used as a |method|: >728 GetBufnr()->term_getsize()729<730 Return type: list<number> or list<any>731 732 733term_getstatus({buf}) *term_getstatus()*734 Get the status of terminal {buf}. This returns a String with735 a comma-separated list of these items:736 running job is running737 finished job has finished738 normal in Terminal-Normal mode739 One of "running" or "finished" is always present.740 741 {buf} must be the buffer number of a terminal window. If the742 buffer does not exist or is not a terminal window, an empty743 string is returned.744 745 Can also be used as a |method|: >746 GetBufnr()->term_getstatus()747<748 Return type: |String|749 750 751term_gettitle({buf}) *term_gettitle()*752 Get the title of terminal {buf}. This is the title that the753 job in the terminal has set.754 755 {buf} must be the buffer number of a terminal window. If the756 buffer does not exist or is not a terminal window, an empty757 string is returned.758 759 Can also be used as a |method|: >760 GetBufnr()->term_gettitle()761<762 Return type: |String|763 764 765term_gettty({buf} [, {input}]) *term_gettty()*766 Get the name of the controlling terminal associated with767 terminal window {buf}. {buf} is used as with |term_getsize()|.768 769 When {input} is omitted or 0, return the name for writing770 (stdout). When {input} is 1 return the name for reading771 (stdin). On UNIX, both return same name.772 773 Can also be used as a |method|: >774 GetBufnr()->term_gettty()775<776 Return type: |String|777 778 779term_list() *term_list()*780 Return a list with the buffer numbers of all buffers for781 terminal windows.782 783 Return type: list<number> or list<any>784 785 786term_scrape({buf}, {row}) *term_scrape()*787 Get the contents of {row} of terminal screen of {buf}.788 For {buf} see |term_getsize()|.789 790 The first line has {row} one. When {row} is "." the cursor791 line is used. When {row} is invalid an empty string is792 returned.793 794 Return a List containing a Dict for each screen cell:795 "chars" character(s) at the cell796 "fg" foreground color as #rrggbb797 "bg" background color as #rrggbb798 "attr" attributes of the cell, use |term_getattr()|799 to get the individual flags800 "width" cell width: 1 or 2801 For a double-width cell there is one item, thus the list can802 be shorter than the width of the terminal.803 804 Can also be used as a |method|: >805 GetBufnr()->term_scrape(row)806<807 Return type: list<dict<any>> or list<any>808 809 810term_sendkeys({buf}, {keys}) *term_sendkeys()*811 Send keystrokes {keys} to terminal {buf}.812 {buf} is used as with |term_getsize()|.813 814 {keys} are translated as key sequences. For example, "\<c-x>"815 means the character CTRL-X.816 817 Can also be used as a |method|: >818 GetBufnr()->term_sendkeys(keys)819<820 Return type: void821 822 823term_setansicolors({buf}, {colors}) *term_setansicolors()*824 Set the ANSI color palette used by terminal {buf}.825 {colors} must be a List of 16 valid color names or hexadecimal826 color codes, like those accepted by |highlight-guifg|.827 Also see |term_getansicolors()| and |g:terminal_ansi_colors|.828 829 The colors normally are:830 0 black831 1 dark red832 2 dark green833 3 brown834 4 dark blue835 5 dark magenta836 6 dark cyan837 7 light grey838 8 dark grey839 9 red840 10 green841 11 yellow842 12 blue843 13 magenta844 14 cyan845 15 white846 847 These colors are used in the GUI and in the terminal when848 'termguicolors' is set. When not using GUI colors (GUI mode849 or 'termguicolors'), the terminal window always uses the 16850 ANSI colors of the underlying terminal.851 852 Can also be used as a |method|: >853 GetBufnr()->term_setansicolors(colors)854<855 Return type: void856 857 {only available with GUI enabled and/or the |+termguicolors|858 feature}859 860 861term_setapi({buf}, {expr}) *term_setapi()*862 Set the function name prefix to be used for the |terminal-api|863 function in terminal {buf}. For example: >864 :call term_setapi(buf, "Myapi_")865 :call term_setapi(buf, "")866<867 The default is "Tapi_". When {expr} is an empty string then868 no |terminal-api| function can be used for {buf}.869 870 When used as a method the base is used for {buf}: >871 GetBufnr()->term_setapi({expr})872<873 Return type: void874 875 876term_setkill({buf}, {how}) *term_setkill()*877 When exiting Vim or trying to close the terminal window in878 another way, {how} defines whether the job in the terminal can879 be stopped.880 When {how} is empty (the default), the job will not be881 stopped, trying to exit will result in |E947|.882 Otherwise, {how} specifies what signal to send to the job.883 See |job_stop()| for the values.884 885 After sending the signal Vim will wait for up to a second to886 check that the job actually stopped.887 888 Can also be used as a |method|: >889 GetBufnr()->term_setkill(how)890<891 Return type: void892 893 894term_setrestore({buf}, {command}) *term_setrestore()*895 Set the command to write in a session file to restore the job896 in this terminal. The line written in the session file is: >897 terminal ++curwin ++cols=%d ++rows=%d {command}898< Make sure to escape the command properly.899 900 Use an empty {command} to run 'shell'.901 Use "NONE" to not restore this window.902 903 Can also be used as a |method|: >904 GetBufnr()->term_setrestore(command)905<906 Return type: void907 908 909term_setsize({buf}, {rows}, {cols}) *term_setsize()* *E955*910 Set the size of terminal {buf}. The size of the window911 containing the terminal will also be adjusted, if possible.912 If {rows} or {cols} is zero or negative, that dimension is not913 changed.914 915 {buf} must be the buffer number of a terminal window. Use an916 empty string for the current buffer. If the buffer does not917 exist or is not a terminal window, an error is given.918 919 Can also be used as a |method|: >920 GetBufnr()->term_setsize(rows, cols)921<922 Return type: void923 924 925term_start({cmd} [, {options}]) *term_start()*926 Open a terminal window and run {cmd} in it.927 928 {cmd} can be a string or a List, like with |job_start()|. The929 string "NONE" can be used to open a terminal window without930 starting a job, the pty of the terminal can be used by a931 command like gdb.932 933 Returns the buffer number of the terminal window. If {cmd}934 cannot be executed the window does open and shows an error935 message.936 If opening the window fails zero is returned.937 938 {options} are similar to what is used for |job_start()|, see939 |job-options|. However, not all options can be used. These940 are supported:941 all timeout options942 "stoponexit", "cwd", "env"943 "callback", "out_cb", "err_cb", "exit_cb", "close_cb"944 "in_io", "in_top", "in_bot", "in_name", "in_buf"945 "out_io", "out_name", "out_buf", "out_modifiable", "out_msg"946 "err_io", "err_name", "err_buf", "err_modifiable", "err_msg"947 On Unix:948 stdin, stdout, and stderr are connected to a pty by default,949 since bidirectional communication with the terminal is950 required. Setting "out_cb" does not switch stdout from the951 pty to a pipe. Only setting "err_cb" switches stderr to a952 pipe.953 Note: Since a pty is line-buffered and a pipe is954 block-buffered, the order of output between stdout and stderr955 may not be preserved. Without "err_cb", stderr uses the same956 pty as stdout, so the output order is preserved but stdout and957 stderr cannot be distinguished.958 959 On MS-Windows with |ConPTY|:960 stdin, stdout, and stderr are always connected through pipes961 to the pseudo console, regardless of callback settings.962 Since stdout and stderr share the same pipe, they cannot be963 separated by "err_cb".964 This is because the CreatePseudoConsole() API only accepts one965 input and one output handle, with no separate handle for966 stderr.967 968 There are extra options:969 "term_name" name to use for the buffer name, instead970 of the command name.971 "term_rows" vertical size to use for the terminal,972 instead of using 'termwinsize'; valid973 range is from 0 to 1000974 "term_cols" horizontal size to use for the terminal,975 instead of using 'termwinsize'; valid976 range is from 0 to 1000977 "vertical" split the window vertically; note that978 other window position can be defined with979 command modifiers, such as |:belowright|.980 "curwin" use the current window, do not split the981 window; fails if the current buffer982 cannot be |abandon|ed983 "hidden" do not open a window984 "norestore" do not add the terminal window to a985 session file986 "term_kill" what to do when trying to close the987 terminal window, see |term_setkill()|988 "term_finish" What to do when the job is finished:989 "close": close any windows990 "open": open window if needed991 Note that "open" can be interruptive.992 See |term++close| and |term++open|.993 "term_opencmd" command to use for opening the window994 when "open" is used for "term_finish";995 must have "%d" where the buffer number996 goes, e.g. "10split|buffer %d"; when not997 specified "botright sbuf %d" is used998 "term_highlight" highlight group to use instead of999 "Terminal"1000 "eof_chars" Text to send after all buffer lines were1001 written to the terminal. When not set1002 CTRL-D is used on MS-Windows. For Python1003 use CTRL-Z or "exit()". For a shell use1004 "exit". A CR is always added.1005 "ansi_colors" A list of 16 color names or hex codes1006 defining the ANSI palette used in GUI1007 color modes. See |g:terminal_ansi_colors|.1008 "tty_type" (MS-Windows only): Specify which pty to1009 use. See 'termwintype' for the values.1010 "term_api" function name prefix for the1011 |terminal-api| function. See1012 |term_setapi()|.1013 1014 Can also be used as a |method|: >1015 GetCommand()->term_start()1016<1017 Return type: |Number|1018 1019 1020term_wait({buf} [, {time}]) *term_wait()*1021 Wait for pending updates of {buf} to be handled.1022 {buf} is used as with |term_getsize()|.1023 {time} is how long to wait for updates to arrive in msec. If1024 not set then 10 msec will be used. Queued messages will also1025 be processed similar to |:sleep|.1026 1027 Can also be used as a |method|: >1028 GetBufnr()->term_wait()1029<1030 Return type: void1031 1032==============================================================================10333. Terminal communication *terminal-communication*1034 1035There are several ways to communicate with the job running in a terminal:1036- Use |term_sendkeys()| to send text and escape sequences from Vim to the job.1037- Use the JSON API to send encoded commands from the job to Vim.1038- Use the |client-server| mechanism. This works on machines with an X server1039 and on MS-Windows.1040 1041 1042Vim to job: term_sendkeys() ~1043 *terminal-to-job*1044This allows for remote controlling the job running in the terminal. It is a1045one-way mechanism. The job can update the display to signal back to Vim.1046For example, if a shell is running in a terminal, you can do: >1047 call term_sendkeys(buf, "ls *.java\<CR>")1048 1049This requires for the job to be in the right state where it will do the right1050thing when receiving the keys. For the above example, the shell must be1051waiting for a command to be typed.1052 1053For a job that was written for the purpose, you can use the JSON API escape1054sequence in the other direction. E.g.: >1055 call term_sendkeys(buf, "\<Esc>]51;["response"]\x07")1056 1057 1058Job to Vim: JSON API ~1059 *terminal-api*1060The job can send JSON to Vim, using a special escape sequence. The JSON1061encodes a command that Vim understands. Example of such a message: >1062 <Esc>]51;["drop", "README.md"]<07>1063 1064The body is always a list, making it easy to find the end: ]<07>.1065The <Esc>]51;msg<07> sequence is reserved by xterm for "Emacs shell", which is1066similar to what we are doing here.1067 1068Currently supported commands:1069 1070 call {funcname} {argument}1071 1072 Call a user defined function with {argument}.1073 The function is called with two arguments: the buffer number1074 of the terminal and {argument}, the decoded JSON argument.1075 By default, the function name must start with "Tapi_" to avoid1076 accidentally calling a function not meant to be used for the1077 terminal API. This can be changed with |term_setapi()|.1078 The user function should sanity check the argument.1079 The function can use |term_sendkeys()| to send back a reply.1080 Example in JSON: >1081 ["call", "Tapi_Impression", ["play", 14]]1082< Calls a function defined like this: >1083 function Tapi_Impression(bufnum, arglist)1084 if len(a:arglist) == 21085 echomsg "impression " .. a:arglist[0]1086 echomsg "count " .. a:arglist[1]1087 endif1088 endfunc1089< Output from `:echo` may be erased by a redraw, use `:echomsg`1090 to be able to see it with `:messages`.1091 1092 drop {filename} [options]1093 1094 Let Vim open a file, like the `:drop` command. If {filename}1095 is already open in a window, switch to that window. Otherwise1096 open a new window to edit {filename}.1097 Note that both the job and Vim may change the current1098 directory, thus it's best to use the full path.1099 1100 [options] is only used when opening a new window. If present,1101 it must be a Dict. Similarly to |++opt|, these entries are1102 recognized:1103 "ff" file format: "dos", "mac" or "unix"1104 "fileformat" idem1105 "enc" overrides 'fileencoding'1106 "encoding" idem1107 "bin" sets 'binary'1108 "binary" idem1109 "nobin" resets 'binary'1110 "nobinary" idem1111 "bad" specifies behavior for bad characters, see1112 |++bad|1113 1114 Example in JSON: >1115 ["drop", "path/file.txt", {"ff": "dos"}]1116 1117You can use |echoraw()| to make Vim send this escape sequence: >1118 call echoraw("\<ESC>]51;[\"call\", \"Tapi_TryThis\", [\"hello\", 123]]\x07")1119 call echoraw("\<Esc>]51;[\"drop\", \"README.md\"]\x07")1120Note: JSON requires double quotes around string values, hence those have to be1121escaped.1122 1123Rationale: Why not allow for any command or expression? Because that might1124create a security problem.1125 *terminal-autoshelldir*1126This can be used to pass the current directory from a shell to Vim.1127Put this in your .vimrc: >1128 def g:Tapi_lcd(_, path: string)1129 if isdirectory(path)1130 execute 'silent lcd ' .. fnameescape(path)1131 endif1132 enddef1133<1134And, in a bash init file: >1135 if [[ -n "$VIM_TERMINAL" ]]; then1136 PROMPT_COMMAND='_vim_sync_PWD'1137 function _vim_sync_PWD() {1138 printf '\033]51;["call", "Tapi_lcd", "%q"]\007' "$PWD"1139 }1140 fi1141<1142Or, for zsh: >1143 if [[ -n "$VIM_TERMINAL" ]]; then1144 autoload -Uz add-zsh-hook1145 add-zsh-hook -Uz chpwd _vim_sync_PWD1146 function _vim_sync_PWD() {1147 printf '\033]51;["call", "Tapi_lcd", "%q"]\007' "$PWD"1148 }1149 fi1150<1151Or, for fish: >1152 if test -n "$VIM_TERMINAL"1153 function _vim_sync_PWD --on-variable=PWD1154 printf '\033]51;["call", "Tapi_lcd", "%s"]\007' "$PWD"1155 end1156 end1157 1158 1159Using the client-server feature ~1160 *terminal-client-server*1161This only works when v:servername is not empty. If needed you can set it,1162before opening the terminal, with: >1163 call remote_startserver('vim-server')1164 1165$VIM_SERVERNAME is set in the terminal to pass on the server name.1166 1167In the job you can then do something like: >1168 vim --servername $VIM_SERVERNAME --remote +123 some_file.c1169This will open the file "some_file.c" and put the cursor on line 123.1170 1171==============================================================================11724. Remote testing *terminal-testing*1173 1174Most Vim tests execute a script inside Vim. For some tests this does not1175work, running the test interferes with the code being tested. To avoid this1176Vim is executed in a terminal window. The test sends keystrokes to it and1177inspects the resulting screen state.1178 1179Functions ~1180 1181|term_sendkeys()| send keystrokes to a terminal (not subject to tmap)1182|term_wait()| wait for screen to be updated1183|term_scrape()| inspect terminal screen1184 1185 1186==============================================================================11875. Diffing screen dumps *terminal-diff*1188 1189In some cases it can be bothersome to test that Vim displays the right1190characters on the screen. E.g. with syntax highlighting. To make this1191simpler it is possible to take a screen dump of a terminal and compare it to1192an expected screen dump.1193 1194Vim uses the window size, text, color and other attributes as displayed. The1195Vim screen size, font and other properties do not matter. Therefore this1196mechanism is portable across systems. A conventional screenshot would reflect1197all differences, including font size and family.1198 1199 1200Writing a screen dump test for Vim ~