internals.texi 113 KB
Newer Older
Glenn Morris's avatar
Glenn Morris committed
1 2
@c -*-texinfo-*-
@c This is part of the GNU Emacs Lisp Reference Manual.
Paul Eggert's avatar
Paul Eggert committed
@c Copyright (C) 1990-1993, 1998-1999, 2001-2019 Free Software
@c Foundation, Inc.
Glenn Morris's avatar
Glenn Morris committed
@c See the file elisp.texi for copying conditions.
@node GNU Emacs Internals
Glenn Morris's avatar
Glenn Morris committed
7 8 9 10 11 12 13 14
@appendix 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.

* Building Emacs::      How the dumped Emacs is made.
Paul Eggert's avatar
Paul Eggert committed
* Pure Storage::        Kludge to make preloaded Lisp functions shareable.
Glenn Morris's avatar
Glenn Morris committed
* Garbage Collection::  Reclaiming space for Lisp objects no longer used.
* Stack-allocated Objects::    Temporary conses and strings on C stack.
Glenn Morris's avatar
Glenn Morris committed
* Memory Usage::        Info about total size of Lisp objects made so far.
* C Dialect::           What C variant Emacs is written in.
Glenn Morris's avatar
Glenn Morris committed
* Writing Emacs Primitives::   Writing C code for Emacs.
* Writing Dynamic Modules::    Writing loadable modules for Emacs.
Glenn Morris's avatar
Glenn Morris committed
* Object Internals::    Data formats of buffers, windows, processes.
* C Integer Types::     How C integer types are used inside Emacs.
Glenn Morris's avatar
Glenn Morris committed
24 25 26
@end menu

@node Building Emacs
@section Building Emacs
Glenn Morris's avatar
Glenn Morris committed
28 29 30 31 32 33
@cindex building Emacs
@pindex temacs

  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.
Glenn Morris's avatar
Glenn Morris committed

36 37 38
  Building Emacs requires GNU Make version 3.81 or later.

  Compilation of the C source files in the @file{src} directory
Glenn Morris's avatar
Glenn Morris committed
produces an executable file called @file{temacs}, also called a
40 41
@dfn{bare impure Emacs}.  It contains the Emacs Lisp interpreter and
I/O routines, but not the editing commands.
Glenn Morris's avatar
Glenn Morris committed
42 43

@cindex @file{loadup.el}
44 45 46 47 48
  The command @w{@command{temacs -l loadup}} would run @file{temacs}
and direct it to load @file{loadup.el}.  The @code{loadup} library
loads additional Lisp libraries, which set up the normal Emacs editing
environment.  After this step, the Emacs executable is no longer
Glenn Morris's avatar
Glenn Morris committed
49 50

@cindex dumping Emacs
@cindex @option{--temacs} option, and dumping method
52 53
  Because it takes some time to load the standard Lisp files, the
@file{temacs} executable usually isn't run directly by users.
54 55 56 57 58 59 60 61 62 63
Instead, one of the last steps of building Emacs runs the command
@w{@samp{temacs -batch -l loadup --temacs=@var{dump-method}}}.  The
special option @option{--temacs} tells @command{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
@option{--temacs} option requires an argument @var{dump-method}, which
can be one of the following:

@table @samp
@item pdump
64 65
@cindex dump file
Record the preloaded Lisp data in a @dfn{dump file}.  This
method produces an additional data file which Emacs will load at
startup.  The produced dump file is usually called @file{emacs.pdmp},
and is installed in the Emacs @code{exec-directory} (@pxref{Help
69 70 71 72 73 74 75 76 77
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.

@item pbootstrap
@cindex bootstrapping Emacs
Like @samp{pdump}, but used while @dfn{bootstrapping} Emacs, when no
previous Emacs binary and no @file{*.elc} byte-compiled Lisp files are
available.  The produced dump file is usually named
79 80 81 82 83 84 85 86 87 88 89 90
@file{bootstrap-emacs.pdmp} in this case.

@item dump
@cindex unexec
This method causes @command{temacs} to dump out an executable program,
called @file{emacs}, which has all the standard Lisp files already
preloaded into it.  (The @samp{-batch} argument prevents
@command{temacs} from trying to initialize any of its data on the
terminal, so that the tables of terminal information are empty in the
dumped Emacs.)  This method is also known as @dfn{unexec}, because it
produces a program file from a running process, and thus is in some
sense the opposite of executing a program to start a process.
91 92
Although this method was the way that Emacs traditionally saved its
state, it is now deprecated.
93 94 95 96 97

@item bootstrap
Like @samp{dump}, but used when bootstrapping Emacs with the
@code{unexec} method.
@end table
98 99

@cindex preloaded Lisp files
@vindex preloaded-file-list
  The dumped @file{emacs} executable (also called a @dfn{pure} Emacs)
is the one which is installed.  If the portable dumper was used to
103 104 105
build Emacs, the @file{emacs} executable is actually an exact copy of
@file{temacs}, and the corresponding @file{emacs.pdmp} file is
installed as well.  The variable @code{preloaded-file-list} stores a
list of the preloaded Lisp files recorded in the dump file or
107 108 109
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 @file{loadup.el} each time it starts.
Glenn Morris's avatar
Glenn Morris committed

Paul Eggert's avatar
Paul Eggert committed
111 112 113 114 115 116 117 118 119 120
@cindex build details
@cindex deterministic build
@cindex @option{--disable-build-details} option to @command{configure}
  By default the dumped @file{emacs} executable records details such
as the build time and host name.  Use the
@option{--disable-build-details} option of @command{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

Glenn Morris's avatar
Glenn Morris committed
121 122
@cindex @file{site-load.el}
  You can specify additional files to preload by writing a library named
123 124
@file{site-load.el} that loads them.  You may need to rebuild Emacs
with an added definition
Glenn Morris's avatar
Glenn Morris committed
125 126 127 128 129 130

@end example

131 132
to make @var{n} added bytes of pure space to hold the additional files;
see @file{src/puresize.h}.
Glenn Morris's avatar
Glenn Morris committed
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
(Try adding increments of 20000 until it is big enough.)  However, the
advantage of preloading additional files decreases as machines get
faster.  On modern machines, it is usually not advisable.

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

@cindex @file{site-init.el}
@cindex preloading additional functions and variables
  You can specify other Lisp expressions to execute just before dumping
by putting them in a library named @file{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:

@itemize @bullet
Arrange to scan these files when producing the @file{etc/DOC} file,
and load them with @file{site-load.el}.

Load the files with @file{site-init.el}, then copy the files into the
installation directory for Lisp files when you install Emacs.

163 164 165 166 167
Specify a @code{nil} value for @code{byte-compile-dynamic-docstrings}
as a local variable in each of these files, and load them with either
@file{site-load.el} or @file{site-init.el}.  (This method has the
drawback that the documentation strings take up space in Emacs all the
Glenn Morris's avatar
Glenn Morris committed
168 169
@end itemize

Eli Zaretskii's avatar
Eli Zaretskii committed
170 171
@cindex change @code{load-path} at configure time
@cindex @option{--enable-locallisppath} option to @command{configure}
Glenn Morris's avatar
Glenn Morris committed
172 173 174 175 176
  It is not advisable to put anything in @file{site-load.el} or
@file{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 @file{default.el}, so that
users can override your changes if they wish.  @xref{Startup Summary}.
177 178 179 180 181
Note that if either @file{site-load.el} or @file{site-init.el} changes
@code{load-path}, the changes will be lost after dumping.
@xref{Library Search}.  To make a permanent change to
@code{load-path}, use the @option{--enable-locallisppath} option
of @command{configure}.
Glenn Morris's avatar
Glenn Morris committed

183 184 185 186 187 188 189 190 191 192 193 194 195 196
  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, @code{tutorial-directory} is a
variable defined in @file{startup.el}, which is preloaded.  The default
value is set based on @code{data-directory}.  The variable needs to
access the value of @code{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.

@defun custom-initialize-delay symbol value
This function delays the initialization of @var{symbol} to the next
Emacs start.  You normally use this function by specifying it as the
@code{:initialize} property of a customizable variable.  (The argument
Paul Eggert's avatar
Paul Eggert committed
@var{value} is unused, and is provided only for compatibility with the
198 199
form Custom expects.)
@end defun
Glenn Morris's avatar
Glenn Morris committed

201 202 203
In the unlikely event that you need a more general functionality than
@code{custom-initialize-delay} provides, you can use
@code{before-init-hook} (@pxref{Startup Summary}).
Glenn Morris's avatar
Glenn Morris committed

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

215 216 217 218
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.

219 220 221 222
If you want to use this function in an Emacs that was already dumped,
you must run Emacs with the @samp{-batch} option.
@end defun

Glenn Morris's avatar
Glenn Morris committed
223 224 225
@defun dump-emacs to-file from-file
@cindex unexec
This function dumps the current state of Emacs into an executable file
226 227
@var{to-file}, using the @code{unexec} method.  It takes symbols from
@var{from-file} (this is normally the executable file @file{temacs}).
Glenn Morris's avatar
Glenn Morris committed

229 230 231
This function cannot be used in an Emacs that was already dumped.
This function is deprecated, and by default Emacs is built without
@code{unexec} support so this function is not available.
Glenn Morris's avatar
Glenn Morris committed
232 233
@end defun

@defun pdumper-stats
If the current Emacs session restored its state from a dump
236 237 238 239 240
file, this function returns information about the dump file and the
time it took to restore the Emacs state.  The value is an alist
@w{@code{((dumped-with-pdumper . t) (load-time . @var{time})
(dump-file-name . @var{file}))}},
where @var{file} is the name of the dump file, and @var{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
243 244 245
value is nil.
@end defun

Glenn Morris's avatar
Glenn Morris committed
@node Pure Storage
@section Pure Storage
Glenn Morris's avatar
Glenn Morris committed
248 249 250 251
@cindex pure storage

  Emacs Lisp uses two kinds of storage for user-created Lisp objects:
@dfn{normal storage} and @dfn{pure storage}.  Normal storage is where
252 253 254 255
all the new data created during an Emacs session are kept
(@pxref{Garbage Collection}).  Pure storage is used for certain data
in the preloaded standard Lisp files---data that should never change
during actual use of Emacs.
Glenn Morris's avatar
Glenn Morris committed

  Pure storage is allocated only while @command{temacs} is loading the
Glenn Morris's avatar
Glenn Morris committed
258 259 260 261 262 263
standard preloaded Lisp libraries.  In the file @file{emacs}, it is
marked as read-only (on operating systems that permit this), so that
the memory space can be shared by all the Emacs jobs running on the
machine at once.  Pure storage is not expandable; a fixed amount is
allocated when Emacs is compiled, and if that is not sufficient for
the preloaded libraries, @file{temacs} allocates dynamic memory for
264 265 266 267 268 269 270 271
the part that didn't fit.  The resulting image will work, but garbage
collection (@pxref{Garbage Collection}) is disabled in this situation,
causing a memory leak.  Such an overflow normally won't happen unless
you try to preload additional libraries or add features to the
standard ones.  Emacs will display a warning about the overflow when
it starts.  If this happens, you should increase the compilation
parameter @code{SYSTEM_PURESIZE_EXTRA} in the file
@file{src/puresize.h} and rebuild Emacs.
Glenn Morris's avatar
Glenn Morris committed
272 273 274 275 276 277 278 279 280 281

@defun purecopy object
This function makes a copy in pure storage of @var{object}, and returns
it.  It copies a string by simply making a new string with the same
characters, but without text properties, in pure storage.  It
recursively copies the contents of vectors and cons cells.  It does
not make copies of other objects such as symbols, but just returns
them unchanged.  It signals an error if asked to copy markers.

This function is a no-op except while Emacs is being built and dumped;
it is usually called only in preloaded Lisp files.
Glenn Morris's avatar
Glenn Morris committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
@end defun

@defvar pure-bytes-used
The value of this variable is the number of bytes of pure storage
allocated so far.  Typically, in a dumped Emacs, this number is very
close to the total amount of pure storage available---if it were not,
we would preallocate less.
@end defvar

@defvar purify-flag
This variable determines whether @code{defun} should make a copy of the
function definition in pure storage.  If it is non-@code{nil}, then the
function definition is copied into pure storage.

This flag is @code{t} while loading all of the basic functions for
Paul Eggert's avatar
Paul Eggert committed
building Emacs initially (allowing those functions to be shareable and
Glenn Morris's avatar
Glenn Morris committed
299 300 301 302 303 304 305 306
non-collectible).  Dumping Emacs as an executable always writes
@code{nil} in this variable, regardless of the value it actually has
before and after dumping.

You should not change this flag in a running Emacs.
@end defvar

@node Garbage Collection
@section Garbage Collection
Glenn Morris's avatar
Glenn Morris committed
308 309

@cindex memory allocation
310 311 312 313
  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
314 315 316 317 318 319 320 321
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).

@cindex vector-like objects, storage
@cindex storage of vector-like Lisp objects
322 323
  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 @code{union vectorlike_header} field whose
325 326 327 328 329
@code{size} member contains the subtype enumerated by @code{enum pvec_type}
and an information about how many @code{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.
Glenn Morris's avatar
Glenn Morris committed

331 332 333 334 335 336 337 338 339 340
@cindex garbage collection
  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 @dfn{garbage collector} to reclaim this
abandoned storage.  The garbage collector operates 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.
Glenn Morris's avatar
Glenn Morris committed
341 342 343 344 345

  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
Paul Eggert's avatar
Paul Eggert committed
(sweep) phase of the garbage collector arranges to reuse them.
Glenn Morris's avatar
Glenn Morris committed
347 348 349 350 351 352 353

@c ??? Maybe add something describing weak hash tables here?

@cindex free list
  The sweep phase puts unused cons cells onto a @dfn{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
354 355 356 357 358 359
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.
Glenn Morris's avatar
Glenn Morris committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

@cindex CL note---allocate more storage
@b{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 @code{gc-cons-threshold} bytes have been

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
@end quotation

@deffn 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 @code{gc-cons-threshold} bytes of
Lisp data since the previous garbage collection.)

382 383 384 385 386 387 388 389
@code{garbage-collect} returns a list with information on amount of space in
use, where each entry has the form @samp{(@var{name} @var{size} @var{used})}
or @samp{(@var{name} @var{size} @var{used} @var{free})}.  In the entry,
@var{name} is a symbol describing the kind of objects this entry represents,
@var{size} is the number of bytes used by each one, @var{used} is the number
of those objects that were found live in the heap, and optional @var{free} is
the number of those objects that are not live but that Emacs keeps around for
future allocations.  So an overall result is:
Glenn Morris's avatar
Glenn Morris committed
390 391

Paul Eggert's avatar
Paul Eggert committed
((@code{conses} @var{cons-size} @var{used-conses} @var{free-conses})
393 394 395 396 397 398 399 400 401
 (@code{symbols} @var{symbol-size} @var{used-symbols} @var{free-symbols})
 (@code{strings} @var{string-size} @var{used-strings} @var{free-strings})
 (@code{string-bytes} @var{byte-size} @var{used-bytes})
 (@code{vectors} @var{vector-size} @var{used-vectors})
 (@code{vector-slots} @var{slot-size} @var{used-slots} @var{free-slots})
 (@code{floats} @var{float-size} @var{used-floats} @var{free-floats})
 (@code{intervals} @var{interval-size} @var{used-intervals} @var{free-intervals})
 (@code{buffers} @var{buffer-size} @var{used-buffers})
 (@code{heap} @var{unit-size} @var{total-size} @var{free-size}))
Glenn Morris's avatar
Glenn Morris committed
402 403 404 405 406 407
@end example

Here is an example:

      @result{} ((conses 16 49126 8058) (symbols 48 14607 0)
                 (strings 32 2942 2607)
410 411 412 413
                 (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))
Glenn Morris's avatar
Glenn Morris committed
414 415
@end example

416 417 418
Below is a table explaining each element.  Note that last @code{heap} entry
is optional and present only if an underlying @code{malloc} implementation
provides @code{mallinfo} function.
Glenn Morris's avatar
Glenn Morris committed
419 420

@table @var
@item cons-size
Internal size of a cons cell, i.e., @code{sizeof (struct Lisp_Cons)}.

Glenn Morris's avatar
Glenn Morris committed
424 425 426 427
@item used-conses
The number of cons cells in use.

@item free-conses
428 429
The number of cons cells for which space has been obtained from
the operating system, but that are not currently being used.
Glenn Morris's avatar
Glenn Morris committed

@item symbol-size
Internal size of a symbol, i.e., @code{sizeof (struct Lisp_Symbol)}.
433 434

@item used-symbols
Glenn Morris's avatar
Glenn Morris committed
435 436
The number of symbols in use.

437 438 439 440 441
@item free-symbols
The number of symbols for which space has been obtained from
the operating system, but that are not currently being used.

@item string-size
Internal size of a string header, i.e., @code{sizeof (struct Lisp_String)}.
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457

@item used-strings
The number of string headers in use.

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

@item byte-size
This is used for convenience and equals to @code{sizeof (char)}.

@item used-bytes
The total size of all string data in bytes.

@item vector-size
Size in bytes of a vector of length 1, including its header.
459 460 461 462 463 464 465 466 467

@item used-vectors
The number of vector headers allocated from the vector blocks.

@item slot-size
Internal size of a vector slot, always equal to @code{sizeof (Lisp_Object)}.

@item used-slots
The number of slots in all used vectors.
468 469
Slot counts might include some or all overhead from vector headers,
depending on the platform.
470 471 472

@item free-slots
The number of free slots in all vector blocks.
Glenn Morris's avatar
Glenn Morris committed

@item float-size
Internal size of a float object, i.e., @code{sizeof (struct Lisp_Float)}.
(Do not confuse it with the native platform @code{float} or @code{double}.)
Glenn Morris's avatar
Glenn Morris committed
477 478 479 480 481

@item used-floats
The number of floats in use.

@item free-floats
482 483 484 485
The number of floats for which space has been obtained from
the operating system, but that are not currently being used.

@item interval-size
Internal size of an interval object, i.e., @code{sizeof (struct interval)}.
Glenn Morris's avatar
Glenn Morris committed
487 488

@item used-intervals
The number of intervals in use.
Glenn Morris's avatar
Glenn Morris committed
490 491

@item free-intervals
492 493
The number of intervals for which space has been obtained from
the operating system, but that are not currently being used.
Glenn Morris's avatar
Glenn Morris committed

@item buffer-size
Internal size of a buffer, i.e., @code{sizeof (struct buffer)}.
(Do not confuse with the value returned by @code{buffer-size} function.)
Glenn Morris's avatar
Glenn Morris committed

499 500
@item used-buffers
The number of buffer objects in use.  This includes killed buffers
invisible to users, i.e., all buffers in @code{all_buffers} list.
502 503 504 505 506 507 508 509 510

@item unit-size
The unit of heap space measurement, always equal to 1024 bytes.

@item total-size
Total heap size, in @var{unit-size} units.

@item free-size
Heap space which is not currently used, in @var{unit-size} units.
Glenn Morris's avatar
Glenn Morris committed
511 512
@end table

If there was overflow in pure space (@pxref{Pure Storage}),
Glenn Morris's avatar
Glenn Morris committed
@code{garbage-collect} returns @code{nil}, because a real garbage
collection cannot be done.
Glenn Morris's avatar
Glenn Morris committed
516 517 518 519 520
@end deffn

@defopt garbage-collection-messages
If this variable is non-@code{nil}, Emacs displays a message at the
beginning and end of garbage collection.  The default value is
Glenn Morris's avatar
Glenn Morris committed
522 523 524 525 526 527 528 529 530 531 532
@end defopt

@defvar 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.
@end defvar

@defopt 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
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
trigger another garbage collection.  You can use the result returned by
@code{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 @code{GC_DEFAULT_THRESHOLD}, defined in
@file{alloc.c}.  Since it's defined in @code{word_size} units, the value
is 400,000 for the default 32-bit configuration and 800,000 for the 64-bit
one.  If you specify a larger value, garbage collection will happen less
often.  This reduces the amount of time spent garbage collecting, but
increases total memory use.  You may want to do this when running a program
that creates lots of Lisp data.

You can make collections more frequent by specifying a smaller value, down
to 1/10th of @code{GC_DEFAULT_THRESHOLD}.  A value less than this minimum
will remain in effect only until the subsequent garbage collection, at which
time @code{garbage-collect} will set the threshold back to the minimum.
Glenn Morris's avatar
Glenn Morris committed
549 550 551 552 553 554 555 556 557 558 559 560 561
@end defopt

@defopt 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 @code{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
@end defopt

Paul Eggert's avatar
Paul Eggert committed
562 563 564 565 566 567 568 569 570 571
  Control over the garbage collector via @code{gc-cons-threshold} and
@code{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
@code{gc-cons-threshold} or @code{gc-cons-percentage}, so exhausting
the threshold does not immediately trigger garbage collection.  Also,
for efficency in threshold calculations Emacs approximates the heap
size, which counts the bytes used by currently-accessible objects in
the heap.

Glenn Morris's avatar
Glenn Morris committed
572 573 574 575 576 577
  The value returned by @code{garbage-collect} describes the amount of
memory used by Lisp data, broken down by data type.  By contrast, the
function @code{memory-limit} provides information on the total amount of
memory Emacs is currently using.

@defun memory-limit
Paul Eggert's avatar
Paul Eggert committed
578 579
This function returns an estimate of the total amount of bytes of
virtual memory that Emacs is currently using, divided by 1024.
Glenn Morris's avatar
Glenn Morris committed
580 581 582 583 584
You can use this to get a general idea of how your actions affect the
memory usage.
@end defun

@defvar memory-full
This variable is @code{t} if Emacs is nearly out of memory for Lisp
Glenn Morris's avatar
Glenn Morris committed
586 587 588 589 590 591 592 593 594
objects, and @code{nil} otherwise.
@end defvar

@defun 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.
@end defun

595 596 597
@defun 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 @code{nil}.
@end defun

Glenn Morris's avatar
Glenn Morris committed
600 601 602 603 604 605 606
@defvar gcs-done
This variable contains the total number of garbage collections
done so far in this Emacs session.
@end defvar

@defvar gc-elapsed
This variable contains the total number of seconds of elapsed time
607 608
during garbage collection so far in this Emacs session, as a
floating-point number.
Glenn Morris's avatar
Glenn Morris committed
609 610
@end defvar

611 612 613
@node Stack-allocated Objects
@section Stack-allocated Objects

Eli Zaretskii's avatar
Eli Zaretskii committed
614 615
@cindex stack allocated Lisp objects
@cindex Lisp objects, stack-allocated
  The garbage collector described above is used to manage data visible
Eli Zaretskii's avatar
Eli Zaretskii committed
from Lisp programs, as well as most of the data internally used by the
618 619 620 621 622 623 624 625 626 627 628
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 @code{GC_CHECK_MARKED_OBJECTS} feature (see
@file{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
629 630
is implemented by C macros like @code{AUTO_CONS} and
@code{AUTO_STRING} that define a named @code{Lisp_Object} with block
631 632 633
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.
635 636 637 638

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

Glenn Morris's avatar
Glenn Morris committed
640 641 642 643 644 645 646
@node Memory Usage
@section Memory Usage
@cindex 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
@code{garbage-collect}; those count objects that currently exist, but
Glenn Morris's avatar
Glenn Morris committed
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
these count the number or size of all allocations, including those for
objects that have since been freed.

@defvar cons-cells-consed
The total number of cons cells that have been allocated so far
in this Emacs session.
@end defvar

@defvar floats-consed
The total number of floats that have been allocated so far
in this Emacs session.
@end defvar

@defvar vector-cells-consed
The total number of vector cells that have been allocated so far
in this Emacs session.
664 665
This includes vector-like objects such as markers and overlays, plus
certain objects not visible to users.
Glenn Morris's avatar
Glenn Morris committed
666 667 668 669 670 671 672 673 674
@end defvar

@defvar symbols-consed
The total number of symbols that have been allocated so far
in this Emacs session.
@end defvar

@defvar string-chars-consed
The total number of string characters that have been allocated so far
in this session.
Glenn Morris's avatar
Glenn Morris committed
676 677 678 679 680 681 682 683 684 685 686 687
@end defvar

@defvar intervals-consed
The total number of intervals that have been allocated so far
in this Emacs session.
@end defvar

@defvar strings-consed
The total number of strings that have been allocated so far in this
Emacs session.
@end defvar

688 689 690 691
@node C Dialect
@section C Dialect
@cindex C programming language

Paul Eggert's avatar
Paul Eggert committed
692 693
The C part of Emacs is portable to C99 or later: C11-specific features such
as @samp{<stdalign.h>} and @samp{_Noreturn} are not used without a check,
typically at configuration time, and the Emacs build procedure
Paul Eggert's avatar
Paul Eggert committed
695 696 697
provides a substitute implementation if necessary.  Some C11 features,
such as anonymous structures and unions, are too difficult to emulate,
so they are avoided entirely.

Paul Eggert's avatar
Paul Eggert committed
At some point in the future the base C dialect will no doubt change to C11.

Glenn Morris's avatar
Glenn Morris committed
@node Writing Emacs Primitives
@section Writing Emacs Primitives
Glenn Morris's avatar
Glenn Morris committed
703 704 705
@cindex primitive function internals
@cindex writing Emacs primitives

  Lisp primitives are Lisp functions implemented in C@.  The details of
Glenn Morris's avatar
Glenn Morris committed
707 708 709 710 711 712 713 714 715 716 717
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 @code{or}, from
@file{eval.c}.  (An ordinary function would have the same general

DEFUN ("or", For, Sor, 0, UNEVALLED, 0,
718 719
       doc: /* Eval args until one of them yields non-nil,
then return that value.
The remaining args are not evalled at all.
Glenn Morris's avatar
Glenn Morris committed
721 722 723
If all args return nil, return nil.
@end group
usage: (or CONDITIONS...)  */)
  (Lisp_Object args)
Glenn Morris's avatar
Glenn Morris committed
  Lisp_Object val = Qnil;
Glenn Morris's avatar
Glenn Morris committed
728 729 730 731 732
@end group

  while (CONSP (args))
      val = eval_sub (XCAR (args));
Glenn Morris's avatar
Glenn Morris committed
734 735 736
      if (!NILP (val))
      args = XCDR (args);
Paul Eggert's avatar
Paul Eggert committed
      maybe_quit ();
Glenn Morris's avatar
Glenn Morris committed
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
@end group

  return val;
@end group
@end smallexample

@cindex @code{DEFUN}, C macro to define Lisp primitives
  Let's start with a precise explanation of the arguments to the
@code{DEFUN} macro.  Here is a template for them:

DEFUN (@var{lname}, @var{fname}, @var{sname}, @var{min}, @var{max}, @var{interactive}, @var{doc})
@end example

@table @var
@item lname
This is the name of the Lisp symbol to define as the function name; in
the example above, it is @code{or}.

@item fname
761 762 763 764 765
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, @samp{F} prepended to the Lisp name, with all dashes
(@samp{-}) in the Lisp name changed to underscores.  Thus, to call
this function from C code, call @code{For}.
Glenn Morris's avatar
Glenn Morris committed
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784

@item 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 @var{fname} with @samp{F} replaced with

@item min
This is the minimum number of arguments that the function requires.  The
function @code{or} allows a minimum of zero arguments.

@item max
This is the maximum number of arguments that the function accepts, if
there is a fixed maximum.  Alternatively, it can be @code{UNEVALLED},
indicating a special form that receives unevaluated arguments, or
@code{MANY}, indicating an unlimited number of evaluated arguments (the
equivalent of @code{&rest}).  Both @code{UNEVALLED} and @code{MANY} are
785 786
macros.  If @var{max} is a number, it must be more than @var{min} but
less than 8.
Glenn Morris's avatar
Glenn Morris committed

@cindex interactive specification in primitives
Glenn Morris's avatar
Glenn Morris committed
@item interactive
This is an interactive specification, a string such as might be used
791 792
as the argument of @code{interactive} in a Lisp function
(@pxref{Using Interactive}).  In the case
of @code{or}, it is @code{0} (a null pointer), indicating that @code{or}
794 795
cannot be called interactively.  A value of @code{""} indicates a
function that should receive no arguments when called interactively.
796 797 798
If the value begins with a @samp{"(}, 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)\
804 805
       doc: /* @dots{} */)
@end group
@end example
Glenn Morris's avatar
Glenn Morris committed
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823

@item 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 @samp{doc:} identifies the comment
that follows as the documentation string.  The @samp{/*} and @samp{*/}
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
@samp{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.
@samp{usage:} is required if the function has an unlimited number of

824 825 826 827 828 829 830
Some primitives have multiple definitions, one per platform (e.g.,
@code{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
@samp{SKIP}, which are ignored by the function that parses the
@file{DOC} file.

Glenn Morris's avatar
Glenn Morris committed
831 832 833
All the usual rules for documentation strings in Lisp code
(@pxref{Documentation Tips}) apply to C code documentation strings
Eli Zaretskii's avatar
Eli Zaretskii committed
834 835 836 837 838 839 840 841

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

DEFUN ("bar", Fbar, Sbar, 0, UNEVALLED, 0
842 843
       doc: /* @dots{} */
       attributes: @var{attr1} @var{attr2} @dots{})
Eli Zaretskii's avatar
Eli Zaretskii committed
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
@end group
@end example

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

@table @code
@item noreturn
Declares the C function as one that never returns.  This corresponds
to the C11 keyword @code{_Noreturn} and to @w{@code{__attribute__
((__noreturn__))}} attribute of GCC (@pxref{Function Attributes,,,
gcc, Using the GNU Compiler Collection}).

@item const
Declares that the function does not examine any values except its
arguments, and has no effects except the return value.  This
corresponds to @w{@code{__attribute__ ((__const__))}} attribute of

@item noinline
This corresponds to @w{@code{__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.
@end table

Glenn Morris's avatar
Glenn Morris committed
871 872
@end table

  After the call to the @code{DEFUN} macro, you must write the
874 875 876 877 878
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 @code{Lisp_Object}.  (Various macros and
functions for creating values of type @code{Lisp_Object} are declared
879 880 881 882 883 884 885 886 887 888 889 890
in the file @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 @code{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 @code{ptrdiff_t} and @w{@code{Lisp_Object *}},
respectively.  Since @code{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 (@pxref{Type Predicates}).
@cindex type checking internals
Glenn Morris's avatar
Glenn Morris committed

@cindex garbage collection protection
Glenn Morris's avatar
Glenn Morris committed
@cindex protect C variables from garbage collection
895 896 897 898
  Within the function @code{For} itself, the local variable
@code{args} refers to objects controlled by Emacs's stack-marking
garbage collector.  Although the garbage collector does not reclaim
objects reachable from C @code{Lisp_Object} stack variables, it may
899 900 901 902 903 904 905 906
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 @code{eval_sub} or @code{Feval}, either directly or
Glenn Morris's avatar
Glenn Morris committed

Paul Eggert's avatar
Paul Eggert committed
909 910
@cindex @code{maybe_quit}, use in Lisp primitives
  Note the call to @code{maybe_quit} inside the loop: this function
911 912 913 914 915 916
checks whether the user pressed @kbd{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.

Glenn Morris's avatar
Glenn Morris committed
917 918 919 920 921 922 923 924 925 926 927 928 929
  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.
@xref{Pure Storage}.

@cindex @code{defsubr}, Lisp symbol for a primitive
  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

defsubr (&@var{sname});
Glenn Morris's avatar
Glenn Morris committed
931 932 933
@end example

Here @var{sname} is the name you used as the third argument to @code{DEFUN}.
Glenn Morris's avatar
Glenn Morris committed
935 936 937 938 939 940 941 942 943 944 945 946 947

  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
@code{syms_of_@var{something}}, and add the call to @code{defsubr}
there.  If the file doesn't have this function, or if you create a new
file, add to it a @code{syms_of_@var{filename}} (e.g.,
@code{syms_of_myfile}).  Then find the spot in @file{emacs.c} where all
of these functions are called, and add a call to
@code{syms_of_@var{filename}} there.

@anchor{Defining Lisp variables in C}
@vindex byte-boolean-vars
@cindex defining Lisp variables in C
@cindex @code{DEFVAR_INT}, @code{DEFVAR_LISP}, @code{DEFVAR_BOOL}, @code{DEFSYM}
Glenn Morris's avatar
Glenn Morris committed
949 950 951 952 953 954 955 956 957 958
  The function @code{syms_of_@var{filename}} is also the place to define
any C variables that are to be visible as Lisp variables.
@code{DEFVAR_LISP} makes a C variable of type @code{Lisp_Object} visible
in Lisp.  @code{DEFVAR_INT} makes a C variable of type @code{int}
visible in Lisp with a value that is always an integer.
@code{DEFVAR_BOOL} makes a C variable of type @code{int} visible in Lisp
with a value that is either @code{t} or @code{nil}.  Note that variables
defined with @code{DEFVAR_BOOL} are automatically added to the list
@code{byte-boolean-vars} used by the byte compiler.

959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
  These macros all expect three arguments:

@table @code
@item lname
The name of the variable to be used by Lisp programs.
@item vname
The name of the variable in the C sources.
@item doc
The documentation for the variable, as a C
comment.  @xref{Documentation Basics} for more details.
@end table

  By convention, when defining variables of a ``native'' type
(@code{int} and @code{bool}), the name of the C variable is the name
of the Lisp variable with @code{-} replaced by @code{_}.  When the
variable has type @code{Lisp_Object}, the convention is to also prefix
the C variable name with @code{V}.  i.e.

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

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

  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 @code{let}.  In C sources, this is done by defining a
corresponding, constant symbol, and using @code{specbind}.  By
convention, @code{Qmy_lisp_variable} corresponds to
@code{Vmy_lisp_variable}; to define it, use the @code{DEFSYM} macro.

DEFSYM (Qmy_lisp_variable, "my-lisp-variable");
@end smallexample

  To perform the actual binding:

specbind (Qmy_lisp_variable, Qt);
@end smallexample

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

(make-variable-buffer-local 'my-lisp-variable)
@end smallexample

In C the corresponding code uses @code{Fmake_variable_buffer_local} in
combination with @code{DEFSYM}, i.e.

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

@cindex defining customization variables in C
  If you want to make a Lisp variable that is defined in C behave
like one declared with @code{defcustom}, add an appropriate entry to
1024 1025
@file{cus-start.el}.  @xref{Variable Definitions}, for a description of
the format to use.

Glenn Morris's avatar
Glenn Morris committed
@cindex @code{staticpro}, protection from GC
1028 1029 1030
  If you directly define a file-scope C variable of type
@code{Lisp_Object}, you must protect it from garbage-collection by
calling @code{staticpro} in @code{syms_of_@var{filename}}, like this:
Glenn Morris's avatar
Glenn Morris committed
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042

staticpro (&@var{variable});
@end example

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

DEFUN ("coordinates-in-window-p", Fcoordinates_in_window_p,
1043 1044 1045
       Scoordinates_in_window_p, 2, 2, 0,
       doc: /* Return non-nil if COORDINATES are in WINDOW.
Glenn Morris's avatar
Glenn Morris committed
1046 1047
@end group
1048 1049
  or `right-margin' is returned.  */)
  (register Lisp_Object coordinates, Lisp_Object window)
Glenn Morris's avatar
Glenn Morris committed
1051 1052
  struct window *w;
  struct frame *f;
Glenn Morris's avatar
Glenn Morris committed
  int x, y;
  Lisp_Object lx, ly;
Glenn Morris's avatar
Glenn Morris committed
1055 1056 1057
@end group

  w = decode_live_window (window);
1059 1060 1061 1062
  f = XFRAME (w->frame);
  CHECK_CONS (coordinates);
  lx = Fcar (coordinates);
  ly = Fcdr (coordinates);
1063 1064 1065 1066
Glenn Morris's avatar
Glenn Morris committed
1067 1068 1069
@end group

  switch (coordinates_in_window (w, x, y))
Glenn Morris's avatar
Glenn Morris committed
    case ON_NOTHING:            /* NOT in window at all.  */
Glenn Morris's avatar
Glenn Morris committed
1073 1074 1075
      return Qnil;
@end group

Glenn Morris's avatar
Glenn Morris committed
1077 1078

    case ON_MODE_LINE:          /* In mode line of window.  */
Glenn Morris's avatar
Glenn Morris committed
1080 1081 1082
      return Qmode_line;
@end group


Glenn Morris's avatar
Glenn Morris committed
1086 1087 1088
    case ON_SCROLL_BAR:         /* On scroll-bar of window.  */
      /* Historically we are supposed to return nil in this case.  */
      return Qnil;
Glenn Morris's avatar
Glenn Morris committed
1089 1090 1091 1092
@end group

      emacs_abort ();
Glenn Morris's avatar
Glenn Morris committed
1094 1095 1096 1097 1098 1099
@end group
@end smallexample

  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
Glenn Morris's avatar
Glenn Morris committed
1101 1102 1103 1104 1105
@code{Ffuncall}, which embodies the Lisp function @code{funcall}.  Since
the Lisp function @code{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.
Glenn Morris's avatar
Glenn Morris committed
1107 1108 1109 1110 1111 1112 1113 1114 1115

  The C functions @code{call0}, @code{call1}, @code{call2}, and so on,
provide handy ways to call a Lisp function conveniently with a fixed
number of arguments.  They work by calling @code{Ffuncall}.

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

1116 1117 1118
  If you define a function which is side-effect free or pure, give it
a non-@code{nil} @code{side-effect-free} or @code{pure} property,
respectively (@pxref{Standard Properties}).
Glenn Morris's avatar
Glenn Morris committed

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
@node Writing Dynamic Modules
@section Writing Dynamically-Loaded Modules
@cindex writing emacs modules
@cindex dynamic modules, writing

@cindex module @acronym{API}
  This section describes the Emacs module @acronym{API} and how to use
it as part of writing extension modules for Emacs.  The module
@acronym{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 (@pxref{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

@itemize @bullet
Writing initialization code for the module.

Writing one or more module functions.

Communicating values and objects between Emacs and your module

Handling of error conditions and nonlocal exits.
@end itemize

The following subsections describe these tasks and the @acronym{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 @code{load-path}
(@pxref{Library Search}), where Emacs will find it.

If you wish to verify the conformance of a module to the Emacs dynamic
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
module @acronym{API}, invoke Emacs with the @kbd{--module-assertions}
option.  @xref{Initial Options,,,emacs, The GNU Emacs Manual}.

* Module Initialization::
* Module Functions::
* Module Values::
* Module Misc::
* Module Nonlocal::
@end menu

@node Module Initialization
@subsection Module Initialization Code
@cindex module initialization

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

#include <emacs-module.h>

int plugin_is_GPL_compatible;
@end example

The @file{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.

@anchor{module initialization function}
Next, write an initialization function for the module.

@deftypefn Function int emacs_module_init (struct emacs_runtime *@var{runtime})
Emacs calls this function when it loads a module.  If a module does
not export a function named @code{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 @kbd{C-g} during the
initialization, Emacs ignores the return value of the initialization
function and quits (@pxref{Quitting}).  (If needed, you can catch user
quitting inside the initialization function, @pxref{should_quit}.)

The argument @var{runtime} is a pointer to a C @code{struct} that
includes 2 public fields: @code{size}, which provides the size of the
structure in bytes; and @code{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

@table @asis
@cindex compatibility, between modules and Emacs
@item Compatibility verification
A module can verify that the Emacs executable which loads the module
is compatible with the module, by comparing the @code{size} member of
the @var{runtime} structure with the value compiled into the module:

emacs_module_init (struct emacs_runtime *ert)
  if (ert->size < sizeof (*ert))
    return 1;
@end example

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
@acronym{API} with what the module expects.  The following sample code
assumes it is part of the @code{emacs_module_init} function shown

  emacs_env *env = ert->get_environment (ert);
  if (env->size < sizeof (*env))
    return 2;
@end example

@cindex module runtime environment
This calls the @code{get_environment} function using the pointer
provided in the @code{runtime} structure to retrieve a pointer to the
@acronym{API}'s @dfn{environment}, a C @code{struct} which also has a
@code{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 = ert->get_environment (ert);
  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;
    return 2; /* Unknown or unsupported version.  */
@end example

This works because later Emacs versions always @emph{add} members to
the environment, never @emph{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 @acronym{API} that existed in
that version, since those parts are identical in later versions.

1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
@file{emacs-module.h} defines a preprocessor macro
@code{EMACS_MAJOR_VERSION}.  It expands to an integer literal which is
the latest major version of Emacs supported by the header.
@xref{Version Info}.  Note that the value of
@code{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 @file{emacs-module.h} as well as various versions
of Emacs, you can use conditional compilation based on

1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
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.

@item 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 @ref{Module Functions}
@end table
@end deftypefn

@node Module Functions
@subsection Writing Module Functions
@cindex writing module functions
@cindex 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 @dfn{module functions}.

A module function has the following general form and signature:

@deftypefn Function emacs_value module_func (emacs_env *@var{env}, ptrdiff_t @var{nargs}, emacs_value *@var{args}, void *@var{data})
The @var{env} argument provides a pointer to the @acronym{API}
environment, needed to access Emacs objects and functions.  The
@var{nargs} argument is the required number of arguments, which can be
zero (see @code{make_function} below for more flexible specification
of the argument number), and @var{args} is a pointer to the array of
the function arguments.  The argument @var{data} points to additional
data required by the function, which was arranged when
@code{make_function} (see below) was called to create an Emacs
function from @code{module_func}.

Module functions use the type @code{emacs_value} to communicate Lisp
objects between Emacs and the module (@pxref{Module Values}).  The
@acronym{API}, described below and in the following subsections,
provides facilities for conversion between basic C data types and the
corresponding @code{emacs_value} objects.

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 @code{emacs_value} value the function returned.
However, if the user typed @kbd{C-g}, or if the module function or its
callees signaled an error or exited nonlocally (@pxref{Module
Nonlocal}), Emacs will ignore the returned value and quit or throw as
it does when Lisp code encounters the same situations.
@end deftypefn

After writing your C code for a module function, you should make a
1337 1338 1339
Lisp function object from it using the @code{make_function} function,
whose pointer is provided in the environment (recall that the pointer
to the environment is returned by @code{get_environment}).  This is
1340 1341
normally done in the module initialization function (@pxref{module
initialization function}), after verifying the @acronym{API}
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472

@deftypefn Function emacs_value make_function (emacs_env *@var{env}, ptrdiff_t @var{min_arity}, ptrdiff_t @var{max_arity}, subr @var{func}, const char *@var{docstring}, void *@var{data})
@vindex emacs_variadic_function
This returns an Emacs function created from the C function @var{func},
whose signature is as described for @code{module_func} above (assumed
here to be @code{typedef}'ed as @code{subr}).  The arguments
@var{min_arity} and @var{max_arity} specify the minimum and maximum
number of arguments that @var{func} can accept.  The @var{max_arity}
argument can have the special value @code{emacs_variadic_function},
which makes the function accept an unlimited number of arguments, like
the @code{&rest} keyword in Lisp (@pxref{Argument List}).

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

The argument @var{docstring} specifies the documentation string for
the function.  It should be either an @acronym{ASCII} string, or a
UTF-8 encoded non-@acronym{ASCII} string, or a @code{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 @ref{Function Documentation}.

Since every module function must accept the pointer to the environment
as its first argument, the call to @code{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.
@end deftypefn

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
@acronym{API} function @code{intern} (@pxref{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
@code{module_func} to be callable as @code{module-func} from Lisp will
look like this, as part of the module initialization function:

 emacs_env *env = ert->get_environment (ert);
 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);
@end example

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

Using the module @acronym{API}, it is possible to define more complex
function and data types: interactive functions, 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 @code{module-func} defined as above, one way of making an
interactive command @code{module-cmd} based on it is with the
following simple Lisp wrapper:

(defun module-cmd (&rest args)
  "Documentation string for the command."
  (interactive @var{spec})
  (apply 'module-func args))
@end lisp

The Lisp package which goes with your module could then load the
module using the @code{module-load} primitive (@pxref{Dynamic
Modules}) when the package is loaded into Emacs.

@node Module Values
@subsection Conversion Between Lisp and Module Values
@cindex module values, conversion

@cindex @code{emacs_value} data type
  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
@acronym{API} provides the @code{emacs_value} type, which represents
Emacs Lisp objects communicated via the @acronym{API}; it is the
functional equivalent of the @code{Lisp_Object} type used in Emacs C
primitives (@pxref{Writing Emacs Primitives}).  This section describes
the parts of the module @acronym{API} that allow to create
@code{emacs_value} objects corresponding to basic Lisp data types, and
how to access from C data in @code{emacs_value} objects that
correspond to Lisp objects.

All of the functions described below are actually @emph{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@dots{});
@end example

The @code{emacs_env} pointer will usually come from the first argument
to the module function, or from the call to @code{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 @acronym{API} functions extract values of various C data
types from @code{emacs_value} objects.  They all raise the
@code{wrong-type-argument} error condition (@pxref{Type Predicates})
if the argument @code{emacs_value} object is not of the type expected
by the function.  @xref{Module Nonlocal}, 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
@acronym{API} function @code{type_of} (@pxref{Module Misc, type_of})
can be used to obtain the type of a @code{emacs_value} object.

@deftypefn Function intmax_t extract_integer (emacs_env *@var{env}, emacs_value @var{arg})
This function returns the value of a Lisp integer specified by
@var{arg}.  The C data type of the return value, @code{intmax_t}, is
the widest integral data type supported by the C compiler, typically
1473 1474 1475
@w{@code{long long}}.  If the value of @var{arg} doesn't fit into an
@code{intmax_t}, the function signals an error using the error symbol
1476 1477
@end deftypefn

1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
@deftypefn Function bool extract_big_integer (emacs_env *@var{env}, emacs_value @var{arg}, int *@var{sign}, ptrdiff_t *@var{count}, emacs_limb_t *@var{magnitude})
This function, which is available since Emacs 27, extracts the
integral value of @var{arg}.  The value of @var{arg} must be an
integer (fixnum or bignum).  If @var{sign} is not @code{NULL}, it
stores the sign of @var{arg} (-1, 0, or +1) into @code{*sign}.  The
magnitude is stored into @var{magnitude} as follows.  If @var{count}
and @var{magnitude} are bot non-@code{NULL}, then @var{magnitude} must
point to an array of at least @code{*count} @code{unsigned long}
elements.  If @var{magnitude} is large enough to hold the magnitude of
@var{arg}, then this function writes the magnitude into the
@var{magnitude} array in little-endian form, stores the number of
array elements written into @code{*count}, and returns @code{true}.
If @var{magnitude} is not large enough, it stores the required array
size into @code{*count}, signals an error, and returns @code{false}.
If @var{count} is not @code{NULL} and @var{magnitude} is @code{NULL},
then the function stores the required array size into @code{*count}
and returns @code{true}.

Emacs guarantees that the maximum required value of @code{*count}
never exceeds @code{min (PTRDIFF_MAX, SIZE_MAX) / sizeof
(emacs_limb_t)}.  This implies that you can use e.g. @code{malloc
((size_t) (*count * sizeof (emacs_limb_t)))} to allocate the
@code{magnitude} array without integer overflow.
@end deftypefn

@deftp {Type alias} emacs_limb_t
This type is an alias to an otherwise unspecified unsigned integral
type.  It is used as element type for the magnitude arrays for the big
integer conversion functions.
@end deftp

@defvr Macro EMACS_LIMB_MAX
This macro expands to an integer literal specifying the maximum
possible value for an @code{emacs_limb_t} object.
@end defvr

1514 1515 1516 1517 1518
@deftypefn Function double extract_float (emacs_env *@var{env}, emacs_value @var{arg})
This function returns the value of a Lisp float specified by
@var{arg}, as a C @code{double} value.
@end deftypefn

1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
@deftypefn Function struct timespec extract_time (emacs_env *@var{env}, emacs_value @var{time})
This function, which is available since Emacs 27, interprets
@var{time} as an Emacs Lisp time value and returns the corresponding
@code{struct timespec}.  @xref{Time of Day}.  @code{struct timespec}
represents a timestamp with nanosecond precision.  It has the
following members:

@table @code
@item time_t tv_sec
Whole number of seconds.
@item long tv_nsec
Fractional seconds as number of nanoseconds, always less than one
@end table

@xref{Elapsed Time,,,libc}.

If @var{time} has higher precision than nanoseconds, then this
1538 1539 1540 1541 1542 1543
function truncates it to nanosecond precision towards negative
infinity.  This function signals an error if @var{time} (truncated to
nanoseconds) cannot be represented by @code{struct timespec}.  For
example, if @code{time_t} is a 32-bit integral type, then a @var{time}
value of ten billion seconds would signal an error, but a @var{time}
value of 600 picoseconds would get truncated to zero.
1544 1545 1546 1547 1548 1549 1550

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

1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587