Processes
*********

In the terminology of operating systems, a process is a space in which a program can execute.  Emacs runs in a process.  Emacs Lisp programs can invoke other programs in processes of their own.  These are called subprocesses or child processes of the Emacs process, which is their parent process.

A subprocess of Emacs may be synchronous or asynchronous, depending on how it is created.  When you create a synchronous subprocess, the Lisp program waits for the subprocess to terminate before continuing execution.  When you create an asynchronous subprocess, it can run in parallel with the Lisp program.  This kind of subprocess is represented within Emacs by a Lisp object which is also called a ``process''.  Lisp programs can use this object to communicate with the subprocess or to control it.  For example, you can send signals, obtain status information, receive output from the process, or send input to it.

In addition to processes that run programs, Lisp programs can open connections of several types to devices or processes running on the same machine or on other machines.  The supported connection types are: TCP and UDP network connections, serial port connections, and pipe connections.  Each such connection is also represented by a process object.

 -- Function: processp object
     This function returns t if OBJECT represents an Emacs process object, nil otherwise.  The process object can represent a subprocess running a program or a connection of any supported type.

In addition to subprocesses of the current Emacs session, you can also access other processes running on your machine.  See System Processes.

Functions that Create Subprocesses
==================================

There are three primitives that create a new subprocess in which to run a program.  One of them, make-process, creates an asynchronous process and returns a process object (see Asynchronous Processes). The other two, call-process and call-process-region, create a synchronous process and do not return a process object (see Synchronous Processes).  There are various higher-level functions that make use of these primitives to run particular types of process.

Synchronous and asynchronous processes are explained in the following sections.  Since the three functions are all called in a similar fashion, their common arguments are described here.

In all cases, the functions specify the program to be run.  An error is signaled if the file is not found or cannot be executed.  If the file name is relative, the variable exec-path contains a list of directories to search.  Emacs initializes exec-path when it starts up, based on the value of the environment variable PATH. The standard file name constructs, ~, ., and .., are interpreted as usual in exec-path, but environment variable substitutions ($HOME, etc.) are not recognized; use substitute-in-file-name to perform them (see File Name Expansion).  nil in this list refers to default-directory.

Executing a program can also try adding suffixes to the specified name:

 -- User Option: exec-suffixes
     This variable is a list of suffixes (strings) to try adding to the specified program file name.  The list should include "" if you want the name to be tried exactly as specified.  The default value is system-dependent.

Please note: The argument PROGRAM contains only the name of the program file; it may not contain any command-line arguments.  You must use a separate argument, ARGS, to provide those, as described below.

Each of the subprocess-creating functions has a BUFFER-OR-NAME argument that specifies where the output from the program will go.  It should be a buffer or a buffer name; if it is a buffer name, that will create the buffer if it does not already exist.  It can also be nil, which says to discard the output, unless a custom filter function handles it.  (see Filter Functions, and Read and Print.)  Normally, you should avoid having multiple processes send output to the same buffer because their output would be intermixed randomly.  For synchronous processes, you can send the output to a file instead of a buffer (and the corresponding argument is therefore more appropriately called DESTINATION).  By default, both standard output and standard error streams go to the same destination, but all the 3 primitives allow optionally to direct the standard error stream to a different destination.

All three of the subprocess-creating functions allow to specify command-line arguments for the process to run. For call-process and call-process-region, these come in the form of a &rest argument, ARGS.  For make-process, both the program to run and its command-line arguments are specified as a list of strings.  The command-line arguments must all be strings, and they are supplied to the program as separate argument strings.  Wildcard characters and other shell constructs have no special meanings in these strings, since the strings are passed directly to the specified program.

The subprocess inherits its environment from Emacs, but you can specify overrides for it with process-environment.  See System Environment.  The subprocess gets its current directory from the value of default-directory.

 -- Variable: exec-directory
     The value of this variable is a string, the name of a directory that contains programs that come with GNU Emacs and are intended for Emacs to invoke.  The program movemail is an example of such a program; Rmail uses it to fetch new mail from an inbox.

 -- User Option: exec-path
     The value of this variable is a list of directories to search for programs to run in subprocesses.  Each element is either the name of a directory (i.e., a string), or nil, which stands for the default directory (which is the value of default-directory). See executable-find, for the details of this search.

     The value of exec-path is used by call-process and start-process when the PROGRAM argument is not an absolute file name.

     Generally, you should not modify exec-path directly.  Instead, ensure that your PATH environment variable is set appropriately before starting Emacs.  Trying to modify exec-path independently of PATH can lead to confusing results.

 -- Function: exec-path
     This function is an extension of the variable exec-path.  If default-directory indicates a remote directory, this function returns a list of directories used for searching programs on the respective remote host.  In case of a local default-directory, the function returns just the value of the variable exec-path.

When starting a program that is part of the Emacs distribution, you must take into account that the program may have been renamed in order to comply with executable naming restrictions present on the system.

Instead of starting ctags, for example, you should specify the value of ctags-program-name instead.  Likewise, instead of starting movemail, you must start movemail-program-name, and the same goes for etags, hexl, emacsclient, and ebrowse.

Shell Arguments
===============

Lisp programs sometimes need to run a shell and give it a command that contains file names that were specified by the user.  These programs ought to be able to support any valid file name.  But the shell gives special treatment to certain characters, and if these characters occur in the file name, they will confuse the shell.  To handle these characters, use the function shell-quote-argument:

 -- Function: shell-quote-argument argument &optional posix
     This function returns a string that represents, in shell syntax, an argument whose actual contents are ARGUMENT.  It should work reliably to concatenate the return value into a shell command and then pass it to a shell for execution.

     Precisely what this function does depends on your operating system.  The function is designed to work with the syntax of your system's standard shell; if you use an unusual shell, you will need to redefine this function.  See Security Considerations.

          ;; This example shows the behavior on GNU and Unix systems.
          (shell-quote-argument "foo > bar")
               => "foo\\ \\>\\ bar"

          ;; This example shows the behavior on MS-DOS and MS-Windows.
          (shell-quote-argument "foo > bar")
               => "\"foo > bar\""

     Here's an example of using shell-quote-argument to construct a shell command:

          (concat "diff -u "
                  (shell-quote-argument oldfile)
                  " "
                  (shell-quote-argument newfile))

     If the optional POSIX argument is non-nil, ARGUMENT is quoted according to POSIX shell quoting rules, regardless of the system’s shell.  This is useful when your shell could run on a remote host, which requires a POSIX shell in general.

          (shell-quote-argument "foo > bar" (file-remote-p default-directory))

The following two functions are useful for combining a list of individual command-line argument strings into a single string, and taking a string apart into a list of individual command-line arguments.  These functions are mainly intended for converting user input in the minibuffer, a Lisp string, into a list of string arguments to be passed to make-process, call-process or start-process, or for converting such lists of arguments into a single Lisp string to be presented in the minibuffer or echo area. Note that if a shell is involved (e.g., if using call-process-shell-command), arguments should still be protected by shell-quote-argument; combine-and-quote-strings is not intended to protect special characters from shell evaluation.

 -- Function: split-string-shell-command string
     This function splits STRING into substrings, respecting double and single quotes, as well as backslash quoting.

          (split-string-shell-command "ls /tmp/'foo bar'")
               => ("ls" "/tmp/foo bar")

 -- Function: split-string-and-unquote string &optional separators
     This function splits STRING into substrings at matches for the regular expression SEPARATORS, like split-string does (see Creating Strings); in addition, it removes quoting from the substrings.  It then makes a list of the substrings and returns it.

     If SEPARATORS is omitted or nil, it defaults to "\\s-+", which is a regular expression that matches one or more characters with whitespace syntax (see Syntax Class Table).

     This function supports two types of quoting: enclosing a whole string in double quotes "...", and quoting individual characters with a backslash escape \.  The latter is also used in Lisp strings, so this function can handle those as well.

 -- Function: combine-and-quote-strings list-of-strings &optional separator
     This function concatenates LIST-OF-STRINGS into a single string, quoting each string as necessary.  It also sticks the SEPARATOR string between each pair of strings; if SEPARATOR is omitted or nil, it defaults to " ".  The return value is the resulting string.

     The strings in LIST-OF-STRINGS that need quoting are those that include SEPARATOR as their substring.  Quoting a string encloses it in double quotes "...".  In the simplest case, if you are consing a command from the individual command-line arguments, every argument that includes embedded blanks will be quoted.

Creating a Synchronous Process
==============================

After a synchronous process is created, Emacs waits for the process to terminate before continuing.  Starting Dired on GNU or Unix (On other systems, Emacs uses a Lisp emulation of ls; see Contents of Directories.) is an example of this: it runs ls in a synchronous process, then modifies the output slightly.  Because the process is synchronous, the entire directory listing arrives in the buffer before Emacs tries to do anything with it.

While Emacs waits for the synchronous subprocess to terminate, the user can quit by typing C-g.  The first C-g tries to kill the subprocess with a SIGINT signal; but it waits until the subprocess actually terminates before quitting.  If during that time the user types another C-g, that kills the subprocess instantly with SIGKILL and quits immediately (except on MS-DOS, where killing other processes doesn't work).  See Quitting.

The synchronous subprocess functions return an indication of how the process terminated.

The output from a synchronous subprocess is generally decoded using a coding system, much like text read from a file.  The input sent to a subprocess by call-process-region is encoded using a coding system, much like text written into a file.  See Coding Systems.

 -- Function: call-process program &optional infile destination display &rest args
     This function calls PROGRAM and waits for it to finish.

     The current working directory of the subprocess is set to the current buffer's value of default-directory if that is local (as determined by unhandled-file-name-directory), or "~" otherwise. If you want to run a process in a remote directory use process-file.

     The standard input for the new process comes from file INFILE if INFILE is not nil, and from the null device otherwise. The argument DESTINATION says where to put the process output. Here are the possibilities:

     a buffer
          Insert the output in that buffer, before point.  This includes both the standard output stream and the standard error stream of the process.

     a buffer name (a string)
          Insert the output in a buffer with that name, before point.

     t
          Insert the output in the current buffer, before point.

     nil
          Discard the output.

     0
          Discard the output, and return nil immediately without waiting for the subprocess to finish.

          In this case, the process is not truly synchronous, since it can run in parallel with Emacs; but you can think of it as synchronous in that Emacs is essentially finished with the subprocess as soon as this function returns.

          MS-DOS doesn't support asynchronous subprocesses, so this option doesn't work there.

     (:file FILE-NAME)
          Send the output to the file name specified, overwriting it if it already exists.

     (REAL-DESTINATION ERROR-DESTINATION)
          Keep the standard output stream separate from the standard error stream; deal with the ordinary output as specified by REAL-DESTINATION, and dispose of the error output according to ERROR-DESTINATION. If ERROR-DESTINATION is nil, that means to discard the error output, t means mix it with the ordinary output, and a string specifies a file name to redirect error output into.

          You can't directly specify a buffer to put the error output in; that is too difficult to implement.  But you can achieve this result by sending the error output to a temporary file and then inserting the file into a buffer when the subprocess finishes.

     If DISPLAY is non-nil, then call-process redisplays the buffer as output is inserted.  (However, if the coding system chosen for decoding output is undecided, meaning deduce the encoding from the actual data, then redisplay sometimes cannot continue once non-ASCII characters are encountered.  There are fundamental reasons why it is hard to fix this; see Output from Processes.)

     Otherwise the function call-process does no redisplay, and the results become visible on the screen only when Emacs redisplays that buffer in the normal course of events.

     The remaining arguments, ARGS, are strings that specify command line arguments for the program.  Each string is passed to PROGRAM as a separate argument.

     The value returned by call-process (unless you told it not to wait) indicates the reason for process termination.  A number gives the exit status of the subprocess; 0 means success, and any other value means failure.  If the process terminated with a signal, call-process returns a string describing the signal.  If you told call-process not to wait, it returns nil.

     In the examples below, the buffer foo is current.

          (call-process "pwd" nil t)
               => 0

          ---------- Buffer: foo ----------
          /home/lewis/manual
          ---------- Buffer: foo ----------

          (call-process "grep" nil "bar" nil "lewis" "/etc/passwd")
               => 0

          ---------- Buffer: bar ----------
          lewis:x:1001:1001:Bil Lewis,,,,:/home/lewis:/bin/bash

          ---------- Buffer: bar ----------

     Here is an example of the use of call-process, as used to be found in the definition of the insert-directory function:

          (call-process insert-directory-program nil t nil switches
                        (if full-directory-p
                            (concat (file-name-as-directory file) ".")
                          file))

 -- Function: process-file program &optional infile buffer display &rest args
     This function processes files synchronously in a separate process.  It is similar to call-process, but may invoke a file name handler based on the value of the variable default-directory, which specifies the current working directory of the subprocess.

     The arguments are handled in almost the same way as for call-process, with the following differences:

     Some file name handlers may not support all combinations and forms of the arguments INFILE, BUFFER, and DISPLAY.  For example, some file name handlers might behave as if DISPLAY were nil, regardless of the value actually passed.  As another example, some file name handlers might not support separating standard output and error output by way of the BUFFER argument.

     If a file name handler is invoked, it determines the program to run based on the first argument PROGRAM.  For instance, suppose that a handler for remote files is invoked.  Then the path that is used for searching for the program might be different from exec-path.

     The second argument INFILE may invoke a file name handler.  The file name handler could be different from the handler chosen for the process-file function itself.  (For example, default-directory could be on one remote host, and INFILE on a different remote host.  Or default-directory could be non-special, whereas INFILE is on a remote host.)

     If BUFFER is a list of the form (REAL-DESTINATION ERROR-DESTINATION), and ERROR-DESTINATION names a file, then the same remarks as for INFILE apply.

     The remaining arguments (ARGS) will be passed to the process verbatim.  Emacs is not involved in processing file names that are present in ARGS.  To avoid confusion, it may be best to avoid absolute file names in ARGS, but rather to specify all file names as relative to default-directory.  The function file-relative-name is useful for constructing such relative file names.  Alternatively, you can use file-local-name (see Magic File Names) to obtain an absolute file name as seen from the remote host's perspective.

 -- Variable: process-file-side-effects
     This variable indicates whether a call of process-file changes remote files.

     By default, this variable is always set to t, meaning that a call of process-file could potentially change any file on a remote host.  When set to nil, a file name handler could optimize its behavior with respect to remote file attribute caching.

     You should only ever change this variable with a let-binding; never with setq.

 -- User Option: process-file-return-signal-string
     This user option indicates whether a call of process-file returns a string describing the signal interrupting a remote process.

     When a process returns an exit code greater than 128, it is interpreted as a signal.  process-file requires to return a string describing this signal.

     Since there are processes violating this rule, returning exit codes greater than 128 which are not bound to a signal, process-file returns always the exit code as natural number for remote processes. Setting this user option to non-nil forces process-file to interpret such exit codes as signals, and to return a corresponding string.

 -- Function: call-process-region start end program &optional delete destination display &rest args
     This function sends the text from START to END as standard input to a process running PROGRAM.  It deletes the text sent if DELETE is non-nil; this is useful when DESTINATION is t, to insert the output in the current buffer in place of the input.

     The arguments DESTINATION and DISPLAY control what to do with the output from the subprocess, and whether to update the display as it comes in.  For details, see the description of call-process, above.  If DESTINATION is the integer 0, call-process-region discards the output and returns nil immediately, without waiting for the subprocess to finish (this only works if asynchronous subprocesses are supported; i.e., not on MS-DOS).

     The remaining arguments, ARGS, are strings that specify command line arguments for the program.

     The return value of call-process-region is just like that of call-process: nil if you told it to return without waiting; otherwise, a number or string which indicates how the subprocess terminated.

     In the following example, we use call-process-region to run the cat utility, with standard input being the first five characters in buffer foo (the word input).  cat copies its standard input into its standard output.  Since the argument DESTINATION is t, this output is inserted in the current buffer.

          ---------- Buffer: foo ----------
          input-!-
          ---------- Buffer: foo ----------

          (call-process-region 1 6 "cat" nil t)
               => 0

          ---------- Buffer: foo ----------
          inputinput-!-
          ---------- Buffer: foo ----------

     For example, the shell-command-on-region command uses call-shell-region in a manner similar to this:

          (call-shell-region
           start end
           command              ; shell command
           nil                  ; do not delete region
           buffer)              ; send output to buffer

 -- Function: call-process-shell-command command &optional infile destination display
     This function executes the shell command COMMAND synchronously. The other arguments are handled as in call-process.  An old calling convention allowed passing any number of additional arguments after DISPLAY, which were concatenated to COMMAND; this is still supported, but strongly discouraged.

 -- Function: process-file-shell-command command &optional infile destination display
     This function is like call-process-shell-command, but uses process-file internally.  Depending on default-directory, COMMAND can be executed also on remote hosts.  An old calling convention allowed passing any number of additional arguments after DISPLAY, which were concatenated to COMMAND; this is still supported, but strongly discouraged.

 -- Function: call-shell-region start end command &optional delete destination
     This function sends the text from START to END as standard input to an inferior shell running COMMAND.  This function is similar than call-process-region, with process being a shell. The arguments delete, destination and the return value are like in call-process-region. Note that this function doesn't accept additional arguments.

 -- Function: shell-command-to-string command
     This function executes COMMAND (a string) as a shell command, then returns the command's output as a string.

 -- Function: process-lines program &rest args
     This function runs PROGRAM, waits for it to finish, and returns its output as a list of strings.  Each string in the list holds a single line of text output by the program; the end-of-line characters are stripped from each line.  The arguments beyond PROGRAM, ARGS, are strings that specify command-line arguments with which to run the program.

     If PROGRAM exits with a non-zero exit status, this function signals an error.

     This function works by calling call-process, so program output is decoded in the same way as for call-process.

 -- Function: process-lines-ignore-status program &rest args
     This function is just like process-lines, but does not signal an error if PROGRAM exits with a non-zero exit status.

Creating an Asynchronous Process
================================

In this section, we describe how to create an asynchronous process.  After an asynchronous process is created, it runs in parallel with Emacs, and Emacs can communicate with it using the functions described in the following sections (see Input to Processes, and see Output from Processes).  Note that process communication is only partially asynchronous: Emacs sends and receives data to and from a process only when those functions are called.

An asynchronous process is controlled either via a pty (pseudo-terminal) or a pipe.  The choice of pty or pipe is made when creating the process, by default based on the value of the variable process-connection-type (see below).  If available, ptys are usually preferable for processes visible to the user, as in Shell mode, because they allow for job control (C-c, C-z, etc.) between the process and its children, and because interactive programs treat ptys as terminal devices, whereas pipes don't support these features.  However, for subprocesses used by Lisp programs for internal purposes (i.e., no user interaction with the subprocess is required), where significant amounts of data need to be exchanged between the subprocess and the Lisp program, it is often better to use a pipe, because pipes are more efficient.  Also, the total number of ptys is limited on many systems, and it is good not to waste them unnecessarily.

 -- Function: make-process &rest args
     This function is the basic low-level primitive for starting asynchronous subprocesses.  It returns a process object representing the subprocess.  Compared to the more high-level start-process, described below, it takes keyword arguments, is more flexible, and allows to specify process filters and sentinels in a single call.

     The arguments ARGS are a list of keyword/argument pairs. Omitting a keyword is always equivalent to specifying it with value nil.  Here are the meaningful keywords:

     :name NAME
          Use the string NAME as the process name; if a process with this name already exists, then NAME is modified (by appending <1>, etc.) to be unique.

     :buffer BUFFER
          Use BUFFER as the process buffer.  If the value is nil, the subprocess is not associated with any buffer.

     :command COMMAND
          Use COMMAND as the command line of the process.  The value should be a list starting with the program's executable file name, followed by strings to give to the program as its arguments.  If the first element of the list is nil, Emacs opens a new pseudoterminal (pty) and associates its input and output with BUFFER, without actually running any program; the rest of the list elements are ignored in that case.

     :coding CODING
          If CODING is a symbol, it specifies the coding system to be used for both reading and writing of data from and to the connection.  If CODING is a cons cell (DECODING . ENCODING), then DECODING will be used for reading and ENCODING for writing.  The coding system used for encoding the data written to the program is also used for encoding the command-line arguments (but not the program itself, whose file name is encoded as any other file name; see file-name-coding-system).

          If CODING is nil, the default rules for finding the coding system will apply.  See Default Coding Systems.

     :connection-type TYPE
          Initialize the type of device used to communicate with the subprocess. Possible values are pty to use a pty, pipe to use a pipe, or nil to use the default derived from the value of the process-connection-type variable.  If TYPE is a cons cell (INPUT . OUTPUT), then INPUT will be used for standard input and OUTPUT for standard output (and standard error if :stderr is nil).

          On systems where ptys are not available (MS-Windows), this parameter is ignored, and pipes are used unconditionally.

     :noquery QUERY-FLAG
          Initialize the process query flag to QUERY-FLAG. See Query Before Exit.

     :stop STOPPED
          If provided, STOPPED must be nil; it is an error to use any non-nil value.  The :stop key is ignored otherwise and is retained for compatibility with other process types such as pipe processes.  Asynchronous subprocesses never start in the stopped state.

     :filter FILTER
          Initialize the process filter to FILTER.  If not specified, a default filter will be provided, which can be overridden later. See Filter Functions.

     :sentinel SENTINEL
          Initialize the process sentinel to SENTINEL.  If not specified, a default sentinel will be used, which can be overridden later. See Sentinels.

     :stderr STDERR
          Associate STDERR with the standard error of the process.  A non-nil value should be either a buffer or a pipe process created with make-pipe-process, described below.  If STDERR is nil, standard error is mixed with standard output, and both are sent to BUFFER or FILTER.

          If STDERR is a buffer, Emacs will create a pipe process, the standard error process.  This process will have the default filter (see Filter Functions), sentinel (see Sentinels), and coding systems (see Default Coding Systems).  On the other hand, it will use QUERY-FLAG as its query-on-exit flag (see Query Before Exit).  It will be associated with the STDERR buffer (see Process Buffers) and send its output (which is the standard error of the main process) there.  To get the process object for the standard error process, pass the STDERR buffer to get-buffer-process.

          If STDERR is a pipe process, Emacs will use it as standard error process for the new process.

     :file-handler FILE-HANDLER
          If FILE-HANDLER is non-nil, then look for a file name handler for the current buffer's default-directory, and invoke that file name handler to make the process.  If there is no such handler, proceed as if FILE-HANDLER were nil.

     The original argument list, modified with the actual connection information, is available via the process-contact function.

     The current working directory of the subprocess is set to the current buffer's value of default-directory if that is local (as determined by unhandled-file-name-directory), or ~ otherwise.  If you want to run a process in a remote directory, pass :file-handler t to make-process.  In that case, the current working directory is the local name component of default-directory (as determined by file-local-name).

     Depending on the implementation of the file name handler, it might not be possible to apply FILTER or SENTINEL to the resulting process object.  The :stderr argument cannot be a pipe process, file name handlers do not support pipe processes for this.  A buffer as :stderr argument is accepted, its contents is shown without the use of pipe processes.  See Filter Functions, Sentinels, and Accepting Output.

     Some file name handlers may not support make-process.  In such cases, this function does nothing and returns nil.

 -- Function: make-pipe-process &rest args
     This function creates a bidirectional pipe which can be attached to a child process.  This is useful with the :stderr keyword of make-process.  The function returns a process object.

     The arguments ARGS are a list of keyword/argument pairs. Omitting a keyword is always equivalent to specifying it with value nil.

     Here are the meaningful keywords:

     :name NAME
          Use the string NAME as the process name.  As with make-process, it is modified if necessary to make it unique.

     :buffer BUFFER
          Use BUFFER as the process buffer.

     :coding CODING
          If CODING is a symbol, it specifies the coding system to be used for both reading and writing of data from and to the connection.  If CODING is a cons cell (DECODING . ENCODING), then DECODING will be used for reading and ENCODING for writing.

          If CODING is nil, the default rules for finding the coding system will apply.  See Default Coding Systems.

     :noquery QUERY-FLAG
          Initialize the process query flag to QUERY-FLAG. See Query Before Exit.

     :stop STOPPED
          If STOPPED is non-nil, start the process in the stopped state.  In the stopped state, a pipe process does not accept incoming data, but you can send outgoing data.  The stopped state is set by stop-process and cleared by continue-process (see Signals to Processes).

     :filter FILTER
          Initialize the process filter to FILTER.  If not specified, a default filter will be provided, which can be changed later. See Filter Functions.

     :sentinel SENTINEL
          Initialize the process sentinel to SENTINEL.  If not specified, a default sentinel will be used, which can be changed later. See Sentinels.

     The original argument list, modified with the actual connection information, is available via the process-contact function.

 -- Function: start-process name buffer-or-name program &rest args
     This function is a higher-level wrapper around make-process, exposing an interface that is similar to call-process.  It creates a new asynchronous subprocess and starts the specified PROGRAM running in it.  It returns a process object that stands for the new subprocess in Lisp.  The argument NAME specifies the name for the process object; as with make-process, it is modified if necessary to make it unique.  The buffer BUFFER-OR-NAME is the buffer to associate with the process.

     If PROGRAM is nil, Emacs opens a new pseudoterminal (pty) and associates its input and output with BUFFER-OR-NAME, without creating a subprocess.  In that case, the remaining arguments ARGS are ignored.

     The rest of ARGS are strings that specify command line arguments for the subprocess.

     In the example below, the first process is started and runs (rather, sleeps) for 100 seconds (the output buffer foo is created immediately).  Meanwhile, the second process is started, and given the name my-process<1> for the sake of uniqueness.  It inserts the directory listing at the end of the buffer foo, before the first process finishes.  Then it finishes, and a message to that effect is inserted in the buffer.  Much later, the first process finishes, and another message is inserted in the buffer for it.

          (start-process "my-process" "foo" "sleep" "100")
               => #<process my-process>

          (start-process "my-process" "foo" "ls" "-l" "/bin")
               => #<process my-process<1>>

          ---------- Buffer: foo ----------
          total 8336
          -rwxr-xr-x 1 root root 971384 Mar 30 10:14 bash
          -rwxr-xr-x 1 root root 146920 Jul  5  2011 bsd-csh
          ...
          -rwxr-xr-x 1 root root 696880 Feb 28 15:55 zsh4

          Process my-process<1> finished

          Process my-process finished
          ---------- Buffer: foo ----------

 -- Function: start-file-process name buffer-or-name program &rest args
     Like start-process, this function starts a new asynchronous subprocess running PROGRAM in it, and returns its process object.

     The difference from start-process is that this function may invoke a file name handler based on the value of default-directory. This handler ought to run PROGRAM, perhaps on the local host, perhaps on a remote host that corresponds to default-directory. In the latter case, the local part of default-directory becomes the working directory of the process.

     This function does not try to invoke file name handlers for PROGRAM or for the rest of ARGS.  For that reason, if PROGRAM or any of ARGS use the remote-file syntax (see Magic File Names), they must be converted either to file names relative to default-directory, or to names that identify the files locally on the remote host, by running them through file-local-name.

     Depending on the implementation of the file name handler, it might not be possible to apply process-filter or process-sentinel to the resulting process object.  See Filter Functions, and Sentinels.

     Some file name handlers may not support start-file-process (for example the function ange-ftp-hook-function).  In such cases, this function does nothing and returns nil.

 -- Function: start-process-shell-command name buffer-or-name command
     This function is like start-process, except that it uses a shell to execute the specified COMMAND.  The argument COMMAND is a shell command string.  The variable shell-file-name specifies which shell to use.

     The point of running a program through the shell, rather than directly with make-process or start-process, is so that you can employ shell features such as wildcards in the arguments.  It follows that if you include any arbitrary user-specified arguments in the command, you should quote them with shell-quote-argument first, so that any special shell characters do not have their special shell meanings.  See Shell Arguments.  Of course, when executing commands based on user input you should also consider the security implications.

 -- Function: start-file-process-shell-command name buffer-or-name command
     This function is like start-process-shell-command, but uses start-file-process internally.  Because of this, COMMAND can also be executed on remote hosts, depending on default-directory.

 -- Variable: process-connection-type
     This variable controls the type of device used to communicate with asynchronous subprocesses.  If it is non-nil, then ptys are used, when available.  Otherwise, pipes are used.

     The value of process-connection-type takes effect when make-process or start-process is called.  So you can specify how to communicate with one subprocess by binding the variable around the call to these functions.

     Note that the value of this variable is ignored when make-process is called with a non-nil value of the :stderr parameter; in that case, Emacs will communicate with the process using pipes.  It is also ignored if ptys are unavailable (MS-Windows).

          (let ((process-connection-type nil))  ; use a pipe
            (start-process ...))

     To determine whether a given subprocess actually got a pipe or a pty, use the function process-tty-name (see Process Information).

 -- Variable: process-error-pause-time
     If a process sentinel/filter function has an error, Emacs will (by default) pause Emacs for process-error-pause-time seconds after displaying this error, so that users will see the error in question. However, this can lead to situations where Emacs becomes unresponsive (if there's a lot of these errors happening), so this can be disabled by setting process-error-pause-time to 0.

Deleting Processes
==================

Deleting a process disconnects Emacs immediately from the subprocess.  Processes are deleted automatically after they terminate, but not necessarily right away.  You can delete a process explicitly at any time.  If you explicitly delete a terminated process before it is deleted automatically, no harm results.  Deleting a running process sends a signal to terminate it (and its child processes, if any), and calls the process sentinel.  See Sentinels.

When a process is deleted, the process object itself continues to exist as long as other Lisp objects point to it.  All the Lisp primitives that work on process objects accept deleted processes, but those that do I/O or send signals will report an error.  The process mark continues to point to the same place as before, usually into a buffer where output from the process was being inserted.

 -- User Option: delete-exited-processes
     This variable controls automatic deletion of processes that have terminated (due to calling exit or to a signal).  If it is nil, then they continue to exist until the user runs list-processes.  Otherwise, they are deleted immediately after they exit.

 -- Function: delete-process &optional process
     This function deletes a process, killing it with a SIGKILL signal if the process was running a program.  The argument may be a process, the name of a process, a buffer, or the name of a buffer.  (A buffer or buffer-name stands for the process that get-buffer-process returns, and a missing or nil PROCESS means that the current buffer's process should be killed.)  Calling delete-process on a running process terminates it, updates the process status, and runs the sentinel immediately.  If the process has already terminated, calling delete-process has no effect on its status, or on the running of its sentinel (which will happen sooner or later).

     If the process object represents a network, serial, or pipe connection, its status changes to closed; otherwise, it changes to signal, unless the process already exited.  See process-status.

          (delete-process "*shell*")
               => nil

Process Information
===================

Several functions return information about processes.

 -- Command: list-processes &optional query-only buffer
     This command displays a listing of all living processes.  In addition, it finally deletes any process whose status was Exited or Signaled.  It returns nil.

     The processes are shown in a buffer named *Process List* (unless you specify otherwise using the optional argument BUFFER), whose major mode is Process Menu mode.

     If QUERY-ONLY is non-nil, it only lists processes whose query flag is non-nil.  See Query Before Exit.

 -- Function: process-list
     This function returns a list of all processes that have not been deleted.

          (process-list)
               => (#<process display-time> #<process shell>)

 -- Function: num-processors &optional query
     This function returns the number of processors, a positive integer. Each usable thread execution unit counts as a processor. By default, the count includes the number of available processors, which you can override by setting the OMP_NUM_THREADS environment variable of OpenMP (https://www.openmp.org/spec-html/5.1/openmpse59.html). If the optional argument QUERY is current, this function ignores OMP_NUM_THREADS; if QUERY is all, this function also counts processors that are on the system but are not available to the current process.

 -- Function: get-process name
     This function returns the process named NAME (a string), or nil if there is none.  The argument NAME can also be a process object, in which case it is returned.

          (get-process "shell")
               => #<process shell>

 -- Function: process-command process
     This function returns the command that was executed to start PROCESS.  This is a list of strings, the first string being the program executed and the rest of the strings being the arguments that were given to the program.  For a network, serial, or pipe connection, this is either nil, which means the process is running or t (process is stopped).

          (process-command (get-process "shell"))
               => ("bash" "-i")

 -- Function: process-contact process &optional key no-block
     This function returns information about how a network, a serial, or a pipe connection was set up.  When KEY is nil, it returns (HOSTNAME SERVICE) for a network connection, (PORT SPEED) for a serial connection, and t for a pipe connection.  For an ordinary child process, this function always returns t when called with a nil KEY.

     If KEY is t, the value is the complete status information for the connection, server, serial port, or pipe; that is, the list of keywords and values specified in make-network-process, make-serial-process, or make-pipe-process, except that some of the values represent the current status instead of what you specified.

     For a network process, the values include (see make-network-process for a complete list):

     :buffer
          The associated value is the process buffer.

     :filter
          The associated value is the process filter function.  See Filter Functions.

     :sentinel
          The associated value is the process sentinel function.  See Sentinels.

     :remote
          In a connection, the address in internal format of the remote peer.

     :local
          The local address, in internal format.

     :service
          In a server, if you specified t for SERVICE, this value is the actual port number.

     :local and :remote are included even if they were not specified explicitly in make-network-process.

     For a serial connection, see make-serial-process and serial-process-configure for the list of keys.  For a pipe connection, see make-pipe-process for the list of keys.

     If KEY is a keyword, the function returns the value corresponding to that keyword.

     If PROCESS is a non-blocking network stream that hasn't been fully set up yet, then this function will block until that has happened.  If given the optional NO-BLOCK parameter, this function will return nil instead of blocking.

 -- Function: process-id process
     This function returns the PID of PROCESS.  This is an integral number that distinguishes the process PROCESS from all other processes running on the same computer at the current time.  The PID of a process is chosen by the operating system kernel when the process is started and remains constant as long as the process exists.  For network, serial, and pipe connections, this function returns nil.

 -- Function: process-name process
     This function returns the name of PROCESS, as a string.

 -- Function: process-status process-name
     This function returns the status of PROCESS-NAME as a symbol. The argument PROCESS-NAME must be a process, a buffer, or a process name (a string).

     The possible values for an actual subprocess are:

     run
          for a process that is running.

     stop
          for a process that is stopped but continuable.

     exit
          for a process that has exited.

     signal
          for a process that has received a fatal signal.

     open
          for a network, serial, or pipe connection that is open.

     closed
          for a network, serial, or pipe connection that is closed.  Once a connection is closed, you cannot reopen it, though you might be able to open a new connection to the same place.

     connect
          for a non-blocking connection that is waiting to complete.

     failed
          for a non-blocking connection that has failed to complete.

     listen
          for a network server that is listening.

     nil
          if PROCESS-NAME is not the name of an existing process.

          (process-status (get-buffer "*shell*"))
               => run

     For a network, serial, or pipe connection, process-status returns one of the symbols open, stop, or closed. The latter means that the other side closed the connection, or Emacs did delete-process.  The value stop means that stop-process was called on the connection.

 -- Function: process-live-p process
     This function returns non-nil if PROCESS is alive.  A process is considered alive if its status is run, open, listen, connect or stop.

 -- Function: process-type process
     This function returns the symbol network for a network connection or server, serial for a serial port connection, pipe for a pipe connection, or real for a subprocess created for running a program.

 -- Function: process-exit-status process
     This function returns the exit status of PROCESS or the signal number that killed it.  (Use the result of process-status to determine which of those it is.)  If PROCESS has not yet terminated, the value is 0.  For network, serial, and pipe connections that are already closed, the value is either 0 or 256, depending on whether the connection was closed normally or abnormally.

 -- Function: process-tty-name process &optional stream
     This function returns the terminal name that PROCESS is using for its communication with Emacs---or nil if it is using pipes instead of a pty (see process-connection-type in Asynchronous Processes).  By default, this function returns the terminal name if any of PROCESS's standard streams use a terminal.  If STREAM is one of stdin, stdout, or stderr, this function returns the terminal name (or nil, as above) that PROCESS uses for that stream specifically.  You can use this to determine whether a particular stream uses a pipe or a pty.

     If PROCESS represents a program running on a remote host, this function returns the local terminal name that communicates with PROCESS; you can get the terminal name used by that program on the remote host with the process property remote-tty.  If PROCESS represents a network, serial, or pipe connection, this function always returns nil.

 -- Function: process-coding-system process
     This function returns a cons cell (DECODE . ENCODE), describing the coding systems in use for decoding output from, and encoding input to, PROCESS (see Coding Systems).

 -- Function: set-process-coding-system process &optional decoding-system encoding-system
     This function specifies the coding systems to use for subsequent output from and input to PROCESS.  It will use DECODING-SYSTEM to decode subprocess output, and ENCODING-SYSTEM to encode subprocess input.

Every process also has a property list that you can use to store miscellaneous values associated with the process.

 -- Function: process-get process propname
     This function returns the value of the PROPNAME property of PROCESS.

 -- Function: process-put process propname value
     This function sets the value of the PROPNAME property of PROCESS to VALUE.

 -- Function: process-plist process
     This function returns the process plist of PROCESS.

 -- Function: set-process-plist process plist
     This function sets the process plist of PROCESS to PLIST.

Sending Input to Processes
==========================

Asynchronous subprocesses receive input when it is sent to them by Emacs, which is done with the functions in this section.  You must specify the process to send input to, and the input data to send.  If the subprocess runs a program, the data appears on the standard input of that program; for connections, the data is sent to the connected device or program.

Some operating systems have limited space for buffered input in a pty.  On these systems, Emacs sends an EOF periodically amidst the other characters, to force them through.  For most programs, these EOFs do no harm.

Subprocess input is normally encoded using a coding system before the subprocess receives it, much like text written into a file.  You can use set-process-coding-system to specify which coding system to use (see Process Information).  Otherwise, the coding system comes from coding-system-for-write, if that is non-nil; or else from the defaulting mechanism (see Default Coding Systems).

Sometimes the system is unable to accept input for that process, because the input buffer is full.  When this happens, the send functions wait a short while, accepting output from subprocesses, and then try again.  This gives the subprocess a chance to read more of its pending input and make space in the buffer.  It also allows filters (including the one currently running), sentinels and timers to run---so take account of that in writing your code.

In these functions, the PROCESS argument can be a process or the name of a process, or a buffer or buffer name (which stands for a process via get-buffer-process).  nil means the current buffer's process.

 -- Function: process-send-string process string
     This function sends PROCESS the contents of STRING as standard input.  It returns nil.  For example, to make a Shell buffer list files:

          (process-send-string "shell<1>" "ls\n")
               => nil

 -- Function: process-send-region process start end
     This function sends the text in the region defined by START and END as standard input to PROCESS.

     An error is signaled unless both START and END are integers or markers that indicate positions in the current buffer.  (It is unimportant which number is larger.)

 -- Function: process-send-eof &optional process
     This function makes PROCESS see an end-of-file in its input.  The EOF comes after any text already sent to it. The function returns PROCESS.

          (process-send-eof "shell")
               => "shell"

 -- Function: process-running-child-p &optional process
     This function will tell you whether a PROCESS, which must not be a connection but a real subprocess, has given control of its terminal to a child process of its own.  If this is true, the function returns the numeric ID of the foreground process group of PROCESS; it returns nil if Emacs can be certain that this is not so.  The value is t if Emacs cannot tell whether this is true.  This function signals an error if PROCESS is a network, serial, or pipe connection, or if the subprocess is not active.

Sending Signals to Processes
============================

Sending a signal to a subprocess is a way of interrupting its activities.  There are several different signals, each with its own meaning.  The set of signals and their names is defined by the operating system.  For example, the signal SIGINT means that the user has typed C-c, or that some analogous thing has happened.

Each signal has a standard effect on the subprocess.  Most signals kill the subprocess, but some stop (or resume) execution instead.  Most signals can optionally be handled by programs; if the program handles the signal, then we can say nothing in general about its effects.

You can send signals explicitly by calling the functions in this section.  Emacs also sends signals automatically at certain times: killing a buffer sends a SIGHUP signal to all its associated processes; killing Emacs sends a SIGHUP signal to all remaining processes.  (SIGHUP is a signal that usually indicates that the user ``hung up the phone'', i.e., disconnected.)

Each of the signal-sending functions takes two optional arguments: PROCESS and CURRENT-GROUP.

The argument PROCESS must be either a process, a process name, a buffer, a buffer name, or nil.  A buffer or buffer name stands for a process through get-buffer-process.  nil stands for the process associated with the current buffer.  Except with stop-process and continue-process, an error is signaled if PROCESS does not identify an active process, or if it represents a network, serial, or pipe connection.

The argument CURRENT-GROUP is a flag that makes a difference when you are running a job-control shell as an Emacs subprocess.  If it is non-nil, then the signal is sent to the current process-group of the terminal that Emacs uses to communicate with the subprocess.  If the process is a job-control shell, this means the shell's current subjob.  If CURRENT-GROUP is nil, the signal is sent to the process group of the immediate subprocess of Emacs.  If the subprocess is a job-control shell, this is the shell itself.  If CURRENT-GROUP is lambda, the signal is sent to the process-group that owns the terminal, but only if it is not the shell itself.

The flag CURRENT-GROUP has no effect when a pipe is used to communicate with the subprocess, because the operating system does not support the distinction in the case of pipes.  For the same reason, job-control shells won't work when a pipe is used.  See process-connection-type in Asynchronous Processes.

 -- Function: interrupt-process &optional process current-group
     This function interrupts the process PROCESS by sending the signal SIGINT.  Outside of Emacs, typing the interrupt character (normally C-c on some systems, and DEL on others) sends this signal.  When the argument CURRENT-GROUP is non-nil, you can think of this function as typing C-c on the terminal by which Emacs talks to the subprocess.

 -- Command: kill-process &optional process current-group
     This command kills the process PROCESS by sending the signal SIGKILL.  This signal kills the subprocess immediately, and cannot be handled by the subprocess.  Interactively, it'll prompt the user for a process name, defaulting to the process (if any) in the current buffer.

 -- Function: quit-process &optional process current-group
     This function sends the signal SIGQUIT to the process PROCESS.  This signal is the one sent by the quit character (usually C-\) when you are not inside Emacs.

 -- Function: stop-process &optional process current-group
     This function stops the specified PROCESS.  If it is a real subprocess running a program, it sends the signal SIGTSTP to that subprocess.  If PROCESS represents a network, serial, or pipe connection, this function inhibits handling of the incoming data from the connection; for a network server, this means not accepting new connections.  Use continue-process to resume normal execution.

     Outside of Emacs, on systems with job control, the stop character (usually C-z) normally sends the SIGTSTP signal to a subprocess.  When CURRENT-GROUP is non-nil, you can think of this function as typing C-z on the terminal Emacs uses to communicate with the subprocess.

 -- Function: continue-process &optional process current-group
     This function resumes execution of the process PROCESS.  If it is a real subprocess running a program, it sends the signal SIGCONT to that subprocess; this presumes that PROCESS was stopped previously.  If PROCESS represents a network, serial, or pipe connection, this function resumes handling of the incoming data from the connection.  For serial connections, data that arrived during the time the process was stopped might be lost.

 -- Command: signal-process process signal &optional remote
     This function sends a signal to process PROCESS.  The argument SIGNAL specifies which signal to send; it should be an integer, or a symbol whose name is a signal.

     The PROCESS argument can be a system process ID (an integer); that allows you to send signals to processes that are not children of Emacs.  See System Processes.

     If PROCESS is a process object which contains the property remote-pid, or PROCESS is a number and REMOTE is a remote file name, PROCESS is interpreted as process on the respective remote host, which will be the process to signal.

Sometimes, it is necessary to send a signal to a non-local asynchronous process.  This is possible by writing an own interrupt-process or signal-process implementation. This function must be added then to interrupt-process-functions or signal-process-functions, respectively.

 -- Variable: interrupt-process-functions
     This variable is a list of functions to be called for interrupt-process.  The arguments of the functions are the same as for interrupt-process.  These functions are called in the order of the list, until one of them returns non-nil.  The default function, which shall always be the last in this list, is internal-default-interrupt-process.

     This is the mechanism, how Tramp implements interrupt-process.

 -- Variable: signal-process-functions
     This variable is a list of functions to be called for signal-process.  The arguments of the functions are the same as for signal-process.  These functions are called in the order of the list, until one of them returns non-nil.  The default function, which shall always be the last in this list, is internal-default-signal-process.

     This is the mechanism, how Tramp implements signal-process.

Receiving Output from Processes
===============================

The output that an asynchronous subprocess writes to its standard output stream is passed to a function called the filter function.  The default filter function simply inserts the output into a buffer, which is called the associated buffer of the process (see Process Buffers).  If the process has no buffer then the default filter discards the output.

If the subprocess writes to its standard error stream, by default the error output is also passed to the process filter function. Alternatively, you could use the :stderr parameter with a non-nil value in a call to make-process (see make-process) to make the destination of the error output separate from the standard output.

When a subprocess terminates, Emacs reads any pending output, then stops reading output from that subprocess.  Therefore, if the subprocess has children that are still live and still producing output, Emacs won't receive that output.

Output from a subprocess can arrive only while Emacs is waiting: when reading terminal input (see the function waiting-for-user-input-p), in sit-for and sleep-for (see Waiting), in accept-process-output (see Accepting Output), and in functions which send data to processes (see Input to Processes). This minimizes the problem of timing errors that usually plague parallel programming.  For example, you can safely create a process and only then specify its buffer or filter function; no output can arrive before you finish, if the code in between does not call any primitive that waits.

 -- Variable: process-adaptive-read-buffering
     On some systems, when Emacs reads the output from a subprocess, the output data is read in very small blocks, potentially resulting in very poor performance.  This behavior can be remedied to some extent by setting the variable process-adaptive-read-buffering to a non-nil value (the default), as it will automatically delay reading from such processes, thus allowing them to produce more output before Emacs tries to read it.

Process Buffers
---------------

A process can (and usually does) have an associated buffer, which is an ordinary Emacs buffer that is used for two purposes: storing the output from the process, and deciding when to kill the process.  You can also use the buffer to identify a process to operate on, since in normal practice only one process is associated with any given buffer. Many applications of processes also use the buffer for editing input to be sent to the process, but this is not built into Emacs Lisp.

By default, process output is inserted in the associated buffer. (You can change this by defining a custom filter function, see Filter Functions.)  The position to insert the output is determined by the process-mark, which is then updated to point to the end of the text just inserted.  Usually, but not always, the process-mark is at the end of the buffer.

Killing the associated buffer of a process also kills the process. Emacs asks for confirmation first, if the process's process-query-on-exit-flag is non-nil (see Query Before Exit).  This confirmation is done by the function process-kill-buffer-query-function, which is run from kill-buffer-query-functions (see Killing Buffers).

 -- Function: process-buffer process
     This function returns the associated buffer of the specified PROCESS.

          (process-buffer (get-process "shell"))
               => #<buffer *shell*>

 -- Function: process-mark process
     This function returns the process marker for PROCESS, which is the marker that says where to insert output from the process.

     If PROCESS does not have a buffer, process-mark returns a marker that points nowhere.

     The default filter function uses this marker to decide where to insert process output, and updates it to point after the inserted text. That is why successive batches of output are inserted consecutively.

     Custom filter functions normally should use this marker in the same fashion. For an example of a filter function that uses process-mark, see Process Filter Example.

     When the user is expected to enter input in the process buffer for transmission to the process, the process marker separates the new input from previous output.

 -- Function: set-process-buffer process buffer
     This function sets the buffer associated with PROCESS to BUFFER.  If BUFFER is nil, the process becomes associated with no buffer; if non-nil, the process mark will be set to point to the end of BUFFER.

 -- Function: get-buffer-process buffer-or-name
     This function returns a nondeleted process associated with the buffer specified by BUFFER-OR-NAME.  If there are several processes associated with it, this function chooses one (currently, the one most recently created, but don't count on that).  Deletion of a process (see delete-process) makes it ineligible for this function to return.

     It is usually a bad idea to have more than one process associated with the same buffer.

          (get-buffer-process "*shell*")
               => #<process shell>

     Killing the process's buffer deletes the process, which kills the subprocess with a SIGHUP signal (see Signals to Processes).

If the process's buffer is displayed in a window, your Lisp program may wish to tell the process the dimensions of that window, so that the process could adapt its output to those dimensions, much as it adapts to the screen dimensions.  The following functions allow communicating this kind of information to processes; however, not all systems support the underlying functionality, so it is best to provide fallbacks, e.g., via command-line arguments or environment variables.

 -- Function: set-process-window-size process height width
     Tell PROCESS that its logical window size has dimensions WIDTH by HEIGHT, in character units.  If this function succeeds in communicating this information to the process, it returns t; otherwise it returns nil.

When windows that display buffers associated with process change their dimensions, the affected processes should be told about these changes. By default, when the window configuration changes, Emacs will automatically call set-process-window-size on behalf of every process whose buffer is displayed in a window, passing it the smallest dimensions of all the windows displaying the process's buffer.  This works via window-configuration-change-hook (see Window Hooks), which is told to invoke the function that is the value of the variable window-adjust-process-window-size-function for each process whose buffer is displayed in at least one window.  You can customize this behavior by setting the value of that variable.

 -- User Option: window-adjust-process-window-size-function
     The value of this variable should be a function of two arguments: a process and the list of windows displaying the process's buffer.  When the function is called, the process's buffer is the current buffer. The function should return a cons cell (WIDTH . HEIGHT) that describes the dimensions of the logical process window to be passed via a call to set-process-window-size.  The function can also return nil, in which case Emacs will not call set-process-window-size for this process.

     Emacs supplies two predefined values for this variable: window-adjust-process-window-size-smallest, which returns the smallest of all the dimensions of the windows that display a process's buffer; and window-adjust-process-window-size-largest, which returns the largest dimensions.  For more complex strategies, write your own function.

     This variable can be buffer-local.

If the process has the adjust-window-size-function property (see Process Information), its value overrides the global and buffer-local values of window-adjust-process-window-size-function.

Process Filter Functions
------------------------

A process filter function is a function that receives the standard output from the associated process.  All output from that process is passed to the filter.  The default filter simply outputs directly to the process buffer.

By default, the error output from the process, if any, is also passed to the filter function, unless the destination for the standard error stream of the process was separated from the standard output when the process was created.  Emacs will only call the filter function during certain function calls.  See Output from Processes. Note that if any of those functions are called by the filter, the filter may be called recursively.

A filter function must accept two arguments: the associated process and a string, which is output just received from it.  The function is then free to do whatever it chooses with the output.

Quitting is normally inhibited within a filter function---otherwise, the effect of typing C-g at command level or to quit a user command would be unpredictable.  If you want to permit quitting inside a filter function, bind inhibit-quit to nil.  In most cases, the right way to do this is with the macro with-local-quit.  See Quitting.

If an error happens during execution of a filter function, it is caught automatically, so that it doesn't stop the execution of whatever program was running when the filter function was started.  However, if debug-on-error is non-nil, errors are not caught. This makes it possible to use the Lisp debugger to debug filter functions.  See Debugger.  If an error is caught, Emacs pauses for process-error-pause-time seconds so that the user sees the error.  See Asynchronous Processes

Many filter functions sometimes (or always) insert the output in the process's buffer, mimicking the actions of the default filter. Such filter functions need to make sure that they save the current buffer, select the correct buffer (if different) before inserting output, and then restore the original buffer. They should also check whether the buffer is still alive, update the process marker, and in some cases update the value of point.  Here is how to do these things:

     (defun ordinary-insertion-filter (proc string)
       (when (buffer-live-p (process-buffer proc))
         (with-current-buffer (process-buffer proc)
           (let ((moving (= (point) (process-mark proc))))

             (save-excursion
               ;; Insert the text, advancing the process marker.
               (goto-char (process-mark proc))
               (insert string)
               (set-marker (process-mark proc) (point)))
             (if moving (goto-char (process-mark proc)))))))

To make the filter force the process buffer to be visible whenever new text arrives, you could insert a line like the following just before the with-current-buffer construct:

     (display-buffer (process-buffer proc))

To force point to the end of the new output, no matter where it was previously, eliminate the variable moving from the example and call goto-char unconditionally.  Note that this doesn't necessarily move the window point.  The default filter actually uses insert-before-markers which moves all markers, including the window point.  This may move unrelated markers, so it's generally better to move the window point explicitly, or set its insertion type to t (see Window Point).

Note that Emacs automatically saves and restores the match data while executing filter functions.  See Match Data.

The output to the filter may come in chunks of any size.  A program that produces the same output twice in a row may send it as one batch of 200 characters one time, and five batches of 40 characters the next.  If the filter looks for certain text strings in the subprocess output, make sure to handle the case where one of these strings is split across two or more batches of output; one way to do this is to insert the received text into a temporary buffer, which can then be searched.

 -- Function: set-process-filter process filter
     This function gives PROCESS the filter function FILTER. If FILTER is nil, it gives the process the default filter, which inserts the process output into the process buffer.  If FILTER is t, Emacs stops accepting output from the process, unless it's a network server process that listens for incoming connections.

 -- Function: process-filter process
     This function returns the filter function of PROCESS.

In case the process's output needs to be passed to several filters, you can use add-function to combine an existing filter with a new one. See Advising Functions.

Here is an example of the use of a filter function:

     (defun keep-output (process output)
        (setq kept (cons output kept)))
          => keep-output

     (setq kept nil)
          => nil

     (set-process-filter (get-process "shell") 'keep-output)
          => keep-output

     (process-send-string "shell" "ls ~/other\n")
          => nil
     kept
          => ("lewis@slug:$ "

     "FINAL-W87-SHORT.MSS    backup.otl              kolstad.mss~
     address.txt             backup.psf              kolstad.psf
     backup.bib~             david.mss               resume-Dec-86.mss~
     backup.err              david.psf               resume-Dec.psf
     backup.mss              dland                   syllabus.mss
     "
     "#backups.mss#          backup.mss~             kolstad.mss
     ")

Decoding Process Output
-----------------------

When Emacs writes process output directly into a multibyte buffer, it decodes the output according to the process output coding system. If the coding system is raw-text or no-conversion, Emacs converts the unibyte output to multibyte using string-to-multibyte, and inserts the resulting multibyte text.

You can use set-process-coding-system to specify which coding system to use (see Process Information).  Otherwise, the coding system comes from coding-system-for-read, if that is non-nil; or else from the defaulting mechanism (see Default Coding Systems).  If the text output by a process contains null bytes, Emacs by default uses no-conversion for it; see inhibit-null-byte-detection, for how to control this behavior.

Warning: Coding systems such as undecided, which determine the coding system from the data, do not work entirely reliably with asynchronous subprocess output.  This is because Emacs has to process asynchronous subprocess output in batches, as it arrives.  Emacs must try to detect the proper coding system from one batch at a time, and this does not always work.  Therefore, if at all possible, specify a coding system that determines both the character code conversion and the end of line conversion---that is, one like latin-1-unix, rather than undecided or latin-1.

When Emacs calls a process filter function, it provides the process output as a multibyte string or as a unibyte string according to the process's filter coding system.  Emacs decodes the output according to the process output coding system, which usually produces a multibyte string, except for coding systems such as binary and raw-text.

Accepting Output from Processes
-------------------------------

Output from asynchronous subprocesses normally arrives only while Emacs is waiting for some sort of external event, such as elapsed time or terminal input.  Occasionally it is useful in a Lisp program to explicitly permit output to arrive at a specific point, or even to wait until output arrives from a process.

 -- Function: accept-process-output &optional process seconds millisec just-this-one
     This function allows Emacs to read pending output from processes.  The output is given to their filter functions.  If PROCESS is non-nil then this function does not return until some output has been received from PROCESS or PROCESS has closed the connection.

     The arguments SECONDS and MILLISEC let you specify timeout periods.  The former specifies a period measured in seconds and the latter specifies one measured in milliseconds.  The two time periods thus specified are added together, and accept-process-output returns after that much time, even if there is no subprocess output.

     The argument MILLISEC is obsolete (and should not be used), because SECONDS can be floating point to specify waiting a fractional number of seconds.  If SECONDS is 0, the function accepts whatever output is pending but does not wait.

     If PROCESS is a process, and the argument JUST-THIS-ONE is non-nil, only output from that process is handled, suspending output from other processes until some output has been received from that process or the timeout expires.  If JUST-THIS-ONE is an integer, also inhibit running timers.  This feature is generally not recommended, but may be necessary for specific applications, such as speech synthesis.

     The function accept-process-output returns non-nil if it got output from PROCESS, or from any process if PROCESS is nil; this can occur even after a process has exited if the corresponding connection contains buffered data.  The function returns nil if the timeout expired or the connection was closed before output arrived.

If a connection from a process contains buffered data, accept-process-output can return non-nil even after the process has exited.  Therefore, although the following loop:

     ;; This loop contains a bug.
     (while (process-live-p process)
       (accept-process-output process))

will often read all output from PROCESS, it has a race condition and can miss some output if process-live-p returns nil while the connection still contains data.  Better is to write the loop like this:

     (while (accept-process-output process))

If you have passed a non-nil STDERR to make-process, it will have a standard error process. See Asynchronous Processes.  In that case, waiting for process output from the main process doesn't wait for output from the standard error process.  To make sure you have received both all of standard output and all of standard error from a process, use the following code:

     (while (accept-process-output process))
     (while (accept-process-output stderr-process))

If you passed a buffer to the STDERR argument of make-process, you still have to wait for the standard error process, like so:

     (let* ((stdout (generate-new-buffer "stdout"))
            (stderr (generate-new-buffer "stderr"))
            (process (make-process :name "test"
                                   :command '("my-program")
                                   :buffer stdout
                                   :stderr stderr))
            (stderr-process (get-buffer-process stderr)))
       (unless (and process stderr-process)
         (error "Process unexpectedly nil"))
       (while (accept-process-output process))
       (while (accept-process-output stderr-process)))

Only when both accept-process-output forms return nil, you can be sure that the process has exited and Emacs has read all its output.

Reading pending standard error from a process running on a remote host is not possible this way.

Processes and Threads
---------------------

Because threads were a relatively late addition to Emacs Lisp, and due to the way dynamic binding was sometimes used in conjunction with accept-process-output, by default a process is locked to the thread that created it.  When a process is locked to a thread, output from the process can only be accepted by that thread.

A Lisp program can specify to which thread a process is to be locked, or instruct Emacs to unlock a process, in which case its output can be processed by any thread.  Only a single thread will wait for output from a given process at one time---once one thread begins waiting for output, the process is temporarily locked until accept-process-output or sit-for returns.

If the thread exits, all the processes locked to it are unlocked.

 -- Function: process-thread process
     Return the thread to which PROCESS is locked.  If PROCESS is unlocked, return nil.

 -- Function: set-process-thread process thread
     Set the locking thread of PROCESS to THREAD.  THREAD may be nil, in which case the process is unlocked.

Sentinels: Detecting Process Status Changes
===========================================

A process sentinel is a function that is called whenever the associated process changes status for any reason, including signals (whether sent by Emacs or caused by the process's own actions) that terminate, stop, or continue the process.  The process sentinel is also called if the process exits.  The sentinel receives two arguments: the process for which the event occurred, and a string describing the type of event.

If no sentinel function was specified for a process, it will use the default sentinel function, which inserts a message in the process's buffer with the process name and the string describing the event.

The string describing the event looks like one of the following (but this is not an exhaustive list of event strings):

  * "finished\n".

  * "deleted\n".

  * "exited abnormally with code EXITCODE (core dumped)\n". The ``core dumped'' part is optional, and only appears if the process dumped core.

  * "failed with code FAIL-CODE\n".

  * "SIGNAL-DESCRIPTION (core dumped)\n".  The SIGNAL-DESCRIPTION is a system-dependent textual description of a signal, e.g., "killed" for SIGKILL.  The ``core dumped'' part is optional, and only appears if the process dumped core.

  * "open from HOST-NAME\n".

  * "open\n".

  * "run\n".

  * "connection broken by remote peer\n".

A sentinel runs only while Emacs is waiting (e.g., for terminal input, or for time to elapse, or for process output).  This avoids the timing errors that could result from running sentinels at random places in the middle of other Lisp programs.  A program can wait, so that sentinels will run, by calling sit-for or sleep-for (see Waiting), or accept-process-output (see Accepting Output).  Emacs also allows sentinels to run when the command loop is reading input.  delete-process calls the sentinel when it terminates a running process.

Emacs does not keep a queue of multiple reasons to call the sentinel of one process; it records just the current status and the fact that there has been a change.  Therefore two changes in status, coming in quick succession, can call the sentinel just once.  However, process termination will always run the sentinel exactly once.  This is because the process status can't change again after termination.

Emacs explicitly checks for output from the process before running the process sentinel.  Once the sentinel runs due to process termination, no further output can arrive from the process.

A sentinel that writes the output into the buffer of the process should check whether the buffer is still alive.  If it tries to insert into a dead buffer, it will get an error.  If the buffer is dead, (buffer-name (process-buffer PROCESS)) returns nil.

Quitting is normally inhibited within a sentinel---otherwise, the effect of typing C-g at command level or to quit a user command would be unpredictable.  If you want to permit quitting inside a sentinel, bind inhibit-quit to nil.  In most cases, the right way to do this is with the macro with-local-quit. See Quitting.

If an error happens during execution of a sentinel, it is caught automatically, so that it doesn't stop the execution of whatever programs was running when the sentinel was started.  However, if debug-on-error is non-nil,  errors are not caught. This makes it possible to use the Lisp debugger to debug the sentinel.  See Debugger.  If an error is caught, Emacs pauses for process-error-pause-time seconds so that the user sees the error.  See Asynchronous Processes

While a sentinel is running, the process sentinel is temporarily set to nil so that the sentinel won't run recursively. For this reason it is not possible for a sentinel to specify a new sentinel.

Note that Emacs automatically saves and restores the match data while executing sentinels.  See Match Data.

 -- Function: set-process-sentinel process sentinel
     This function associates SENTINEL with PROCESS.  If SENTINEL is nil, then the process will have the default sentinel, which inserts a message in the process's buffer when the process status changes.

     Changes in process sentinels take effect immediately---if the sentinel is slated to be run but has not been called yet, and you specify a new sentinel, the eventual call to the sentinel will use the new one.

          (defun msg-me (process event)
             (princ
               (format "Process: %s had the event '%s'" process event)))
          (set-process-sentinel (get-process "shell") 'msg-me)
               => msg-me

          (kill-process (get-process "shell"))
               -| Process: #<process shell> had the event 'killed'
               => #<process shell>

 -- Function: process-sentinel process
     This function returns the sentinel of PROCESS.

In case a process status changes need to be passed to several sentinels, you can use add-function to combine an existing sentinel with a new one. See Advising Functions.

 -- Function: waiting-for-user-input-p
     While a sentinel or filter function is running, this function returns non-nil if Emacs was waiting for keyboard input from the user at the time the sentinel or filter function was called, or nil if it was not.

Querying Before Exit
====================

When Emacs exits, it terminates all its subprocesses.  For subprocesses that run a program, it sends them the SIGHUP signal; connections are simply closed.  Because subprocesses may be doing valuable work, Emacs normally asks the user to confirm that it is ok to terminate them.  Each process has a query flag, which, if non-nil, says that Emacs should ask for confirmation before exiting and thus killing that process.  The default for the query flag is t, meaning do query.

 -- Function: process-query-on-exit-flag process
     This returns the query flag of PROCESS.

 -- Function: set-process-query-on-exit-flag process flag
     This function sets the query flag of PROCESS to FLAG.  It returns FLAG.

     Here is an example of using set-process-query-on-exit-flag on a shell process to avoid querying:

          (set-process-query-on-exit-flag (get-process "shell") nil)
               => nil

 -- User Option: confirm-kill-processes
     If this user option is set to t (the default), then Emacs asks for confirmation before killing processes on exit.  If it is nil, Emacs kills processes without confirmation, i.e., the query flag of all processes is ignored.

Accessing Other Processes
=========================

In addition to accessing and manipulating processes that are subprocesses of the current Emacs session, Emacs Lisp programs can also access other processes.  We call these system processes, to distinguish them from Emacs subprocesses.

Emacs provides several primitives for accessing system processes. Not all platforms support these primitives; on those which don't, these primitives return nil.

 -- Function: list-system-processes
     This function returns a list of all the processes running on the system.  Each process is identified by its PID, a numerical process ID that is assigned by the OS and distinguishes the process from all the other processes running on the same machine at the same time.

     If default-directory points to a remote host, processes of that host are returned.

 -- Function: process-attributes pid
     This function returns an alist of attributes for the process specified by its process ID PID.  Each association in the alist is of the form (KEY . VALUE), where KEY designates the attribute and VALUE is the value of that attribute.  The various attribute KEYs that this function can return are listed below. Not all platforms support all of these attributes; if an attribute is not supported, its association will not appear in the returned alist.

     If default-directory points to a remote host, PID is regarded as process of that host.

     euid
          The effective user ID of the user who invoked the process.  The corresponding VALUE is a number.  If the process was invoked by the same user who runs the current Emacs session, the value is identical to what user-uid returns (see User Identification).

     user
          User name corresponding to the process's effective user ID, a string.

     egid
          The group ID of the effective user ID, a number.

     group
          Group name corresponding to the effective user's group ID, a string.

     comm
          The name of the command that runs in the process.  This is a string that usually specifies the name of the executable file of the process, without the leading directories.  However, some special system processes can report strings that do not correspond to an executable file of a program.

     state
          The state code of the process.  This is a short string that encodes the scheduling state of the process.  Here's a list of the most frequently seen codes:

          "D"
               uninterruptible sleep (usually I/O)

          "R"
               running

          "S"
               interruptible sleep (waiting for some event)

          "T"
               stopped, e.g., by a job control signal

          "Z"
               zombie: a process that terminated, but was not reaped by its parent

          For the full list of the possible states, see the manual page of the ps command.

     ppid
          The process ID of the parent process, a number.

     pgrp
          The process group ID of the process, a number.

     sess
          The session ID of the process.  This is a number that is the process ID of the process's session leader.

     ttname
          A string that is the name of the process's controlling terminal.  On Unix and GNU systems, this is normally the file name of the corresponding terminal device, such as /dev/pts65.

     tpgid
          The numerical process group ID of the foreground process group that uses the process's terminal.

     minflt
          The number of minor page faults caused by the process since its beginning.  (Minor page faults are those that don't involve reading from disk.)

     majflt
          The number of major page faults caused by the process since its beginning.  (Major page faults require a disk to be read, and are thus more expensive than minor page faults.)

     cminflt
     cmajflt
          Like minflt and majflt, but include the number of page faults for all the child processes of the given process.

     utime
          Time spent by the process in the user context, for running the application's code.  The corresponding VALUE is a Lisp timestamp (see Time of Day).

     stime
          Time spent by the process in the system (kernel) context, for processing system calls.  The corresponding VALUE is a Lisp timestamp.

     time
          The sum of utime and stime.  The corresponding VALUE is a Lisp timestamp.

     cutime
     cstime
     ctime
          Like utime, stime, and time, but include the times of all the child processes of the given process.

     pri
          The numerical priority of the process.

     nice
          The nice value of the process, a number.  (Processes with smaller nice values get scheduled more favorably.)

     thcount
          The number of threads in the process.

     start
          The time when the process was started, as a Lisp timestamp.

     etime
          The time elapsed since the process started, as a Lisp timestamp.

     vsize
          The virtual memory size of the process, measured in kilobytes.

     rss
          The size of the process's resident set, the number of kilobytes occupied by the process in the machine's physical memory.

     pcpu
          The percentage of the CPU time used by the process since it started. The corresponding VALUE is a nonnegative floating-point number. Although in theory the number can exceed 100 on a multicore platform, it is usually less than 100 because Emacs is typically single-threaded.

     pmem
          The percentage of the total physical memory installed on the machine used by the process's resident set.  The value is a floating-point number between 0 and 100.

     args
          The command-line with which the process was invoked.  This is a string in which individual command-line arguments are separated by blanks; whitespace characters that are embedded in the arguments are quoted as appropriate for the system's shell: escaped by backslash characters on GNU and Unix, and enclosed in double quote characters on Windows. Thus, this command-line string can be directly used in primitives such as shell-command.

Transaction Queues
==================

You can use a transaction queue to communicate with a subprocess using transactions.  First use tq-create to create a transaction queue communicating with a specified process.  Then you can call tq-enqueue to send a transaction.

 -- Function: tq-create process
     This function creates and returns a transaction queue communicating with PROCESS.  The argument PROCESS should be a subprocess capable of sending and receiving streams of bytes.  It may be a child process, or it may be a TCP connection to a server, possibly on another machine.

 -- Function: tq-enqueue queue question regexp closure fn &optional delay-question
     This function sends a transaction to queue QUEUE.  Specifying the queue has the effect of specifying the subprocess to talk to.

     The argument QUESTION is the outgoing message that starts the transaction.  The argument FN is the function to call when the corresponding answer comes back; it is called with two arguments: CLOSURE, and the answer received.

     The argument REGEXP is a regular expression that should match text at the end of the entire answer, but nothing before; that's how tq-enqueue determines where the answer ends.

     If the argument DELAY-QUESTION is non-nil, delay sending this question until the process has finished replying to any previous questions.  This produces more reliable results with some processes.

 -- Function: tq-close queue
     Shut down transaction queue QUEUE, waiting for all pending transactions to complete, and then terminate the connection or child process.

Transaction queues are implemented by means of a filter function. See Filter Functions.

Network Connections
===================

Emacs Lisp programs can open stream (TCP) and datagram (UDP) network connections (see Datagrams) to other processes on the same machine or other machines. A network connection is handled by Lisp much like a subprocess, and is represented by a process object.  However, the process you are communicating with is not a child of the Emacs process, has no process ID, and you can't kill it or send it signals.  All you can do is send and receive data.  delete-process closes the connection, but does not kill the program at the other end; that program must decide what to do about closure of the connection.

Lisp programs can listen for connections by creating network servers.  A network server is also represented by a kind of process object, but unlike a network connection, the network server never transfers data itself.  When it receives a connection request, it creates a new network connection to represent the connection just made.  (The network connection inherits certain information, including the process plist, from the server.)  The network server then goes back to listening for more connection requests.

Network connections and servers are created by calling make-network-process with an argument list consisting of keyword/argument pairs, for example :server t to create a server process, or :type 'datagram to create a datagram connection.  See Low-Level Network, for details.  You can also use the open-network-stream function described below.

To distinguish the different types of processes, the process-type function returns the symbol network for a network connection or server, serial for a serial port connection, pipe for a pipe connection, or real for a real subprocess.

The process-status function returns open, closed, connect, stop, or failed for network connections.  For a network server, the status is always listen.  Except for stop, none of those values is possible for a real subprocess.  See Process Information.

You can stop and resume operation of a network process by calling stop-process and continue-process.  For a server process, being stopped means not accepting new connections.  (Up to 5 connection requests will be queued for when you resume the server; you can increase this limit, unless it is imposed by the operating system---see the :server keyword of make-network-process, Network Processes.)  For a network stream connection, being stopped means not processing input (any arriving input waits until you resume the connection).  For a datagram connection, some number of packets may be queued but input may be lost.  You can use the function process-command to determine whether a network connection or server is stopped; a non-nil value means yes.

Emacs can create encrypted network connections, using the built-in support for the GnuTLS Transport Layer Security Library; see the GnuTLS project page (https://www.gnu.org/software/gnutls/). If your Emacs was compiled with GnuTLS support, the function gnutls-available-p is defined and returns non-nil.  For more details, see Overview (The Emacs-GnuTLS manual). The open-network-stream function can transparently handle the details of creating encrypted connections for you, using whatever support is available.

 -- Function: open-network-stream name buffer host service &rest parameters
     This function opens a TCP connection, with optional encryption, and returns a process object that represents the connection.

     The NAME argument specifies the name for the process object.  It is modified as necessary to make it unique.

     The BUFFER argument is the buffer to associate with the connection.  Output from the connection is inserted in the buffer, unless you specify your own filter function to handle the output.  If BUFFER is nil, it means that the connection is not associated with any buffer.

     The arguments HOST and SERVICE specify where to connect to; HOST is the host name (a string), and SERVICE is the name of a defined network service (a string) or a port number (an integer like 80 or an integer string like "80").

     The remaining arguments PARAMETERS are keyword/argument pairs that are mainly relevant to encrypted connections:

     :nowait BOOLEAN
          If non-nil, try to make an asynchronous connection.

     :noquery QUERY-FLAG
          Initialize the process query flag to QUERY-FLAG. See Query Before Exit.

     :coding CODING
          Use this to set the coding systems used by the network process, in preference to binding coding-system-for-read or coding-system-for-write.  See Network Processes, for details.

     :type TYPE
          The type of connection.  Options are:

          plain
               An ordinary, unencrypted connection.

          tls
          ssl
               A TLS (Transport Layer Security) connection.

          nil
          network
               Start with a plain connection, and if parameters :success and :capability-command are supplied, try to upgrade to an encrypted connection via STARTTLS.  If that fails, retain the unencrypted connection.

          starttls
               As for nil, but if STARTTLS fails drop the connection.

          shell
               A shell connection.

     :always-query-capabilities BOOLEAN
          If non-nil, always ask for the server's capabilities, even when doing a plain connection.

     :capability-command CAPABILITY-COMMAND
          Command to query the host capabilities.  This can either be a string (which will then be sent verbatim to the server), or a function (called with a single parameter; the "greeting" from the server when connecting), and should return a string.

     :end-of-command REGEXP
     :end-of-capability REGEXP
          Regular expression matching the end of a command, or the end of the command CAPABILITY-COMMAND.  The latter defaults to the former.

     :starttls-function FUNCTION
          Function of one argument (the response to CAPABILITY-COMMAND), which returns either nil, or the command to activate STARTTLS if supported.

     :success REGEXP
          Regular expression matching a successful STARTTLS negotiation.

     :use-starttls-if-possible BOOLEAN
          If non-nil, do opportunistic STARTTLS upgrades even if Emacs doesn't have built-in TLS support.

     :warn-unless-encrypted BOOLEAN
          If non-nil, and :return-value is also non-nil, Emacs will warn if the connection isn't encrypted.  This is useful for protocols like IMAP and the like, where most users would expect the network traffic to be encrypted.

     :client-certificate LIST-OR-T
          Either a list of the form (KEY-FILE CERT-FILE), naming the certificate key file and certificate file itself, or t, meaning to query auth-source for this information (see auth-source (Emacs auth-source Library)).  Only used for TLS or STARTTLS.  To enable automatic queries of auth-source when :client-certificate is not specified customize network-stream-use-client-certificates to t.

     :return-list CONS-OR-NIL
          The return value of this function.  If omitted or nil, return a process object.  Otherwise, a cons of the form (PROCESS-OBJECT . PLIST), where PLIST has keywords:

          :greeting STRING-OR-NIL
               If non-nil, the greeting string returned by the host.

          :capabilities STRING-OR-NIL
               If non-nil, the host's capability string.

          :type SYMBOL
               The connection type: plain or tls.

     :shell-command STRING-OR-NIL
          If the connection type is shell, this parameter will be interpreted as a format-spec string that will be executed to make the connection.  The specs available are %s for the host name and %p for the port number.  For instance, if you want to first ssh to gateway before making a plain connection, then this parameter could be something like ssh gateway nc %s %p.

Network Servers
===============

You create a server by calling make-network-process (see Network Processes) with :server t.  The server will listen for connection requests from clients.  When it accepts a client connection request, that creates a new network connection, itself a process object, with the following parameters:

  * The connection's process name is constructed by concatenating the server process's NAME with a client identification string.  The client identification string for an IPv4 connection looks like <A.B.C.D:P>, which represents an address and port number.  Otherwise, it is a unique number in brackets, as in <NNN>.  The number is unique for each connection in the Emacs session.

  * If the server has a non-default filter, the connection process does not get a separate process buffer; otherwise, Emacs creates a new buffer for the purpose.  The buffer name is the server's buffer name or process name, concatenated with the client identification string.

     The server's process buffer value is never used directly, but the log function can retrieve it and use it to log connections by inserting text there.

  * The communication type and the process filter and sentinel are inherited from those of the server.  The server never directly uses its filter and sentinel; their sole purpose is to initialize connections made to the server.

  * The connection's process contact information is set according to the client's addressing information (typically an IP address and a port number). This information is associated with the process-contact keywords :host, :service, :remote.

  * The connection's local address is set up according to the port number used for the connection.

  * The client process's plist is initialized from the server's plist.

Datagrams
=========

A datagram connection communicates with individual packets rather than streams of data.  Each call to process-send sends one datagram packet (see Input to Processes), and each datagram received results in one call to the filter function.

The datagram connection doesn't have to talk with the same remote peer all the time.  It has a remote peer address which specifies where to send datagrams to.  Each time an incoming datagram is passed to the filter function, the peer address is set to the address that datagram came from; that way, if the filter function sends a datagram, it will go back to that place.  You can specify the remote peer address when you create the datagram connection using the :remote keyword.  You can change it later on by calling set-process-datagram-address.

 -- Function: process-datagram-address process
     If PROCESS is a datagram connection or server, this function returns its remote peer address.

 -- Function: set-process-datagram-address process address
     If PROCESS is a datagram connection or server, this function sets its remote peer address to ADDRESS.

Low-Level Network Access
========================

You can also create network connections by operating at a lower level than that of open-network-stream, using make-network-process.

make-network-process
--------------------

The basic function for creating network connections and network servers is make-network-process.  It can do either of those jobs, depending on the arguments you give it.

 -- Function: make-network-process &rest args
     This function creates a network connection or server and returns the process object that represents it.  The arguments ARGS are a list of keyword/argument pairs.  Omitting a keyword is always equivalent to specifying it with value nil, except for :coding, :filter-multibyte, and :reuseaddr.  Here are the meaningful keywords (those corresponding to network options are listed in the following section):

     :name NAME
          Use the string NAME as the process name.  It is modified if necessary to make it unique.

     :type TYPE
          Specify the communication type.  A value of nil specifies a stream connection (the default); datagram specifies a datagram connection; seqpacket specifies a sequenced packet stream connection.  Both connections and servers can be of these types.

     :server SERVER-FLAG
          If SERVER-FLAG is non-nil, create a server.  Otherwise, create a connection.  For a stream type server, SERVER-FLAG may be an integer, which then specifies the length of the queue of pending connections to the server.  The default queue length is 5.

     :host HOST
          Specify the host to connect to.  HOST should be a host name or Internet address, as a string, or the symbol local to specify the local host.  If you specify HOST for a server, it must specify a valid address for the local host, and only clients connecting to that address will be accepted.  When using local, by default IPv4 will be used, specify a FAMILY of ipv6 to override this.  To listen on all interfaces, specify an address of "0.0.0.0" for IPv4 or "::" for IPv6.  Note that on some operating systems, listening on "::" will also listen on IPv4, so attempting to then listen separately on IPv4 will result in EADDRINUSE errors ("Address already in use").

     :service SERVICE
          SERVICE specifies a port number to connect to; or, for a server, the port number to listen on.  It should be a service name like "https" that translates to a port number, or an integer like 443 or an integer string like "443" that specifies the port number directly.  For a server, it can also be t, which means to let the system select an unused port number.

     :family FAMILY
          FAMILY specifies the address (and protocol) family for communication.  nil means determine the proper address family automatically for the given HOST and SERVICE. local specifies a Unix socket, in which case HOST is ignored.  ipv4 and ipv6 specify to use IPv4 and IPv6, respectively.

     :use-external-socket USE-EXTERNAL-SOCKET
          If USE-EXTERNAL-SOCKET is non-nil use any sockets passed to Emacs on invocation instead of allocating one.  This is used by the Emacs server code to allow on-demand socket activation.  If Emacs wasn't passed a socket, this option is silently ignored.

     :local LOCAL-ADDRESS
          For a server process, LOCAL-ADDRESS is the address to listen on. It overrides FAMILY, HOST and SERVICE, so you might as well not specify them.

     :remote REMOTE-ADDRESS
          For a connection, REMOTE-ADDRESS is the address to connect to. It overrides FAMILY, HOST and SERVICE, so you might as well not specify them.

          For a datagram server, REMOTE-ADDRESS specifies the initial setting of the remote datagram address.

          The format of LOCAL-ADDRESS or REMOTE-ADDRESS depends on the address family:

            - An IPv4 address is represented as a five-element vector of four 8-bit integers and one 16-bit integer [A B C D P] corresponding to numeric IPv4 address A.B.C.D and port number P.

            - An IPv6 address is represented as a nine-element vector of 16-bit integers [A B C D E F G H P] corresponding to numeric IPv6 address A:B:C:D:E:F:G:H and port number P.

            - A local address is represented as a string, which specifies the address in the local address space.

            - An unsupported-family address is represented by a cons (F . AV), where F is the family number and AV is a vector specifying the socket address using one element per address data byte.  Do not rely on this format in portable code, as it may depend on implementation defined constants, data sizes, and data structure alignment.

     :nowait BOOL
          If BOOL is non-nil for a stream connection, return without waiting for the connection to complete.  When the connection succeeds or fails, Emacs will call the sentinel function, with a second argument matching "open" (if successful) or "failed".  The default is to block, so that make-network-process does not return until the connection has succeeded or failed.

          If you're setting up an asynchronous TLS connection, you have to also provide the :tls-parameters parameter (see below).

          Depending on the capabilities of Emacs, how asynchronous :nowait is may vary.  The three elements that may (or may not) be done asynchronously are domain name resolution, socket setup, and (for TLS connections) TLS negotiation.

          Many functions that interact with process objects, (for instance, process-datagram-address) rely on them at least having a socket before they can return a useful value.  These functions will block until the socket has achieved the desired status.  The recommended way of interacting with asynchronous sockets is to place a sentinel on the process, and not try to interact with it before it has changed status to "run".  That way, none of these functions will block.

     :tls-parameters
          When opening a TLS connection, this should be where the first element is the TLS type (which should either be gnutls-x509pki or gnutls-anon, and the remaining elements should form a keyword list acceptable for gnutls-boot.  (This keyword list can be obtained from the gnutls-boot-parameters function.)  The TLS connection will then be negotiated after completing the connection to the host.

     :stop STOPPED
          If STOPPED is non-nil, start the network connection or server in the stopped state.

     :buffer BUFFER
          Use BUFFER as the process buffer.

     :coding CODING
          Use CODING as the coding system for this process.  To specify different coding systems for decoding data from the connection and for encoding data sent to it, specify (DECODING . ENCODING) for CODING.

          If you don't specify this keyword at all, the default is to determine the coding systems from the data.

     :noquery QUERY-FLAG
          Initialize the process query flag to QUERY-FLAG. See Query Before Exit.

     :filter FILTER
          Initialize the process filter to FILTER.

     :filter-multibyte MULTIBYTE
          If MULTIBYTE is non-nil, strings given to the process filter are multibyte, otherwise they are unibyte.  The default is t.

     :sentinel SENTINEL
          Initialize the process sentinel to SENTINEL.

     :log LOG
          Initialize the log function of a server process to LOG.  The log function is called each time the server accepts a network connection from a client.  The arguments passed to the log function are SERVER, CONNECTION, and MESSAGE; where SERVER is the server process, CONNECTION is the new process for the connection, and MESSAGE is a string describing what has happened.

     :plist PLIST
          Initialize the process plist to PLIST.

     The original argument list, modified with the actual connection information, is available via the process-contact function.

Network Options
---------------

The following network options can be specified when you create a network process.  Except for :reuseaddr, you can also set or modify these options later, using set-network-process-option.

For a server process, the options specified with make-network-process are not inherited by the client connections, so you will need to set the necessary options for each child connection as it is created.

:bindtodevice DEVICE-NAME
     If DEVICE-NAME is a non-empty string identifying a network interface name (see network-interface-list), only handle packets received on that interface.  If DEVICE-NAME is nil (the default), handle packets received on any interface.

     Using this option may require special privileges on some systems.

:broadcast BROADCAST-FLAG
     If BROADCAST-FLAG is non-nil for a datagram process, the process will receive datagram packet sent to a broadcast address, and be able to send packets to a broadcast address.  This is ignored for a stream connection.

:dontroute DONTROUTE-FLAG
     If DONTROUTE-FLAG is non-nil, the process can only send to hosts on the same network as the local host.

:keepalive KEEPALIVE-FLAG
     If KEEPALIVE-FLAG is non-nil for a stream connection, enable exchange of low-level keep-alive messages.

:linger LINGER-ARG
     If LINGER-ARG is non-nil, wait for successful transmission of all queued packets on the connection before it is deleted (see delete-process).  If LINGER-ARG is an integer, it specifies the maximum time in seconds to wait for queued packets to be sent before closing the connection.  The default is nil, which means to discard unsent queued packets when the process is deleted.

:oobinline OOBINLINE-FLAG
     If OOBINLINE-FLAG is non-nil for a stream connection, receive out-of-band data in the normal data stream.  Otherwise, ignore out-of-band data.

:priority PRIORITY
     Set the priority for packets sent on this connection to the integer PRIORITY.  The interpretation of this number is protocol specific; such as setting the TOS (type of service) field on IP packets sent on this connection.  It may also have system dependent effects, such as selecting a specific output queue on the network interface.

:reuseaddr REUSEADDR-FLAG
     If REUSEADDR-FLAG is non-nil (the default) for a stream server process, allow this server to reuse a specific port number (see :service), unless another process on this host is already listening on that port.  If REUSEADDR-FLAG is nil, there may be a period of time after the last use of that port (by any process on the host) where it is not possible to make a new server on that port.

 -- Function: set-network-process-option process option value &optional no-error
     This function sets or modifies a network option for network process PROCESS.  The accepted options and values are as for make-network-process.  If NO-ERROR is non-nil, this function returns nil instead of signaling an error if OPTION is not a supported option.  If the function successfully completes, it returns t.

     The current setting of an option is available via the process-contact function.

Testing Availability of Network Features
----------------------------------------

To test for the availability of a given network feature, use featurep like this:

     (featurep 'make-network-process '(KEYWORD VALUE))

The result of this form is t if it works to specify KEYWORD with value VALUE in make-network-process. Here are some of the KEYWORD---VALUE pairs you can test in this way.

(:nowait t)
     Non-nil if non-blocking connect is supported.

(:type datagram)
     Non-nil if datagrams are supported.

(:family local)
     Non-nil if local (a.k.a. ``UNIX domain'') sockets are supported.

(:family ipv6)
     Non-nil if IPv6 is supported.

(:service t)
     Non-nil if the system can select the port for a server.

To test for the availability of a given network option, use featurep like this:

     (featurep 'make-network-process 'KEYWORD)

The accepted KEYWORD values are :bindtodevice, etc. For the complete list, see Network Options.  This form returns non-nil if that particular network option is supported by make-network-process (or set-network-process-option).

Misc Network Facilities
=======================

These additional functions are useful for creating and operating on network connections.  Note that they are supported only on some systems.

 -- Function: network-interface-list &optional full family
     This function returns a list describing the network interfaces of the machine you are using.  The value is an alist whose elements have the form (IFNAME . ADDRESS).  IFNAME is a string naming the interface, ADDRESS has the same form as the LOCAL-ADDRESS and REMOTE-ADDRESS arguments to make-network-process, i.e. a vector of integers.  By default both IPv4 and IPv6 addresses are returned if possible.

     Optional argument FULL non-nil means to instead return a list of one or more elements of the form (IFNAME ADDR BCAST NETMASK).  IFNAME is a non-unique string naming the interface.  ADDR, BCAST, and NETMASK are vectors of integers detailing the IP address, broadcast address, and network mask.

     Optional argument FAMILY specified as symbol ipv4 or ipv6 restricts the returned information to IPv4 and IPv6 addresses respectively, independently of the value of FULL. Specifying ipv6 when IPv6 support is not available will result in an error being signaled.

     Some examples:

          (network-interface-list) =>
          (("vmnet8" .
            [172 16 76 1 0])
           ("vmnet1" .
            [172 16 206 1 0])
           ("lo0" .
            [65152 0 0 0 0 0 0 1 0])
           ("lo0" .
            [0 0 0 0 0 0 0 1 0])
           ("lo0" .
            [127 0 0 1 0]))

          (network-interface-list t) =>
          (("vmnet8"
            [172 16 76 1 0]
            [172 16 76 255 0]
            [255 255 255 0 0])
           ("vmnet1"
            [172 16 206 1 0]
            [172 16 206 255 0]
            [255 255 255 0 0])
           ("lo0"
            [65152 0 0 0 0 0 0 1 0]
            [65152 0 0 0 65535 65535 65535 65535 0]
            [65535 65535 65535 65535 0 0 0 0 0])
           ("lo0"
            [0 0 0 0 0 0 0 1 0]
            [0 0 0 0 0 0 0 1 0]
            [65535 65535 65535 65535 65535 65535 65535 65535 0])
           ("lo0"
            [127 0 0 1 0]
            [127 255 255 255 0]
            [255 0 0 0 0]))

 -- Function: network-interface-info ifname
     This function returns information about the network interface named IFNAME.  The value is a list of the form (ADDR BCAST NETMASK HWADDR FLAGS).

     addr
          The Internet protocol address.

     bcast
          The broadcast address.

     netmask
          The network mask.

     hwaddr
          The layer 2 address (Ethernet MAC address, for instance).

     flags
          The current flags of the interface.

     Note that this function returns only IPv4 information.

 -- Function: format-network-address address &optional omit-port
     This function converts the Lisp representation of a network address to a string.

     A five-element vector [A B C D P] represents an IPv4 address A.B.C.D and port number P.  format-network-address converts that to the string "A.B.C.D:P".

     A nine-element vector [A B C D E F G H P] represents an IPv6 address along with a port number.  format-network-address converts that to the string "[A:B:C:D:E:F:G:H]:P".

     If the vector does not include the port number, P, or if OMIT-PORT is non-nil, the result does not include the :P suffix.

 -- Function: network-lookup-address-info name &optional family hints
     This function perform hostname lookups on NAME, which is expected to be an ASCII-only string, otherwise it signals an error.  Call puny-encode-domain on NAME first if you wish to lookup internationalized hostnames.

     If successful, this function returns a list of Lisp representations of network addresses (see Network Processes, for a description of the format), otherwise return nil.  In the latter case, it also logs an error message hopefully explaining what went wrong.

     By default, this function attempts both IPv4 and IPv6 lookups.  The optional argument FAMILY controls this behavior, specifying the symbol ipv4 or ipv6 restricts lookups to IPv4 and IPv6 respectively.

     If optional argument HINTS is numeric, the function treats the NAME as a numerical IP address (and does not perform DNS lookups).  This can be used to check whether a string is a valid numerical representation of an IP address, or to convert a numerical string to its canonical representation. e.g.

          (network-lookup-address-info "127.1" 'ipv4 'numeric)
              => ([127 0 0 1 0])

          (network-lookup-address-info "::1" nil 'numeric)
              => ([0 0 0 0 0 0 0 1 0])

     Be warned that there are some surprising valid forms, especially for IPv4, e.g 0xe3010203 and 0343.1.2.3 are both valid, as are 0 and 1 (but they are invalid for IPv6).

Communicating with Serial Ports
===============================

Emacs can communicate with serial ports.  For interactive use, M-x serial-term opens a terminal window.  In a Lisp program, make-serial-process creates a process object.

The serial port can be configured at run-time, without having to close and re-open it.  The function serial-process-configure lets you change the speed, bytesize, and other parameters.  In a terminal window created by serial-term, you can click on the mode line for configuration.

A serial connection is represented by a process object, which can be used in a similar way to a subprocess or network process.  You can send and receive data, and configure the serial port.  A serial process object has no process ID, however, and you can't send signals to it, and the status codes are different from other types of processes. delete-process on the process object or kill-buffer on the process buffer close the connection, but this does not affect the device connected to the serial port.

The function process-type returns the symbol serial for a process object representing a serial port connection.

Serial ports are available on GNU/Linux, Unix, and MS Windows systems.

 -- Command: serial-term port speed &optional line-mode
     Start a terminal-emulator for a serial port in a new buffer. PORT is the name of the serial port to connect to.  For example, this could be /dev/ttyS0 on Unix.  On MS Windows, this could be COM1, or \\.\COM10 (double the backslashes in Lisp strings).

     SPEED is the speed of the serial port in bits per second.  9600 is a common value.  The buffer is in Term mode; see Term Mode (The GNU Emacs Manual), for the commands to use in that buffer. You can change the speed and the configuration in the mode line menu. If LINE-MODE is non-nil, term-line-mode is used; otherwise term-raw-mode is used.

 -- Function: make-serial-process &rest args
     This function creates a process and a buffer.  Arguments are specified as keyword/argument pairs.  Here's the list of the meaningful keywords, with the first two (PORT and SPEED) being mandatory:

     :port PORT
          This is the name of the serial port.  On Unix and GNU systems, this is a file name such as /dev/ttyS0.  On Windows, this could be COM1, or \\.\COM10 for ports higher than COM9 (double the backslashes in Lisp strings).

     :speed SPEED
          The speed of the serial port in bits per second.  This function calls serial-process-configure to handle the speed; see the following documentation of that function for more details.

     :name NAME
          The name of the process.  If NAME is not given, PORT will serve as the process name as well.

     :buffer BUFFER
          The buffer to associate with the process.  The value can be either a buffer or a string that names a buffer.  Process output goes at the end of that buffer, unless you specify an output stream or filter function to handle the output.  If BUFFER is not given, the process buffer's name is taken from the value of the :name keyword.

     :coding CODING
          If CODING is a symbol, it specifies the coding system used for both reading and writing for this process.  If CODING is a cons (DECODING . ENCODING), DECODING is used for reading, and ENCODING is used for writing.  If not specified, the default is to determine the coding systems from the data itself.

     :noquery QUERY-FLAG
          Initialize the process query flag to QUERY-FLAG.  See Query Before Exit.  The flags defaults to nil if unspecified.

     :stop BOOL
          Start process in the stopped state if BOOL is non-nil.  In the stopped state, a serial process does not accept incoming data, but you can send outgoing data.  The stopped state is cleared by continue-process and set by stop-process.

     :filter FILTER
          Install FILTER as the process filter.

     :sentinel SENTINEL
          Install SENTINEL as the process sentinel.

     :plist PLIST
          Install PLIST as the initial plist of the process.

     :bytesize
     :parity
     :stopbits
     :flowcontrol
          These are handled by serial-process-configure, which is called by make-serial-process.

     The original argument list, possibly modified by later configuration, is available via the function process-contact.

     Here is an example:

          (make-serial-process :port "/dev/ttyS0" :speed 9600)

 -- Function: serial-process-configure &rest args

     This function configures a serial port connection.  Arguments are specified as keyword/argument pairs.  Attributes that are not given are re-initialized from the process's current configuration (available via the function process-contact), or set to reasonable default values.  The following arguments are defined:

     :process PROCESS
     :name NAME
     :buffer BUFFER
     :port PORT
          Any of these arguments can be given to identify the process that is to be configured.  If none of these arguments is given, the current buffer's process is used.

     :speed SPEED
          The speed of the serial port in bits per second, a.k.a. baud rate.  The value can be any number, but most serial ports work only at a few defined values between 1200 and 115200, with 9600 being the most common value.  If SPEED is nil, the function ignores all other arguments and does not configure the port.  This may be useful for special serial ports such as Bluetooth-to-serial converters, which can only be configured through AT commands sent through the connection.  The value of nil for SPEED is valid only for connections that were already opened by a previous call to make-serial-process or serial-term.

     :bytesize BYTESIZE
          The number of bits per byte, which can be 7 or 8.  If BYTESIZE is not given or nil, it defaults to 8.

     :parity PARITY
          The value can be nil (don't use parity), the symbol odd (use odd parity), or the symbol even (use even parity).  If PARITY is not given, it defaults to no parity.

     :stopbits STOPBITS
          The number of stopbits used to terminate a transmission of each byte.  STOPBITS can be 1 or 2.  If STOPBITS is not given or nil, it defaults to 1.

     :flowcontrol FLOWCONTROL
          The type of flow control to use for this connection, which is either nil (don't use flow control), the symbol hw (use RTS/CTS hardware flow control), or the symbol sw (use XON/XOFF software flow control).  If FLOWCONTROL is not given, it defaults to no flow control.

     Internally, make-serial-process calls serial-process-configure for the initial configuration of the serial port.

Packing and Unpacking Byte Arrays
=================================

This section describes how to pack and unpack arrays of bytes, usually for binary network protocols.  These functions convert byte arrays to alists, and vice versa.  The byte array can be represented as a unibyte string or as a vector of integers, while the alist associates symbols either with fixed-size objects or with recursive sub-alists. To use the functions referred to in this section, load the bindat library.

Conversion from byte arrays to nested alists is also known as deserializing or unpacking, while going in the opposite direction is also known as serializing or packing.

Describing Data Layout
----------------------

To control unpacking and packing, you write a data layout specification, also called a Bindat type expression.  This can be a base type or a composite type made of several fields, where the specification controls the length of each field to be processed, and how to pack or unpack it.  We normally keep bindat type values in variables whose names end in -bindat-spec; that kind of name is automatically recognized as risky (see File Local Variables).

 -- Macro: bindat-type &rest type
     Creates a Bindat type value object according to the Bindat type expression TYPE.

A field's type describes the size (in bytes) of the object that the field represents and, in the case of multibyte fields, how the bytes are ordered within the field.  The two possible orderings are big endian (also known as ``network byte ordering'') and little endian.  For instance, the number #x23cd (decimal 9165) in big endian would be the two bytes #x23 #xcd; and in little endian, #xcd #x23.  Here are the possible type values:

u8
byte
     Unsigned byte, with length 1.

uint BITLEN &optional LE
     Unsigned integer in network byte order (big-endian), with BITLEN bits. BITLEN has to be a multiple of 8. If LE is non-nil, then use little-endian byte order.

sint BITLEN LE
     Signed integer in network byte order (big-endian), with BITLEN bits. BITLEN has to be a multiple of 8. If LE is non-nil, then use little-endian byte order.

str LEN
     Unibyte string (see Text Representations) of length LEN bytes. When packing, the first LEN bytes of the input string are copied to the packed output.  If the input string is shorter than LEN, the remaining bytes will be null (zero) unless a pre-allocated string was provided to bindat-pack, in which case the remaining bytes are left unmodified.  If the input string is multibyte with only ASCII and eight-bit characters, it is converted to unibyte before it is packed; other multibyte strings signal an error.  When unpacking, any null bytes in the packed input string will appear in the unpacked output.

strz &optional LEN
     If LEN is not provided, this is a variable-length null-terminated unibyte string (see Text Representations).  When packing into strz, the entire input string is copied to the packed output followed by a null (zero) byte.  (If pre-allocated string is provided for packing into strz, that pre-allocated string should have enough space for the additional null byte appended to the output string contents, see Bindat Functions).  The length of the packed output is the length of the input string plus one (for the null terminator).  The input string must not contain any null bytes.  If the input string is multibyte with only ASCII and eight-bit characters, it is converted to unibyte before it is packed; other multibyte strings signal an error.  When unpacking a strz, the resulting output string will contain all bytes up to (but excluding) the null byte that terminated the input string.

     If LEN is provided, strz behaves the same as str, but with a couple of differences:

       * When packing, a null terminator is written after the packed input string if the number of characters in the input string is less than LEN.

       * When unpacking, the first null byte encountered in the packed string is interpreted as the terminating byte, and it and all subsequent bytes are excluded from the result of the unpacking.

          The packed output will not be null-terminated unless the input string is shorter than LEN bytes or it contains a null byte within the first LEN bytes.

vec LEN [TYPE]
     Vector of LEN elements.  The type of the elements is given by TYPE, defaulting to bytes.  The TYPE can be any Bindat type expression.

repeat LEN [TYPE]
     Like vec, but it unpacks to and packs from lists, whereas vec unpacks to vectors.

bits LEN
     List of bits that are set to 1 in LEN bytes.  The bytes are taken in big-endian order, and the bits are numbered starting with 8 * LEN - 1 and ending with zero.  For example: bits 2 unpacks #x28 #x1c to (2 3 4 11 13) and #x1c #x28 to (3 5 10 11 12).

fill LEN
     LEN bytes used as a mere filler.  In packing, these bytes are left unchanged, which normally means they remain zero. When unpacking, this just returns nil.

align LEN
     Same as fill except the number of bytes is that needed to skip to the next multiple of LEN bytes.

type EXP
     This lets you refer to a type indirectly: EXP is a Lisp expression which should return a Bindat type value.

unit EXP
     This is a trivial type which uses up 0 bits of space.  EXP describes the value returned when we try to ``unpack'' such a field.

struct FIELDS...
     Composite type made of several fields.  Every field is of the form (NAME TYPE) where TYPE can be any Bindat type expression.  NAME can be _ when the field's value does not deserve to be named, as is often the case for align and fill fields. When the context makes it clear that this is a Bindat type expression, the symbol struct can be omitted.

In the types above, LEN and BITLEN are given as an integer specifying the number of bytes (or bits) in the field.  When the length of a field is not fixed, it typically depends on the value of preceding fields.  For this reason, the length LEN does not have to be a constant but can be any Lisp expression and it can refer to the value of previous fields via their name.

For example, the specification of a data layout where a leading byte gives the size of a subsequent vector of 16 bit integers could be:

     (bindat-type
       (len      u8)
       (payload  vec (1+ len) uint 16))

Functions to Unpack and Pack Bytes
----------------------------------

In the following documentation, TYPE refers to a Bindat type value as returned from bindat-type, RAW to a byte array, and STRUCT to an alist representing unpacked field data.

 -- Function: bindat-unpack type raw &optional idx
     This function unpacks data from the unibyte string or byte array RAW according to TYPE.  Normally, this starts unpacking at the beginning of the byte array, but if IDX is non-nil, it specifies a zero-based starting position to use instead.

     The value is an alist or nested alist in which each element describes one unpacked field.

 -- Function: bindat-get-field struct &rest name
     This function selects a field's data from the nested alist STRUCT.  Usually STRUCT was returned by bindat-unpack.  If NAME corresponds to just one argument, that means to extract a top-level field value.  Multiple NAME arguments specify repeated lookup of sub-structures.  An integer NAME acts as an array index.

     For example, (bindat-get-field STRUCT a b 2 c) means to find field c in the third element of subfield b of field a.  (This corresponds to STRUCT.a.b[2].c in the C programming language syntax.)

Although packing and unpacking operations change the organization of data (in memory), they preserve the data's total length, which is the sum of all the fields' lengths, in bytes.  This value is not generally inherent in either the specification or alist alone; instead, both pieces of information contribute to its calculation.  Likewise, the length of a string or array being unpacked may be longer than the data's total length as described by the specification.

 -- Function: bindat-length type struct
     This function returns the total length of the data in STRUCT, according to TYPE.

 -- Function: bindat-pack type struct &optional raw idx
     This function returns a byte array packed according to TYPE from the data in the alist STRUCT.  It normally creates and fills a new byte array starting at the beginning.  However, if RAW is non-nil, it specifies a pre-allocated unibyte string or vector to pack into.  If IDX is non-nil, it specifies the starting offset for packing into RAW.

     When pre-allocating, you should make sure (length RAW) meets or exceeds the total length to avoid an out-of-range error.

 -- Function: bindat-ip-to-string ip
     Convert the Internet address vector IP to a string in the usual dotted notation.

          (bindat-ip-to-string [127 0 0 1])
               => "127.0.0.1"

Advanced data layout specifications
-----------------------------------

Bindat type expressions are not limited to the types described earlier.  They can also be arbitrary Lisp forms returning Bindat type expressions.  For example, the type below describes data which can either contain a 24-bit error code or a vector of bytes:

     (bindat-type
       (len      u8)
       (payload  . (if (zerop len) (uint 24) (vec (1- len)))))

Furthermore, while composite types are normally unpacked to (and packed from) association lists, this can be changed via the use of the following special keyword arguments:

:unpack-val EXP
     When the list of fields ends with this keyword argument, then the value returned when unpacking is the value of EXP instead of the standard alist.  EXP can refer to all the previous fields by their name.

:pack-val EXP
     If a field's type is followed by this keyword argument, then the value packed into this field is returned by EXP instead of being extracted from the alist.

:pack-var NAME
     If the list of fields is preceded by this keyword argument, then all the subsequent :pack-val arguments can refer to the overall value to pack into this composite type via the variable named NAME.

For example, one could describe a 16-bit signed integer as follows:

     (defconst sint16-bindat-spec
       (let* ((max (ash 1 15))
              (wrap (+ max max)))
         (bindat-type :pack-var v
                      (n uint 16 :pack-val (if (< v 0) (+ v wrap) v))
                      :unpack-val (if (>= n max) (- n wrap) n))))

Which would then behave as follows:

     (bindat-pack sint16-bindat-spec -8)
          => "\377\370"

     (bindat-unpack sint16-bindat-spec "\300\100")
          => -16320

Finally, you can define new Bindat type forms to use in Bindat type expressions with bindat-defmacro:

 -- Macro: bindat-defmacro name args &rest body
     Define a new Bindat type expression named NAME and taking arguments ARGS.  Its behavior follows that of defmacro, which the important difference that the new forms can only be used within Bindat type expressions.