dotemacs

My Emacs configuration
git clone git://git.entf.net/dotemacs
Log | Files | Refs | LICENSE

vterm.el (68544B)


      1 ;;; vterm.el --- Fully-featured terminal emulator -*- lexical-binding: t; -*-
      2 
      3 ;; Copyright (C) 2017-2020 by Lukas Fürmetz & Contributors
      4 ;;
      5 ;; Author: Lukas Fürmetz <fuermetz@mailbox.org>
      6 ;; Version: 0.0.2
      7 ;; URL: https://github.com/akermu/emacs-libvterm
      8 ;; Keywords: terminals
      9 ;; Package-Requires: ((emacs "25.1"))
     10 
     11 
     12 ;; This file is not part of GNU Emacs.
     13 
     14 ;; This file is free software; you can redistribute it and/or modify
     15 ;; it under the terms of the GNU General Public License as published by
     16 ;; the Free Software Foundation; either version 2, or (at your option)
     17 ;; any later version.
     18 
     19 ;; This file is distributed in the hope that it will be useful,
     20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
     21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     22 ;; GNU General Public License for more details.
     23 
     24 ;; You should have received a copy of the GNU General Public License
     25 ;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
     26 
     27 
     28 ;;; Commentary:
     29 ;;
     30 ;; Emacs-libvterm (vterm) is fully-fledged terminal emulator based on an
     31 ;; external library (libvterm) loaded as a dynamic module.  As a result of using
     32 ;; compiled code (instead of elisp), emacs-libvterm is fully capable, fast, and
     33 ;; it can seamlessly handle large outputs.
     34 
     35 ;;; Installation
     36 
     37 ;; Emacs-libvterm requires support for loading modules.  You can check if your
     38 ;; Emacs supports modules by inspecting the variable module-file-suffix.  If it
     39 ;; nil, than, you need to recompile Emacs or obtain a copy of Emacs with this
     40 ;; option enabled.
     41 
     42 ;; Emacs-libvterm requires CMake and libvterm.  If libvterm is not available,
     43 ;; emacs-libvterm will downloaded and compiled.  In this case, libtool is
     44 ;; needed.
     45 
     46 ;; The reccomended way to install emacs-libvterm is from MELPA.
     47 
     48 ;;; Usage
     49 
     50 ;; To open a terminal, simply use the command M-x vterm.
     51 
     52 ;;; Tips and tricks
     53 
     54 ;; Adding some shell-side configuration enables a large set of additional
     55 ;; features, including, directory tracking, prompt recognition, message passing.
     56 
     57 ;;; Code:
     58 
     59 (require 'term/xterm)
     60 
     61 (unless module-file-suffix
     62   (error "VTerm needs module support.  Please compile Emacs with
     63   the --with-modules option!"))
     64 
     65 (defvar vterm-copy-mode)
     66 
     67 ;;; Compilation of the module
     68 
     69 (defcustom vterm-module-cmake-args ""
     70   "Arguments given to CMake to compile vterm-module.
     71 
     72 Currently, vterm defines the following flags (in addition to the
     73 ones already available in CMake):
     74 
     75 `USE_SYSTEM_LIBVTERM'.  Set it to `Off' to use the vendored version of
     76 libvterm instead of the one installed on your system.
     77 
     78 This string is given verbatim to CMake, so it has to have the
     79 correct syntax.  An example of meaningful value for this variable
     80 is `-DUSE_SYSTEM_LIBVTERM=Off'."
     81   :type 'string
     82   :group 'vterm)
     83 
     84 (defcustom vterm-always-compile-module nil
     85   "If not nil, if `vterm-module' is not found, compile it without asking.
     86 
     87 When `vterm-always-compile-module' is nil, vterm will ask for
     88 confirmation before compiling."
     89   :type  'boolean
     90   :group 'vterm)
     91 
     92 (defvar vterm-install-buffer-name " *Install vterm* "
     93   "Name of the buffer used for compiling vterm-module.")
     94 
     95 (defun vterm-module--cmake-is-available ()
     96   "Return t if cmake is available.
     97 CMake is needed to build vterm, here we check that we can find
     98 the executable."
     99 
    100   (unless (executable-find "cmake")
    101     (error "Vterm needs CMake to be compiled.  Please, install CMake"))
    102   t)
    103 
    104 ;;;###autoload
    105 (defun vterm-module-compile ()
    106   "Compile vterm-module."
    107   (interactive)
    108   (when (vterm-module--cmake-is-available)
    109     (let* ((vterm-directory
    110             (shell-quote-argument
    111              ;; NOTE: This is a workaround to fix an issue with how the Emacs
    112              ;; feature/native-comp branch changes the result of
    113              ;; `(locate-library "vterm")'. See emacs-devel thread
    114              ;; https://lists.gnu.org/archive/html/emacs-devel/2020-07/msg00306.html
    115              ;; for a discussion.
    116              (file-name-directory (locate-library "vterm.el" t))))
    117            (make-commands
    118             (concat
    119              "cd " vterm-directory "; \
    120              mkdir -p build; \
    121              cd build; \
    122              cmake -G 'Unix Makefiles' "
    123              vterm-module-cmake-args
    124              " ..; \
    125              make; \
    126              cd -"))
    127            (buffer (get-buffer-create vterm-install-buffer-name)))
    128       (pop-to-buffer buffer)
    129       (compilation-mode)
    130       (if (zerop (let ((inhibit-read-only t))
    131                    (call-process "sh" nil buffer t "-c" make-commands)))
    132           (message "Compilation of `emacs-libvterm' module succeeded")
    133         (error "Compilation of `emacs-libvterm' module failed!")))))
    134 
    135 ;; If the vterm-module is not compiled yet, compile it
    136 (unless (require 'vterm-module nil t)
    137   (if (or vterm-always-compile-module
    138           (y-or-n-p "Vterm needs `vterm-module' to work.  Compile it now? "))
    139       (progn
    140         (vterm-module-compile)
    141         (require 'vterm-module))
    142     (error "Vterm will not work until `vterm-module' is compiled!")))
    143 
    144 ;;; Dependencies
    145 
    146 ;; Generate this list with:
    147 ;; awk -F\" '/bind_function*/ {print "(declare-function", $2, "\"vterm-module\")"}' vterm-module.c
    148 (declare-function vterm--new "vterm-module")
    149 (declare-function vterm--update "vterm-module")
    150 (declare-function vterm--redraw "vterm-module")
    151 (declare-function vterm--write-input "vterm-module")
    152 (declare-function vterm--set-size "vterm-module")
    153 (declare-function vterm--set-pty-name "vterm-module")
    154 (declare-function vterm--get-pwd-raw "vterm-module")
    155 (declare-function vterm--reset-point "vterm-module")
    156 (declare-function vterm--get-icrnl "vterm-module")
    157 
    158 (require 'subr-x)
    159 (require 'find-func)
    160 (require 'cl-lib)
    161 (require 'term)
    162 (require 'color)
    163 (require 'compile)
    164 (require 'face-remap)
    165 (require 'tramp)
    166 (require 'bookmark)
    167 
    168 ;;; Options
    169 
    170 (defcustom vterm-shell shell-file-name
    171   "The shell that gets run in the vterm."
    172   :type 'string
    173   :group 'vterm)
    174 
    175 (defcustom vterm-tramp-shells '(("docker" "/bin/sh"))
    176   "The shell that gets run in the vterm for tramp.
    177 
    178 `vterm-tramp-shells' has to be a list of pairs of the format:
    179 \(TRAMP-METHOD SHELL)"
    180   :type '(alist :key-type string :value-type string)
    181   :group 'vterm)
    182 
    183 (defcustom vterm-buffer-name "*vterm*"
    184   "The basename used for vterm buffers.
    185 This is the default name used when running `vterm' or
    186 `vterm-other-window'.
    187 
    188 With a numeric prefix argument to `vterm', the buffer name will
    189 be the value of this variable followed by the number.  For
    190 example, with the numeric prefix argument 2, the buffer would be
    191 named \"*vterm*<2>\"."
    192   :type 'string
    193   :group 'vterm)
    194 
    195 (defcustom vterm-max-scrollback 1000
    196   "Maximum \\='scrollback\\=' value.
    197 
    198 The maximum allowed is 100000.  This value can modified by
    199 changing the SB_MAX variable in vterm-module.h and recompiling
    200 the module."
    201   :type 'number
    202   :group 'vterm)
    203 
    204 (defcustom vterm-min-window-width 80
    205   "Minimum window width."
    206   :type 'number
    207   :group 'vterm)
    208 
    209 (defcustom vterm-kill-buffer-on-exit t
    210   "If not nil vterm buffers are killed when the attached process is terminated.
    211 
    212 If `vterm-kill-buffer-on-exit' is set to t, when the process
    213 associated to a vterm buffer quits, the buffer is killed.  When
    214 nil, the buffer will still be available as if it were in
    215 `fundamental-mode'."
    216   :type  'boolean
    217   :group 'vterm)
    218 
    219 (define-obsolete-variable-alias 'vterm-clear-scrollback
    220   'vterm-clear-scrollback-when-clearing "0.0.1")
    221 
    222 (define-obsolete-variable-alias 'vterm-use-vterm-prompt
    223   'vterm-use-vterm-prompt-detection-method "0.0.1")
    224 
    225 (defcustom vterm-clear-scrollback-when-clearing nil
    226   "If not nil `vterm-clear' clears both screen and scrollback.
    227 
    228 The scrollback is everything that is not current visible on
    229 screen in vterm buffers.
    230 
    231 If `vterm-clear-scrollback-when-clearing' is nil, `vterm-clear'
    232 clears only the screen, so the scrollback is accessible moving
    233 the point up."
    234   :type 'boolean
    235   :group 'vterm)
    236 
    237 (defcustom vterm-keymap-exceptions
    238   '("C-c" "C-x" "C-u" "C-g" "C-h" "C-l" "M-x" "M-o" "C-y" "M-y")
    239   "Exceptions for `vterm-keymap'.
    240 
    241 If you use a keybinding with a prefix-key, add that prefix-key to
    242 this list.  Note that after doing so that prefix-key cannot be sent
    243 to the terminal anymore.
    244 
    245 The mapping is done by the macro `vterm-define-key', and the
    246 function `vterm--exclude-keys' removes the keybindings defined in
    247 `vterm-keymap-exceptions'."
    248   :type '(repeat string)
    249   :set (lambda (sym val)
    250          (set sym val)
    251          (when (and (fboundp 'vterm--exclude-keys)
    252                     (boundp 'vterm-mode-map))
    253            (vterm--exclude-keys vterm-mode-map val)))
    254   :group 'vterm)
    255 
    256 (defcustom vterm-exit-functions nil
    257   "List of functions called when a vterm process exits.
    258 
    259 Each function is called with two arguments: the vterm buffer of
    260 the process if any, and a string describing the event passed from
    261 the sentinel.
    262 
    263 This hook applies only to new vterms, created after setting this
    264 value with `add-hook'.
    265 
    266 Note that this hook will not work if another package like
    267 `shell-pop' sets its own sentinel to the `vterm' process."
    268   :type 'hook
    269   :group 'vterm)
    270 
    271 (make-obsolete-variable 'vterm-set-title-functions
    272                         "This variable was substituted by `vterm-buffer-name-string'."
    273                         "0.0.1")
    274 
    275 (defcustom vterm-buffer-name-string nil
    276   "Format string for the title of vterm buffers.
    277 
    278 If `vterm-buffer-name-string' is nil, vterm will not set the
    279 title of its buffers.  If not nil, `vterm-buffer-name-string' has
    280 to be a format control string (see `format') containing one
    281 instance of %s which will be substituted with the string TITLE.
    282 The argument TITLE is provided by the shell.  This requires shell
    283 side configuration.
    284 
    285 For example, if `vterm-buffer-name-string' is set to \"vterm %s\",
    286 and the shell properly configured to set TITLE=$(pwd), than vterm
    287 buffers will be named \"vterm\" followed by the current path.
    288 
    289 See URL http://tldp.org/HOWTO/Xterm-Title-4.html for additional
    290 information on the how to configure the shell."
    291   :type 'string
    292   :group 'vterm)
    293 
    294 (defcustom vterm-term-environment-variable "xterm-256color"
    295   "TERM value for terminal."
    296   :type 'string
    297   :group 'vterm)
    298 
    299 (defcustom vterm-environment nil
    300   "List of extra environment variables to the vterm shell processes only.
    301 
    302 demo: \\='(\"env1=v1\" \"env2=v2\")"
    303   :type '(repeat string)
    304   :group 'vterm)
    305 
    306 
    307 (defcustom vterm-enable-manipulate-selection-data-by-osc52 nil
    308   "Support OSC 52 MANIPULATE SELECTION DATA(libvterm 0.2 is needed).
    309 
    310 Support copy text to Emacs kill ring and system clipboard by using OSC 52.
    311 For example: send base64 encoded \\='foo\\=' to kill ring: echo -en \\='\\e]52;c;Zm9v\\a\\=',
    312 tmux can share its copy buffer to terminals by supporting osc52(like iterm2
    313  xterm) you can enable this feature for tmux by :
    314 set -g set-clipboard on         #osc 52 copy paste share with iterm
    315 set -ga terminal-overrides \\=',xterm*:XT:Ms=\\E]52;%p1%s;%p2%s\\007\\='
    316 set -ga terminal-overrides \\=',screen*:XT:Ms=\\E]52;%p1%s;%p2%s\\007\\='
    317 
    318 The clipboard querying/clearing functionality offered by OSC 52 is not
    319 implemented here,And for security reason, this feature is disabled
    320 by default."
    321   :type 'boolean
    322   :group 'vterm)
    323 
    324 ;; TODO: Improve doc string, it should not point to the readme but it should
    325 ;;       be self-contained.
    326 (defcustom vterm-eval-cmds '(("find-file" find-file)
    327                              ("message" message)
    328                              ("vterm-clear-scrollback" vterm-clear-scrollback))
    329   "Whitelisted Emacs functions that can be executed from vterm.
    330 
    331 You can execute Emacs functions directly from vterm buffers.  To do this,
    332 you have to escape the name of the function and its arguments with \e]51;E.
    333 
    334 See Message passing in README.
    335 
    336 The function you want to execute has to be in `vterm-eval-cmds'.
    337 
    338 `vterm-eval-cmds' has to be a list of pairs of the format:
    339 \(NAME-OF-COMMAND-IN-SHELL EMACS-FUNCTION)
    340 
    341 The need for an explicit map is to avoid arbitrary code execution."
    342   :type '(alist :key-type string)
    343   :group 'vterm)
    344 
    345 (defcustom vterm-disable-underline nil
    346   "When not-nil, underline text properties are ignored.
    347 
    348 This means that vterm will render underlined text as if it was not
    349 underlined."
    350   :type  'boolean
    351   :group 'vterm)
    352 
    353 (defcustom vterm-disable-inverse-video nil
    354   "When not-nil, inverse video text properties are ignored.
    355 
    356 This means that vterm will render reversed video text as if it was not
    357 such."
    358   :type  'boolean
    359   :group 'vterm)
    360 
    361 (define-obsolete-variable-alias 'vterm-disable-bold-font
    362   'vterm-disable-bold "0.0.1")
    363 
    364 (defcustom vterm-disable-bold-font nil
    365   "When not-nil, bold text properties are ignored.
    366 
    367 This means that vterm will render bold with the default face weight."
    368   :type  'boolean
    369   :group 'vterm)
    370 
    371 (defcustom vterm-set-bold-hightbright nil
    372   "When not-nil, using hightbright colors for bolded text, see #549."
    373   :type  'boolean
    374   :group 'vterm)
    375 
    376 (defcustom vterm-ignore-blink-cursor t
    377   "When t, vterm will ignore request from application to turn on/off cursor blink.
    378 
    379 If nil, cursor in any window may begin to blink or not blink because
    380 `blink-cursor-mode`is a global minor mode in Emacs,
    381 you can use `M-x blink-cursor-mode` to toggle."
    382   :type 'boolean
    383   :group 'vterm)
    384 
    385 (defcustom vterm-copy-exclude-prompt t
    386   "When not-nil, the prompt is not included by `vterm-copy-mode-done'."
    387   :type 'boolean
    388   :group 'vterm)
    389 
    390 (defcustom vterm-use-vterm-prompt-detection-method t
    391   "When not-nil, the prompt is detected through the shell.
    392 
    393 Vterm needs to know where the shell prompt is to enable all the
    394 available features.  There are two supported ways to do this.
    395 First, the shell can inform vterm on the location of the prompt.
    396 This requires shell-side configuration: the escape code 51;A is
    397 used to set the current directory and prompt location.  This
    398 detection method is the most-reliable.  To use it, you have
    399 to change your shell prompt to print 51;A.
    400 
    401 The second method is using a regular expression. This method does
    402 not require any shell-side configuration. See
    403 `term-prompt-regexp', for more information."
    404   :type 'boolean
    405   :group 'vterm)
    406 
    407 (defcustom vterm-bookmark-check-dir t
    408   "When set to non-nil, also restore directory when restoring a vterm bookmark."
    409   :type 'boolean
    410   :group 'vterm)
    411 
    412 (defcustom vterm-copy-mode-remove-fake-newlines nil
    413   "When not-nil fake newlines are removed on entering copy mode.
    414 
    415 vterm inserts \\='fake\\=' newlines purely for rendering. When using
    416 vterm-copy-mode these are in conflict with many emacs functions
    417 like isearch-forward. if this varialbe is not-nil the
    418 fake-newlines are removed on entering copy-mode and re-inserted
    419 on leaving copy mode. Also truncate-lines is set to t on entering
    420 copy-mode and set to nil on leaving."
    421   :type 'boolean
    422   :group 'vterm)
    423 
    424 ;;; Faces
    425 
    426 (defface vterm-color-black
    427   `((t :inherit term-color-black))
    428   "Face used to render black color code.
    429 The foreground color is used as ANSI color 0 and the background
    430 color is used as ANSI color 8."
    431   :group 'vterm)
    432 
    433 (defface vterm-color-red
    434   `((t :inherit term-color-red))
    435   "Face used to render red color code.
    436 The foreground color is used as ANSI color 1 and the background
    437 color is used as ANSI color 9."
    438   :group 'vterm)
    439 
    440 (defface vterm-color-green
    441   `((t :inherit term-color-green))
    442   "Face used to render green color code.
    443 The foreground color is used as ANSI color 2 and the background
    444 color is used as ANSI color 10."
    445   :group 'vterm)
    446 
    447 (defface vterm-color-yellow
    448   `((t :inherit term-color-yellow))
    449   "Face used to render yellow color code.
    450 The foreground color is used as ANSI color 3 and the background
    451 color is used as ANSI color 11."
    452   :group 'vterm)
    453 
    454 (defface vterm-color-blue
    455   `((t :inherit term-color-blue))
    456   "Face used to render blue color code.
    457 The foreground color is used as ANSI color 4 and the background
    458 color is used as ANSI color 12."
    459   :group 'vterm)
    460 
    461 (defface vterm-color-magenta
    462   `((t :inherit term-color-magenta))
    463   "Face used to render magenta color code.
    464 The foreground color is used as ansi color 5 and the background
    465 color is used as ansi color 13."
    466   :group 'vterm)
    467 
    468 (defface vterm-color-cyan
    469   `((t :inherit term-color-cyan))
    470   "Face used to render cyan color code.
    471 The foreground color is used as ansi color 6 and the background
    472 color is used as ansi color 14."
    473   :group 'vterm)
    474 
    475 (defface vterm-color-white
    476   `((t :inherit term-color-white))
    477   "Face used to render white color code.
    478 The foreground color is used as ansi color 7 and the background
    479 color is used as ansi color 15."
    480   :group 'vterm)
    481 
    482 (defface vterm-color-underline
    483   `((t :inherit default))
    484   "Face used to render cells with underline attribute.
    485 Only foreground is used."
    486   :group 'vterm)
    487 
    488 (defface vterm-color-inverse-video
    489   `((t :inherit default))
    490   "Face used to render cells with inverse video attribute.
    491 Only background is used."
    492   :group 'vterm)
    493 
    494 ;;; Variables
    495 
    496 (defvar vterm-color-palette
    497   [vterm-color-black
    498    vterm-color-red
    499    vterm-color-green
    500    vterm-color-yellow
    501    vterm-color-blue
    502    vterm-color-magenta
    503    vterm-color-cyan
    504    vterm-color-white]
    505   "Color palette for the foreground and background.")
    506 
    507 (defvar-local vterm--term nil
    508   "Pointer to Term.")
    509 
    510 (defvar-local vterm--process nil
    511   "Shell process of current term.")
    512 
    513 (defvar-local vterm--redraw-timer nil)
    514 (defvar-local vterm--redraw-immididately nil)
    515 (defvar-local vterm--linenum-remapping nil)
    516 (defvar-local vterm--prompt-tracking-enabled-p nil)
    517 (defvar-local vterm--insert-function (symbol-function #'insert))
    518 (defvar-local vterm--delete-char-function (symbol-function #'delete-char))
    519 (defvar-local vterm--delete-region-function (symbol-function #'delete-region))
    520 (defvar-local vterm--undecoded-bytes nil)
    521 (defvar-local vterm--copy-mode-fake-newlines nil)
    522 
    523 
    524 (defvar vterm-timer-delay 0.1
    525   "Delay for refreshing the buffer after receiving updates from libvterm.
    526 
    527 A larger delary improves performance when receiving large bursts
    528 of data.  If nil, never delay.  The units are seconds.")
    529 
    530 ;;; Keybindings
    531 
    532 ;; We have many functions defined by vterm-define-key.  Later, we will bind some
    533 ;; of the functions.  If the following is not evaluated during compilation, the compiler
    534 ;; will complain that some functions are not defined (eg, vterm-send-C-c)
    535 (eval-and-compile
    536   (defmacro vterm-define-key (key)
    537     "Define a command that sends KEY with modifiers C and M to vterm."
    538     (declare (indent defun)
    539              (doc-string 3))
    540     `(progn (defun ,(intern (format "vterm-send-%s" key))()
    541               ,(format "Sends %s to the libvterm."  key)
    542               (interactive)
    543               (vterm-send-key ,(char-to-string (get-byte (1- (length key)) key))
    544                               ,(let ((case-fold-search nil))
    545                                  (or (string-match-p "[A-Z]$" key)
    546                                      (string-match-p "S-" key)))
    547                               ,(string-match-p "M-" key)
    548                               ,(string-match-p "C-" key)))
    549             (make-obsolete ',(intern (format "vterm-send-%s" key))
    550                            "use `vterm--self-insert' or `vterm-send' or `vterm-send-key'."
    551                            "v0.1")))
    552   (make-obsolete 'vterm-define-key "" "v0.1")
    553   (mapc (lambda (key)
    554           (eval `(vterm-define-key ,key)))
    555         (cl-loop for prefix in '("M-")
    556                  append (cl-loop for char from ?A to ?Z
    557                                  for key = (format "%s%c" prefix char)
    558                                  collect key)))
    559   (mapc (lambda (key)
    560           (eval `(vterm-define-key ,key)))
    561         (cl-loop for prefix in '("C-" "M-" "C-S-")
    562                  append (cl-loop for char from ?a to ?z
    563                                  for key = (format "%s%c" prefix char)
    564                                  collect key))))
    565 
    566 ;; Function keys and most of C- and M- bindings
    567 (defun vterm--exclude-keys (map exceptions)
    568   "Remove EXCEPTIONS from the keys bound by `vterm-define-keys'.
    569 
    570 Exceptions are defined by `vterm-keymap-exceptions'."
    571   (mapc (lambda (key)
    572           (define-key map (kbd key) nil))
    573         exceptions)
    574   (mapc (lambda (key)
    575           (define-key map (kbd key) #'vterm--self-insert))
    576         (cl-loop for number from 1 to 12
    577                  for key = (format "<f%i>" number)
    578                  unless (member key exceptions)
    579                  collect key))
    580   (let ((esc-map (lookup-key map "\e"))
    581         (i 0)
    582         key)
    583     (unless esc-map (setq esc-map (make-keymap)))
    584     (while (< i 128)
    585       (setq key (make-string 1 i))
    586       (unless (member (key-description key) exceptions)
    587         (define-key map key 'vterm--self-insert))
    588       ;; Avoid O and [. They are used in escape sequences for various keys.
    589       (unless (or (eq i ?O) (eq i 91))
    590         (unless (member (key-description key "\e") exceptions)
    591           (define-key esc-map key 'vterm--self-insert-meta)))
    592       (setq i (1+ i)))
    593     (define-key map "\e" esc-map)))
    594 
    595 (defun vterm-xterm-paste (event)
    596   "Handle xterm paste EVENT in vterm."
    597   (interactive "e")
    598   (with-temp-buffer
    599     (xterm-paste event)
    600     (kill-new (buffer-string)))
    601   (vterm-yank))
    602 
    603 (defvar vterm-mode-map
    604   (let ((map (make-sparse-keymap)))
    605     (vterm--exclude-keys map vterm-keymap-exceptions)
    606     (define-key map (kbd "C-]")                 #'vterm--self-insert)
    607     (define-key map (kbd "M-<")                 #'vterm--self-insert)
    608     (define-key map (kbd "M->")                 #'vterm--self-insert)
    609     (define-key map [tab]                       #'vterm-send-tab)
    610     (define-key map (kbd "TAB")                 #'vterm-send-tab)
    611     (define-key map [backtab]                   #'vterm--self-insert)
    612     (define-key map [backspace]                 #'vterm-send-backspace)
    613     (define-key map (kbd "DEL")                 #'vterm-send-backspace)
    614     (define-key map [delete]                    #'vterm-send-delete)
    615     (define-key map [M-backspace]               #'vterm-send-meta-backspace)
    616     (define-key map (kbd "M-DEL")               #'vterm-send-meta-backspace)
    617     (define-key map [C-backspace]               #'vterm-send-meta-backspace)
    618     (define-key map [return]                    #'vterm-send-return)
    619     (define-key map (kbd "RET")                 #'vterm-send-return)
    620     (define-key map [C-left]                    #'vterm--self-insert)
    621     (define-key map [M-left]                    #'vterm--self-insert)
    622     (define-key map [C-right]                   #'vterm--self-insert)
    623     (define-key map [M-right]                   #'vterm--self-insert)
    624     (define-key map [C-up]                      #'vterm--self-insert)
    625     (define-key map [C-down]                    #'vterm--self-insert)
    626     (define-key map [M-up]                      #'vterm--self-insert)
    627     (define-key map [M-down]                    #'vterm--self-insert)
    628     (define-key map [left]                      #'vterm--self-insert)
    629     (define-key map [right]                     #'vterm--self-insert)
    630     (define-key map [up]                        #'vterm--self-insert)
    631     (define-key map [down]                      #'vterm--self-insert)
    632     (define-key map [prior]                     #'vterm--self-insert)
    633     (define-key map [S-prior]                   #'scroll-down-command)
    634     (define-key map [next]                      #'vterm--self-insert)
    635     (define-key map [S-next]                    #'scroll-up-command)
    636     (define-key map [home]                      #'vterm--self-insert)
    637     (define-key map [end]                       #'vterm--self-insert)
    638     (define-key map [C-home]                    #'vterm--self-insert)
    639     (define-key map [C-end]                     #'vterm--self-insert)
    640     (define-key map [escape]                    #'vterm--self-insert)
    641     (define-key map [remap yank]                #'vterm-yank)
    642     (define-key map [remap xterm-paste]         #'vterm-xterm-paste)
    643     (define-key map [remap yank-pop]            #'vterm-yank-pop)
    644     (define-key map [remap mouse-yank-primary]  #'vterm-yank-primary)
    645     (define-key map [mouse-1]                   #'vterm-mouse-set-point)
    646     (define-key map (kbd "C-SPC")               #'vterm--self-insert)
    647     (define-key map (kbd "S-SPC")               #'vterm-send-space)
    648     (define-key map (kbd "C-_")                 #'vterm--self-insert)
    649     (define-key map [remap undo]                #'vterm-undo)
    650     (define-key map (kbd "M-.")                 #'vterm--self-insert)
    651     (define-key map (kbd "M-,")                 #'vterm--self-insert)
    652     (define-key map (kbd "C-c C-y")             #'vterm--self-insert)
    653     (define-key map (kbd "C-c C-c")             #'vterm--self-insert)
    654     (define-key map (kbd "C-c C-l")             #'vterm-clear-scrollback)
    655     (define-key map (kbd "C-l")                 #'vterm-clear)
    656     (define-key map (kbd "C-\\")                #'vterm--self-insert)
    657     (define-key map (kbd "C-c C-g")             #'vterm--self-insert)
    658     (define-key map (kbd "C-c C-u")             #'vterm--self-insert)
    659     (define-key map [remap self-insert-command] #'vterm--self-insert)
    660     (define-key map (kbd "C-c C-r")             #'vterm-reset-cursor-point)
    661     (define-key map (kbd "C-c C-n")             #'vterm-next-prompt)
    662     (define-key map (kbd "C-c C-p")             #'vterm-previous-prompt)
    663     (define-key map (kbd "C-c C-t")             #'vterm-copy-mode)
    664     map))
    665 
    666 (defvar vterm-copy-mode-map
    667   (let ((map (make-sparse-keymap)))
    668     (define-key map (kbd "C-c C-t")        #'vterm-copy-mode)
    669     (define-key map [return]               #'vterm-copy-mode-done)
    670     (define-key map (kbd "RET")            #'vterm-copy-mode-done)
    671     (define-key map (kbd "C-c C-r")        #'vterm-reset-cursor-point)
    672     (define-key map (kbd "C-a")            #'vterm-beginning-of-line)
    673     (define-key map (kbd "C-e")            #'vterm-end-of-line)
    674     (define-key map (kbd "C-c C-n")        #'vterm-next-prompt)
    675     (define-key map (kbd "C-c C-p")        #'vterm-previous-prompt)
    676     map))
    677 
    678 
    679 ;;; Mode
    680 
    681 (define-derived-mode vterm-mode fundamental-mode "VTerm"
    682   "Major mode for vterm buffer."
    683   (buffer-disable-undo)
    684   (and (boundp 'display-line-numbers)
    685        (let ((font-height (expt text-scale-mode-step text-scale-mode-amount)))
    686          (setq vterm--linenum-remapping
    687                (face-remap-add-relative 'line-number :height font-height))))
    688   (hack-dir-local-variables)
    689   (let ((vterm-env (assq 'vterm-environment dir-local-variables-alist)))
    690     (when vterm-env
    691       (make-local-variable 'vterm-environment)
    692       (setq vterm-environment (cdr vterm-env))))
    693   (let ((process-environment (append vterm-environment
    694                                      `(,(concat "TERM="
    695                                                 vterm-term-environment-variable)
    696                                        ,(concat "EMACS_VTERM_PATH="
    697                                                 (file-name-directory (find-library-name "vterm")))
    698                                        "INSIDE_EMACS=vterm"
    699                                        "LINES"
    700                                        "COLUMNS")
    701                                      process-environment))
    702         ;; TODO: Figure out why inhibit is needed for curses to render correctly.
    703         (inhibit-eol-conversion nil)
    704         (coding-system-for-read 'binary)
    705         (process-adaptive-read-buffering nil)
    706         (width (max (- (window-body-width) (vterm--get-margin-width))
    707                     vterm-min-window-width)))
    708     (setq vterm--term (vterm--new (window-body-height)
    709                                   width vterm-max-scrollback
    710                                   vterm-disable-bold-font
    711                                   vterm-disable-underline
    712                                   vterm-disable-inverse-video
    713                                   vterm-ignore-blink-cursor
    714                                   vterm-set-bold-hightbright))
    715     (setq buffer-read-only t)
    716     (setq-local scroll-conservatively 101)
    717     (setq-local scroll-margin 0)
    718     (setq-local hscroll-margin 0)
    719     (setq-local hscroll-step 1)
    720     (setq-local truncate-lines t)
    721 
    722 
    723     ;; Disable all automatic fontification
    724     (setq-local font-lock-defaults '(nil t))
    725 
    726     (add-function :filter-return
    727                   (local 'filter-buffer-substring-function)
    728                   #'vterm--filter-buffer-substring)
    729     (setq vterm--process
    730           (make-process
    731            :name "vterm"
    732            :buffer (current-buffer)
    733            :command
    734            `("/bin/sh" "-c"
    735              ,(format
    736                "stty -nl sane %s erase ^? rows %d columns %d >/dev/null && exec %s"
    737                ;; Some stty implementations (i.e. that of *BSD) do not
    738                ;; support the iutf8 option.  to handle that, we run some
    739                ;; heuristics to work out if the system supports that
    740                ;; option and set the arg string accordingly. This is a
    741                ;; gross hack but FreeBSD doesn't seem to want to fix it.
    742                ;;
    743                ;; See: https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=220009
    744                (if (eq system-type 'berkeley-unix) "" "iutf8")
    745                (window-body-height)
    746                width (vterm--get-shell)))
    747            ;; :coding 'no-conversion
    748            :connection-type 'pty
    749            :file-handler t
    750            :filter #'vterm--filter
    751            ;; The sentinel is needed if there are exit functions or if
    752            ;; vterm-kill-buffer-on-exit is set to t.  In this latter case,
    753            ;; vterm--sentinel will kill the buffer
    754            :sentinel (when (or vterm-exit-functions
    755                                vterm-kill-buffer-on-exit)
    756                        #'vterm--sentinel))))
    757 
    758   ;; Change major-mode is not allowed
    759   ;; Vterm interfaces with an underlying process. Changing the major
    760   ;; mode can break this, leading to segmentation faults.
    761   (add-hook 'change-major-mode-hook
    762             (lambda () (interactive)
    763               (user-error "You cannot change major mode in vterm buffers")) nil t)
    764 
    765   (vterm--set-pty-name vterm--term (process-tty-name vterm--process))
    766   (process-put vterm--process 'adjust-window-size-function
    767                #'vterm--window-adjust-process-window-size)
    768   ;; Support to compilation-shell-minor-mode
    769   ;; Is this necessary? See vterm--compilation-setup
    770   (setq next-error-function 'vterm-next-error-function)
    771   (setq-local bookmark-make-record-function 'vterm--bookmark-make-record))
    772 
    773 (defun vterm--get-shell ()
    774   "Get the shell that gets run in the vterm."
    775   (if (ignore-errors (file-remote-p default-directory))
    776       (with-parsed-tramp-file-name default-directory nil
    777         (or (cadr (assoc method vterm-tramp-shells))
    778             (with-connection-local-variables shell-file-name)
    779             vterm-shell))
    780     vterm-shell))
    781 
    782 (defun vterm--bookmark-make-record ()
    783   "Create a vterm bookmark.
    784 
    785 Notes down the current directory and buffer name."
    786   `(nil
    787     (handler . vterm--bookmark-handler)
    788     (thisdir . ,default-directory)
    789     (buf-name . ,(buffer-name))
    790     (defaults . nil)))
    791 
    792 
    793 ;;;###autoload
    794 (defun vterm--bookmark-handler (bmk)
    795   "Handler to restore a vterm bookmark BMK.
    796 
    797 If a vterm buffer of the same name does not exist, the function will create a
    798 new vterm buffer of the name. It also checks the current directory and sets
    799 it to the bookmarked directory if needed."
    800   (let* ((thisdir (bookmark-prop-get bmk 'thisdir))
    801          (buf-name (bookmark-prop-get bmk 'buf-name))
    802          (buf (get-buffer buf-name))
    803          (thismode (and buf (with-current-buffer buf major-mode))))
    804     ;; create if no such vterm buffer exists
    805     (when (or (not buf) (not (eq thismode 'vterm-mode)))
    806       (setq buf (generate-new-buffer buf-name))
    807       (with-current-buffer buf
    808         (when vterm-bookmark-check-dir
    809           (setq default-directory thisdir))
    810         (vterm-mode)))
    811     ;; check the current directory
    812     (with-current-buffer buf
    813       (when (and vterm-bookmark-check-dir
    814                  (not (string-equal default-directory thisdir)))
    815         (when vterm-copy-mode
    816           (vterm-copy-mode-done nil))
    817         (vterm-insert (concat "cd " thisdir))
    818         (vterm-send-return)))
    819     ;; set to this vterm buf
    820     (set-buffer buf)))
    821 
    822 (defun vterm--compilation-setup ()
    823   "Function to enable the option `compilation-shell-minor-mode' for vterm.
    824 `'compilation-shell-minor-mode' would change the value of local
    825 variable `next-error-function', so we should call this function in
    826 `compilation-shell-minor-mode-hook'."
    827   (when (eq major-mode 'vterm-mode)
    828     (setq next-error-function 'vterm-next-error-function)))
    829 
    830 (add-hook 'compilation-shell-minor-mode-hook #'vterm--compilation-setup)
    831 
    832 ;;;###autoload
    833 (defun vterm-next-error-function (n &optional reset)
    834   "Advance to the next error message and visit the file where the error was.
    835 This is the value of `next-error-function' in Compilation
    836 buffers.  Prefix arg N says how many error messages to move
    837 forwards (or backwards, if negative).
    838 
    839 Optional argument RESET clears all the errors."
    840   (interactive "p")
    841   (let* ((pt (point))
    842          (default-directory default-directory)
    843          (pwd (vterm--get-pwd)))
    844     (when pwd
    845       (setq default-directory pwd))
    846     (goto-char pt)
    847     (compilation-next-error-function n reset)))
    848 
    849 ;;; Copy Mode
    850 
    851 (defun vterm--enter-copy-mode ()
    852   (use-local-map nil)
    853   (vterm-send-stop)
    854   (when vterm-copy-mode-remove-fake-newlines
    855     (save-excursion
    856       (setq truncate-lines nil)
    857       (vterm--remove-fake-newlines t))))
    858 
    859 
    860 (defun vterm--exit-copy-mode ()
    861   (when vterm-copy-mode-remove-fake-newlines
    862     (save-excursion
    863       (setq truncate-lines t)
    864       (vterm--reinsert-fake-newlines)))
    865   (vterm-reset-cursor-point)
    866   (use-local-map vterm-mode-map)
    867   (vterm-send-start))
    868 
    869 (define-minor-mode vterm-copy-mode
    870   "Toggle `vterm-copy-mode'.
    871 
    872 When `vterm-copy-mode' is enabled, the terminal will not display
    873 additional output received from the underlying process and will
    874 behave similarly to buffer in `fundamental-mode'.  This mode is
    875 typically used to copy text from vterm buffers.
    876 
    877 A conventient way to exit `vterm-copy-mode' is with
    878 `vterm-copy-mode-done', which copies the selected text and exit
    879 `vterm-copy-mode'."
    880   :group 'vterm
    881   :lighter " VTermCopy"
    882   :keymap vterm-copy-mode-map
    883   (if (equal major-mode 'vterm-mode)
    884       (if vterm-copy-mode
    885           (vterm--enter-copy-mode)
    886         (vterm--exit-copy-mode))
    887     (user-error "You cannot enable vterm-copy-mode outside vterm buffers")))
    888 
    889 (defun vterm-copy-mode-done (arg)
    890   "Save the active region or line to the kill ring and exit `vterm-copy-mode'.
    891 
    892 If a region is defined then that region is killed, with no region then
    893 current line is killed from start to end.
    894 
    895 The option `vterm-copy-exclude-prompt' controls if the prompt
    896 should be included in a line copy.  Using the universal prefix ARG
    897 will invert `vterm-copy-exclude-prompt' for that call."
    898   (interactive "P")
    899   (unless vterm-copy-mode
    900     (user-error "This command is effective only in vterm-copy-mode"))
    901   (unless (use-region-p)
    902     (goto-char (vterm--get-beginning-of-line))
    903     ;; Are we excluding the prompt?
    904     (if (or (and vterm-copy-exclude-prompt (not arg))
    905             (and (not vterm-copy-exclude-prompt) arg))
    906         (goto-char (max (or (vterm--get-prompt-point) 0)
    907                         (vterm--get-beginning-of-line))))
    908     (set-mark (point))
    909     (goto-char (vterm--get-end-of-line)))
    910   (kill-ring-save (region-beginning) (region-end))
    911   (vterm-copy-mode -1))
    912 
    913 ;;; Commands
    914 
    915 (defun vterm--self-insert-meta ()
    916   (interactive)
    917   (when vterm--term
    918     (dolist (key (vterm--translate-event-to-args
    919                   last-command-event :meta))
    920       (apply #'vterm-send-key key))))
    921 
    922 (defun vterm--self-insert ()
    923   "Send invoking key to libvterm."
    924   (interactive)
    925   (when vterm--term
    926     (dolist (key (vterm--translate-event-to-args
    927                   last-command-event))
    928       (apply #'vterm-send-key key))))
    929 
    930 (defun vterm-send-key (key &optional shift meta ctrl accept-proc-output)
    931   "Send KEY to libvterm with optional modifiers SHIFT, META and CTRL."
    932   (deactivate-mark)
    933   (when vterm--term
    934     (let ((inhibit-redisplay t)
    935           (inhibit-read-only t))
    936       (vterm--update vterm--term key shift meta ctrl)
    937       (setq vterm--redraw-immididately t)
    938       (when accept-proc-output
    939         (accept-process-output vterm--process vterm-timer-delay nil t)))))
    940 
    941 (defun vterm-send (key)
    942   "Send KEY to libvterm.  KEY can be anything `kbd' understands."
    943   (dolist (key (vterm--translate-event-to-args
    944                 (listify-key-sequence (kbd key))))
    945     (apply #'vterm-send-key key)))
    946 
    947 (defun vterm-send-next-key ()
    948   "Read next input event and send it to the libvterm.
    949 
    950 With this you can directly send modified keys to applications
    951 running in the terminal (like Emacs or Nano)."
    952   (interactive)
    953   (dolist (key (vterm--translate-event-to-args
    954                 (read-event)))
    955     (apply #'vterm-send-key key)))
    956 
    957 (defun vterm-send-start ()
    958   "Output from the system is started when the system receives START."
    959   (interactive)
    960   (vterm-send-key "<start>"))
    961 
    962 (defun vterm-send-stop ()
    963   "Output from the system is stopped when the system receives STOP."
    964   (interactive)
    965   (vterm-send-key "<stop>"))
    966 
    967 (defun vterm-send-return ()
    968   "Send `C-m' to the libvterm."
    969   (interactive)
    970   (deactivate-mark)
    971   (when vterm--term
    972     (if (vterm--get-icrnl vterm--term)
    973         (process-send-string vterm--process "\C-j")
    974       (process-send-string vterm--process "\C-m"))))
    975 
    976 (defun vterm-send-tab ()
    977   "Send `<tab>' to the libvterm."
    978   (interactive)
    979   (vterm-send-key "<tab>"))
    980 
    981 (defun vterm-send-space ()
    982   "Send `<space>' to the libvterm."
    983   (interactive)
    984   (vterm-send-key " "))
    985 
    986 (defun vterm-send-backspace ()
    987   "Send `<backspace>' to the libvterm."
    988   (interactive)
    989   (vterm-send-key "<backspace>"))
    990 
    991 (defun vterm-send-delete ()
    992   "Send `<delete>' to the libvterm."
    993   (interactive)
    994   (vterm-send-key "<delete>"))
    995 
    996 (defun vterm-send-meta-backspace ()
    997   "Send `M-<backspace>' to the libvterm."
    998   (interactive)
    999   (vterm-send-key "<backspace>" nil t))
   1000 
   1001 (defun vterm-send-up ()
   1002   "Send `<up>' to the libvterm."
   1003   (interactive)
   1004   (vterm-send-key "<up>"))
   1005 (make-obsolete 'vterm-send-up 'vterm--self-insert "v0.1")
   1006 
   1007 (defun vterm-send-down ()
   1008   "Send `<down>' to the libvterm."
   1009   (interactive)
   1010   (vterm-send-key "<down>"))
   1011 (make-obsolete 'vterm-send-down 'vterm--self-insert "v0.1")
   1012 
   1013 (defun vterm-send-left ()
   1014   "Send `<left>' to the libvterm."
   1015   (interactive)
   1016   (vterm-send-key "<left>"))
   1017 (make-obsolete 'vterm-send-left 'vterm--self-insert "v0.1")
   1018 
   1019 (defun vterm-send-right ()
   1020   "Send `<right>' to the libvterm."
   1021   (interactive)
   1022   (vterm-send-key "<right>"))
   1023 (make-obsolete 'vterm-send-right 'vterm--self-insert "v0.1")
   1024 
   1025 (defun vterm-send-prior ()
   1026   "Send `<prior>' to the libvterm."
   1027   (interactive)
   1028   (vterm-send-key "<prior>"))
   1029 (make-obsolete 'vterm-send-prior 'vterm--self-insert "v0.1")
   1030 
   1031 (defun vterm-send-next ()
   1032   "Send `<next>' to the libvterm."
   1033   (interactive)
   1034   (vterm-send-key "<next>"))
   1035 (make-obsolete 'vterm-send-next 'vterm--self-insert "v0.1")
   1036 
   1037 (defun vterm-send-meta-dot ()
   1038   "Send `M-.' to the libvterm."
   1039   (interactive)
   1040   (vterm-send-key "." nil t))
   1041 (make-obsolete 'vterm-send-meta-dot 'vterm--self-insert "v0.1")
   1042 
   1043 (defun vterm-send-meta-comma ()
   1044   "Send `M-,' to the libvterm."
   1045   (interactive)
   1046   (vterm-send-key "," nil t))
   1047 (make-obsolete 'vterm-send-meta-comma 'vterm--self-insert "v0.1")
   1048 
   1049 (defun vterm-send-ctrl-slash ()
   1050   "Send `C-\' to the libvterm."
   1051   (interactive)
   1052   (vterm-send-key "\\" nil nil t))
   1053 (make-obsolete 'vterm-send-ctrl-slash 'vterm--self-insert "v0.1")
   1054 
   1055 (defun vterm-send-escape ()
   1056   "Send `<escape>' to the libvterm."
   1057   (interactive)
   1058   (vterm-send-key "<escape>"))
   1059 
   1060 (defun vterm-clear-scrollback ()
   1061   "Send `<clear-scrollback>' to the libvterm."
   1062   (interactive)
   1063   (vterm-send-key "<clear_scrollback>"))
   1064 
   1065 (defun vterm-clear (&optional arg)
   1066   "Send `<clear>' to the libvterm.
   1067 
   1068 `vterm-clear-scrollback' determines whether
   1069 `vterm-clear' should also clear the scrollback or not.
   1070 
   1071 This behavior can be altered by calling `vterm-clear' with a
   1072 prefix argument ARG or with \\[universal-argument]."
   1073   (interactive "P")
   1074   (if (or
   1075        (and vterm-clear-scrollback-when-clearing (not arg))
   1076        (and arg (not vterm-clear-scrollback-when-clearing)))
   1077       (vterm-clear-scrollback))
   1078   (vterm-send-key "l" nil nil :ctrl))
   1079 
   1080 (defun vterm-undo ()
   1081   "Send `C-_' to the libvterm."
   1082   (interactive)
   1083   (vterm-send-key "_" nil nil t))
   1084 
   1085 (defun vterm-yank (&optional arg)
   1086   "Yank (paste) text in vterm.
   1087 
   1088 Argument ARG is passed to `yank'."
   1089   (interactive "P")
   1090   (deactivate-mark)
   1091   (vterm-goto-char (point))
   1092   (let ((inhibit-read-only t))
   1093     (cl-letf (((symbol-function 'insert-for-yank) #'vterm-insert))
   1094       (yank arg))))
   1095 
   1096 (defun vterm-yank-primary ()
   1097   "Yank text from the primary selection in vterm."
   1098   (interactive)
   1099   (vterm-goto-char (point))
   1100   (let ((inhibit-read-only t)
   1101         (primary (gui-get-primary-selection)))
   1102     (cl-letf (((symbol-function 'insert-for-yank) #'vterm-insert))
   1103       (insert-for-yank primary))))
   1104 
   1105 (defun vterm-yank-pop (&optional arg)
   1106   "Replaced text just yanked with the next entry in the kill ring.
   1107 
   1108 Argument ARG is passed to `yank'"
   1109   (interactive "p")
   1110   (vterm-goto-char (point))
   1111   (let ((inhibit-read-only t)
   1112         (yank-undo-function #'(lambda (_start _end) (vterm-undo))))
   1113     (cl-letf (((symbol-function 'insert-for-yank) #'vterm-insert))
   1114       (yank-pop arg))))
   1115 
   1116 (defun vterm-mouse-set-point (event &optional promote-to-region)
   1117   "Move point to the position clicked on with the mouse.
   1118 But when clicking to the unused area below the last prompt,
   1119 move the cursor to the prompt area."
   1120   (interactive "e\np")
   1121   (let ((pt (mouse-set-point event promote-to-region)))
   1122     (if (= (count-words pt (point-max)) 0)
   1123         (vterm-reset-cursor-point)
   1124       pt))
   1125   ;; Otherwise it selects text for every other click
   1126   (keyboard-quit))
   1127 
   1128 (defun vterm-send-string (string &optional paste-p)
   1129   "Send the string STRING to vterm.
   1130 Optional argument PASTE-P paste-p."
   1131   (when vterm--term
   1132     (when paste-p
   1133       (vterm--update vterm--term "<start_paste>" ))
   1134     (dolist (char (string-to-list string))
   1135       (vterm--update vterm--term (char-to-string char)))
   1136     (when paste-p
   1137       (vterm--update vterm--term "<end_paste>")))
   1138   (setq vterm--redraw-immididately t)
   1139   (accept-process-output vterm--process vterm-timer-delay nil t))
   1140 
   1141 (defun vterm-insert (&rest contents)
   1142   "Insert the arguments, either strings or characters, at point.
   1143 
   1144 Provide similar behavior as `insert' for vterm."
   1145   (when vterm--term
   1146     (vterm--update vterm--term "<start_paste>")
   1147     (dolist (c contents)
   1148       (if (characterp c)
   1149           (vterm--update vterm--term (char-to-string c))
   1150         (dolist (char (string-to-list c))
   1151           (vterm--update vterm--term (char-to-string char)))))
   1152     (vterm--update vterm--term "<end_paste>")
   1153     (setq vterm--redraw-immididately t)
   1154     (accept-process-output vterm--process vterm-timer-delay nil t)))
   1155 
   1156 (defun vterm-delete-region (start end)
   1157   "Delete the text between START and END for vterm. "
   1158   (when vterm--term
   1159     (save-excursion
   1160       (when (get-text-property start 'vterm-line-wrap)
   1161         ;; skip over the fake newline when start there.
   1162         (setq start (1+ start))))
   1163     ;; count of chars after fake newline removed
   1164     (let ((count (length (filter-buffer-substring start end))))
   1165       (if (vterm-goto-char start)
   1166           (cl-loop repeat count do
   1167                    (vterm-send-key "<delete>" nil nil nil t))
   1168         (let ((inhibit-read-only nil))
   1169           (vterm--delete-region start end))))))
   1170 
   1171 (defun vterm-goto-char (pos)
   1172   "Set point to POSITION for vterm.
   1173 
   1174 The return value is `t' when point moved successfully."
   1175   (when (and vterm--term
   1176              (vterm-cursor-in-command-buffer-p)
   1177              (vterm-cursor-in-command-buffer-p pos))
   1178     (vterm-reset-cursor-point)
   1179     (let ((diff (- pos (point))))
   1180       (cond
   1181        ((zerop diff) t)                   ;do not need move
   1182        ((< diff 0)                        ;backward
   1183         (while (and
   1184                 (vterm--backward-char)
   1185                 (> (point) pos)))
   1186         (<= (point) pos))
   1187        (t
   1188         (while (and (vterm--forward-char)
   1189                     (< (point) pos)))
   1190         (>= (point) pos))))))
   1191 
   1192 ;;; Internal
   1193 
   1194 (defun vterm--forward-char ()
   1195   "Move point 1 character forward ().
   1196 
   1197 the return value is `t' when cursor moved."
   1198   (vterm-reset-cursor-point)
   1199   (let ((pt (point)))
   1200     (vterm-send-key "<right>" nil nil nil t)
   1201     (cond
   1202      ((= (point) (1+ pt)) t)
   1203      ((and (> (point) pt)
   1204            ;; move over the fake newline
   1205            (get-text-property (1- (point)) 'vterm-line-wrap))
   1206       t)
   1207      ((and (= (point) (+ 4 pt))
   1208            (looking-back (regexp-quote "^[[C") nil)) ;escape code for <right>
   1209       (dotimes (_ 3) (vterm-send-key "<backspace>" nil nil nil t)) ;;delete  "^[[C"
   1210       nil)
   1211      ((> (point) (1+ pt))             ;auto suggest
   1212       (vterm-send-key "_" nil nil t t) ;undo C-_
   1213       nil)
   1214      (t nil))))
   1215 
   1216 
   1217 
   1218 (defun vterm--backward-char ()
   1219   "Move point N characters backward.
   1220 
   1221 Return count of moved characeters."
   1222   (vterm-reset-cursor-point)
   1223   (let ((pt (point)))
   1224     (vterm-send-key "<left>" nil nil nil t)
   1225     (cond
   1226      ((= (point) (1- pt)) t)
   1227      ((and (= (point) (- pt 2))
   1228            ;; backward cross fake newline
   1229            (string-equal (buffer-substring-no-properties
   1230                           (1+ (point)) (+ 2 (point)))
   1231                          "\n"))
   1232       t)
   1233      ((and (= (point) (+ 4 pt))
   1234            (looking-back (regexp-quote "^[[D") nil)) ;escape code for <left>
   1235       (dotimes (_ 3) (vterm-send-key "<backspace>" nil nil nil t)) ;;delete  "^[[D"
   1236       nil)
   1237      (t nil))))
   1238 
   1239 (defun vterm--delete-region(start end)
   1240   "A wrapper for `delete-region'."
   1241   (funcall vterm--delete-region-function start end))
   1242 
   1243 (defun vterm--insert(&rest content)
   1244   "A wrapper for `insert'."
   1245   (apply vterm--insert-function content))
   1246 
   1247 (defun vterm--delete-char(n &optional killflag)
   1248   "A wrapper for `delete-char'."
   1249   (funcall vterm--delete-char-function n killflag))
   1250 
   1251 (defun vterm--translate-event-to-args (event &optional meta)
   1252   "Translate EVENT as list of args for `vterm-send-key'.
   1253 
   1254 When some input method is enabled, one key may generate
   1255 several characters, so the result of this function is a list,
   1256 looks like: ((\"m\" :shift ))"
   1257   (let* ((modifiers (event-modifiers event))
   1258          (shift (memq 'shift modifiers))
   1259          (meta (or meta (memq 'meta modifiers)))
   1260          (ctrl (memq 'control modifiers))
   1261          (raw-key (event-basic-type event))
   1262          (ev-keys) keys)
   1263     (if input-method-function
   1264         (let ((inhibit-read-only t))
   1265           (setq ev-keys (funcall input-method-function raw-key))
   1266           (when (listp ev-keys)
   1267             (dolist (k ev-keys)
   1268               (when-let ((key (key-description (vector k))))
   1269                 (when (and (not (symbolp event)) shift (not meta) (not ctrl))
   1270                   (setq key (upcase key)))
   1271                 (setq keys (append keys (list (list key shift meta ctrl))))))))
   1272       (when-let ((key (key-description (vector raw-key))))
   1273         (when (and (not (symbolp event)) shift (not meta) (not ctrl))
   1274           (setq key (upcase key)))
   1275         (setq keys  (list (list key shift meta ctrl)))))
   1276     keys))
   1277 
   1278 (defun vterm--invalidate ()
   1279   "The terminal buffer is invalidated, the buffer needs redrawing."
   1280   (if (and (not vterm--redraw-immididately)
   1281            vterm-timer-delay)
   1282       (unless vterm--redraw-timer
   1283         (setq vterm--redraw-timer
   1284               (run-with-timer vterm-timer-delay nil
   1285                               #'vterm--delayed-redraw (current-buffer))))
   1286     (vterm--delayed-redraw (current-buffer))
   1287     (setq vterm--redraw-immididately nil)))
   1288 
   1289 (defun vterm-check-proc (&optional buffer)
   1290   "Check if there is a running process associated to the vterm buffer BUFFER.
   1291 
   1292 BUFFER can be either a buffer or the name of one."
   1293   (let* ((buffer (get-buffer (or buffer (current-buffer))))
   1294          (proc (get-buffer-process buffer)))
   1295     (and proc
   1296          (memq (process-status proc) '(run stop open listen connect))
   1297          (buffer-local-value 'vterm--term buffer))))
   1298 
   1299 (defun vterm--delayed-redraw (buffer)
   1300   "Redraw the terminal buffer.
   1301 Argument BUFFER the terminal buffer."
   1302   (when (buffer-live-p buffer)
   1303     (with-current-buffer buffer
   1304       (let ((inhibit-redisplay t)
   1305             (inhibit-read-only t)
   1306             (windows (get-buffer-window-list)))
   1307         (setq vterm--redraw-timer nil)
   1308         (when vterm--term
   1309           (vterm--redraw vterm--term)
   1310           (unless (zerop (window-hscroll))
   1311             (when (cl-member (selected-window) windows :test #'eq)
   1312               (set-window-hscroll (selected-window) 0))))))))
   1313 
   1314 ;; see VTermSelectionMask in vterm.el
   1315 ;; VTERM_SELECTION_CLIPBOARD = (1<<0),
   1316 ;; VTERM_SELECTION_PRIMARY   = (1<<1),
   1317 (defconst vterm--selection-clipboard 1)   ;(1<<0)
   1318 (defconst vterm--selection-primary   2)   ;(1<<1)
   1319 (defun vterm--set-selection (mask data)
   1320   "OSC 52 Manipulate Selection Data.
   1321 Search Manipulate Selection Data in
   1322  https://invisible-island.net/xterm/ctlseqs/ctlseqs.html ."
   1323   (when vterm-enable-manipulate-selection-data-by-osc52
   1324     (let ((select-enable-clipboard select-enable-clipboard)
   1325           (select-enable-primary select-enable-primary))
   1326       (setq select-enable-clipboard
   1327             (logand mask vterm--selection-clipboard))
   1328       (setq select-enable-primary
   1329             (logand mask vterm--selection-primary))
   1330       (kill-new data)
   1331       (message "kill-ring is updated by vterm OSC 52(Manipulate Selection Data)"))
   1332     ))
   1333 
   1334 ;;; Entry Points
   1335 
   1336 ;;;###autoload
   1337 (defun vterm (&optional arg)
   1338   "Create an interactive Vterm buffer.
   1339 Start a new Vterm session, or switch to an already active
   1340 session.  Return the buffer selected (or created).
   1341 
   1342 With a nonnumeric prefix arg, create a new session.
   1343 
   1344 With a string prefix arg, create a new session with arg as buffer name.
   1345 
   1346 With a numeric prefix arg (as in `C-u 42 M-x vterm RET'), switch
   1347 to the session with that number, or create it if it doesn't
   1348 already exist.
   1349 
   1350 The buffer name used for Vterm sessions is determined by the
   1351 value of `vterm-buffer-name'."
   1352   (interactive "P")
   1353   (vterm--internal #'pop-to-buffer-same-window arg))
   1354 
   1355 ;;;###autoload
   1356 (defun vterm-other-window (&optional arg)
   1357   "Create an interactive Vterm buffer in another window.
   1358 Start a new Vterm session, or switch to an already active
   1359 session.  Return the buffer selected (or created).
   1360 
   1361 With a nonnumeric prefix arg, create a new session.
   1362 
   1363 With a string prefix arg, create a new session with arg as buffer name.
   1364 
   1365 With a numeric prefix arg (as in `C-u 42 M-x vterm RET'), switch
   1366 to the session with that number, or create it if it doesn't
   1367 already exist.
   1368 
   1369 The buffer name used for Vterm sessions is determined by the
   1370 value of `vterm-buffer-name'."
   1371   (interactive "P")
   1372   (vterm--internal #'pop-to-buffer arg))
   1373 
   1374 (defun vterm--internal (pop-to-buf-fun &optional arg)
   1375   (cl-assert vterm-buffer-name)
   1376   (let ((buf (cond ((numberp arg)
   1377                     (get-buffer-create (format "%s<%d>"
   1378                                                vterm-buffer-name
   1379                                                arg)))
   1380                    ((stringp arg) (generate-new-buffer arg))
   1381                    (arg (generate-new-buffer vterm-buffer-name))
   1382                    (t
   1383                     (get-buffer-create vterm-buffer-name)))))
   1384     (cl-assert (and buf (buffer-live-p buf)))
   1385     (funcall pop-to-buf-fun buf)
   1386     (with-current-buffer buf
   1387       (unless (derived-mode-p 'vterm-mode)
   1388         (vterm-mode)))
   1389     buf))
   1390 
   1391 ;;; Internal
   1392 
   1393 (defun vterm--flush-output (output)
   1394   "Send the virtual terminal's OUTPUT to the shell."
   1395   (process-send-string vterm--process output))
   1396 ;; Terminal emulation
   1397 ;; This is the standard process filter for term buffers.
   1398 ;; It emulates (most of the features of) a VT100/ANSI-style terminal.
   1399 
   1400 ;; References:
   1401 ;; [ctlseqs]: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
   1402 ;; [ECMA-48]: https://www.ecma-international.org/publications/standards/Ecma-048.htm
   1403 ;; [vt100]: https://vt100.net/docs/vt100-ug/chapter3.html
   1404 
   1405 (defconst vterm-control-seq-regexp
   1406   (concat
   1407    ;; A control character,
   1408    "\\(?:[\r\n\000\007\t\b\016\017]\\|"
   1409    ;; a C1 escape coded character (see [ECMA-48] section 5.3 "Elements
   1410    ;; of the C1 set"),
   1411    "\e\\(?:[DM78c=]\\|"
   1412    ;; another Emacs specific control sequence for term.el,
   1413    "AnSiT[^\n]+\n\\|"
   1414    ;; another Emacs specific control sequence for vterm.el
   1415    ;; printf "\e]%s\e\\"
   1416    "\\][^\e]+\e\\\\\\|"
   1417    ;; or an escape sequence (section 5.4 "Control Sequences"),
   1418    "\\[\\([\x30-\x3F]*\\)[\x20-\x2F]*[\x40-\x7E]\\)\\)")
   1419   "Regexp matching control sequences handled by term.el.")
   1420 
   1421 (defconst vterm-control-seq-prefix-regexp
   1422   "[\032\e]")
   1423 
   1424 (defun vterm--filter (process input)
   1425   "I/O Event.  Feeds PROCESS's INPUT to the virtual terminal.
   1426 
   1427 Then triggers a redraw from the module."
   1428   (let ((inhibit-redisplay t)
   1429         (inhibit-eol-conversion t)
   1430         (inhibit-read-only t)
   1431         (buf (process-buffer process))
   1432         (i 0)
   1433         (str-length (length input))
   1434         decoded-substring
   1435         funny)
   1436     (when (buffer-live-p buf)
   1437       (with-current-buffer buf
   1438         ;; borrowed from term.el
   1439         ;; Handle non-control data.  Decode the string before
   1440         ;; counting characters, to avoid garbling of certain
   1441         ;; multibyte characters (https://github.com/akermu/emacs-libvterm/issues/394).
   1442         ;; same bug of term.el https://debbugs.gnu.org/cgi/bugreport.cgi?bug=1006
   1443         (when vterm--undecoded-bytes
   1444           (setq input (concat vterm--undecoded-bytes input))
   1445           (setq vterm--undecoded-bytes nil)
   1446           (setq str-length (length input)))
   1447         (while (< i str-length)
   1448           (setq funny (string-match vterm-control-seq-regexp input i))
   1449           (let ((ctl-end (if funny (match-end 0)
   1450                            (setq funny (string-match vterm-control-seq-prefix-regexp input i))
   1451                            (if funny
   1452                                (setq vterm--undecoded-bytes
   1453                                      (substring input funny))
   1454                              (setq funny str-length))
   1455                            ;; The control sequence ends somewhere
   1456                            ;; past the end of this string.
   1457                            (1+ str-length))))
   1458             (when (> funny i)
   1459               ;; Handle non-control data.  Decode the string before
   1460               ;; counting characters, to avoid garbling of certain
   1461               ;; multibyte characters (emacs bug#1006).
   1462               (setq decoded-substring
   1463                     (decode-coding-string
   1464                      (substring input i funny)
   1465                      locale-coding-system t))
   1466               ;; Check for multibyte characters that ends
   1467               ;; before end of string, and save it for
   1468               ;; next time.
   1469               (when (= funny str-length)
   1470                 (let ((partial 0)
   1471                       (count (length decoded-substring)))
   1472                   (while (and (< partial count)
   1473                               (eq (char-charset (aref decoded-substring
   1474                                                       (- count 1 partial)))
   1475                                   'eight-bit))
   1476                     (cl-incf partial))
   1477                   (when (> count partial 0)
   1478                     (setq vterm--undecoded-bytes
   1479                           (substring decoded-substring (- partial)))
   1480                     (setq decoded-substring
   1481                           (substring decoded-substring 0 (- partial)))
   1482                     (cl-decf str-length partial)
   1483                     (cl-decf funny partial))))
   1484               (ignore-errors (vterm--write-input vterm--term decoded-substring))
   1485               (setq i funny))
   1486             (when (<= ctl-end str-length)
   1487               (ignore-errors (vterm--write-input vterm--term (substring input i ctl-end))))
   1488             (setq i ctl-end)))
   1489         (vterm--update vterm--term)))))
   1490 
   1491 (defun vterm--sentinel (process event)
   1492   "Sentinel of vterm PROCESS.
   1493 Argument EVENT process event."
   1494   (let ((buf (process-buffer process)))
   1495     (run-hook-with-args 'vterm-exit-functions
   1496                         (if (buffer-live-p buf) buf nil)
   1497                         event)
   1498     (if (and vterm-kill-buffer-on-exit (buffer-live-p buf))
   1499         (kill-buffer buf))))
   1500 
   1501 (defun vterm--text-scale-mode (&optional _argv)
   1502   "Fix `line-number' height for scaled text."
   1503   (and text-scale-mode
   1504        (equal major-mode 'vterm-mode)
   1505        (boundp 'display-line-numbers)
   1506        (let ((height (expt text-scale-mode-step
   1507                            text-scale-mode-amount)))
   1508          (when vterm--linenum-remapping
   1509            (face-remap-remove-relative vterm--linenum-remapping))
   1510          (setq vterm--linenum-remapping
   1511                (face-remap-add-relative 'line-number :height height))))
   1512   (window--adjust-process-windows))
   1513 
   1514 (advice-add #'text-scale-mode :after #'vterm--text-scale-mode)
   1515 
   1516 (defun vterm--window-adjust-process-window-size (process windows)
   1517   "Adjust width of window WINDOWS associated to process PROCESS.
   1518 
   1519 `vterm-min-window-width' determines the minimum width allowed."
   1520   ;; We want `vterm-copy-mode' to resemble a fundamental buffer as much as
   1521   ;; possible.  Hence, we must not call this function when the minor mode is
   1522   ;; enabled, otherwise the buffer would be redrawn, messing around with the
   1523   ;; position of the point.
   1524   (unless vterm-copy-mode
   1525     (let* ((size (funcall window-adjust-process-window-size-function
   1526                           process windows))
   1527            (width (car size))
   1528            (height (cdr size))
   1529            (inhibit-read-only t))
   1530       (setq width (- width (vterm--get-margin-width)))
   1531       (setq width (max width vterm-min-window-width))
   1532       (when (and (processp process)
   1533                  (process-live-p process)
   1534                  (> width 0)
   1535                  (> height 0))
   1536         (vterm--set-size vterm--term height width)
   1537         (cons width height)))))
   1538 
   1539 (defun vterm--get-margin-width ()
   1540   "Get margin width of vterm buffer when `display-line-numbers-mode' is enabled."
   1541   (let ((width 0)
   1542         (max-line-num (+ (frame-height) vterm-max-scrollback)))
   1543     (when (bound-and-true-p display-line-numbers)
   1544       (setq width (+ width 4
   1545                      (string-width (number-to-string max-line-num)))))
   1546     width))
   1547 
   1548 (defun vterm--delete-lines (line-num count &optional delete-whole-line)
   1549   "Delete COUNT lines from LINE-NUM.
   1550 If LINE-NUM is negative backward-line from end of buffer.
   1551 If option DELETE-WHOLE-LINE is non-nil, then this command kills
   1552 the whole line including its terminating newline"
   1553   (save-excursion
   1554     (when (vterm--goto-line line-num)
   1555       (vterm--delete-region (point) (line-end-position count))
   1556       (when (and delete-whole-line
   1557                  (looking-at "\n"))
   1558         (vterm--delete-char 1)))))
   1559 
   1560 (defun vterm--goto-line (n)
   1561   "Go to line N and return true on success.
   1562 If N is negative backward-line from end of buffer."
   1563   (cond
   1564    ((> n 0)
   1565     (goto-char (point-min))
   1566     (eq 0 (forward-line (1- n))))
   1567    (t
   1568     (goto-char (point-max))
   1569     (eq 0 (forward-line n)))))
   1570 
   1571 (defun vterm--set-title (title)
   1572   "Use TITLE to set the buffer name according to `vterm-buffer-name-string'."
   1573   (when vterm-buffer-name-string
   1574     (rename-buffer (format vterm-buffer-name-string title) t)))
   1575 
   1576 (defun vterm--set-directory (path)
   1577   "Set `default-directory' to PATH."
   1578   (let ((dir (vterm--get-directory path)))
   1579     (when dir (setq default-directory dir))))
   1580 
   1581 (defun vterm--get-directory (path)
   1582   "Get normalized directory to PATH."
   1583   (when path
   1584     (let (directory)
   1585       (if (string-match "^\\(.*?\\)@\\(.*?\\):\\(.*?\\)$" path)
   1586           (progn
   1587             (let ((user (match-string 1 path))
   1588                   (host (match-string 2 path))
   1589                   (dir (match-string 3 path)))
   1590               (if (and (string-equal user user-login-name)
   1591                        (string-equal host (system-name)))
   1592                   (progn
   1593                     (when (file-directory-p dir)
   1594                       (setq directory (file-name-as-directory dir))))
   1595                 (setq directory (file-name-as-directory (concat "/-:" path))))))
   1596         (when (file-directory-p path)
   1597           (setq directory (file-name-as-directory path))))
   1598       directory)))
   1599 
   1600 (defun vterm--get-pwd (&optional linenum)
   1601   "Get working directory at LINENUM."
   1602   (when vterm--term
   1603     (let ((raw-pwd (vterm--get-pwd-raw
   1604                     vterm--term
   1605                     (or linenum (line-number-at-pos)))))
   1606       (when raw-pwd
   1607         (vterm--get-directory raw-pwd)))))
   1608 
   1609 (defun vterm--get-color (index)
   1610   "Get color by index from `vterm-color-palette'.
   1611 Argument INDEX index of the terminal color.
   1612 Special values for INDEX are:
   1613 -11 foreground for cells with underline attribute, foreground of
   1614 the `vterm-color-underline' face is used in this case.
   1615 -12 background for cells with inverse video attribute, background
   1616 of the `vterm-color-inverse-video' face is used in this case."
   1617   (cond
   1618    ((and (>= index 0) (< index 8))
   1619     (face-foreground
   1620      (elt vterm-color-palette index)
   1621      nil 'default))
   1622    ((and (>= index 8) (< index 16))
   1623     (face-background
   1624      (elt vterm-color-palette (% index 8))
   1625      nil 'default))
   1626    ((= index -11)
   1627     (face-foreground 'vterm-color-underline nil 'default))
   1628    ((= index -12)
   1629     (face-background 'vterm-color-inverse-video nil 'default))
   1630    (t
   1631     nil)))
   1632 
   1633 (defun vterm--eval (str)
   1634   "Check if string STR is `vterm-eval-cmds' and execute command.
   1635 
   1636 All passed in arguments are strings and forwarded as string to
   1637 the called functions."
   1638   (let* ((parts (split-string-and-unquote str))
   1639          (command (car parts))
   1640          (args (cdr parts))
   1641          (f (assoc command vterm-eval-cmds)))
   1642     (if f
   1643         (apply (cadr f) args)
   1644       (message "Failed to find command: %s.  To execute a command,
   1645                 add it to the `vterm-eval-cmd' list" command))))
   1646 
   1647 ;; TODO: Improve doc string, it should not point to the readme but it should
   1648 ;;       be self-contained.
   1649 (defun vterm--prompt-tracking-enabled-p ()
   1650   "Return t if tracking the prompt is enabled.
   1651 
   1652 Prompt tracking need shell side configurations.
   1653 
   1654 For zsh user, this is done by PROMPT=$PROMPT'%{$(vterm_prompt_end)%}'.
   1655 
   1656 The shell send semantic information about where the prompt ends via properly
   1657 escaped sequences to Emacs.
   1658 
   1659 More information see `Shell-side configuration' and `Directory tracking'
   1660 in README."
   1661   (or vterm--prompt-tracking-enabled-p
   1662       (save-excursion
   1663         (setq vterm--prompt-tracking-enabled-p
   1664               (next-single-property-change (point-min) 'vterm-prompt)))))
   1665 
   1666 (defun vterm-next-prompt (n)
   1667   "Move to end of Nth next prompt in the buffer."
   1668   (interactive "p")
   1669   (if (and vterm-use-vterm-prompt-detection-method
   1670            (vterm--prompt-tracking-enabled-p))
   1671       (let ((pt (point))
   1672             (promp-pt (vterm--get-prompt-point)))
   1673         (when promp-pt (goto-char promp-pt))
   1674         (cl-loop repeat (or n 1) do
   1675                  (setq pt (next-single-property-change (line-beginning-position 2) 'vterm-prompt))
   1676                  (when pt (goto-char pt))))
   1677     (term-next-prompt n)))
   1678 
   1679 (defun vterm-previous-prompt (n)
   1680   "Move to end of Nth previous prompt in the buffer."
   1681   (interactive "p")
   1682   (if (and vterm-use-vterm-prompt-detection-method
   1683            (vterm--prompt-tracking-enabled-p))
   1684       (let ((pt (point))
   1685             (prompt-pt (vterm--get-prompt-point)))
   1686         (when prompt-pt
   1687           (goto-char prompt-pt)
   1688           (when (> pt (point))
   1689             (setq n (1- (or n 1))))
   1690           (cl-loop repeat n do
   1691                    (setq pt (previous-single-property-change (1- (point)) 'vterm-prompt))
   1692                    (when pt (goto-char (1- pt))))))
   1693     (term-previous-prompt n)))
   1694 
   1695 (defun vterm--get-beginning-of-line (&optional pt)
   1696   "Find the start of the line, bypassing line wraps.
   1697 If PT is specified, find it's beginning of the line instead of the beginning
   1698 of the line at cursor."
   1699   (save-excursion
   1700     (when pt (goto-char pt))
   1701     (beginning-of-line)
   1702     (while (and (not (bobp))
   1703                 (get-text-property (1- (point)) 'vterm-line-wrap))
   1704       (forward-char -1)
   1705       (beginning-of-line))
   1706     (point)))
   1707 
   1708 (defun vterm--get-end-of-line (&optional pt)
   1709   "Find the start of the line, bypassing line wraps.
   1710 If PT is specified, find it's end of the line instead of the end
   1711 of the line at cursor."
   1712   (save-excursion
   1713     (when pt (goto-char pt))
   1714     (end-of-line)
   1715     (while (get-text-property (point) 'vterm-line-wrap)
   1716       (forward-char)
   1717       (end-of-line))
   1718     (point)))
   1719 
   1720 ;; TODO: Improve doc string, it should not point to the readme but it should
   1721 ;;       be self-contained.
   1722 (defun vterm--get-prompt-point ()
   1723   "Get the position of the end of current prompt.
   1724 More information see `vterm--prompt-tracking-enabled-p' and
   1725 `Directory tracking and Prompt tracking'in README."
   1726   (let ((end-point (vterm--get-end-of-line))
   1727         prompt-point)
   1728     (save-excursion
   1729       (if (and vterm-use-vterm-prompt-detection-method
   1730                (vterm--prompt-tracking-enabled-p))
   1731           (if (get-text-property end-point 'vterm-prompt)
   1732               end-point
   1733             (setq prompt-point (previous-single-property-change end-point 'vterm-prompt))
   1734             (when prompt-point (setq prompt-point (1- prompt-point))))
   1735         (goto-char end-point)
   1736         (if (search-backward-regexp term-prompt-regexp nil t)
   1737             (goto-char (match-end 0))
   1738           (vterm--get-beginning-of-line))))))
   1739 
   1740 (defun vterm--at-prompt-p ()
   1741   "Return t if the cursor position is at shell prompt."
   1742   (= (point) (or (vterm--get-prompt-point) 0)))
   1743 
   1744 (defun vterm-cursor-in-command-buffer-p (&optional pt)
   1745   "Check whether cursor in command buffer area."
   1746   (save-excursion
   1747     (vterm-reset-cursor-point)
   1748     (let ((promp-pt (vterm--get-prompt-point)))
   1749       (when promp-pt
   1750         (<= promp-pt (or pt (vterm--get-cursor-point)))))))
   1751 
   1752 (defun vterm-beginning-of-line ()
   1753   "Move point to the beginning of the line.
   1754 
   1755 Move the point to the first character after the shell prompt on this line.
   1756 If the point is already there, move to the beginning of the line.
   1757 Effectively toggle between the two positions."
   1758   (interactive "^")
   1759   (if (vterm--at-prompt-p)
   1760       (goto-char (vterm--get-beginning-of-line))
   1761     (goto-char (max (or (vterm--get-prompt-point) 0)
   1762                     (vterm--get-beginning-of-line)))))
   1763 
   1764 (defun vterm-end-of-line ()
   1765   "Move point to the end of the line, bypassing line wraps."
   1766   (interactive "^")
   1767   (goto-char (vterm--get-end-of-line)))
   1768 
   1769 (defun vterm-reset-cursor-point ()
   1770   "Make sure the cursor at the right position."
   1771   (interactive)
   1772   (when vterm--term
   1773     (let ((inhibit-read-only t))
   1774       (vterm--reset-point vterm--term))))
   1775 
   1776 (defun vterm--get-cursor-point ()
   1777   "Get term cursor position."
   1778   (when vterm--term
   1779     (save-excursion
   1780       (vterm-reset-cursor-point))))
   1781 
   1782 (defun vterm--reinsert-fake-newlines ()
   1783   "Reinsert fake newline from `vterm--copy-mode-fake-newlines'."
   1784   (let ((inhibit-read-only t)
   1785         (inhibit-redisplay t)
   1786         (fake-newline-text "\n")
   1787         fake-newline-pos)
   1788     (add-text-properties 0 1 '(vterm-line-wrap t rear-nonsticky t)
   1789                          fake-newline-text)
   1790     (while vterm--copy-mode-fake-newlines
   1791       (setq fake-newline-pos (car vterm--copy-mode-fake-newlines))
   1792       (setq vterm--copy-mode-fake-newlines (cdr vterm--copy-mode-fake-newlines))
   1793       (goto-char fake-newline-pos)
   1794       (insert fake-newline-text))))
   1795 
   1796 (defun vterm--remove-fake-newlines (&optional remembering-pos-p)
   1797   "Filter out injected newlines were injected when rendering the terminal.
   1798 
   1799 These newlines were tagged with \\='vterm-line-wrap property so we
   1800 can find them and remove them.
   1801 If REMEMBERING-POS-P is not nil remembering their positions in a buffer-local
   1802 `vterm--copy-mode-fake-newlines'."
   1803   (let (fake-newline
   1804         (inhibit-read-only t)
   1805         (inhibit-redisplay t))
   1806     (when remembering-pos-p
   1807       (setq vterm--copy-mode-fake-newlines nil))
   1808 
   1809     (goto-char (point-max))
   1810     (when (and (bolp)
   1811                (not (bobp))
   1812                (get-text-property (1- (point)) 'vterm-line-wrap))
   1813       (forward-char -1)
   1814       (when remembering-pos-p
   1815         (setq vterm--copy-mode-fake-newlines
   1816               (cons (point) vterm--copy-mode-fake-newlines)))
   1817       (vterm--delete-char 1))
   1818 
   1819     (while (and (not (bobp))
   1820                 (setq fake-newline (previous-single-property-change
   1821                                     (point) 'vterm-line-wrap)))
   1822       (goto-char (1- fake-newline))
   1823       (cl-assert (eq ?\n (char-after)))
   1824       (when remembering-pos-p
   1825         (setq vterm--copy-mode-fake-newlines
   1826               (cons (point) vterm--copy-mode-fake-newlines)))
   1827       (vterm--delete-char 1))))
   1828 
   1829 (defun vterm--filter-buffer-substring (content)
   1830   "Filter string CONTENT of fake/injected newlines."
   1831   (with-temp-buffer
   1832     (vterm--insert content)
   1833     (vterm--remove-fake-newlines nil)
   1834     (buffer-string)))
   1835 
   1836 
   1837 (provide 'vterm)
   1838 ;; Local Variables:
   1839 ;; indent-tabs-mode: nil
   1840 ;; End:
   1841 ;;; vterm.el ends here