Appendix E GNU Emacs Internals

This chapter describes how the runnable Emacs executable is dumped with the preloaded Lisp libraries in it, how storage is allocated, and some internal aspects of GNU Emacs that may be of interest to C programmers.


E.1 Building Emacs

This section explains the steps involved in building the Emacs executable. You don’t have to know this material to build and install Emacs, since the makefiles do all these things automatically. This information is pertinent to Emacs developers.

Building Emacs requires GNU Make version 3.81 or later.

Compilation of the C source files in the src directory produces an executable file called temacs, also called a bare impure Emacs. It contains the Emacs Lisp interpreter and I/O routines, but not the editing commands.

The command temacs -l loadup would run temacs and direct it to load loadup.el. The loadup library loads additional Lisp libraries, which set up the normal Emacs editing environment. After this step, the Emacs executable is no longer bare.

Because it takes some time to load the standard Lisp files, the temacs executable usually isn’t run directly by users. Instead, one of the last steps of building Emacs runs the command ‘temacs -batch -l loadup --temacs=dump-method’. The special option --temacs tells temacs how to record all the standard preloaded Lisp functions and variables, so that when you subsequently run Emacs, it will start much faster. The --temacs option requires an argument dump-method, which can be one of the following:

‘pdump’

Record the preloaded Lisp data in a dump file. This method produces an additional data file which Emacs will load at startup. The produced dump file is usually called emacs.pdmp, and is installed in the Emacs exec-directory (see Help Functions). This method is the most preferred one, as it does not require Emacs to employ any special techniques of memory allocation, which might get in the way of various memory-layout techniques used by modern systems to enhance security and privacy.

‘pbootstrap’

Like ‘pdump’, but used while bootstrapping Emacs, when no previous Emacs binary and no *.elc byte-compiled Lisp files are available. The produced dump file is usually named bootstrap-emacs.pdmp in this case.

The dumped emacs executable (also called a pure Emacs) is the one which is installed. If the portable dumper was used to build Emacs, the emacs executable is actually an exact copy of temacs, and the corresponding emacs.pdmp file is installed as well. The variable preloaded-file-list stores a list of the preloaded Lisp files recorded in the dump file or in the dumped Emacs executable. If you port Emacs to a new operating system, and are not able to implement dumping of any kind, then Emacs must load loadup.el each time it starts.

By default the dumped emacs executable records details such as the build time and host name. Use the --disable-build-details option of configure to suppress these details, so that building and installing Emacs twice from the same sources is more likely to result in identical copies of Emacs.

You can specify additional files to preload by writing a library named site-load.el that loads them. However, the advantage of preloading additional files decreases as machines get faster. On modern machines, it is usually not advisable.

After loadup.el reads site-load.el, it finds the documentation strings for primitive and preloaded functions (and variables) in the file etc/DOC where they are stored, by calling Snarf-documentation (see Accessing Documentation).

You can specify other Lisp expressions to execute just before dumping by putting them in a library named site-init.el. This file is executed after the documentation strings are found.

If you want to preload function or variable definitions, there are three ways you can do this and make their documentation strings accessible when you subsequently run Emacs:

It is not advisable to put anything in site-load.el or site-init.el that would alter any of the features that users expect in an ordinary unmodified Emacs. If you feel you must override normal features for your site, do it with default.el, so that users can override your changes if they wish. See Summary: Sequence of Actions at Startup. Note that if either site-load.el or site-init.el changes load-path, the changes will be lost after dumping. See Library Search. To make a permanent change to load-path, use the --enable-locallisppath option of configure.

In a package that can be preloaded, it is sometimes necessary (or useful) to delay certain evaluations until Emacs subsequently starts up. The vast majority of such cases relate to the values of customizable variables. For example, tutorial-directory is a variable defined in startup.el, which is preloaded. The default value is set based on data-directory. The variable needs to access the value of data-directory when Emacs starts, not when it is dumped, because the Emacs executable has probably been installed in a different location since it was dumped.

Function: custom-initialize-delay symbol value

This function delays the initialization of symbol to the next Emacs start. You normally use this function by specifying it as the :initialize property of a customizable variable. (The argument value is unused, and is provided only for compatibility with the form Custom expects.)

In the unlikely event that you need a more general functionality than custom-initialize-delay provides, you can use before-init-hook (see Summary: Sequence of Actions at Startup).

Function: dump-emacs-portable to-file &optional track-referrers

This function dumps the current state of Emacs into a dump file to-file, using the pdump method. Normally, the dump file is called emacs-name.dmp, where emacs-name is the name of the Emacs executable file. The optional argument track-referrers, if non-nil, causes the portable dumper to keep additional information to help track down the provenance of object types that are not yet supported by the pdump method.

Although the portable dumper code can run on many platforms, the dump files that it produces are not portable—they can be loaded only by the Emacs executable that dumped them.

If you want to use this function in an Emacs that was already dumped, you must run Emacs with the ‘-batch’ option.

If you’re including ‘.el’ files in the dumped Emacs and that ‘.el’ file has code that is normally run at load time, that code won’t be run when Emacs starts after dumping. To help work around that problem, you can put functions on the after-pdump-load-hook hook. This hook is run when starting Emacs.

Function: pdumper-stats

If the current Emacs session restored its state from a dump file, this function returns information about the dump file and the time it took to restore the Emacs state. The value is an alist ((dumped-with-pdumper . t) (load-time . time) (dump-file-name . file)), where file is the name of the dump file, and time is the time in seconds it took to restore the state from the dump file. If the current session was not restored from a dump file, the value is nil.


E.2 Garbage Collection

When a program creates a list or the user defines a new function (such as by loading a library), that data is placed in normal storage. If normal storage runs low, then Emacs asks the operating system to allocate more memory. Different types of Lisp objects, such as symbols, cons cells, small vectors, markers, etc., are segregated in distinct blocks in memory. (Large vectors, long strings, buffers and certain other editing types, which are fairly large, are allocated in individual blocks, one per object; small strings are packed into blocks of 8k bytes, and small vectors are packed into blocks of 4k bytes).

Beyond the basic vector, a lot of objects like markers, overlays and buffers are managed as if they were vectors. The corresponding C data structures include the union vectorlike_header field whose size member contains the subtype enumerated by enum pvec_type and an information about how many Lisp_Object fields this structure contains and what the size of the rest data is. This information is needed to calculate the memory footprint of an object, and used by the vector allocation code while iterating over the vector blocks.

It is quite common to use some storage for a while, then release it by (for example) killing a buffer or deleting the last pointer to an object. Emacs provides a garbage collector to reclaim this abandoned storage. The garbage collector operates, in essence, by finding and marking all Lisp objects that are still accessible to Lisp programs. To begin with, it assumes all the symbols, their values and associated function definitions, and any data presently on the stack, are accessible. Any objects that can be reached indirectly through other accessible objects are also accessible, but this calculation is done “conservatively”, so it may slightly overestimate how many objects that are accessible.

When marking is finished, all objects still unmarked are garbage. No matter what the Lisp program or the user does, it is impossible to refer to them, since there is no longer a way to reach them. Their space might as well be reused, since no one will miss them. The second (sweep) phase of the garbage collector arranges to reuse them. (But since the marking was done “conservatively”, not all unused objects are guaranteed to be garbage-collected by any one sweep.)

The sweep phase puts unused cons cells onto a free list for future allocation; likewise for symbols and markers. It compacts the accessible strings so they occupy fewer 8k blocks; then it frees the other 8k blocks. Unreachable vectors from vector blocks are coalesced to create largest possible free areas; if a free area spans a complete 4k block, that block is freed. Otherwise, the free area is recorded in a free list array, where each entry corresponds to a free list of areas of the same size. Large vectors, buffers, and other large objects are allocated and freed individually.

Common Lisp note: Unlike other Lisps, GNU Emacs Lisp does not call the garbage collector when the free list is empty. Instead, it simply requests the operating system to allocate more storage, and processing continues until gc-cons-threshold bytes have been used.

This means that you can make sure that the garbage collector will not run during a certain portion of a Lisp program by calling the garbage collector explicitly just before it (provided that portion of the program does not use so much space as to force a second garbage collection).

Function: garbage-collect-heapsize

This function returns information on the current memory usage. The return value is a list with information on amount of space in use, where each entry has the form ‘(name size used)’ or ‘(name size used free)’. In the entry, name is a symbol describing the kind of objects this entry represents, size is the number of bytes used by each one, used is the number of those objects that were found live in the heap, and optional free is the number of those objects that are not live but that Emacs keeps around for future allocations. So an overall result is:

((conses cons-size used-conses free-conses)
 (symbols symbol-size used-symbols free-symbols)
 (strings string-size used-strings free-strings)
 (string-bytes byte-size used-bytes)
 (vectors vector-size used-vectors)
 (vector-slots slot-size used-slots free-slots)
 (floats float-size used-floats free-floats)
 (intervals interval-size used-intervals free-intervals)
 (buffers buffer-size used-buffers)
 (heap unit-size total-size free-size))

Here is an example:

(garbage-collect)
      ⇒ ((conses 16 49126 8058) (symbols 48 14607 0)
                 (strings 32 2942 2607)
                 (string-bytes 1 78607) (vectors 16 7247)
                 (vector-slots 8 341609 29474) (floats 8 71 102)
                 (intervals 56 27 26) (buffers 944 8)
                 (heap 1024 11715 2678))

Below is a table explaining each element. Note that last heap entry is optional and present only if an underlying malloc implementation provides mallinfo function.

cons-size

Internal size of a cons cell, i.e., sizeof (struct Lisp_Cons).

used-conses

The number of cons cells in use.

free-conses

The number of cons cells for which space has been obtained from the operating system, but that are not currently being used.

symbol-size

Internal size of a symbol, i.e., sizeof (struct Lisp_Symbol).

used-symbols

The number of symbols in use.

free-symbols

The number of symbols for which space has been obtained from the operating system, but that are not currently being used.

string-size

Internal size of a string header, i.e., sizeof (struct Lisp_String).

used-strings

The number of string headers in use.

free-strings

The number of string headers for which space has been obtained from the operating system, but that are not currently being used.

byte-size

This is used for convenience and equals to sizeof (char).

used-bytes

The total size of all string data in bytes.

vector-size

Size in bytes of a vector of length 1, including its header.

used-vectors

The number of vector headers allocated from the vector blocks.

slot-size

Internal size of a vector slot, always equal to sizeof (Lisp_Object).

used-slots

The number of slots in all used vectors. Slot counts might include some or all overhead from vector headers, depending on the platform.

free-slots

The number of free slots in all vector blocks.

float-size

Internal size of a float object, i.e., sizeof (struct Lisp_Float). (Do not confuse it with the native platform float or double.)

used-floats

The number of floats in use.

free-floats

The number of floats for which space has been obtained from the operating system, but that are not currently being used.

interval-size

Internal size of an interval object, i.e., sizeof (struct interval).

used-intervals

The number of intervals in use.

free-intervals

The number of intervals for which space has been obtained from the operating system, but that are not currently being used.

buffer-size

Internal size of a buffer, i.e., sizeof (struct buffer). (Do not confuse with the value returned by buffer-size function.)

used-buffers

The number of buffer objects in use. This includes killed buffers invisible to users, i.e., all buffers in all_buffers list.

unit-size

The unit of heap space measurement, always equal to 1024 bytes.

total-size

Total heap size, in unit-size units.

free-size

Heap space which is not currently used, in unit-size units.

Command: garbage-collect

This command runs a garbage collection, and returns information on the amount of space in use. (Garbage collection can also occur spontaneously if you use more than gc-cons-threshold bytes of Lisp data since the previous garbage collection.)

garbage-collect returns the same list as shown above for garbage-collect-heapsize.

User Option: garbage-collection-messages

If this variable is non-nil, Emacs displays a message at the beginning and end of garbage collection. The default value is nil.

Variable: post-gc-hook

This is a normal hook that is run at the end of garbage collection. Garbage collection is inhibited while the hook functions run, so be careful writing them.

User Option: gc-cons-threshold

The value of this variable is the number of bytes of storage that must be allocated for Lisp objects after one garbage collection in order to trigger another garbage collection. You can use the result returned by garbage-collect to get an information about size of the particular object type; space allocated to the contents of buffers does not count.

The initial threshold value is GC_DEFAULT_THRESHOLD, defined in alloc.c. Since it’s defined in word_size units, the value is 400,000 for the default 32-bit configuration, and 800,000 for the 64-bit one and for 32-bit builds configured with the --with-wide-int option. If you specify a larger value, garbage collection will happen less often. This reduces the amount of time spent garbage collecting (so Lisp programs will run faster between cycles of garbage collection that happen more rarely), but increases total memory use. You may want to do this when running a program that creates lots of Lisp data, especially if you need it to run faster. However, we recommend against increasing the threshold for prolonged periods of time, and advise that you never set it higher than needed for the program to run in reasonable time. Using thresholds higher than necessary could potentially cause higher system-wide memory pressure, and also make each garbage-collection cycle take much more time, and should therefore be avoided.

You can make collections more frequent by specifying a smaller value, down to 1/10th of GC_DEFAULT_THRESHOLD. A value less than this minimum will remain in effect only until the subsequent garbage collection, at which time garbage-collect will set the threshold back to the minimum.

User Option: gc-cons-percentage

The value of this variable specifies the amount of consing before a garbage collection occurs, as a fraction of the current heap size. This criterion and gc-cons-threshold apply in parallel, and garbage collection occurs only when both criteria are satisfied.

As the heap size increases, the time to perform a garbage collection increases. Thus, it can be desirable to do them less frequently in proportion.

The initial percentage value is 0.1 in interactive sessions and while dumping Emacs (see Building Emacs), and 1.0 in non-interactive (a.k.a. “batch”) sessions.

As with gc-cons-threshold, do not enlarge this more than necessary, and never for prolonged periods of time.

Control over the garbage collector via gc-cons-threshold and gc-cons-percentage is only approximate. Although Emacs checks for threshold exhaustion regularly, for efficiency reasons it does not do so immediately after every change to the heap or to gc-cons-threshold or gc-cons-percentage, so exhausting the threshold does not immediately trigger garbage collection. Also, for efficiency in threshold calculations Emacs approximates the heap size, which counts the bytes used by currently-accessible objects in the heap.

The value returned by garbage-collect describes the amount of memory used by Lisp data, broken down by data type. By contrast, the function memory-limit provides information on the total amount of memory Emacs is currently using.

Function: memory-limit

This function returns an estimate of the total amount of bytes of virtual memory that Emacs is currently using, divided by 1024. You can use this to get a general idea of how your actions affect the memory usage.

Variable: memory-full

This variable is t if Emacs is nearly out of memory for Lisp objects, and nil otherwise.

Function: memory-use-counts

This returns a list of numbers that count the number of objects created in this Emacs session. Each of these counters increments for a certain kind of object. See the documentation string for details.

Function: memory-info

This functions returns an amount of total system memory and how much of it is free. On an unsupported system, the value may be nil.

If default-directory points to a remote host, memory information of that host is returned.

Variable: gcs-done

This variable contains the total number of garbage collections done so far in this Emacs session.

Variable: gc-elapsed

This variable contains the total number of seconds of elapsed time during garbage collection so far in this Emacs session, as a floating-point number.

Function: memory-report

It can sometimes be useful to see where Emacs is using memory (in various variables, buffers, and caches). This command will open a new buffer (called ‘"*Memory Report*"’) that will give an overview, in addition to listing the “largest” buffers and variables.

All the data here is approximate, because there’s really no consistent way to compute the size of a variable. For instance, two variables may share parts of a data structure, and this will be counted twice, but this command may still give a useful high-level overview of which parts of Emacs are using memory.


E.3 Stack-allocated Objects

The garbage collector described above is used to manage data visible from Lisp programs, as well as most of the data internally used by the Lisp interpreter. Sometimes it may be useful to allocate temporary internal objects using the C stack of the interpreter. This can help performance, as stack allocation is typically faster than using heap memory to allocate and the garbage collector to free. The downside is that using such objects after they are freed results in undefined behavior, so uses should be well thought out and carefully debugged by using the GC_CHECK_MARKED_OBJECTS feature (see src/alloc.c). In particular, stack-allocated objects should never be made visible to user Lisp code.

Currently, cons cells and strings can be allocated this way. This is implemented by C macros like AUTO_CONS and AUTO_STRING that define a named Lisp_Object with block lifetime. These objects are not freed by the garbage collector; instead, they have automatic storage duration, i.e., they are allocated like local variables and are automatically freed at the end of execution of the C block that defined the object.

For performance reasons, stack-allocated strings are limited to ASCII characters, and many of these strings are immutable, i.e., calling ASET on them produces undefined behavior.


E.4 Memory Usage

These functions and variables give information about the total amount of memory allocation that Emacs has done, broken down by data type. Note the difference between these and the values returned by garbage-collect; those count objects that currently exist, but these count the number or size of all allocations, including those for objects that have since been freed.

Variable: cons-cells-consed

The total number of cons cells that have been allocated so far in this Emacs session.

Variable: floats-consed

The total number of floats that have been allocated so far in this Emacs session.

Variable: vector-cells-consed

The total number of vector cells that have been allocated so far in this Emacs session. This includes vector-like objects such as markers and overlays, plus certain objects not visible to users.

Variable: symbols-consed

The total number of symbols that have been allocated so far in this Emacs session.

Variable: string-chars-consed

The total number of string characters that have been allocated so far in this session.

Variable: intervals-consed

The total number of intervals that have been allocated so far in this Emacs session.

Variable: strings-consed

The total number of strings that have been allocated so far in this Emacs session.


E.5 C Dialect

The C part of Emacs is portable to C99 or later: later C features such as ‘<stdckdint.h>’ and ‘[[noreturn]]’ are not used without a check, typically at configuration time, and the Emacs build procedure provides a substitute implementation if necessary. Some later features, such as anonymous structures and unions, are too difficult to emulate, so they are avoided entirely.

At some point in the future the base C dialect will no doubt change to something later than C99.


E.6 Writing Emacs Primitives

Lisp primitives are Lisp functions implemented in C. The details of interfacing the C function so that Lisp can call it are handled by a few C macros. The only way to really understand how to write new C code is to read the source, but we can explain some things here.

An example of a special form is the definition of or, from eval.c. (An ordinary function would have the same general appearance.)

DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
       doc: /* Eval args until one of them yields non-nil,
then return that value.
The remaining args are not evalled at all.
If all args return nil, return nil.
usage: (or CONDITIONS...)  */)
  (Lisp_Object args)
{
  Lisp_Object val = Qnil;

  while (CONSP (args))
    {
      val = eval_sub (XCAR (args));
      if (!NILP (val))
        break;
      args = XCDR (args);
      maybe_quit ();
    }

  return val;
}

Let’s start with a precise explanation of the arguments to the DEFUN macro. Here is a template for them:

DEFUN (lname, fname, sname, min, max, interactive, doc)
lname

This is the name of the Lisp symbol to define as the function name; in the example above, it is or.

fname

This is the C function name for this function. This is the name that is used in C code for calling the function. The name is, by convention, ‘F’ prepended to the Lisp name, with all dashes (‘-’) in the Lisp name changed to underscores. Thus, to call this function from C code, call For.

sname

This is a C variable name to use for a structure that holds the data for the subr object that represents the function in Lisp. This structure conveys the Lisp symbol name to the initialization routine that will create the symbol and store the subr object as its definition. By convention, this name is always fname with ‘F’ replaced with ‘S’.

min

This is the minimum number of arguments that the function requires. The function or allows a minimum of zero arguments.

max

This is the maximum number of arguments that the function accepts, if there is a fixed maximum. Alternatively, it can be UNEVALLED, indicating a special form that receives unevaluated arguments, or MANY, indicating an unlimited number of evaluated arguments (the equivalent of &rest). Both UNEVALLED and MANY are macros. If max is a number, it must be more than min but less than 8.

interactive

This is an interactive specification, a string such as might be used as the argument of interactive in a Lisp function (see Using interactive). In the case of or, it is 0 (a null pointer), indicating that or cannot be called interactively. A value of "" indicates a function that should receive no arguments when called interactively. If the value begins with a ‘"(’, the string is evaluated as a Lisp form. For example:

DEFUN ("foo", Ffoo, Sfoo, 0, 3,
       "(list (read-char-by-name \"Insert character: \")\
              (prefix-numeric-value current-prefix-arg)\
              t)",
       doc: /* ... */)
doc

This is the documentation string. It uses C comment syntax rather than C string syntax because comment syntax requires nothing special to include multiple lines. The ‘doc:’ identifies the comment that follows as the documentation string. The ‘/*’ and ‘*/’ delimiters that begin and end the comment are not part of the documentation string.

If the last line of the documentation string begins with the keyword ‘usage:’, the rest of the line is treated as the argument list for documentation purposes. This way, you can use different argument names in the documentation string from the ones used in the C code. ‘usage:’ is required if the function has an unlimited number of arguments.

Some primitives have multiple definitions, one per platform (e.g., x-create-frame). In such cases, rather than writing the same documentation string in each definition, only one definition has the actual documentation. The others have placeholders beginning with ‘SKIP’, which are ignored by the function that parses the DOC file.

All the usual rules for documentation strings in Lisp code (see Tips for Documentation Strings) apply to C code documentation strings too.

The documentation string can be followed by a list of C function attributes for the C function that implements the primitive, like this:

DEFUN ("bar", Fbar, Sbar, 0, UNEVALLED, 0
       doc: /* ... */
       attributes: attr1 attr2 ...)

You can specify more than a single attribute, one after the other. Currently, only the following attributes are recognized:

noreturn

Declares the C function as one that never returns. This corresponds to C23’s [[noreturn]], to C11’s _Noreturn, and to GCC’s __attribute__ ((__noreturn__)) (see Function Attributes in Using the GNU Compiler Collection). (Internally, Emacs’s own C code uses _Noreturn as it can be defined as a macro on C platforms that do not support it.)

const

Declares that the function does not examine any values except its arguments, and has no effects except the return value. This corresponds to C23’s [[unsequenced]] and to GCC’s __attribute__ ((__const__)).

noinline

This corresponds to __attribute__ ((__noinline__)) attribute of GCC, which prevents the function from being considered for inlining. This might be needed, e.g., to countermand effects of link-time optimizations on stack-based variables.

After the call to the DEFUN macro, you must write the argument list for the C function, including the types for the arguments. If the primitive accepts a fixed maximum number of Lisp arguments, there must be one C argument for each Lisp argument, and each argument must be of type Lisp_Object. (Various macros and functions for creating values of type Lisp_Object are declared in the file lisp.h.) If the primitive is a special form, it must accept a Lisp list containing its unevaluated Lisp arguments as a single argument of type Lisp_Object. If the primitive has no upper limit on the number of evaluated Lisp arguments, it must have exactly two C arguments: the first is the number of Lisp arguments, and the second is the address of a block containing their values. These have types ptrdiff_t and Lisp_Object *, respectively. Since Lisp_Object can hold any Lisp object of any data type, you can determine the actual data type only at run time; so if you want a primitive to accept only a certain type of argument, you must check the type explicitly using a suitable predicate (see Type Predicates).

Within the function For itself, the local variable args refers to objects controlled by Emacs’s stack-marking garbage collector. Although the garbage collector does not reclaim objects reachable from C Lisp_Object stack variables, it may move some of the components of an object, such as the contents of a string or the text of a buffer. Therefore, functions that access these components must take care to refetch their addresses after performing Lisp evaluation. This means that instead of keeping C pointers to string contents or buffer text, the code should keep the buffer or string position, and recompute the C pointer from the position after performing Lisp evaluation. Lisp evaluation can occur via calls to eval_sub or Feval, either directly or indirectly.

Note the call to maybe_quit inside the loop: this function checks whether the user pressed C-g, and if so, aborts the processing. You should do that in any loop that can potentially require a large number of iterations; in this case, the list of arguments could be very long. This increases Emacs responsiveness and improves user experience.

You must not use C initializers for static or global variables unless the variables are never written once Emacs is dumped. These variables with initializers are allocated in an area of memory that becomes read-only (on certain operating systems) as a result of dumping Emacs.

Defining the C function is not enough to make a Lisp primitive available; you must also create the Lisp symbol for the primitive and store a suitable subr object in its function cell. The code looks like this:

defsubr (&sname);

Here sname is the name you used as the third argument to DEFUN.

If you add a new primitive to a file that already has Lisp primitives defined in it, find the function (near the end of the file) named syms_of_something, and add the call to defsubr there. If the file doesn’t have this function, or if you create a new file, add to it a syms_of_filename (e.g., syms_of_myfile). Then find the spot in emacs.c where all of these functions are called, and add a call to syms_of_filename there.

The function syms_of_filename is also the place to define any C variables that are to be visible as Lisp variables. DEFVAR_LISP makes a C variable of type Lisp_Object visible in Lisp. DEFVAR_INT makes a C variable of type int visible in Lisp with a value that is always an integer. DEFVAR_BOOL makes a C variable of type int visible in Lisp with a value that is either t or nil. Note that variables defined with DEFVAR_BOOL are automatically added to the list byte-boolean-vars used by the byte compiler.

These macros all expect three arguments:

lname

The name of the variable to be used by Lisp programs.

vname

The name of the variable in the C sources.

doc

The documentation for the variable, as a C comment. See Documentation Basics, for more details.

By convention, when defining variables of a “native” type (int and bool), the name of the C variable is the name of the Lisp variable with - replaced by _. When the variable has type Lisp_Object, the convention is to also prefix the C variable name with V. This is an example:

DEFVAR_INT ("my-int-variable", my_int_variable,
           doc: /* An integer variable.  */);

DEFVAR_LISP ("my-lisp-variable", Vmy_lisp_variable,
           doc: /* A Lisp variable.  */);

There are situations in Lisp where you need to refer to the symbol itself rather than the value of that symbol. One such case is when temporarily overriding the value of a variable, which in Lisp is done with let. In C sources, this is done by defining a corresponding, constant symbol, and using specbind. By convention, Qmy_lisp_variable corresponds to Vmy_lisp_variable; to define it, use the DEFSYM macro.

DEFSYM (Qmy_lisp_variable, "my-lisp-variable");

To perform the actual binding:

specbind (Qmy_lisp_variable, Qt);

In Lisp, symbols sometimes need to be quoted. To achieve the same effect in C, you again use the corresponding constant symbol Qmy_lisp_variable. For example, when creating a buffer-local variable (see Buffer-Local Variables) in Lisp, you would write:

(make-variable-buffer-local 'my-lisp-variable)

In C, the corresponding code uses Fmake_variable_buffer_local in combination with DEFSYM:

DEFSYM (Qmy_lisp_variable, "my-lisp-variable");
Fmake_variable_buffer_local (Qmy_lisp_variable);

If you want to make a Lisp variable that is defined in C behave like one declared with defcustom, add an appropriate entry to cus-start.el. See Defining Customization Variables, for a description of the format to use.

If you directly define a file-scope C variable of type Lisp_Object, you must protect it from garbage collection by calling staticpro in syms_of_filename, like this:

staticpro (&variable);

Here is another example function, with more complicated arguments. This comes from the code in window.c, and it demonstrates the use of macros and functions to manipulate Lisp objects.

DEFUN ("coordinates-in-window-p", Fcoordinates_in_window_p,
       Scoordinates_in_window_p, 2, 2, 0,
       doc: /* Return non-nil if COORDINATES are in WINDOW.
  ...
  or `right-margin' is returned.  */)
  (register Lisp_Object coordinates, Lisp_Object window)
{
  struct window *w;
  struct frame *f;
  int x, y;
  Lisp_Object lx, ly;

  w = decode_live_window (window);
  f = XFRAME (w->frame);
  CHECK_CONS (coordinates);
  lx = Fcar (coordinates);
  ly = Fcdr (coordinates);
  CHECK_NUMBER (lx);
  CHECK_NUMBER (ly);
  x = FRAME_PIXEL_X_FROM_CANON_X (f, lx) + FRAME_INTERNAL_BORDER_WIDTH (f);
  y = FRAME_PIXEL_Y_FROM_CANON_Y (f, ly) + FRAME_INTERNAL_BORDER_WIDTH (f);

  switch (coordinates_in_window (w, x, y))
    {
    case ON_NOTHING:            /* NOT in window at all.  */
      return Qnil;

    ...

    case ON_MODE_LINE:          /* In mode line of window.  */
      return Qmode_line;

    ...

    case ON_SCROLL_BAR:         /* On scroll-bar of window.  */
      /* Historically we are supposed to return nil in this case.  */
      return Qnil;

    default:
      emacs_abort ();
    }
}

Note that C code cannot call functions by name unless they are defined in C. The way to call a function written in Lisp is to use Ffuncall, which embodies the Lisp function funcall. Since the Lisp function funcall accepts an unlimited number of arguments, in C it takes two: the number of Lisp-level arguments, and a one-dimensional array containing their values. The first Lisp-level argument is the Lisp function to call, and the rest are the arguments to pass to it.

The C macro calln is a convenient way to call a Lisp function without having to specify the number of arguments. It works by calling Ffuncall.

eval.c is a very good file to look through for examples; lisp.h contains the definitions for some important macros and functions.

If you define a function which is side-effect free or pure, give it a non-nil side-effect-free or pure property, respectively (see Standard Symbol Properties). See the lists defined in ‘byte-opt.el’.


E.7 Writing Dynamically-Loaded Modules

This section describes the Emacs module API and how to use it as part of writing extension modules for Emacs. The module API is defined in the C programming language, therefore the description and the examples in this section assume the module is written in C. For other programming languages, you will need to use the appropriate bindings, interfaces and facilities for calling C code. Emacs C code requires a C99 or later compiler (see C Dialect), and so the code examples in this section also follow that standard.

Writing a module and integrating it into Emacs comprises the following tasks:

The following subsections describe these tasks and the API itself in more detail.

Once your module is written, compile it to produce a shared library, according to the conventions of the underlying platform. Then place the shared library in a directory mentioned in load-path (see Library Search), where Emacs will find it.

If you wish to verify the conformance of a module to the Emacs dynamic module API, invoke Emacs with the --module-assertions option. See Initial Options in The GNU Emacs Manual.


E.7.1 Module Initialization Code

Begin your module by including the header file emacs-module.h and defining the GPL compatibility symbol:

#include <emacs-module.h>

int plugin_is_GPL_compatible;

The emacs-module.h file is installed into your system’s include tree as part of the Emacs installation. Alternatively, you can find it in the Emacs source tree.

Next, write an initialization function for the module.

Function: int emacs_module_init (struct emacs_runtime *runtime)

Emacs calls this function when it loads a module. If a module does not export a function named emacs_module_init, trying to load the module will signal an error. The initialization function should return zero if the initialization succeeds, non-zero otherwise. In the latter case, Emacs will signal an error, and the loading of the module will fail. If the user presses C-g during the initialization, Emacs ignores the return value of the initialization function and quits (see Quitting). (If needed, you can catch user quitting inside the initialization function, see should_quit.)

The argument runtime is a pointer to a C struct that includes 2 public fields: size, which provides the size of the structure in bytes; and get_environment, which provides a pointer to a function that allows the module initialization function access to the Emacs environment object and its interfaces.

The initialization function should perform whatever initialization is required for the module. In addition, it can perform the following tasks:

Compatibility verification

A module can verify that the Emacs executable which loads the module is compatible with the module, by comparing the size member of the runtime structure with the value compiled into the module:

int
emacs_module_init (struct emacs_runtime *runtime)
{
  if (runtime->size < sizeof (*runtime))
    return 1;
}

If the size of the runtime object passed to the module is smaller than what it expects, it means the module was compiled for an Emacs version newer (later) than the one which attempts to load it, i.e. the module might be incompatible with the Emacs binary.

In addition, a module can verify the compatibility of the module API with what the module expects. The following sample code assumes it is part of the emacs_module_init function shown above:

  emacs_env *env = runtime->get_environment (runtime);
  if (env->size < sizeof (*env))
    return 2;

This calls the get_environment function using the pointer provided in the runtime structure to retrieve a pointer to the API’s environment, a C struct which also has a size field holding the size of the structure in bytes.

Finally, you can write a module that will work with older versions of Emacs, by comparing the size of the environment passed by Emacs with known sizes, like this:

  emacs_env *env = runtime->get_environment (runtime);
  if (env->size >= sizeof (struct emacs_env_26))
    emacs_version = 26;  /* Emacs 26 or later.  */
  else if (env->size >= sizeof (struct emacs_env_25))
    emacs_version = 25;
  else
    return 2; /* Unknown or unsupported version.  */

This works because later Emacs versions always add members to the environment, never remove any members, so the size can only grow with new Emacs releases. Given the version of Emacs, the module can use only the parts of the module API that existed in that version, since those parts are identical in later versions.

emacs-module.h defines a preprocessor macro EMACS_MAJOR_VERSION. It expands to an integer literal which is the latest major version of Emacs supported by the header. See Version Information. Note that the value of EMACS_MAJOR_VERSION is a compile-time constant and does not represent the version of Emacs that is currently running and has loaded your module. If you want your module to be compatible with various versions of emacs-module.h as well as various versions of Emacs, you can use conditional compilation based on EMACS_MAJOR_VERSION.

We recommend that modules always perform the compatibility verification, unless they do their job entirely in the initialization function, and don’t access any Lisp objects or use any Emacs functions accessible through the environment structure.

Binding module functions to Lisp symbols

This gives the module functions names so that Lisp code could call it by that name. We describe how to do this in Writing Module Functions below.


E.7.2 Writing Module Functions

The main reason for writing an Emacs module is to make additional functions available to Lisp programs that load the module. This subsection describes how to write such module functions.

A module function has the following general form and signature:

Function: emacs_value emacs_function (emacs_env *env, ptrdiff_t nargs, emacs_value *args, void *data)

The env argument provides a pointer to the API environment, needed to access Emacs objects and functions. The nargs argument is the required number of arguments, which can be zero (see make_function below for more flexible specification of the argument number), and args is a pointer to the array of the function arguments. The argument data points to additional data required by the function, which was arranged when make_function (see below) was called to create an Emacs function from emacs_function.

Module functions use the type emacs_value to communicate Lisp objects between Emacs and the module (see Conversion Between Lisp and Module Values). The API, described below and in the following subsections, provides facilities for conversion between basic C data types and the corresponding emacs_value objects.

In the module function’s body, do not attempt to access elements of the args array beyond the index nargs-1: memory for the args array is allocated exactly to accommodate nargs values, and accessing beyond that will most probably crash your module. In particular, if the value of nargs passed to the function at run time is zero, it must not access args at all, as no memory will have been allocated for it in that case.

A module function always returns a value. If the function returns normally, the Lisp code which called it will see the Lisp object corresponding to the emacs_value value the function returned. However, if the user typed C-g, or if the module function or its callees signaled an error or exited nonlocally (see Nonlocal Exits in Modules), Emacs will ignore the returned value and quit or throw as it does when Lisp code encounters the same situations.

The header emacs-module.h provides the type emacs_function as an alias type for a function pointer to a module function.

After writing your C code for a module function, you should make a Lisp function object from it using the make_function function, whose pointer is provided in the environment (recall that the pointer to the environment is returned by get_environment). This is normally done in the module initialization function (see module initialization function), after verifying the API compatibility.

Function: emacs_value make_function (emacs_env *env, ptrdiff_t min_arity, ptrdiff_t max_arity, emacs_function func, const char *docstring, void *data)

This returns an Emacs function created from the C function func, whose signature is as described for emacs_function above. The arguments min_arity and max_arity specify the minimum and maximum number of arguments that func can accept. The max_arity argument can have the special value emacs_variadic_function, which makes the function accept an unlimited number of arguments, like the &rest keyword in Lisp (see Features of Argument Lists).

The argument data is a way to arrange for arbitrary additional data to be passed to func when it is called. Whatever pointer is passed to make_function will be passed unaltered to func.

The argument docstring specifies the documentation string for the function. It should be either an ASCII string, or a UTF-8 encoded non-ASCII string, or a NULL pointer; in the latter case the function will have no documentation. The documentation string can end with a line that specifies the advertised calling convention, see Documentation Strings of Functions.

Since every module function must accept the pointer to the environment as its first argument, the call to make_function could be made from any module function, but you will normally want to do that from the module initialization function, so that all the module functions are known to Emacs once the module is loaded.

Finally, you should bind the Lisp function to a symbol, so that Lisp code could call your function by name. For that, use the module API function intern (see intern) whose pointer is also provided in the environment that module functions can access.

Combining the above steps, code that arranges for a C function module_func to be callable as module-func from Lisp will look like this, as part of the module initialization function:

 emacs_env *env = runtime->get_environment (runtime);
 emacs_value func = env->make_function (env, min_arity, max_arity,
                                        module_func, docstring, data);
 emacs_value symbol = env->intern (env, "module-func");
 emacs_value args[] = {symbol, func};
 env->funcall (env, env->intern (env, "defalias"), 2, args);

This makes the symbol module-func known to Emacs by calling env->intern, then invokes defalias from Emacs to bind the function to that symbol. Note that it is possible to use fset instead of defalias; the differences are described in defalias.

Module functions including the emacs_module_init function (see module initialization function) may only interact with Emacs by calling environment functions from some live emacs_env pointer while being called directly or indirectly from Emacs. In other words, if a module function wants to call Lisp functions or Emacs primitives, convert emacs_value objects to and from C datatypes (see Conversion Between Lisp and Module Values), or interact with Emacs in any other way, some call from Emacs to emacs_module_init or to a module function must be in the call stack. Module functions may not interact with Emacs while garbage collection is running; see Garbage Collection. They may only interact with Emacs from Lisp interpreter threads (including the main thread) created by Emacs; see Threads. The --module-assertions command-line option can detect some violations of the above requirements. See Initial Options in The GNU Emacs Manual.

Using the module API, it is possible to define more complex function and data types: inline functions, macros, etc. However, the resulting C code will be cumbersome and hard to read. Therefore, we recommend that you limit the module code which creates functions and data structures to the absolute minimum, and leave the rest for a Lisp package that will accompany your module, because doing these additional tasks in Lisp is much easier, and will produce a much more readable code. For example, given a module function module-func defined as above, one way of making a macro module-macro based on it is with the following simple Lisp wrapper:

(defmacro module-macro (&rest args)
  "Documentation string for the macro."
  (module-func args))

The Lisp package which goes with your module could then load the module using the load primitive (see Emacs Dynamic Modules) when the package is loaded into Emacs.

By default, module functions created by make_function are not interactive. To make them interactive, you can use the following function.

Function: void make_interactive (emacs_env *env, emacs_value function, emacs_value spec)

This function, which is available since Emacs 28, makes the function function interactive using the interactive specification spec. Emacs interprets spec like the argument to the interactive form. Using interactive, and see Code Characters for interactive. function must be an Emacs module function returned by make_function.

Note that there is no native module support for retrieving the interactive specification of a module function. Use the function interactive-form for that. Using interactive. It is not possible to make a module function non-interactive once you have made it interactive using make_interactive.

If you want to run some code when a module function object (i.e., an object returned by make_function) is garbage-collected, you can install a function finalizer. Function finalizers are available since Emacs 28. For example, if you have passed some heap-allocated structure to the data argument of make_function, you can use the finalizer to deallocate the structure. See (libc)Basic Allocation, and see (libc)Freeing after Malloc. The finalizer function has the following signature:

void finalizer (void *data)

Here, data receives the value passed to data when calling make_function. Note that the finalizer can’t interact with Emacs in any way.

Directly after calling make_function, the newly-created function doesn’t have a finalizer. Use set_function_finalizer to add one, if desired.

Function: void emacs_finalizer (void *ptr)

The header emacs-module.h provides the type emacs_finalizer as a type alias for an Emacs finalizer function.

Function: emacs_finalizer get_function_finalizer (emacs_env *env, emacs_value arg)

This function, which is available since Emacs 28, returns the function finalizer associated with the module function represented by arg. arg must refer to a module function, that is, an object returned by make_function. If no finalizer is associated with the function, NULL is returned.

Function: void set_function_finalizer (emacs_env *env, emacs_value arg, emacs_finalizer fin)

This function, which is available since Emacs 28, sets the function finalizer associated with the module function represented by arg to fin. arg must refer to a module function, that is, an object returned by make_function. fin can either be NULL to clear arg’s function finalizer, or a pointer to a function to be called when the object represented by arg is garbage-collected. At most one function finalizer can be set per function; if arg already has a finalizer, it is replaced by fin.


E.7.3 Conversion Between Lisp and Module Values

With very few exceptions, most modules need to exchange data with Lisp programs that call them: accept arguments to module functions and return values from module functions. For this purpose, the module API provides the emacs_value type, which represents Emacs Lisp objects communicated via the API; it is the functional equivalent of the Lisp_Object type used in Emacs C primitives (see Writing Emacs Primitives). This section describes the parts of the module API that allow creating emacs_value objects corresponding to basic Lisp data types, and how to access from C data in emacs_value objects that correspond to Lisp objects.

All of the functions described below are actually function pointers provided via the pointer to the environment which every module function accepts. Therefore, module code should call these functions through the environment pointer, like this:

emacs_env *env;  /* the environment pointer */
env->some_function (arguments...);

The emacs_env pointer will usually come from the first argument to the module function, or from the call to get_environment if you need the environment in the module initialization function.

Most of the functions described below became available in Emacs 25, the first Emacs release that supported dynamic modules. For the few functions that became available in later Emacs releases, we mention the first Emacs version that supported them.

The following API functions extract values of various C data types from emacs_value objects. They all raise the wrong-type-argument error condition (see Type Predicates) if the argument emacs_value object is not of the type expected by the function. See Nonlocal Exits in Modules, for details of how signaling errors works in Emacs modules, and how to catch error conditions inside the module before they are reported to Emacs. The API function type_of (see type_of) can be used to obtain the type of a emacs_value object.

Function: intmax_t extract_integer (emacs_env *env, emacs_value arg)

This function returns the value of a Lisp integer specified by arg. The C data type of the return value, intmax_t, is the widest integer data type supported by the C compiler, typically long long. If the value of arg doesn’t fit into an intmax_t, the function signals an error using the error symbol overflow-error.

Function: bool extract_big_integer (emacs_env *env, emacs_value arg, int *sign, ptrdiff_t *count, emacs_limb_t *magnitude)

This function, which is available since Emacs 27, extracts the integer value of arg. The value of arg must be an integer (fixnum or bignum). If sign is not NULL, it stores the sign of arg (-1, 0, or +1) into *sign. The magnitude is stored into magnitude as follows. If count and magnitude are both non-NULL, then magnitude must point to an array of at least *count unsigned long elements. If magnitude is large enough to hold the magnitude of arg, then this function writes the magnitude into the magnitude array in little-endian form, stores the number of array elements written into *count, and returns true. If magnitude is not large enough, it stores the required array size into *count, signals an error, and returns false. If count is not NULL and magnitude is NULL, then the function stores the required array size into *count and returns true.

Emacs guarantees that the maximum required value of *count never exceeds min (PTRDIFF_MAX, SIZE_MAX) / sizeof (emacs_limb_t), so you can use malloc (*count * sizeof *magnitude) to allocate the magnitude array without worrying about integer overflow in the size calculation.

Type alias: emacs_limb_t

This is an unsigned integer type, used as the element type for the magnitude arrays for the big integer conversion functions. The type is guaranteed to have unique object representations, i.e., no padding bits.

Macro: EMACS_LIMB_MAX

This macro expands to a constant expression specifying the maximum possible value for an emacs_limb_t object. The expression is suitable for use in #if.

Function: double extract_float (emacs_env *env, emacs_value arg)

This function returns the value of a Lisp float specified by arg, as a C double value.

Function: struct timespec extract_time (emacs_env *env, emacs_value arg)

This function, which is available since Emacs 27, interprets arg as an Emacs Lisp time value and returns the corresponding struct timespec. See Time of Day. struct timespec represents a timestamp with nanosecond precision. It has the following members:

time_t tv_sec

Whole number of seconds.

long tv_nsec

Fractional seconds as a number of nanoseconds. For timestamps returned by extract_time, this is always nonnegative and less than one billion. (Although POSIX requires the type of tv_nsec to be long, the type is long long on some nonstandard platforms.)

See (libc)Elapsed Time.

If time has higher precision than nanoseconds, then this function truncates it to nanosecond precision towards negative infinity. This function signals an error if time (truncated to nanoseconds) cannot be represented by struct timespec. For example, if time_t is a 32-bit integer type, then a time value of ten billion seconds would signal an error, but a time value of 600 picoseconds would get truncated to zero.

If you need to deal with time values that are not representable by struct timespec, or if you want higher precision, call the Lisp function encode-time and work with its return value. See Time Conversion.

Function: bool copy_string_contents (emacs_env *env, emacs_value arg, char *buf, ptrdiff_t *len)

This function stores the UTF-8 encoded text of a Lisp string specified by arg in the array of char pointed by buf, which should have enough space to hold at least *len bytes, including the terminating null byte. The argument len must not be a NULL pointer, and, when the function is called, it should point to a value that specifies the size of buf in bytes.

If the buffer size specified by *len is large enough to hold the string’s text, the function stores in *len the actual number of bytes copied to buf, including the terminating null byte, and returns true. If the buffer is too small, the function raises the args-out-of-range error condition, stores the required number of bytes in *len, and returns false. See Nonlocal Exits in Modules, for how to handle pending error conditions.

The argument buf can be a NULL pointer, in which case the function stores in *len the number of bytes required for storing the contents of arg, and returns true. This is how you can determine the size of buf needed to store a particular string: first call copy_string_contents with NULL as buf, then allocate enough memory to hold the number of bytes stored by the function in *len, and call the function again with non-NULL buf to actually perform the text copying.

Function: emacs_value vec_get (emacs_env *env, emacs_value vector, ptrdiff_t index)

This function returns the element of vector at index. The index of the first vector element is zero. The function raises the args-out-of-range error condition if the value of index is invalid. To extract C data from the value the function returns, use the other extraction functions described here, as appropriate for the Lisp data type stored in that element of the vector.

Function: ptrdiff_t vec_size (emacs_env *env, emacs_value vector)

This function returns the number of elements in vector.

Function: void vec_set (emacs_env *env, emacs_value vector, ptrdiff_t index, emacs_value value)

This function stores value in the element of vector whose index is index. It raises the args-out-of-range error condition if the value of index is invalid.

The following API functions create emacs_value objects from basic C data types. They all return the created emacs_value object.

Function: emacs_value make_integer (emacs_env *env, intmax_t n)

This function takes an integer argument n and returns the corresponding emacs_value object. It returns either a fixnum or a bignum depending on whether the value of n is inside the limits set by most-negative-fixnum and most-positive-fixnum (see Integer Basics).

Function: emacs_value make_big_integer (emacs_env *env, int sign, ptrdiff_t count, const emacs_limb_t *magnitude)

This function, which is available since Emacs 27, takes an arbitrary-sized integer argument and returns a corresponding emacs_value object. The sign argument gives the sign of the return value. If sign is nonzero, then magnitude must point to an array of at least count elements specifying the little-endian magnitude of the return value.

The following example uses the GNU Multiprecision Library (GMP) to calculate the next probable prime after a given integer. See (gmp)Top, for a general overview of GMP, and see (gmp)Integer Import and Export for how to convert the magnitude array to and from GMP mpz_t values.

#include <emacs-module.h>
int plugin_is_GPL_compatible;

#include <assert.h>
#include <limits.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#include <gmp.h>

static void
memory_full (emacs_env *env)
{
  static const char message[] = "Memory exhausted";
  emacs_value data = env->make_string (env, message,
                                       strlen (message));
  env->non_local_exit_signal
    (env, env->intern (env, "error"),
     env->funcall (env, env->intern (env, "list"), 1, &data));
}

enum
{
  order = -1, endian = 0, nails = 0,
  limb_size = sizeof (emacs_limb_t),
  max_nlimbs = ((SIZE_MAX < PTRDIFF_MAX ? SIZE_MAX : PTRDIFF_MAX)
                / limb_size)
};

static bool
extract_big_integer (emacs_env *env, emacs_value arg, mpz_t result)
{
  ptrdiff_t nlimbs;
  bool ok = env->extract_big_integer (env, arg, NULL, &nlimbs, NULL);
  if (!ok)
    return false;
  assert (0 < nlimbs && nlimbs <= max_nlimbs);
  emacs_limb_t *magnitude = malloc (nlimbs * limb_size);
  if (magnitude == NULL)
    {
      memory_full (env);
      return false;
    }
  int sign;
  ok = env->extract_big_integer (env, arg, &sign, &nlimbs, magnitude);
  assert (ok);
  mpz_import (result, nlimbs, order, limb_size, endian, nails, magnitude);
  free (magnitude);
  if (sign < 0)
    mpz_neg (result, result);
  return true;
}

static emacs_value
make_big_integer (emacs_env *env, const mpz_t value)
{
  size_t nbits = mpz_sizeinbase (value, 2);
  int bitsperlimb = CHAR_BIT * limb_size - nails;
  size_t nlimbs = nbits / bitsperlimb + (nbits % bitsperlimb != 0);
  emacs_limb_t *magnitude
    = nlimbs <= max_nlimbs ? malloc (nlimbs * limb_size) : NULL;
  if (magnitude == NULL)
    {
      memory_full (env);
      return NULL;
    }
  size_t written;
  mpz_export (magnitude, &written, order, limb_size, endian, nails, value);
  assert (written == nlimbs);
  assert (nlimbs <= PTRDIFF_MAX);
  emacs_value result = env->make_big_integer (env, mpz_sgn (value),
                                              nlimbs, magnitude);
  free (magnitude);
  return result;
}

static emacs_value
next_prime (emacs_env *env, ptrdiff_t nargs, emacs_value *args,
            void *data)
{
  assert (nargs == 1);
  mpz_t p;
  mpz_init (p);
  extract_big_integer (env, args[0], p);

  /* Assume Emacs is linked to the full GMP library,
     not to its mini-gmp subset that lacks mpz_nextprime.  */
  mpz_nextprime (p, p);

  emacs_value result = make_big_integer (env, p);
  mpz_clear (p);
  return result;
}

int
emacs_module_init (struct emacs_runtime *runtime)
{
  emacs_env *env = runtime->get_environment (runtime);
  emacs_value symbol = env->intern (env, "next-prime");
  emacs_value func
    = env->make_function (env, 1, 1, next_prime, NULL, NULL);
  emacs_value args[] = {symbol, func};
  env->funcall (env, env->intern (env, "defalias"), 2, args);
  return 0;
}
Function: emacs_value make_float (emacs_env *env, double d)

This function takes a double argument d and returns the corresponding Emacs floating-point value.

Function: emacs_value make_time (emacs_env *env, struct timespec time)

This function, which is available since Emacs 27, takes a struct timespec argument time and returns the corresponding Emacs timestamp as a pair (ticks . hz). See Time of Day. The return value represents exactly the same timestamp as time: all input values are representable, and there is never a loss of precision. time.tv_sec and time.tv_nsec can be arbitrary values. In particular, there’s no requirement that time be normalized. This means that time.tv_nsec can be negative or larger than 999,999,999.

Function: emacs_value make_string (emacs_env *env, const char *str, ptrdiff_t len)

This function creates an Emacs string from C text string pointed by str whose length in bytes, not including the terminating null byte, is len. The original string in str can be either an ASCII string or a UTF-8 encoded non-ASCII string; it can include embedded null bytes, and doesn’t have to end in a terminating null byte at str[len]. The function raises the overflow-error error condition if len is negative or exceeds the maximum length of an Emacs string. If len is zero, then str can be NULL, otherwise it must point to valid memory. For nonzero len, make_string returns unique mutable string objects.

Function: emacs_value make_unibyte_string (emacs_env *env, const char *str, ptrdiff_t len)

This function, which is available since Emacs 28, is like make_string, but has no restrictions on the values of the bytes in the C string, and can be used to pass binary data to Emacs in the form of a unibyte string.

The API does not provide functions to manipulate Lisp data structures, for example, create lists with cons and list (see Building Cons Cells and Lists), extract list members with car and cdr (see Accessing Elements of Lists), create vectors with vector (see Functions for Vectors), etc. For these, use intern and funcall, described in the next subsection, to call the corresponding Lisp functions.

Normally, emacs_value objects have a rather short lifetime: it ends when the emacs_env pointer used for their creation goes out of scope. Occasionally, you may need to create global references: emacs_value objects that live as long as you wish. Use the following two functions to manage such objects.

Function: emacs_value make_global_ref (emacs_env *env, emacs_value value)

This function returns a global reference for value.

Function: void free_global_ref (emacs_env *env, emacs_value global_value)

This function frees the global_value previously created by make_global_ref. The global_value is no longer valid after the call. Your module code should pair each call to make_global_ref with the corresponding free_global_ref.

An alternative to keeping around C data structures that need to be passed to module functions later is to create user pointer objects. A user pointer, or user-ptr, object is a Lisp object that encapsulates a C pointer and can have an associated finalizer function, which is called when the object is garbage-collected (see Garbage Collection). The module API provides functions to create and access user-ptr objects. These functions raise the wrong-type-argument error condition if they are called on emacs_value that doesn’t represent a user-ptr object.

Function: emacs_value make_user_ptr (emacs_env *env, emacs_finalizer fin, void *ptr)

This function creates and returns a user-ptr object which wraps the C pointer ptr. The finalizer function fin can be a NULL pointer (meaning no finalizer), or it can be a function of the following signature:

typedef void (*emacs_finalizer) (void *ptr);

If fin is not a NULL pointer, it will be called with the ptr as the argument when the user-ptr object is garbage-collected. Don’t run any expensive code in a finalizer, because GC must finish quickly to keep Emacs responsive.

Function: void *get_user_ptr (emacs_env *env, emacs_value arg)

This function extracts the C pointer from the Lisp object represented by arg.

Function: void set_user_ptr (emacs_env *env, emacs_value arg, void *ptr)

This function sets the C pointer embedded in the user-ptr object represented by arg to ptr.

Function: emacs_finalizer get_user_finalizer (emacs_env *env, emacs_value arg)

This function returns the finalizer of the user-ptr object represented by arg, or NULL if it doesn’t have a finalizer.

Function: void set_user_finalizer (emacs_env *env, emacs_value arg, emacs_finalizer fin)

This function changes the finalizer of the user-ptr object represented by arg to be fin. If fin is a NULL pointer, the user-ptr object will have no finalizer.

Note that the emacs_finalizer type works for both user pointer an module function finalizers. See Module Function Finalizers.


E.7.4 Miscellaneous Convenience Functions for Modules

This subsection describes a few convenience functions provided by the module API. Like the functions described in previous subsections, all of them are actually function pointers, and need to be called via the emacs_env pointer. Description of functions that were introduced after Emacs 25 calls out the first version where they became available.

Function: bool eq (emacs_env *env, emacs_value a, emacs_value b)

This function returns true if the Lisp objects represented by a and b are identical, false otherwise. This is the same as the Lisp function eq (see Equality Predicates), but avoids the need to intern the objects represented by the arguments.

There are no API functions for other equality predicates, so you will need to use intern and funcall, described below, to perform more complex equality tests.

Function: bool is_not_nil (emacs_env *env, emacs_value arg)

This function tests whether the Lisp object represented by arg is non-nil; it returns true or false accordingly.

Note that you could implement an equivalent test by using intern to get an emacs_value representing nil, then use eq, described above, to test for equality. But using this function is more convenient.

Function: emacs_value type_of (emacs_env *env, emacs_value arg)

This function returns the type of arg as a value that represents a symbol: string for a string, integer for an integer, process for a process, etc. See Type Predicates. You can use intern and eq to compare against known type symbols, if your code needs to depend on the object type.

Function: emacs_value intern (emacs_env *env, const char *name)

This function returns an interned Emacs symbol whose name is name, which should be an ASCII null-terminated string. It creates a new symbol if one does not already exist.

Together with funcall, described below, this function provides a means for invoking any Lisp-callable Emacs function, provided that its name is a pure ASCII string. For example, here’s how to intern a symbol whose name name_str is non-ASCII, by calling the more powerful Emacs intern function (see Creating and Interning Symbols):

emacs_value fintern = env->intern (env, "intern");
emacs_value sym_name =
  env->make_string (env, name_str, strlen (name_str));
emacs_value symbol = env->funcall (env, fintern, 1, &sym_name);
Function: emacs_value funcall (emacs_env *env, emacs_value func, ptrdiff_t nargs, emacs_value *args)

This function calls the specified func passing it nargs arguments from the array pointed to by args. The argument func can be a function symbol (e.g., returned by intern described above), a module function returned by make_function (see Writing Module Functions), a subroutine written in C, etc. If nargs is zero, args can be a NULL pointer.

The function returns the value that func returned.

If your module includes potentially long-running code, it is a good idea to check from time to time in that code whether the user wants to quit, e.g., by typing C-g (see Quitting). The following function, which is available since Emacs 26.1, is provided for that purpose.

Function: bool should_quit (emacs_env *env)

This function returns true if the user wants to quit. In that case, we recommend that your module function aborts any on-going processing and returns as soon as possible. In most cases, use process_input instead.

To process input events in addition to checking whether the user wants to quit, use the following function, which is available since Emacs 27.1.

Function: enum emacs_process_input_result process_input (emacs_env *env)

This function processes pending input events. It returns emacs_process_input_quit if the user wants to quit or an error occurred while processing signals. In that case, we recommend that your module function aborts any on-going processing and returns as soon as possible. If the module code may continue running, process_input returns emacs_process_input_continue. The return value is emacs_process_input_continue if and only if there is no pending nonlocal exit in env. If the module continues after calling process_input, global state such as variable values and buffer content may have been modified in arbitrary ways.

Function: int open_channel (emacs_env *env, emacs_value pipe_process)

This function, which is available since Emacs 28, opens a channel to an existing pipe process. pipe_process must refer to an existing pipe process created by make-pipe-process. Pipe Processes. If successful, the return value will be a new file descriptor that you can use to write to the pipe. Unlike all other module functions, you can use the returned file descriptor from arbitrary threads, even if no module environment is active. You can use the write function to write to the file descriptor. Once done, close the file descriptor using close. (libc)Low-Level I/O.


E.7.5 Nonlocal Exits in Modules

Emacs Lisp supports nonlocal exits, whereby program control is transferred from one point in a program to another remote point. See Nonlocal Exits. Thus, Lisp functions called by your module might exit nonlocally by calling signal or throw, and your module functions must handle such nonlocal exits properly. Such handling is needed because C programs will not automatically release resources and perform other cleanups in these cases; your module code must itself do it. The module API provides facilities for that, described in this subsection. They are generally available since Emacs 25; those of them that became available in later releases explicitly call out the first Emacs version where they became part of the API.

When some Lisp code called by a module function signals an error or throws, the nonlocal exit is trapped, and the pending exit and its associated data are stored in the environment. Whenever a nonlocal exit is pending in the environment, any module API function called with a pointer to that environment will return immediately without any processing (the functions non_local_exit_check, non_local_exit_get, and non_local_exit_clear are exceptions from this rule). If your module function then does nothing and returns to Emacs, a pending nonlocal exit will cause Emacs to act on it: signal an error or throw to the corresponding catch.

So the simplest “handling” of nonlocal exits in module functions is to do nothing special and let the rest of your code to run as if nothing happened. However, this can cause two classes of problems:

  • Your module function might use uninitialized or undefined values, since API functions return immediately without producing the expected results.
  • Your module might leak resources, because it might not have the opportunity to release them.

Therefore, we recommend that your module functions check for nonlocal exit conditions and recover from them, using the functions described below.

Function: enum emacs_funcall_exit non_local_exit_check (emacs_env *env)

This function returns the kind of nonlocal exit condition stored in env. The possible values are:

emacs_funcall_exit_return

The last API function exited normally.

emacs_funcall_exit_signal

The last API function signaled an error.

emacs_funcall_exit_throw

The last API function exited via throw.

Function: enum emacs_funcall_exit non_local_exit_get (emacs_env *env, emacs_value *symbol, emacs_value *data)

This function returns the kind of nonlocal exit condition stored in env, like non_local_exit_check does, but it also returns the full information about the nonlocal exit, if any. If the return value is emacs_funcall_exit_signal, the function stores the error symbol in *symbol and the error data in *data (see How to Signal an Error). If the return value is emacs_funcall_exit_throw, the function stores the catch tag symbol in *symbol and the throw value in *data. The function doesn’t store anything in memory pointed by these arguments when the return value is emacs_funcall_exit_return. If the function fails to allocate storage for symbol or data, it stores a value representing the symbol module-out-of-memory in *symbol, stores a value representing nil in *data, and returns emacs_funcall_exit_signal.

You should check nonlocal exit conditions where it matters: before you allocated some resource or after you allocated a resource that might need freeing, or where a failure means further processing is impossible or infeasible.

Once your module function detected that a nonlocal exit is pending, it can either return to Emacs (after performing the necessary local cleanup), or it can attempt to recover from the nonlocal exit. The following API functions will help with these tasks.

Function: void non_local_exit_clear (emacs_env *env)

This function clears the pending nonlocal exit conditions and data from env. After calling it, the module API functions will work normally. Use this function if your module function can recover from nonlocal exits of the Lisp functions it calls and continue, and also before calling any of the following two functions (or any other API functions, if you want them to perform their intended processing when a nonlocal exit is pending).

Function: void non_local_exit_throw (emacs_env *env, emacs_value tag, emacs_value value)

This function throws to the Lisp catch symbol represented by tag, passing it value as the value to return. Your module function should in general return soon after calling this function. One use of this function is when you want to re-throw a non-local exit from one of the called API or Lisp functions.

Function: void non_local_exit_signal (emacs_env *env, emacs_value symbol, emacs_value data)

This function signals the error represented by the error symbol symbol with the specified error data data. The module function should return soon after calling this function. This function could be useful, e.g., for signaling errors from module functions to Emacs.


E.8 Object Internals

Emacs Lisp provides a rich set of the data types. Some of them, like cons cells, integers and strings, are common to nearly all Lisp dialects. Some others, like markers and buffers, are quite special and needed to provide the basic support to write editor commands in Lisp. To implement such a variety of object types and provide an efficient way to pass objects between the subsystems of an interpreter, there is a set of C data structures and a special type to represent the pointers to all of them, which is known as tagged pointer.

In C, the tagged pointer is an object of type Lisp_Object. Any initialized variable of such a type always holds the value of one of the following basic data types: integer, symbol, string, cons cell, float, or vectorlike object. Each of these data types has the corresponding tag value. All tags are enumerated by enum Lisp_Type and placed into a 3-bit bitfield of the Lisp_Object. The rest of the bits is the value itself. Integers are immediate, i.e., directly represented by those value bits, and all other objects are represented by the C pointers to a corresponding object allocated from the heap. Width of the Lisp_Object is platform- and configuration-dependent: usually it’s equal to the width of an underlying platform pointer (i.e., 32-bit on a 32-bit machine and 64-bit on a 64-bit one), but also there is a special configuration where Lisp_Object is 64-bit but all pointers are 32-bit. The latter trick was designed to overcome the limited range of values for Lisp integers on a 32-bit system by using 64-bit long long type for Lisp_Object.

The following C data structures are defined in lisp.h to represent the basic data types beyond integers:

struct Lisp_Cons

Cons cell, an object used to construct lists.

struct Lisp_String

String, the basic object to represent a sequence of characters.

struct Lisp_Vector

Array, a fixed-size set of Lisp objects which may be accessed by an index.

struct Lisp_Symbol

Symbol, the unique-named entity commonly used as an identifier.

struct Lisp_Float

Floating-point value.

These types are the first-class citizens of an internal type system. Since the tag space is limited, all other types are the subtypes of Lisp_Vectorlike. Vector subtypes are enumerated by enum pvec_type, and nearly all complex objects like windows, buffers, frames, and processes fall into this category.

Below there is a description of a few subtypes of Lisp_Vectorlike. Buffer object represents the text to display and edit. Window is the part of display structure which shows the buffer or is used as a container to recursively place other windows on the same frame. (Do not confuse Emacs Lisp window object with the window as an entity managed by the user interface system like X; in Emacs terminology, the latter is called frame.) Finally, process object is used to manage the subprocesses.


E.8.1 Buffer Internals

Two structures (see buffer.h) are used to represent buffers in C. The buffer_text structure contains fields describing the text of a buffer; the buffer structure holds other fields. In the case of indirect buffers, two or more buffer structures reference the same buffer_text structure.

Here are some of the fields in struct buffer_text:

beg

The address of the buffer contents. The buffer contents is a linear C array of char, with the gap somewhere in its midst.

gpt
gpt_byte

The character and byte positions of the buffer gap. See The Buffer Gap.

z
z_byte

The character and byte positions of the end of the buffer text.

gap_size

The size of buffer’s gap. See The Buffer Gap.

modiff
save_modiff
chars_modiff
overlay_modiff

These fields count the number of buffer-modification events performed in this buffer. modiff is incremented after each buffer-modification event, and is never otherwise changed; save_modiff contains the value of modiff the last time the buffer was visited or saved; chars_modiff counts only modifications to the characters in the buffer, ignoring all other kinds of changes (such as text properties); and overlay_modiff counts only modifications to the buffer’s overlays.

beg_unchanged
end_unchanged

The number of characters at the start and end of the text that are known to be unchanged since the last complete redisplay.

unchanged_modified
overlay_unchanged_modified

The values of modiff and overlay_modiff, respectively, after the last complete redisplay. If their current values match modiff or overlay_modiff, that means beg_unchanged and end_unchanged contain no useful information.

markers

The markers that refer to this buffer. This is actually a single marker, and successive elements in its marker chain (a linked list) are the other markers referring to this buffer text.

intervals

The interval tree which records the text properties of this buffer.

Some of the fields of struct buffer are:

header

A header of type union vectorlike_header is common to all vectorlike objects.

own_text

A struct buffer_text structure that ordinarily holds the buffer contents. In indirect buffers, this field is not used.

text

A pointer to the buffer_text structure for this buffer. In an ordinary buffer, this is the own_text field above. In an indirect buffer, this is the own_text field of the base buffer.

next

A pointer to the next buffer, in the chain of all buffers, including killed buffers. This chain is used only for allocation and garbage collection, in order to collect killed buffers properly.

pt
pt_byte

The character and byte positions of point in a buffer.

begv
begv_byte

The character and byte positions of the beginning of the accessible range of text in the buffer.

zv
zv_byte

The character and byte positions of the end of the accessible range of text in the buffer.

base_buffer

In an indirect buffer, this points to the base buffer. In an ordinary buffer, it is null.

local_flags

This field contains flags indicating that certain variables are local in this buffer. Such variables are declared in the C code using DEFVAR_PER_BUFFER, and their buffer-local bindings are stored in fields in the buffer structure itself. (Some of these fields are described in this table.)

modtime

The modification time of the visited file. It is set when the file is written or read. Before writing the buffer into a file, this field is compared to the modification time of the file to see if the file has changed on disk. See Buffer Modification.

auto_save_modified

The time when the buffer was last auto-saved.

last_window_start

The window-start position in the buffer as of the last time the buffer was displayed in a window.

clip_changed

This flag indicates that narrowing has changed in the buffer. See Narrowing.

prevent_redisplay_optimizations_p

This flag indicates that redisplay optimizations should not be used to display this buffer.

inhibit_buffer_hooks

This flag indicates that the buffer should not run the hooks kill-buffer-hook, kill-buffer-query-functions (see Killing Buffers), and buffer-list-update-hook (see The Buffer List). It is set at buffer creation (see Creating Buffers), and avoids slowing down internal or temporary buffers, such as those created by with-temp-buffer (see Current Buffer).

name

A Lisp string that names the buffer. It is guaranteed to be unique. See Buffer Names. This and the following fields have their names in the C struct definition end in a _ to indicate that they should not be accessed directly, but via the BVAR macro, like this:

  Lisp_Object buf_name = BVAR (buffer, name);
save_length

The length of the file this buffer is visiting, when last read or saved. It can have 2 special values: −1 means auto-saving was turned off in this buffer, and −2 means don’t turn off auto-saving if buffer text shrinks a lot. This and other fields concerned with saving are not kept in the buffer_text structure because indirect buffers are never saved.

directory

The directory for expanding relative file names. This is the value of the buffer-local variable default-directory (see Functions that Expand Filenames).

filename

The name of the file visited in this buffer, or nil. This is the value of the buffer-local variable buffer-file-name (see Buffer File Name).

undo_list
backed_up
auto_save_file_name
auto_save_file_format
read_only
file_format
file_truename
invisibility_spec
display_count
display_time

These fields store the values of Lisp variables that are automatically buffer-local (see Buffer-Local Variables), whose corresponding variable names have the additional prefix buffer- and have underscores replaced with dashes. For instance, undo_list stores the value of buffer-undo-list.

mark

The mark for the buffer. The mark is a marker, hence it is also included on the list markers. See The Mark.

local_var_alist

The association list describing the buffer-local variable bindings of this buffer, not including the built-in buffer-local bindings that have special slots in the buffer object. (Those slots are omitted from this table.) See Buffer-Local Variables.

major_mode

Symbol naming the major mode of this buffer, e.g., lisp-mode.

mode_name

Pretty name of the major mode, e.g., "Lisp".

keymap
abbrev_table
syntax_table
category_table
display_table

These fields store the buffer’s local keymap (see Keymaps), abbrev table (see Abbrev Tables), syntax table (see Syntax Tables), category table (see Categories), and display table (see Display Tables).

downcase_table
upcase_table
case_canon_table

These fields store the conversion tables for converting text to lower case, upper case, and for canonicalizing text for case-fold search. See The Case Table.

minor_modes

An alist of the minor modes of this buffer.

pt_marker
begv_marker
zv_marker

These fields are only used in an indirect buffer, or in a buffer that is the base of an indirect buffer. Each holds a marker that records pt, begv, and zv respectively, for this buffer when the buffer is not current.

mode_line_format
header_line_format
tab_width
fill_column
left_margin
auto_fill_function
truncate_lines
word_wrap
ctl_arrow
bidi_display_reordering
bidi_paragraph_direction
selective_display
selective_display_ellipses
overwrite_mode
abbrev_mode
mark_active
enable_multibyte_characters
buffer_file_coding_system
cache_long_line_scans
point_before_scroll
left_fringe_width
right_fringe_width
fringes_outside_margins
scroll_bar_width
indicate_empty_lines
indicate_buffer_boundaries
fringe_indicator_alist
fringe_cursor_alist
scroll_up_aggressively
scroll_down_aggressively
cursor_type
cursor_in_non_selected_windows

These fields store the values of Lisp variables that are automatically buffer-local (see Buffer-Local Variables), whose corresponding variable names have underscores replaced with dashes. For instance, mode_line_format stores the value of mode-line-format.

overlays

The interval tree containing this buffer’s overlays.

last_selected_window

This is the last window that was selected with this buffer in it, or nil if that window no longer displays this buffer.


E.8.2 Window Internals

The fields of a window (for a complete list, see the definition of struct window in window.h) include:

frame

The frame that this window is on, as a Lisp object.

mini

Non-zero if this window is a minibuffer window, a window showing the minibuffer or the echo area.

pseudo_window_p

Non-zero if this window is a pseudo window. A pseudo window is either a window used to display the menu bar or the tool bar (when Emacs uses toolkits that don’t display their own menu bar and tool bar) or the tab bar or a window showing a tooltip on a tooltip frame. Pseudo windows are in general not accessible from Lisp code.

parent

Internally, Emacs arranges windows in a tree; each group of siblings has a parent window whose area includes all the siblings. This field points to the window’s parent in that tree, as a Lisp object. For the root window of the tree and a minibuffer window this is always nil.

Parent windows do not display buffers, and play little role in display except to shape their child windows. Emacs Lisp programs cannot directly manipulate parent windows; they operate on the windows at the leaves of the tree, which actually display buffers.

contents

For a leaf window and windows showing a tooltip, this is the buffer, as a Lisp object, that the window is displaying. For an internal (“parent”) window, this is its first child window. For a pseudo window showing a menu or tool bar this is nil. It is also nil for a window that has been deleted.

next
prev

The next and previous sibling of this window as Lisp objects. next is nil if the window is the right-most or bottom-most in its group; prev is nil if it is the left-most or top-most in its group. Whether the sibling is left/right or up/down is determined by the horizontal field of the sibling’s parent: if it’s non-zero, the siblings are arranged horizontally.

As a special case, next of a frame’s root window points to the frame’s minibuffer window, provided this is not a minibuffer-only or minibuffer-less frame. On such frames prev of the minibuffer window points to that frame’s root window. In any other case, the root window’s next and the minibuffer window’s (if present) prev fields are nil.

left_col

The left-hand edge of the window, measured in columns, relative to the leftmost column (column 0) of the window’s native frame.

top_line

The top edge of the window, measured in lines, relative to the topmost line (line 0) of the window’s native frame.

pixel_left
pixel_top

The left-hand and top edges of this window, measured in pixels, relative to the top-left corner (0, 0) of the window’s native frame.

total_cols
total_lines

The total width and height of the window, measured in columns and lines respectively. The values include scroll bars and fringes, dividers and/or the separator line on the right of the window (if any).

pixel_width;
pixel_height;

The total width and height of the window measured in pixels.

start

A marker pointing to the position in the buffer that is the first character (in the logical order, see Bidirectional Display) displayed in the window.

pointm

This is the value of point in the current buffer when this window is selected; when it is not selected, it retains its previous value.

old_pointm

The value of pointm at the last redisplay time.

force_start

If this flag is non-nil, it says that the window has been scrolled explicitly by the Lisp program, and the value of the window’s start was set for redisplay to honor. This affects what the next redisplay does if point is off the screen: instead of scrolling the window to show the text around point, it moves point to a location that is on the screen.

optional_new_start

This is similar to force_start, but the next redisplay will only obey it if point stays visible.

start_at_line_beg

Non-nil means current value of start was the beginning of a line when it was chosen.

use_time

This is the last time that the window was selected. The function get-lru-window uses this field.

sequence_number

A unique number assigned to this window when it was created.

last_modified

The modiff field of the window’s buffer, as of the last time a redisplay completed in this window.

last_overlay_modified

The overlay_modiff field of the window’s buffer, as of the last time a redisplay completed in this window.

last_point

The buffer’s value of point, as of the last time a redisplay completed in this window.

last_had_star

A non-zero value means the window’s buffer was modified when the window was last updated.

vertical_scroll_bar_type
horizontal_scroll_bar_type

The types of this window’s vertical and horizontal scroll bars.

scroll_bar_width
scroll_bar_height

The width of this window’s vertical scroll bar and the height of this window’s horizontal scroll bar, in pixels.

left_margin_cols
right_margin_cols

The widths of the left and right margins in this window. A value of zero means no margin.

left_fringe_width
right_fringe_width

The pixel widths of the left and right fringes in this window. A value of −1 means use the values of the frame.

fringes_outside_margins

A non-zero value means the fringes outside the display margins; othersize they are between the margin and the text.

window_end_pos

This is computed as z minus the buffer position of the last glyph in the current matrix of the window. The value is only valid if window_end_valid is non-zero.

window_end_bytepos

The byte position corresponding to window_end_pos.

window_end_vpos

The window-relative vertical position of the line containing window_end_pos.

window_end_valid

This field is set to a non-zero value if window_end_pos and window_end_vpos are truly valid. This is zero if nontrivial redisplay is preempted, since in that case the display that window_end_pos was computed for did not get onto the screen.

cursor

A structure describing where the cursor is in this window.

last_cursor_vpos

The window-relative vertical position of the line showing the cursor as of the last redisplay that finished.

phys_cursor

A structure describing where the cursor of this window physically is.

phys_cursor_type
phys_cursor_height
phys_cursor_width

The type, height, and width of the cursor that was last displayed on this window.

phys_cursor_on_p

This field is non-zero if the cursor is physically on.

cursor_off_p

Non-zero means the cursor in this window is logically off. This is used for blinking the cursor.

last_cursor_off_p

This field contains the value of cursor_off_p as of the time of the last redisplay.

must_be_updated_p

This is set to 1 during redisplay when this window must be updated.

hscroll

This is the number of columns that the display in the window is scrolled horizontally to the left. Normally, this is 0. When only the current line is hscrolled, this describes how much the current line is scrolled.

min_hscroll

Minimum value of hscroll, set by the user via set-window-hscroll (see Horizontal Scrolling). When only the current line is hscrolled, this describes the horizontal scrolling of lines other than the current one.

vscroll

Vertical scroll amount, in pixels. Normally, this is 0.

dedicated

Non-nil if this window is dedicated to its buffer.

combination_limit

This window’s combination limit, meaningful only for a parent window. If this is t, then it is not allowed to delete this window and recombine its child windows with other siblings of this window.

window_parameters

The alist of this window’s parameters.

display_table

The window’s display table, or nil if none is specified for it.

update_mode_line

Non-zero means this window’s mode line needs to be updated.

mode_line_height
header_line_height

The height in pixels of the mode line and the header line, or −1 if not known.

base_line_number

The line number of a certain position in the buffer, or zero. This is used for displaying the line number of point in the mode line.

base_line_pos

The position in the buffer for which the line number is known, or zero meaning none is known. If it is −1, don’t display the line number as long as the window shows that buffer.

column_number_displayed

The column number currently displayed in this window’s mode line, or −1 if column numbers are not being displayed.

current_matrix
desired_matrix

Glyph matrices describing the current and desired display of this window.


E.8.3 Process Internals

The fields of a process (for a complete list, see the definition of struct Lisp_Process in process.h) include:

name

A Lisp string, the name of the process.

command

A list containing the command arguments that were used to start this process. For a network or serial process, it is nil if the process is running or t if the process is stopped.

filter

A Lisp function used to accept output from the process.

sentinel

A Lisp function called whenever the state of the process changes.

buffer

The associated buffer of the process.

pid

An integer, the operating system’s process ID. Pseudo-processes such as network or serial connections use a value of 0.

childp

A flag, t if this is really a child process. For a network or serial connection, it is a plist based on the arguments to make-network-process or make-serial-process.

mark

A marker indicating the position of the end of the last output from this process inserted into the buffer. This is often but not always the end of the buffer.

kill_without_query

If this is non-zero, killing Emacs while this process is still running does not ask for confirmation about killing the process.

raw_status

The raw process status, as returned by the wait system call.

status

The process status, as process-status should return it. This is a Lisp symbol, a cons cell, or a list.

tick
update_tick

If these two fields are not equal, a change in the status of the process needs to be reported, either by running the sentinel or by inserting a message in the process buffer.

pty_flag

Non-zero if communication with the subprocess uses a pty; zero if it uses a pipe.

infd

The file descriptor for input from the process.

outfd

The file descriptor for output to the process.

tty_name

The name of the terminal that the subprocess is using, or nil if it is using pipes.

decode_coding_system

Coding-system for decoding the input from this process.

decoding_buf

A working buffer for decoding.

decoding_carryover

Size of carryover in decoding.

encode_coding_system

Coding-system for encoding the output to this process.

encoding_buf

A working buffer for encoding.

inherit_coding_system_flag

Flag to set coding-system of the process buffer from the coding system used to decode process output.

type

Symbol indicating the type of process: real, network, serial.


E.9 C Integer Types

Here are some guidelines for use of integer types in the Emacs C source code. These guidelines sometimes give competing advice; common sense is advised.