File: term.el.html

This file defines a general command-interpreter-in-a-buffer package
(term mode). The idea is that you can build specific process-in-a-buffer
modes on top of term mode -- e.g., Lisp, shell, Scheme, T, soar, .... This way, all these specific packages share a common base functionality, and a common set of bindings, which makes them easier to use (and saves code, implementation time, etc., etc.).

If, instead of term, you call ansi-term, you get multiple term buffers, after every new call ansi-term opens a new
"*ansi-term*<xx>" window, where <xx> is, as usual, a number...

For hints on converting existing process modes (e.g., tex-mode, background, dbx, gdb, kermit, prolog, telnet) to use term-mode instead of shell-mode, see the notes at the end of this file.

Speed considerations and a few caveats
--------------------------------------

While the message passing and the colorization surely introduce some overhead this has became so small that IMHO it is surely outweighed by the benefits you get but, as usual, YMMV.

Important caveat, when deciding the cursor/'gray keys' keycodes I had to make a choice: on my Linux box this choice allows me to run all the ncurses applications without problems but make these keys incomprehensible to all the cursesX programs. Your mileage may vary so you may consider changing the default 'emulation'. Just search for this piece of code and modify it as you like:

;; Which would be better: "\\e[A" or "\\eOA"? readline accepts either.
;; For my configuration it's definitely better \eOA but YMMV. -mm
;; For example: vi works with \eOA while elm wants \e[A ...
(defun term-send-up () (interactive) (term-send-raw-string "\\eOA"))
(defun term-send-down () (interactive) (term-send-raw-string "\\eOB"))
(defun term-send-right () (interactive) (term-send-raw-string "\\eOC"))
(defun term-send-left () (interactive) (term-send-raw-string "\\eOD"))


IMPORTANT: additions & changes
------------------------------

 With this enhanced ansi-term.el you will get a reliable mechanism of
directory/username/host tracking: the only drawback is that you will have to modify your shell start-up script. It's worth it, believe me :).

When you ssh/sudo/su and the account you access has a modified startup script, you will be able to access the remote files as usual with C-x C-f, if it's needed you will have to enter a password, otherwise the file should get loaded straight away.

This is useful even if you work only on one host: it often happens that, for maintenance reasons, you have to edit files 'as root': before patching term.el, I su-ed in a term.el buffer and used vi :), now I simply do a C-x C-f and, via ange-ftp, the file is automatically loaded
'as-root'. (If you don't want to enter the root password every time you
can put it in your .netrc: note that this is -not- advisable if you're connected to the internet or if somebody else works on your workstation!)

If you use wu-ftpd you can use some of its features to avoid root ftp access to the rest of the world: just put in /etc/ftphosts something like

# Local access
allow root 127.0.0.1

# By default nobody can't do anything
deny root *

            ----------------------------------------

 With the variable term-buffer-maximum-size you can decide how many
scrollback lines to keep: its default is 8192.

            ----------------------------------------


 ANSI colorization should work well. Blink, is not supported.
 Currently it's mapped as bold.

            ----------------------------------------

 TODO:

 - Add hooks to allow raw-mode keys to be configurable
 - Which keys are better ? \eOA or \e[A ?

 ----------------------------------------------------------------
 You should/could have something like this in your .emacs to take
 full advantage of this package

 (add-hook 'term-mode-hook
           (lambda ()
             (setq term-prompt-regexp "^[^#$%>\\n]*[#$%>] *")
             (setq-local mouse-yank-at-point t)
             (setq-local transient-mark-mode nil)
             (auto-fill-mode -1)
             (setq tab-width 8)))

            ----------------------------------------

 If you want to use color ls the best setup is to have a different file
when you use eterm ( see above, mine is named .emacs_dircolors ). This is necessary because some terminals, rxvt for example, need non-ansi hacks to work ( for example on my rxvt white is wired to fg, and to obtain normal white I have to do bold-white :)

            ----------------------------------------

 # Configuration file for the color ls utility
 # This file goes in the /etc directory, and must be world readable.
 # You can copy this file to .dir_colors in your $HOME directory to
 # override the system defaults.

 # COLOR needs one of these arguments: 'tty' colorizes output to ttys, but
 # not pipes. 'all' adds color characters to all output. 'none' shuts
 # colorization off.
 COLOR tty
 OPTIONS -F

 # Below, there should be one TERM entry for each termtype that is
 # colorizable
 TERM eterm

 # EIGHTBIT, followed by '1' for on, '0' for off. (8-bit output)
 EIGHTBIT 1

 # Below are the color init strings for the basic file types. A color init
 # string consists of one or more of the following numeric codes:
 # Attribute codes:
 # 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed
 # Text color codes:
 # 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
 # Background color codes:
 # 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white
 NORMAL 00 # global default, although everything should be something.
 FILE 00 # normal file
 DIR 00;37 # directory
 LINK 00;36 # symbolic link
 FIFO 00;37 # pipe
 SOCK 40;35 # socket
 BLK 33;01 # block device driver
 CHR 33;01 # character device driver

 # This is for files with execute permission:
 EXEC 00;32

 # List any file extensions like '.gz' or '.tar' that you would like ls
 # to colorize below. Put the extension, a space, and the color init
 # string. (and any comments you want to add after a '#')
 .tar 01;33 # archives or compressed
 .tgz 01;33
 .arj 01;33
 .taz 01;33
 .lzh 01;33
 .zip 01;33
 .z 01;33
 .Z 01;33
 .gz 01;33
 .jpg 01;35 # image formats
 .gif 01;35
 .bmp 01;35
 .xbm 01;35
 .xpm 01;35

            ----------------------------------------

There are actually two methods for directory tracking, one implemented in term-command-hook(var)/term-command-hook(fun) which sets the directory according to an escape sequence of the form "\\032/<directory>\\n". Some shells like bash will already send this escape sequence when they detect they are running in Emacs. This can be configured or disabled on the Emacs side by setting term-command-hook(var)/term-command-hook(fun) to a different function.

The second method is in term-handle-ansi-terminal-messages which sets user, host, and directory according to escape sequences of the form "\\033AnSiTc <directory>\\n" (replace the "c" with "u" and "h" for user and host, respectively). If the user and host don't match, it will set directory to a remote one, so it is important to set user and host correctly first. See the example bash configuration below.

            ----------------------------------------

# Set HOSTNAME if not already set.
: ${HOSTNAME=$(uname -n)}

# su does not change this but I'd like it to
USER=$(whoami)

# ...

case $TERM in
    eterm*)

printf '%s\n' \
-------------------------------------------------------------- \
"Hello $USER" \
"Today is $(date)" \
"We are on $HOSTNAME running $(uname) under Emacs term mode" \
--------------------------------------------------------------

# The \033 stands for ESC.
# There is a space between "AnSiT?" and $whatever.
printf '\033AnSiTh %s\n' "$HOSTNAME"
printf '\033AnSiTu %s\n' "$USER"
printf '\033AnSiTc %s\n' "$PWD"

cd() { command cd "$@" && printf '\033AnSiTc %s\n' "$PWD"; }
pushd() { command pushd "$@" && printf '\033AnSiTc %s\n' "$PWD"; }
popd() { command popd "$@" && printf '\033AnSiTc %s\n' "$PWD"; }

# Use custom dircolors in term buffers.
# eval $(dircolors $HOME/.emacs_dircolors)
esac

# ...

For troubleshooting in Bash, you can check the definition of the custom functions with the "type" command. e.g. "type cd". If you do not see the expected definition from the config below, then the directory tracking will not work.


Brief Command Documentation:
============================================================================
Term Mode Commands: (common to all derived modes, like cmushell & cmulisp mode)

M-p term-previous-input Cycle backwards in input history
M-n term-next-input Cycle forwards
M-r term-previous-matching-input Previous input matching a regexp
M-s term-next-matching-input Next input that matches
return term-send-input
C-c C-a term-bol Beginning of line; skip prompt.
C-d term-delchar-or-maybe-eof Delete char unless at end of buff.
C-c C-u term-kill-input ^u
C-c C-w backward-kill-word ^w
C-c C-c term-interrupt-subjob ^c
C-c C-z term-stop-subjob ^z
C-c C-\ term-quit-subjob ^\
C-c C-o term-kill-output Delete last batch of process output
C-c C-r term-show-output Show last batch of process output
C-c C-h term-dynamic-list-input-ring List input history

Not bound by default in term-mode
term-send-invisible Read a line without echo, and send to proc
(These are bound in shell-mode)
term-dynamic-complete Complete filename at point.
term-dynamic-list-completions List completions in help buffer.
term-replace-by-expanded-filename Expand and complete filename at point;
replace with expanded/completed name.
term-kill-subjob No mercy.
term-show-maximum-output Show as much output as possible.
term-continue-subjob Send CONT signal to buffer's process
group. Useful if you accidentally
suspend your process (with C-c C-z).

term-mode-hook is the term mode hook. Basically for your keybindings. term-load-hook is run after loading in this package.

Defined variables (68)

serial-name-historyHistory of serial ports used by ‘serial-read-name’.
serial-no-speedString for ‘serial-read-speed’ for special serial ports.
serial-speed-historyHistory of serial port speeds used by ‘serial-read-speed’.
term--bash-needs-EMACS-status43 if Bash is so old that it needs EMACS set.
term--osc-max-bytesLimit the length of OSC sequences to keep in memory.
term-auto-marginsWhen non-nil, terminal will automatically wrap lines at the right margin.
term-bind-function-keysIf nil, don’t alter <f1>, <f2> and so on.
term-buffer-maximum-sizeThe maximum size in lines for term buffers.
term-char-mode-buffer-read-onlyIf non-nil, only the process filter may modify the buffer in char mode.
term-char-mode-point-at-process-markIf non-nil, keep point at the process mark in char mode.
term-clear-full-screen-programsWhether to clear contents of full-screen terminal programs after exit.
term-completion-addsuffixIf non-nil, add a ‘/’ to completed directories, ‘ ’ to file names.
term-completion-autolistIf non-nil, automatically list possibilities on partial completion.
term-completion-fignoreList of suffixes to be disregarded during file completion.
term-completion-recexactIf non-nil, use shortest completion if characters cannot be added.
term-control-seq-regexpRegexp matching control sequences handled by term.el.
term-current-columnIf non-nil, is cache for (current-column).
term-current-rowCurrent vertical row (relative to home-marker) or nil if unknown.
term-delimiter-argument-listList of characters to recognize as separate arguments in input.
term-do-line-wrappingLast character was a graphic in the last column.
term-dynamic-complete-functionsList of functions called to perform completion.
term-eol-on-sendNon-nil means go to the end of the line before sending input.
term-escape-charEscape character for char sub-mode of term mode.
term-exec-hookCalled each time a process is exec’d by ‘term-exec’.
term-file-name-prefixPrefix prepended to absolute file names taken from process input.
term-get-old-inputFunction that submits old text in term mode.
term-goto-process-markWhether to reset point to the current process mark after this command.
term-input-autoexpandIf non-nil, expand input command history references on completion.
term-input-chunk-sizeLong inputs send to term processes are broken up into chunks of this size.
term-input-filterPredicate for filtering additions to input history.
term-input-filter-functionsFunctions to call before input is sent to the process.
term-input-ignoredupsIf non-nil, don’t add input matching the last on the input ring.
term-input-ring-file-nameIf non-nil, name of the file to read/write input history.
term-input-ring-indexIndex of last matched history element.
term-input-ring-sizeSize of input history ring.
term-input-senderFunction to actually send to PROCESS the STRING submitted by user.
term-kill-echo-listA queue of strings whose echo we want suppressed.
term-last-input-matchLast string searched for by term input history search, for defaulting.
term-line-mode-buffer-read-onlyThe ‘buffer-read-only’ state to set in ‘term-line-mode’.
term-load-hookThis hook is run when term is loaded in.
term-matching-input-from-input-stringInput previously used to match input history.
term-mode-abbrev-tableAbbrev table for ‘term-mode’.
term-mode-hookCalled upon entry into term mode.
term-mode-mapKeymap for "line mode" in Term mode.
term-mode-syntax-tableSyntax table for ‘term-mode’.
term-old-mode-mapSaves the old keymap when in char mode.
term-osc-handlersTerminal-specific OSC sequence handler function alist.
term-pager-break-mapKeymap used in Term pager mode.
term-pager-countNumber of lines before we need to page; if nil, paging is disabled.
term-pager-menuMenu for Term pager mode.
term-pager-old-local-mapSaves old keymap while paging.
term-prompt-regexpRegexp to recognize prompts in the inferior process.
term-ptypNon-nil if communications via pty; false if by pipe. Buffer local.
term-raw-mapKeyboard map for sending characters directly to the inferior process.
term-saved-home-markerWhen using alternate sub-buffer,
term-scroll-endBottom-most line (inclusive) of the scrolling region.
term-scroll-show-maximum-outputControls how interpreter output causes window to scroll.
term-scroll-snap-to-bottomControl whether to keep the prompt at the bottom of the window.
term-scroll-startTop-most line (inclusive) of the scrolling region.
term-scroll-to-bottom-on-outputControls whether interpreter output causes window to scroll.
term-scroll-with-deleteIf t, forward scrolling should be implemented by delete to
term-set-terminal-sizeIf non-nil, set the LINES and COLUMNS environment variables.
term-signals-menuSignals menu for Term mode.
term-start-line-column(current-column) at start of screen line, or nil if unknown.
term-suppress-hard-newlineNon-nil means interpreter should not break long lines with newlines.
term-term-nameName to use for TERM.
term-termcap-formatTermcap capabilities supported.
term-terminal-menuTerminal menu for Term mode.

Defined functions (143)

ansi-term(PROGRAM &optional NEW-BUFFER-NAME)
make-term(NAME PROGRAM &optional STARTFILE &rest SWITCHES)
serial-mode-line-config-menu(EVENT)
serial-mode-line-config-menu-1(EVENT)
serial-mode-line-speed-menu(EVENT)
serial-mode-line-speed-menu-1(EVENT)
serial-nice-speed-history()
serial-port-is-file-p()
serial-read-name()
serial-read-speed()
serial-speed()
serial-supported-or-barf()
serial-term(PORT SPEED &optional LINE-MODE)
term(PROGRAM)
term--bash-needs-EMACSp()
term--color-as-hex(FOR-FOREGROUND)
term--filter-buffer-substring(CONTENT)
term--handle-colors-list(PARAMETERS)
term--reset-scroll-region()
term--unwrap-visible-long-lines(WIDTH)
term--update-term-menu(&optional FORCE)
term--xterm-paste(EVENT)
term-adjust-current-row-cache(DELTA)
term-after-pmark-p()
term-ansi-make-term(NAME PROGRAM &optional STARTFILE &rest SWITCHES)
term-args(STRING BEGIN END)
term-arguments(STRING NTH MTH)
term-backward-matching-input(REGEXP N)
term-bol(ARG)
term-buffer-vertical-motion(COUNT)
term-char-mode()
term-check-proc(BUFFER)
term-check-source(FNAME)
term-command-hook(STRING)
term-continue-subjob()
term-copy-old-input()
term-delchar-or-maybe-eof(ARG)
term-delete-chars(COUNT)
term-delete-lines(LINES)
term-delim-arg(ARG)
term-directory(DIRECTORY)
term-display-buffer-line(BUFFER LINE)
term-display-line(TRUE-FILE LINE)
term-down(DOWN &optional CHECK-FOR-SCROLL)
term-dynamic-complete()
term-dynamic-complete-as-filename()
term-dynamic-complete-filename()
term-dynamic-list-completions(COMPLETIONS)
term-dynamic-list-filename-completions()
term-dynamic-list-input-ring()
term-emulate-terminal(PROC STR)
term-erase-in-display(KIND)
term-erase-in-line(KIND)
term-exec(BUFFER NAME COMMAND STARTFILE SWITCHES)
term-exec-1(NAME BUFFER COMMAND SWITCHES)
term-extract-string()
term-forward-matching-input(REGEXP N)
term-generate-db-directory()
term-get-old-input-default()
term-get-source(PROMPT PREV-DIR/FILE SOURCE-MODES MUSTMATCH-P)
term-goto(ROW COL)
term-goto-process-mark-maybe()
term-handle-ansi-escape(PROC PARAMS CHAR &optional PRIVATE)
term-handle-ansi-terminal-messages(MESSAGE)
term-handle-colors-array(PARAMETER)
term-handle-exit(PROCESS-NAME MSG)
term-handle-scroll(DOWN)
term-how-many-region(REGEXP BEG END)
term-insert-char(CHAR COUNT)
term-insert-lines(LINES)
term-insert-spaces(COUNT)
term-interrupt-subjob()
term-kill-input()
term-kill-output()
term-kill-subjob()
term-line-mode()
term-line-mode-buffer-read-only-update()
term-magic-space(ARG)
term-match-partial-filename()
term-mode()
term-mouse-paste(CLICK)
term-move-columns(DELTA)
term-move-to-column(COLUMN)
term-next-input(ARG)
term-next-matching-input(REGEXP N)
term-next-matching-input-from-input(N)
term-next-prompt(N)
term-pager-back-line(LINES)
term-pager-back-page(ARG)
term-pager-continue(NEW-COUNT)
term-pager-help()
term-pager-line(LINES)
term-pager-menu(ARG1)
term-pager-page(ARG)
term-paste()
term-previous-input(ARG)
term-previous-input-string(ARG)
term-previous-matching-input(REGEXP N)
term-previous-matching-input-from-input(N)
term-previous-matching-input-string(REGEXP ARG)
term-previous-matching-input-string-position(REGEXP ARG &optional START)
term-previous-prompt(N)
term-proc-query(PROC STR)
term-process-mark()
term-quit-subjob()
term-read-input-ring(&optional SILENT)
term-read-noecho(PROMPT &optional STARS)
term-regexp-arg(PROMPT)
term-replace-by-expanded-filename()
term-replace-by-expanded-history(&optional SILENT)
term-replace-by-expanded-history-before-point(SILENT)
term-reset-size(HEIGHT WIDTH)
term-reset-terminal()
term-search-arg(ARG)
term-search-start(ARG)
term-send-eof()
term-send-function-key()
term-send-input()
term-send-invisible(STR &optional PROC)
term-send-raw()
term-send-raw-string(CHARS)
term-send-region(PROC START END)
term-send-string(PROC STR)
term-sentinel(PROC MSG)
term-set-escape-char(KEY)
term-set-goto-process-mark()
term-set-scroll-region(TOP BOTTOM)
term-show-maximum-output()
term-show-output()
term-signals-menu(ARG1)
term-simple-send(PROC STRING)
term-skip-prompt()
term-source-default(PREVIOUS-DIR/FILE SOURCE-MODES)
term-start-output-log(NAME)
term-stop-output-log()
term-stop-subjob()
term-switch-to-alternate-sub-buffer(SET)
term-terminal-menu(ARG1)
term-vertical-motion(COUNT)
term-watch-for-password-prompt(STRING)
term-within-quotes(BEG END)
term-word(WORD-CHARS)
term-write-input-ring()

Defined faces (23)

termDefault face to use in Term mode.
term-boldDefault face to use for bold text.
term-color-blackFace used to render black color code.
term-color-blueFace used to render blue color code.
term-color-bright-blackFace used to render bright black color code.
term-color-bright-blueFace used to render bright blue color code.
term-color-bright-cyanFace used to render bright cyan color code.
term-color-bright-greenFace used to render bright green color code.
term-color-bright-magentaFace used to render bright magenta color code.
term-color-bright-redFace used to render bright red color code.
term-color-bright-whiteFace used to render bright white color code.
term-color-bright-yellowFace used to render bright yellow color code.
term-color-cyanFace used to render cyan color code.
term-color-greenFace used to render green color code.
term-color-magentaFace used to render magenta color code.
term-color-redFace used to render red color code.
term-color-whiteFace used to render white color code.
term-color-yellowFace used to render yellow color code.
term-faintDefault face to use for faint text.
term-fast-blinkDefault face to use for rapidly blinking text.
term-italicDefault face to use for italic text.
term-slow-blinkDefault face to use for slowly blinking text.
term-underlineDefault face to use for underlined text.