@c -*-texinfo-*-@c This is part of the GNU Emacs Lisp Reference Manual.@c Copyright (C) 1990, 1991, 1992, 1993, 1998, 1999, 2001, 2002, 2003,@c 2004, 2005, 2006, 2007 Free Software Foundation, Inc.@c See the file elisp.texi for copying conditions.@setfilename ../info/internals@node GNU Emacs Internals, Standard Errors, Tips, Top@comment node-name, next, previous, up@appendix GNU Emacs InternalsThis chapter describes how the runnable Emacs executable is dumped withthe preloaded Lisp libraries in it, how storage is allocated, and someinternal aspects of GNU Emacs that may be of interest to C programmers.@menu* Building Emacs:: How the dumped Emacs is made.* Pure Storage:: A kludge to make preloaded Lisp functions sharable.* Garbage Collection:: Reclaiming space for Lisp objects no longer used.* Memory Usage:: Info about total size of Lisp objects made so far.* Writing Emacs Primitives:: Writing C code for Emacs.* Object Internals:: Data formats of buffers, windows, processes.@end menu@node Building Emacs@appendixsec Building Emacs@cindex building Emacs@pindex temacs This section explains the steps involved in building the Emacsexecutable. You don't have to know this material to build and installEmacs, since the makefiles do all these things automatically. Thisinformation is pertinent to Emacs maintenance. Compilation of the C source files in the @file{src} directoryproduces an executable file called @file{temacs}, also called a@dfn{bare impure Emacs}. It contains the Emacs Lisp interpreter and I/Oroutines, but not the editing commands.@cindex @file{loadup.el} The command @w{@samp{temacs -l loadup}} uses @file{temacs} to createthe real runnable Emacs executable. These arguments direct@file{temacs} to evaluate the Lisp files specified in the file@file{loadup.el}. These files set up the normal Emacs editingenvironment, resulting in an Emacs that is still impure but no longerbare.@cindex dumping Emacs It takes a substantial time to load the standard Lisp files. Luckily,you don't have to do this each time you run Emacs; @file{temacs} candump out an executable program called @file{emacs} that has these filespreloaded. @file{emacs} starts more quickly because it does not need toload the files. This is the Emacs executable that is normallyinstalled. To create @file{emacs}, use the command @samp{temacs -batch -l loadupdump}. The purpose of @samp{-batch} here is to prevent @file{temacs}from trying to initialize any of its data on the terminal; this ensuresthat the tables of terminal information are empty in the dumped Emacs.The argument @samp{dump} tells @file{loadup.el} to dump a new executablenamed @file{emacs}. Some operating systems don't support dumping. On those systems, youmust start Emacs with the @samp{temacs -l loadup} command each time youuse it. This takes a substantial time, but since you need to startEmacs once a day at most---or once a week if you never log out---theextra time is not too severe a problem.@cindex @file{site-load.el} You can specify additional files to preload by writing a library named@file{site-load.el} that loads them. You may need to add a definition@example#define SITELOAD_PURESIZE_EXTRA @var{n}@end example@noindentto make @var{n} added bytes of pure space to hold the additional files.(Try adding increments of 20000 until it is big enough.) However, theadvantage of preloading additional files decreases as machines getfaster. On modern machines, it is usually not advisable. After @file{loadup.el} reads @file{site-load.el}, it finds thedocumentation strings for primitive and preloaded functions (andvariables) in the file @file{etc/DOC} where they are stored, bycalling @code{Snarf-documentation} (@pxref{Definition ofSnarf-documentation,, Accessing Documentation}).@cindex @file{site-init.el}@cindex preloading additional functions and variables You can specify other Lisp expressions to execute just before dumpingby putting them in a library named @file{site-init.el}. This file isexecuted after the documentation strings are found. If you want to preload function or variable definitions, there arethree ways you can do this and make their documentation stringsaccessible when you subsequently run Emacs:@itemize @bullet@itemArrange to scan these files when producing the @file{etc/DOC} file,and load them with @file{site-load.el}.@itemLoad the files with @file{site-init.el}, then copy the files into theinstallation directory for Lisp files when you install Emacs.@itemSpecify a non-@code{nil} value for@code{byte-compile-dynamic-docstrings} as a local variable in each of thesefiles, and load them with either @file{site-load.el} or@file{site-init.el}. (This method has the drawback that thedocumentation strings take up space in Emacs all the time.)@end itemize 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 usersexpect in an ordinary unmodified Emacs. If you feel you must overridenormal features for your site, do it with @file{default.el}, so thatusers can override your changes if they wish. @xref{Startup Summary}. In a package that can be preloaded, it is sometimes useful tospecify a computation to be done when Emacs subsequently starts up.For this, use @code{eval-at-startup}:@defmac eval-at-startup body@dots{}This evaluates the @var{body} forms, either immediately if running inan Emacs that has already started up, or later when Emacs does startup. Since the value of the @var{body} forms is not necessarilyavailable when the @code{eval-at-startup} form is run, that formalways returns @code{nil}.@end defmac@defun dump-emacs to-file from-file@cindex unexecThis function dumps the current state of Emacs into an executable file@var{to-file}. It takes symbols from @var{from-file} (this is normallythe executable file @file{temacs}).If you want to use this function in an Emacs that was already dumped,you must run Emacs with @samp{-batch}.@end defun@node Pure Storage@appendixsec Pure Storage@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 whereall the new data created during an Emacs session are kept; see thefollowing section for information on normal storage. Pure storage isused for certain data in the preloaded standard Lisp files---data thatshould never change during actual use of Emacs. Pure storage is allocated only while @file{temacs} is loading thestandard preloaded Lisp libraries. In the file @file{emacs}, it ismarked as read-only (on operating systems that permit this), so thatthe memory space can be shared by all the Emacs jobs running on themachine at once. Pure storage is not expandable; a fixed amount isallocated when Emacs is compiled, and if that is not sufficient forthe preloaded libraries, @file{temacs} allocates dynamic memory forthe part that didn't fit. If that happens, you should increase thecompilation parameter @code{PURESIZE} in the file@file{src/puresize.h} and rebuild Emacs, even though the resultingimage will work: garbage collection is disabled in this situation,causing a memory leak. Such an overflow normally won't happen unless youtry to preload additional libraries or add features to the standardones. Emacs will display a warning about the overflow when itstarts.@defun purecopy objectThis function makes a copy in pure storage of @var{object}, and returnsit. It copies a string by simply making a new string with the samecharacters, but without text properties, in pure storage. Itrecursively copies the contents of vectors and cons cells. It doesnot make copies of other objects such as symbols, but just returnsthem 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 the file @file{emacs/lisp/loaddefs.el}, buta few packages call it just in case you decide to preload them.@end defun@defvar pure-bytes-usedThe value of this variable is the number of bytes of pure storageallocated so far. Typically, in a dumped Emacs, this number is veryclose to the total amount of pure storage available---if it were not,we would preallocate less.@end defvar@defvar purify-flagThis variable determines whether @code{defun} should make a copy of thefunction definition in pure storage. If it is non-@code{nil}, then thefunction definition is copied into pure storage.This flag is @code{t} while loading all of the basic functions forbuilding Emacs initially (allowing those functions to be sharable andnon-collectible). Dumping Emacs as an executable always writes@code{nil} in this variable, regardless of the value it actually hasbefore and after dumping.You should not change this flag in a running Emacs.@end defvar@node Garbage Collection@appendixsec Garbage Collection@cindex garbage collector@cindex memory allocation When a program creates a list or the user defines a new function (suchas by loading a library), that data is placed in normal storage. Ifnormal storage runs low, then Emacs asks the operating system toallocate more memory in blocks of 1k bytes. Each block is used for onetype of Lisp object, so symbols, cons cells, markers, etc., aresegregated in distinct blocks in memory. (Vectors, long strings,buffers and certain other editing types, which are fairly large, areallocated in individual blocks, one per object, while small strings arepacked into blocks of 8k bytes.) 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 anobject. Emacs provides a @dfn{garbage collector} to reclaim thisabandoned storage. (This name is traditional, but ``garbage recycler''might be a more intuitive metaphor for this facility.) The garbage collector operates by finding and marking all Lisp objectsthat are still accessible to Lisp programs. To begin with, it assumesall the symbols, their values and associated function definitions, andany data presently on the stack, are accessible. Any objects that canbe reached indirectly through other accessible objects are alsoaccessible. When marking is finished, all objects still unmarked are garbage. Nomatter what the Lisp program or the user does, it is impossible to referto them, since there is no longer a way to reach them. Their spacemight as well be reused, since no one will miss them. The second(``sweep'') phase of the garbage collector arranges to reuse them.@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 compactsthe accessible strings so they occupy fewer 8k blocks; then it frees theother 8k blocks. Vectors, buffers, windows, and other large objects areindividually allocated and freed using @code{malloc} and @code{free}.@cindex CL note---allocate more storage@quotation@b{Common Lisp note:} Unlike other Lisps, GNU Emacs Lisp does notcall the garbage collector when the free list is empty. Instead, itsimply requests the operating system to allocate more storage, andprocessing continues until @code{gc-cons-threshold} bytes have beenused.This means that you can make sure that the garbage collector will notrun during a certain portion of a Lisp program by calling the garbagecollector explicitly just before it (provided that portion of theprogram does not use so much space as to force a second garbagecollection).@end quotation@deffn Command garbage-collectThis command runs a garbage collection, and returns information onthe amount of space in use. (Garbage collection can also occurspontaneously if you use more than @code{gc-cons-threshold} bytes ofLisp data since the previous garbage collection.)@code{garbage-collect} returns a list containing the followinginformation:@example@group((@var{used-conses} . @var{free-conses}) (@var{used-syms} . @var{free-syms})@end group (@var{used-miscs} . @var{free-miscs}) @var{used-string-chars} @var{used-vector-slots} (@var{used-floats} . @var{free-floats}) (@var{used-intervals} . @var{free-intervals}) (@var{used-strings} . @var{free-strings}))@end exampleHere is an example:@example@group(garbage-collect) @result{} ((106886 . 13184) (9769 . 0) (7731 . 4651) 347543 121628 (31 . 94) (1273 . 168) (25474 . 3569))@end group@end exampleHere is a table explaining each element:@table @var@item used-consesThe number of cons cells in use.@item free-consesThe number of cons cells for which space has been obtained from theoperating system, but that are not currently being used.@item used-symsThe number of symbols in use.@item free-symsThe number of symbols for which space has been obtained from theoperating system, but that are not currently being used.@item used-miscsThe number of miscellaneous objects in use. These include markers andoverlays, plus certain objects not visible to users.@item free-miscsThe number of miscellaneous objects for which space has been obtainedfrom the operating system, but that are not currently being used.@item used-string-charsThe total size of all strings, in characters.@item used-vector-slotsThe total number of elements of existing vectors.@item used-floats@c Emacs 19 featureThe number of floats in use.@item free-floats@c Emacs 19 featureThe number of floats for which space has been obtained from theoperating system, but that are not currently being used.@item used-intervalsThe number of intervals in use. Intervals are an internaldata structure used for representing text properties.@item free-intervalsThe number of intervals for which space has been obtainedfrom the operating system, but that are not currently being used.@item used-stringsThe number of strings in use.@item free-stringsThe number of string headers for which the space was obtained from theoperating system, but which are currently not in use. (A stringobject consists of a header and the storage for the string textitself; the latter is only allocated when the string is created.)@end tableIf there was overflow in pure space (see the previous section),@code{garbage-collect} returns @code{nil}, because a real garbagecollection can not be done in this situation.@end deffn@defopt garbage-collection-messagesIf this variable is non-@code{nil}, Emacs displays a message at thebeginning and end of garbage collection. The default value is@code{nil}, meaning there are no such messages.@end defopt@defvar post-gc-hookThis is a normal hook that is run at the end of garbage collection.Garbage collection is inhibited while the hook functions run, so becareful writing them.@end defvar@defopt gc-cons-thresholdThe value of this variable is the number of bytes of storage that mustbe allocated for Lisp objects after one garbage collection in order totrigger another garbage collection. A cons cell counts as eight bytes,a string as one byte per character plus a few bytes of overhead, and soon; space allocated to the contents of buffers does not count. Notethat the subsequent garbage collection does not happen immediately whenthe threshold is exhausted, but only the next time the Lisp evaluator iscalled.The initial threshold value is 400,000. If you specify a largervalue, garbage collection will happen less often. This reduces theamount of time spent garbage collecting, but increases total memory use.You may want to do this when running a program that creates lots ofLisp data.You can make collections more frequent by specifying a smaller value,down to 10,000. A value less than 10,000 will remain in effect onlyuntil the subsequent garbage collection, at which time@code{garbage-collect} will set the threshold back to 10,000.@end defopt@defopt gc-cons-percentageThe value of this variable specifies the amount of consing before agarbage collection occurs, as a fraction of the current heap size.This criterion and @code{gc-cons-threshold} apply in parallel, andgarbage collection occurs only when both criteria are satisfied.As the heap size increases, the time to perform a garbage collectionincreases. Thus, it can be desirable to do them less frequently inproportion.@end defopt The value returned by @code{garbage-collect} describes the amount ofmemory used by Lisp data, broken down by data type. By contrast, thefunction @code{memory-limit} provides information on the total amount ofmemory Emacs is currently using.@c Emacs 19 feature@defun memory-limitThis function returns the address of the last byte Emacs has allocated,divided by 1024. We divide the value by 1024 to make sure it fits in aLisp integer.You can use this to get a general idea of how your actions affect thememory usage.@end defun@defvar memory-fullThis variable is @code{t} if Emacs is close to out of memory for Lispobjects, and @code{nil} otherwise.@end defvar@defun memory-use-countsThis returns a list of numbers that count the number of objectscreated in this Emacs session. Each of these counters increments fora certain kind of object. See the documentation string for details.@end defun@defvar gcs-doneThis variable contains the total number of garbage collectionsdone so far in this Emacs session.@end defvar@defvar gc-elapsedThis variable contains the total number of seconds of elapsed timeduring garbage collection so far in this Emacs session, as a floatingpoint number.@end defvar@node Memory Usage@section Memory Usage These functions and variables give information about the total amountof 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, butthese count the number or size of all allocations, including those forobjects that have since been freed.@defvar cons-cells-consedThe total number of cons cells that have been allocated so farin this Emacs session.@end defvar@defvar floats-consedThe total number of floats that have been allocated so farin this Emacs session.@end defvar@defvar vector-cells-consedThe total number of vector cells that have been allocated so farin this Emacs session.@end defvar@defvar symbols-consedThe total number of symbols that have been allocated so farin this Emacs session.@end defvar@defvar string-chars-consedThe total number of string characters that have been allocated so farin this Emacs session.@end defvar@defvar misc-objects-consedThe total number of miscellaneous objects that have been allocated sofar in this Emacs session. These include markers and overlays, pluscertain objects not visible to users.@end defvar@defvar intervals-consedThe total number of intervals that have been allocated so farin this Emacs session.@end defvar@defvar strings-consedThe total number of strings that have been allocated so far in thisEmacs session.@end defvar@node Writing Emacs Primitives@appendixsec Writing Emacs Primitives@cindex primitive function internals@cindex writing Emacs primitives Lisp primitives are Lisp functions implemented in C. The details ofinterfacing the C function so that Lisp can call it are handled by a fewC macros. The only way to really understand how to write new C code isto 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 generalappearance.)@cindex garbage collection protection@smallexample@groupDEFUN ("or", For, Sor, 0, UNEVALLED, 0, doc: /* Eval args until one of them yields non-nil, then return thatvalue. The remaining args are not evalled at all.If all args return nil, return nil.@end group@groupusage: (or CONDITIONS ...) */) (args) Lisp_Object args;@{ register Lisp_Object val = Qnil; struct gcpro gcpro1;@end group@group GCPRO1 (args);@end group@group while (CONSP (args)) @{ val = Feval (XCAR (args)); if (!NILP (val)) break; args = XCDR (args); @}@end group@group UNGCPRO; 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:@exampleDEFUN (@var{lname}, @var{fname}, @var{sname}, @var{min}, @var{max}, @var{interactive}, @var{doc})@end example@table @var@item lnameThis is the name of the Lisp symbol to define as the function name; inthe example above, it is @code{or}.@item fnameThis is the C function name for this function. This isthe 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 thisfunction from C code, call @code{For}. Remember that the arguments mustbe of type @code{Lisp_Object}; various macros and functions for creatingvalues of type @code{Lisp_Object} are declared in the file@file{lisp.h}.@item snameThis is a C variable name to use for a structure that holds the data forthe subr object that represents the function in Lisp. This structureconveys the Lisp symbol name to the initialization routine that willcreate the symbol and store the subr object as its definition. Byconvention, this name is always @var{fname} with @samp{F} replaced with@samp{S}.@item minThis is the minimum number of arguments that the function requires. Thefunction @code{or} allows a minimum of zero arguments.@item maxThis is the maximum number of arguments that the function accepts, ifthere 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 (theequivalent of @code{&rest}). Both @code{UNEVALLED} and @code{MANY} aremacros. If @var{max} is a number, it may not be less than @var{min} andit may not be greater than eight.@item interactiveThis is an interactive specification, a string such as might be used asthe argument of @code{interactive} in a Lisp function. In the case of@code{or}, it is 0 (a null pointer), indicating that @code{or} cannot becalled interactively. A value of @code{""} indicates a function thatshould receive no arguments when called interactively.@item docThis is the documentation string. It uses C comment syntax ratherthan C string syntax because comment syntax requires nothing specialto include multiple lines. The @samp{doc:} identifies the commentthat follows as the documentation string. The @samp{/*} and @samp{*/}delimiters that begin and end the comment are not part of thedocumentation 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 listfor documentation purposes. This way, you can use different argumentnames in the documentation string from the ones used in the C code.@samp{usage:} is required if the function has an unlimited number ofarguments.All the usual rules for documentation strings in Lisp code(@pxref{Documentation Tips}) apply to C code documentation stringstoo.@end table After the call to the @code{DEFUN} macro, you must write the argumentname list that every C function must have, followed by ordinary Cdeclarations for the arguments. For a function with a fixed maximumnumber of arguments, declare a C argument for each Lisp argument, andgive them all type @code{Lisp_Object}. When a Lisp function has noupper limit on the number of arguments, its implementation in C actuallyreceives exactly two arguments: the first is the number of Lisparguments, and the second is the address of a block containing theirvalues. They have types @code{int} and @w{@code{Lisp_Object *}}.@cindex @code{GCPRO} and @code{UNGCPRO}@cindex protect C variables from garbage collection Within the function @code{For} itself, note the use of the macros@code{GCPRO1} and @code{UNGCPRO}. @code{GCPRO1} is used to``protect'' a variable from garbage collection---to inform the garbagecollector that it must look in that variable and regard its contentsas an accessible object. GC protection is necessary whenever you call@code{Feval} or anything that can directly or indirectly call@code{Feval}. At such a time, any Lisp object that this function mayrefer to again must be protected somehow. It suffices to ensure that at least one pointer to each object isGC-protected; that way, the object cannot be recycled, so all pointersto it remain valid. Thus, a particular local variable can do withoutprotection if it is certain that the object it points to will bepreserved by some other pointer (such as another local variable whichhas a @code{GCPRO})@footnote{Formerly, strings were a specialexception; in older Emacs versions, every local variable that mightpoint to a string needed a @code{GCPRO}.}. Otherwise, the localvariable needs a @code{GCPRO}. The macro @code{GCPRO1} protects just one local variable. If youwant to protect two variables, use @code{GCPRO2} instead; repeating@code{GCPRO1} will not work. Macros @code{GCPRO3}, @code{GCPRO4},@code{GCPRO5}, and @code{GCPRO6} also exist. All these macrosimplicitly use local variables such as @code{gcpro1}; you must declarethese explicitly, with type @code{struct gcpro}. Thus, if you use@code{GCPRO2}, you must declare @code{gcpro1} and @code{gcpro2}.Alas, we can't explain all the tricky details here. @code{UNGCPRO} cancels the protection of the variables that areprotected in the current function. It is necessary to do thisexplicitly. Built-in functions that take a variable number of arguments actuallyaccept two arguments at the C level: the number of Lisp arguments, anda @code{Lisp_Object *} pointer to a C vector containing those Lisparguments. This C vector may be part of a Lisp vector, but it neednot be. The responsibility for using @code{GCPRO} to protect the Lisparguments from GC if necessary rests with the caller in this case,since the caller allocated or found the storage for them. You must not use C initializers for static or global variables unlessthe variables are never written once Emacs is dumped. These variableswith initializers are allocated in an area of memory that becomesread-only (on certain operating systems) as a result of dumping Emacs.@xref{Pure Storage}. Do not use static variables within functions---place all staticvariables at top level in the file. This is necessary because Emacs onsome operating systems defines the keyword @code{static} as a nullmacro. (This definition is used because those systems put all variablesdeclared static in a place that becomes read-only after dumping, whetherthey have initializers or not.)@cindex @code{defsubr}, Lisp symbol for a primitive Defining the C function is not enough to make a Lisp primitiveavailable; you must also create the Lisp symbol for the primitive andstore a suitable subr object in its function cell. The code looks likethis:@exampledefsubr (&@var{subr-structure-name});@end example@noindentHere @var{subr-structure-name} is the name you used as the thirdargument to @code{DEFUN}. If you add a new primitive to a file that already has Lisp primitivesdefined 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 newfile, add to it a @code{syms_of_@var{filename}} (e.g.,@code{syms_of_myfile}). Then find the spot in @file{emacs.c} where allof 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} The function @code{syms_of_@var{filename}} is also the place to defineany C variables that are to be visible as Lisp variables.@code{DEFVAR_LISP} makes a C variable of type @code{Lisp_Object} visiblein 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 Lispwith a value that is either @code{t} or @code{nil}. Note that variablesdefined with @code{DEFVAR_BOOL} are automatically added to the list@code{byte-boolean-vars} used by the byte compiler.@cindex @code{staticpro}, protect file-scope variables from GC If you 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:@examplestaticpro (&@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 useof macros and functions to manipulate Lisp objects.@smallexample@groupDEFUN ("coordinates-in-window-p", Fcoordinates_in_window_p, Scoordinates_in_window_p, 2, 2, "xSpecify coordinate pair: \nXExpression which evals to window: ", "Return non-nil if COORDINATES is in WINDOW.\n\COORDINATES is a cons of the form (X . Y), X and Y being distances\n\...@end group@groupIf they are on the border between WINDOW and its right sibling,\n\ `vertical-line' is returned.") (coordinates, window) register Lisp_Object coordinates, window;@{ int x, y;@end group@group CHECK_LIVE_WINDOW (window, 0); CHECK_CONS (coordinates, 1); x = XINT (Fcar (coordinates)); y = XINT (Fcdr (coordinates));@end group@group switch (coordinates_in_window (XWINDOW (window), &x, &y)) @{ case 0: /* NOT in window at all. */ return Qnil;@end group@group case 1: /* In text part of window. */ return Fcons (make_number (x), make_number (y));@end group@group case 2: /* In mode line of window. */ return Qmode_line;@end group@group case 3: /* On right border of window. */ return Qvertical_line;@end group@group default: abort (); @}@}@end group@end smallexample Note that C code cannot call functions by name unless they are definedin C. The way to call a function written in Lisp is to use@code{Ffuncall}, which embodies the Lisp function @code{funcall}. Sincethe Lisp function @code{funcall} accepts an unlimited number ofarguments, in C it takes two: the number of Lisp-level arguments, and aone-dimensional array containing their values. The first Lisp-levelargument is the Lisp function to call, and the rest are the arguments topass to it. Since @code{Ffuncall} can call the evaluator, you mustprotect pointers from garbage collection around the call to@code{Ffuncall}. The C functions @code{call0}, @code{call1}, @code{call2}, and so on,provide handy ways to call a Lisp function conveniently with a fixednumber 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 andfunctions. If you define a function which is side-effect free, update the codein @file{byte-opt.el} which binds @code{side-effect-free-fns} and@code{side-effect-and-error-free-fns} so that the compiler optimizerknows about it.@node Object Internals@appendixsec Object Internals@cindex object internals GNU Emacs Lisp manipulates many different types of data. The actualdata are stored in a heap and the only access that programs have to itis through pointers. Pointers are thirty-two bits wide in mostimplementations. Depending on the operating system and type of machinefor which you compile Emacs, twenty-nine bits are used to address theobject, and the remaining three bits are used for the tag thatidentifies the object's type. Because Lisp objects are represented as tagged pointers, it is alwayspossible to determine the Lisp data type of any object. The C data type@code{Lisp_Object} can hold any Lisp object of any data type. Ordinaryvariables have type @code{Lisp_Object}, which means they can hold anytype of Lisp value; you can determine the actual data type only at runtime. The same is true for function arguments; if you want a functionto accept only a certain type of argument, you must check the typeexplicitly using a suitable predicate (@pxref{Type Predicates}).@cindex type checking internals@menu* Buffer Internals:: Components of a buffer structure.* Window Internals:: Components of a window structure.* Process Internals:: Components of a process structure.@end menu@node Buffer Internals@appendixsubsec Buffer Internals@cindex internals, of buffer@cindex buffer internals Buffers contain fields not directly accessible by the Lisp programmer.We describe them here, naming them by the names used in the C code.Many are accessible indirectly in Lisp programs via Lisp primitives.Two structures are used to represent buffers in C. The@code{buffer_text} structure contains fields describing the text of abuffer; the @code{buffer} structure holds other fields. In the caseof indirect buffers, two or more @code{buffer} structures referencethe same @code{buffer_text} structure.Here is a list of the @code{struct buffer_text} fields:@table @code@item begThis field contains the actual address of the buffer contents.@item gptThis holds the character position of the gap in the buffer.@xref{Buffer Gap}.@item zThis field contains the character position of the end of the buffertext.@item gpt_byteContains the byte position of the gap.@item z_byteHolds the byte position of the end of the buffer text.@item gap_sizeContains the size of buffer's gap. @xref{Buffer Gap}.@item modiffThis field counts buffer-modification events for this buffer. It isincremented for each such event, and never otherwise changed.@item save_modiffContains the previous value of @code{modiff}, as of the last time abuffer was visited or saved in a file.@item overlay_modiffCounts modifications to overlays analogous to @code{modiff}.@item beg_unchangedHolds the number of characters at the start of the text that are knownto be unchanged since the last redisplay that finished.@item end_unchangedHolds the number of characters at the end of the text that are known tobe unchanged since the last redisplay that finished.@item unchanged_modifiedContains the value of @code{modiff} at the time of the last redisplaythat finished. If this value matches @code{modiff},@code{beg_unchanged} and @code{end_unchanged} contain no usefulinformation.@item overlay_unchanged_modifiedContains the value of @code{overlay_modiff} at the time of the lastredisplay that finished. If this value matches @code{overlay_modiff},@code{beg_unchanged} and @code{end_unchanged} contain no usefulinformation.@item markersThe markers that refer to this buffer. This is actually a singlemarker, and successive elements in its marker @code{chain} are the othermarkers referring to this buffer text.@item intervalsContains the interval tree which records the text properties of thisbuffer.@end tableThe fields of @code{struct buffer} are:@table @code@item nextPoints to the next buffer, in the chain of all buffers including killedbuffers. This chain is used only for garbage collection, in order tocollect killed buffers properly. Note that vectors, and most kinds ofobjects allocated as vectors, are all on one chain, but buffers are on aseparate chain of their own.@item own_textThis is a @code{struct buffer_text} structure. In an ordinary buffer,it holds the buffer contents. In indirect buffers, this field is notused.@item textThis points to the @code{buffer_text} structure that is used for thisbuffer. In an ordinary buffer, this is the @code{own_text} field above.In an indirect buffer, this is the @code{own_text} field of the basebuffer.@item ptContains the character position of point in a buffer.@item pt_byteContains the byte position of point in a buffer.@item begvThis field contains the character position of the beginning of theaccessible range of text in the buffer.@item begv_byteThis field contains the byte position of the beginning of theaccessible range of text in the buffer.@item zvThis field contains the character position of the end of theaccessible range of text in the buffer.@item zv_byteThis field contains the byte position of the end of theaccessible range of text in the buffer.@item base_bufferIn an indirect buffer, this points to the base buffer. In an ordinarybuffer, it is null.@item local_var_flagsThis field contains flags indicating that certain variables are local inthis buffer. Such variables are declared in the C code using@code{DEFVAR_PER_BUFFER}, and their buffer-local bindings are stored infields in the buffer structure itself. (Some of these fields aredescribed in this table.)@item modtimeThis field contains the modification time of the visited file. It isset when the file is written or read. Before writing the buffer into afile, this field is compared to the modification time of the file to seeif the file has changed on disk. @xref{Buffer Modification}.@item auto_save_modifiedThis field contains the time when the buffer was last auto-saved.@item auto_save_failure_timeThe time at which we detected a failure to auto-save, or -1 if we didn'thave a failure.@item last_window_startThis field contains the @code{window-start} position in the buffer as ofthe last time the buffer was displayed in a window.@item clip_changedThis flag is set when narrowing changes in a buffer.@item prevent_redisplay_optimizations_pthis flag indicates that redisplay optimizations should not be usedto display this buffer.@item undo_listThis field points to the buffer's undo list. @xref{Undo}.@item nameThe buffer name is a string that names the buffer. It is guaranteed tobe unique. @xref{Buffer Names}.@item filenameThe name of the file visited in this buffer, or @code{nil}.@item directoryThe directory for expanding relative file names.@item save_lengthLength of the file this buffer is visiting, when last read or saved.This and other fields concerned with saving are not kept in the@code{buffer_text} structure because indirect buffers are never saved.@item auto_save_file_nameFile name used for auto-saving this buffer. This is not in the@code{buffer_text} because it's not used in indirect buffers at all.@item read_onlyNon-@code{nil} means this buffer is read-only.@item markThis field contains the mark for the buffer. The mark is a marker,hence it is also included on the list @code{markers}. @xref{The Mark}.@item local_var_alistThis field contains the association list describing the buffer-localvariable bindings of this buffer, not including the built-inbuffer-local bindings that have special slots in the buffer object.(Those slots are omitted from this table.) @xref{Buffer-LocalVariables}.@item major_modeSymbol naming the major mode of this buffer, e.g., @code{lisp-mode}.@item mode_namePretty name of major mode, e.g., @code{"Lisp"}.@item mode_line_formatMode line element that controls the format of the mode line. If thisis @code{nil}, no mode line will be displayed.@item header_line_formatThis field is analogous to @code{mode_line_format} for the modeline displayed at the top of windows.@item keymapThis field holds the buffer's local keymap. @xref{Keymaps}.@item abbrev_tableThis buffer's local abbrevs.@item syntax_tableThis field contains the syntax table for the buffer. @xref{Syntax Tables}.@item category_tableThis field contains the category table for the buffer.@item case_fold_searchThe value of @code{case-fold-search} in this buffer.@item tab_widthThe value of @code{tab-width} in this buffer.@item fill_columnThe value of @code{fill-column} in this buffer.@item left_marginThe value of @code{left-margin} in this buffer.@item auto_fill_functionThe value of @code{auto-fill-function} in this buffer.@item downcase_tableThis field contains the conversion table for converting text to lower case.@xref{Case Tables}.@item upcase_tableThis field contains the conversion table for converting text to upper case.@xref{Case Tables}.@item case_canon_tableThis field contains the conversion table for canonicalizing text forcase-folding search. @xref{Case Tables}.@item case_eqv_tableThis field contains the equivalence table for case-folding search.@xref{Case Tables}.@item truncate_linesThe value of @code{truncate-lines} in this buffer.@item ctl_arrowThe value of @code{ctl-arrow} in this buffer.@item selective_displayThe value of @code{selective-display} in this buffer.@item selective_display_ellipsisThe value of @code{selective-display-ellipsis} in this buffer.@item minor_modesAn alist of the minor modes of this buffer.@item overwrite_modeThe value of @code{overwrite_mode} in this buffer.@item abbrev_modeThe value of @code{abbrev-mode} in this buffer.@item display_tableThis field contains the buffer's display table, or @code{nil} if it doesn'thave one. @xref{Display Tables}.@item save_modifiedThis field contains the time when the buffer was last saved, as an integer.@xref{Buffer Modification}.@item mark_activeThis field is non-@code{nil} if the buffer's mark is active.@item overlays_beforeThis field holds a list of the overlays in this buffer that end at orbefore the current overlay center position. They are sorted in order ofdecreasing end position.@item overlays_afterThis field holds a list of the overlays in this buffer that end afterthe current overlay center position. They are sorted in order ofincreasing beginning position.@item overlay_centerThis field holds the current overlay center position. @xref{Overlays}.@item enable_multibyte_charactersThis field holds the buffer's local value of@code{enable-multibyte-characters}---either @code{t} or @code{nil}.@item buffer_file_coding_systemThe value of @code{buffer-file-coding-system} in this buffer.@item file_formatThe value of @code{buffer-file-format} in this buffer.@item auto_save_file_formatThe value of @code{buffer-auto-save-file-format} in this buffer.@item pt_markerIn an indirect buffer, or a buffer that is the base of an indirectbuffer, this holds a marker that records point for this buffer when thebuffer is not current.@item begv_markerIn an indirect buffer, or a buffer that is the base of an indirectbuffer, this holds a marker that records @code{begv} for this bufferwhen the buffer is not current.@item zv_markerIn an indirect buffer, or a buffer that is the base of an indirectbuffer, this holds a marker that records @code{zv} for this buffer whenthe buffer is not current.@item file_truenameThe truename of the visited file, or @code{nil}.@item invisibility_specThe value of @code{buffer-invisibility-spec} in this buffer.@item last_selected_windowThis is the last window that was selected with this buffer in it, or @code{nil}if that window no longer displays this buffer.@item display_countThis field is incremented each time the buffer is displayed in a window.@item left_margin_widthThe value of @code{left-margin-width} in this buffer.@item right_margin_widthThe value of @code{right-margin-width} in this buffer.@item indicate_empty_linesNon-@code{nil} means indicate empty lines (lines with no text) with asmall bitmap in the fringe, when using a window system that can do it.@item display_timeThis holds a time stamp that is updated each time this buffer isdisplayed in a window.@item scroll_up_aggressivelyThe value of @code{scroll-up-aggressively} in this buffer.@item scroll_down_aggressivelyThe value of @code{scroll-down-aggressively} in this buffer.@end table@node Window Internals@appendixsubsec Window Internals@cindex internals, of window@cindex window internals Windows have the following accessible fields:@table @code@item frameThe frame that this window is on.@item mini_pNon-@code{nil} if this window is a minibuffer window.@item parentInternally, Emacs arranges windows in a tree; each group of siblings hasa parent window whose area includes all the siblings. This field pointsto a window's parent.Parent windows do not display buffers, and play little role in displayexcept to shape their child windows. Emacs Lisp programs usually haveno access to the parent windows; they operate on the windows at theleaves of the tree, which actually display buffers.The following four fields also describe the window tree structure.@item hchildIn a window subdivided horizontally by child windows, the leftmost child.Otherwise, @code{nil}.@item vchildIn a window subdivided vertically by child windows, the topmost child.Otherwise, @code{nil}.@item nextThe next sibling of this window. It is @code{nil} in a window that isthe rightmost or bottommost of a group of siblings.@item prevThe previous sibling of this window. It is @code{nil} in a window thatis the leftmost or topmost of a group of siblings.@item leftThis is the left-hand edge of the window, measured in columns. (Theleftmost column on the screen is @w{column 0}.)@item topThis is the top edge of the window, measured in lines. (The top line onthe screen is @w{line 0}.)@item heightThe height of the window, measured in lines.@item widthThe width of the window, measured in columns. This width includes thescroll bar and fringes, and/or the separator line on the right of thewindow (if any).@item bufferThe buffer that the window is displaying. This may change often duringthe life of the window.@item startThe position in the buffer that is the first character to be displayedin the window.@item pointm@cindex window point internalsThis is the value of point in the current buffer when this window isselected; when it is not selected, it retains its previous value.@item force_startIf this flag is non-@code{nil}, it says that the window has beenscrolled explicitly by the Lisp program. This affects what the nextredisplay does if point is off the screen: instead of scrolling thewindow to show the text around point, it moves point to a location thatis on the screen.@item frozen_window_start_pThis field is set temporarily to 1 to indicate to redisplay that@code{start} of this window should not be changed, even if pointgets invisible.@item start_at_line_begNon-@code{nil} means current value of @code{start} was the beginning of a linewhen it was chosen.@item too_small_okNon-@code{nil} means don't delete this window for becoming ``too small.''@item height_fixed_pThis field is temporarily set to 1 to fix the height of the selectedwindow when the echo area is resized.@item use_timeThis is the last time that the window was selected. The function@code{get-lru-window} uses this field.@item sequence_numberA unique number assigned to this window when it was created.@item last_modifiedThe @code{modiff} field of the window's buffer, as of the last timea redisplay completed in this window.@item last_overlay_modifiedThe @code{overlay_modiff} field of the window's buffer, as of the lasttime a redisplay completed in this window.@item last_pointThe buffer's value of point, as of the last time a redisplay completedin this window.@item last_had_starA non-@code{nil} value means the window's buffer was ``modified'' when thewindow was last updated.@item vertical_scroll_barThis window's vertical scroll bar.@item left_margin_widthThe width of the left margin in this window, or @code{nil} not tospecify it (in which case the buffer's value of @code{left-margin-width}is used.@item right_margin_widthLikewise for the right margin.@ignore@item last_mark_x@item last_mark_y???Not used.@end ignore@item window_end_posThis is computed as @code{z} minus the buffer position of the last glyphin the current matrix of the window. The value is only valid if@code{window_end_valid} is not @code{nil}.@item window_end_byteposThe byte position corresponding to @code{window_end_pos}.@item window_end_vposThe window-relative vertical position of the line containing@code{window_end_pos}.@item window_end_validThis field is set to a non-@code{nil} value if @code{window_end_pos} is trulyvalid. This is @code{nil} if nontrivial redisplay is preempted since in thatcase the display that @code{window_end_pos} was computed for did not getonto the screen.@item redisplay_end_triggerIf redisplay in this window goes beyond this buffer position, it runsthe @code{redisplay-end-trigger-hook}.@ignore@item orig_height@item orig_top??? Are temporary storage areas.@end ignore@item cursorA structure describing where the cursor is in this window.@item last_cursorThe value of @code{cursor} as of the last redisplay that finished.@item phys_cursorA structure describing where the cursor of this window physically is.@item phys_cursor_typeThe type of cursor that was last displayed on this window.@item phys_cursor_on_pThis field is non-zero if the cursor is physically on.@item cursor_off_pNon-zero means the cursor in this window is logically on.@item last_cursor_off_pThis field contains the value of @code{cursor_off_p} as of the time ofthe last redisplay.@item must_be_updated_pThis is set to 1 during redisplay when this window must be updated.@item hscrollThis is the number of columns that the display in the window is scrolledhorizontally to the left. Normally, this is 0.@item vscrollVertical scroll amount, in pixels. Normally, this is 0.@item dedicatedNon-@code{nil} if this window is dedicated to its buffer.@item display_tableThe window's display table, or @code{nil} if none is specified for it.@item update_mode_lineNon-@code{nil} means this window's mode line needs to be updated.@item base_line_numberThe line number of a certain position in the buffer, or @code{nil}.This is used for displaying the line number of point in the mode line.@item base_line_posThe position in the buffer for which the line number is known, or@code{nil} meaning none is known.@item region_showingIf the region (or part of it) is highlighted in this window, this fieldholds the mark position that made one end of that region. Otherwise,this field is @code{nil}.@item column_number_displayedThe column number currently displayed in this window's mode line, or @code{nil}if column numbers are not being displayed.@item current_matrixA glyph matrix describing the current display of this window.@item desired_matrixA glyph matrix describing the desired display of this window.@end table@node Process Internals@appendixsubsec Process Internals@cindex internals, of process@cindex process internals The fields of a process are:@table @code@item nameA string, the name of the process.@item commandA list containing the command arguments that were used to start thisprocess.@item filterA function used to accept output from the process instead of a buffer,or @code{nil}.@item sentinelA function called whenever the process receives a signal, or @code{nil}.@item bufferThe associated buffer of the process.@item pidAn integer, the operating system's process @acronym{ID}.@item childpA flag, non-@code{nil} if this is really a child process.It is @code{nil} for a network connection.@item markA marker indicating the position of the end of the last output from thisprocess inserted into the buffer. This is often but not always the endof the buffer.@item kill_without_queryIf this is non-@code{nil}, killing Emacs while this process is stillrunning does not ask for confirmation about killing the process.@item raw_status_low@itemx raw_status_highThese two fields record 16 bits each of the process status returned bythe @code{wait} system call.@item statusThe process status, as @code{process-status} should return it.@item tick@itemx update_tickIf these two fields are not equal, a change in the status of the processneeds to be reported, either by running the sentinel or by inserting amessage in the process buffer.@item pty_flagNon-@code{nil} if communication with the subprocess uses a @acronym{PTY};@code{nil} if it uses a pipe.@item infdThe file descriptor for input from the process.@item outfdThe file descriptor for output to the process.@item subttyThe file descriptor for the terminal that the subprocess is using. (Onsome systems, there is no need to record this, so the value is@code{nil}.)@item tty_nameThe name of the terminal that the subprocess is using,or @code{nil} if it is using pipes.@item decode_coding_systemCoding-system for decoding the input from this process.@item decoding_bufA working buffer for decoding.@item decoding_carryoverSize of carryover in decoding.@item encode_coding_systemCoding-system for encoding the output to this process.@item encoding_bufA working buffer for encoding.@item encoding_carryoverSize of carryover in encoding.@item inherit_coding_system_flagFlag to set @code{coding-system} of the process buffer from thecoding system used to decode process output.@end table@ignore arch-tag: 4b2c33bc-d7e4-43f5-bc20-27c0db52a53e@end ignore