1 \input texinfo @c -*-texinfo-*-
3 @setfilename ../../info/internals.info
4 @settitle XEmacs Internals Manual
8 @dircategory XEmacs Editor
10 * Internals: (internals). XEmacs Internals Manual.
13 Copyright @copyright{} 1992 - 1996 Ben Wing.
14 Copyright @copyright{} 1996, 1997 Sun Microsystems.
15 Copyright @copyright{} 1994 - 1998 Free Software Foundation.
16 Copyright @copyright{} 1994, 1995 Board of Trustees, University of Illinois.
19 Permission is granted to make and distribute verbatim copies of this
20 manual provided the copyright notice and this permission notice are
21 preserved on all copies.
24 Permission is granted to process this file through TeX and print the
25 results, provided the printed document carries copying permission notice
26 identical to this one except for the removal of this paragraph (this
27 paragraph not being relevant to the printed manual).
30 Permission is granted to copy and distribute modified versions of this
31 manual under the conditions for verbatim copying, provided that the
32 entire resulting derived work is distributed under the terms of a
33 permission notice identical to this one.
35 Permission is granted to copy and distribute translations of this manual
36 into another language, under the above conditions for modified versions,
37 except that this permission notice may be stated in a translation
38 approved by the Foundation.
40 Permission is granted to copy and distribute modified versions of this
41 manual under the conditions for verbatim copying, provided also that the
42 section entitled ``GNU General Public License'' is included exactly as
43 in the original, and provided that the entire resulting derived work is
44 distributed under the terms of a permission notice identical to this
47 Permission is granted to copy and distribute translations of this manual
48 into another language, under the above conditions for modified versions,
49 except that the section entitled ``GNU General Public License'' may be
50 included in a translation approved by the Free Software Foundation
51 instead of in the original English.
61 @setchapternewpage odd
65 @title XEmacs Internals Manual
66 @subtitle Version 1.2, October 1998
69 @author Martin Buchholz
75 Copyright @copyright{} 1992 - 1996 Ben Wing. @*
76 Copyright @copyright{} 1996, 1997 Sun Microsystems, Inc. @*
77 Copyright @copyright{} 1994 - 1998 Free Software Foundation. @*
78 Copyright @copyright{} 1994, 1995 Board of Trustees, University of Illinois.
84 Permission is granted to make and distribute verbatim copies of this
85 manual provided the copyright notice and this permission notice are
86 preserved on all copies.
88 Permission is granted to copy and distribute modified versions of this
89 manual under the conditions for verbatim copying, provided also that the
90 section entitled ``GNU General Public License'' is included
91 exactly as in the original, and provided that the entire resulting
92 derived work is distributed under the terms of a permission notice
93 identical to this one.
95 Permission is granted to copy and distribute translations of this manual
96 into another language, under the above conditions for modified versions,
97 except that the section entitled ``GNU General Public License'' may be
98 included in a translation approved by the Free Software Foundation
99 instead of in the original English.
103 @node Top, A History of Emacs, (dir), (dir)
106 This Info file contains v1.0 of the XEmacs Internals Manual.
110 * A History of Emacs:: Times, dates, important events.
111 * XEmacs From the Outside:: A broad conceptual overview.
112 * The Lisp Language:: An overview.
113 * XEmacs From the Perspective of Building::
114 * XEmacs From the Inside::
115 * The XEmacs Object System (Abstractly Speaking)::
116 * How Lisp Objects Are Represented in C::
117 * Rules When Writing New C Code::
118 * A Summary of the Various XEmacs Modules::
119 * Allocation of Objects in XEmacs Lisp::
120 * Events and the Event Loop::
121 * Evaluation; Stack Frames; Bindings::
122 * Symbols and Variables::
123 * Buffers and Textual Representation::
124 * MULE Character Sets and Encodings::
125 * The Lisp Reader and Compiler::
127 * Consoles; Devices; Frames; Windows::
128 * The Redisplay Mechanism::
134 * Interface to X Windows::
135 * Index:: Index including concepts, functions, variables,
138 --- The Detailed Node Listing ---
140 Here are other nodes that are inferiors of those already listed,
141 mentioned here so you can get to them in one step:
145 * Through Version 18:: Unification prevails.
146 * Lucid Emacs:: One version 19 Emacs.
147 * GNU Emacs 19:: The other version 19 Emacs.
148 * XEmacs:: The continuation of Lucid Emacs.
150 Rules When Writing New C Code
152 * General Coding Rules::
153 * Writing Lisp Primitives::
154 * Adding Global Lisp Variables::
155 * Techniques for XEmacs Developers::
157 A Summary of the Various XEmacs Modules
159 * Low-Level Modules::
160 * Basic Lisp Modules::
161 * Modules for Standard Editing Operations::
162 * Editor-Level Control Flow Modules::
163 * Modules for the Basic Displayable Lisp Objects::
164 * Modules for other Display-Related Lisp Objects::
165 * Modules for the Redisplay Mechanism::
166 * Modules for Interfacing with the File System::
167 * Modules for Other Aspects of the Lisp Interpreter and Object System::
168 * Modules for Interfacing with the Operating System::
169 * Modules for Interfacing with X Windows::
170 * Modules for Internationalization::
172 Allocation of Objects in XEmacs Lisp
174 * Introduction to Allocation::
175 * Garbage Collection::
177 * Integers and Characters::
178 * Allocation from Frob Blocks::
180 * Low-level allocation::
188 * Compiled Function::
190 Events and the Event Loop
192 * Introduction to Events::
194 * Specifics of the Event Gathering Mechanism::
195 * Specifics About the Emacs Event::
196 * The Event Stream Callback Routines::
197 * Other Event Loop Functions::
198 * Converting Events::
199 * Dispatching Events; The Command Builder::
201 Evaluation; Stack Frames; Bindings
204 * Dynamic Binding; The specbinding Stack; Unwind-Protects::
205 * Simple Special Forms::
208 Symbols and Variables
210 * Introduction to Symbols::
214 Buffers and Textual Representation
216 * Introduction to Buffers:: A buffer holds a block of text such as a file.
217 * The Text in a Buffer:: Representation of the text in a buffer.
218 * Buffer Lists:: Keeping track of all buffers.
219 * Markers and Extents:: Tagging locations within a buffer.
220 * Bufbytes and Emchars:: Representation of individual characters.
221 * The Buffer Object:: The Lisp object corresponding to a buffer.
223 MULE Character Sets and Encodings
227 * Internal Mule Encodings::
231 * Japanese EUC (Extended Unix Code)::
234 Internal Mule Encodings
236 * Internal String Encoding::
237 * Internal Character Encoding::
239 The Lisp Reader and Compiler
243 Consoles; Devices; Frames; Windows
245 * Introduction to Consoles; Devices; Frames; Windows::
249 The Redisplay Mechanism
251 * Critical Redisplay Sections::
256 * Introduction to Extents:: Extents are ranges over text, with properties.
257 * Extent Ordering:: How extents are ordered internally.
258 * Format of the Extent Info:: The extent information in a buffer or string.
259 * Zero-Length Extents:: A weird special case.
260 * Mathematics of Extent Ordering:: A rigorous foundation.
261 * Extent Fragments:: Cached information useful for redisplay.
271 Interface to X Windows
275 @node A History of Emacs, XEmacs From the Outside, Top, Top
276 @chapter A History of Emacs
277 @cindex history of Emacs
278 @cindex Hackers (Steven Levy)
280 @cindex ITS (Incompatible Timesharing System)
281 @cindex Stallman, Richard
286 @cindex Free Software Foundation
288 XEmacs is a powerful, customizable text editor and development
289 environment. It began as Lucid Emacs, which was in turn derived from
290 GNU Emacs, a program written by Richard Stallman of the Free Software
291 Foundation. GNU Emacs dates back to the 1970's, and was modelled
292 after a package called ``Emacs'', written in 1976, that was a set of
293 macros on top of TECO, an old, old text editor written at MIT on the
294 DEC PDP 10 under one of the earliest time-sharing operating systems,
295 ITS (Incompatible Timesharing System). (ITS dates back well before
296 Unix.) ITS, TECO, and Emacs were products of a group of people at MIT
297 who called themselves ``hackers'', who shared an idealistic belief
298 system about the free exchange of information and were fanatical in
299 their devotion to and time spent with computers. (The hacker
300 subculture dates back to the late 1950's at MIT and is described in
301 detail in Steven Levy's book @cite{Hackers}. This book also includes
302 a lot of information about Stallman himself and the development of
303 Lisp, a programming language developed at MIT that underlies Emacs.)
306 * Through Version 18:: Unification prevails.
307 * Lucid Emacs:: One version 19 Emacs.
308 * GNU Emacs 19:: The other version 19 Emacs.
309 * GNU Emacs 20:: The other version 20 Emacs.
310 * XEmacs:: The continuation of Lucid Emacs.
313 @node Through Version 18
314 @section Through Version 18
315 @cindex Gosling, James
316 @cindex Great Usenet Renaming
318 Although the history of the early versions of GNU Emacs is unclear,
319 the history is well-known from the middle of 1985. A time line is:
323 GNU Emacs version 15 (15.34) was released sometime in 1984 or 1985 and
324 shared some code with a version of Emacs written by James Gosling (the
325 same James Gosling who later created the Java language).
327 GNU Emacs version 16 (first released version was 16.56) was released on
328 July 15, 1985. All Gosling code was removed due to potential copyright
329 problems with the code.
331 version 16.57: released on September 16, 1985.
333 versions 16.58, 16.59: released on September 17, 1985.
335 version 16.60: released on September 19, 1985. These later version 16's
336 incorporated patches from the net, esp. for getting Emacs to work under
339 version 17.36 (first official v17 release) released on December 20,
340 1985. Included a TeX-able user manual. First official unpatched
341 version that worked on vanilla System V machines.
343 version 17.43 (second official v17 release) released on January 25,
346 version 17.45 released on January 30, 1986.
348 version 17.46 released on February 4, 1986.
350 version 17.48 released on February 10, 1986.
352 version 17.49 released on February 12, 1986.
354 version 17.55 released on March 18, 1986.
356 version 17.57 released on March 27, 1986.
358 version 17.58 released on April 4, 1986.
360 version 17.61 released on April 12, 1986.
362 version 17.63 released on May 7, 1986.
364 version 17.64 released on May 12, 1986.
366 version 18.24 (a beta version) released on October 2, 1986.
368 version 18.30 (a beta version) released on November 15, 1986.
370 version 18.31 (a beta version) released on November 23, 1986.
372 version 18.32 (a beta version) released on December 7, 1986.
374 version 18.33 (a beta version) released on December 12, 1986.
376 version 18.35 (a beta version) released on January 5, 1987.
378 version 18.36 (a beta version) released on January 21, 1987.
380 January 27, 1987: The Great Usenet Renaming. net.emacs is now
383 version 18.37 (a beta version) released on February 12, 1987.
385 version 18.38 (a beta version) released on March 3, 1987.
387 version 18.39 (a beta version) released on March 14, 1987.
389 version 18.40 (a beta version) released on March 18, 1987.
391 version 18.41 (the first ``official'' release) released on March 22,
394 version 18.45 released on June 2, 1987.
396 version 18.46 released on June 9, 1987.
398 version 18.47 released on June 18, 1987.
400 version 18.48 released on September 3, 1987.
402 version 18.49 released on September 18, 1987.
404 version 18.50 released on February 13, 1988.
406 version 18.51 released on May 7, 1988.
408 version 18.52 released on September 1, 1988.
410 version 18.53 released on February 24, 1989.
412 version 18.54 released on April 26, 1989.
414 version 18.55 released on August 23, 1989. This is the earliest version
415 that is still available by FTP.
417 version 18.56 released on January 17, 1991.
419 version 18.57 released late January, 1991.
421 version 18.58 released ?????.
423 version 18.59 released October 31, 1992.
433 Lucid Emacs was developed by the (now-defunct) Lucid Inc., a maker of
434 C++ and Lisp development environments. It began when Lucid decided they
435 wanted to use Emacs as the editor and cornerstone of their C++
436 development environment (called ``Energize''). They needed many features
437 that were not available in the existing version of GNU Emacs (version
438 18.5something), in particular good and integrated support for GUI
439 elements such as mouse support, multiple fonts, multiple window-system
440 windows, etc. A branch of GNU Emacs called Epoch, written at the
441 University of Illinois, existed that supplied many of these features;
442 however, Lucid needed more than what existed in Epoch. At the time, the
443 Free Software Foundation was working on version 19 of Emacs (this was
444 sometime around 1991), which was planned to have similar features, and
445 so Lucid decided to work with the Free Software Foundation. Their plan
446 was to add features that they needed, and coordinate with the FSF so
447 that the features would get included back into Emacs version 19.
449 Delays in the release of version 19 occurred, however (resulting in it
450 finally being released more than a year after what was initially
451 planned), and Lucid encountered unexpected technical resistance in
452 getting their changes merged back into version 19, so they decided to
453 release their own version of Emacs, which became Lucid Emacs 19.0.
455 @cindex Zawinski, Jamie
456 @cindex Sexton, Harlan
458 @cindex Devin, Matthieu
459 The initial authors of Lucid Emacs were Matthieu Devin, Harlan Sexton,
460 and Eric Benson, and the work was later taken over by Jamie Zawinski,
461 who became ``Mr. Lucid Emacs'' for many releases.
463 A time line for Lucid Emacs/XEmacs is
467 version 19.0 shipped with Energize 1.0, April 1992.
469 version 19.1 released June 4, 1992.
471 version 19.2 released June 19, 1992.
473 version 19.3 released September 9, 1992.
475 version 19.4 released January 21, 1993.
477 version 19.5 was a repackaging of 19.4 with a few bug fixes and
478 shipped with Energize 2.0. Never released to the net.
480 version 19.6 released April 9, 1993.
482 version 19.7 was a repackaging of 19.6 with a few bug fixes and
483 shipped with Energize 2.1. Never released to the net.
485 version 19.8 released September 6, 1993.
487 version 19.9 released January 12, 1994.
489 version 19.10 released May 27, 1994.
491 version 19.11 (first XEmacs) released September 13, 1994.
493 version 19.12 released June 23, 1995.
495 version 19.13 released September 1, 1995.
497 version 19.14 released June 23, 1996.
499 version 20.0 released February 9, 1997.
501 version 19.15 released March 28, 1997.
503 version 20.1 (not released to the net) April 15, 1997.
505 version 20.2 released May 16, 1997.
507 version 19.16 released October 31, 1997.
509 version 20.3 (the first stable version of XEmacs 20.x) released November 30,
511 version 20.4 released February 28, 1998.
515 @section GNU Emacs 19
519 About a year after the initial release of Lucid Emacs, the FSF
520 released a beta of their version of Emacs 19 (referred to here as ``GNU
521 Emacs''). By this time, the current version of Lucid Emacs was
522 19.6. (Strangely, the first released beta from the FSF was GNU Emacs
523 19.7.) A time line for GNU Emacs version 19 is
527 version 19.8 (beta) released May 27, 1993.
529 version 19.9 (beta) released May 27, 1993.
531 version 19.10 (beta) released May 30, 1993.
533 version 19.11 (beta) released June 1, 1993.
535 version 19.12 (beta) released June 2, 1993.
537 version 19.13 (beta) released June 8, 1993.
539 version 19.14 (beta) released June 17, 1993.
541 version 19.15 (beta) released June 19, 1993.
543 version 19.16 (beta) released July 6, 1993.
545 version 19.17 (beta) released late July, 1993.
547 version 19.18 (beta) released August 9, 1993.
549 version 19.19 (beta) released August 15, 1993.
551 version 19.20 (beta) released November 17, 1993.
553 version 19.21 (beta) released November 17, 1993.
555 version 19.22 (beta) released November 28, 1993.
557 version 19.23 (beta) released May 17, 1994.
559 version 19.24 (beta) released May 16, 1994.
561 version 19.25 (beta) released June 3, 1994.
563 version 19.26 (beta) released September 11, 1994.
565 version 19.27 (beta) released September 14, 1994.
567 version 19.28 (first ``official'' release) released November 1, 1994.
569 version 19.29 released June 21, 1995.
571 version 19.30 released November 24, 1995.
573 version 19.31 released May 25, 1996.
575 version 19.32 released July 31, 1996.
577 version 19.33 released August 11, 1996.
579 version 19.34 released August 21, 1996.
581 version 19.34b released September 6, 1996.
584 @cindex Mlynarik, Richard
585 In some ways, GNU Emacs 19 was better than Lucid Emacs; in some ways,
586 worse. Lucid soon began incorporating features from GNU Emacs 19 into
587 Lucid Emacs; the work was mostly done by Richard Mlynarik, who had been
588 working on and using GNU Emacs for a long time (back as far as version
592 @section GNU Emacs 20
596 On February 2, 1997 work began on GNU Emacs to integrate Mule. The first
597 release was made in September of that year.
599 A timeline for Emacs 20 is
603 version 20.1 released September 17, 1997.
605 version 20.2 released September 20, 1997.
607 version 20.3 released August 19, 1998.
614 @cindex Sun Microsystems
615 @cindex University of Illinois
616 @cindex Illinois, University of
618 @cindex Andreessen, Marc
620 @cindex Buchholz, Martin
621 @cindex Kaplan, Simon
623 @cindex Thompson, Chuck
626 @cindex Amdahl Corporation
627 Around the time that Lucid was developing Energize, Sun Microsystems
628 was developing their own development environment (called ``SPARCWorks'')
629 and also decided to use Emacs. They joined forces with the Epoch team
630 at the University of Illinois and later with Lucid. The maintainer of
631 the last-released version of Epoch was Marc Andreessen, but he dropped
632 out and the Epoch project, headed by Simon Kaplan, lured Chuck Thompson
633 away from a system administration job to become the primary Lucid Emacs
634 author for Epoch and Sun. Chuck's area of specialty became the
635 redisplay engine (he replaced the old Lucid Emacs redisplay engine with
636 a ported version from Epoch and then later rewrote it from scratch).
637 Sun also hired Ben Wing (the author of Win-Emacs, a port of Lucid Emacs
638 to Microsoft Windows 3.1) in 1993, for what was initially a one-month
639 contract to fix some event problems but later became a many-year
640 involvement, punctuated by a six-month contract with Amdahl Corporation.
642 @cindex rename to XEmacs
643 In 1994, Sun and Lucid agreed to rename Lucid Emacs to XEmacs (a name
644 not favorable to either company); the first release called XEmacs was
645 version 19.11. In June 1994, Lucid folded and Jamie quit to work for
646 the newly formed Mosaic Communications Corp., later Netscape
647 Communications Corp. (co-founded by the same Marc Andreessen, who had
648 quit his Epoch job to work on a graphical browser for the World Wide
649 Web). Chuck then become the primary maintainer of XEmacs, and put out
650 versions 19.11 through 19.14 in conjunction with Ben. For 19.12 and
651 19.13, Chuck added the new redisplay and many other display improvements
652 and Ben added MULE support (support for Asian and other languages) and
653 redesigned most of the internal Lisp subsystems to better support the
654 MULE work and the various other features being added to XEmacs. After
655 19.14 Chuck retired as primary maintainer and Steve Baur stepped in.
657 @cindex MULE merged XEmacs appears
658 Soon after 19.13 was released, work began in earnest on the MULE
659 internationalization code and the source tree was divided into two
660 development paths. The MULE version was initially called 19.20, but was
661 soon renamed to 20.0. In 1996 Martin Buchholz of Sun Microsystems took
662 over the care and feeding of it and worked on it in parallel with the
663 19.14 development that was occurring at the same time. After much work
664 by Martin, it was decided to release 20.0 ahead of 19.15 in February
665 1997. The source tree remained divided until 20.2 when the version 19
666 source was finally retired at version 19.16.
669 @cindex Buchholz, Martin
671 @cindex Niksic, Hrvoje
672 @cindex XEmacs goes it alone
673 In 1997, Sun finally dropped all pretense of support for XEmacs and
674 Martin Buchholz left the company in November. Since then, and mostly
675 for the previous year, because Steve Baur was never paid to work on
676 XEmacs, XEmacs has existed solely on the contributions of volunteers
677 from the Free Software Community. Starting from 1997, Hrvoje Niksic and
678 Kyle Jones have figured prominently in XEmacs development.
680 @cindex merging attempts
681 Many attempts have been made to merge XEmacs and GNU Emacs, but they
682 have consistently failed.
684 A more detailed history is contained in the XEmacs About page.
686 @node XEmacs From the Outside, The Lisp Language, A History of Emacs, Top
687 @chapter XEmacs From the Outside
688 @cindex read-eval-print
690 XEmacs appears to the outside world as an editor, but it is really a
691 Lisp environment. At its heart is a Lisp interpreter; it also
692 ``happens'' to contain many specialized object types (e.g. buffers,
693 windows, frames, events) that are useful for implementing an editor.
694 Some of these objects (in particular windows and frames) have
695 displayable representations, and XEmacs provides a function
696 @code{redisplay()} that ensures that the display of all such objects
697 matches their internal state. Most of the time, a standard Lisp
698 environment is in a @dfn{read-eval-print} loop -- i.e. ``read some Lisp
699 code, execute it, and print the results''. XEmacs has a similar loop:
705 dispatch the event (i.e. ``do it'')
710 Reading an event is done using the Lisp function @code{next-event},
711 which waits for something to happen (typically, the user presses a key
712 or moves the mouse) and returns an event object describing this.
713 Dispatching an event is done using the Lisp function
714 @code{dispatch-event}, which looks up the event in a keymap object (a
715 particular kind of object that associates an event with a Lisp function)
716 and calls that function. The function ``does'' what the user has
717 requested by changing the state of particular frame objects, buffer
718 objects, etc. Finally, @code{redisplay()} is called, which updates the
719 display to reflect those changes just made. Thus is an ``editor'' born.
721 @cindex bridge, playing
723 @cindex pi, calculating
724 Note that you do not have to use XEmacs as an editor; you could just
725 as well make it do your taxes, compute pi, play bridge, etc. You'd just
726 have to write functions to do those operations in Lisp.
728 @node The Lisp Language, XEmacs From the Perspective of Building, XEmacs From the Outside, Top
729 @chapter The Lisp Language
732 @cindex Lisp vs. Java
733 @cindex Java vs. Lisp
734 @cindex dynamic scoping
735 @cindex scoping, dynamic
736 @cindex dynamic types
737 @cindex types, dynamic
740 @cindex Gosling, James
742 Lisp is a general-purpose language that is higher-level than C and in
743 many ways more powerful than C. Powerful dialects of Lisp such as
744 Common Lisp are probably much better languages for writing very large
745 applications than is C. (Unfortunately, for many non-technical
746 reasons C and its successor C++ have become the dominant languages for
747 application development. These languages are both inadequate for
748 extremely large applications, which is evidenced by the fact that newer,
749 larger programs are becoming ever harder to write and are requiring ever
750 more programmers despite great increases in C development environments;
751 and by the fact that, although hardware speeds and reliability have been
752 growing at an exponential rate, most software is still generally
753 considered to be slow and buggy.)
755 The new Java language holds promise as a better general-purpose
756 development language than C. Java has many features in common with
757 Lisp that are not shared by C (this is not a coincidence, since
758 Java was designed by James Gosling, a former Lisp hacker). This
759 will be discussed more later.
761 For those used to C, here is a summary of the basic differences between
766 Lisp has an extremely regular syntax. Every function, expression,
767 and control statement is written in the form
770 (@var{func} @var{arg1} @var{arg2} ...)
773 This is as opposed to C, which writes functions as
776 func(@var{arg1}, @var{arg2}, ...)
779 but writes expressions involving operators as (e.g.)
782 @var{arg1} + @var{arg2}
785 and writes control statements as (e.g.)
788 while (@var{expr}) @{ @var{statement1}; @var{statement2}; ... @}
791 Lisp equivalents of the latter two would be
794 (+ @var{arg1} @var{arg2} ...)
800 (while @var{expr} @var{statement1} @var{statement2} ...)
804 Lisp is a safe language. Assuming there are no bugs in the Lisp
805 interpreter/compiler, it is impossible to write a program that ``core
806 dumps'' or otherwise causes the machine to execute an illegal
807 instruction. This is very different from C, where perhaps the most
808 common outcome of a bug is exactly such a crash. A corollary of this is that
809 the C operation of casting a pointer is impossible (and unnecessary) in
810 Lisp, and that it is impossible to access memory outside the bounds of
814 Programs and data are written in the same form. The
815 parenthesis-enclosing form described above for statements is the same
816 form used for the most common data type in Lisp, the list. Thus, it is
817 possible to represent any Lisp program using Lisp data types, and for
818 one program to construct Lisp statements and then dynamically
819 @dfn{evaluate} them, or cause them to execute.
822 All objects are @dfn{dynamically typed}. This means that part of every
823 object is an indication of what type it is. A Lisp program can
824 manipulate an object without knowing what type it is, and can query an
825 object to determine its type. This means that, correspondingly,
826 variables and function parameters can hold objects of any type and are
827 not normally declared as being of any particular type. This is opposed
828 to the @dfn{static typing} of C, where variables can hold exactly one
829 type of object and must be declared as such, and objects do not contain
830 an indication of their type because it's implicit in the variables they
831 are stored in. It is possible in C to have a variable hold different
832 types of objects (e.g. through the use of @code{void *} pointers or
833 variable-argument functions), but the type information must then be
834 passed explicitly in some other fashion, leading to additional program
838 Allocated memory is automatically reclaimed when it is no longer in use.
839 This operation is called @dfn{garbage collection} and involves looking
840 through all variables to see what memory is being pointed to, and
841 reclaiming any memory that is not pointed to and is thus
842 ``inaccessible'' and out of use. This is as opposed to C, in which
843 allocated memory must be explicitly reclaimed using @code{free()}. If
844 you simply drop all pointers to memory without freeing it, it becomes
845 ``leaked'' memory that still takes up space. Over a long period of
846 time, this can cause your program to grow and grow until it runs out of
850 Lisp has built-in facilities for handling errors and exceptions. In C,
851 when an error occurs, usually either the program exits entirely or the
852 routine in which the error occurs returns a value indicating this. If
853 an error occurs in a deeply-nested routine, then every routine currently
854 called must unwind itself normally and return an error value back up to
855 the next routine. This means that every routine must explicitly check
856 for an error in all the routines it calls; if it does not do so,
857 unexpected and often random behavior results. This is an extremely
858 common source of bugs in C programs. An alternative would be to do a
859 non-local exit using @code{longjmp()}, but that is often very dangerous
860 because the routines that were exited past had no opportunity to clean
861 up after themselves and may leave things in an inconsistent state,
862 causing a crash shortly afterwards.
864 Lisp provides mechanisms to make such non-local exits safe. When an
865 error occurs, a routine simply signals that an error of a particular
866 class has occurred, and a non-local exit takes place. Any routine can
867 trap errors occurring in routines it calls by registering an error
868 handler for some or all classes of errors. (If no handler is registered,
869 a default handler, generally installed by the top-level event loop, is
870 executed; this prints out the error and continues.) Routines can also
871 specify cleanup code (called an @dfn{unwind-protect}) that will be
872 called when control exits from a block of code, no matter how that exit
873 occurs -- i.e. even if a function deeply nested below it causes a
874 non-local exit back to the top level.
876 Note that this facility has appeared in some recent vintages of C, in
877 particular Visual C++ and other PC compilers written for the Microsoft
881 In Emacs Lisp, local variables are @dfn{dynamically scoped}. This means
882 that if you declare a local variable in a particular function, and then
883 call another function, that subfunction can ``see'' the local variable
884 you declared. This is actually considered a bug in Emacs Lisp and in
885 all other early dialects of Lisp, and was corrected in Common Lisp. (In
886 Common Lisp, you can still declare dynamically scoped variables if you
887 want to -- they are sometimes useful -- but variables by default are
888 @dfn{lexically scoped} as in C.)
891 For those familiar with Lisp, Emacs Lisp is modelled after MacLisp, an
892 early dialect of Lisp developed at MIT (no relation to the Macintosh
893 computer). There is a Common Lisp compatibility package available for
894 Emacs that provides many of the features of Common Lisp.
896 The Java language is derived in many ways from C, and shares a similar
897 syntax, but has the following features in common with Lisp (and different
902 Java is a safe language, like Lisp.
904 Java provides garbage collection, like Lisp.
906 Java has built-in facilities for handling errors and exceptions, like
909 Java has a type system that combines the best advantages of both static
910 and dynamic typing. Objects (except very simple types) are explicitly
911 marked with their type, as in dynamic typing; but there is a hierarchy
912 of types and functions are declared to accept only certain types, thus
913 providing the increased compile-time error-checking of static typing.
916 The Java language also has some negative attributes:
920 Java uses the edit/compile/run model of software development. This
921 makes it hard to use interactively. For example, to use Java like
922 @code{bc} it is necessary to write a special purpose, albeit tiny,
923 application. In Emacs Lisp, a calculator comes built-in without any
924 effort - one can always just type an expression in the @code{*scratch*}
927 Java tries too hard to enforce, not merely enable, portability, making
928 ordinary access to standard OS facilities painful. Java has an
929 @dfn{agenda}. I think this is why @code{chdir} is not part of standard
930 Java, which is inexcusable.
933 Unfortunately, there is no perfect language. Static typing allows a
934 compiler to catch programmer errors and produce more efficient code, but
935 makes programming more tedious and less fun. For the forseeable future,
936 an Ideal Editing and Programming Environment (and that is what XEmacs
937 aspires to) will be programmable in multiple languages: high level ones
938 like Lisp for user customization and prototyping, and lower level ones
939 for infrastructure and industrial strength applications. If I had my
940 way, XEmacs would be friendly towards the Python, Scheme, C++, ML,
941 etc... communities. But there are serious technical difficulties to
944 The word @dfn{application} in the previous paragraph was used
945 intentionally. XEmacs implements an API for programs written in Lisp
946 that makes it a full-fledged application platform, very much like an OS
949 @node XEmacs From the Perspective of Building, XEmacs From the Inside, The Lisp Language, Top
950 @chapter XEmacs From the Perspective of Building
952 The heart of XEmacs is the Lisp environment, which is written in C.
953 This is contained in the @file{src/} subdirectory. Underneath
954 @file{src/} are two subdirectories of header files: @file{s/} (header
955 files for particular operating systems) and @file{m/} (header files for
956 particular machine types). In practice the distinction between the two
957 types of header files is blurred. These header files define or undefine
958 certain preprocessor constants and macros to indicate particular
959 characteristics of the associated machine or operating system. As part
960 of the configure process, one @file{s/} file and one @file{m/} file is
961 identified for the particular environment in which XEmacs is being
964 XEmacs also contains a great deal of Lisp code. This implements the
965 operations that make XEmacs useful as an editor as well as just a Lisp
966 environment, and also contains many add-on packages that allow XEmacs to
967 browse directories, act as a mail and Usenet news reader, compile Lisp
968 code, etc. There is actually more Lisp code than C code associated with
969 XEmacs, but much of the Lisp code is peripheral to the actual operation
970 of the editor. The Lisp code all lies in subdirectories underneath the
971 @file{lisp/} directory.
973 The @file{lwlib/} directory contains C code that implements a
974 generalized interface onto different X widget toolkits and also
975 implements some widgets of its own that behave like Motif widgets but
976 are faster, free, and in some cases more powerful. The code in this
977 directory compiles into a library and is mostly independent from XEmacs.
979 The @file{etc/} directory contains various data files associated with
980 XEmacs. Some of them are actually read by XEmacs at startup; others
981 merely contain useful information of various sorts.
983 The @file{lib-src/} directory contains C code for various auxiliary
984 programs that are used in connection with XEmacs. Some of them are used
985 during the build process; others are used to perform certain functions
986 that cannot conveniently be placed in the XEmacs executable (e.g. the
987 @file{movemail} program for fetching mail out of @file{/var/spool/mail},
988 which must be setgid to @file{mail} on many systems; and the
989 @file{gnuclient} program, which allows an external script to communicate
990 with a running XEmacs process).
992 The @file{man/} directory contains the sources for the XEmacs
993 documentation. It is mostly in a form called Texinfo, which can be
994 converted into either a printed document (by passing it through @TeX{})
995 or into on-line documentation called @dfn{info files}.
997 The @file{info/} directory contains the results of formatting the XEmacs
998 documentation as @dfn{info files}, for on-line use. These files are
999 used when you enter the Info system using @kbd{C-h i} or through the
1002 The @file{dynodump/} directory contains auxiliary code used to build
1003 XEmacs on Solaris platforms.
1005 The other directories contain various miscellaneous code and information
1006 that is not normally used or needed.
1008 The first step of building involves running the @file{configure} program
1009 and passing it various parameters to specify any optional features you
1010 want and compiler arguments and such, as described in the @file{INSTALL}
1011 file. This determines what the build environment is, chooses the
1012 appropriate @file{s/} and @file{m/} file, and runs a series of tests to
1013 determine many details about your environment, such as which library
1014 functions are available and exactly how they work. The reason for
1015 running these tests is that it allows XEmacs to be compiled on a much
1016 wider variety of platforms than those that the XEmacs developers happen
1017 to be familiar with, including various sorts of hybrid platforms. This
1018 is especially important now that many operating systems give you a great
1019 deal of control over exactly what features you want installed, and allow
1020 for easy upgrading of parts of a system without upgrading the rest. It
1021 would be impossible to pre-determine and pre-specify the information for
1022 all possible configurations.
1024 In fact, the @file{s/} and @file{m/} files are basically @emph{evil},
1025 since they contain unmaintainable platform-specific hard-coded
1026 information. XEmacs has been moving in the direction of having all
1027 system-specific information be determined dynamically by
1028 @file{configure}. Perhaps someday we can @code{rm -rf src/s src/m}.
1030 When configure is done running, it generates @file{Makefile}s and
1031 @file{GNUmakefile}s and the file @file{src/config.h} (which describes
1032 the features of your system) from template files. You then run
1033 @file{make}, which compiles the auxiliary code and programs in
1034 @file{lib-src/} and @file{lwlib/} and the main XEmacs executable in
1035 @file{src/}. The result of compiling and linking is an executable
1036 called @file{temacs}, which is @emph{not} the final XEmacs executable.
1037 @file{temacs} by itself is not intended to function as an editor or even
1038 display any windows on the screen, and if you simply run it, it will
1039 exit immediately. The @file{Makefile} runs @file{temacs} with certain
1040 options that cause it to initialize itself, read in a number of basic
1041 Lisp files, and then dump itself out into a new executable called
1042 @file{xemacs}. This new executable has been pre-initialized and
1043 contains pre-digested Lisp code that is necessary for the editor to
1044 function (this includes most basic editing functions,
1045 e.g. @code{kill-line}, that can be defined in terms of other Lisp
1046 primitives; some initialization code that is called when certain
1047 objects, such as frames, are created; and all of the standard
1048 keybindings and code for the actions they result in). This executable,
1049 @file{xemacs}, is the executable that you run to use the XEmacs editor.
1051 Although @file{temacs} is not intended to be run as an editor, it can,
1052 by using the incantation @code{temacs -batch -l loadup.el run-temacs}.
1053 This is useful when the dumping procedure described above is broken, or
1054 when using certain program debugging tools such as Purify. These tools
1055 get mighty confused by the tricks played by the XEmacs build process,
1056 such as allocation memory in one process, and freeing it in the next.
1058 @node XEmacs From the Inside, The XEmacs Object System (Abstractly Speaking), XEmacs From the Perspective of Building, Top
1059 @chapter XEmacs From the Inside
1061 Internally, XEmacs is quite complex, and can be very confusing. To
1062 simplify things, it can be useful to think of XEmacs as containing an
1063 event loop that ``drives'' everything, and a number of other subsystems,
1064 such as a Lisp engine and a redisplay mechanism. Each of these other
1065 subsystems exists simultaneously in XEmacs, and each has a certain
1066 state. The flow of control continually passes in and out of these
1067 different subsystems in the course of normal operation of the editor.
1069 It is important to keep in mind that, most of the time, the editor is
1070 ``driven'' by the event loop. Except during initialization and batch
1071 mode, all subsystems are entered directly or indirectly through the
1072 event loop, and ultimately, control exits out of all subsystems back up
1073 to the event loop. This cycle of entering a subsystem, exiting back out
1074 to the event loop, and starting another iteration of the event loop
1075 occurs once each keystroke, mouse motion, etc.
1077 If you're trying to understand a particular subsystem (other than the
1078 event loop), think of it as a ``daemon'' process or ``servant'' that is
1079 responsible for one particular aspect of a larger system, and
1080 periodically receives commands or environment changes that cause it to
1081 do something. Ultimately, these commands and environment changes are
1082 always triggered by the event loop. For example:
1086 The window and frame mechanism is responsible for keeping track of what
1087 windows and frames exist, what buffers are in them, etc. It is
1088 periodically given commands (usually from the user) to make a change to
1089 the current window/frame state: i.e. create a new frame, delete a
1093 The buffer mechanism is responsible for keeping track of what buffers
1094 exist and what text is in them. It is periodically given commands
1095 (usually from the user) to insert or delete text, create a buffer, etc.
1096 When it receives a text-change command, it notifies the redisplay
1100 The redisplay mechanism is responsible for making sure that windows and
1101 frames are displayed correctly. It is periodically told (by the event
1102 loop) to actually ``do its job'', i.e. snoop around and see what the
1103 current state of the environment (mostly of the currently-existing
1104 windows, frames, and buffers) is, and make sure that that state matches
1105 what's actually displayed. It keeps lots and lots of information around
1106 (such as what is actually being displayed currently, and what the
1107 environment was last time it checked) so that it can minimize the work
1108 it has to do. It is also helped along in that whenever a relevant
1109 change to the environment occurs, the redisplay mechanism is told about
1110 this, so it has a pretty good idea of where it has to look to find
1111 possible changes and doesn't have to look everywhere.
1114 The Lisp engine is responsible for executing the Lisp code in which most
1115 user commands are written. It is entered through a call to @code{eval}
1116 or @code{funcall}, which occurs as a result of dispatching an event from
1117 the event loop. The functions it calls issue commands to the buffer
1118 mechanism, the window/frame subsystem, etc.
1121 The Lisp allocation subsystem is responsible for keeping track of Lisp
1122 objects. It is given commands from the Lisp engine to allocate objects,
1123 garbage collect, etc.
1128 The important idea here is that there are a number of independent
1129 subsystems each with its own responsibility and persistent state, just
1130 like different employees in a company, and each subsystem is
1131 periodically given commands from other subsystems. Commands can flow
1132 from any one subsystem to any other, but there is usually some sort of
1133 hierarchy, with all commands originating from the event subsystem.
1135 XEmacs is entered in @code{main()}, which is in @file{emacs.c}. When
1136 this is called the first time (in a properly-invoked @file{temacs}), it
1141 It does some very basic environment initializations, such as determining
1142 where it and its directories (e.g. @file{lisp/} and @file{etc/}) reside
1143 and setting up signal handlers.
1145 It initializes the entire Lisp interpreter.
1147 It sets the initial values of many built-in variables (including many
1148 variables that are visible to Lisp programs), such as the global keymap
1149 object and the built-in faces (a face is an object that describes the
1150 display characteristics of text). This involves creating Lisp objects
1151 and thus is dependent on step (2).
1153 It performs various other initializations that are relevant to the
1154 particular environment it is running in, such as retrieving environment
1155 variables, determining the current date and the user who is running the
1156 program, examining its standard input, creating any necessary file
1159 At this point, the C initialization is complete. A Lisp program that
1160 was specified on the command line (usually @file{loadup.el}) is called
1161 (temacs is normally invoked as @code{temacs -batch -l loadup.el dump}).
1162 @file{loadup.el} loads all of the other Lisp files that are needed for
1163 the operation of the editor, calls the @code{dump-emacs} function to
1164 write out @file{xemacs}, and then kills the temacs process.
1167 When @file{xemacs} is then run, it only redoes steps (1) and (4)
1168 above; all variables already contain the values they were set to when
1169 the executable was dumped, and all memory that was allocated with
1170 @code{malloc()} is still around. (XEmacs knows whether it is being run
1171 as @file{xemacs} or @file{temacs} because it sets the global variable
1172 @code{initialized} to 1 after step (4) above.) At this point,
1173 @file{xemacs} calls a Lisp function to do any further initialization,
1174 which includes parsing the command-line (the C code can only do limited
1175 command-line parsing, which includes looking for the @samp{-batch} and
1176 @samp{-l} flags and a few other flags that it needs to know about before
1177 initialization is complete), creating the first frame (or @dfn{window}
1178 in standard window-system parlance), running the user's init file
1179 (usually the file @file{.emacs} in the user's home directory), etc. The
1180 function to do this is usually called @code{normal-top-level};
1181 @file{loadup.el} tells the C code about this function by setting its
1182 name as the value of the Lisp variable @code{top-level}.
1184 When the Lisp initialization code is done, the C code enters the event
1185 loop, and stays there for the duration of the XEmacs process. The code
1186 for the event loop is contained in @file{keyboard.c}, and is called
1187 @code{Fcommand_loop_1()}. Note that this event loop could very well be
1188 written in Lisp, and in fact a Lisp version exists; but apparently,
1189 doing this makes XEmacs run noticeably slower.
1191 Notice how much of the initialization is done in Lisp, not in C.
1192 In general, XEmacs tries to move as much code as is possible
1193 into Lisp. Code that remains in C is code that implements the
1194 Lisp interpreter itself, or code that needs to be very fast, or
1195 code that needs to do system calls or other such stuff that
1196 needs to be done in C, or code that needs to have access to
1197 ``forbidden'' structures. (One conscious aspect of the design of
1198 Lisp under XEmacs is a clean separation between the external
1199 interface to a Lisp object's functionality and its internal
1200 implementation. Part of this design is that Lisp programs
1201 are forbidden from accessing the contents of the object other
1202 than through using a standard API. In this respect, XEmacs Lisp
1203 is similar to modern Lisp dialects but differs from GNU Emacs,
1204 which tends to expose the implementation and allow Lisp
1205 programs to look at it directly. The major advantage of
1206 hiding the implementation is that it allows the implementation
1207 to be redesigned without affecting any Lisp programs, including
1208 those that might want to be ``clever'' by looking directly at
1209 the object's contents and possibly manipulating them.)
1211 Moving code into Lisp makes the code easier to debug and maintain and
1212 makes it much easier for people who are not XEmacs developers to
1213 customize XEmacs, because they can make a change with much less chance
1214 of obscure and unwanted interactions occurring than if they were to
1217 @node The XEmacs Object System (Abstractly Speaking), How Lisp Objects Are Represented in C, XEmacs From the Inside, Top
1218 @chapter The XEmacs Object System (Abstractly Speaking)
1220 At the heart of the Lisp interpreter is its management of objects.
1221 XEmacs Lisp contains many built-in objects, some of which are
1222 simple and others of which can be very complex; and some of which
1223 are very common, and others of which are rarely used or are only
1224 used internally. (Since the Lisp allocation system, with its
1225 automatic reclamation of unused storage, is so much more convenient
1226 than @code{malloc()} and @code{free()}, the C code makes extensive use of it
1227 in its internal operations.)
1229 The basic Lisp objects are
1233 28 or 31 bits of precision, or 60 or 63 bits on 64-bit machines; the
1234 reason for this is described below when the internal Lisp object
1235 representation is described.
1237 Same precision as a double in C.
1239 A simple container for two Lisp objects, used to implement lists and
1240 most other data structures in Lisp.
1242 An object representing a single character of text; chars behave like
1243 integers in many ways but are logically considered text rather than
1244 numbers and have a different read syntax. (the read syntax for a char
1245 contains the char itself or some textual encoding of it -- for example,
1246 a Japanese Kanji character might be encoded as @samp{^[$(B#&^[(B} using the
1247 ISO-2022 encoding standard -- rather than the numerical representation
1248 of the char; this way, if the mapping between chars and integers
1249 changes, which is quite possible for Kanji characters and other extended
1250 characters, the same character will still be created. Note that some
1251 primitives confuse chars and integers. The worst culprit is @code{eq},
1252 which makes a special exception and considers a char to be @code{eq} to
1253 its integer equivalent, even though in no other case are objects of two
1254 different types @code{eq}. The reason for this monstrosity is
1255 compatibility with existing code; the separation of char from integer
1256 came fairly recently.)
1258 An object that contains Lisp objects and is referred to by name;
1259 symbols are used to implement variables and named functions
1260 and to provide the equivalent of preprocessor constants in C.
1262 A one-dimensional array of Lisp objects providing constant-time access
1263 to any of the objects; access to an arbitrary object in a vector is
1264 faster than for lists, but the operations that can be done on a vector
1267 Self-explanatory; behaves much like a vector of chars
1268 but has a different read syntax and is stored and manipulated
1271 A vector of bits; similar to a string in spirit.
1272 @item compiled-function
1273 An object containing compiled Lisp code, known as @dfn{byte code}.
1275 A Lisp primitive, i.e. a Lisp-callable function implemented in C.
1279 Note that there is no basic ``function'' type, as in more powerful
1280 versions of Lisp (where it's called a @dfn{closure}). XEmacs Lisp does
1281 not provide the closure semantics implemented by Common Lisp and Scheme.
1282 The guts of a function in XEmacs Lisp are represented in one of four
1283 ways: a symbol specifying another function (when one function is an
1284 alias for another), a list (whose first element must be the symbol
1285 @code{lambda}) containing the function's source code, a
1286 compiled-function object, or a subr object. (In other words, given a
1287 symbol specifying the name of a function, calling @code{symbol-function}
1288 to retrieve the contents of the symbol's function cell will return one
1289 of these types of objects.)
1291 XEmacs Lisp also contains numerous specialized objects used to implement
1296 Stores text like a string, but is optimized for insertion and deletion
1297 and has certain other properties that can be set.
1299 An object with various properties whose displayable representation is a
1300 @dfn{window} in window-system parlance.
1302 A section of a frame that displays the contents of a buffer;
1303 often called a @dfn{pane} in window-system parlance.
1304 @item window-configuration
1305 An object that represents a saved configuration of windows in a frame.
1307 An object representing a screen on which frames can be displayed;
1308 equivalent to a @dfn{display} in the X Window System and a @dfn{TTY} in
1311 An object specifying the appearance of text or graphics; it has
1312 properties such as font, foreground color, and background color.
1314 An object that refers to a particular position in a buffer and moves
1315 around as text is inserted and deleted to stay in the same relative
1316 position to the text around it.
1318 Similar to a marker but covers a range of text in a buffer; can also
1319 specify properties of the text, such as a face in which the text is to
1320 be displayed, whether the text is invisible or unmodifiable, etc.
1322 Generated by calling @code{next-event} and contains information
1323 describing a particular event happening in the system, such as the user
1324 pressing a key or a process terminating.
1326 An object that maps from events (described using lists, vectors, and
1327 symbols rather than with an event object because the mapping is for
1328 classes of events, rather than individual events) to functions to
1329 execute or other events to recursively look up; the functions are
1330 described by name, using a symbol, or using lists to specify the
1333 An object that describes the appearance of an image (e.g. pixmap) on
1334 the screen; glyphs can be attached to the beginning or end of extents
1335 and in some future version of XEmacs will be able to be inserted
1336 directly into a buffer.
1338 An object that describes a connection to an externally-running process.
1341 There are some other, less-commonly-encountered general objects:
1345 An object that maps from an arbitrary Lisp object to another arbitrary
1346 Lisp object, using hashing for fast lookup.
1348 A limited form of hash-table that maps from strings to symbols; obarrays
1349 are used to look up a symbol given its name and are not actually their
1350 own object type but are kludgily represented using vectors with hidden
1351 fields (this representation derives from GNU Emacs).
1353 A complex object used to specify the value of a display property; a
1354 default value is given and different values can be specified for
1355 particular frames, buffers, windows, devices, or classes of device.
1357 An object that maps from chars or classes of chars to arbitrary Lisp
1358 objects; internally char tables use a complex nested-vector
1359 representation that is optimized to the way characters are represented
1362 An object that maps from ranges of integers to arbitrary Lisp objects.
1365 And some strange special-purpose objects:
1369 @itemx coding-system
1370 Objects used when MULE, or multi-lingual/Asian-language, support is
1372 @item color-instance
1373 @itemx font-instance
1374 @itemx image-instance
1375 An object that encapsulates a window-system resource; instances are
1376 mostly used internally but are exposed on the Lisp level for cleanness
1377 of the specifier model and because it's occasionally useful for Lisp
1378 program to create or query the properties of instances.
1380 An object that encapsulate a @dfn{subwindow} resource, i.e. a
1381 window-system child window that is drawn into by an external process;
1382 this object should be integrated into the glyph system but isn't yet,
1383 and may change form when this is done.
1384 @item tooltalk-message
1385 @itemx tooltalk-pattern
1386 Objects that represent resources used in the ToolTalk interprocess
1387 communication protocol.
1388 @item toolbar-button
1389 An object used in conjunction with the toolbar.
1392 And objects that are only used internally:
1396 A generic object for encapsulating arbitrary memory; this allows you the
1397 generality of @code{malloc()} and the convenience of the Lisp object
1400 A buffering I/O stream, used to provide a unified interface to anything
1401 that can accept output or provide input, such as a file descriptor, a
1402 stdio stream, a chunk of memory, a Lisp buffer, a Lisp string, etc.;
1403 it's a Lisp object to make its memory management more convenient.
1404 @item char-table-entry
1405 Subsidiary objects in the internal char-table representation.
1406 @item extent-auxiliary
1409 Various special-purpose objects that are basically just used to
1410 encapsulate memory for particular subsystems, similar to the more
1411 general ``opaque'' object.
1412 @item symbol-value-forward
1413 @itemx symbol-value-buffer-local
1414 @itemx symbol-value-varalias
1415 @itemx symbol-value-lisp-magic
1416 Special internal-only objects that are placed in the value cell of a
1417 symbol to indicate that there is something special with this variable --
1418 e.g. it has no value, it mirrors another variable, or it mirrors some C
1419 variable; there is really only one kind of object, called a
1420 @dfn{symbol-value-magic}, but it is sort-of halfway kludged into
1421 semi-different object types.
1424 @cindex permanent objects
1425 @cindex temporary objects
1426 Some types of objects are @dfn{permanent}, meaning that once created,
1427 they do not disappear until explicitly destroyed, using a function such
1428 as @code{delete-buffer}, @code{delete-window}, @code{delete-frame}, etc.
1429 Others will disappear once they are not longer used, through the garbage
1430 collection mechanism. Buffers, frames, windows, devices, and processes
1431 are among the objects that are permanent. Note that some objects can go
1432 both ways: Faces can be created either way; extents are normally
1433 permanent, but detached extents (extents not referring to any text, as
1434 happens to some extents when the text they are referring to is deleted)
1435 are temporary. Note that some permanent objects, such as faces and
1436 coding systems, cannot be deleted. Note also that windows are unique in
1437 that they can be @emph{undeleted} after having previously been
1438 deleted. (This happens as a result of restoring a window configuration.)
1441 Note that many types of objects have a @dfn{read syntax}, i.e. a way of
1442 specifying an object of that type in Lisp code. When you load a Lisp
1443 file, or type in code to be evaluated, what really happens is that the
1444 function @code{read} is called, which reads some text and creates an object
1445 based on the syntax of that text; then @code{eval} is called, which
1446 possibly does something special; then this loop repeats until there's
1447 no more text to read. (@code{eval} only actually does something special
1448 with symbols, which causes the symbol's value to be returned,
1449 similar to referencing a variable; and with conses [i.e. lists],
1450 which cause a function invocation. All other values are returned
1459 converts to an integer whose value is 17297.
1465 converts to a float whose value is 1.983e-4, or .0001983.
1471 converts to a char that represents the lowercase letter b.
1477 (where @samp{^[} actually is an @samp{ESC} character) converts to a
1478 particular Kanji character when using an ISO2022-based coding system for
1479 input. (To decode this goo: @samp{ESC} begins an escape sequence;
1480 @samp{ESC $ (} is a class of escape sequences meaning ``switch to a
1481 94x94 character set''; @samp{ESC $ ( B} means ``switch to Japanese
1482 Kanji''; @samp{#} and @samp{&} collectively index into a 94-by-94 array
1483 of characters [subtract 33 from the ASCII value of each character to get
1484 the corresponding index]; @samp{ESC (} is a class of escape sequences
1485 meaning ``switch to a 94 character set''; @samp{ESC (B} means ``switch
1486 to US ASCII''. It is a coincidence that the letter @samp{B} is used to
1487 denote both Japanese Kanji and US ASCII. If the first @samp{B} were
1488 replaced with an @samp{A}, you'd be requesting a Chinese Hanzi character
1489 from the GB2312 character set.)
1495 converts to a string.
1501 converts to a symbol whose name is @code{"foobar"}. This is done by
1502 looking up the string equivalent in the global variable
1503 @code{obarray}, whose contents should be an obarray. If no symbol
1504 is found, a new symbol with the name @code{"foobar"} is automatically
1505 created and added to @code{obarray}; this process is called
1506 @dfn{interning} the symbol.
1513 converts to a cons cell containing the symbols @code{foo} and @code{bar}.
1519 converts to a three-element list containing the specified objects
1520 (note that a list is actually a set of nested conses; see the
1521 XEmacs Lisp Reference).
1527 converts to a three-element vector containing the specified objects.
1533 converts to a compiled-function object (the actual contents are not
1534 shown since they are not relevant here; look at a file that ends with
1535 @file{.elc} for examples).
1541 converts to a bit-vector.
1544 #s(hash-table ... ...)
1547 converts to a hash table (the actual contents are not shown).
1550 #s(range-table ... ...)
1553 converts to a range table (the actual contents are not shown).
1556 #s(char-table ... ...)
1559 converts to a char table (the actual contents are not shown).
1561 Note that the @code{#s()} syntax is the general syntax for structures,
1562 which are not really implemented in XEmacs Lisp but should be.
1564 When an object is printed out (using @code{print} or a related
1565 function), the read syntax is used, so that the same object can be read
1568 The other objects do not have read syntaxes, usually because it does not
1569 really make sense to create them in this fashion (i.e. processes, where
1570 it doesn't make sense to have a subprocess created as a side effect of
1571 reading some Lisp code), or because they can't be created at all
1572 (e.g. subrs). Permanent objects, as a rule, do not have a read syntax;
1573 nor do most complex objects, which contain too much state to be easily
1574 initialized through a read syntax.
1576 @node How Lisp Objects Are Represented in C, Rules When Writing New C Code, The XEmacs Object System (Abstractly Speaking), Top
1577 @chapter How Lisp Objects Are Represented in C
1579 Lisp objects are represented in C using a 32-bit or 64-bit machine word
1580 (depending on the processor; i.e. DEC Alphas use 64-bit Lisp objects and
1581 most other processors use 32-bit Lisp objects). The representation
1582 stuffs a pointer together with a tag, as follows:
1585 [ 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 ]
1586 [ 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 ]
1588 <---> ^ <------------------------------------------------------>
1589 tag | a pointer to a structure, or an integer
1594 The tag describes the type of the Lisp object. For integers and chars,
1595 the lower 28 bits contain the value of the integer or char; for all
1596 others, the lower 28 bits contain a pointer. The mark bit is used
1597 during garbage-collection, and is always 0 when garbage collection is
1598 not happening. (The way that garbage collection works, basically, is that it
1599 loops over all places where Lisp objects could exist -- this includes
1600 all global variables in C that contain Lisp objects [including
1601 @code{Vobarray}, the C equivalent of @code{obarray}; through this, all
1602 Lisp variables will get marked], plus various other places -- and
1603 recursively scans through the Lisp objects, marking each object it finds
1604 by setting the mark bit. Then it goes through the lists of all objects
1605 allocated, freeing the ones that are not marked and turning off the mark
1606 bit of the ones that are marked.)
1608 Lisp objects use the typedef @code{Lisp_Object}, but the actual C type
1609 used for the Lisp object can vary. It can be either a simple type
1610 (@code{long} on the DEC Alpha, @code{int} on other machines) or a
1611 structure whose fields are bit fields that line up properly (actually, a
1612 union of structures is used). Generally the simple integral type is
1613 preferable because it ensures that the compiler will actually use a
1614 machine word to represent the object (some compilers will use more
1615 general and less efficient code for unions and structs even if they can
1616 fit in a machine word). The union type, however, has the advantage of
1617 stricter type checking (if you accidentally pass an integer where a Lisp
1618 object is desired, you get a compile error), and it makes it easier to
1619 decode Lisp objects when debugging. The choice of which type to use is
1620 determined by the preprocessor constant @code{USE_UNION_TYPE} which is
1621 defined via the @code{--use-union-type} option to @code{configure}.
1625 Note that there are only eight types that the tag can represent, but
1626 many more actual types than this. This is handled by having one of the
1627 tag types specify a meta-type called a @dfn{record}; for all such
1628 objects, the first four bytes of the pointed-to structure indicate what
1631 Note also that having 28 bits for pointers and integers restricts a lot
1632 of things to 256 megabytes of memory. (Basically, enough pointers and
1633 indices and whatnot get stuffed into Lisp objects that the total amount
1634 of memory used by XEmacs can't grow above 256 megabytes. In older
1635 versions of XEmacs and GNU Emacs, the tag was 5 bits wide, allowing for
1636 32 types, which was more than the actual number of types that existed at
1637 the time, and no ``record'' type was necessary. However, this limited
1638 the editor to 64 megabytes total, which some users who edited large
1639 files might conceivably exceed.)
1641 Also, note that there is an implicit assumption here that all pointers
1642 are low enough that the top bits are all zero and can just be chopped
1643 off. On standard machines that allocate memory from the bottom up (and
1644 give each process its own address space), this works fine. Some
1645 machines, however, put the data space somewhere else in memory
1646 (e.g. beginning at 0x80000000). Those machines cope by defining
1647 @code{DATA_SEG_BITS} in the corresponding @file{m/} or @file{s/} file to
1648 the proper mask. Then, pointers retrieved from Lisp objects are
1649 automatically OR'ed with this value prior to being used.
1651 A corollary of the previous paragraph is that @strong{(pointers to)
1652 stack-allocated structures cannot be put into Lisp objects}. The stack
1653 is generally located near the top of memory; if you put such a pointer
1654 into a Lisp object, it will get its top bits chopped off, and you will
1657 Actually, there's an alternative representation of a @code{Lisp_Object},
1658 invented by Kyle Jones, that is used when the
1659 @code{--use-minimal-tagbits} option to @code{configure} is used. In
1660 this case the 2 lower bits are used for the tag bits. This
1661 representation assumes that pointers to structs are always aligned to
1662 multiples of 4, so the lower 2 bits are always zero.
1665 [ 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 ]
1666 [ 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 ]
1668 <---------------------------------------------------------> <->
1669 a pointer to a structure, or an integer tag
1672 A tag of 00 is used for all pointer object types, a tag of 10 is used
1673 for characters, and the other two tags 01 and 11 are joined together to
1674 form the integer object type. The markbit is moved to part of the
1675 structure being pointed at (integers and chars do not need to be marked,
1676 since no memory is allocated). This representation has these
1681 31 bits can be used for Lisp Integers.
1683 @emph{Any} pointer can be represented directly, and no bit masking
1684 operations are necessary.
1687 The disadvantages are:
1691 An extra level of indirection is needed when accessing the object types
1692 that were not record types. So checking whether a Lisp object is a cons
1693 cell becomes a slower operation.
1695 Mark bits can no longer be stored directly in Lisp objects, so another
1696 place for them must be found. This means that a cons cell requires more
1697 memory than merely room for 2 lisp objects, leading to extra memory use.
1700 Various macros are used to construct Lisp objects and extract the
1701 components. Macros of the form @code{XINT()}, @code{XCHAR()},
1702 @code{XSTRING()}, @code{XSYMBOL()}, etc. mask out the pointer/integer
1703 field and cast it to the appropriate type. All of the macros that
1704 construct pointers will @code{OR} with @code{DATA_SEG_BITS} if
1705 necessary. @code{XINT()} needs to be a bit tricky so that negative
1706 numbers are properly sign-extended: Usually it does this by shifting the
1707 number four bits to the left and then four bits to the right. This
1708 assumes that the right-shift operator does an arithmetic shift (i.e. it
1709 leaves the most-significant bit as-is rather than shifting in a zero, so
1710 that it mimics a divide-by-two even for negative numbers). Not all
1711 machines/compilers do this, and on the ones that don't, a more
1712 complicated definition is selected by defining
1713 @code{EXPLICIT_SIGN_EXTEND}.
1715 Note that when @code{ERROR_CHECK_TYPECHECK} is defined, the extractor
1716 macros become more complicated -- they check the tag bits and/or the
1717 type field in the first four bytes of a record type to ensure that the
1718 object is really of the correct type. This is great for catching places
1719 where an incorrect type is being dereferenced -- this typically results
1720 in a pointer being dereferenced as the wrong type of structure, with
1721 unpredictable (and sometimes not easily traceable) results.
1723 There are similar @code{XSET@var{TYPE}()} macros that construct a Lisp
1724 object. These macros are of the form @code{XSET@var{TYPE}
1725 (@var{lvalue}, @var{result})},
1726 i.e. they have to be a statement rather than just used in an expression.
1727 The reason for this is that standard C doesn't let you ``construct'' a
1728 structure (but GCC does). Granted, this sometimes isn't too convenient;
1729 for the case of integers, at least, you can use the function
1730 @code{make_int()}, which constructs and @emph{returns} an integer
1731 Lisp object. Note that the @code{XSET@var{TYPE}()} macros are also
1732 affected by @code{ERROR_CHECK_TYPECHECK} and make sure that the
1733 structure is of the right type in the case of record types, where the
1734 type is contained in the structure.
1736 The C programmer is responsible for @strong{guaranteeing} that a
1737 Lisp_Object is is the correct type before using the @code{X@var{TYPE}}
1738 macros. This is especially important in the case of lists. Use
1739 @code{XCAR} and @code{XCDR} if a Lisp_Object is certainly a cons cell,
1740 else use @code{Fcar()} and @code{Fcdr()}. Trust other C code, but not
1741 Lisp code. On the other hand, if XEmacs has an internal logic error,
1742 it's better to crash immediately, so sprinkle ``unreachable''
1743 @code{abort()}s liberally about the source code.
1745 @node Rules When Writing New C Code, A Summary of the Various XEmacs Modules, How Lisp Objects Are Represented in C, Top
1746 @chapter Rules When Writing New C Code
1748 The XEmacs C Code is extremely complex and intricate, and there are many
1749 rules that are more or less consistently followed throughout the code.
1750 Many of these rules are not obvious, so they are explained here. It is
1751 of the utmost importance that you follow them. If you don't, you may
1752 get something that appears to work, but which will crash in odd
1753 situations, often in code far away from where the actual breakage is.
1756 * General Coding Rules::
1757 * Writing Lisp Primitives::
1758 * Adding Global Lisp Variables::
1760 * Techniques for XEmacs Developers::
1763 @node General Coding Rules
1764 @section General Coding Rules
1766 The C code is actually written in a dialect of C called @dfn{Clean C},
1767 meaning that it can be compiled, mostly warning-free, with either a C or
1768 C++ compiler. Coding in Clean C has several advantages over plain C.
1769 C++ compilers are more nit-picking, and a number of coding errors have
1770 been found by compiling with C++. The ability to use both C and C++
1771 tools means that a greater variety of development tools are available to
1774 Almost every module contains a @code{syms_of_*()} function and a
1775 @code{vars_of_*()} function. The former declares any Lisp primitives
1776 you have defined and defines any symbols you will be using. The latter
1777 declares any global Lisp variables you have added and initializes global
1778 C variables in the module. For each such function, declare it in
1779 @file{symsinit.h} and make sure it's called in the appropriate place in
1780 @file{emacs.c}. @strong{Important}: There are stringent requirements on
1781 exactly what can go into these functions. See the comment in
1782 @file{emacs.c}. The reason for this is to avoid obscure unwanted
1783 interactions during initialization. If you don't follow these rules,
1784 you'll be sorry! If you want to do anything that isn't allowed, create
1785 a @code{complex_vars_of_*()} function for it. Doing this is tricky,
1786 though: You have to make sure your function is called at the right time
1787 so that all the initialization dependencies work out.
1789 Every module includes @file{<config.h>} (angle brackets so that
1790 @samp{--srcdir} works correctly; @file{config.h} may or may not be in
1791 the same directory as the C sources) and @file{lisp.h}. @file{config.h}
1792 must always be included before any other header files (including
1793 system header files) to ensure that certain tricks played by various
1794 @file{s/} and @file{m/} files work out correctly.
1796 @strong{All global and static variables that are to be modifiable must
1797 be declared uninitialized.} This means that you may not use the
1798 ``declare with initializer'' form for these variables, such as @code{int
1799 some_variable = 0;}. The reason for this has to do with some kludges
1800 done during the dumping process: If possible, the initialized data
1801 segment is re-mapped so that it becomes part of the (unmodifiable) code
1802 segment in the dumped executable. This allows this memory to be shared
1803 among multiple running XEmacs processes. XEmacs is careful to place as
1804 much constant data as possible into initialized variables (in
1805 particular, into what's called the @dfn{pure space} -- see below) during
1806 the @file{temacs} phase.
1808 @cindex copy-on-write
1809 @strong{Please note:} This kludge only works on a few systems nowadays,
1810 and is rapidly becoming irrelevant because most modern operating systems
1811 provide @dfn{copy-on-write} semantics. All data is initially shared
1812 between processes, and a private copy is automatically made (on a
1813 page-by-page basis) when a process first attempts to write to a page of
1816 Formerly, there was a requirement that static variables not be declared
1817 inside of functions. This had to do with another hack along the same
1818 vein as what was just described: old USG systems put statically-declared
1819 variables in the initialized data space, so those header files had a
1820 @code{#define static} declaration. (That way, the data-segment remapping
1821 described above could still work.) This fails badly on static variables
1822 inside of functions, which suddenly become automatic variables;
1823 therefore, you weren't supposed to have any of them. This awful kludge
1824 has been removed in XEmacs because
1828 almost all of the systems that used this kludge ended up having
1829 to disable the data-segment remapping anyway;
1831 the only systems that didn't were extremely outdated ones;
1833 this hack completely messed up inline functions.
1836 The C source code makes heavy use of C preprocessor macros. One popular
1840 #define FOO(var, value) do @{ \
1841 Lisp_Object FOO_value = (value); \
1842 ... /* compute using FOO_value */ \
1847 The @code{do @{...@} while (0)} is a standard trick to allow FOO to have
1848 statement semantics, so that it can safely be used within an @code{if}
1849 statement in C, for example. Multiple evaluation is prevented by
1850 copying a supplied argument into a local variable, so that
1851 @code{FOO(var,fun(1))} only calls @code{fun} once.
1853 Lisp lists are popular data structures in the C code as well as in
1854 Elisp. There are two sets of macros that iterate over lists.
1855 @code{EXTERNAL_LIST_LOOP_@var{n}} should be used when the list has been
1856 supplied by the user, and cannot be trusted to be acyclic and
1857 nil-terminated. A @code{malformed-list} or @code{circular-list} error
1858 will be generated if the list being iterated over is not entirely
1859 kosher. @code{LIST_LOOP_@var{n}}, on the other hand, is faster and less
1860 safe, and can be used only on trusted lists.
1862 Related macros are @code{GET_EXTERNAL_LIST_LENGTH} and
1863 @code{GET_LIST_LENGTH}, which calculate the length of a list, and in the
1864 case of @code{GET_EXTERNAL_LIST_LENGTH}, validating the properness of
1865 the list. The macros @code{EXTERNAL_LIST_LOOP_DELETE_IF} and
1866 @code{LIST_LOOP_DELETE_IF} delete elements from a lisp list satisfying some
1869 @node Writing Lisp Primitives
1870 @section Writing Lisp Primitives
1872 Lisp primitives are Lisp functions implemented in C. The details of
1873 interfacing the C function so that Lisp can call it are handled by a few
1874 C macros. The only way to really understand how to write new C code is
1875 to read the source, but we can explain some things here.
1877 An example of a special form is the definition of @code{prog1}, from
1878 @file{eval.c}. (An ordinary function would have the same general
1881 @cindex garbage collection protection
1884 DEFUN ("prog1", Fprog1, 1, UNEVALLED, 0, /*
1885 Similar to `progn', but the value of the first form is returned.
1886 \(prog1 FIRST BODY...): All the arguments are evaluated sequentially.
1887 The value of FIRST is saved during evaluation of the remaining args,
1888 whose values are discarded.
1892 /* This function can GC */
1893 REGISTER Lisp_Object val, form, tail;
1894 struct gcpro gcpro1;
1896 val = Feval (XCAR (args));
1900 LIST_LOOP_3 (form, XCDR (args), tail)
1909 Let's start with a precise explanation of the arguments to the
1910 @code{DEFUN} macro. Here is a template for them:
1914 DEFUN (@var{lname}, @var{fname}, @var{min_args}, @var{max_args}, @var{interactive}, /*
1923 This string is the name of the Lisp symbol to define as the function
1924 name; in the example above, it is @code{"prog1"}.
1927 This is the C function name for this function. This is the name that is
1928 used in C code for calling the function. The name is, by convention,
1929 @samp{F} prepended to the Lisp name, with all dashes (@samp{-}) in the
1930 Lisp name changed to underscores. Thus, to call this function from C
1931 code, call @code{Fprog1}. Remember that the arguments are of type
1932 @code{Lisp_Object}; various macros and functions for creating values of
1933 type @code{Lisp_Object} are declared in the file @file{lisp.h}.
1935 Primitives whose names are special characters (e.g. @code{+} or
1936 @code{<}) are named by spelling out, in some fashion, the special
1937 character: e.g. @code{Fplus()} or @code{Flss()}. Primitives whose names
1938 begin with normal alphanumeric characters but also contain special
1939 characters are spelled out in some creative way, e.g. @code{let*}
1940 becomes @code{FletX()}.
1942 Each function also has an associated structure that holds the data for
1943 the subr object that represents the function in Lisp. This structure
1944 conveys the Lisp symbol name to the initialization routine that will
1945 create the symbol and store the subr object as its definition. The C
1946 variable name of this structure is always @samp{S} prepended to the
1947 @var{fname}. You hardly ever need to be aware of the existence of this
1948 structure, since @code{DEFUN} plus @code{DEFSUBR} takes care of all the
1952 This is the minimum number of arguments that the function requires. The
1953 function @code{prog1} allows a minimum of one argument.
1956 This is the maximum number of arguments that the function accepts, if
1957 there is a fixed maximum. Alternatively, it can be @code{UNEVALLED},
1958 indicating a special form that receives unevaluated arguments, or
1959 @code{MANY}, indicating an unlimited number of evaluated arguments (the
1960 C equivalent of @code{&rest}). Both @code{UNEVALLED} and @code{MANY}
1961 are macros. If @var{max_args} is a number, it may not be less than
1962 @var{min_args} and it may not be greater than 8. (If you need to add a
1963 function with more than 8 arguments, use the @code{MANY} form. Resist
1964 the urge to edit the definition of @code{DEFUN} in @file{lisp.h}. If
1965 you do it anyways, make sure to also add another clause to the switch
1966 statement in @code{primitive_funcall().})
1969 This is an interactive specification, a string such as might be used as
1970 the argument of @code{interactive} in a Lisp function. In the case of
1971 @code{prog1}, it is 0 (a null pointer), indicating that @code{prog1}
1972 cannot be called interactively. A value of @code{""} indicates a
1973 function that should receive no arguments when called interactively.
1976 This is the documentation string. It is written just like a
1977 documentation string for a function defined in Lisp; in particular, the
1978 first line should be a single sentence. Note how the documentation
1979 string is enclosed in a comment, none of the documentation is placed on
1980 the same lines as the comment-start and comment-end characters, and the
1981 comment-start characters are on the same line as the interactive
1982 specification. @file{make-docfile}, which scans the C files for
1983 documentation strings, is very particular about what it looks for, and
1984 will not properly extract the doc string if it's not in this exact format.
1986 In order to make both @file{etags} and @file{make-docfile} happy, make
1987 sure that the @code{DEFUN} line contains the @var{lname} and
1988 @var{fname}, and that the comment-start characters for the doc string
1989 are on the same line as the interactive specification, and put a newline
1990 directly after them (and before the comment-end characters).
1993 This is the comma-separated list of arguments to the C function. For a
1994 function with a fixed maximum number of arguments, provide a C argument
1995 for each Lisp argument. In this case, unlike regular C functions, the
1996 types of the arguments are not declared; they are simply always of type
1999 The names of the C arguments will be used as the names of the arguments
2000 to the Lisp primitive as displayed in its documentation, modulo the same
2001 concerns described above for @code{F...} names (in particular,
2002 underscores in the C arguments become dashes in the Lisp arguments).
2004 There is one additional kludge: A trailing `_' on the C argument is
2005 discarded when forming the Lisp argument. This allows C language
2006 reserved words (like @code{default}) or global symbols (like
2007 @code{dirname}) to be used as argument names without compiler warnings
2010 A Lisp function with @w{@var{max_args} = @code{UNEVALLED}} is a
2011 @w{@dfn{special form}}; its arguments are not evaluated. Instead it
2012 receives one argument of type @code{Lisp_Object}, a (Lisp) list of the
2013 unevaluated arguments, conventionally named @code{(args)}.
2015 When a Lisp function has no upper limit on the number of arguments,
2016 specify @w{@var{max_args} = @code{MANY}}. In this case its implementation in
2017 C actually receives exactly two arguments: the number of Lisp arguments
2018 (an @code{int}) and the address of a block containing their values (a
2019 @w{@code{Lisp_Object *}}). In this case only are the C types specified
2020 in the @var{arglist}: @w{@code{(int nargs, Lisp_Object *args)}}.
2024 Within the function @code{Fprog1} itself, note the use of the macros
2025 @code{GCPRO1} and @code{UNGCPRO}. @code{GCPRO1} is used to ``protect''
2026 a variable from garbage collection---to inform the garbage collector
2027 that it must look in that variable and regard the object pointed at by
2028 its contents as an accessible object. This is necessary whenever you
2029 call @code{Feval} or anything that can directly or indirectly call
2030 @code{Feval} (this includes the @code{QUIT} macro!). At such a time,
2031 any Lisp object that you intend to refer to again must be protected
2032 somehow. @code{UNGCPRO} cancels the protection of the variables that
2033 are protected in the current function. It is necessary to do this
2036 The macro @code{GCPRO1} protects just one local variable. If you want
2037 to protect two, use @code{GCPRO2} instead; repeating @code{GCPRO1} will
2038 not work. Macros @code{GCPRO3} and @code{GCPRO4} also exist.
2040 These macros implicitly use local variables such as @code{gcpro1}; you
2041 must declare these explicitly, with type @code{struct gcpro}. Thus, if
2042 you use @code{GCPRO2}, you must declare @code{gcpro1} and @code{gcpro2}.
2044 @cindex caller-protects (@code{GCPRO} rule)
2045 Note also that the general rule is @dfn{caller-protects}; i.e. you are
2046 only responsible for protecting those Lisp objects that you create. Any
2047 objects passed to you as arguments should have been protected by whoever
2048 created them, so you don't in general have to protect them.
2050 In particular, the arguments to any Lisp primitive are always
2051 automatically @code{GCPRO}ed, when called ``normally'' from Lisp code or
2052 bytecode. So only a few Lisp primitives that are called frequently from
2053 C code, such as @code{Fprogn} protect their arguments as a service to
2054 their caller. You don't need to protect your arguments when writing a
2057 @code{GCPRO}ing is perhaps the trickiest and most error-prone part of
2058 XEmacs coding. It is @strong{extremely} important that you get this
2059 right and use a great deal of discipline when writing this code.
2060 @xref{GCPROing, ,@code{GCPRO}ing}, for full details on how to do this.
2062 What @code{DEFUN} actually does is declare a global structure of type
2063 @code{Lisp_Subr} whose name begins with capital @samp{SF} and which
2064 contains information about the primitive (e.g. a pointer to the
2065 function, its minimum and maximum allowed arguments, a string describing
2066 its Lisp name); @code{DEFUN} then begins a normal C function declaration
2067 using the @code{F...} name. The Lisp subr object that is the function
2068 definition of a primitive (i.e. the object in the function slot of the
2069 symbol that names the primitive) actually points to this @samp{SF}
2070 structure; when @code{Feval} encounters a subr, it looks in the
2071 structure to find out how to call the C function.
2073 Defining the C function is not enough to make a Lisp primitive
2074 available; you must also create the Lisp symbol for the primitive (the
2075 symbol is @dfn{interned}; @pxref{Obarrays}) and store a suitable subr
2076 object in its function cell. (If you don't do this, the primitive won't
2077 be seen by Lisp code.) The code looks like this:
2080 DEFSUBR (@var{fname});
2084 Here @var{fname} is the same name you used as the second argument to
2087 This call to @code{DEFSUBR} should go in the @code{syms_of_*()} function
2088 at the end of the module. If no such function exists, create it and
2089 make sure to also declare it in @file{symsinit.h} and call it from the
2090 appropriate spot in @code{main()}. @xref{General Coding Rules}.
2092 Note that C code cannot call functions by name unless they are defined
2093 in C. The way to call a function written in Lisp from C is to use
2094 @code{Ffuncall}, which embodies the Lisp function @code{funcall}. Since
2095 the Lisp function @code{funcall} accepts an unlimited number of
2096 arguments, in C it takes two: the number of Lisp-level arguments, and a
2097 one-dimensional array containing their values. The first Lisp-level
2098 argument is the Lisp function to call, and the rest are the arguments to
2099 pass to it. Since @code{Ffuncall} can call the evaluator, you must
2100 protect pointers from garbage collection around the call to
2101 @code{Ffuncall}. (However, @code{Ffuncall} explicitly protects all of
2102 its parameters, so you don't have to protect any pointers passed as
2105 The C functions @code{call0}, @code{call1}, @code{call2}, and so on,
2106 provide handy ways to call a Lisp function conveniently with a fixed
2107 number of arguments. They work by calling @code{Ffuncall}.
2109 @file{eval.c} is a very good file to look through for examples;
2110 @file{lisp.h} contains the definitions for important macros and
2113 @node Adding Global Lisp Variables
2114 @section Adding Global Lisp Variables
2116 Global variables whose names begin with @samp{Q} are constants whose
2117 value is a symbol of a particular name. The name of the variable should
2118 be derived from the name of the symbol using the same rules as for Lisp
2119 primitives. These variables are initialized using a call to
2120 @code{defsymbol()} in the @code{syms_of_*()} function. (This call
2121 interns a symbol, sets the C variable to the resulting Lisp object, and
2122 calls @code{staticpro()} on the C variable to tell the
2123 garbage-collection mechanism about this variable. What
2124 @code{staticpro()} does is add a pointer to the variable to a large
2125 global array; when garbage-collection happens, all pointers listed in
2126 the array are used as starting points for marking Lisp objects. This is
2127 important because it's quite possible that the only current reference to
2128 the object is the C variable. In the case of symbols, the
2129 @code{staticpro()} doesn't matter all that much because the symbol is
2130 contained in @code{obarray}, which is itself @code{staticpro()}ed.
2131 However, it's possible that a naughty user could do something like
2132 uninterning the symbol out of @code{obarray} or even setting
2133 @code{obarray} to a different value [although this is likely to make
2136 @strong{Please note:} It is potentially deadly if you declare a
2137 @samp{Q...} variable in two different modules. The two calls to
2138 @code{defsymbol()} are no problem, but some linkers will complain about
2139 multiply-defined symbols. The most insidious aspect of this is that
2140 often the link will succeed anyway, but then the resulting executable
2141 will sometimes crash in obscure ways during certain operations! To
2142 avoid this problem, declare any symbols with common names (such as
2143 @code{text}) that are not obviously associated with this particular
2144 module in the module @file{general.c}.
2146 Global variables whose names begin with @samp{V} are variables that
2147 contain Lisp objects. The convention here is that all global variables
2148 of type @code{Lisp_Object} begin with @samp{V}, and all others don't
2149 (including integer and boolean variables that have Lisp
2150 equivalents). Most of the time, these variables have equivalents in
2151 Lisp, but some don't. Those that do are declared this way by a call to
2152 @code{DEFVAR_LISP()} in the @code{vars_of_*()} initializer for the
2153 module. What this does is create a special @dfn{symbol-value-forward}
2154 Lisp object that contains a pointer to the C variable, intern a symbol
2155 whose name is as specified in the call to @code{DEFVAR_LISP()}, and set
2156 its value to the symbol-value-forward Lisp object; it also calls
2157 @code{staticpro()} on the C variable to tell the garbage-collection
2158 mechanism about the variable. When @code{eval} (or actually
2159 @code{symbol-value}) encounters this special object in the process of
2160 retrieving a variable's value, it follows the indirection to the C
2161 variable and gets its value. @code{setq} does similar things so that
2162 the C variable gets changed.
2164 Whether or not you @code{DEFVAR_LISP()} a variable, you need to
2165 initialize it in the @code{vars_of_*()} function; otherwise it will end
2166 up as all zeroes, which is the integer 0 (@emph{not} @code{nil}), and
2167 this is probably not what you want. Also, if the variable is not
2168 @code{DEFVAR_LISP()}ed, @strong{you must call} @code{staticpro()} on the
2169 C variable in the @code{vars_of_*()} function. Otherwise, the
2170 garbage-collection mechanism won't know that the object in this variable
2171 is in use, and will happily collect it and reuse its storage for another
2172 Lisp object, and you will be the one who's unhappy when you can't figure
2173 out how your variable got overwritten.
2175 @node Coding for Mule
2176 @section Coding for Mule
2177 @cindex Coding for Mule
2179 Although Mule support is not compiled by default in XEmacs, many people
2180 are using it, and we consider it crucial that new code works correctly
2181 with multibyte characters. This is not hard; it is only a matter of
2182 following several simple user-interface guidelines. Even if you never
2183 compile with Mule, with a little practice you will find it quite easy
2184 to code Mule-correctly.
2186 Note that these guidelines are not necessarily tied to the current Mule
2187 implementation; they are also a good idea to follow on the grounds of
2188 code generalization for future I18N work.
2191 * Character-Related Data Types::
2192 * Working With Character and Byte Positions::
2193 * Conversion to and from External Data::
2194 * General Guidelines for Writing Mule-Aware Code::
2195 * An Example of Mule-Aware Code::
2198 @node Character-Related Data Types
2199 @subsection Character-Related Data Types
2201 First, let's review the basic character-related datatypes used by
2202 XEmacs. Note that the separate @code{typedef}s are not mandatory in the
2203 current implementation (all of them boil down to @code{unsigned char} or
2204 @code{int}), but they improve clarity of code a great deal, because one
2205 glance at the declaration can tell the intended use of the variable.
2210 An @code{Emchar} holds a single Emacs character.
2212 Obviously, the equality between characters and bytes is lost in the Mule
2213 world. Characters can be represented by one or more bytes in the
2214 buffer, and @code{Emchar} is the C type large enough to hold any
2217 Without Mule support, an @code{Emchar} is equivalent to an
2218 @code{unsigned char}.
2222 The data representing the text in a buffer or string is logically a set
2225 XEmacs does not work with character formats all the time; when reading
2226 characters from the outside, it decodes them to an internal format, and
2227 likewise encodes them when writing. @code{Bufbyte} (in fact
2228 @code{unsigned char}) is the basic unit of XEmacs internal buffers and
2231 One character can correspond to one or more @code{Bufbyte}s. In the
2232 current implementation, an ASCII character is represented by the same
2233 @code{Bufbyte}, and extended characters are represented by a sequence of
2236 Without Mule support, a @code{Bufbyte} is equivalent to an
2243 A @code{Bufpos} represents a character position in a buffer or string.
2244 A @code{Charcount} represents a number (count) of characters.
2245 Logically, subtracting two @code{Bufpos} values yields a
2246 @code{Charcount} value. Although all of these are @code{typedef}ed to
2247 @code{int}, we use them in preference to @code{int} to make it clear
2248 what sort of position is being used.
2250 @code{Bufpos} and @code{Charcount} values are the only ones that are
2251 ever visible to Lisp.
2257 A @code{Bytind} represents a byte position in a buffer or string. A
2258 @code{Bytecount} represents the distance between two positions in bytes.
2259 The relationship between @code{Bytind} and @code{Bytecount} is the same
2260 as the relationship between @code{Bufpos} and @code{Charcount}.
2266 When dealing with the outside world, XEmacs works with @code{Extbyte}s,
2267 which are equivalent to @code{unsigned char}. Obviously, an
2268 @code{Extcount} is the distance between two @code{Extbyte}s. Extbytes
2269 and Extcounts are not all that frequent in XEmacs code.
2272 @node Working With Character and Byte Positions
2273 @subsection Working With Character and Byte Positions
2275 Now that we have defined the basic character-related types, we can look
2276 at the macros and functions designed for work with them and for
2277 conversion between them. Most of these macros are defined in
2278 @file{buffer.h}, and we don't discuss all of them here, but only the
2279 most important ones. Examining the existing code is the best way to
2283 @item MAX_EMCHAR_LEN
2284 @cindex MAX_EMCHAR_LEN
2285 This preprocessor constant is the maximum number of buffer bytes per
2286 Emacs character, i.e. the byte length of an @code{Emchar}. It is useful
2287 when allocating temporary strings to keep a known number of characters.
2296 /* Allocate place for @var{cclen} characters. */
2297 Bufbyte *buf = (Bufbyte *)alloca (cclen * MAX_EMCHAR_LEN);
2302 If you followed the previous section, you can guess that, logically,
2303 multiplying a @code{Charcount} value with @code{MAX_EMCHAR_LEN} produces
2304 a @code{Bytecount} value.
2306 In the current Mule implementation, @code{MAX_EMCHAR_LEN} equals 4.
2307 Without Mule, it is 1.
2309 @item charptr_emchar
2310 @itemx set_charptr_emchar
2311 @cindex charptr_emchar
2312 @cindex set_charptr_emchar
2313 The @code{charptr_emchar} macro takes a @code{Bufbyte} pointer and
2314 returns the @code{Emchar} stored at that position. If it were a
2315 function, its prototype would be:
2318 Emchar charptr_emchar (Bufbyte *p);
2321 @code{set_charptr_emchar} stores an @code{Emchar} to the specified byte
2322 position. It returns the number of bytes stored:
2325 Bytecount set_charptr_emchar (Bufbyte *p, Emchar c);
2328 It is important to note that @code{set_charptr_emchar} is safe only for
2329 appending a character at the end of a buffer, not for overwriting a
2330 character in the middle. This is because the width of characters
2331 varies, and @code{set_charptr_emchar} cannot resize the string if it
2332 writes, say, a two-byte character where a single-byte character used to
2335 A typical use of @code{set_charptr_emchar} can be demonstrated by this
2336 example, which copies characters from buffer @var{buf} to a temporary
2343 for (pos = beg; pos < end; pos++)
2345 Emchar c = BUF_FETCH_CHAR (buf, pos);
2346 p += set_charptr_emchar (buf, c);
2352 Note how @code{set_charptr_emchar} is used to store the @code{Emchar}
2353 and increment the counter, at the same time.
2359 These two macros increment and decrement a @code{Bufbyte} pointer,
2360 respectively. They will adjust the pointer by the appropriate number of
2361 bytes according to the byte length of the character stored there. Both
2362 macros assume that the memory address is located at the beginning of a
2365 Without Mule support, @code{INC_CHARPTR (p)} and @code{DEC_CHARPTR (p)}
2366 simply expand to @code{p++} and @code{p--}, respectively.
2368 @item bytecount_to_charcount
2369 @cindex bytecount_to_charcount
2370 Given a pointer to a text string and a length in bytes, return the
2371 equivalent length in characters.
2374 Charcount bytecount_to_charcount (Bufbyte *p, Bytecount bc);
2377 @item charcount_to_bytecount
2378 @cindex charcount_to_bytecount
2379 Given a pointer to a text string and a length in characters, return the
2380 equivalent length in bytes.
2383 Bytecount charcount_to_bytecount (Bufbyte *p, Charcount cc);
2386 @item charptr_n_addr
2387 @cindex charptr_n_addr
2388 Return a pointer to the beginning of the character offset @var{cc} (in
2389 characters) from @var{p}.
2392 Bufbyte *charptr_n_addr (Bufbyte *p, Charcount cc);
2396 @node Conversion to and from External Data
2397 @subsection Conversion to and from External Data
2399 When an external function, such as a C library function, returns a
2400 @code{char} pointer, you should almost never treat it as @code{Bufbyte}.
2401 This is because these returned strings may contain 8bit characters which
2402 can be misinterpreted by XEmacs, and cause a crash. Likewise, when
2403 exporting a piece of internal text to the outside world, you should
2404 always convert it to an appropriate external encoding, lest the internal
2405 stuff (such as the infamous \201 characters) leak out.
2407 The interface to conversion between the internal and external
2408 representations of text are the numerous conversion macros defined in
2409 @file{buffer.h}. Before looking at them, we'll look at the external
2410 formats supported by these macros.
2412 Currently meaningful formats are @code{FORMAT_BINARY},
2413 @code{FORMAT_FILENAME}, @code{FORMAT_OS}, and @code{FORMAT_CTEXT}. Here
2414 is a description of these.
2418 Binary format. This is the simplest format and is what we use in the
2419 absence of a more appropriate format. This converts according to the
2420 @code{binary} coding system:
2424 On input, bytes 0--255 are converted into characters 0--255.
2426 On output, characters 0--255 are converted into bytes 0--255 and other
2427 characters are converted into `X'.
2430 @item FORMAT_FILENAME
2431 Format used for filenames. In the original Mule, this is user-definable
2432 with the @code{pathname-coding-system} variable. For the moment, we
2433 just use the @code{binary} coding system.
2436 Format used for the external Unix environment---@code{argv[]}, stuff
2437 from @code{getenv()}, stuff from the @file{/etc/passwd} file, etc.
2439 Perhaps should be the same as FORMAT_FILENAME.
2442 Compound--text format. This is the standard X format used for data
2443 stored in properties, selections, and the like. This is an 8-bit
2444 no-lock-shift ISO2022 coding system.
2447 The macros to convert between these formats and the internal format, and
2451 @item GET_CHARPTR_INT_DATA_ALLOCA
2452 @itemx GET_CHARPTR_EXT_DATA_ALLOCA
2453 These two are the most basic conversion macros.
2454 @code{GET_CHARPTR_INT_DATA_ALLOCA} converts external data to internal
2455 format, and @code{GET_CHARPTR_EXT_DATA_ALLOCA} converts the other way
2456 around. The arguments each of these receives are @var{ptr} (pointer to
2457 the text in external format), @var{len} (length of texts in bytes),
2458 @var{fmt} (format of the external text), @var{ptr_out} (lvalue to which
2459 new text should be copied), and @var{len_out} (lvalue which will be
2460 assigned the length of the internal text in bytes). The resulting text
2461 is stored to a stack-allocated buffer. If the text doesn't need
2462 changing, these macros will do nothing, except for setting
2465 The macros above take many arguments which makes them unwieldy. For
2466 this reason, a number of convenience macros are defined with obvious
2467 functionality, but accepting less arguments. The general rule is that
2468 macros with @samp{INT} in their name convert text to internal Emacs
2469 representation, whereas the @samp{EXT} macros convert to external
2472 @item GET_C_CHARPTR_INT_DATA_ALLOCA
2473 @itemx GET_C_CHARPTR_EXT_DATA_ALLOCA
2474 As their names imply, these macros work on C char pointers, which are
2475 zero-terminated, and thus do not need @var{len} or @var{len_out}
2478 @item GET_STRING_EXT_DATA_ALLOCA
2479 @itemx GET_C_STRING_EXT_DATA_ALLOCA
2480 These two macros convert a Lisp string into an external representation.
2481 The difference between them is that @code{GET_STRING_EXT_DATA_ALLOCA}
2482 stores its output to a generic string, providing @var{len_out}, the
2483 length of the resulting external string. On the other hand,
2484 @code{GET_C_STRING_EXT_DATA_ALLOCA} assumes that the caller will be
2485 satisfied with output string being zero-terminated.
2487 Note that for Lisp strings only one conversion direction makes sense.
2489 @item GET_C_CHARPTR_EXT_BINARY_DATA_ALLOCA
2490 @itemx GET_CHARPTR_EXT_BINARY_DATA_ALLOCA
2491 @itemx GET_STRING_BINARY_DATA_ALLOCA
2492 @itemx GET_C_STRING_BINARY_DATA_ALLOCA
2493 @itemx GET_C_CHARPTR_EXT_FILENAME_DATA_ALLOCA
2495 These macros convert internal text to a specific external
2496 representation, with the external format being encoded into the name of
2497 the macro. Note that the @code{GET_STRING_...} and
2498 @code{GET_C_STRING...} macros lack the @samp{EXT} tag, because they
2499 only make sense in that direction.
2501 @item GET_C_CHARPTR_INT_BINARY_DATA_ALLOCA
2502 @itemx GET_CHARPTR_INT_BINARY_DATA_ALLOCA
2503 @itemx GET_C_CHARPTR_INT_FILENAME_DATA_ALLOCA
2505 These macros convert external text of a specific format to its internal
2506 representation, with the external format being incoded into the name of
2510 @node General Guidelines for Writing Mule-Aware Code
2511 @subsection General Guidelines for Writing Mule-Aware Code
2513 This section contains some general guidance on how to write Mule-aware
2514 code, as well as some pitfalls you should avoid.
2517 @item Never use @code{char} and @code{char *}.
2518 In XEmacs, the use of @code{char} and @code{char *} is almost always a
2519 mistake. If you want to manipulate an Emacs character from ``C'', use
2520 @code{Emchar}. If you want to examine a specific octet in the internal
2521 format, use @code{Bufbyte}. If you want a Lisp-visible character, use a
2522 @code{Lisp_Object} and @code{make_char}. If you want a pointer to move
2523 through the internal text, use @code{Bufbyte *}. Also note that you
2524 almost certainly do not need @code{Emchar *}.
2526 @item Be careful not to confuse @code{Charcount}, @code{Bytecount}, and @code{Bufpos}.
2527 The whole point of using different types is to avoid confusion about the
2528 use of certain variables. Lest this effect be nullified, you need to be
2529 careful about using the right types.
2531 @item Always convert external data
2532 It is extremely important to always convert external data, because
2533 XEmacs can crash if unexpected 8bit sequences are copied to its internal
2536 This means that when a system function, such as @code{readdir}, returns
2537 a string, you need to convert it using one of the conversion macros
2538 described in the previous chapter, before passing it further to Lisp.
2539 In the case of @code{readdir}, you would use the
2540 @code{GET_C_CHARPTR_INT_FILENAME_DATA_ALLOCA} macro.
2542 Also note that many internal functions, such as @code{make_string},
2543 accept Bufbytes, which removes the need for them to convert the data
2544 they receive. This increases efficiency because that way external data
2545 needs to be decoded only once, when it is read. After that, it is
2546 passed around in internal format.
2549 @node An Example of Mule-Aware Code
2550 @subsection An Example of Mule-Aware Code
2552 As an example of Mule-aware code, we shall will analyze the
2553 @code{string} function, which conses up a Lisp string from the character
2554 arguments it receives. Here is the definition, pasted from
2559 DEFUN ("string", Fstring, 0, MANY, 0, /*
2560 Concatenate all the argument characters and make the result a string.
2562 (int nargs, Lisp_Object *args))
2564 Bufbyte *storage = alloca_array (Bufbyte, nargs * MAX_EMCHAR_LEN);
2565 Bufbyte *p = storage;
2567 for (; nargs; nargs--, args++)
2569 Lisp_Object lisp_char = *args;
2570 CHECK_CHAR_COERCE_INT (lisp_char);
2571 p += set_charptr_emchar (p, XCHAR (lisp_char));
2573 return make_string (storage, p - storage);
2578 Now we can analyze the source line by line.
2580 Obviously, string will be as long as there are arguments to the
2581 function. This is why we allocate @code{MAX_EMCHAR_LEN} * @var{nargs}
2582 bytes on the stack, i.e. the worst-case number of bytes for @var{nargs}
2583 @code{Emchar}s to fit in the string.
2585 Then, the loop checks that each element is a character, converting
2586 integers in the process. Like many other functions in XEmacs, this
2587 function silently accepts integers where characters are expected, for
2588 historical and compatibility reasons. Unless you know what you are
2589 doing, @code{CHECK_CHAR} will also suffice. @code{XCHAR (lisp_char)}
2590 extracts the @code{Emchar} from the @code{Lisp_Object}, and
2591 @code{set_charptr_emchar} stores it to storage, increasing @code{p} in
2594 Other instructive examples of correct coding under Mule can be found all
2595 over the XEmacs code. For starters, I recommend
2596 @code{Fnormalize_menu_item_name} in @file{menubar.c}. After you have
2597 understood this section of the manual and studied the examples, you can
2598 proceed writing new Mule-aware code.
2600 @node Techniques for XEmacs Developers
2601 @section Techniques for XEmacs Developers
2603 To make a quantified XEmacs, do: @code{make quantmacs}.
2605 You simply can't dump Quantified and Purified images. Run the image
2606 like so: @code{quantmacs -batch -l loadup.el run-temacs @var{xemacs-args...}}.
2608 Before you go through the trouble, are you compiling with all
2609 debugging and error-checking off? If not try that first. Be warned
2610 that while Quantify is directly responsible for quite a few
2611 optimizations which have been made to XEmacs, doing a run which
2612 generates results which can be acted upon is not necessarily a trivial
2615 Also, if you're still willing to do some runs make sure you configure
2616 with the @samp{--quantify} flag. That will keep Quantify from starting
2617 to record data until after the loadup is completed and will shut off
2618 recording right before it shuts down (which generates enough bogus data
2619 to throw most results off). It also enables three additional elisp
2620 commands: @code{quantify-start-recording-data},
2621 @code{quantify-stop-recording-data} and @code{quantify-clear-data}.
2623 If you want to make XEmacs faster, target your favorite slow benchmark,
2624 run a profiler like Quantify, @code{gprof}, or @code{tcov}, and figure
2625 out where the cycles are going. Specific projects:
2629 Make the garbage collector faster. Figure out how to write an
2630 incremental garbage collector.
2632 Write a compiler that takes bytecode and spits out C code.
2633 Unfortunately, you will then need a C compiler and a more fully
2634 developed module system.
2638 Speed up syntax highlighting. Maybe moving some of the syntax
2639 highlighting capabilities into C would make a difference.
2641 Implement tail recursion in Emacs Lisp (hard!).
2644 Unfortunately, Emacs Lisp is slow, and is going to stay slow. Function
2645 calls in elisp are especially expensive. Iterating over a long list is
2646 going to be 30 times faster implemented in C than in Elisp.
2648 To get started debugging XEmacs, take a look at the @file{gdbinit} and
2649 @file{dbxrc} files in the @file{src} directory.
2650 @xref{Q2.1.15 - How to Debug an XEmacs problem with a debugger,,,
2651 xemacs-faq, XEmacs FAQ}.
2653 After making source code changes, run @code{make check} to ensure that
2654 you haven't introduced any regressions. If you're feeling ambitious,
2655 you can try to improve the test suite in @file{tests/automated}.
2657 Here are things to know when you create a new source file:
2661 All @file{.c} files should @code{#include <config.h>} first. Almost all
2662 @file{.c} files should @code{#include "lisp.h"} second.
2665 Generated header files should be included using the @code{#include <...>} syntax,
2666 not the @code{#include "..."} syntax. The generated headers are:
2668 @file{config.h puresize-adjust.h sheap-adjust.h paths.h Emacs.ad.h}
2670 The basic rule is that you should assume builds using @code{--srcdir}
2671 and the @code{#include <...>} syntax needs to be used when the
2672 to-be-included generated file is in a potentially different directory
2673 @emph{at compile time}. The non-obvious C rule is that @code{#include "..."}
2674 means to search for the included file in the same directory as the
2675 including file, @emph{not} in the current directory.
2678 Header files should @emph{not} include @code{<config.h>} and
2679 @code{"lisp.h"}. It is the responsibility of the @file{.c} files that
2683 If the header uses @code{INLINE}, either directly or through
2684 @code{DECLARE_LRECORD}, then it must be added to @file{inline.c}'s
2688 Try compiling at least once with
2691 gcc --with-mule --with-union-type --error-checking=all
2695 Did I mention that you should run the test suite?
2702 @node A Summary of the Various XEmacs Modules, Allocation of Objects in XEmacs Lisp, Rules When Writing New C Code, Top
2703 @chapter A Summary of the Various XEmacs Modules
2705 This is accurate as of XEmacs 20.0.
2708 * Low-Level Modules::
2709 * Basic Lisp Modules::
2710 * Modules for Standard Editing Operations::
2711 * Editor-Level Control Flow Modules::
2712 * Modules for the Basic Displayable Lisp Objects::
2713 * Modules for other Display-Related Lisp Objects::
2714 * Modules for the Redisplay Mechanism::
2715 * Modules for Interfacing with the File System::
2716 * Modules for Other Aspects of the Lisp Interpreter and Object System::
2717 * Modules for Interfacing with the Operating System::
2718 * Modules for Interfacing with X Windows::
2719 * Modules for Internationalization::
2722 @node Low-Level Modules
2723 @section Low-Level Modules
2729 This is automatically generated from @file{config.h.in} based on the
2730 results of configure tests and user-selected optional features and
2731 contains preprocessor definitions specifying the nature of the
2732 environment in which XEmacs is being compiled.
2740 This is automatically generated from @file{paths.h.in} based on supplied
2741 configure values, and allows for non-standard installed configurations
2742 of the XEmacs directories. It's currently broken, though.
2751 @file{emacs.c} contains @code{main()} and other code that performs the most
2752 basic environment initializations and handles shutting down the XEmacs
2753 process (this includes @code{kill-emacs}, the normal way that XEmacs is
2754 exited; @code{dump-emacs}, which is used during the build process to
2755 write out the XEmacs executable; @code{run-emacs-from-temacs}, which can
2756 be used to start XEmacs directly when temacs has finished loading all
2757 the Lisp code; and emergency code to handle crashes [XEmacs tries to
2758 auto-save all files before it crashes]).
2760 Low-level code that directly interacts with the Unix signal mechanism,
2761 however, is in @file{signal.c}. Note that this code does not handle system
2762 dependencies in interfacing to signals; that is handled using the
2763 @file{syssignal.h} header file, described in section J below.
2787 These modules contain code dumping out the XEmacs executable on various
2788 different systems. (This process is highly machine-specific and
2789 requires intimate knowledge of the executable format and the memory map
2790 of the process.) Only one of these modules is actually used; this is
2791 chosen by @file{configure}.
2801 These modules are used in conjunction with the dump mechanism. On some
2802 systems, an alternative version of the C startup code (the actual code
2803 that receives control from the operating system when the process is
2804 started, and which calls @code{main()}) is required so that the dumping
2805 process works properly; @file{crt0.c} provides this.
2807 @file{pre-crt0.c} and @file{lastfile.c} should be the very first and
2808 very last file linked, respectively. (Actually, this is not really true.
2809 @file{lastfile.c} should be after all Emacs modules whose initialized
2810 data should be made constant, and before all other Emacs files and all
2811 libraries. In particular, the allocation modules @file{gmalloc.c},
2812 @file{alloca.c}, etc. are normally placed past @file{lastfile.c}, and
2813 all of the files that implement Xt widget classes @emph{must} be placed
2814 after @file{lastfile.c} because they contain various structures that
2815 must be statically initialized and into which Xt writes at various
2816 times.) @file{pre-crt0.c} and @file{lastfile.c} contain exported symbols
2817 that are used to determine the start and end of XEmacs' initialized
2818 data space when dumping.
2833 These handle basic C allocation of memory. @file{alloca.c} is an emulation of
2834 the stack allocation function @code{alloca()} on machines that lack
2835 this. (XEmacs makes extensive use of @code{alloca()} in its code.)
2837 @file{gmalloc.c} and @file{malloc.c} are two implementations of the standard C
2838 functions @code{malloc()}, @code{realloc()} and @code{free()}. They are
2839 often used in place of the standard system-provided @code{malloc()}
2840 because they usually provide a much faster implementation, at the
2841 expense of additional memory use. @file{gmalloc.c} is a newer implementation
2842 that is much more memory-efficient for large allocations than @file{malloc.c},
2843 and should always be preferred if it works. (At one point, @file{gmalloc.c}
2844 didn't work on some systems where @file{malloc.c} worked; but this should be
2847 @cindex relocating allocator
2848 @file{ralloc.c} is the @dfn{relocating allocator}. It provides
2849 functions similar to @code{malloc()}, @code{realloc()} and @code{free()}
2850 that allocate memory that can be dynamically relocated in memory. The
2851 advantage of this is that allocated memory can be shuffled around to
2852 place all the free memory at the end of the heap, and the heap can then
2853 be shrunk, releasing the memory back to the operating system. The use
2854 of this can be controlled with the configure option @code{--rel-alloc};
2855 if enabled, memory allocated for buffers will be relocatable, so that if
2856 a very large file is visited and the buffer is later killed, the memory
2857 can be released to the operating system. (The disadvantage of this
2858 mechanism is that it can be very slow. On systems with the
2859 @code{mmap()} system call, the XEmacs version of @file{ralloc.c} uses
2860 this to move memory around without actually having to block-copy it,
2861 which can speed things up; but it can still cause noticeable performance
2864 @file{free-hook.c} contains some debugging functions for checking for invalid
2865 arguments to @code{free()}.
2867 @file{vm-limit.c} contains some functions that warn the user when memory is
2868 getting low. These are callback functions that are called by @file{gmalloc.c}
2869 and @file{malloc.c} at appropriate times.
2871 @file{getpagesize.h} provides a uniform interface for retrieving the size of a
2872 page in virtual memory. @file{mem-limits.h} provides a uniform interface for
2873 retrieving the total amount of available virtual memory. Both are
2874 similar in spirit to the @file{sys*.h} files described in section J, below.
2884 These implement a couple of basic C data types to facilitate memory
2885 allocation. The @code{Blocktype} type efficiently manages the
2886 allocation of fixed-size blocks by minimizing the number of times that
2887 @code{malloc()} and @code{free()} are called. It allocates memory in
2888 large chunks, subdivides the chunks into blocks of the proper size, and
2889 returns the blocks as requested. When blocks are freed, they are placed
2890 onto a linked list, so they can be efficiently reused. This data type
2891 is not much used in XEmacs currently, because it's a fairly new
2894 @cindex dynamic array
2895 The @code{Dynarr} type implements a @dfn{dynamic array}, which is
2896 similar to a standard C array but has no fixed limit on the number of
2897 elements it can contain. Dynamic arrays can hold elements of any type,
2898 and when you add a new element, the array automatically resizes itself
2899 if it isn't big enough. Dynarrs are extensively used in the redisplay
2908 This module is used in connection with inline functions (available in
2909 some compilers). Often, inline functions need to have a corresponding
2910 non-inline function that does the same thing. This module is where they
2911 reside. It contains no actual code, but defines some special flags that
2912 cause inline functions defined in header files to be rendered as actual
2913 functions. It then includes all header files that contain any inline
2914 function definitions, so that each one gets a real function equivalent.
2923 These functions provide a system for doing internal consistency checks
2924 during code development. This system is not currently used; instead the
2925 simpler @code{assert()} macro is used along with the various checks
2926 provided by the @samp{--error-check-*} configuration options.
2934 This is actually the source for a small, self-contained program
2935 used during building.
2942 This is not currently used.
2946 @node Basic Lisp Modules
2947 @section Basic Lisp Modules
2958 These are the basic header files for all XEmacs modules. Each module
2959 includes @file{lisp.h}, which brings the other header files in.
2960 @file{lisp.h} contains the definitions of the structures and extractor
2961 and constructor macros for the basic Lisp objects and various other
2962 basic definitions for the Lisp environment, as well as some
2963 general-purpose definitions (e.g. @code{min()} and @code{max()}).
2964 @file{lisp.h} includes either @file{lisp-disunion.h} or
2965 @file{lisp-union.h}, depending on whether @code{USE_UNION_TYPE} is
2966 defined. These files define the typedef of the Lisp object itself (as
2967 described above) and the low-level macros that hide the actual
2968 implementation of the Lisp object. All extractor and constructor macros
2969 for particular types of Lisp objects are defined in terms of these
2972 As a general rule, all typedefs should go into the typedefs section of
2973 @file{lisp.h} rather than into a module-specific header file even if the
2974 structure is defined elsewhere. This allows function prototypes that
2975 use the typedef to be placed into other header files. Forward structure
2976 declarations (i.e. a simple declaration like @code{struct foo;} where
2977 the structure itself is defined elsewhere) should be placed into the
2978 typedefs section as necessary.
2980 @file{lrecord.h} contains the basic structures and macros that implement
2981 all record-type Lisp objects -- i.e. all objects whose type is a field
2982 in their C structure, which includes all objects except the few most
2985 @file{lisp.h} contains prototypes for most of the exported functions in
2986 the various modules. Lisp primitives defined using @code{DEFUN} that
2987 need to be called by C code should be declared using @code{EXFUN}.
2988 Other function prototypes should be placed either into the appropriate
2989 section of @code{lisp.h}, or into a module-specific header file,
2990 depending on how general-purpose the function is and whether it has
2991 special-purpose argument types requiring definitions not in
2992 @file{lisp.h}.) All initialization functions are prototyped in
3003 The large module @file{alloc.c} implements all of the basic allocation and
3004 garbage collection for Lisp objects. The most commonly used Lisp
3005 objects are allocated in chunks, similar to the Blocktype data type
3006 described above; others are allocated in individually @code{malloc()}ed
3007 blocks. This module provides the foundation on which all other aspects
3008 of the Lisp environment sit, and is the first module initialized at
3011 Note that @file{alloc.c} provides a series of generic functions that are
3012 not dependent on any particular object type, and interfaces to
3013 particular types of objects using a standardized interface of
3014 type-specific methods. This scheme is a fundamental principle of
3015 object-oriented programming and is heavily used throughout XEmacs. The
3016 great advantage of this is that it allows for a clean separation of
3017 functionality into different modules -- new classes of Lisp objects, new
3018 event interfaces, new device types, new stream interfaces, etc. can be
3019 added transparently without affecting code anywhere else in XEmacs.
3020 Because the different subsystems are divided into general and specific
3021 code, adding a new subtype within a subsystem will in general not
3022 require changes to the generic subsystem code or affect any of the other
3023 subtypes in the subsystem; this provides a great deal of robustness to
3027 @file{pure.c} contains the declaration of the @dfn{purespace} array.
3028 Pure space is a hack used to place some constant Lisp data into the code
3029 segment of the XEmacs executable, even though the data needs to be
3030 initialized through function calls. (See above in section VIII for more
3031 info about this.) During startup, certain sorts of data is
3032 automatically copied into pure space, and other data is copied manually
3033 in some of the basic Lisp files by calling the function @code{purecopy},
3034 which copies the object if possible (this only works in temacs, of
3035 course) and returns the new object. In particular, while temacs is
3036 executing, the Lisp reader automatically copies all compiled-function
3037 objects that it reads into pure space. Since compiled-function objects
3038 are large, are never modified, and typically comprise the majority of
3039 the contents of a compiled-Lisp file, this works well. While XEmacs is
3040 running, any attempt to modify an object that resides in pure space
3041 causes an error. Objects in pure space are never garbage collected --
3042 almost all of the time, they're intended to be permanent, and in any
3043 case you can't write into pure space to set the mark bits.
3045 @file{puresize.h} contains the declaration of the size of the pure space
3046 array. This depends on the optional features that are compiled in, any
3047 extra purespace requested by the user at compile time, and certain other
3048 factors (e.g. 64-bit machines need more pure space because their Lisp
3049 objects are larger). The smallest size that suffices should be used, so
3050 that there's no wasted space. If there's not enough pure space, you
3051 will get an error during the build process, specifying how much more
3052 pure space is needed.
3061 This module contains all of the functions to handle the flow of control.
3062 This includes the mechanisms of defining functions, calling functions,
3063 traversing stack frames, and binding variables; the control primitives
3064 and other special forms such as @code{while}, @code{if}, @code{eval},
3065 @code{let}, @code{and}, @code{or}, @code{progn}, etc.; handling of
3066 non-local exits, unwind-protects, and exception handlers; entering the
3067 debugger; methods for the subr Lisp object type; etc. It does
3068 @emph{not} include the @code{read} function, the @code{print} function,
3069 or the handling of symbols and obarrays.
3071 @file{backtrace.h} contains some structures related to stack frames and the
3080 This module implements the Lisp reader and the @code{read} function,
3081 which converts text into Lisp objects, according to the read syntax of
3082 the objects, as described above. This is similar to the parser that is
3083 a part of all compilers.
3091 This module implements the Lisp print mechanism and the @code{print}
3092 function and related functions. This is the inverse of the Lisp reader
3093 -- it converts Lisp objects to a printed, textual representation.
3094 (Hopefully something that can be read back in using @code{read} to get
3095 an equivalent object.)
3105 @file{symbols.c} implements the handling of symbols, obarrays, and
3106 retrieving the values of symbols. Much of the code is devoted to
3107 handling the special @dfn{symbol-value-magic} objects that define
3108 special types of variables -- this includes buffer-local variables,
3109 variable aliases, variables that forward into C variables, etc. This
3110 module is initialized extremely early (right after @file{alloc.c}),
3111 because it is here that the basic symbols @code{t} and @code{nil} are
3112 created, and those symbols are used everywhere throughout XEmacs.
3114 @file{symeval.h} contains the definitions of symbol structures and the
3115 @code{DEFVAR_LISP()} and related macros for declaring variables.
3125 These modules implement the methods and standard Lisp primitives for all
3126 the basic Lisp object types other than symbols (which are described
3127 above). @file{data.c} contains all the predicates (primitives that return
3128 whether an object is of a particular type); the integer arithmetic
3129 functions; and the basic accessor and mutator primitives for the various
3130 object types. @file{fns.c} contains all the standard predicates for working
3131 with sequences (where, abstractly speaking, a sequence is an ordered set
3132 of objects, and can be represented by a list, string, vector, or
3133 bit-vector); it also contains @code{equal}, perhaps on the grounds that
3134 bulk of the operation of @code{equal} is comparing sequences.
3135 @file{floatfns.c} contains methods and primitives for floats and floating-point
3145 @file{bytecode.c} implements the byte-code interpreter and
3146 compiled-function objects, and @file{bytecode.h} contains associated
3147 structures. Note that the byte-code @emph{compiler} is written in Lisp.
3152 @node Modules for Standard Editing Operations
3153 @section Modules for Standard Editing Operations
3161 @file{buffer.c} implements the @dfn{buffer} Lisp object type. This
3162 includes functions that create and destroy buffers; retrieve buffers by
3163 name or by other properties; manipulate lists of buffers (remember that
3164 buffers are permanent objects and stored in various ordered lists);
3165 retrieve or change buffer properties; etc. It also contains the
3166 definitions of all the built-in buffer-local variables (which can be
3167 viewed as buffer properties). It does @emph{not} contain code to
3168 manipulate buffer-local variables (that's in @file{symbols.c}, described
3169 above); or code to manipulate the text in a buffer.
3171 @file{buffer.h} defines the structures associated with a buffer and the various
3172 macros for retrieving text from a buffer and special buffer positions
3173 (e.g. @code{point}, the default location for text insertion). It also
3174 contains macros for working with buffer positions and converting between
3175 their representations as character offsets and as byte offsets (under
3176 MULE, they are different, because characters can be multi-byte). It is
3177 one of the largest header files.
3179 @file{bufslots.h} defines the fields in the buffer structure that correspond to
3180 the built-in buffer-local variables. It is its own header file because
3181 it is included many times in @file{buffer.c}, as a way of iterating over all
3182 the built-in buffer-local variables.
3191 @file{insdel.c} contains low-level functions for inserting and deleting text in
3192 a buffer, keeping track of changed regions for use by redisplay, and
3193 calling any before-change and after-change functions that may have been
3194 registered for the buffer. It also contains the actual functions that
3195 convert between byte offsets and character offsets.
3197 @file{insdel.h} contains associated headers.
3205 This module implements the @dfn{marker} Lisp object type, which
3206 conceptually is a pointer to a text position in a buffer that moves
3207 around as text is inserted and deleted, so as to remain in the same
3208 relative position. This module doesn't actually move the markers around
3209 -- that's handled in @file{insdel.c}. This module just creates them and
3210 implements the primitives for working with them. As markers are simple
3211 objects, this does not entail much.
3213 Note that the standard arithmetic primitives (e.g. @code{+}) accept
3214 markers in place of integers and automatically substitute the value of
3215 @code{marker-position} for the marker, i.e. an integer describing the
3216 current buffer position of the marker.
3225 This module implements the @dfn{extent} Lisp object type, which is like
3226 a marker that works over a range of text rather than a single position.
3227 Extents are also much more complex and powerful than markers and have a
3228 more efficient (and more algorithmically complex) implementation. The
3229 implementation is described in detail in comments in @file{extents.c}.
3231 The code in @file{extents.c} works closely with @file{insdel.c} so that
3232 extents are properly moved around as text is inserted and deleted.
3233 There is also code in @file{extents.c} that provides information needed
3234 by the redisplay mechanism for efficient operation. (Remember that
3235 extents can have display properties that affect [sometimes drastically,
3236 as in the @code{invisible} property] the display of the text they
3245 @file{editfns.c} contains the standard Lisp primitives for working with
3246 a buffer's text, and calls the low-level functions in @file{insdel.c}.
3247 It also contains primitives for working with @code{point} (the default
3248 buffer insertion location).
3250 @file{editfns.c} also contains functions for retrieving various
3251 characteristics from the external environment: the current time, the
3252 process ID of the running XEmacs process, the name of the user who ran
3253 this XEmacs process, etc. It's not clear why this code is in
3265 These modules implement the basic @dfn{interactive} commands,
3266 i.e. user-callable functions. Commands, as opposed to other functions,
3267 have special ways of getting their parameters interactively (by querying
3268 the user), as opposed to having them passed in a normal function
3269 invocation. Many commands are not really meant to be called from other
3270 Lisp functions, because they modify global state in a way that's often
3271 undesired as part of other Lisp functions.
3273 @file{callint.c} implements the mechanism for querying the user for
3274 parameters and calling interactive commands. The bulk of this module is
3275 code that parses the interactive spec that is supplied with an
3276 interactive command.
3278 @file{cmds.c} implements the basic, most commonly used editing commands:
3279 commands to move around the current buffer and insert and delete
3280 characters. These commands are implemented using the Lisp primitives
3281 defined in @file{editfns.c}.
3283 @file{commands.h} contains associated structure definitions and prototypes.
3293 @file{search.c} implements the Lisp primitives for searching for text in
3294 a buffer, and some of the low-level algorithms for doing this. In
3295 particular, the fast fixed-string Boyer-Moore search algorithm is
3296 implemented in @file{search.c}. The low-level algorithms for doing
3297 regular-expression searching, however, are implemented in @file{regex.c}
3298 and @file{regex.h}. These two modules are largely independent of
3299 XEmacs, and are similar to (and based upon) the regular-expression
3300 routines used in @file{grep} and other GNU utilities.
3308 @file{doprnt.c} implements formatted-string processing, similar to
3309 @code{printf()} command in C.
3317 This module implements the undo mechanism for tracking buffer changes.
3318 Most of this could be implemented in Lisp.
3322 @node Editor-Level Control Flow Modules
3323 @section Editor-Level Control Flow Modules
3333 These implement the handling of events (user input and other system
3336 @file{events.c} and @file{events.h} define the @dfn{event} Lisp object
3337 type and primitives for manipulating it.
3339 @file{event-stream.c} implements the basic functions for working with
3340 event queues, dispatching an event by looking it up in relevant keymaps
3341 and such, and handling timeouts; this includes the primitives
3342 @code{next-event} and @code{dispatch-event}, as well as related
3343 primitives such as @code{sit-for}, @code{sleep-for}, and
3344 @code{accept-process-output}. (@file{event-stream.c} is one of the
3345 hairiest and trickiest modules in XEmacs. Beware! You can easily mess
3348 @file{event-Xt.c} and @file{event-tty.c} implement the low-level
3349 interfaces onto retrieving events from Xt (the X toolkit) and from TTY's
3350 (using @code{read()} and @code{select()}), respectively. The event
3351 interface enforces a clean separation between the specific code for
3352 interfacing with the operating system and the generic code for working
3353 with events, by defining an API of basic, low-level event methods;
3354 @file{event-Xt.c} and @file{event-tty.c} are two different
3355 implementations of this API. To add support for a new operating system
3356 (e.g. NeXTstep), one merely needs to provide another implementation of
3357 those API functions.
3359 Note that the choice of whether to use @file{event-Xt.c} or
3360 @file{event-tty.c} is made at compile time! Or at the very latest, it
3361 is made at startup time. @file{event-Xt.c} handles events for
3362 @emph{both} X and TTY frames; @file{event-tty.c} is only used when X
3363 support is not compiled into XEmacs. The reason for this is that there
3364 is only one event loop in XEmacs: thus, it needs to be able to receive
3365 events from all different kinds of frames.
3374 @file{keymap.c} and @file{keymap.h} define the @dfn{keymap} Lisp object
3375 type and associated methods and primitives. (Remember that keymaps are
3376 objects that associate event descriptions with functions to be called to
3377 ``execute'' those events; @code{dispatch-event} looks up events in the
3386 @file{keyboard.c} contains functions that implement the actual editor
3387 command loop -- i.e. the event loop that cyclically retrieves and
3388 dispatches events. This code is also rather tricky, just like
3389 @file{event-stream.c}.
3398 These two modules contain the basic code for defining keyboard macros.
3399 These functions don't actually do much; most of the code that handles keyboard
3400 macros is mixed in with the event-handling code in @file{event-stream.c}.
3408 This contains some miscellaneous code related to the minibuffer (most of
3409 the minibuffer code was moved into Lisp by Richard Mlynarik). This
3410 includes the primitives for completion (although filename completion is
3411 in @file{dired.c}), the lowest-level interface to the minibuffer (if the
3412 command loop were cleaned up, this too could be in Lisp), and code for
3413 dealing with the echo area (this, too, was mostly moved into Lisp, and
3414 the only code remaining is code to call out to Lisp or provide simple
3415 bootstrapping implementations early in temacs, before the echo-area Lisp
3420 @node Modules for the Basic Displayable Lisp Objects
3421 @section Modules for the Basic Displayable Lisp Objects
3435 These modules implement the @dfn{device} Lisp object type. This
3436 abstracts a particular screen or connection on which frames are
3437 displayed. As with Lisp objects, event interfaces, and other
3438 subsystems, the device code is separated into a generic component that
3439 contains a standardized interface (in the form of a set of methods) onto
3440 particular device types.
3442 The device subsystem defines all the methods and provides method
3443 services for not only device