1 \input texinfo @c -*-texinfo-*-
3 @setfilename ../../info/internals.info
4 @settitle XEmacs Internals Manual
9 Copyright @copyright{} 1992 - 1996 Ben Wing.
10 Copyright @copyright{} 1996, 1997 Sun Microsystems.
11 Copyright @copyright{} 1994, 1995 Free Software Foundation.
12 Copyright @copyright{} 1994, 1995 Board of Trustees, University of Illinois.
15 Permission is granted to make and distribute verbatim copies of this
16 manual provided the copyright notice and this permission notice are
17 preserved on all copies.
20 Permission is granted to process this file through TeX and print the
21 results, provided the printed document carries copying permission notice
22 identical to this one except for the removal of this paragraph (this
23 paragraph not being relevant to the printed manual).
26 Permission is granted to copy and distribute modified versions of this
27 manual under the conditions for verbatim copying, provided that the
28 entire resulting derived work is distributed under the terms of a
29 permission notice identical to this one.
31 Permission is granted to copy and distribute translations of this manual
32 into another language, under the above conditions for modified versions,
33 except that this permission notice may be stated in a translation
34 approved by the Foundation.
36 Permission is granted to copy and distribute modified versions of this
37 manual under the conditions for verbatim copying, provided also that the
38 section entitled ``GNU General Public License'' is included exactly as
39 in the original, and provided that the entire resulting derived work is
40 distributed under the terms of a permission notice identical to this
43 Permission is granted to copy and distribute translations of this manual
44 into another language, under the above conditions for modified versions,
45 except that the section entitled ``GNU General Public License'' may be
46 included in a translation approved by the Free Software Foundation
47 instead of in the original English.
57 @setchapternewpage odd
61 @title XEmacs Internals Manual
62 @subtitle Version 1.1, March 1997
65 @author Martin Buchholz
70 Copyright @copyright{} 1992 - 1996 Ben Wing. @*
71 Copyright @copyright{} 1996 Sun Microsystems, Inc. @*
72 Copyright @copyright{} 1994 Free Software Foundation. @*
73 Copyright @copyright{} 1994, 1995 Board of Trustees, University of Illinois.
79 Permission is granted to make and distribute verbatim copies of this
80 manual provided the copyright notice and this permission notice are
81 preserved on all copies.
83 Permission is granted to copy and distribute modified versions of this
84 manual under the conditions for verbatim copying, provided also that the
85 section entitled ``GNU General Public License'' is included
86 exactly as in the original, and provided that the entire resulting
87 derived work is distributed under the terms of a permission notice
88 identical to this one.
90 Permission is granted to copy and distribute translations of this manual
91 into another language, under the above conditions for modified versions,
92 except that the section entitled ``GNU General Public License'' may be
93 included in a translation approved by the Free Software Foundation
94 instead of in the original English.
98 @node Top, A History of Emacs, (dir), (dir)
101 This Info file contains v1.0 of the XEmacs Internals Manual.
105 * A History of Emacs:: Times, dates, important events.
106 * XEmacs From the Outside:: A broad conceptual overview.
107 * The Lisp Language:: An overview.
108 * XEmacs From the Perspective of Building::
109 * XEmacs From the Inside::
110 * The XEmacs Object System (Abstractly Speaking)::
111 * How Lisp Objects Are Represented in C::
112 * Rules When Writing New C Code::
113 * A Summary of the Various XEmacs Modules::
114 * Allocation of Objects in XEmacs Lisp::
115 * Events and the Event Loop::
116 * Evaluation; Stack Frames; Bindings::
117 * Symbols and Variables::
118 * Buffers and Textual Representation::
119 * MULE Character Sets and Encodings::
120 * The Lisp Reader and Compiler::
122 * Consoles; Devices; Frames; Windows::
123 * The Redisplay Mechanism::
129 * Interface to X Windows::
130 * Index:: Index including concepts, functions, variables,
133 --- The Detailed Node Listing ---
135 Here are other nodes that are inferiors of those already listed,
136 mentioned here so you can get to them in one step:
140 * Through Version 18:: Unification prevails.
141 * Lucid Emacs:: One version 19 Emacs.
142 * GNU Emacs 19:: The other version 19 Emacs.
143 * XEmacs:: The continuation of Lucid Emacs.
145 Rules When Writing New C Code
147 * General Coding Rules::
148 * Writing Lisp Primitives::
149 * Adding Global Lisp Variables::
150 * Techniques for XEmacs Developers::
152 A Summary of the Various XEmacs Modules
154 * Low-Level Modules::
155 * Basic Lisp Modules::
156 * Modules for Standard Editing Operations::
157 * Editor-Level Control Flow Modules::
158 * Modules for the Basic Displayable Lisp Objects::
159 * Modules for other Display-Related Lisp Objects::
160 * Modules for the Redisplay Mechanism::
161 * Modules for Interfacing with the File System::
162 * Modules for Other Aspects of the Lisp Interpreter and Object System::
163 * Modules for Interfacing with the Operating System::
164 * Modules for Interfacing with X Windows::
165 * Modules for Internationalization::
167 Allocation of Objects in XEmacs Lisp
169 * Introduction to Allocation::
170 * Garbage Collection::
172 * Integers and Characters::
173 * Allocation from Frob Blocks::
175 * Low-level allocation::
185 Events and the Event Loop
187 * Introduction to Events::
189 * Specifics of the Event Gathering Mechanism::
190 * Specifics About the Emacs Event::
191 * The Event Stream Callback Routines::
192 * Other Event Loop Functions::
193 * Converting Events::
194 * Dispatching Events; The Command Builder::
196 Evaluation; Stack Frames; Bindings
199 * Dynamic Binding; The specbinding Stack; Unwind-Protects::
200 * Simple Special Forms::
203 Symbols and Variables
205 * Introduction to Symbols::
209 Buffers and Textual Representation
211 * Introduction to Buffers:: A buffer holds a block of text such as a file.
212 * The Text in a Buffer:: Representation of the text in a buffer.
213 * Buffer Lists:: Keeping track of all buffers.
214 * Markers and Extents:: Tagging locations within a buffer.
215 * Bufbytes and Emchars:: Representation of individual characters.
216 * The Buffer Object:: The Lisp object corresponding to a buffer.
218 MULE Character Sets and Encodings
222 * Internal Mule Encodings::
226 * Japanese EUC (Extended Unix Code)::
229 Internal Mule Encodings
231 * Internal String Encoding::
232 * Internal Character Encoding::
234 The Lisp Reader and Compiler
238 Consoles; Devices; Frames; Windows
240 * Introduction to Consoles; Devices; Frames; Windows::
244 The Redisplay Mechanism
246 * Critical Redisplay Sections::
251 * Introduction to Extents:: Extents are ranges over text, with properties.
252 * Extent Ordering:: How extents are ordered internally.
253 * Format of the Extent Info:: The extent information in a buffer or string.
254 * Zero-Length Extents:: A weird special case.
255 * Mathematics of Extent Ordering:: A rigorous foundation.
256 * Extent Fragments:: Cached information useful for redisplay.
266 Interface to X Windows
270 @node A History of Emacs, XEmacs From the Outside, Top, Top
271 @chapter A History of Emacs
272 @cindex history of Emacs
273 @cindex Hackers (Steven Levy)
275 @cindex ITS (Incompatible Timesharing System)
276 @cindex Stallman, Richard
281 @cindex Free Software Foundation
283 XEmacs is a powerful, customizable text editor and development
284 environment. It began as Lucid Emacs, which was in turn derived from
285 GNU Emacs, a program written by Richard Stallman of the Free Software
286 Foundation. GNU Emacs dates back to the 1970's, and was modelled
287 after a package called ``Emacs'', written in 1976, that was a set of
288 macros on top of TECO, an old, old text editor written at MIT on the
289 DEC PDP 10 under one of the earliest time-sharing operating systems,
290 ITS (Incompatible Timesharing System). (ITS dates back well before
291 Unix.) ITS, TECO, and Emacs were products of a group of people at MIT
292 who called themselves ``hackers'', who shared an idealistic belief
293 system about the free exchange of information and were fanatical in
294 their devotion to and time spent with computers. (The hacker
295 subculture dates back to the late 1950's at MIT and is described in
296 detail in Steven Levy's book @cite{Hackers}. This book also includes
297 a lot of information about Stallman himself and the development of
298 Lisp, a programming language developed at MIT that underlies Emacs.)
301 * Through Version 18:: Unification prevails.
302 * Lucid Emacs:: One version 19 Emacs.
303 * GNU Emacs 19:: The other version 19 Emacs.
304 * GNU Emacs 20:: The other version 20 Emacs.
305 * XEmacs:: The continuation of Lucid Emacs.
308 @node Through Version 18
309 @section Through Version 18
310 @cindex Gosling, James
311 @cindex Great Usenet Renaming
313 Although the history of the early versions of GNU Emacs is unclear,
314 the history is well-known from the middle of 1985. A time line is:
318 GNU Emacs version 15 (15.34) was released sometime in 1984 or 1985 and
319 shared some code with a version of Emacs written by James Gosling (the
320 same James Gosling who later created the Java language).
322 GNU Emacs version 16 (first released version was 16.56) was released on
323 July 15, 1985. All Gosling code was removed due to potential copyright
324 problems with the code.
326 version 16.57: released on September 16, 1985.
328 versions 16.58, 16.59: released on September 17, 1985.
330 version 16.60: released on September 19, 1985. These later version 16's
331 incorporated patches from the net, esp. for getting Emacs to work under
334 version 17.36 (first official v17 release) released on December 20,
335 1985. Included a TeX-able user manual. First official unpatched
336 version that worked on vanilla System V machines.
338 version 17.43 (second official v17 release) released on January 25,
341 version 17.45 released on January 30, 1986.
343 version 17.46 released on February 4, 1986.
345 version 17.48 released on February 10, 1986.
347 version 17.49 released on February 12, 1986.
349 version 17.55 released on March 18, 1986.
351 version 17.57 released on March 27, 1986.
353 version 17.58 released on April 4, 1986.
355 version 17.61 released on April 12, 1986.
357 version 17.63 released on May 7, 1986.
359 version 17.64 released on May 12, 1986.
361 version 18.24 (a beta version) released on October 2, 1986.
363 version 18.30 (a beta version) released on November 15, 1986.
365 version 18.31 (a beta version) released on November 23, 1986.
367 version 18.32 (a beta version) released on December 7, 1986.
369 version 18.33 (a beta version) released on December 12, 1986.
371 version 18.35 (a beta version) released on January 5, 1987.
373 version 18.36 (a beta version) released on January 21, 1987.
375 January 27, 1987: The Great Usenet Renaming. net.emacs is now
378 version 18.37 (a beta version) released on February 12, 1987.
380 version 18.38 (a beta version) released on March 3, 1987.
382 version 18.39 (a beta version) released on March 14, 1987.
384 version 18.40 (a beta version) released on March 18, 1987.
386 version 18.41 (the first ``official'' release) released on March 22,
389 version 18.45 released on June 2, 1987.
391 version 18.46 released on June 9, 1987.
393 version 18.47 released on June 18, 1987.
395 version 18.48 released on September 3, 1987.
397 version 18.49 released on September 18, 1987.
399 version 18.50 released on February 13, 1988.
401 version 18.51 released on May 7, 1988.
403 version 18.52 released on September 1, 1988.
405 version 18.53 released on February 24, 1989.
407 version 18.54 released on April 26, 1989.
409 version 18.55 released on August 23, 1989. This is the earliest version
410 that is still available by FTP.
412 version 18.56 released on January 17, 1991.
414 version 18.57 released late January, 1991.
416 version 18.58 released ?????.
418 version 18.59 released October 31, 1992.
428 Lucid Emacs was developed by the (now-defunct) Lucid Inc., a maker of
429 C++ and Lisp development environments. It began when Lucid decided they
430 wanted to use Emacs as the editor and cornerstone of their C++
431 development environment (called ``Energize''). They needed many features
432 that were not available in the existing version of GNU Emacs (version
433 18.5something), in particular good and integrated support for GUI
434 elements such as mouse support, multiple fonts, multiple window-system
435 windows, etc. A branch of GNU Emacs called Epoch, written at the
436 University of Illinois, existed that supplied many of these features;
437 however, Lucid needed more than what existed in Epoch. At the time, the
438 Free Software Foundation was working on version 19 of Emacs (this was
439 sometime around 1991), which was planned to have similar features, and
440 so Lucid decided to work with the Free Software Foundation. Their plan
441 was to add features that they needed, and coordinate with the FSF so
442 that the features would get included back into Emacs version 19.
444 Delays in the release of version 19 occurred, however (resulting in it
445 finally being released more than a year after what was initially
446 planned), and Lucid encountered unexpected technical resistance in
447 getting their changes merged back into version 19, so they decided to
448 release their own version of Emacs, which became Lucid Emacs 19.0.
450 @cindex Zawinski, Jamie
451 @cindex Sexton, Harlan
453 @cindex Devin, Matthieu
454 The initial authors of Lucid Emacs were Matthieu Devin, Harlan Sexton,
455 and Eric Benson, and the work was later taken over by Jamie Zawinski,
456 who became ``Mr. Lucid Emacs'' for many releases.
458 A time line for Lucid Emacs/XEmacs is
462 version 19.0 shipped with Energize 1.0, April 1992.
464 version 19.1 released June 4, 1992.
466 version 19.2 released June 19, 1992.
468 version 19.3 released September 9, 1992.
470 version 19.4 released January 21, 1993.
472 version 19.5 was a repackaging of 19.4 with a few bug fixes and
473 shipped with Energize 2.0. Never released to the net.
475 version 19.6 released April 9, 1993.
477 version 19.7 was a repackaging of 19.6 with a few bug fixes and
478 shipped with Energize 2.1. Never released to the net.
480 version 19.8 released September 6, 1993.
482 version 19.9 released January 12, 1994.
484 version 19.10 released May 27, 1994.
486 version 19.11 (first XEmacs) released September 13, 1994.
488 version 19.12 released June 23, 1995.
490 version 19.13 released September 1, 1995.
492 version 19.14 released June 23, 1996.
494 version 20.0 released February 9, 1997.
496 version 19.15 released March 28, 1997.
498 version 20.1 (not released to the net) April 15, 1997.
500 version 20.2 released May 16, 1997.
502 version 19.16 released October 31, 1997.
504 version 20.3 (the first stable version of XEmacs 20.x) released November 30,
506 version 20.4 released February 28, 1998.
510 @section GNU Emacs 19
514 About a year after the initial release of Lucid Emacs, the FSF
515 released a beta of their version of Emacs 19 (referred to here as ``GNU
516 Emacs''). By this time, the current version of Lucid Emacs was
517 19.6. (Strangely, the first released beta from the FSF was GNU Emacs
518 19.7.) A time line for GNU Emacs version 19 is
522 version 19.8 (beta) released May 27, 1993.
524 version 19.9 (beta) released May 27, 1993.
526 version 19.10 (beta) released May 30, 1993.
528 version 19.11 (beta) released June 1, 1993.
530 version 19.12 (beta) released June 2, 1993.
532 version 19.13 (beta) released June 8, 1993.
534 version 19.14 (beta) released June 17, 1993.
536 version 19.15 (beta) released June 19, 1993.
538 version 19.16 (beta) released July 6, 1993.
540 version 19.17 (beta) released late July, 1993.
542 version 19.18 (beta) released August 9, 1993.
544 version 19.19 (beta) released August 15, 1993.
546 version 19.20 (beta) released November 17, 1993.
548 version 19.21 (beta) released November 17, 1993.
550 version 19.22 (beta) released November 28, 1993.
552 version 19.23 (beta) released May 17, 1994.
554 version 19.24 (beta) released May 16, 1994.
556 version 19.25 (beta) released June 3, 1994.
558 version 19.26 (beta) released September 11, 1994.
560 version 19.27 (beta) released September 14, 1994.
562 version 19.28 (first ``official'' release) released November 1, 1994.
564 version 19.29 released June 21, 1995.
566 version 19.30 released November 24, 1995.
568 version 19.31 released May 25, 1996.
570 version 19.32 released July 31, 1996.
572 version 19.33 released August 11, 1996.
574 version 19.34 released August 21, 1996.
576 version 19.34b released September 6, 1996.
579 @cindex Mlynarik, Richard
580 In some ways, GNU Emacs 19 was better than Lucid Emacs; in some ways,
581 worse. Lucid soon began incorporating features from GNU Emacs 19 into
582 Lucid Emacs; the work was mostly done by Richard Mlynarik, who had been
583 working on and using GNU Emacs for a long time (back as far as version
587 @section GNU Emacs 20
591 On February 2, 1997 work began on GNU Emacs to integrate Mule. The first
592 release was made in September of that year.
594 A timeline for Emacs 20 is
598 version 20.1 released September 17, 1997.
600 version 20.2 released September 20, 1997.
602 version 20.3 released August 19, 1998.
609 @cindex Sun Microsystems
610 @cindex University of Illinois
611 @cindex Illinois, University of
613 @cindex Andreessen, Marc
615 @cindex Buchholz, Martin
616 @cindex Kaplan, Simon
618 @cindex Thompson, Chuck
621 @cindex Amdahl Corporation
622 Around the time that Lucid was developing Energize, Sun Microsystems
623 was developing their own development environment (called ``SPARCWorks'')
624 and also decided to use Emacs. They joined forces with the Epoch team
625 at the University of Illinois and later with Lucid. The maintainer of
626 the last-released version of Epoch was Marc Andreessen, but he dropped
627 out and the Epoch project, headed by Simon Kaplan, lured Chuck Thompson
628 away from a system administration job to become the primary Lucid Emacs
629 author for Epoch and Sun. Chuck's area of specialty became the
630 redisplay engine (he replaced the old Lucid Emacs redisplay engine with
631 a ported version from Epoch and then later rewrote it from scratch).
632 Sun also hired Ben Wing (the author of Win-Emacs, a port of Lucid Emacs
633 to Microsoft Windows 3.1) in 1993, for what was initially a one-month
634 contract to fix some event problems but later became a many-year
635 involvement, punctuated by a six-month contract with Amdahl Corporation.
637 @cindex rename to XEmacs
638 In 1994, Sun and Lucid agreed to rename Lucid Emacs to XEmacs (a name
639 not favorable to either company); the first release called XEmacs was
640 version 19.11. In June 1994, Lucid folded and Jamie quit to work for
641 the newly formed Mosaic Communications Corp., later Netscape
642 Communications Corp. (co-founded by the same Marc Andreessen, who had
643 quit his Epoch job to work on a graphical browser for the World Wide
644 Web). Chuck then become the primary maintainer of XEmacs, and put out
645 versions 19.11 through 19.14 in conjunction with Ben. For 19.12 and
646 19.13, Chuck added the new redisplay and many other display improvements
647 and Ben added MULE support (support for Asian and other languages) and
648 redesigned most of the internal Lisp subsystems to better support the
649 MULE work and the various other features being added to XEmacs. After
650 19.14 Chuck retired as primary maintainer and Steve Baur stepped in.
652 @cindex MULE merged XEmacs appears
653 Soon after 19.13 was released, work began in earnest on the MULE
654 internationalization code and the source tree was divided into two
655 development paths. The MULE version was initially called 19.20, but was
656 soon renamed to 20.0. In 1996 Martin Buchholz of Sun Microsystems took
657 over the care and feeding of it and worked on it in parallel with the
658 19.14 development that was occurring at the same time. After much work
659 by Martin, it was decided to release 20.0 ahead of 19.15 in February
660 1997. The source tree remained divided until 20.2 when the version 19
661 source was finally retired at version 19.16.
664 @cindex Buchholz, Martin
666 @cindex Niksic, Hrvoje
667 @cindex XEmacs goes it alone
668 In 1997, Sun finally dropped all pretense of support for XEmacs and
669 Martin Buchholz left the company in November. Since then, and mostly
670 for the previous year, because Steve Baur was never paid to work on
671 XEmacs, XEmacs has existed solely on the contributions of volunteers
672 from the Free Software Community. Starting from 1997, Hrvoje Niksic and
673 Kyle Jones have figured prominently in XEmacs development.
675 @cindex merging attempts
676 Many attempts have been made to merge XEmacs and GNU Emacs, but they
677 have consistently failed.
679 A more detailed history is contained in the XEmacs About page.
681 @node XEmacs From the Outside, The Lisp Language, A History of Emacs, Top
682 @chapter XEmacs From the Outside
683 @cindex read-eval-print
685 XEmacs appears to the outside world as an editor, but it is really a
686 Lisp environment. At its heart is a Lisp interpreter; it also
687 ``happens'' to contain many specialized object types (e.g. buffers,
688 windows, frames, events) that are useful for implementing an editor.
689 Some of these objects (in particular windows and frames) have
690 displayable representations, and XEmacs provides a function
691 @code{redisplay()} that ensures that the display of all such objects
692 matches their internal state. Most of the time, a standard Lisp
693 environment is in a @dfn{read-eval-print} loop -- i.e. ``read some Lisp
694 code, execute it, and print the results''. XEmacs has a similar loop:
700 dispatch the event (i.e. ``do it'')
705 Reading an event is done using the Lisp function @code{next-event},
706 which waits for something to happen (typically, the user presses a key
707 or moves the mouse) and returns an event object describing this.
708 Dispatching an event is done using the Lisp function
709 @code{dispatch-event}, which looks up the event in a keymap object (a
710 particular kind of object that associates an event with a Lisp function)
711 and calls that function. The function ``does'' what the user has
712 requested by changing the state of particular frame objects, buffer
713 objects, etc. Finally, @code{redisplay()} is called, which updates the
714 display to reflect those changes just made. Thus is an ``editor'' born.
716 @cindex bridge, playing
718 @cindex pi, calculating
719 Note that you do not have to use XEmacs as an editor; you could just
720 as well make it do your taxes, compute pi, play bridge, etc. You'd just
721 have to write functions to do those operations in Lisp.
723 @node The Lisp Language, XEmacs From the Perspective of Building, XEmacs From the Outside, Top
724 @chapter The Lisp Language
727 @cindex Lisp vs. Java
728 @cindex Java vs. Lisp
729 @cindex dynamic scoping
730 @cindex scoping, dynamic
731 @cindex dynamic types
732 @cindex types, dynamic
735 @cindex Gosling, James
737 Lisp is a general-purpose language that is higher-level than C and in
738 many ways more powerful than C. Powerful dialects of Lisp such as
739 Common Lisp are probably much better languages for writing very large
740 applications than is C. (Unfortunately, for many non-technical
741 reasons C and its successor C++ have become the dominant languages for
742 application development. These languages are both inadequate for
743 extremely large applications, which is evidenced by the fact that newer,
744 larger programs are becoming ever harder to write and are requiring ever
745 more programmers despite great increases in C development environments;
746 and by the fact that, although hardware speeds and reliability have been
747 growing at an exponential rate, most software is still generally
748 considered to be slow and buggy.)
750 The new Java language holds promise as a better general-purpose
751 development language than C. Java has many features in common with
752 Lisp that are not shared by C (this is not a coincidence, since
753 Java was designed by James Gosling, a former Lisp hacker). This
754 will be discussed more later.
756 For those used to C, here is a summary of the basic differences between
761 Lisp has an extremely regular syntax. Every function, expression,
762 and control statement is written in the form
765 (@var{func} @var{arg1} @var{arg2} ...)
768 This is as opposed to C, which writes functions as
771 func(@var{arg1}, @var{arg2}, ...)
774 but writes expressions involving operators as (e.g.)
777 @var{arg1} + @var{arg2}
780 and writes control statements as (e.g.)
783 while (@var{expr}) @{ @var{statement1}; @var{statement2}; ... @}
786 Lisp equivalents of the latter two would be
789 (+ @var{arg1} @var{arg2} ...)
795 (while @var{expr} @var{statement1} @var{statement2} ...)
799 Lisp is a safe language. Assuming there are no bugs in the Lisp
800 interpreter/compiler, it is impossible to write a program that ``core
801 dumps'' or otherwise causes the machine to execute an illegal
802 instruction. This is very different from C, where perhaps the most
803 common outcome of a bug is exactly such a crash. A corollary of this is that
804 the C operation of casting a pointer is impossible (and unnecessary) in
805 Lisp, and that it is impossible to access memory outside the bounds of
809 Programs and data are written in the same form. The
810 parenthesis-enclosing form described above for statements is the same
811 form used for the most common data type in Lisp, the list. Thus, it is
812 possible to represent any Lisp program using Lisp data types, and for
813 one program to construct Lisp statements and then dynamically
814 @dfn{evaluate} them, or cause them to execute.
817 All objects are @dfn{dynamically typed}. This means that part of every
818 object is an indication of what type it is. A Lisp program can
819 manipulate an object without knowing what type it is, and can query an
820 object to determine its type. This means that, correspondingly,
821 variables and function parameters can hold objects of any type and are
822 not normally declared as being of any particular type. This is opposed
823 to the @dfn{static typing} of C, where variables can hold exactly one
824 type of object and must be declared as such, and objects do not contain
825 an indication of their type because it's implicit in the variables they
826 are stored in. It is possible in C to have a variable hold different
827 types of objects (e.g. through the use of @code{void *} pointers or
828 variable-argument functions), but the type information must then be
829 passed explicitly in some other fashion, leading to additional program
833 Allocated memory is automatically reclaimed when it is no longer in use.
834 This operation is called @dfn{garbage collection} and involves looking
835 through all variables to see what memory is being pointed to, and
836 reclaiming any memory that is not pointed to and is thus
837 ``inaccessible'' and out of use. This is as opposed to C, in which
838 allocated memory must be explicitly reclaimed using @code{free()}. If
839 you simply drop all pointers to memory without freeing it, it becomes
840 ``leaked'' memory that still takes up space. Over a long period of
841 time, this can cause your program to grow and grow until it runs out of
845 Lisp has built-in facilities for handling errors and exceptions. In C,
846 when an error occurs, usually either the program exits entirely or the
847 routine in which the error occurs returns a value indicating this. If
848 an error occurs in a deeply-nested routine, then every routine currently
849 called must unwind itself normally and return an error value back up to
850 the next routine. This means that every routine must explicitly check
851 for an error in all the routines it calls; if it does not do so,
852 unexpected and often random behavior results. This is an extremely
853 common source of bugs in C programs. An alternative would be to do a
854 non-local exit using @code{longjmp()}, but that is often very dangerous
855 because the routines that were exited past had no opportunity to clean
856 up after themselves and may leave things in an inconsistent state,
857 causing a crash shortly afterwards.
859 Lisp provides mechanisms to make such non-local exits safe. When an
860 error occurs, a routine simply signals that an error of a particular
861 class has occurred, and a non-local exit takes place. Any routine can
862 trap errors occurring in routines it calls by registering an error
863 handler for some or all classes of errors. (If no handler is registered,
864 a default handler, generally installed by the top-level event loop, is
865 executed; this prints out the error and continues.) Routines can also
866 specify cleanup code (called an @dfn{unwind-protect}) that will be
867 called when control exits from a block of code, no matter how that exit
868 occurs -- i.e. even if a function deeply nested below it causes a
869 non-local exit back to the top level.
871 Note that this facility has appeared in some recent vintages of C, in
872 particular Visual C++ and other PC compilers written for the Microsoft
876 In Emacs Lisp, local variables are @dfn{dynamically scoped}. This means
877 that if you declare a local variable in a particular function, and then
878 call another function, that subfunction can ``see'' the local variable
879 you declared. This is actually considered a bug in Emacs Lisp and in
880 all other early dialects of Lisp, and was corrected in Common Lisp. (In
881 Common Lisp, you can still declare dynamically scoped variables if you
882 want to -- they are sometimes useful -- but variables by default are
883 @dfn{lexically scoped} as in C.)
886 For those familiar with Lisp, Emacs Lisp is modelled after MacLisp, an
887 early dialect of Lisp developed at MIT (no relation to the Macintosh
888 computer). There is a Common Lisp compatibility package available for
889 Emacs that provides many of the features of Common Lisp.
891 The Java language is derived in many ways from C, and shares a similar
892 syntax, but has the following features in common with Lisp (and different
897 Java is a safe language, like Lisp.
899 Java provides garbage collection, like Lisp.
901 Java has built-in facilities for handling errors and exceptions, like
904 Java has a type system that combines the best advantages of both static
905 and dynamic typing. Objects (except very simple types) are explicitly
906 marked with their type, as in dynamic typing; but there is a hierarchy
907 of types and functions are declared to accept only certain types, thus
908 providing the increased compile-time error-checking of static typing.
911 @node XEmacs From the Perspective of Building, XEmacs From the Inside, The Lisp Language, Top
912 @chapter XEmacs From the Perspective of Building
914 The heart of XEmacs is the Lisp environment, which is written in C.
915 This is contained in the @file{src/} subdirectory. Underneath
916 @file{src/} are two subdirectories of header files: @file{s/} (header
917 files for particular operating systems) and @file{m/} (header files for
918 particular machine types). In practice the distinction between the two
919 types of header files is blurred. These header files define or undefine
920 certain preprocessor constants and macros to indicate particular
921 characteristics of the associated machine or operating system. As part
922 of the configure process, one @file{s/} file and one @file{m/} file is
923 identified for the particular environment in which XEmacs is being
926 XEmacs also contains a great deal of Lisp code. This implements the
927 operations that make XEmacs useful as an editor as well as just a
928 Lisp environment, and also contains many add-on packages that allow
929 XEmacs to browse directories, act as a mail and Usenet news reader,
930 compile Lisp code, etc. There is actually more Lisp code than
931 C code associated with XEmacs, but much of the Lisp code is
932 peripheral to the actual operation of the editor. The Lisp code
933 all lies in subdirectories underneath the @file{lisp/} directory.
935 The @file{lwlib/} directory contains C code that implements a
936 generalized interface onto different X widget toolkits and also
937 implements some widgets of its own that behave like Motif widgets but
938 are faster, free, and in some cases more powerful. The code in this
939 directory compiles into a library and is mostly independent from XEmacs.
941 The @file{etc/} directory contains various data files associated with
942 XEmacs. Some of them are actually read by XEmacs at startup; others
943 merely contain useful information of various sorts.
945 The @file{lib-src/} directory contains C code for various auxiliary
946 programs that are used in connection with XEmacs. Some of them are used
947 during the build process; others are used to perform certain functions
948 that cannot conveniently be placed in the XEmacs executable (e.g. the
949 @file{movemail} program for fetching mail out of @file{/var/spool/mail},
950 which must be setgid to @file{mail} on many systems; and the
951 @file{gnuclient} program, which allows an external script to communicate
952 with a running XEmacs process).
954 The @file{man/} directory contains the sources for the XEmacs
955 documentation. It is mostly in a form called Texinfo, which can be
956 converted into either a printed document (by passing it through @TeX{})
957 or into on-line documentation called @dfn{info files}.
959 The @file{info/} directory contains the results of formatting the
960 XEmacs documentation as @dfn{info files}, for on-line use. These files
961 are used when you enter the Info system using @kbd{C-h i} or through the
964 The @file{dynodump/} directory contains auxiliary code used to build
965 XEmacs on Solaris platforms.
967 The other directories contain various miscellaneous code and
968 information that is not normally used or needed.
970 The first step of building involves running the @file{configure}
971 program and passing it various parameters to specify any optional
972 features you want and compiler arguments and such, as described in the
973 @file{INSTALL} file. This determines what the build environment is,
974 chooses the appropriate @file{s/} and @file{m/} file, and runs a series
975 of tests to determine many details about your environment, such as which
976 library functions are available and exactly how they work. (The
977 @file{s/} and @file{m/} files only contain information that cannot be
978 conveniently detected in this fashion.) The reason for running these
979 tests is that it allows XEmacs to be compiled on a much wider variety of
980 platforms than those that the XEmacs developers happen to be familiar
981 with, including various sorts of hybrid platforms. This is especially
982 important now that many operating systems give you a great deal of
983 control over exactly what features you want installed, and allow for
984 easy upgrading of parts of a system without upgrading the rest. It
985 would be impossible to pre-determine and pre-specify the information for
986 all possible configurations.
988 When configure is done running, it generates @file{Makefile}s and the
989 file @file{src/config.h} (which describes the features of your system)
990 from template files. You then run @file{make}, which compiles the
991 auxiliary code and programs in @file{lib-src/} and @file{lwlib/} and the
992 main XEmacs executable in @file{src/}. The result of compiling and
993 linking is an executable called @file{temacs}, which is @emph{not} the
994 final XEmacs executable. @file{temacs} by itself is not intended to
995 function as an editor or even display any windows on the screen, and if
996 you simply run it, it will exit immediately. The @file{Makefile} runs
997 @file{temacs} with certain options that cause it to initialize itself,
998 read in a number of basic Lisp files, and then dump itself out into a
999 new executable called @file{xemacs}. This new executable has been
1000 pre-initialized and contains pre-digested Lisp code that is necessary
1001 for the editor to function (this includes most basic Lisp functions,
1002 e.g. @code{not}, that can be defined in terms of other Lisp primitives;
1003 some initialization code that is called when certain objects, such as
1004 frames, are created; and all of the standard keybindings and code for
1005 the actions they result in). This executable, @file{xemacs}, is the
1006 executable that you run to use the XEmacs editor.
1008 Although @file{temacs} is not intended to be run as an editor, it can,
1009 by using the incantation @code{temacs -batch -l loadup.el run-temacs}.
1010 This is useful when the dumping procedure described above is broken, or
1011 when using certain program debugging tools such as Purify. These tools
1012 get mighty confused by the tricks played by the XEmacs build process,
1013 such as allocation memory in one process, and freeing it in the next.
1015 @node XEmacs From the Inside, The XEmacs Object System (Abstractly Speaking), XEmacs From the Perspective of Building, Top
1016 @chapter XEmacs From the Inside
1018 Internally, XEmacs is quite complex, and can be very confusing. To
1019 simplify things, it can be useful to think of XEmacs as containing an
1020 event loop that ``drives'' everything, and a number of other subsystems,
1021 such as a Lisp engine and a redisplay mechanism. Each of these other
1022 subsystems exists simultaneously in XEmacs, and each has a certain
1023 state. The flow of control continually passes in and out of these
1024 different subsystems in the course of normal operation of the editor.
1026 It is important to keep in mind that, most of the time, the editor is
1027 ``driven'' by the event loop. Except during initialization and batch
1028 mode, all subsystems are entered directly or indirectly through the
1029 event loop, and ultimately, control exits out of all subsystems back up
1030 to the event loop. This cycle of entering a subsystem, exiting back out
1031 to the event loop, and starting another iteration of the event loop
1032 occurs once each keystroke, mouse motion, etc.
1034 If you're trying to understand a particular subsystem (other than the
1035 event loop), think of it as a ``daemon'' process or ``servant'' that is
1036 responsible for one particular aspect of a larger system, and
1037 periodically receives commands or environment changes that cause it to
1038 do something. Ultimately, these commands and environment changes are
1039 always triggered by the event loop. For example:
1043 The window and frame mechanism is responsible for keeping track of what
1044 windows and frames exist, what buffers are in them, etc. It is
1045 periodically given commands (usually from the user) to make a change to
1046 the current window/frame state: i.e. create a new frame, delete a
1050 The buffer mechanism is responsible for keeping track of what buffers
1051 exist and what text is in them. It is periodically given commands
1052 (usually from the user) to insert or delete text, create a buffer, etc.
1053 When it receives a text-change command, it notifies the redisplay
1057 The redisplay mechanism is responsible for making sure that windows and
1058 frames are displayed correctly. It is periodically told (by the event
1059 loop) to actually ``do its job'', i.e. snoop around and see what the
1060 current state of the environment (mostly of the currently-existing
1061 windows, frames, and buffers) is, and make sure that that state matches
1062 what's actually displayed. It keeps lots and lots of information around
1063 (such as what is actually being displayed currently, and what the
1064 environment was last time it checked) so that it can minimize the work
1065 it has to do. It is also helped along in that whenever a relevant
1066 change to the environment occurs, the redisplay mechanism is told about
1067 this, so it has a pretty good idea of where it has to look to find
1068 possible changes and doesn't have to look everywhere.
1071 The Lisp engine is responsible for executing the Lisp code in which most
1072 user commands are written. It is entered through a call to @code{eval}
1073 or @code{funcall}, which occurs as a result of dispatching an event from
1074 the event loop. The functions it calls issue commands to the buffer
1075 mechanism, the window/frame subsystem, etc.
1078 The Lisp allocation subsystem is responsible for keeping track of Lisp
1079 objects. It is given commands from the Lisp engine to allocate objects,
1080 garbage collect, etc.
1085 The important idea here is that there are a number of independent
1086 subsystems each with its own responsibility and persistent state, just
1087 like different employees in a company, and each subsystem is
1088 periodically given commands from other subsystems. Commands can flow
1089 from any one subsystem to any other, but there is usually some sort of
1090 hierarchy, with all commands originating from the event subsystem.
1092 XEmacs is entered in @code{main()}, which is in @file{emacs.c}. When
1093 this is called the first time (in a properly-invoked @file{temacs}), it
1098 It does some very basic environment initializations, such as determining
1099 where it and its directories (e.g. @file{lisp/} and @file{etc/}) reside
1100 and setting up signal handlers.
1102 It initializes the entire Lisp interpreter.
1104 It sets the initial values of many built-in variables (including many
1105 variables that are visible to Lisp programs), such as the global keymap
1106 object and the built-in faces (a face is an object that describes the
1107 display characteristics of text). This involves creating Lisp objects
1108 and thus is dependent on step (2).
1110 It performs various other initializations that are relevant to the
1111 particular environment it is running in, such as retrieving environment
1112 variables, determining the current date and the user who is running the
1113 program, examining its standard input, creating any necessary file
1116 At this point, the C initialization is complete. A Lisp program that
1117 was specified on the command line (usually @file{loadup.el}) is called
1118 (temacs is normally invoked as @code{temacs -batch -l loadup.el dump}).
1119 @file{loadup.el} loads all of the other Lisp files that are needed for
1120 the operation of the editor, calls the @code{dump-emacs} function to
1121 write out @file{xemacs}, and then kills the temacs process.
1124 When @file{xemacs} is then run, it only redoes steps (1) and (4)
1125 above; all variables already contain the values they were set to when
1126 the executable was dumped, and all memory that was allocated with
1127 @code{malloc()} is still around. (XEmacs knows whether it is being run
1128 as @file{xemacs} or @file{temacs} because it sets the global variable
1129 @code{initialized} to 1 after step (4) above.) At this point,
1130 @file{xemacs} calls a Lisp function to do any further initialization,
1131 which includes parsing the command-line (the C code can only do limited
1132 command-line parsing, which includes looking for the @samp{-batch} and
1133 @samp{-l} flags and a few other flags that it needs to know about before
1134 initialization is complete), creating the first frame (or @dfn{window}
1135 in standard window-system parlance), running the user's init file
1136 (usually the file @file{.emacs} in the user's home directory), etc. The
1137 function to do this is usually called @code{normal-top-level};
1138 @file{loadup.el} tells the C code about this function by setting its
1139 name as the value of the Lisp variable @code{top-level}.
1141 When the Lisp initialization code is done, the C code enters the event
1142 loop, and stays there for the duration of the XEmacs process. The code
1143 for the event loop is contained in @file{keyboard.c}, and is called
1144 @code{Fcommand_loop_1()}. Note that this event loop could very well be
1145 written in Lisp, and in fact a Lisp version exists; but apparently,
1146 doing this makes XEmacs run noticeably slower.
1148 Notice how much of the initialization is done in Lisp, not in C.
1149 In general, XEmacs tries to move as much code as is possible
1150 into Lisp. Code that remains in C is code that implements the
1151 Lisp interpreter itself, or code that needs to be very fast, or
1152 code that needs to do system calls or other such stuff that
1153 needs to be done in C, or code that needs to have access to
1154 ``forbidden'' structures. (One conscious aspect of the design of
1155 Lisp under XEmacs is a clean separation between the external
1156 interface to a Lisp object's functionality and its internal
1157 implementation. Part of this design is that Lisp programs
1158 are forbidden from accessing the contents of the object other
1159 than through using a standard API. In this respect, XEmacs Lisp
1160 is similar to modern Lisp dialects but differs from GNU Emacs,
1161 which tends to expose the implementation and allow Lisp
1162 programs to look at it directly. The major advantage of
1163 hiding the implementation is that it allows the implementation
1164 to be redesigned without affecting any Lisp programs, including
1165 those that might want to be ``clever'' by looking directly at
1166 the object's contents and possibly manipulating them.)
1168 Moving code into Lisp makes the code easier to debug and maintain and
1169 makes it much easier for people who are not XEmacs developers to
1170 customize XEmacs, because they can make a change with much less chance
1171 of obscure and unwanted interactions occurring than if they were to
1174 @node The XEmacs Object System (Abstractly Speaking), How Lisp Objects Are Represented in C, XEmacs From the Inside, Top
1175 @chapter The XEmacs Object System (Abstractly Speaking)
1177 At the heart of the Lisp interpreter is its management of objects.
1178 XEmacs Lisp contains many built-in objects, some of which are
1179 simple and others of which can be very complex; and some of which
1180 are very common, and others of which are rarely used or are only
1181 used internally. (Since the Lisp allocation system, with its
1182 automatic reclamation of unused storage, is so much more convenient
1183 than @code{malloc()} and @code{free()}, the C code makes extensive use of it
1184 in its internal operations.)
1186 The basic Lisp objects are
1190 28 bits of precision, or 60 bits on 64-bit machines; the reason for this
1191 is described below when the internal Lisp object representation is
1194 Same precision as a double in C.
1196 A simple container for two Lisp objects, used to implement lists and
1197 most other data structures in Lisp.
1199 An object representing a single character of text; chars behave like
1200 integers in many ways but are logically considered text rather than
1201 numbers and have a different read syntax. (the read syntax for a char
1202 contains the char itself or some textual encoding of it -- for example,
1203 a Japanese Kanji character might be encoded as @samp{^[$(B#&^[(B} using the
1204 ISO-2022 encoding standard -- rather than the numerical representation
1205 of the char; this way, if the mapping between chars and integers
1206 changes, which is quite possible for Kanji characters and other extended
1207 characters, the same character will still be created. Note that some
1208 primitives confuse chars and integers. The worst culprit is @code{eq},
1209 which makes a special exception and considers a char to be @code{eq} to
1210 its integer equivalent, even though in no other case are objects of two
1211 different types @code{eq}. The reason for this monstrosity is
1212 compatibility with existing code; the separation of char from integer
1213 came fairly recently.)
1215 An object that contains Lisp objects and is referred to by name;
1216 symbols are used to implement variables and named functions
1217 and to provide the equivalent of preprocessor constants in C.
1219 A one-dimensional array of Lisp objects providing constant-time access
1220 to any of the objects; access to an arbitrary object in a vector is
1221 faster than for lists, but the operations that can be done on a vector
1224 Self-explanatory; behaves much like a vector of chars
1225 but has a different read syntax and is stored and manipulated
1226 more compactly and efficiently.
1228 A vector of bits; similar to a string in spirit.
1229 @item compiled-function
1230 An object describing compiled Lisp code, known as @dfn{byte code}.
1232 An object describing a Lisp primitive.
1236 Note that there is no basic ``function'' type, as in more powerful
1237 versions of Lisp (where it's called a @dfn{closure}). XEmacs Lisp does
1238 not provide the closure semantics implemented by Common Lisp and Scheme.
1239 The guts of a function in XEmacs Lisp are represented in one of four
1240 ways: a symbol specifying another function (when one function is an
1241 alias for another), a list containing the function's source code, a
1242 bytecode object, or a subr object. (In other words, given a symbol
1243 specifying the name of a function, calling @code{symbol-function} to
1244 retrieve the contents of the symbol's function cell will return one of
1245 these types of objects.)
1247 XEmacs Lisp also contains numerous specialized objects used to
1248 implement the editor:
1252 Stores text like a string, but is optimized for insertion and deletion
1253 and has certain other properties that can be set.
1255 An object with various properties whose displayable representation is a
1256 @dfn{window} in window-system parlance.
1258 A section of a frame that displays the contents of a buffer;
1259 often called a @dfn{pane} in window-system parlance.
1260 @item window-configuration
1261 An object that represents a saved configuration of windows in a frame.
1263 An object representing a screen on which frames can be displayed;
1264 equivalent to a @dfn{display} in the X Window System and a @dfn{TTY} in
1267 An object specifying the appearance of text or graphics; it contains
1268 characteristics such as font, foreground color, and background color.
1270 An object that refers to a particular position in a buffer and moves
1271 around as text is inserted and deleted to stay in the same relative
1272 position to the text around it.
1274 Similar to a marker but covers a range of text in a buffer; can also
1275 specify properties of the text, such as a face in which the text is to
1276 be displayed, whether the text is invisible or unmodifiable, etc.
1278 Generated by calling @code{next-event} and contains information
1279 describing a particular event happening in the system, such as the user
1280 pressing a key or a process terminating.
1282 An object that maps from events (described using lists, vectors, and
1283 symbols rather than with an event object because the mapping is for
1284 classes of events, rather than individual events) to functions to
1285 execute or other events to recursively look up; the functions are
1286 described by name, using a symbol, or using lists to specify the
1289 An object that describes the appearance of an image (e.g. pixmap) on
1290 the screen; glyphs can be attached to the beginning or end of extents
1291 and in some future version of XEmacs will be able to be inserted
1292 directly into a buffer.
1294 An object that describes a connection to an externally-running process.
1297 There are some other, less-commonly-encountered general objects:
1301 An object that maps from an arbitrary Lisp object to another arbitrary
1302 Lisp object, using hashing for fast lookup.
1304 A limited form of hashtable that maps from strings to symbols; obarrays
1305 are used to look up a symbol given its name and are not actually their
1306 own object type but are kludgily represented using vectors with hidden
1307 fields (this representation derives from GNU Emacs).
1309 A complex object used to specify the value of a display property; a
1310 default value is given and different values can be specified for
1311 particular frames, buffers, windows, devices, or classes of device.
1313 An object that maps from chars or classes of chars to arbitrary Lisp
1314 objects; internally char tables use a complex nested-vector
1315 representation that is optimized to the way characters are represented
1318 An object that maps from ranges of integers to arbitrary Lisp objects.
1321 And some strange special-purpose objects:
1325 @itemx coding-system
1326 Objects used when MULE, or multi-lingual/Asian-language, support is
1328 @item color-instance
1329 @itemx font-instance
1330 @itemx image-instance
1331 An object that encapsulates a window-system resource; instances are
1332 mostly used internally but are exposed on the Lisp level for cleanness
1333 of the specifier model and because it's occasionally useful for Lisp
1334 program to create or query the properties of instances.
1336 An object that encapsulate a @dfn{subwindow} resource, i.e. a
1337 window-system child window that is drawn into by an external process;
1338 this object should be integrated into the glyph system but isn't yet,
1339 and may change form when this is done.
1340 @item tooltalk-message
1341 @itemx tooltalk-pattern
1342 Objects that represent resources used in the ToolTalk interprocess
1343 communication protocol.
1344 @item toolbar-button
1345 An object used in conjunction with the toolbar.
1347 An object that encapsulates certain miscellaneous resources in the X
1348 window system, used only when Epoch support is enabled.
1351 And objects that are only used internally:
1355 A generic object for encapsulating arbitrary memory; this allows you the
1356 generality of @code{malloc()} and the convenience of the Lisp object
1359 A buffering I/O stream, used to provide a unified interface to anything
1360 that can accept output or provide input, such as a file descriptor, a
1361 stdio stream, a chunk of memory, a Lisp buffer, a Lisp string, etc.;
1362 it's a Lisp object to make its memory management more convenient.
1363 @item char-table-entry
1364 Subsidiary objects in the internal char-table representation.
1365 @item extent-auxiliary
1368 Various special-purpose objects that are basically just used to
1369 encapsulate memory for particular subsystems, similar to the more
1370 general ``opaque'' object.
1371 @item symbol-value-forward
1372 @itemx symbol-value-buffer-local
1373 @itemx symbol-value-varalias
1374 @itemx symbol-value-lisp-magic
1375 Special internal-only objects that are placed in the value cell of a
1376 symbol to indicate that there is something special with this variable --
1377 e.g. it has no value, it mirrors another variable, or it mirrors some C
1378 variable; there is really only one kind of object, called a
1379 @dfn{symbol-value-magic}, but it is sort-of halfway kludged into
1380 semi-different object types.
1383 @cindex permanent objects
1384 @cindex temporary objects
1385 Some types of objects are @dfn{permanent}, meaning that once created,
1386 they do not disappear until explicitly destroyed, using a function such
1387 as @code{delete-buffer}, @code{delete-window}, @code{delete-frame}, etc.
1388 Others will disappear once they are not longer used, through the garbage
1389 collection mechanism. Buffers, frames, windows, devices, and processes
1390 are among the objects that are permanent. Note that some objects can go
1391 both ways: Faces can be created either way; extents are normally
1392 permanent, but detached extents (extents not referring to any text, as
1393 happens to some extents when the text they are referring to is deleted)
1394 are temporary. Note that some permanent objects, such as faces and
1395 coding systems, cannot be deleted. Note also that windows are unique in
1396 that they can be @emph{undeleted} after having previously been
1397 deleted. (This happens as a result of restoring a window configuration.)
1400 Note that many types of objects have a @dfn{read syntax}, i.e. a way of
1401 specifying an object of that type in Lisp code. When you load a Lisp
1402 file, or type in code to be evaluated, what really happens is that the
1403 function @code{read} is called, which reads some text and creates an object
1404 based on the syntax of that text; then @code{eval} is called, which
1405 possibly does something special; then this loop repeats until there's
1406 no more text to read. (@code{eval} only actually does something special
1407 with symbols, which causes the symbol's value to be returned,
1408 similar to referencing a variable; and with conses [i.e. lists],
1409 which cause a function invocation. All other values are returned
1418 converts to an integer whose value is 17297.
1424 converts to a float whose value is 1983.23e-4, or .0001983.
1430 converts to a char that represents the lowercase letter b.
1436 (where @samp{^[} actually is an @samp{ESC} character) converts to a
1437 particular Kanji character when using an ISO2022-based coding system for
1438 input. (To decode this gook: @samp{ESC} begins an escape sequence;
1439 @samp{ESC $ (} is a class of escape sequences meaning ``switch to a
1440 94x94 character set''; @samp{ESC $ ( B} means ``switch to Japanese
1441 Kanji''; @samp{#} and @samp{&} collectively index into a 94-by-94 array
1442 of characters [subtract 33 from the ASCII value of each character to get
1443 the corresponding index]; @samp{ESC (} is a class of escape sequences
1444 meaning ``switch to a 94 character set''; @samp{ESC (B} means ``switch
1445 to US ASCII''. It is a coincidence that the letter @samp{B} is used to
1446 denote both Japanese Kanji and US ASCII. If the first @samp{B} were
1447 replaced with an @samp{A}, you'd be requesting a Chinese Hanzi character
1448 from the GB2312 character set.)
1454 converts to a string.
1460 converts to a symbol whose name is @code{"foobar"}. This is done by
1461 looking up the string equivalent in the global variable
1462 @code{obarray}, whose contents should be an obarray. If no symbol
1463 is found, a new symbol with the name @code{"foobar"} is automatically
1464 created and added to @code{obarray}; this process is called
1465 @dfn{interning} the symbol.
1472 converts to a cons cell containing the symbols @code{foo} and @code{bar}.
1478 converts to a three-element list containing the specified objects
1479 (note that a list is actually a set of nested conses; see the
1480 XEmacs Lisp Reference).
1486 converts to a three-element vector containing the specified objects.
1492 converts to a compiled-function object (the actual contents are not
1493 shown since they are not relevant here; look at a file that ends with
1494 @file{.elc} for examples).
1500 converts to a bit-vector.
1503 #s(range-table ... ...)
1506 converts to a range table (the actual contents are not shown).
1509 #s(char-table ... ...)
1512 converts to a char table (the actual contents are not shown).
1513 (Note that the #s syntax is the general syntax for structures,
1514 which are not really implemented in XEmacs Lisp but should be.)
1516 When an object is printed out (using @code{print} or a related
1517 function), the read syntax is used, so that the same object can be read
1520 The other objects do not have read syntaxes, usually because it does
1521 not really make sense to create them in this fashion (i.e. processes,
1522 where it doesn't make sense to have a subprocess created as a side
1523 effect of reading some Lisp code), or because they can't be created at
1524 all (e.g. subrs). Permanent objects, as a rule, do not have a read
1525 syntax; nor do most complex objects, which contain too much state to be
1526 easily initialized through a read syntax.
1528 @node How Lisp Objects Are Represented in C, Rules When Writing New C Code, The XEmacs Object System (Abstractly Speaking), Top
1529 @chapter How Lisp Objects Are Represented in C
1531 Lisp objects are represented in C using a 32- or 64-bit machine word
1532 (depending on the processor; i.e. DEC Alphas use 64-bit Lisp objects and
1533 most other processors use 32-bit Lisp objects). The representation
1534 stuffs a pointer together with a tag, as follows:
1537 [ 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 ]
1538 [ 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 ]
1540 ^ <---> <------------------------------------------------------>
1541 | tag a pointer to a structure, or an integer
1546 The tag describes the type of the Lisp object. For integers and
1547 chars, the lower 28 bits contain the value of the integer or char; for
1548 all others, the lower 28 bits contain a pointer. The mark bit is used
1549 during garbage-collection, and is always 0 when garbage collection is
1550 not happening. Many macros that extract out parts of a Lisp object
1551 expect that the mark bit is 0, and will produce incorrect results if
1552 it's not. (The way that garbage collection works, basically, is that it
1553 loops over all places where Lisp objects could exist -- this includes
1554 all global variables in C that contain Lisp objects [including
1555 @code{Vobarray}, the C equivalent of @code{obarray}; through this, all
1556 Lisp variables will get marked], plus various other places -- and
1557 recursively scans through the Lisp objects, marking each object it finds
1558 by setting the mark bit. Then it goes through the lists of all objects
1559 allocated, freeing the ones that are not marked and turning off the
1560 mark bit of the ones that are marked.)
1562 Lisp objects use the typedef @code{Lisp_Object}, but the actual C type
1563 used for the Lisp object can vary. It can be either a simple type
1564 (@code{long} on the DEC Alpha, @code{int} on other machines) or a
1565 structure whose fields are bit fields that line up properly (actually, a
1566 union of structures that's used). Generally the simple integral type is
1567 preferable because it ensures that the compiler will actually use a
1568 machine word to represent the object (some compilers will use more
1569 general and less efficient code for unions and structs even if they can
1570 fit in a machine word). The union type, however, has the advantage of
1571 stricter type checking (if you accidentally pass an integer where a Lisp
1572 object is desired, you get a compile error), and it makes it easier to
1573 decode Lisp objects when debugging. The choice of which type to use is
1574 determined by the presence or absence of the preprocessor constant
1575 @code{USE_UNION_TYPE}.
1578 Note that there are only eight types that the tag can represent,
1579 but many more actual types than this. This is handled by having
1580 one of the tag types specify a meta-type called a @dfn{record};
1581 for all such objects, the first four bytes of the pointed-to
1582 structure indicate what the actual type is.
1584 Note also that having 28 bits for pointers and integers restricts a
1585 lot of things to 256 megabytes of memory. (Basically, enough pointers
1586 and indices and whatnot get stuffed into Lisp objects that the total
1587 amount of memory used by XEmacs can't grow above 256 megabytes. In
1588 older versions of XEmacs and GNU Emacs, the tag was 5 bits wide,
1589 allowing for 32 types, which was more than the actual number of types
1590 that existed at the time, and no ``record'' type was necessary.
1591 However, this limited the editor to 64 megabytes total, which some users
1592 who edited large files might conceivably exceed.)
1594 Also, note that there is an implicit assumption here that all pointers
1595 are low enough that the top bits are all zero and can just be chopped
1596 off. On standard machines that allocate memory from the bottom up (and
1597 give each process its own address space), this works fine. Some
1598 machines, however, put the data space somewhere else in memory
1599 (e.g. beginning at 0x80000000). Those machines cope by defining
1600 @code{DATA_SEG_BITS} in the corresponding @file{m/} or @file{s/} file to
1601 the proper mask. Then, pointers retrieved from Lisp objects are
1602 automatically OR'ed with this value prior to being used.
1604 A corollary of the previous paragraph is that @strong{(pointers to)
1605 stack-allocated structures cannot be put into Lisp objects}. The stack
1606 is generally located near the top of memory; if you put such a pointer
1607 into a Lisp object, it will get its top bits chopped off, and you will
1610 Various macros are used to construct Lisp objects and extract the
1611 components. Macros of the form @code{XINT()}, @code{XCHAR()},
1612 @code{XSTRING()}, @code{XSYMBOL()}, etc. mask out the pointer/integer
1613 field and cast it to the appropriate type. All of the macros that
1614 construct pointers will @code{OR} with @code{DATA_SEG_BITS} if
1615 necessary. @code{XINT()} needs to be a bit tricky so that negative
1616 numbers are properly sign-extended: Usually it does this by shifting the
1617 number four bits to the left and then four bits to the right. This
1618 assumes that the right-shift operator does an arithmetic shift (i.e. it
1619 leaves the most-significant bit as-is rather than shifting in a zero, so
1620 that it mimics a divide-by-two even for negative numbers). Not all
1621 machines/compilers do this, and on the ones that don't, a more
1622 complicated definition is selected by defining
1623 @code{EXPLICIT_SIGN_EXTEND}.
1625 Note that when @code{ERROR_CHECK_TYPECHECK} is defined, the extractor
1626 macros become more complicated -- they check the tag bits and/or the
1627 type field in the first four bytes of a record type to ensure that the
1628 object is really of the correct type. This is great for catching places
1629 where an incorrect type is being dereferenced -- this typically results
1630 in a pointer being dereferenced as the wrong type of structure, with
1631 unpredictable (and sometimes not easily traceable) results.
1633 There are similar @code{XSET@var{TYPE}()} macros that construct a Lisp object.
1634 These macros are of the form @code{XSET@var{TYPE} (@var{lvalue}, @var{result})},
1635 i.e. they have to be a statement rather than just used in an expression.
1636 The reason for this is that standard C doesn't let you ``construct'' a
1637 structure (but GCC does). Granted, this sometimes isn't too convenient;
1638 for the case of integers, at least, you can use the function
1639 @code{make_int()}, which constructs and @emph{returns} an integer
1640 Lisp object. Note that the @code{XSET@var{TYPE}()} macros are also
1641 affected by @code{ERROR_CHECK_TYPECHECK} and make sure that the
1642 structure is of the right type in the case of record types, where the
1643 type is contained in the structure.
1645 @node Rules When Writing New C Code, A Summary of the Various XEmacs Modules, How Lisp Objects Are Represented in C, Top
1646 @chapter Rules When Writing New C Code
1648 The XEmacs C Code is extremely complex and intricate, and there are
1649 many rules that are more or less consistently followed throughout the code.
1650 Many of these rules are not obvious, so they are explained here. It is
1651 of the utmost importance that you follow them. If you don't, you may get
1652 something that appears to work, but which will crash in odd situations,
1653 often in code far away from where the actual breakage is.
1656 * General Coding Rules::
1657 * Writing Lisp Primitives::
1658 * Adding Global Lisp Variables::
1660 * Techniques for XEmacs Developers::
1663 @node General Coding Rules
1664 @section General Coding Rules
1666 Almost every module contains a @code{syms_of_*()} function and a
1667 @code{vars_of_*()} function. The former declares any Lisp primitives
1668 you have defined and defines any symbols you will be using. The latter
1669 declares any global Lisp variables you have added and initializes global
1670 C variables in the module. For each such function, declare it in
1671 @file{symsinit.h} and make sure it's called in the appropriate place in
1672 @file{emacs.c}. @strong{Important}: There are stringent requirements on
1673 exactly what can go into these functions. See the comment in
1674 @file{emacs.c}. The reason for this is to avoid obscure unwanted
1675 interactions during initialization. If you don't follow these rules,
1676 you'll be sorry! If you want to do anything that isn't allowed, create
1677 a @code{complex_vars_of_*()} function for it. Doing this is tricky,
1678 though: You have to make sure your function is called at the right time
1679 so that all the initialization dependencies work out.
1681 Every module includes @file{<config.h>} (angle brackets so that
1682 @samp{--srcdir} works correctly; @file{config.h} may or may not be in
1683 the same directory as the C sources) and @file{lisp.h}. @file{config.h}
1684 should always be included before any other header files (including
1685 system header files) to ensure that certain tricks played by various
1686 @file{s/} and @file{m/} files work out correctly.
1688 @strong{All global and static variables that are to be modifiable must
1689 be declared uninitialized.} This means that you may not use the ``declare
1690 with initializer'' form for these variables, such as @code{int
1691 some_variable = 0;}. The reason for this has to do with some kludges
1692 done during the dumping process: If possible, the initialized data
1693 segment is re-mapped so that it becomes part of the (unmodifiable) code
1694 segment in the dumped executable. This allows this memory to be shared
1695 among multiple running XEmacs processes. XEmacs is careful to place as
1696 much constant data as possible into initialized variables (in
1697 particular, into what's called the @dfn{pure space} -- see below) during
1698 the @file{temacs} phase.
1700 @cindex copy-on-write
1701 @strong{Please note:} This kludge only works on a few systems
1702 nowadays, and is rapidly becoming irrelevant because most modern
1703 operating systems provide @dfn{copy-on-write} semantics. All data is
1704 initially shared between processes, and a private copy is automatically
1705 made (on a page-by-page basis) when a process first attempts to write to
1708 Formerly, there was a requirement that static variables not be
1709 declared inside of functions. This had to do with another hack along
1710 the same vein as what was just described: old USG systems put
1711 statically-declared variables in the initialized data space, so those
1712 header files had a @code{#define static} declaration. (That way, the
1713 data-segment remapping described above could still work.) This fails
1714 badly on static variables inside of functions, which suddenly become
1715 automatic variables; therefore, you weren't supposed to have any of
1716 them. This awful kludge has been removed in XEmacs because
1720 almost all of the systems that used this kludge ended up having
1721 to disable the data-segment remapping anyway;
1723 the only systems that didn't were extremely outdated ones;
1725 this hack completely messed up inline functions.
1728 @node Writing Lisp Primitives
1729 @section Writing Lisp Primitives
1731 Lisp primitives are Lisp functions implemented in C. The details of
1732 interfacing the C function so that Lisp can call it are handled by a few
1733 C macros. The only way to really understand how to write new C code is
1734 to read the source, but we can explain some things here.
1736 An example of a special form is the definition of @code{or}, from
1737 @file{eval.c}. (An ordinary function would have the same general
1740 @cindex garbage collection protection
1743 DEFUN ("or", For, 0, UNEVALLED, 0, /*
1744 Eval args until one of them yields non-nil, then return that value.
1745 The remaining args are not evalled at all.
1746 If all args return nil, return nil.
1750 /* This function can GC */
1751 Lisp_Object val = Qnil;
1752 struct gcpro gcpro1;
1756 while (!NILP (args))
1758 val = Feval (XCAR (args));
1770 Let's start with a precise explanation of the arguments to the
1771 @code{DEFUN} macro. Here is a template for them:
1774 DEFUN (@var{lname}, @var{fname}, @var{min}, @var{max}, @var{interactive}, /*
1782 This string is the name of the Lisp symbol to define as the function
1783 name; in the example above, it is @code{"or"}.
1786 This is the C function name for this function. This is the name that is
1787 used in C code for calling the function. The name is, by convention,
1788 @samp{F} prepended to the Lisp name, with all dashes (@samp{-}) in the
1789 Lisp name changed to underscores. Thus, to call this function from C
1790 code, call @code{For}. Remember that the arguments are of type
1791 @code{Lisp_Object}; various macros and functions for creating values of
1792 type @code{Lisp_Object} are declared in the file @file{lisp.h}.
1794 Primitives whose names are special characters (e.g. @code{+} or
1795 @code{<}) are named by spelling out, in some fashion, the special
1796 character: e.g. @code{Fplus()} or @code{Flss()}. Primitives whose names
1797 begin with normal alphanumeric characters but also contain special
1798 characters are spelled out in some creative way, e.g. @code{let*}
1799 becomes @code{FletX()}.
1801 Each function also has an associated structure that holds the data for
1802 the subr object that represents the function in Lisp. This structure
1803 conveys the Lisp symbol name to the initialization routine that will
1804 create the symbol and store the subr object as its definition. The C
1805 variable name of this structure is always @samp{S} prepended to the
1806 @var{fname}. You hardly ever need to be aware of the existence of this
1810 This is the minimum number of arguments that the function requires. The
1811 function @code{or} allows a minimum of zero arguments.
1814 This is the maximum number of arguments that the function accepts, if
1815 there is a fixed maximum. Alternatively, it can be @code{UNEVALLED},
1816 indicating a special form that receives unevaluated arguments, or
1817 @code{MANY}, indicating an unlimited number of evaluated arguments (the
1818 equivalent of @code{&rest}). Both @code{UNEVALLED} and @code{MANY} are
1819 macros. If @var{max} is a number, it may not be less than @var{min} and
1820 it may not be greater than 8. (If you need to add a function with
1821 more than 8 arguments, either use the @code{MANY} form or edit the
1822 definition of @code{DEFUN} in @file{lisp.h}. If you do the latter,
1823 make sure to also add another clause to the switch statement in
1824 @code{primitive_funcall().})
1827 This is an interactive specification, a string such as might be used as
1828 the argument of @code{interactive} in a Lisp function. In the case of
1829 @code{or}, it is 0 (a null pointer), indicating that @code{or} cannot be
1830 called interactively. A value of @code{""} indicates a function that
1831 should receive no arguments when called interactively.
1834 This is the documentation string. It is written just like a
1835 documentation string for a function defined in Lisp; in particular, the
1836 first line should be a single sentence. Note how the documentation
1837 string is enclosed in a comment, none of the documentation is placed on
1838 the same lines as the comment-start and comment-end characters, and the
1839 comment-start characters are on the same line as the interactive
1840 specification. @file{make-docfile}, which scans the C files for
1841 documentation strings, is very particular about what it looks for, and
1842 will not properly extract the doc string if it's not in this exact format.
1844 You are free to put the various arguments to @code{DEFUN} on separate
1845 lines to avoid overly long lines. However, make sure to put the
1846 comment-start characters for the doc string on the same line as the
1847 interactive specification, and put a newline directly after them (and
1848 before the comment-end characters).
1851 This is the comma-separated list of arguments to the C function. For a
1852 function with a fixed maximum number of arguments, provide a C argument
1853 for each Lisp argument. In this case, unlike regular C functions, the
1854 types of the arguments are not declared; they are simply always of type
1857 The names of the C arguments will be used as the names of the arguments
1858 to the Lisp primitive as displayed in its documentation, modulo the same
1859 concerns described above for @code{F...} names (in particular,
1860 underscores in the C arguments become dashes in the Lisp arguments).
1862 There is one additional kludge: A trailing `_' on the C argument is
1863 discarded when forming the Lisp argument. This allows C language
1864 reserved words (like @code{default}) or global symbols (like
1865 @code{dirname}) to be used as argument names without compiler warnings
1868 A Lisp function with @w{@var{max} = @code{UNEVALLED}} is a
1869 @w{@dfn{special form}}; its arguments are not evaluated. Instead it
1870 receives one argument of type @code{Lisp_Object}, a (Lisp) list of the
1871 unevaluated arguments, conventionally named @code{(args)}.
1873 When a Lisp function has no upper limit on the number of arguments,
1874 specify @w{@var{max} = @code{MANY}}. In this case its implementation in
1875 C actually receives exactly two arguments: the number of Lisp arguments
1876 (an @code{int}) and the address of a block containing their values (a
1877 @w{@code{Lisp_Object *}}). In this case only are the C types specified
1878 in the @var{arglist}: @w{@code{(int nargs, Lisp_Object *args)}}.
1882 Within the function @code{For} itself, note the use of the macros
1883 @code{GCPRO1} and @code{UNGCPRO}. @code{GCPRO1} is used to ``protect''
1884 a variable from garbage collection---to inform the garbage collector
1885 that it must look in that variable and regard its contents as an
1886 accessible object. This is necessary whenever you call @code{Feval} or
1887 anything that can directly or indirectly call @code{Feval} (this
1888 includes the @code{QUIT} macro!). At such a time, any Lisp object that
1889 you intend to refer to again must be protected somehow. @code{UNGCPRO}
1890 cancels the protection of the variables that are protected in the
1891 current function. It is necessary to do this explicitly.
1893 The macro @code{GCPRO1} protects just one local variable. If you want
1894 to protect two, use @code{GCPRO2} instead; repeating @code{GCPRO1} will
1895 not work. Macros @code{GCPRO3} and @code{GCPRO4} also exist.
1897 These macros implicitly use local variables such as @code{gcpro1}; you
1898 must declare these explicitly, with type @code{struct gcpro}. Thus, if
1899 you use @code{GCPRO2}, you must declare @code{gcpro1} and @code{gcpro2}.
1901 @cindex caller-protects (@code{GCPRO} rule)
1902 Note also that the general rule is @dfn{caller-protects}; i.e. you
1903 are only responsible for protecting those Lisp objects that you create.
1904 Any objects passed to you as parameters should have been protected
1905 by whoever created them, so you don't in general have to protect them.
1906 @code{For} is an exception; it protects its parameters to provide
1907 extra assurance against Lisp primitives elsewhere that are incorrectly
1908 written, and against malicious self-modifying code. There are a few
1909 other standard functions that also do this.
1911 @code{GCPRO}ing is perhaps the trickiest and most error-prone part
1912 of XEmacs coding. It is @strong{extremely} important that you get this
1913 right and use a great deal of discipline when writing this code.
1914 @xref{GCPROing, ,@code{GCPRO}ing}, for full details on how to do this.
1916 What @code{DEFUN} actually does is declare a global structure of
1917 type @code{Lisp_Subr} whose name begins with capital @samp{SF} and
1918 which contains information about the primitive (e.g. a pointer to the
1919 function, its minimum and maximum allowed arguments, a string describing
1920 its Lisp name); @code{DEFUN} then begins a normal C function
1921 declaration using the @code{F...} name. The Lisp subr object that is
1922 the function definition of a primitive (i.e. the object in the function
1923 slot of the symbol that names the primitive) actually points to this
1924 @samp{SF} structure; when @code{Feval} encounters a subr, it looks in the
1925 structure to find out how to call the C function.
1927 Defining the C function is not enough to make a Lisp primitive
1928 available; you must also create the Lisp symbol for the primitive (the
1929 symbol is @dfn{interned}; @pxref{Obarrays}) and store a suitable subr
1930 object in its function cell. (If you don't do this, the primitive won't
1931 be seen by Lisp code.) The code looks like this:
1934 DEFSUBR (@var{fname});
1938 Here @var{fname} is the name you used as the second argument to
1941 This call to @code{DEFSUBR} should go in the @code{syms_of_*()}
1942 function at the end of the module. If no such function exists, create
1943 it and make sure to also declare it in @file{symsinit.h} and call it
1944 from the appropriate spot in @code{main()}. @xref{General Coding
1947 Note that C code cannot call functions by name unless they are defined
1948 in C. The way to call a function written in Lisp from C is to use
1949 @code{Ffuncall}, which embodies the Lisp function @code{funcall}. Since
1950 the Lisp function @code{funcall} accepts an unlimited number of
1951 arguments, in C it takes two: the number of Lisp-level arguments, and a
1952 one-dimensional array containing their values. The first Lisp-level
1953 argument is the Lisp function to call, and the rest are the arguments to
1954 pass to it. Since @code{Ffuncall} can call the evaluator, you must
1955 protect pointers from garbage collection around the call to
1956 @code{Ffuncall}. (However, @code{Ffuncall} explicitly protects all of
1957 its parameters, so you don't have to protect any pointers passed
1958 as parameters to it.)
1960 The C functions @code{call0}, @code{call1}, @code{call2}, and so on,
1961 provide handy ways to call a Lisp function conveniently with a fixed
1962 number of arguments. They work by calling @code{Ffuncall}.
1964 @file{eval.c} is a very good file to look through for examples;
1965 @file{lisp.h} contains the definitions for some important macros and
1968 @node Adding Global Lisp Variables
1969 @section Adding Global Lisp Variables
1971 Global variables whose names begin with @samp{Q} are constants whose
1972 value is a symbol of a particular name. The name of the variable should
1973 be derived from the name of the symbol using the same rules as for Lisp
1974 primitives. These variables are initialized using a call to
1975 @code{defsymbol()} in the @code{syms_of_*()} function. (This call
1976 interns a symbol, sets the C variable to the resulting Lisp object, and
1977 calls @code{staticpro()} on the C variable to tell the
1978 garbage-collection mechanism about this variable. What
1979 @code{staticpro()} does is add a pointer to the variable to a large
1980 global array; when garbage-collection happens, all pointers listed in
1981 the array are used as starting points for marking Lisp objects. This is
1982 important because it's quite possible that the only current reference to
1983 the object is the C variable. In the case of symbols, the
1984 @code{staticpro()} doesn't matter all that much because the symbol is
1985 contained in @code{obarray}, which is itself @code{staticpro()}ed.
1986 However, it's possible that a naughty user could do something like
1987 uninterning the symbol out of @code{obarray} or even setting
1988 @code{obarray} to a different value [although this is likely to make
1991 @strong{Please note:} It is potentially deadly if you declare a
1992 @samp{Q...} variable in two different modules. The two calls to
1993 @code{defsymbol()} are no problem, but some linkers will complain about
1994 multiply-defined symbols. The most insidious aspect of this is that
1995 often the link will succeed anyway, but then the resulting executable
1996 will sometimes crash in obscure ways during certain operations! To
1997 avoid this problem, declare any symbols with common names (such as
1998 @code{text}) that are not obviously associated with this particular
1999 module in the module @file{general.c}.
2001 Global variables whose names begin with @samp{V} are variables that
2002 contain Lisp objects. The convention here is that all global variables
2003 of type @code{Lisp_Object} begin with @samp{V}, and all others don't
2004 (including integer and boolean variables that have Lisp
2005 equivalents). Most of the time, these variables have equivalents in
2006 Lisp, but some don't. Those that do are declared this way by a call to
2007 @code{DEFVAR_LISP()} in the @code{vars_of_*()} initializer for the
2008 module. What this does is create a special @dfn{symbol-value-forward}
2009 Lisp object that contains a pointer to the C variable, intern a symbol
2010 whose name is as specified in the call to @code{DEFVAR_LISP()}, and set
2011 its value to the symbol-value-forward Lisp object; it also calls
2012 @code{staticpro()} on the C variable to tell the garbage-collection
2013 mechanism about the variable. When @code{eval} (or actually
2014 @code{symbol-value}) encounters this special object in the process of
2015 retrieving a variable's value, it follows the indirection to the C
2016 variable and gets its value. @code{setq} does similar things so that
2017 the C variable gets changed.
2019 Whether or not you @code{DEFVAR_LISP()} a variable, you need to
2020 initialize it in the @code{vars_of_*()} function; otherwise it will end
2021 up as all zeroes, which is the integer 0 (@emph{not} @code{nil}), and
2022 this is probably not what you want. Also, if the variable is not
2023 @code{DEFVAR_LISP()}ed, @strong{you must call} @code{staticpro()} on the
2024 C variable in the @code{vars_of_*()} function. Otherwise, the
2025 garbage-collection mechanism won't know that the object in this variable
2026 is in use, and will happily collect it and reuse its storage for another
2027 Lisp object, and you will be the one who's unhappy when you can't figure
2028 out how your variable got overwritten.
2030 @node Coding for Mule
2031 @section Coding for Mule
2032 @cindex Coding for Mule
2034 Although Mule support is not compiled by default in XEmacs, many people
2035 are using it, and we consider it crucial that new code works correctly
2036 with multibyte characters. This is not hard; it is only a matter of
2037 following several simple user-interface guidelines. Even if you never
2038 compile with Mule, with a little practice you will find it quite easy
2039 to code Mule-correctly.
2041 Note that these guidelines are not necessarily tied to the current Mule
2042 implementation; they are also a good idea to follow on the grounds of
2043 code generalization for future I18N work.
2046 * Character-Related Data Types::
2047 * Working With Character and Byte Positions::
2048 * Conversion of External Data::
2049 * General Guidelines for Writing Mule-Aware Code::
2050 * An Example of Mule-Aware Code::
2053 @node Character-Related Data Types
2054 @subsection Character-Related Data Types
2056 First, we will list the basic character-related datatypes used by
2057 XEmacs. Note that the separate @code{typedef}s are not required for the
2058 code to work (all of them boil down to @code{unsigned char} or
2059 @code{int}), but they improve clarity of code a great deal, because one
2060 glance at the declaration can tell the intended use of the variable.
2065 An @code{Emchar} holds a single Emacs character.
2067 Obviously, the equality between characters and bytes is lost in the Mule
2068 world. Characters can be represented by one or more bytes in the
2069 buffer, and @code{Emchar} is the C type large enough to hold any
2072 Without Mule support, an @code{Emchar} is equivalent to an
2073 @code{unsigned char}.
2077 The data representing the text in a buffer or string is logically a set
2080 XEmacs does not work with character formats all the time; when reading
2081 characters from the outside, it decodes them to an internal format, and
2082 likewise encodes them when writing. @code{Bufbyte} (in fact
2083 @code{unsigned char}) is the basic unit of XEmacs internal buffers and
2086 One character can correspond to one or more @code{Bufbyte}s. In the
2087 current implementation, an ASCII character is represented by the same
2088 @code{Bufbyte}, and extended characters are represented by a sequence of
2091 Without Mule support, a @code{Bufbyte} is equivalent to an
2096 A @code{Bufpos} represents a character position in a buffer or string.
2097 A @code{Charcount} represents a number (count) of characters.
2098 Logically, subtracting two @code{Bufpos} values yields a
2099 @code{Charcount} value. Although all of these are @code{typedef}ed to
2100 @code{int}, we use them in preference to @code{int} to make it clear
2101 what sort of position is being used.
2103 @code{Bufpos} and @code{Charcount} values are the only ones that are
2104 ever visible to Lisp.
2108 A @code{Bytind} represents a byte position in a buffer or string. A
2109 @code{Bytecount} represents the distance between two positions in bytes.
2110 The relationship between @code{Bytind} and @code{Bytecount} is the same
2111 as the relationship between @code{Bufpos} and @code{Charcount}.
2115 When dealing with the outside world, XEmacs works with @code{Extbyte}s,
2116 which are equivalent to @code{unsigned char}. Obviously, an
2117 @code{Extcount} is the distance between two @code{Extbyte}s. Extbytes
2118 and Extcounts are not all that frequent in XEmacs code.
2121 @node Working With Character and Byte Positions
2122 @subsection Working With Character and Byte Positions
2124 Now that we have defined the basic character-related types, we can look
2125 at the macros and functions designed for work with them and for
2126 conversion between them. Most of these macros are defined in
2127 @file{buffer.h}, and we don't discuss all of them here, but only the
2128 most important ones. Examining the existing code is the best way to
2132 @item MAX_EMCHAR_LEN
2133 This preprocessor constant is the maximum number of buffer bytes per
2134 Emacs character, i.e. the byte length of an @code{Emchar}. It is useful
2135 when allocating temporary strings to keep a known number of characters.
2144 /* Allocate place for @var{cclen} characters. */
2145 Bufbyte *tmp_buf = (Bufbyte *)alloca (cclen * MAX_EMCHAR_LEN);
2150 If you followed the previous section, you can guess that, logically,
2151 multiplying a @code{Charcount} value with @code{MAX_EMCHAR_LEN} produces
2152 a @code{Bytecount} value.
2154 In the current Mule implementation, @code{MAX_EMCHAR_LEN} equals 4.
2155 Without Mule, it is 1.
2157 @item charptr_emchar
2158 @item set_charptr_emchar
2159 @code{charptr_emchar} macro takes a @code{Bufbyte} pointer and returns
2160 the underlying @code{Emchar}. If it were a function, its prototype
2164 Emchar charptr_emchar (Bufbyte *p);
2167 @code{set_charptr_emchar} stores an @code{Emchar} to the specified byte
2168 position. It returns the number of bytes stored:
2171 Bytecount set_charptr_emchar (Bufbyte *p, Emchar c);
2174 It is important to note that @code{set_charptr_emchar} is safe only for
2175 appending a character at the end of a buffer, not for overwriting a
2176 character in the middle. This is because the width of characters
2177 varies, and @code{set_charptr_emchar} cannot resize the string if it
2178 writes, say, a two-byte character where a single-byte character used to
2181 A typical use of @code{set_charptr_emchar} can be demonstrated by this
2182 example, which copies characters from buffer @var{buf} to a temporary
2189 for (pos = beg; pos < end; pos++)
2191 Emchar c = BUF_FETCH_CHAR (buf, pos);
2192 p += set_charptr_emchar (buf, c);
2198 Note how @code{set_charptr_emchar} is used to store the @code{Emchar}
2199 and increment the counter, at the same time.
2203 These two macros increment and decrement a @code{Bufbyte} pointer,
2204 respectively. The pointer needs to be correctly positioned at the
2205 beginning of a valid character position.
2207 Without Mule support, @code{INC_CHARPTR (p)} and @code{DEC_CHARPTR (p)}
2208 simply expand to @code{p++} and @code{p--}, respectively.
2210 @item bytecount_to_charcount
2211 Given a pointer to a text string and a length in bytes, return the
2212 equivalent length in characters.
2215 Charcount bytecount_to_charcount (Bufbyte *p, Bytecount bc);
2218 @item charcount_to_bytecount
2219 Given a pointer to a text string and a length in characters, return the
2220 equivalent length in bytes.
2223 Bytecount charcount_to_bytecount (Bufbyte *p, Charcount cc);
2226 @item charptr_n_addr
2227 Return a pointer to the beginning of the character offset @var{cc} (in
2228 characters) from @var{p}.
2231 Bufbyte *charptr_n_addr (Bufbyte *p, Charcount cc);
2235 @node Conversion of External Data
2236 @subsection Conversion of External Data
2238 When an external function, such as a C library function, returns a
2239 @code{char} pointer, you should never treat it as @code{Bufbyte}. This
2240 is because these returned strings may contain 8bit characters which can
2241 be misinterpreted by XEmacs, and cause a crash. Instead, you should use
2242 a conversion macro. Many different conversion macros are defined in
2243 @file{buffer.h}, so I will try to order them logically, by direction and
2246 Thus the basic conversion macros are @code{GET_CHARPTR_INT_DATA_ALLOCA}
2247 and @code{GET_CHARPTR_EXT_DATA_ALLOCA}. The former is used to convert
2248 external data to internal format, and the latter is used to convert the
2249 other way around. The arguments each of these receives are @var{ptr}
2250 (pointer to the text in external format), @var{len} (length of texts in
2251 bytes), @var{fmt} (format of the external text), @var{ptr_out} (lvalue
2252 to which new text should be copied), and @var{len_out} (lvalue which
2253 will be assigned the length of the internal text in bytes). The
2254 resulting text is stored to a stack-allocated buffer. If the text
2255 doesn't need changing, these macros will do nothing, except for setting
2258 Currently meaningful formats are @code{FORMAT_BINARY},
2259 @code{FORMAT_FILENAME}, @code{FORMAT_OS}, and @code{FORMAT_CTEXT}.
2261 The two macros above take many arguments which makes them unwieldy. For
2262 this reason, several convenience macros are defined with obvious
2263 functionality, but accepting less arguments:
2266 @item GET_C_CHARPTR_EXT_DATA_ALLOCA
2267 @itemx GET_C_CHARPTR_INT_DATA_ALLOCA
2268 These two macros work on ``C char pointers'', which are zero-terminated,
2269 and thus do not need @var{len} or @var{len_out} parameters.
2271 @item GET_STRING_EXT_DATA_ALLOCA
2272 @itemx GET_C_STRING_EXT_DATA_ALLOCA
2273 These two macros work on Lisp strings, thus also not needing a @var{len}
2274 parameter. However, @code{GET_STRING_EXT_DATA_ALLOCA} still provides a
2275 @var{len_out} parameter. Note that for Lisp strings only one conversion
2276 direction makes sense.
2278 @item GET_C_CHARPTR_EXT_BINARY_DATA_ALLOCA
2279 @itemx GET_C_CHARPTR_EXT_FILENAME_DATA_ALLOCA
2280 @itemx GET_C_CHARPTR_EXT_CTEXT_DATA_ALLOCA
2282 These macros are a combination of the above, but with the @var{fmt}
2283 argument encoded into the name of the macro.
2286 @node General Guidelines for Writing Mule-Aware Code
2287 @subsection General Guidelines for Writing Mule-Aware Code
2289 This section contains some general guidance on how to write Mule-aware
2290 code, as well as some pitfalls you should avoid.
2293 @item Never use @code{char} and @code{char *}.
2294 In XEmacs, the use of @code{char} and @code{char *} is almost always a
2295 mistake. If you want to manipulate an Emacs character from ``C'', use
2296 @code{Emchar}. If you want to examine a specific octet in the internal
2297 format, use @code{Bufbyte}. If you want a Lisp-visible character, use a
2298 @code{Lisp_Object} and @code{make_char}. If you want a pointer to move
2299 through the internal text, use @code{Bufbyte *}. Also note that you
2300 almost certainly do not need @code{Emchar *}.
2302 @item Be careful not to confuse @code{Charcount}, @code{Bytecount}, and @code{Bufpos}.
2303 The whole point of using different types is to avoid confusion about the
2304 use of certain variables. Lest this effect be nullified, you need to be
2305 careful about using the right types.
2307 @item Always convert external data
2308 It is extremely important to always convert external data, because
2309 XEmacs can crash if unexpected 8bit sequences are copied to its internal
2312 This means that when a system function, such as @code{readdir}, returns
2313 a string, you need to convert it using one of the conversion macros
2314 described in the previous chapter, before passing it further to Lisp.
2315 In the case of @code{readdir}, you would use the
2316 @code{GET_C_CHARPTR_INT_FILENAME_DATA_ALLOCA} macro.
2318 Also note that many internal functions, such as @code{make_string},
2319 accept Bufbytes, which removes the need for them to convert the data
2320 they receive. This increases efficiency because that way external data
2321 needs to be decoded only once, when it is read. After that, it is
2322 passed around in internal format.
2325 @node An Example of Mule-Aware Code
2326 @subsection An Example of Mule-Aware Code
2328 As an example of Mule-aware code, we shall will analyze the
2329 @code{string} function, which conses up a Lisp string from the character
2330 arguments it receives. Here is the definition, pasted from
2335 DEFUN ("string", Fstring, 0, MANY, 0, /*
2336 Concatenate all the argument characters and make the result a string.
2338 (int nargs, Lisp_Object *args))
2340 Bufbyte *storage = alloca_array (Bufbyte, nargs * MAX_EMCHAR_LEN);
2341 Bufbyte *p = storage;
2343 for (; nargs; nargs--, args++)
2345 Lisp_Object lisp_char = *args;
2346 CHECK_CHAR_COERCE_INT (lisp_char);
2347 p += set_charptr_emchar (p, XCHAR (lisp_char));
2349 return make_string (storage, p - storage);
2354 Now we can analyze the source line by line.
2356 Obviously, string will be as long as there are arguments to the
2357 function. This is why we allocate @code{MAX_EMCHAR_LEN} * @var{nargs}
2358 bytes on the stack, i.e. the worst-case number of bytes for @var{nargs}
2359 @code{Emchar}s to fit in the string.
2361 Then, the loop checks that each element is a character, converting
2362 integers in the process. Like many other functions in XEmacs, this
2363 function silently accepts integers where characters are expected, for
2364 historical and compatibility reasons. Unless you know what you are
2365 doing, @code{CHECK_CHAR} will also suffice. @code{XCHAR (lisp_char)}
2366 extracts the @code{Emchar} from the @code{Lisp_Object}, and
2367 @code{set_charptr_emchar} stores it to storage, increasing @code{p} in
2370 Other instructing examples of correct coding under Mule can be found all
2371 over XEmacs code. For starters, I recommend
2372 @code{Fnormalize_menu_item_name} in @file{menubar.c}. After you have
2373 understood this section of the manual and studied the examples, you can
2374 proceed writing new Mule-aware code.
2376 @node Techniques for XEmacs Developers
2377 @section Techniques for XEmacs Developers
2379 To make a quantified XEmacs, do: @code{make quantmacs}.
2381 You simply can't dump Quantified and Purified images. Run the image
2382 like so: @code{quantmacs -batch -l loadup.el run-temacs -q}.
2384 Before you go through the trouble, are you compiling with all
2385 debugging and error-checking off? If not try that first. Be warned
2386 that while Quantify is directly responsible for quite a few
2387 optimizations which have been made to XEmacs, doing a run which
2388 generates results which can be acted upon is not necessarily a trivial
2391 Also, if you're still willing to do some runs make sure you configure
2392 with the @samp{--quantify} flag. That will keep Quantify from starting
2393 to record data until after the loadup is completed and will shut off
2394 recording right before it shuts down (which generates enough bogus data
2395 to throw most results off). It also enables three additional elisp
2396 commands: @code{quantify-start-recording-data},
2397 @code{quantify-stop-recording-data} and @code{quantify-clear-data}.
2399 To get started debugging XEmacs, take a look at the @file{gdbinit} and
2400 @file{dbxrc} files in the @file{src} directory.
2401 @xref{Q2.1.15 - How to Debug an XEmacs problem with a debugger,,,
2402 xemacs-faq, XEmacs FAQ}.
2405 Here are things to know when you create a new source file:
2409 All .c files should @code{#include <config.h>} first. Almost all .c
2410 files should @code{#include "lisp.h"} second.
2413 Generated header files should be included using the @code{<>} syntax,
2414 not the @code{""} syntax. The generated headers are:
2416 config.h puresize-adjust.h sheap-adjust.h paths.h Emacs.ad.h
2418 The basic rule is that you should assume builds using @code{--srcdir}
2419 and the @code{<>} syntax needs to be used when the to-be-included
2420 generated file is in a potentially different directory
2421 @emph{at compile time}.
2424 Header files should not include <config.h> and "lisp.h". It is the
2425 responsibility of the .c files that use it to do so.
2428 If the header uses INLINE, either directly or though DECLARE_LRECORD,
2429 then it must be added to inline.c's includes.
2432 Try compiling at least once with
2435 gcc --with-mule --with-union-type --error-checking=all
2439 @node A Summary of the Various XEmacs Modules, Allocation of Objects in XEmacs Lisp, Rules When Writing New C Code, Top
2440 @chapter A Summary of the Various XEmacs Modules
2442 This is accurate as of XEmacs 20.0.
2445 * Low-Level Modules::
2446 * Basic Lisp Modules::
2447 * Modules for Standard Editing Operations::
2448 * Editor-Level Control Flow Modules::
2449 * Modules for the Basic Displayable Lisp Objects::
2450 * Modules for other Display-Related Lisp Objects::
2451 * Modules for the Redisplay Mechanism::
2452 * Modules for Interfacing with the File System::
2453 * Modules for Other Aspects of the Lisp Interpreter and Object System::
2454 * Modules for Interfacing with the Operating System::
2455 * Modules for Interfacing with X Windows::
2456 * Modules for Internationalization::
2459 @node Low-Level Modules
2460 @section Low-Level Modules
2464 ------- ---------------------
2468 This is automatically generated from @file{config.h.in} based on the
2469 results of configure tests and user-selected optional features and
2470 contains preprocessor definitions specifying the nature of the
2471 environment in which XEmacs is being compiled.
2479 This is automatically generated from @file{paths.h.in} based on supplied
2480 configure values, and allows for non-standard installed configurations
2481 of the XEmacs directories. It's currently broken, though.
2490 @file{emacs.c} contains @code{main()} and other code that performs the most
2491 basic environment initializations and handles shutting down the XEmacs
2492 process (this includes @code{kill-emacs}, the normal way that XEmacs is
2493 exited; @code{dump-emacs}, which is used during the build process to
2494 write out the XEmacs executable; @code{run-emacs-from-temacs}, which can
2495 be used to start XEmacs directly when temacs has finished loading all
2496 the Lisp code; and emergency code to handle crashes [XEmacs tries to
2497 auto-save all files before it crashes]).
2499 Low-level code that directly interacts with the Unix signal mechanism,
2500 however, is in @file{signal.c}. Note that this code does not handle system
2501 dependencies in interfacing to signals; that is handled using the
2502 @file{syssignal.h} header file, described in section J below.
2526 These modules contain code dumping out the XEmacs executable on various
2527 different systems. (This process is highly machine-specific and
2528 requires intimate knowledge of the executable format and the memory map
2529 of the process.) Only one of these modules is actually used; this is
2530 chosen by @file{configure}.
2540 These modules are used in conjunction with the dump mechanism. On some
2541 systems, an alternative version of the C startup code (the actual code
2542 that receives control from the operating system when the process is
2543 started, and which calls @code{main()}) is required so that the dumping
2544 process works properly; @file{crt0.c} provides this.
2546 @file{pre-crt0.c} and @file{lastfile.c} should be the very first and
2547 very last file linked, respectively. (Actually, this is not really true.
2548 @file{lastfile.c} should be after all Emacs modules whose initialized
2549 data should be made constant, and before all other Emacs files and all
2550 libraries. In particular, the allocation modules @file{gmalloc.c},
2551 @file{alloca.c}, etc. are normally placed past @file{lastfile.c}, and
2552 all of the files that implement Xt widget classes @emph{must} be placed
2553 after @file{lastfile.c} because they contain various structures that
2554 must be statically initialized and into which Xt writes at various
2555 times.) @file{pre-crt0.c} and @file{lastfile.c} contain exported symbols
2556 that are used to determine the start and end of XEmacs' initialized
2557 data space when dumping.
2572 These handle basic C allocation of memory. @file{alloca.c} is an emulation of
2573 the stack allocation function @code{alloca()} on machines that lack
2574 this. (XEmacs makes extensive use of @code{alloca()} in its code.)
2576 @file{gmalloc.c} and @file{malloc.c} are two implementations of the standard C
2577 functions @code{malloc()}, @code{realloc()} and @code{free()}. They are
2578 often used in place of the standard system-provided @code{malloc()}
2579 because they usually provide a much faster implementation, at the
2580 expense of additional memory use. @file{gmalloc.c} is a newer implementation
2581 that is much more memory-efficient for large allocations than @file{malloc.c},
2582 and should always be preferred if it works. (At one point, @file{gmalloc.c}
2583 didn't work on some systems where @file{malloc.c} worked; but this should be
2586 @cindex relocating allocator
2587 @file{ralloc.c} is the @dfn{relocating allocator}. It provides functions
2588 similar to @code{malloc()}, @code{realloc()} and @code{free()} that allocate
2589 memory that can be dynamically relocated in memory. The advantage of
2590 this is that allocated memory can be shuffled around to place all the
2591 free memory at the end of the heap, and the heap can then be shrunk,
2592 releasing the memory back to the operating system. The use of this can
2593 be controlled with the configure option @code{--rel-alloc}; if enabled, memory allocated for
2594 buffers will be relocatable, so that if a very large file is visited and
2595 the buffer is later killed, the memory can be released to the operating
2596 system. (The disadvantage of this mechanism is that it can be very
2597 slow. On systems with the @code{mmap()} system call, the XEmacs version
2598 of @file{ralloc.c} uses this to move memory around without actually having to
2599 block-copy it, which can speed things up; but it can still cause
2600 noticeable performance degradation.)
2602 @file{free-hook.c} contains some debugging functions for checking for invalid
2603 arguments to @code{free()}.
2605 @file{vm-limit.c} contains some functions that warn the user when memory is
2606 getting low. These are callback functions that are called by @file{gmalloc.c}
2607 and @file{malloc.c} at appropriate times.
2609 @file{getpagesize.h} provides a uniform interface for retrieving the size of a
2610 page in virtual memory. @file{mem-limits.h} provides a uniform interface for
2611 retrieving the total amount of available virtual memory. Both are
2612 similar in spirit to the @file{sys*.h} files described in section J, below.
2623 These implement a couple of basic C data types to facilitate memory
2624 allocation. The @code{Blocktype} type efficiently manages the
2625 allocation of fixed-size blocks by minimizing the number of times that
2626 @code{malloc()} and @code{free()} are called. It allocates memory in
2627 large chunks, subdivides the chunks into blocks of the proper size, and
2628 returns the blocks as requested. When blocks are freed, they are placed
2629 onto a linked list, so they can be efficiently reused. This data type
2630 is not much used in XEmacs currently, because it's a fairly new
2633 @cindex dynamic array
2634 The @code{Dynarr} type implements a @dfn{dynamic array}, which is
2635 similar to a standard C array but has no fixed limit on the number of
2636 elements it can contain. Dynamic arrays can hold elements of any type,
2637 and when you add a new element, the array automatically resizes itself
2638 if it isn't big enough. Dynarrs are extensively used in the redisplay
2647 This module is used in connection with inline functions (available in
2648 some compilers). Often, inline functions need to have a corresponding
2649 non-inline function that does the same thing. This module is where they
2650 reside. It contains no actual code, but defines some special flags that
2651 cause inline functions defined in header files to be rendered as actual
2652 functions. It then includes all header files that contain any inline
2653 function definitions, so that each one gets a real function equivalent.
2662 These functions provide a system for doing internal consistency checks
2663 during code development. This system is not currently used; instead the
2664 simpler @code{assert()} macro is used along with the various checks
2665 provided by the @samp{--error-check-*} configuration options.
2673 This is actually the source for a small, self-contained program
2674 used during building.
2681 This is not currently used.
2685 @node Basic Lisp Modules
2686 @section Basic Lisp Modules
2690 ------- ---------------------
2692 6305 lisp-disunion.h
2699 These are the basic header files for all XEmacs modules. Each module
2700 includes @file{lisp.h}, which brings the other header files in.
2701 @file{lisp.h} contains the definitions of the structures and extractor
2702 and constructor macros for the basic Lisp objects and various other
2703 basic definitions for the Lisp environment, as well as some
2704 general-purpose definitions (e.g. @code{min()} and @code{max()}).
2705 @file{lisp.h} includes either @file{lisp-disunion.h} or
2706 @file{lisp-union.h}, depending on whether @code{USE_UNION_TYPE} is
2707 defined. These files define the typedef of the Lisp object itself (as
2708 described above) and the low-level macros that hide the actual
2709 implementation of the Lisp object. All extractor and constructor macros
2710 for particular types of Lisp objects are defined in terms of these
2713 As a general rule, all typedefs should go into the typedefs section of
2714 @file{lisp.h} rather than into a module-specific header file even if the
2715 structure is defined elsewhere. This allows function prototypes that
2716 use the typedef to be placed into @file{emacsfns.h}. Forward structure
2717 declarations (i.e. a simple declaration like @code{struct foo;} where
2718 the structure itself is defined elsewhere) should be placed into the
2719 typedefs section as necessary.
2721 @file{lrecord.h} contains the basic structures and macros that implement
2722 all record-type Lisp objects -- i.e. all objects whose type is a field
2723 in their C structure, which includes all objects except the few most
2726 @file{emacsfns.h} contains prototypes for most of the exported functions
2727 in the various modules. (In particular, prototypes for Lisp primitives
2728 should always go into this header file. Prototypes for other functions
2729 can either go here or in a module-specific header file, depending on how
2730 general-purpose the function is and whether it has special-purpose
2731 argument types requiring definitions not in @file{lisp.h}.) All
2732 initialization functions are prototyped in @file{symsinit.h}.
2742 The large module @file{alloc.c} implements all of the basic allocation and
2743 garbage collection for Lisp objects. The most commonly used Lisp
2744 objects are allocated in chunks, similar to the Blocktype data type
2745 described above; others are allocated in individually @code{malloc()}ed
2746 blocks. This module provides the foundation on which all other aspects
2747 of the Lisp environment sit, and is the first module initialized at
2750 Note that @file{alloc.c} provides a series of generic functions that are
2751 not dependent on any particular object type, and interfaces to
2752 particular types of objects using a standardized interface of
2753 type-specific methods. This scheme is a fundamental principle of
2754 object-oriented programming and is heavily used throughout XEmacs. The
2755 great advantage of this is that it allows for a clean separation of
2756 functionality into different modules -- new classes of Lisp objects, new
2757 event interfaces, new device types, new stream interfaces, etc. can be
2758 added transparently without affecting code anywhere else in XEmacs.
2759 Because the different subsystems are divided into general and specific
2760 code, adding a new subtype within a subsystem will in general not
2761 require changes to the generic subsystem code or affect any of the other
2762 subtypes in the subsystem; this provides a great deal of robustness to
2766 @file{pure.c} contains the declaration of the @dfn{purespace} array.
2767 Pure space is a hack used to place some constant Lisp data into the code
2768 segment of the XEmacs executable, even though the data needs to be
2769 initialized through function calls. (See above in section VIII for more
2770 info about this.) During startup, certain sorts of data is
2771 automatically copied into pure space, and other data is copied manually
2772 in some of the basic Lisp files by calling the function @code{purecopy},
2773 which copies the object if possible (this only works in temacs, of
2774 course) and returns the new object. In particular, while temacs is
2775 executing, the Lisp reader automatically copies all compiled-function
2776 objects that it reads into pure space. Since compiled-function objects
2777 are large, are never modified, and typically comprise the majority of
2778 the contents of a compiled-Lisp file, this works well. While XEmacs is
2779 running, any attempt to modify an object that resides in pure space
2780 causes an error. Objects in pure space are never garbage collected --
2781 almost all of the time, they're intended to be permanent, and in any
2782 case you can't write into pure space to set the mark bits.
2784 @file{puresize.h} contains the declaration of the size of the pure space
2785 array. This depends on the optional features that are compiled in, any
2786 extra purespace requested by the user at compile time, and certain other
2787 factors (e.g. 64-bit machines need more pure space because their Lisp
2788 objects are larger). The smallest size that suffices should be used, so
2789 that there's no wasted space. If there's not enough pure space, you
2790 will get an error during the build process, specifying how much more
2791 pure space is needed.
2800 This module contains all of the functions to handle the flow of control.
2801 This includes the mechanisms of defining functions, calling functions,
2802 traversing stack frames, and binding variables; the control primitives
2803 and other special forms such as @code{while}, @code{if}, @code{eval},
2804 @code{let}, @code{and}, @code{or}, @code{progn}, etc.; handling of
2805 non-local exits, unwind-protects, and exception handlers; entering the
2806 debugger; methods for the subr Lisp object type; etc. It does
2807 @emph{not} include the @code{read} function, the @code{print} function,
2808 or the handling of symbols and obarrays.
2810 @file{backtrace.h} contains some structures related to stack frames and the
2819 This module implements the Lisp reader and the @code{read} function,
2820 which converts text into Lisp objects, according to the read syntax of
2821 the objects, as described above. This is similar to the parser that is
2822 a part of all compilers.
2830 This module implements the Lisp print mechanism and the @code{print}
2831 function and related functions. This is the inverse of the Lisp reader
2832 -- it converts Lisp objects to a printed, textual representation.
2833 (Hopefully something that can be read back in using @code{read} to get
2834 an equivalent object.)
2844 @file{symbols.c} implements the handling of symbols, obarrays, and
2845 retrieving the values of symbols. Much of the code is devoted to
2846 handling the special @dfn{symbol-value-magic} objects that define
2847 special types of variables -- this includes buffer-local variables,
2848 variable aliases, variables that forward into C variables, etc. This
2849 module is initialized extremely early (right after @file{alloc.c}),
2850 because it is here that the basic symbols @code{t} and @code{nil} are
2851 created, and those symbols are used everywhere throughout XEmacs.
2853 @file{symeval.h} contains the definitions of symbol structures and the
2854 @code{DEFVAR_LISP()} and related macros for declaring variables.
2864 These modules implement the methods and standard Lisp primitives for all
2865 the basic Lisp object types other than symbols (which are described
2866 above). @file{data.c} contains all the predicates (primitives that return
2867 whether an object is of a particular type); the integer arithmetic
2868 functions; and the basic accessor and mutator primitives for the various
2869 object types. @file{fns.c} contains all the standard predicates for working
2870 with sequences (where, abstractly speaking, a sequence is an ordered set
2871 of objects, and can be represented by a list, string, vector, or
2872 bit-vector); it also contains @code{equal}, perhaps on the grounds that
2873 bulk of the operation of @code{equal} is comparing sequences.
2874 @file{floatfns.c} contains methods and primitives for floats and floating-point
2884 @file{bytecode.c} implements the byte-code interpreter, and @file{bytecode.h} contains
2885 associated structures. Note that the byte-code @emph{compiler} is
2891 @node Modules for Standard Editing Operations
2892 @section Modules for Standard Editing Operations
2896 ------- ---------------------
2902 @file{buffer.c} implements the @dfn{buffer} Lisp object type. This
2903 includes functions that create and destroy buffers; retrieve buffers by
2904 name or by other properties; manipulate lists of buffers (remember that
2905 buffers are permanent objects and stored in various ordered lists);
2906 retrieve or change buffer properties; etc. It also contains the
2907 definitions of all the built-in buffer-local variables (which can be
2908 viewed as buffer properties). It does @emph{not} contain code to
2909 manipulate buffer-local variables (that's in @file{symbols.c}, described
2910 above); or code to manipulate the text in a buffer.
2912 @file{buffer.h} defines the structures associated with a buffer and the various
2913 macros for retrieving text from a buffer and special buffer positions
2914 (e.g. @code{point}, the default location for text insertion). It also
2915 contains macros for working with buffer positions and converting between
2916 their representations as character offsets and as byte offsets (under
2917 MULE, they are different, because characters can be multi-byte). It is
2918 one of the largest header files.
2920 @file{bufslots.h} defines the fields in the buffer structure that correspond to
2921 the built-in buffer-local variables. It is its own header file because
2922 it is included many times in @file{buffer.c}, as a way of iterating over all
2923 the built-in buffer-local variables.
2932 @file{insdel.c} contains low-level functions for inserting and deleting text in
2933 a buffer, keeping track of changed regions for use by redisplay, and
2934 calling any before-change and after-change functions that may have been
2935 registered for the buffer. It also contains the actual functions that
2936 convert between byte offsets and character offsets.
2938 @file{insdel.h} contains associated headers.
2946 This module implements the @dfn{marker} Lisp object type, which
2947 conceptually is a pointer to a text position in a buffer that moves
2948 around as text is inserted and deleted, so as to remain in the same
2949 relative position. This module doesn't actually move the markers around
2950 -- that's handled in @file{insdel.c}. This module just creates them and
2951 implements the primitives for working with them. As markers are simple
2952 objects, this does not entail much.
2954 Note that the standard arithmetic primitives (e.g. @code{+}) accept
2955 markers in place of integers and automatically substitute the value of
2956 @code{marker-position} for the marker, i.e. an integer describing the
2957 current buffer position of the marker.
2966 This module implements the @dfn{extent} Lisp object type, which is like
2967 a marker that works over a range of text rather than a single position.
2968 Extents are also much more complex and powerful than markers and have a
2969 more efficient (and more algorithmically complex) implementation. The
2970 implementation is described in detail in comments in @file{extents.c}.
2972 The code in @file{extents.c} works closely with @file{insdel.c} so that
2973 extents are properly moved around as text is inserted and deleted.
2974 There is also code in @file{extents.c} that provides information needed
2975 by the redisplay mechanism for efficient operation. (Remember that
2976 extents can have display properties that affect [sometimes drastically,
2977 as in the @code{invisible} property] the display of the text they
2986 @file{editfns.c} contains the standard Lisp primitives for working with
2987 a buffer's text, and calls the low-level functions in @file{insdel.c}.
2988 It also contains primitives for working with @code{point} (the default
2989 buffer insertion location).
2991 @file{editfns.c} also contains functions for retrieving various
2992 characteristics from the external environment: the current time, the
2993 process ID of the running XEmacs process, the name of the user who ran
2994 this XEmacs process, etc. It's not clear why this code is in
3006 These modules implement the basic @dfn{interactive} commands,
3007 i.e. user-callable functions. Commands, as opposed to other functions,
3008 have special ways of getting their parameters interactively (by querying
3009 the user), as opposed to having them passed in a normal function
3010 invocation. Many commands are not really meant to be called from other
3011 Lisp functions, because they modify global state in a way that's often
3012 undesired as part of other Lisp functions.
3014 @file{callint.c} implements the mechanism for querying the user for
3015 parameters and calling interactive commands. The bulk of this module is
3016 code that parses the interactive spec that is supplied with an
3017 interactive command.
3019 @file{cmds.c} implements the basic, most commonly used editing commands:
3020 commands to move around the current buffer and insert and delete
3021 characters. These commands are implemented using the Lisp primitives
3022 defined in @file{editfns.c}.
3024 @file{commands.h} contains associated structure definitions and prototypes.
3034 @file{search.c} implements the Lisp primitives for searching for text in
3035 a buffer, and some of the low-level algorithms for doing this. In
3036 particular, the fast fixed-string Boyer-Moore search algorithm is
3037 implemented in @file{search.c}. The low-level algorithms for doing
3038 regular-expression searching, however, are implemented in @file{regex.c}
3039 and @file{regex.h}. These two modules are largely independent of
3040 XEmacs, and are similar to (and based upon) the regular-expression
3041 routines used in @file{grep} and other GNU utilities.
3049 @file{doprnt.c} implements formatted-string processing, similar to
3050 @code{printf()} command in C.
3058 This module implements the undo mechanism for tracking buffer changes.
3059 Most of this could be implemented in Lisp.
3063 @node Editor-Level Control Flow Modules
3064 @section Editor-Level Control Flow Modules
3068 ------- ---------------------
3070 121483 event-stream.c
3076 These implement the handling of events (user input and other system
3079 @file{events.c} and @file{events.h} define the @dfn{event} Lisp object
3080 type and primitives for manipulating it.
3082 @file{event-stream.c} implements the basic functions for working with
3083 event queues, dispatching an event by looking it up in relevant keymaps
3084 and such, and handling timeouts; this includes the primitives
3085 @code{next-event} and @code{dispatch-event}, as well as related
3086 primitives such as @code{sit-for}, @code{sleep-for}, and
3087 @code{accept-process-output}. (@file{event-stream.c} is one of the
3088 hairiest and trickiest modules in XEmacs. Beware! You can easily mess
3091 @file{event-Xt.c} and @file{event-tty.c} implement the low-level
3092 interfaces onto retrieving events from Xt (the X toolkit) and from TTY's
3093 (using @code{read()} and @code{select()}), respectively. The event
3094 interface enforces a clean separation between the specific code for
3095 interfacing with the operating system and the generic code for working
3096 with events, by defining an API of basic, low-level event methods;
3097 @file{event-Xt.c} and @file{event-tty.c} are two different
3098 implementations of this API. To add support for a new operating system
3099 (e.g. NeXTstep), one merely needs to provide another implementation of
3100 those API functions.
3102 Note that the choice of whether to use @file{event-Xt.c} or
3103 @file{event-tty.c} is made at compile time! Or at the very latest, it
3104 is made at startup time. @file{event-Xt.c} handles events for
3105 @emph{both} X and TTY frames; @file{event-tty.c} is only used when X
3106 support is not compiled into XEmacs. The reason for this is that there
3107 is only one event loop in XEmacs: thus, it needs to be able to receive
3108 events from all different kinds of frames.
3117 @file{keymap.c} and @file{keymap.h} define the @dfn{keymap} Lisp object
3118 type and associated methods and primitives. (Remember that keymaps are
3119 objects that associate event descriptions with functions to be called to
3120 ``execute'' those events; @code{dispatch-event} looks up events in the
3129 @file{keyboard.c} contains functions that implement the actual editor
3130 command loop -- i.e. the event loop that cyclically retrieves and
3131 dispatches events. This code is also rather tricky, just like
3132 @file{event-stream.c}.
3141 These two modules contain the basic code for defining keyboard macros.
3142 These functions don't actually do much; most of the code that handles keyboard
3143 macros is mixed in with the event-handling code in @file{event-stream.c}.
3151 This contains some miscellaneous code related to the minibuffer (most of
3152 the minibuffer code was moved into Lisp by Richard Mlynarik). This
3153 includes the primitives for completion (although filename completion is
3154 in @file{dired.c}), the lowest-level interface to the minibuffer (if the
3155 command loop were cleaned up, this too could be in Lisp), and code for
3156 dealing with the echo area (this, too, was mostly moved into Lisp, and
3157 the only code remaining is code to call out to Lisp or provide simple
3158 bootstrapping implementations early in temacs, before the echo-area Lisp
3163 @node Modules for the Basic Displayable Lisp Objects
3164 @section Modules for the Basic Displayable Lisp Objects
3168 ------- ---------------------
3170 6454 device-stream.c
3171 1196 device-stream.h
3180 These modules implement the @dfn{device} Lisp object type. This
3181 abstracts a particular screen or connection on which frames are
3182 displayed. As with Lisp objects, event interfaces, and other
3183 subsystems, the device code is separated into a generic component that
3184 contains a standardized interface (in the form of a set of methods) onto
3185 particular device types.
3187 The device subsystem defines all the methods and provides method
3188 services for not only device operations but also for the frame, window,
3189 menubar, scrollbar, toolbar, and other displayable-object subsystems.
3190 The reason for this is that all of these subsystems have the same
3191 subtypes (X, TTY, NeXTstep, Microsoft Windows, etc.) as devices do.
3204 Each device contains one or more frames in which objects (e.g. text) are
3205 displayed. A frame corresponds to a window in the window system;
3206 usually this is a top-level window but it could potentially be one of a
3207 number of overlapping child windows within a top-level window, using the
3208 MDI (Multiple Document Interface) protocol in Microsoft Windows or a
3211 The @file{frame-*} files implement the @dfn{frame} Lisp object type and
3212 provide the generic and device-type-specific operations on frames
3213 (e.g. raising, lowering, resizing, moving, etc.).
3222 @cindex window (in Emacs)
3224 Each frame consists of one or more non-overlapping @dfn{windows} (better
3225 known as @dfn{panes} in standard window-system terminology) in which a
3226 buffer's text can be displayed. Windows can also have scrollbars
3227 displayed around their edges.
3229 @file{window.c} and @file{window.h} implement the @dfn{window} Lisp
3230 object type and provide code to manage windows. Since windows have no
3231 associated resources in the window system (the window system knows only
3232 about the frame; no child windows or anything are used for XEmacs
3233 windows), there is no device-type-specific code here; all of that code
3234 is part of the redisplay mechanism or the code for particular object
3235 types such as scrollbars.
3239 @node Modules for other Display-Related Lisp Objects
3240 @section Modules for other Display-Related Lisp Objects
3244 ------- ---------------------
3302 This file provides C support for syntax highlighting -- i.e.
3303 highlighting different syntactic constructs of a source file in
3304 different colors, for easy reading. The C support is provided so that
3316 These modules decode GIF-format image files, for use with glyphs.
3320 @node Modules for the Redisplay Mechanism
3321 @section Modules for the Redisplay Mechanism
3325 ------- ---------------------
3326 38692 redisplay-output.c
3327 40835 redisplay-tty.c
3333 These files provide the redisplay mechanism. As with many other
3334 subsystems in XEmacs, there is a clean separation between the general
3335 and device-specific support.
3337 @file{redisplay.c} contains the bulk of the redisplay engine. These
3338 functions update the redisplay structures (which describe how the screen
3339 is to appear) to reflect any changes made to the state of any
3340 displayable objects (buffer, frame, window, etc.) since the last time
3341 that redisplay was called. These functions are highly optimized to
3342 avoid doing more work than necessary (since redisplay is called
3343 extremely often and is potentially a huge time sink), and depend heavily
3344 on notifications from the objects themselves that changes have occurred,
3345 so that redisplay doesn't explicitly have to check each possible object.
3346 The redisplay mechanism also contains a great deal of caching to further
3347 speed things up; some of this caching is contained within the various
3348 displayable objects.
3350 @file{redisplay-output.c} goes through the redisplay structures and converts
3351 them into calls to device-specific methods to actually output the screen
3354 @file{redisplay-x.c} and @file{redisplay-tty.c} are two implementations
3355 of these redisplay output methods, for X frames and TTY frames,
3364 This module contains various functions and Lisp primitives for
3365 converting between buffer positions and screen positions. These
3366 functions call the redisplay mechanism to do most of the work, and then
3367 examine the redisplay structures to get the necessary information. This
3378 These files contain functions for working with the termcap (BSD-style)
3379 and terminfo (System V style) databases of terminal capabilities and
3380 escape sequences, used when XEmacs is displaying in a TTY.
3389 These files provide some miscellaneous TTY-output functions and should
3390 probably be merged into @file{redisplay-tty.c}.
3394 @node Modules for Interfacing with the File System
3395 @section Modules for Interfacing with the File System
3399 ------- ---------------------
3404 These modules implement the @dfn{stream} Lisp object type. This is an
3405 internal-only Lisp object that implements a generic buffering stream.
3406 The idea is to provide a uniform interface onto all sources and sinks of
3407 data, including file descriptors, stdio streams, chunks of memory, Lisp
3408 buffers, Lisp strings, etc. That way, I/O functions can be written to
3409 the stream interface and can transparently handle all possible sources
3410 and sinks. (For example, the @code{read} function can read data from a
3411 file, a string, a buffer, or even a function that is called repeatedly
3412 to return data, without worrying about where the data is coming from or
3413 what-size chunks it is returned in.)
3416 Note that in the C code, streams are called @dfn{lstreams} (for ``Lisp
3417 streams'') to distinguish them from other kinds of streams, e.g. stdio
3418 streams and C++ I/O streams.
3420 Similar to other subsystems in XEmacs, lstreams are separated into
3421 generic functions and a set of methods for the different types of
3422 lstreams. @file{lstream.c} provides implementations of many different
3423 types of streams; others are provided, e.g., in @file{mule-coding.c}.
3431 This implements the basic primitives for interfacing with the file
3432 system. This includes primitives for reading files into buffers,
3433 writing buffers into files, checking for the presence or accessibility
3434 of files, canonicalizing file names, etc. Note that these primitives
3435 are usually not invoked directly by the user: There is a great deal of
3436 higher-level Lisp code that implements the user commands such as
3437 @code{find-file} and @code{save-buffer}. This is similar to the
3438 distinction between the lower-level primitives in @file{editfns.c} and
3439 the higher-level user commands in @file{commands.c} and
3448 This file provides functions for detecting clashes between different
3449 processes (e.g. XEmacs and some external process, or two different
3450 XEmacs processes) modifying the same file. (XEmacs can optionally use
3451 the @file{lock/} subdirectory to provide a form of ``locking'' between
3452 different XEmacs processes.) This module is also used by the low-level
3453 functions in @file{insdel.c} to ensure that, if the first modification
3454 is being made to a buffer whose corresponding file has been externally
3455 modified, the user is made aware of this so that the buffer can be
3456 synched up with the external changes if necessary.
3463 This file provides some miscellaneous functions that construct a
3464 @samp{rwxr-xr-x}-type permissions string (as might appear in an
3465 @file{ls}-style directory listing) given the information returned by the
3466 @code{stat()} system call.
3475 These files implement the XEmacs interface to directory searching. This
3476 includes a number of primitives for determining the files in a directory
3477 and for doing filename completion. (Remember that generic completion is
3478 handled by a different mechanism, in @file{minibuf.c}.)
3480 @file{ndir.h} is a header file used for the directory-searching
3481 emulation functions provided in @file{sysdep.c} (see section J below),
3482 for systems that don't provide any directory-searching functions. (On
3483 those systems, directories can be read directly as files, and parsed.)
3491 This file provides an implementation of the @code{realpath()} function
3492 for expanding symbolic links, on systems that don't implement it or have
3493 a broken implementation.
3497 @node Modules for Other Aspects of the Lisp Interpreter and Object System
3498 @section Modules for Other Aspects of the Lisp Interpreter and Object System
3502 ------- ---------------------
3509 These files implement the @dfn{hashtable} Lisp object type.
3510 @file{hash.c} and @file{hash.h} provide a generic C implementation of
3511 hash tables (which can stand independently of XEmacs), and
3512 @file{elhash.c} and @file{elhash.h} provide a Lisp interface onto the C
3513 hash tables using the hashtable Lisp object type.
3522 This module implements the @dfn{specifier} Lisp object type. This is
3523 primarily used for displayable properties, and allows for values that
3524 are specific to a particular buffer, window, frame, device, or device
3525 class, as well as a default value existing. This is used, for example,
3526 to control the height of the horizontal scrollbar or the appearance of
3527 the @code{default}, @code{bold}, or other faces. The specifier object
3528 consists of a number of specifications, each of which maps from a
3529 buffer, window, etc. to a value. The function @code{specifier-instance}
3530 looks up a value given a window (from which a buffer, frame, and device
3540 @file{chartab.c} and @file{chartab.h} implement the @dfn{char table}
3541 Lisp object type, which maps from characters or certain sorts of
3542 character ranges to Lisp objects. The implementation of this object
3543 type is optimized for the internal representation of characters. Char
3544 tables come in different types, which affect the allowed object types to
3545 which a character can be mapped and also dictate certain other
3546 properties of the char table.
3549 @file{casetab.c} implements one sort of char table, the @dfn{case
3550 table}, which maps characters to other characters of possibly different
3551 case. These are used by XEmacs to implement case-changing primitives
3552 and to do case-insensitive searching.
3562 This module implements @dfn{syntax tables}, another sort of char table
3563 that maps characters into syntax classes that define the syntax of these
3564 characters (e.g. a parenthesis belongs to a class of @samp{open}
3565 characters that have corresponding @samp{close} characters and can be
3566 nested). This module also implements the Lisp @dfn{scanner}, a set of
3567 primitives for scanning over text based on syntax tables. This is used,
3568 for example, to find the matching parenthesis in a command such as
3569 @code{forward-sexp}, and by @file{font-lock.c} to locate quoted strings,
3578 This module implements various Lisp primitives for upcasing, downcasing
3579 and capitalizing strings or regions of buffers.
3587 This module implements the @dfn{range table} Lisp object type, which
3588 provides for a mapping from ranges of integers to arbitrary Lisp
3598 This module implements the @dfn{opaque} Lisp object type, an
3599 internal-only Lisp object that encapsulates an arbitrary block of memory
3600 so that it can be managed by the Lisp allocation system. To create an
3601 opaque object, you call @code{make_opaque()}, passing a pointer to a
3602 block of memory. An object is created that is big enough to hold the
3603 memory, which is copied into the object's storage. The object will then
3604 stick around as long as you keep pointers to it, after which it will be
3605 automatically reclaimed.
3608 Opaque objects can also have an arbitrary @dfn{mark method} associated
3609 with them, in case the block of memory contains other Lisp objects that
3610 need to be marked for garbage-collection purposes. (If you need other
3611 object methods, such as a finalize method, you should just go ahead and
3612 create a new Lisp object type -- it's not hard.)
3620 This function provides a few primitives for doing dynamic abbreviation
3621 expansion. In XEmacs, most of the code for this has been moved into
3622 Lisp. Some C code remains for speed and because the primitive
3623 @code{self-insert-command} (which is executed for all self-inserting
3624 characters) hooks into the abbrev mechanism. (@code{self-insert-command}
3625 is itself in C only for speed.)
3633 This function provides primitives for retrieving the documentation
3634 strings of functions and variables. These documentation strings contain
3635 certain special markers that get dynamically expanded (e.g. a
3636 reverse-lookup is performed on some named functions to retrieve their
3637 current key bindings). Some documentation strings (in particular, for
3638 the built-in primitives and pre-loaded Lisp functions) are stored
3639 externally in a file @file{DOC} in the @file{lib-src/} directory and
3640 need to be fetched from that file. (Part of the build stage involves
3641 building this file, and another part involves constructing an index for
3642 this file and embedding it into the executable, so that the functions in
3643 @file{doc.c} do not have to search the entire @file{DOC} file to find
3644 the appropriate documentation string.)
3652 This function provides a Lisp primitive that implements the MD5 secure
3653 hashing scheme, used to create a large hash value of a string of data such that
3654 the data cannot be derived from the hash value. This is used for
3655 various security applications on the Internet.
3660 @node Modules for Interfacing with the Operating System
3661 @section Modules for Interfacing with the Operating System
3665 ------- ---------------------
3671 These modules allow XEmacs to spawn and communicate with subprocesses
3672 and network connections.
3674 @cindex synchronous subprocesses
3675 @cindex subprocesses, synchronous
3676 @file{callproc.c} implements (through the @code{call-process}
3677 primitive) what are called @dfn{synchronous subprocesses}. This means
3678 that XEmacs runs a program, waits till it's done, and retrieves its
3679 output. A typical example might be calling the @file{ls} program to get
3680 a directory listing.
3682 @cindex asynchronous subprocesses
3683 @cindex subprocesses, asynchronous
3684 @file{process.c} and @file{process.h} implement @dfn{asynchronous
3685 subprocesses}. This means that XEmacs starts a program and then
3686 continues normally, not waiting for the process to finish. Data can be
3687 sent to the process or retrieved from it as it's running. This is used
3688 for the @code{shell} command (which provides a front end onto a shell
3689 program such as @file{csh}), the mail and news readers implemented in
3690 XEmacs, etc. The result of calling @code{start-process} to start a
3691 subprocess is a process object, a particular kind of object used to
3692 communicate with the subprocess. You can send data to the process by
3693 passing the process object and the data to @code{send-process}, and you
3694 can specify what happens to data retrieved from the process by setting
3695 properties of the process object. (When the process sends data, XEmacs
3696 receives a process event, which says that there is data ready. When
3697 @code{dispatch-event} is called on this event, it reads the data from
3698 the process and does something with it, as specified by the process
3699 object's properties. Typically, this means inserting the data into a
3700 buffer or calling a function.) Another property of the process object is
3701 called the @dfn{sentinel}, which is a function that is called when the
3704 @cindex network connections
3705 Process objects are also used for network connections (connections to a
3706 process running on another machine). Network connections are started
3707 with @code{open-network-stream} but otherwise work just like
3717 These modules implement most of the low-level, messy operating-system
3718 interface code. This includes various device control (ioctl) operations
3719 for file descriptors, TTY's, pseudo-terminals, etc. (usually this stuff
3720 is fairly system-dependent; thus the name of this module), and emulation
3721 of standard library functions and system calls on systems that don't
3722 provide them or have broken versions.
3738 These header files provide consistent interfaces onto system-dependent
3739 header files and system calls. The idea is that, instead of including a
3740 standard header file like @file{<sys/param.h>} (which may or may not
3741 exist on various systems) or having to worry about whether all system
3742 provide a particular preprocessor constant, or having to deal with the
3743 four different paradigms for manipulating signals, you just include the
3744 appropriate @file{sys*.h} header file, which includes all the right
3745 system header files, defines and missing preprocessor constants,
3746 provides a uniform interface onto system calls, etc.
3748 @file{sysdir.h} provides a uniform interface onto directory-querying
3749 functions. (In some cases, this is in conjunction with emulation
3750 functions in @file{sysdep.c}.)
3752 @file{sysfile.h} includes all the necessary header files for standard
3753 system calls (e.g. @code{read()}), ensures that all necessary
3754 @code{open()} and @code{stat()} preprocessor constants are defined, and
3755 possibly (usually) substitutes sugared versions of @code{read()},
3756 @code{write()}, etc. that automatically restart interrupted I/O
3759 @file{sysfloat.h} includes the necessary header files for floating-point
3762 @file{sysproc.h} includes the necessary header files for calling
3763 @code{select()}, @code{fork()}, @code{execve()}, socket operations, and
3764 the like, and ensures that the @code{FD_*()} macros for descriptor-set
3765 manipulations are available.
3767 @file{syspwd.h} includes the necessary header files for obtaining
3768 information from @file{/etc/passwd} (the functions are emulated under
3771 @file{syssignal.h} includes the necessary header files for
3772 signal-handling and provides a uniform interface onto the different
3773 signal-handling and signal-blocking paradigms.
3775 @file{systime.h} includes the necessary header files and provides
3776 uniform interfaces for retrieving the time of day, setting file
3777 access/modification times, getting the amount of time used by the XEmacs
3780 @file{systty.h} buffers against the infinitude of different ways of
3783 @file{syswait.h} provides a uniform way of retrieving the exit status
3784 from a @code{wait()}ed-on process (some systems use a union, others use
3801 These files implement the ability to play various sounds on some types
3802 of computers. You have to configure your XEmacs with sound support in
3803 order to get this capability.
3805 @file{sound.c} provides the generic interface. It implements various
3806 Lisp primitives and variables that let you specify which sounds should
3807 be played in certain conditions. (The conditions are identified by
3808 symbols, which are passed to @code{ding} to make a sound. Various
3809 standard functions call this function at certain times; if sound support
3810 does not exist, a simple beep results.
3812 @cindex native sound
3813 @cindex sound, native
3814 @file{sgiplay.c}, @file{sunplay.c}, @file{hpplay.c}, and
3815 @file{linuxplay.c} interface to the machine's speaker for various
3816 different kind of machines. This is called @dfn{native} sound.
3818 @cindex sound, network
3819 @cindex network sound
3821 @file{nas.c} interfaces to a computer somewhere else on the network
3822 using the NAS (Network Audio Server) protocol, playing sounds on that
3823 machine. This allows you to run XEmacs on a remote machine, with its
3824 display set to your local machine, and have the sounds be made on your
3825 local machine, provided that you have a NAS server running on your local
3828 @file{libsst.c}, @file{libsst.h}, and @file{libst.h} provide some
3829 additional functions for playing sound on a Sun SPARC but are not
3839 These two modules implement an interface to the ToolTalk protocol, which
3840 is an interprocess communication protocol implemented on some versions
3841 of Unix. ToolTalk is a high-level protocol that allows processes to
3842 register themselves as providers of particular services; other processes
3843 can then request a service without knowing or caring exactly who is
3844 providing the service. It is similar in spirit to the DDE protocol
3845 provided under Microsoft Windows. ToolTalk is a part of the new CDE
3846 (Common Desktop Environment) specification and is used to connect the
3847 parts of the SPARCWorks development environment.
3855 This module provides the ability to retrieve the system's current load
3856 average. (The way to do this is highly system-specific, unfortunately,
3857 and requires a lot of special-case code.)
3866 This module provides code to interface to an Energize server (when
3867 XEmacs is used as part of Lucid's Energize development environment) and
3868 provides some other Energize-specific functions. Much of the code in
3869 this module should be made more general-purpose and moved elsewhere, but
3870 is no longer very relevant now that Lucid is defunct. It also hasn't
3871 worked since version 19.12, since nobody has been maintaining it.
3879 This module provides a small amount of code used internally at Sun to
3880 keep statistics on the usage of XEmacs.
3891 These files provide replacement functions and prototypes to fix numerous
3892 bugs in early releases of SunOS 4.1.
3900 This module provides some terminal-control code necessary on versions of
3919 All of these files are used for VMS support, which has never worked in
3929 These modules are used for MS-DOS support, which does not work in
3934 @node Modules for Interfacing with X Windows
3935 @section Modules for Interfacing with X Windows
3939 ------- ---------------------
3943 A file generated from @file{Emacs.ad}, which contains XEmacs-supplied
3944 fallback resources (so that XEmacs has pretty defaults).
3954 These modules implement an Xt widget class that encapsulates a frame.
3955 This is for ease in integrating with Xt. The EmacsFrame widget covers
3956 the entire X window except for the menubar; the scrollbars are
3957 positioned on top of the EmacsFrame widget.
3959 @strong{Warning:} Abandon hope, all ye who enter here. This code took
3960 an ungodly amount of time to get right, and is likely to fall apart
3961 mercilessly at the slightest change. Such is life under Xt.
3968 1895 EmacsManagerP.h
3971 These modules implement a simple Xt manager (i.e. composite) widget
3972 class that simply lets its children set whatever geometry they want.
3973 It's amazing that Xt doesn't provide this standardly, but on second
3974 thought, it makes sense, considering how amazingly broken Xt is.
3978 13188 EmacsShell-sub.c
3984 These modules implement two Xt widget classes that are subclasses of
3985 the TopLevelShell and TransientShell classes. This is necessary to deal
3986 with more brokenness that Xt has sadistically thrust onto the backs of
3996 These modules provide functions for maintenance and caching of GC's
3997 (graphics contexts) under the X Window System. This code is junky and
3998 needs to be rewritten.
4007 This module provides an interface to the X Window System's concept of
4008 @dfn{selections}, the standard way for X applications to communicate
4020 These header files are similar in spirit to the @file{sys*.h} files and buffer
4021 against different implementations of Xt and Motif.
4025 @file{xintrinsic.h} should be included in place of @file{<Intrinsic.h>}.
4027 @file{xintrinsicp.h} should be included in place of @file{<IntrinsicP.h>}.
4029 @file{xmmanagerp.h} should be included in place of @file{<XmManagerP.h>}.
4031 @file{xmprimitivep.h} should be included in place of @file{<XmPrimitiveP.h>}.
4041 These files provide an emulation of the Xmu library for those systems
4042 (i.e. HPUX) that don't provide it as a standard part of X.
4047 4201 ExternalClient-Xlib.c
4048 18083 ExternalClient.c
4049 2035 ExternalClient.h
4050 2104 ExternalClientP.h
4051 22684 ExternalShell.c
4052 1709 ExternalShell.h
4053 1971 ExternalShellP.h
4060 @cindex external widget
4061 These files provide the @dfn{external widget} interface, which allows an
4062 XEmacs frame to appear as a widget in another application. To do this,
4063 you have to configure with @samp{--external-widget}.
4065 @file{ExternalShell*} provides the server (XEmacs) side of the
4068 @file{ExternalClient*} provides the client (other application) side of
4069 the connection. These files are not compiled into XEmacs but are
4070 compiled into libraries that are then linked into your application.
4072 @file{extw-*} is common code that is used for both the client and server.
4074 Don't touch this code; something is liable to break if you do.
4082 This file provides some additional, Epoch-compatible, functionality for
4083 interfacing to the X Window System.
4087 @node Modules for Internationalization
4088 @section Modules for Internationalization
4092 ------- ---------------------
4095 41080 mule-charset.c
4096 30176 mule-charset.h
4097 146844 mule-coding.c
4105 These files implement the MULE (Asian-language) support. Note that MULE
4106 actually provides a general interface for all sorts of languages, not
4107 just Asian languages (although they are generally the most complicated
4108 to support). This code is still in beta.
4110 @file{mule-charset.*} and @file{mule-coding.*} provide the heart of the
4111 XEmacs MULE support. @file{mule-charset.*} implements the @dfn{charset}
4112 Lisp object type, which encapsulates a character set (an ordered one- or
4113 two-dimensional set of characters, such as US ASCII or JISX0208 Japanese
4116 @file{mule-coding.*} implements the @dfn{coding-system} Lisp object
4117 type, which encapsulates a method of converting between different
4118 encodings. An encoding is a representation of a stream of characters,
4119 possibly from multiple character sets, using a stream of bytes or words,
4120 and defines (e.g.) which escape sequences are used to specify particular
4121 character sets, how the indices for a character are converted into bytes
4122 (sometimes this involves setting the high bit; sometimes complicated
4123 rearranging of the values takes place, as in the Shift-JIS encoding),
4126 @file{mule-ccl.c} provides the CCL (Code Conversion Language)
4127 interpreter. CCL is similar in spirit to Lisp byte code and is used to
4128 implement converters for custom encodings.
4130 @file{mule-canna.c} and @file{mule-wnnfns.c} implement interfaces to
4131 external programs used to implement the Canna and WNN input methods,
4132 respectively. This is currently in beta.
4134 @file{mule-mcpath.c} provides some functions to allow for pathnames
4135 containing extended characters. This code is fragmentary, obsolete, and
4136 completely non-working. Instead, @var{pathname-coding-system} is used
4137 to specify conversions of names of files and directories. The standard
4138 C I/O functions like @samp{open()} are wrapped so that conversion occurs
4141 @file{mule.c} provides a few miscellaneous things that should probably
4150 This provides some miscellaneous internationalization code for
4151 implementing message translation and interfacing to the Ximp input
4152 method. None of this code is currently working.
4160 This contains leftover code from an earlier implementation of
4161 Asian-language support, and is not currently used.
4166 @node Allocation of Objects in XEmacs Lisp, Events and the Event Loop, A Summary of the Various XEmacs Modules, Top
4167 @chapter Allocation of Objects in XEmacs Lisp
4170 * Introduction to Allocation::
4171 * Garbage Collection::
4173 * Integers and Characters::
4174 * Allocation from Frob Blocks::
4176 * Low-level allocation::
4187 @node Introduction to Allocation
4188 @section Introduction to Allocation
4190 Emacs Lisp, like all Lisps, has garbage collection. This means that
4191 the programmer never has to explicitly free (destroy) an object; it
4192 happens automatically when the object becomes inaccessible. Most
4193 experts agree that garbage collection is a necessity in a modern,
4194 high-level language. Its omission from C stems from the fact that C was
4195 originally designed to be a nice abstract layer on top of assembly
4196 language, for writing kernels and basic system utilities rather than
4199 Lisp objects can be created by any of a number of Lisp primitives.
4200 Most object types have one or a small number of basic primitives
4201 for creating objects. For conses, the basic primitive is @code{cons};
4202 for vectors, the primitives are @code{make-vector} and @code{vector}; for
4203 symbols, the primitives are @code{make-symbol} and @code{intern}; etc.
4204 Some Lisp objects, especially those that are primarily used internally,
4205 have no corresponding Lisp primitives. Every Lisp object, though,
4206 has at least one C primitive for creating it.
4208 Recall from section (VII) that a Lisp object, as stored in a 32-bit
4209 or 64-bit word, has a mark bit, a few tag bits, and a ``value'' that
4210 occupies the remainder of the bits. We can separate the different
4211 Lisp object types into four broad categories:
4215 (a) Those for whom the value directly represents the contents of the
4216 Lisp object. Only two types are in this category: integers and
4217 characters. No special allocation or garbage collection is necessary
4218 for such objects. Lisp objects of these types do not need to be
4222 In the remaining three categories, the value is a pointer to a
4228 (b) Those for whom the tag directly specifies the type. Recall that
4229 there are only three tag bits; this means that at most five types can be
4230 specified this way. The most commonly-used types are stored in this
4231 format; this includes conses, strings, vectors, and sometimes symbols.
4232 With the exception of vectors, objects in this category are allocated in
4233 @dfn{frob blocks}, i.e. large blocks of memory that are subdivided into
4234 individual objects. This saves a lot on malloc overhead, since there
4235 are typically quite a lot of these objects around, and the objects are
4236 small. (A cons, for example, occupies 8 bytes on 32-bit machines -- 4
4237 bytes for each of the two objects it contains.) Vectors are individually
4238 @code{malloc()}ed since they are of variable size. (It would be
4239 possible, and desirable, to allocate vectors of certain small sizes out
4240 of frob blocks, but it isn't currently done.) Strings are handled
4241 specially: Each string is allocated in two parts, a fixed size structure
4242 containing a length and a data pointer, and the actual data of the
4243 string. The former structure is allocated in frob blocks as usual, and
4244 the latter data is stored in @dfn{string chars blocks} and is relocated
4245 during garbage collection to eliminate holes.
4248 In the remaining two categories, the type is stored in the object
4249 itself. The tag for all such objects is the generic @dfn{lrecord}
4250 (Lisp_Record) tag. The first four bytes (or eight, for 64-bit machines)
4251 of the object's structure are a pointer to a structure that describes
4252 the object's type, which includes method pointers and a pointer to a
4253 string naming the type. Note that it's possible to save some space by
4254 using a one- or two-byte tag, rather than a four- or eight-byte pointer
4255 to store the type, but it's not clear it's worth making the change.
4259 (c) Those lrecords that are allocated in frob blocks (see above). This
4260 includes the objects that are most common and relatively small, and
4261 includes floats, bytecodes, symbols (when not in category (b)), extents,
4262 events, and markers. With the cleanup of frob blocks done in 19.12,
4263 it's not terribly hard to add more objects to this category, but it's a
4264 bit trickier than adding an object type to type (d) (esp. if the object
4265 needs a finalization method), and is not likely to save much space
4266 unless the object is small and there are many of them. (In fact, if
4267 there are very few of them, it might actually waste space.)
4269 (d) Those lrecords that are individually @code{malloc()}ed. These are
4270 called @dfn{lcrecords}. All other types are in this category. Adding a
4271 new type to this category is comparatively easy, and all types added
4272 since 19.8 (when the current allocation scheme was devised, by Richard
4273 Mlynarik), with the exception of the character type, have been in this
4277 Note that bit vectors are a bit of a special case. They are
4278 simple lrecords as in category (c), but are individually @code{malloc()}ed
4279 like vectors. You can basically view them as exactly like vectors
4280 except that their type is stored in lrecord fashion rather than
4281 in directly-tagged fashion.
4283 Note that FSF Emacs redesigned their object system in 19.29 to follow
4284 a similar scheme. However, given RMS's expressed dislike for data
4285 abstraction, the FSF scheme is not nearly as clean or as easy to
4286 extend. (FSF calls items of type (c) @code{Lisp_Misc} and items of type
4287 (d) @code{Lisp_Vectorlike}, with separate tags for each, although
4288 @code{Lisp_Vectorlike} is also used for vectors.)
4290 @node Garbage Collection
4291 @section Garbage Collection
4292 @cindex garbage collection
4294 @cindex mark and sweep
4295 Garbage collection is simple in theory but tricky to implement.
4296 Emacs Lisp uses the oldest garbage collection method, called
4297 @dfn{mark and sweep}. Garbage collection begins by starting with
4298 all accessible locations (i.e. all variables and other slots where
4299 Lisp objects might occur) and recursively traversing all objects
4300 accessible from those slots, marking each one that is found.
4301 We then go through all of memory and free each object that is
4302 not marked, and unmarking each object that is marked. Note
4303 that ``all of memory'' means all currently allocated objects.
4304 Traversing all these objects means traversing all frob blocks,
4305 all vectors (which are chained in one big list), and all
4306 lcrecords (which are likewise chained).
4308 Note that, when an object is marked, the mark has to occur
4309 inside of the object's structure, rather than in the 32-bit
4310 @code{Lisp_Object} holding the object's pointer; i.e. you can't just
4311 set the pointer's mark bit. This is because there may be many
4312 pointers to the same object. This means that the method of
4313 marking an object can differ depending on the type. The
4314 different marking methods are approximately as follows:
4318 For conses, the mark bit of the car is set.
4320 For strings, the mark bit of the string's plist is set.
4322 For symbols when not lrecords, the mark bit of the
4323 symbol's plist is set.
4325 For vectors, the length is negated after adding 1.
4327 For lrecords, the pointer to the structure describing
4328 the type is changed (see below).
4330 Integers and characters do not need to be marked, since
4331 no allocation occurs for them.
4334 The details of this are in the @code{mark_object()} function.
4336 Note that any code that operates during garbage collection has
4337 to be especially careful because of the fact that some objects
4338 may be marked and as such may not look like they normally do.
4342 Some object pointers may have their mark bit set. This will make
4343 @code{FOOBARP()} predicates fail. Use @code{GC_FOOBARP()} to deal with
4346 Even if you clear the mark bit, @code{FOOBARP()} will still fail
4347 for lrecords because the implementation pointer has been
4348 changed (see below). @code{GC_FOOBARP()} will correctly deal with
4351 Vectors have their size field munged, so anything that
4352 looks at this field will fail.
4354 Note that @code{XFOOBAR()} macros @emph{will} work correctly on object
4355 pointers with their mark bit set, because the logical shift operations
4356 that remove the tag also remove the mark bit.
4359 Finally, note that garbage collection can be invoked explicitly
4360 by calling @code{garbage-collect} but is also called automatically
4361 by @code{eval}, once a certain amount of memory has been allocated
4362 since the last garbage collection (according to @code{gc-cons-threshold}).
4365 @section @code{GCPRO}ing
4367 @code{GCPRO}ing is one of the ugliest and trickiest parts of Emacs
4368 internals. The basic idea is that whenever garbage collection
4369 occurs, all in-use objects must be reachable somehow or
4370 other from one of the roots of accessibility. The roots
4371 of accessibility are:
4375 All objects that have been @code{staticpro()}d. This is used for
4376 any global C variables that hold Lisp objects. A call to
4377 @code{staticpro()} happens implicitly as a result of any symbols
4378 declared with @code{defsymbol()} and any variables declared with
4379 @code{DEFVAR_FOO()}. You need to explicitly call @code{staticpro()}
4380 (in the @code{vars_of_foo()} method of a module) for other global
4381 C variables holding Lisp objects. (This typically includes
4382 internal lists and such things.)
4384 Note that @code{obarray} is one of the @code{staticpro()}d things.
4385 Therefore, all functions and variables get marked through this.
4387 Any shadowed bindings that are sitting on the @code{specpdl} stack.
4389 Any objects sitting in currently active (Lisp) stack frames,
4390 catches, and condition cases.
4392 A couple of special-case places where active objects are
4395 Anything currently marked with @code{GCPRO}.
4398 Marking with @code{GCPRO} is necessary because some C functions (quite
4399 a lot, in fact), allocate objects during their operation. Quite
4400 frequently, there will be no other pointer to the object while the
4401 function is running, and if a garbage collection occurs and the object
4402 needs to be referenced again, bad things will happen. The solution is
4403 to mark those objects with @code{GCPRO}. Unfortunately this is easy to
4404 forget, and there is basically no way around this problem. Here are
4409 For every @code{GCPRO@var{n}}, there have to be declarations of
4410 @code{struct gcpro gcpro1, gcpro2}, etc.
4413 You @emph{must} @code{UNGCPRO} anything that's @code{GCPRO}ed, and you
4414 @emph{must not} @code{UNGCPRO} if you haven't @code{GCPRO}ed. Getting
4415 either of these wrong will lead to crashes, often in completely random
4416 places unrelated to where the problem lies.
4419 The way this actually works is that all currently active @code{GCPRO}s
4420 are chained through the @code{struct gcpro} local variables, with the
4421 variable @samp{gcprolist} pointing to the head of the list and the nth
4422 local @code{gcpro} variable pointing to the first @code{gcpro} variable
4423 in the next enclosing stack frame. Each @code{GCPRO}ed thing is an
4424 lvalue, and the @code{struct gcpro} local variable contains a pointer to
4425 this lvalue. This is why things will mess up badly if you don't pair up
4426 the @code{GCPRO}s and @code{UNGCPRO}s -- you will end up with
4427 @code{gcprolist}s containing pointers to @code{struct gcpro}s or local
4428 @code{Lisp_Object} variables in no-longer-active stack frames.
4431 It is actually possible for a single @code{struct gcpro} to
4432 protect a contiguous array of any number of values, rather than
4433 just a single lvalue. To effect this, call @code{GCPRO@var{n}} as usual on
4434 the first object in the array and then set @code{gcpro@var{n}.nvars}.
4437 @strong{Strings are relocated.} What this means in practice is that the
4438 pointer obtained using @code{XSTRING_DATA()} is liable to change at any
4439 time, and you should never keep it around past any function call, or
4440 pass it as an argument to any function that might cause a garbage
4441 collection. This is why a number of functions accept either a
4442 ``non-relocatable'' @code{char *} pointer or a relocatable Lisp string,
4443 and only access the Lisp string's data at the very last minute. In some
4444 cases, you may end up having to @code{alloca()} some space and copy the
4445 string's data into it.
4448 By convention, if you have to nest @code{GCPRO}'s, use @code{NGCPRO@var{n}}
4449 (along with @code{struct gcpro ngcpro1, ngcpro2}, etc.), @code{NNGCPRO@var{n}},
4450 etc. This avoids compiler warnings about shadowed locals.
4453 It is @emph{always} better to err on the side of extra @code{GCPRO}s
4454 rather than too few. The extra cycles spent on this are
4455 almost never going to make a whit of difference in the
4459 The general rule to follow is that caller, not callee, @code{GCPRO}s.
4460 That is, you should not have to explicitly @code{GCPRO} any Lisp objects
4461 that are passed in as parameters.
4463 One exception from this rule is if you ever plan to change the parameter
4464 value, and store a new object in it. In that case, you @emph{must}
4465 @code{GCPRO} the parameter, because otherwise the new object will not be
4468 So, if you create any Lisp objects (remember, this happens in all sorts
4469 of circumstances, e.g. with @code{Fcons()}, etc.), you are responsible
4470 for @code{GCPRO}ing them, unless you are @emph{absolutely sure} that
4471 there's no possibility that a garbage-collection can occur while you
4472 need to use the object. Even then, consider @code{GCPRO}ing.
4475 A garbage collection can occur whenever anything calls @code{Feval}, or
4476 whenever a QUIT can occur where execution can continue past
4477 this. (Remember, this is almost anywhere.)
4480 If you have the @emph{least smidgeon of doubt} about whether
4481 you need to @code{GCPRO}, you should @code{GCPRO}.
4484 Beware of @code{GCPRO}ing something that is uninitialized. If you have
4485 any shade of doubt about this, initialize all your variables to @code{Qnil}.
4488 Be careful of traps, like calling @code{Fcons()} in the argument to
4489 another function. By the ``caller protects'' law, you should be
4490 @code{GCPRO}ing the newly-created cons, but you aren't. A certain
4491 number of functions that are commonly called on freshly created stuff
4492 (e.g. @code{nconc2()}, @code{Fsignal()}), break the ``caller protects''
4493 law and go ahead and @code{GCPRO} their arguments so as to simplify
4494 things, but make sure and check if it's OK whenever doing something like
4498 Once again, remember to @code{GCPRO}! Bugs resulting from insufficient
4499 @code{GCPRO}ing are intermittent and extremely difficult to track down,
4500 often showing up in crashes inside of @code{garbage-collect} or in
4501 weirdly corrupted objects or even in incorrect values in a totally
4502 different section of code.
4505 @cindex garbage collection, conservative
4506 @cindex conservative garbage collection
4507 Given the extremely error-prone nature of the @code{GCPRO} scheme, and
4508 the difficulties in tracking down, it should be considered a deficiency
4509 in the XEmacs code. A solution to this problem would involve
4510 implementing so-called @dfn{conservative} garbage collection for the C
4511 stack. That involves looking through all of stack memory and treating
4512 anything that looks like a reference to an object as a reference. This
4513 will result in a few objects not getting collected when they should, but
4514 it obviates the need for @code{GCPRO}ing, and allows garbage collection
4515 to happen at any point at all, such as during object allocation.
4517 @node Integers and Characters
4518 @section Integers and Characters
4520 Integer and character Lisp objects are created from integers using the
4521 macros @code{XSETINT()} and @code{XSETCHAR()} or the equivalent
4522 functions @code{make_int()} and @code{make_char()}. (These are actually
4523 macros on most systems.) These functions basically just do some moving
4524 of bits around, since the integral value of the object is stored
4525 directly in the @code{Lisp_Object}.
4527 @code{XSETINT()} and the like will truncate values given to them that
4528 are too big; i.e. you won't get the value you expected but the tag bits
4529 will at least be correct.
4531 @node Allocation from Frob Blocks
4532 @section Allocation from Frob Blocks
4534 The uninitialized memory required by a @code{Lisp_Object} of a particular type
4536 @code{ALLOCATE_FIXED_TYPE()}. This only occurs inside of the
4537 lowest-level object-creating functions in @file{alloc.c}:
4538 @code{Fcons()}, @code{make_float()}, @code{Fmake_byte_code()},
4539 @code{Fmake_symbol()}, @code{allocate_extent()},
4540 @code{allocate_event()}, @code{Fmake_marker()}, and
4541 @code{make_uninit_string()}. The idea is that, for each type, there are
4542 a number of frob blocks (each 2K in size); each frob block is divided up
4543 into object-sized chunks. Each frob block will have some of these
4544 chunks that are currently assigned to objects, and perhaps some that are
4545 free. (If a frob block has nothing but free chunks, it is freed at the
4546 end of the garbage collection cycle.) The free chunks are stored in a
4547 free list, which is chained by storing a pointer in the first four bytes
4548 of the chunk. (Except for the free chunks at the end of the last frob
4549 block, which are handled using an index which points past the end of the
4550 last-allocated chunk in the last frob block.)
4551 @code{ALLOCATE_FIXED_TYPE()} first tries to retrieve a chunk from the
4552 free list; if that fails, it calls
4553 @code{ALLOCATE_FIXED_TYPE_FROM_BLOCK()}, which looks at the end of the
4554 last frob block for space, and creates a new frob block if there is
4555 none. (There are actually two versions of these macros, one of which is
4556 more defensive but less efficient and is used for error-checking.)
4561 [see @file{lrecord.h}]
4563 All lrecords have at the beginning of their structure a @code{struct
4564 lrecord_header}. This just contains a pointer to a @code{struct
4565 lrecord_implementation}, which is a structure containing method pointers
4566 and such. There is one of these for each type, and it is a global,
4567 constant, statically-declared structure that is declared in the
4568 @code{DEFINE_LRECORD_IMPLEMENTATION()} macro. (This macro actually
4569 declares an array of two @code{struct lrecord_implementation}
4570 structures. The first one contains all the standard method pointers,
4571 and is used in all normal circumstances. During garbage collection,
4572 however, the lrecord is @dfn{marked} by bumping its implementation
4573 pointer by one, so that it points to the second structure in the array.
4574 This structure contains a special indication in it that it's a
4575 @dfn{marked-object} structure: the finalize method is the special
4576 function @code{this_marks_a_marked_record()}, and all other methods are
4577 null pointers. At the end of garbage collection, all lrecords will
4578 either be reclaimed or unmarked by decrementing their implementation
4579 pointers, so this second structure pointer will never remain past
4582 Simple lrecords (of type (c) above) just have a @code{struct
4583 lrecord_header} at their beginning. lcrecords, however, actually have a
4584 @code{struct lcrecord_header}. This, in turn, has a @code{struct
4585 lrecord_header} at its beginning, so sanity is preserved; but it also
4586 has a pointer used to chain all lcrecords together, and a special ID
4587 field used to distinguish one lcrecord from another. (This field is used
4588 only for debugging and could be removed, but the space gain is not
4591 Simple lrecords are created using @code{ALLOCATE_FIXED_TYPE()}, just
4592 like for other frob blocks. The only change is that the implementation
4593 pointer must be initialized correctly. (The implementation structure for
4594 an lrecord, or rather the pointer to it, is named @code{lrecord_float},
4595 @code{lrecord_extent}, @code{lrecord_buffer}, etc.)
4597 lcrecords are created using @code{alloc_lcrecord()}. This takes a
4598 size to allocate and an implementation pointer. (The size needs to be
4599 passed because some lcrecords, such as window configurations, are of
4600 variable size.) This basically just @code{malloc()}s the storage,
4601 initializes the @code{struct lcrecord_header}, and chains the lcrecord
4602 onto the head of the list of all lcrecords, which is stored in the
4603 variable @code{all_lcrecords}. The calls to @code{alloc_lcrecord()}
4604 generally occur in the lowest-level allocation function for each lrecord
4607 Whenever you create an lrecord, you need to call either
4608 @code{DEFINE_LRECORD_IMPLEMENTATION()} or
4609 @code{DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION()}. This needs to be
4610 specified in a C file, at the top level. What this actually does is
4611 define and initialize the implementation structure for the lrecord. (And
4612 possibly declares a function @code{error_check_foo()} that implements
4613 the @code{XFOO()} macro when error-checking is enabled.) The arguments
4614 to the macros are the actual type name (this is used to construct the C
4615 variable name of the lrecord implementation structure and related
4616 structures using the @samp{##} macro concatenation operator), a string
4617 that names the type on the Lisp level (this may not be the same as the C
4618 type name; typically, the C type name has underscores, while the Lisp
4619 string has dashes), various method pointers, and the name of the C
4620 structure that contains the object. The methods are used to encapsulate
4621 type-specific information about the object, such as how to print it or
4622 mark it for garbage collection, so that it's easy to add new object
4623 types without having to add a specific case for each new type in a bunch
4624 of different places.
4626 The difference between @code{DEFINE_LRECORD_IMPLEMENTATION()} and
4627 @code{DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION()} is that the former is
4628 used for fixed-size object types and the latter is for variable-size
4629 object types. Most object types are fixed-size; some complex
4630 types, however (e.g. window configurations), are variable-size.
4631 Variable-size object types have an extra method, which is called
4632 to determine the actual size of a particular object of that type.
4633 (Currently this is only used for keeping allocation statistics.)
4635 For the purpose of keeping allocation statistics, the allocation
4636 engine keeps a list of all the different types that exist. Note that,
4637 since @code{DEFINE_LRECORD_IMPLEMENTATION()} is a macro that is
4638 specified at top-level, there is no way for it to add to the list of all
4639 existing types. What happens instead is that each implementation
4640 structure contains in it a dynamically assigned number that is
4641 particular to that type. (Or rather, it contains a pointer to another
4642 structure that contains this number. This evasiveness is done so that
4643 the implementation structure can be declared const.) In the sweep stage
4644 of garbage collection, each lrecord is examined to see if its
4645 implementation structure has its dynamically-assigned number set. If
4646 not, it must be a new type, and it is added to the list of known types
4647 and a new number assigned. The number is used to index into an array
4648 holding the number of objects of each type and the total memory
4649 allocated for objects of that type. The statistics in this array are
4650 also computed during the sweep stage. These statistics are returned by
4651 the call to @code{garbage-collect} and are printed out at the end of the
4654 Note that for every type defined with a @code{DEFINE_LRECORD_*()}
4655 macro, there needs to be a @code{DECLARE_LRECORD_IMPLEMENTATION()}
4656 somewhere in a @file{.h} file, and this @file{.h} file needs to be
4657 included by @file{inline.c}.
4659 Furthermore, there should generally be a set of @code{XFOOBAR()},
4660 @code{FOOBARP()}, etc. macros in a @file{.h} (or occasionally @file{.c})
4661 file. To create one of these, copy an existing model and modify as
4664 The various methods in the lrecord implementation structure are:
4669 A @dfn{mark} method. This is called during the marking stage and passed
4670 a function pointer (usually the @code{mark_object()} function), which is
4671 used to mark an object. All Lisp objects that are contained within the
4672 object need to be marked by applying this function to them. The mark
4673 method should also return a Lisp object, which should be either nil or
4674 an object to mark. (This can be used in lieu of calling
4675 @code{mark_object()} on the object, to reduce the recursion depth, and
4676 consequently should be the most heavily nested sub-object, such as a
4679 @strong{Please note:} When the mark method is called, garbage collection
4680 is in progress, and special precautions need to be taken when accessing
4681 objects; see section (B) above.
4683 If your mark method does not need to do anything, it can be
4687 A @dfn{print} method. This is called to create a printed representation
4688 of the object, whenever @code{princ}, @code{prin1}, or the like is
4689 called. It is passed the object, a stream to which the output is to be
4690 directed, and an @code{escapeflag} which indicates whether the object's
4691 printed representation should be @dfn{escaped} so that it is
4692 readable. (This corresponds to the difference between @code{princ} and
4693 @code{prin1}.) Basically, @dfn{escaped} means that strings will have
4694 quotes around them and confusing characters in the strings such as
4695 quotes, backslashes, and newlines will be backslashed; and that special
4696 care will be taken to make symbols print in a readable fashion
4697 (e.g. symbols that look like numbers will be backslashed). Other
4698 readable objects should perhaps pass @code{escapeflag} on when
4699 sub-objects are printed, so that readability is preserved when necessary
4700 (or if not, always pass in a 1 for @code{escapeflag}). Non-readable
4701 objects should in general ignore @code{escapeflag}, except that some use
4702 it as an indication that more verbose output should be given.
4704 Sub-objects are printed using @code{print_internal()}, which takes
4705 exactly the same arguments as are passed to the print method.
4707 Literal C strings should be printed using @code{write_c_string()},
4708 or @code{write_string_1()} for non-null-terminated strings.
4710 Functions that do not have a readable representation should check the
4711 @code{print_readably} flag and signal an error if it is set.
4713 If you specify NULL for the print method, the
4714 @code{default_object_printer()} will be used.
4717 A @dfn{finalize} method. This is called at the beginning of the sweep
4718 stage on lcrecords that are about to be freed, and should be used to
4719 perform any extra object cleanup. This typically involves freeing any
4720 extra @code{malloc()}ed memory associated with the object, releasing any
4721 operating-system and window-system resources associated with the object
4722 (e.g. pixmaps, fonts), etc.
4724 The finalize method can be NULL if nothing needs to be done.
4726 WARNING #1: The finalize method is also called at the end of the dump
4727 phase; this time with the for_disksave parameter set to non-zero. The
4728 object is @emph{not} about to disappear, so you have to make sure to
4729 @emph{not} free any extra @code{malloc()}ed memory if you're going to
4730 need it later. (Also, signal an error if there are any operating-system
4731 and window-system resources here, because they can't be dumped.)
4733 Finalize methods should, as a rule, set to zero any pointers after
4734 they've been freed, and check to make sure pointers are not zero before
4735 freeing. Although I'm pretty sure that finalize methods are not called
4736 twice on the same object (except for the @code{for_disksave} proviso),
4737 we've gotten nastily burned in some cases by not doing this.
4739 WARNING #2: The finalize method is @emph{only} called for
4740 lcrecords, @emph{not} for simply lrecords. If you need a
4741 finalize method for simple lrecords, you have to stick
4742 it in the @code{ADDITIONAL_FREE_foo()} macro in @file{alloc.c}.
4744 WARNING #3: Things are in an @emph{extremely} bizarre state
4745 when @code{ADDITIONAL_FREE_foo()} is called, so you have to
4746 be incredibly careful when writing one of these functions.
4747 See the comment in @code{gc_sweep()}. If you ever have to add
4748 one of these, consider using an lcrecord or dealing with
4749 the problem in a different fashion.
4752 An @dfn{equal} method. This compares the two objects for similarity,
4753 when @code{equal} is called. It should compare the contents of the
4754 objects in some reasonable fashion. It is passed the two objects and a
4755 @dfn{depth} value, which is used to catch circular objects. To compare
4756 sub-Lisp-objects, call @code{internal_equal()} and bump the depth value
4757 by one. If this value gets too high, a @code{circular-object} error
4760 If this is NULL, objects are @code{equal} only when they are @code{eq},
4764 A @dfn{hash} method. This is used to hash objects when they are to be
4765 compared with @code{equal}. The rule here is that if two objects are
4766 @code{equal}, they @emph{must} hash to the same value; i.e. your hash
4767 function should use some subset of the sub-fields of the object that are
4768 compared in the ``equal'' method. If you specify this method as
4769 @code{NULL}, the object's pointer will be used as the hash, which will
4770 @emph{fail} if the object has an @code{equal} method, so don't do this.
4772 To hash a sub-Lisp-object, call @code{internal_hash()}. Bump the
4773 depth by one, just like in the ``equal'' method.
4775 To convert a Lisp object directly into a hash value (using
4776 its pointer), use @code{LISP_HASH()}. This is what happens when
4777 the hash method is NULL.
4779 To hash two or more values together into a single value, use
4780 @code{HASH2()}, @code{HASH3()}, @code{HASH4()}, etc.
4783 @dfn{getprop}, @dfn{putprop}, @dfn{remprop}, and @dfn{plist} methods.
4784 These are used for object types that have properties. I don't feel like
4785 documenting them here. If you create one of these objects, you have to
4786 use different macros to define them,
4787 i.e. @code{DEFINE_LRECORD_IMPLEMENTATION_WITH_PROPS()} or
4788 @code{DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION_WITH_PROPS()}.
4791 A @dfn{size_in_bytes} method, when the object is of variable-size.
4792 (i.e. declared with a @code{_SEQUENCE_IMPLEMENTATION} macro.) This should
4793 simply return the object's size in bytes, exactly as you might expect.
4794 For an example, see the methods for window configurations and opaques.
4797 @node Low-level allocation
4798 @section Low-level allocation
4800 Memory that you want to allocate directly should be allocated using
4801 @code{xmalloc()} rather than @code{malloc()}. This implements
4802 error-checking on the return value, and once upon a time did some more
4803 vital stuff (i.e. @code{BLOCK_INPUT}, which is no longer necessary).
4804 Free using @code{xfree()}, and realloc using @code{xrealloc()}. Note
4805 that @code{xmalloc()} will do a non-local exit if the memory can't be
4806 allocated. (Many functions, however, do not expect this, and thus XEmacs
4807 will likely crash if this happens. @strong{This is a bug.} If you can,
4808 you should strive to make your function handle this OK. However, it's
4809 difficult in the general circumstance, perhaps requiring extra
4810 unwind-protects and such.)
4812 Note that XEmacs provides two separate replacements for the standard
4813 @code{malloc()} library function. These are called @dfn{old GNU malloc}
4814 (@file{malloc.c}) and @dfn{new GNU malloc} (@file{gmalloc.c}),
4815 respectively. New GNU malloc is better in pretty much every way than
4816 old GNU malloc, and should be used if possible. (It used to be that on
4817 some systems, the old one worked but the new one didn't. I think this
4818 was due specifically to a bug in SunOS, which the new one now works
4819 around; so I don't think the old one ever has to be used any more.) The
4820 primary difference between both of these mallocs and the standard system
4821 malloc is that they are much faster, at the expense of increased space.
4822 The basic idea is that memory is allocated in fixed chunks of powers of
4823 two. This allows for basically constant malloc time, since the various
4824 chunks can just be kept on a number of free lists. (The standard system
4825 malloc typically allocates arbitrary-sized chunks and has to spend some
4826 time, sometimes a significant amount of time, walking the heap looking
4827 for a free block to use and cleaning things up.) The new GNU malloc
4828 improves on things by allocating large objects in chunks of 4096 bytes
4829 rather than in ever larger powers of two, which results in ever larger
4830 wastage. There is a slight speed loss here, but it's of doubtful
4833 NOTE: Apparently there is a third-generation GNU malloc that is
4834 significantly better than the new GNU malloc, and should probably
4835 be included in XEmacs.
4837 There is also the relocating allocator, @file{ralloc.c}. This actually
4838 moves blocks of memory around so that the @code{sbrk()} pointer shrunk
4839 and virtual memory released back to the system. On some systems,
4840 this is a big win. On all systems, it causes a noticeable (and
4841 sometimes huge) speed penalty, so I turn it off by default.
4842 @file{ralloc.c} only works with the new GNU malloc in @file{gmalloc.c}.
4843 There are also two versions of @file{ralloc.c}, one that uses @code{mmap()}
4844 rather than block copies to move data around. This purports to
4845 be faster, although that depends on the amount of data that would
4846 have had to be block copied and the system-call overhead for
4847 @code{mmap()}. I don't know exactly how this works, except that the
4848 relocating-allocation routines are pretty much used only for
4849 the memory allocated for a buffer, which is the biggest consumer
4850 of space, esp. of space that may get freed later.
4852 Note that the GNU mallocs have some ``memory warning'' facilities.
4853 XEmacs taps into them and issues a warning through the standard
4854 warning system, when memory gets to 75%, 85%, and 95% full.
4855 (On some systems, the memory warnings are not functional.)
4857 Allocated memory that is going to be used to make a Lisp object
4858 is created using @code{allocate_lisp_storage()}. This calls @code{xmalloc()}
4859 but also verifies that the pointer to the memory can fit into
4860 a Lisp word (remember that some bits are taken away for a type
4861 tag and a mark bit). If not, an error is issued through @code{memory_full()}.
4862 @code{allocate_lisp_storage()} is called by @code{alloc_lcrecord()},
4863 @code{ALLOCATE_FIXED_TYPE()}, and the vector and bit-vector creation
4864 routines. These routines also call @code{INCREMENT_CONS_COUNTER()} at the
4865 appropriate times; this keeps statistics on how much memory is
4866 allocated, so that garbage-collection can be invoked when the
4867 threshold is reached.
4877 Conses are allocated in standard frob blocks. The only thing to
4878 note is that conses can be explicitly freed using @code{free_cons()}
4879 and associated functions @code{free_list()} and @code{free_alist()}. This
4880 immediately puts the conses onto the cons free list, and decrements
4881 the statistics on memory allocation appropriately. This is used
4882 to good effect by some extremely commonly-used code, to avoid
4883 generating extra objects and thereby triggering GC sooner.
4884 However, you have to be @emph{extremely} careful when doing this.
4885 If you mess this up, you will get BADLY BURNED, and it has happened
4891 As mentioned above, each vector is @code{malloc()}ed individually, and
4892 all are threaded through the variable @code{all_vectors}. Vectors are
4893 marked strangely during garbage collection, by kludging the size field.
4894 Note that the @code{struct Lisp_Vector} is declared with its
4895 @code{contents} field being a @emph{stretchy} array of one element. It
4896 is actually @code{malloc()}ed with the right size, however, and access
4897 to any element through the @code{contents} array works fine.
4902 Bit vectors work exactly like vectors, except for more complicated
4903 code to access an individual bit, and except for the fact that bit
4904 vectors are lrecords while vectors are not. (The only difference here is
4905 that there's an lrecord implementation pointer at the beginning and the
4906 tag field in bit vector Lisp words is ``lrecord'' rather than
4912 Symbols are also allocated in frob blocks. Note that the code
4913 exists for symbols to be either lrecords (category (c) above)
4914 or simple types (category (b) above), and are lrecords by
4915 default (I think), although there is no good reason for this.
4917 Note that symbols in the awful horrible obarray structure are
4918 chained through their @code{next} field.
4920 Remember that @code{intern} looks up a symbol in an obarray, creating
4926 Markers are allocated in frob blocks, as usual. They are kept
4927 in a buffer unordered, but in a doubly-linked list so that they
4928 can easily be removed. (Formerly this was a singly-linked list,
4929 but in some cases garbage collection took an extraordinarily
4930 long time due to the O(N^2) time required to remove lots of
4931 markers from a buffer.) Markers are removed from a buffer in
4932 the finalize stage, in @code{ADDITIONAL_FREE_marker()}.
4937 As mentioned above, strings are a special case. A string is logically
4938 two parts, a fixed-size object (containing the length, property list,
4939 and a pointer to the actual data), and the actual data in the string.
4940 The fixed-size object is a @code{struct Lisp_String} and is allocated in
4941 frob blocks, as usual. The actual data is stored in special
4942 @dfn{string-chars blocks}, which are 8K blocks of memory.
4943 Currently-allocated strings are simply laid end to end in these
4944 string-chars blocks, with a pointer back to the @code{struct Lisp_String}
4945 stored before each string in the string-chars block. When a new string
4946 needs to be allocated, the remaining space at the end of the last
4947 string-chars block is used if there's enough, and a new string-chars
4948 block is created otherwise.
4950 There are never any holes in the string-chars blocks due to the string
4951 compaction and relocation that happens at the end of garbage collection.
4952 During the sweep stage of garbage collection, when objects are
4953 reclaimed, the garbage collector goes through all string-chars blocks,
4954 looking for unused strings. Each chunk of string data is preceded by a
4955 pointer to the corresponding @code{struct Lisp_String}, which indicates
4956 both whether the string is used and how big the string is, i.e. how to
4957 get to the next chunk of string data. Holes are compressed by
4958 block-copying the next string into the empty space and relocating the
4959 pointer stored in the corresponding @code{struct Lisp_String}.
4960 @strong{This means you have to be careful with strings in your code.}
4961 See the section above on @code{GCPRO}ing.
4963 Note that there is one situation not handled: a string that is too big
4964 to fit into a string-chars block. Such strings, called @dfn{big
4965 strings}, are all @code{malloc()}ed as their own block. (#### Although it
4966 would make more sense for the threshold for big strings to be somewhat
4967 lower, e.g. 1/2 or 1/4 the size of a string-chars block. It seems that
4968 this was indeed the case formerly -- indeed, the threshold was set at
4969 1/8 -- but Mly forgot about this when rewriting things for 19.8.)
4971 Note also that the string data in string-chars blocks is padded as
4972 necessary so that proper alignment constraints on the @code{struct
4973 Lisp_String} back pointers are maintained.
4975 Finally, strings can be resized. This happens in Mule when a
4976 character is substituted with a different-length character, or during
4977 modeline frobbing. (You could also export this to Lisp, but it's not
4978 done so currently.) Resizing a string is a potentially tricky process.
4979 If the change is small enough that the padding can absorb it, nothing
4980 other than a simple memory move needs to be done. Keep in mind,
4981 however, that the string can't shrink too much because the offset to the
4982 next string in the string-chars block is computed by looking at the
4983 length and rounding to the nearest multiple of four or eight. If the
4984 string would shrink or expand beyond the correct padding, new string
4985 data needs to be allocated at the end of the last string-chars block and
4986 the data moved appropriately. This leaves some dead string data, which
4987 is marked by putting a special marker of 0xFFFFFFFF in the @code{struct
4988 Lisp_String} pointer before the data (there's no real @code{struct
4989 Lisp_String} to point to and relocate), and storing the size of the dead
4990 string data (which would normally be obtained from the now-non-existent
4991 @code{struct Lisp_String}) at the beginning of the dead string data gap.
4992 The string compactor recognizes this special 0xFFFFFFFF marker and
4993 handles it correctly.
5000 @node Events and the Event Loop, Evaluation; Stack Frames; Bindings, Allocation of Objects in XEmacs Lisp, Top
5001 @chapter Events and the Event Loop
5004 * Introduction to Events::
5006 * Specifics of the Event Gathering Mechanism::
5007 * Specifics About the Emacs Event::
5008 * The Event Stream Callback Routines::
5009 * Other Event Loop Functions::
5010 * Converting Events::
5011 * Dispatching Events; The Command Builder::
5014 @node Introduction to Events
5015 @section Introduction to Events
5017 An event is an object that encapsulates information about an
5018 interesting occurrence in the operating system. Events are
5019 generated either by user action, direct (e.g. typing on the
5020 keyboard or moving the mouse) or indirect (moving another
5021 window, thereby generating an expose event on an Emacs frame),
5022 or as a result of some other typically asynchronous action happening,
5023 such as output from a subprocess being ready or a timer expiring.
5024 Events come into the system in an asynchronous fashion (typically
5025 through a callback being called) and are converted into a
5026 synchronous event queue (first-in, first-out) in a process that
5027 we will call @dfn{collection}.
5029 Note that each application has its own event queue. (It is
5030 immaterial whether the collection process directly puts the
5031 events in the proper application's queue, or puts them into
5032 a single system queue, which is later split up.)
5034 The most basic level of event collection is done by the
5035 operating system or window system. Typically, XEmacs does
5036 its own event collection as well. Often there are multiple
5037 layers of collection in XEmacs, with events from various
5038 sources being collected into a queue, which is then combined
5039 with other sources to go into another queue (i.e. a second
5040 level of collection), with perhaps another level on top of
5043 XEmacs has its own types of events (called @dfn{Emacs events}),
5044 which provides an abstract layer on top of the system-dependent
5045 nature of the most basic events that are received. Part of the
5046 complex nature of the XEmacs event collection process involves
5047 converting from the operating-system events into the proper
5048 Emacs events -- there may not be a one-to-one correspondence.
5050 Emacs events are documented in @file{events.h}; I'll discuss them
5056 The @dfn{command loop} is the top-level loop that the editor is always
5057 running. It loops endlessly, calling @code{next-event} to retrieve an
5058 event and @code{dispatch-event} to execute it. @code{dispatch-event} does
5059 the appropriate thing with non-user events (process, timeout,
5060 magic, eval, mouse motion); this involves calling a Lisp handler
5061 function, redrawing a newly-exposed part of a frame, reading
5062 subprocess output, etc. For user events, @code{dispatch-event}
5063 looks up the event in relevant keymaps or menubars; when a
5064 full key sequence or menubar selection is reached, the appropriate
5065 function is executed. @code{dispatch-event} may have to keep state
5066 across calls; this is done in the ``command-builder'' structure
5067 associated with each console (remember, there's usually only
5068 one console), and the engine that looks up keystrokes and
5069 constructs full key sequences is called the @dfn{command builder}.
5070 This is documented elsewhere.
5072 The guts of the command loop are in @code{command_loop_1()}. This
5073 function doesn't catch errors, though -- that's the job of
5074 @code{command_loop_2()}, which is a condition-case (i.e. error-trapping)
5075 wrapper around @code{command_loop_1()}. @code{command_loop_1()} never
5076 returns, but may get thrown out of.
5078 When an error occurs, @code{cmd_error()} is called, which usually
5079 invokes the Lisp error handler in @code{command-error}; however, a
5080 default error handler is provided if @code{command-error} is @code{nil}
5081 (e.g. during startup). The purpose of the error handler is simply to
5082 display the error message and do associated cleanup; it does not need to
5083 throw anywhere. When the error handler finishes, the condition-case in
5084 @code{command_loop_2()} will finish and @code{command_loop_2()} will
5085 reinvoke @code{command_loop_1()}.
5087 @code{command_loop_2()} is invoked from three places: from
5088 @code{initial_command_loop()} (called from @code{main()} at the end of
5089 internal initialization), from the Lisp function @code{recursive-edit},
5090 and from @code{call_command_loop()}.
5092 @code{call_command_loop()} is called when a macro is started and when
5093 the minibuffer is entered; normal termination of the macro or minibuffer
5094 causes a throw out of the recursive command loop. (To
5095 @code{execute-kbd-macro} for macros and @code{exit} for minibuffers.
5096 Note also that the low-level minibuffer-entering function,
5097 @code{read-minibuffer-internal}, provides its own error handling and
5098 does not need @code{command_loop_2()}'s error encapsulation; so it tells
5099 @code{call_command_loop()} to invoke @code{command_loop_1()} directly.)
5101 Note that both read-minibuffer-internal and recursive-edit set up a
5102 catch for @code{exit}; this is why @code{abort-recursive-edit}, which
5103 throws to this catch, exits out of either one.
5105 @code{initial_command_loop()}, called from @code{main()}, sets up a
5106 catch for @code{top-level} when invoking @code{command_loop_2()},
5107 allowing functions to throw all the way to the top level if they really
5108 need to. Before invoking @code{command_loop_2()},
5109 @code{initial_command_loop()} calls @code{top_level_1()}, which handles
5110 all of the startup stuff (creating the initial frame, handling the
5111 command-line options, loading the user's @file{.emacs} file, etc.). The
5112 function that actually does this is in Lisp and is pointed to by the
5113 variable @code{top-level}; normally this function is
5114 @code{normal-top-level}. @code{top_level_1()} is just an error-handling
5115 wrapper similar to @code{command_loop_2()}. Note also that
5116 @code{initial_command_loop()} sets up a catch for @code{top-level} when
5117 invoking @code{top_level_1()}, just like when it invokes
5118 @code{command_loop_2()}.
5120 @node Specifics of the Event Gathering Mechanism
5121 @section Specifics of the Event Gathering Mechanism
5123 Here is an approximate diagram of the collection processes
5124 at work in XEmacs, under TTY's (TTY's are simpler than X
5125 so we'll look at this first):
5129 asynch. asynch. asynch. asynch. [Collectors in
5130 kbd events kbd events process process the OS]
5133 | | | | SIGINT, [signal handlers
5134 | | | | SIGQUIT, in XEmacs]
5136 file file file file SIGALRM
5137 desc. desc. desc. desc. |
5138 (TTY) (TTY) (pipe) (pipe) |
5139 | | | | fake timeouts
5147 ------>-----------<----------------<----------------
5150 | [collected using select() in emacs_tty_next_event()
5151 | and converted to the appropriate Emacs event]
5154 V (above this line is TTY-specific)
5155 Emacs ------------------------------------------------
5156 event (below this line is the generic event mechanism)
5159 was there if not, call
5160 a SIGINT? emacs_tty_next_event()
5167 | [collected in event_stream_next_event();
5168 | SIGINT is converted using maybe_read_quit_event()]
5173 \---->------>----- maybe_kbd_translate() ---->---\
5177 command event queue |
5179 (contains events that were event queue, call
5180 read earlier but not processed, event_stream_next_event()
5181 typically when waiting in a |
5182 sit-for, sleep-for, etc. for |
5183 a particular event to be received) |
5187 ---->------------------------------------<----
5190 | next_event_internal()]
5192 unread- unread- event from |
5193 command- command- keyboard else, call
5194 events event macro next_event_internal()
5199 --------->----------------------<------------
5201 | [collected in `next-event', which may loop
5202 | more than once if the event it gets is on
5203 | a dead frame, device, etc.]
5207 feed into top-level event loop,
5208 which repeatedly calls `next-event'
5209 and then dispatches the event
5210 using `dispatch-event'
5213 Notice the separation between TTY-specific and generic event mechanism.
5214 When using the Xt-based event loop, the TTY-specific stuff is replaced
5215 but the rest stays the same.
5217 It's also important to realize that only one different kind of
5218 system-specific event loop can be operating at a time, and must be able
5219 to receive all kinds of events simultaneously. For the two existing
5220 event loops (implemented in @file{event-tty.c} and @file{event-Xt.c},
5221 respectively), the TTY event loop @emph{only} handles TTY consoles,
5222 while the Xt event loop handles @emph{both} TTY and X consoles. This
5223 situation is different from all of the output handlers, where you simply
5224 have one per console type.
5226 Here's the Xt Event Loop Diagram (notice that below a certain point,
5227 it's the same as the above diagram):
5230 asynch. asynch. asynch. asynch. [Collectors in
5231 kbd kbd process process the OS]
5232 events events output output
5234 | | | | asynch. asynch. [Collectors in the
5235 | | | | X X OS and X Window System]
5236 | | | | events events
5239 | | | | | | SIGINT, [signal handlers
5240 | | | | | | SIGQUIT, in XEmacs]
5241 | | | | | | SIGWINCH,
5245 | | | | | | | timeouts
5250 file file file file file file file |
5251 desc. desc. desc. desc. desc. desc. desc. |
5252 (TTY) (TTY) (pipe) (pipe) (socket) (socket) (pipe) |
5257 --->----------------------------------------<---------<------
5259 | | | [collected using select() in
5260 | | | _XtWaitForSomething(), called
5261 | | | from XtAppProcessEvent(), called
5262 | | | in emacs_Xt_next_event();
5263 | | | dispatched to various callbacks]
5266 emacs_Xt_ p_s_callback(), | [popup_selection_callback]
5267 event_handler() x_u_v_s_callback(),| [x_update_vertical_scrollbar_
5268 | x_u_h_s_callback(),| callback]
5269 | search_callback() | [x_update_horizontal_scrollbar_
5273 enqueue_Xt_ signal_special_ |
5274 dispatch_event() Xt_user_event() |
5279 | dispatch_event() |
5286 dispatch Xt_what_callback()
5293 ---->-----------<--------
5296 | [collected and converted as appropriate in
5297 | emacs_Xt_next_event()]
5300 V (above this line is Xt-specific)
5301 Emacs ------------------------------------------------
5302 event (below this line is the generic event mechanism)
5305 was there if not, call
5306 a SIGINT? emacs_Xt_next_event()
5313 | [collected in event_stream_next_event();
5314 | SIGINT is converted using maybe_read_quit_event()]
5319 \---->------>----- maybe_kbd_translate() -->-----\
5323 command event queue |
5325 (contains events that were event queue, call
5326 read earlier but not processed, event_stream_next_event()
5327 typically when waiting in a |
5328 sit-for, sleep-for, etc. for |
5329 a particular event to be received) |
5333 ---->----------------------------------<------
5336 | next_event_internal()]
5338 unread- unread- event from |
5339 command- command- keyboard else, call
5340 events event macro next_event_internal()
5345 --------->----------------------<------------
5347 | [collected in `next-event', which may loop
5348 | more than once if the event it gets is on
5349 | a dead frame, device, etc.]
5353 feed into top-level event loop,
5354 which repeatedly calls `next-event'
5355 and then dispatches the event
5356 using `dispatch-event'
5359 @node Specifics About the Emacs Event
5360 @section Specifics About the Emacs Event
5362 @node The Event Stream Callback Routines
5363 @section The Event Stream Callback Routines
5365 @node Other Event Loop Functions
5366 @section Other Event Loop Functions
5368 @code{detect_input_pending()} and @code{input-pending-p} look for
5369 input by calling @code{event_stream->event_pending_p} and looking in
5370 @code{[V]unread-command-event} and the @code{command_event_queue} (they
5371 do not check for an executing keyboard macro, though).
5373 @code{discard-input} cancels any command events pending (and any
5374 keyboard macros currently executing), and puts the others onto the
5375 @code{command_event_queue}. There is a comment about a ``race
5376 condition'', which is not a good sign.
5378 @code{next-command-event} and @code{read-char} are higher-level
5379 interfaces to @code{next-event}. @code{next-command-event} gets the
5380 next @dfn{command} event (i.e. keypress, mouse event, menu selection,
5381 or scrollbar action), calling @code{dispatch-event} on any others.
5382 @code{read-char} calls @code{next-command-event} and uses
5383 @code{event_to_character()} to return the character equivalent. With
5384 the right kind of input method support, it is possible for (read-char)
5385 to return a Kanji character.
5387 @node Converting Events
5388 @section Converting Events
5390 @code{character_to_event()}, @code{event_to_character()},
5391 @code{event-to-character}, and @code{character-to-event} convert between
5392 characters and keypress events corresponding to the characters. If the
5393 event was not a keypress, @code{event_to_character()} returns -1 and
5394 @code{event-to-character} returns @code{nil}. These functions convert
5395 between character representation and the split-up event representation
5396 (keysym plus mod keys).
5398 @node Dispatching Events; The Command Builder
5399 @section Dispatching Events; The Command Builder
5403 @node Evaluation; Stack Frames; Bindings, Symbols and Variables, Events and the Event Loop, Top
5404 @chapter Evaluation; Stack Frames; Bindings
5408 * Dynamic Binding; The specbinding Stack; Unwind-Protects::
5409 * Simple Special Forms::
5416 @code{Feval()} evaluates the form (a Lisp object) that is passed to
5417 it. Note that evaluation is only non-trivial for two types of objects:
5418 symbols and conses. A symbol is evaluated simply by calling
5419 symbol-value on it and returning the value.
5421 Evaluating a cons means calling a function. First, @code{eval} checks
5422 to see if garbage-collection is necessary, and calls
5423 @code{Fgarbage_collect()} if so. It then increases the evaluation depth
5424 by 1 (@code{lisp_eval_depth}, which is always less than @code{max_lisp_eval_depth}) and adds an
5425 element to the linked list of @code{struct backtrace}'s
5426 (@code{backtrace_list}). Each such structure contains a pointer to the
5427 function being called plus a list of the function's arguments.
5428 Originally these values are stored unevalled, and as they are evaluated,
5429 the backtrace structure is updated. Garbage collection pays attention
5430 to the objects pointed to in the backtrace structures (garbage
5431 collection might happen while a function is being called or while an
5432 argument is being evaluated, and there could easily be no other
5433 references to the arguments in the argument list; once an argument is
5434 evaluated, however, the unevalled version is not needed by eval, and so
5435 the backtrace structure is changed).
5437 At this point, the function to be called is determined by looking at
5438 the car of the cons (if this is a symbol, its function definition is
5439 retrieved and the process repeated). The function should then consist
5440 of either a @code{Lisp_Subr} (built-in function), a
5441 @code{Lisp_Compiled_Function} object, or a cons whose car is the symbol
5442 @code{autoload}, @code{macro} or @code{lambda}.
5444 If the function is a @code{Lisp_Subr}, the lisp object points to a
5445 @code{struct Lisp_Subr} (created by @code{DEFUN()}), which contains a
5446 pointer to the C function, a minimum and maximum number of arguments
5447 (possibly the special constants @code{MANY} or @code{UNEVALLED}), a
5448 pointer to the symbol referring to that subr, and a couple of other
5449 things. If the subr wants its arguments @code{UNEVALLED}, they are
5450 passed raw as a list. Otherwise, an array of evaluated arguments is
5451 created and put into the backtrace structure, and either passed whole
5452 (@code{MANY}) or each argument is passed as a C argument.
5454 If the function is a @code{Lisp_Compiled_Function} object or a lambda,
5455 @code{apply_lambda()} is called. If the function is a macro,
5456 [..... fill in] is done. If the function is an autoload,
5457 @code{do_autoload()} is called to load the definition and then eval
5458 starts over [explain this more].
5460 When @code{Feval} exits, the evaluation depth is reduced by one, the
5461 debugger is called if appropriate, and the current backtrace structure
5462 is removed from the list.
5464 @code{apply_lambda()} is passed a function, a list of arguments, and a
5465 flag indicating whether to evaluate the arguments. It creates an array
5466 of (possibly) evaluated arguments and fixes up the backtrace structure,
5467 just like eval does. Then it calls @code{funcall_lambda()}.
5469 @code{funcall_lambda()} goes through the formal arguments to the
5470 function and binds them to the actual arguments, checking for
5471 @code{&rest} and @code{&optional} symbols in the formal arguments and
5472 making sure the number of actual arguments is correct. Then either
5473 @code{progn} or @code{byte-code} is called to actually execute the body
5476 @code{Ffuncall()} implements Lisp @code{funcall}. @code{(funcall fun
5477 x1 x2 x3 ...)} is equivalent to @code{(eval (list fun (quote x1) (quote
5478 x2) (quote x3) ...))}. @code{Ffuncall()} contains its own code to do
5479 the evaluation, however, and is almost identical to eval.
5481 @code{Fapply()} implements Lisp @code{apply}, which is very similar to
5482 @code{funcall} except that if the last argument is a list, the result is the
5483 same as if each of the arguments in the list had been passed separately.
5484 @code{Fapply()} does some business to expand the last argument if it's a
5485 list, then calls @code{Ffuncall()} to do the work.
5487 @code{apply1()}, @code{call0()}, @code{call1()}, @code{call2()}, and
5488 @code{call3()} call a function, passing it the argument(s) given (the
5489 arguments are given as separate C arguments rather than being passed as
5490 an array). @code{apply1()} uses @code{apply} while the others use
5493 @node Dynamic Binding; The specbinding Stack; Unwind-Protects
5494 @section Dynamic Binding; The specbinding Stack; Unwind-Protects
5499 Lisp_Object symbol, old_value;
5500 Lisp_Object (*func) (Lisp_Object); /* for unwind-protect */
5504 @code{struct specbinding} is used for local-variable bindings and
5505 unwind-protects. @code{specpdl} holds an array of @code{struct specbinding}'s,
5506 @code{specpdl_ptr} points to the beginning of the free bindings in the
5507 array, @code{specpdl_size} specifies the total number of binding slots
5508 in the array, and @code{max_specpdl_size} specifies the maximum number
5509 of bindings the array can be expanded to hold. @code{grow_specpdl()}
5510 increases the size of the @code{specpdl} array, multiplying its size by
5511 2 but never exceeding @code{max_specpdl_size} (except that if this
5512 number is less than 400, it is first set to 400).
5514 @code{specbind()} binds a symbol to a value and is used for local
5515 variables and @code{let} forms. The symbol and its old value (which
5516 might be @code{Qunbound}, indicating no prior value) are recorded in the
5517 specpdl array, and @code{specpdl_size} is increased by 1.
5519 @code{record_unwind_protect()} implements an @dfn{unwind-protect},
5520 which, when placed around a section of code, ensures that some specified
5521 cleanup routine will be executed even if the code exits abnormally
5522 (e.g. through a @code{throw} or quit). @code{record_unwind_protect()}
5523 simply adds a new specbinding to the @code{specpdl} array and stores the
5524 appropriate information in it. The cleanup routine can either be a C
5525 function, which is stored in the @code{func} field, or a @code{progn}
5526 form, which is stored in the @code{old_value} field.
5528 @code{unbind_to()} removes specbindings from the @code{specpdl} array
5529 until the specified position is reached. Each specbinding can be one of
5534 an unwind-protect with a C cleanup function (@code{func} is not 0, and
5535 @code{old_value} holds an argument to be passed to the function);
5537 an unwind-protect with a Lisp form (@code{func} is 0, @code{symbol}
5538 is @code{nil}, and @code{old_value} holds the form to be executed with
5539 @code{Fprogn()}); or
5541 a local-variable binding (@code{func} is 0, @code{symbol} is not
5542 @code{nil}, and @code{old_value} holds the old value, which is stored as
5543 the symbol's value).
5546 @node Simple Special Forms
5547 @section Simple Special Forms
5549 @code{or}, @code{and}, @code{if}, @code{cond}, @code{progn},
5550 @code{prog1}, @code{prog2}, @code{setq}, @code{quote}, @code{function},
5551 @code{let*}, @code{let}, @code{while}
5553 All of these are very simple and work as expected, calling
5554 @code{Feval()} or @code{Fprogn()} as necessary and (in the case of
5555 @code{let} and @code{let*}) using @code{specbind()} to create bindings
5556 and @code{unbind_to()} to undo the bindings when finished. Note that
5557 these functions do a lot of @code{GCPRO}ing to protect their arguments
5558 from garbage collection because they call @code{Feval()} (@pxref{Garbage
5561 @node Catch and Throw
5562 @section Catch and Throw
5569 struct catchtag *next;
5570 struct gcpro *gcpro;
5572 struct backtrace *backlist;
5573 int lisp_eval_depth;
5578 @code{catch} is a Lisp function that places a catch around a body of
5579 code. A catch is a means of non-local exit from the code. When a catch
5580 is created, a tag is specified, and executing a @code{throw} to this tag
5581 will exit from the body of code caught with this tag, and its value will
5582 be the value given in the call to @code{throw}. If there is no such
5583 call, the code will be executed normally.
5585 Information pertaining to a catch is held in a @code{struct catchtag},
5586 which is placed at the head of a linked list pointed to by
5587 @code{catchlist}. @code{internal_catch()} is passed a C function to
5588 call (@code{Fprogn()} when Lisp @code{catch} is called) and arguments to
5589 give it, and places a catch around the function. Each @code{struct
5590 catchtag} is held in the stack frame of the @code{internal_catch()}
5591 instance that created the catch.
5593 @code{internal_catch()} is fairly straightforward. It stores into the
5594 @code{struct catchtag} the tag name and the current values of
5595 @code{backtrace_list}, @code{lisp_eval_depth}, @code{gcprolist}, and the
5596 offset into the @code{specpdl} array, sets a jump point with @code{_setjmp()}
5597 (storing the jump point into the @code{struct catchtag}), and calls the
5598 function. Control will return to @code{internal_catch()} either when
5599 the function exits normally or through a @code{_longjmp()} to this jump
5600 point. In the latter case, @code{throw} will store the value to be
5601 returned into the @code{struct catchtag} before jumping. When it's
5602 done, @code{internal_catch()} removes the @code{struct catchtag} from
5603 the catchlist and returns the proper value.
5605 @code{Fthrow()} goes up through the catchlist until it finds one with
5606 a matching tag. It then calls @code{unbind_catch()} to restore
5607 everything to what it was when the appropriate catch was set, stores the
5608 return value in the @code{struct catchtag}, and jumps (with
5609 @code{_longjmp()}) to its jump point.
5611 @code{unbind_catch()} removes all catches from the catchlist until it
5612 finds the correct one. Some of the catches might have been placed for
5613 error-trapping, and if so, the appropriate entries on the handlerlist
5614 must be removed (see ``errors''). @code{unbind_catch()} also restores
5615 the values of @code{gcprolist}, @code{backtrace_list}, and
5616 @code{lisp_eval}, and calls @code{unbind_to()} to undo any specbindings
5617 created since the catch.
5620 @node Symbols and Variables, Buffers and Textual Representation, Evaluation; Stack Frames; Bindings, Top
5621 @chapter Symbols and Variables
5624 * Introduction to Symbols::
5629 @node Introduction to Symbols
5630 @section Introduction to Symbols
5632 A symbol is basically just an object with four fields: a name (a
5633 string), a value (some Lisp object), a function (some Lisp object), and
5634 a property list (usually a list of alternating keyword/value pairs).
5635 What makes symbols special is that there is usually only one symbol with
5636 a given name, and the symbol is referred to by name. This makes a
5637 symbol a convenient way of calling up data by name, i.e. of implementing
5638 variables. (The variable's value is stored in the @dfn{value slot}.)
5639 Similarly, functions are referenced by name, and the definition of the
5640 function is stored in a symbol's @dfn{function slot}. This means that
5641 there can be a distinct function and variable with the same name. The
5642 property list is used as a more general mechanism of associating
5643 additional values with particular names, and once again the namespace is
5644 independent of the function and variable namespaces.
5649 The identity of symbols with their names is accomplished through a
5650 structure called an obarray, which is just a poorly-implemented hash
5651 table mapping from strings to symbols whose name is that string. (I say
5652 ``poorly implemented'' because an obarray appears in Lisp as a vector
5653 with some hidden fields rather than as its own opaque type. This is an
5654 Emacs Lisp artifact that should be fixed.)
5656 Obarrays are implemented as a vector of some fixed size (which should
5657 be a prime for best results), where each ``bucket'' of the vector
5658 contains one or more symbols, threaded through a hidden @code{next}
5659 field in the symbol. Lookup of a symbol in an obarray, and adding a
5660 symbol to an obarray, is accomplished through standard hash-table
5663 The standard Lisp function for working with symbols and obarrays is
5664 @code{intern}. This looks up a symbol in an obarray given its name; if
5665 it's not found, a new symbol is automatically created with the specified
5666 name, added to the obarray, and returned. This is what happens when the
5667 Lisp reader encounters a symbol (or more precisely, encounters the name
5668 of a symbol) in some text that it is reading. There is a standard
5669 obarray called @code{obarray} that is used for this purpose, although
5670 the Lisp programmer is free to create his own obarrays and @code{intern}
5673 Note that, once a symbol is in an obarray, it stays there until
5674 something is done about it, and the standard obarray @code{obarray}
5675 always stays around, so once you use any particular variable name, a
5676 corresponding symbol will stay around in @code{obarray} until you exit
5679 Note that @code{obarray} itself is a variable, and as such there is a
5680 symbol in @code{obarray} whose name is @code{"obarray"} and which
5681 contains @code{obarray} as its value.
5683 Note also that this call to @code{intern} occurs only when in the Lisp
5684 reader, not when the code is executed (at which point the symbol is
5685 already around, stored as such in the definition of the function).
5687 You can create your own obarray using @code{make-vector} (this is
5688 horrible but is an artifact) and intern symbols into that obarray.
5689 Doing that will result in two or more symbols with the same name.
5690 However, at most one of these symbols is in the standard @code{obarray}:
5691 You cannot have two symbols of the same name in any particular obarray.
5692 Note that you cannot add a symbol to an obarray in any fashion other
5693 than using @code{intern}: i.e. you can't take an existing symbol and put
5694 it in an existing obarray. Nor can you change the name of an existing
5695 symbol. (Since obarrays are vectors, you can violate the consistency of
5696 things by storing directly into the vector, but let's ignore that
5699 Usually symbols are created by @code{intern}, but if you really want,
5700 you can explicitly create a symbol using @code{make-symbol}, giving it
5701 some name. The resulting symbol is not in any obarray (i.e. it is
5702 @dfn{uninterned}), and you can't add it to any obarray. Therefore its
5703 primary purpose is as a symbol to use in macros to avoid namespace
5704 pollution. It can also be used as a carrier of information, but cons
5705 cells could probably be used just as well.
5707 You can also use @code{intern-soft} to look up a symbol but not create
5708 a new one, and @code{unintern} to remove a symbol from an obarray. This
5709 returns the removed symbol. (Remember: You can't put the symbol back
5710 into any obarray.) Finally, @code{mapatoms} maps over all of the symbols
5714 @section Symbol Values
5716 The value field of a symbol normally contains a Lisp object. However,
5717 a symbol can be @dfn{unbound}, meaning that it logically has no value.
5718 This is internally indicated by storing a special Lisp object, called
5719 @dfn{the unbound marker} and stored in the global variable
5720 @code{Qunbound}. The unbound marker is of a special Lisp object type
5721 called @dfn{symbol-value-magic}. It is impossible for the Lisp
5722 programmer to directly create or access any object of this type.
5724 @strong{You must not let any ``symbol-value-magic'' object escape to
5725 the Lisp level.} Printing any of these objects will cause the message
5726 @samp{INTERNAL EMACS BUG} to appear as part of the print representation.
5727 (You may see this normally when you call @code{debug_print()} from the
5728 debugger on a Lisp object.) If you let one of these objects escape to
5729 the Lisp level, you will violate a number of assumptions contained in
5730 the C code and make the unbound marker not function right.
5732 When a symbol is created, its value field (and function field) are set
5733 to @code{Qunbound}. The Lisp programmer can restore these conditions
5734 later using @code{makunbound} or @code{fmakunbound}, and can query to
5735 see whether the value of function fields are @dfn{bound} (i.e. have a
5736 value other than @code{Qunbound}) using @code{boundp} and
5737 @code{fboundp}. The fields are set to a normal Lisp object using
5738 @code{set} (or @code{setq}) and @code{fset}.
5740 Other symbol-value-magic objects are used as special markers to
5741 indicate variables that have non-normal properties. This includes any
5742 variables that are tied into C variables (setting the variable magically
5743 sets some global variable in the C code, and likewise for retrieving the
5744 variable's value), variables that magically tie into slots in the
5745 current buffer, variables that are buffer-local, etc. The
5746 symbol-value-magic object is stored in the value cell in place of
5747 a normal object, and the code to retrieve a symbol's value
5748 (i.e. @code{symbol-value}) knows how to do special things with them.
5749 This means that you should not just fetch the value cell directly if you
5750 want a symbol's value.
5752 The exact workings of this are rather complex and involved and are
5753 well-documented in comments in @file{buffer.c}, @file{symbols.c}, and
5756 @node Buffers and Textual Representation, MULE Character Sets and Encodings, Symbols and Variables, Top
5757 @chapter Buffers and Textual Representation
5760 * Introduction to Buffers:: A buffer holds a block of text such as a file.
5761 * The Text in a Buffer:: Representation of the text in a buffer.
5762 * Buffer Lists:: Keeping track of all buffers.
5763 * Markers and Extents:: Tagging locations within a buffer.
5764 * Bufbytes and Emchars:: Representation of individual characters.
5765 * The Buffer Object:: The Lisp object corresponding to a buffer.
5768 @node Introduction to Buffers
5769 @section Introduction to Buffers
5771 A buffer is logically just a Lisp object that holds some text.
5772 In this, it is like a string, but a buffer is optimized for
5773 frequent insertion and deletion, while a string is not. Furthermore:
5777 Buffers are @dfn{permanent} objects, i.e. once you create them, they
5778 remain around, and need to be explicitly deleted before they go away.
5780 Each buffer has a unique name, which is a string. Buffers are
5781 normally referred to by name. In this respect, they are like
5784 Buffers have a default insertion position, called @dfn{point}.
5785 Inserting text (unless you explicitly give a position) goes at point,
5786 and moves point forward past the text. This is what is going on when
5787 you type text into Emacs.
5789 Buffers have lots of extra properties associated with them.
5791 Buffers can be @dfn{displayed}. What this means is that there
5792 exist a number of @dfn{windows}, which are objects that correspond
5793 to some visible section of your display, and each window has
5794 an associated buffer, and the current contents of the buffer
5795 are shown in that section of the display. The redisplay mechanism
5796 (which takes care of doing this) knows how to look at the
5797 text of a buffer and come up with some reasonable way of displaying
5798 this. Many of the properties of a buffer control how the
5799 buffer's text is displayed.
5801 One buffer is distinguished and called the @dfn{current buffer}. It is
5802 stored in the variable @code{current_buffer}. Buffer operations operate
5803 on this buffer by default. When you are typing text into a buffer, the
5804 buffer you are typing into is always @code{current_buffer}. Switching
5805 to a different window changes the current buffer. Note that Lisp code
5806 can temporarily change the current buffer using @code{set-buffer} (often
5807 enclosed in a @code{save-excursion} so that the former current buffer
5808 gets restored when the code is finished). However, calling
5809 @code{set-buffer} will NOT cause a permanent change in the current
5810 buffer. The reason for this is that the top-level event loop sets
5811 @code{current_buffer} to the buffer of the selected window, each time
5812 it finishes executing a user command.
5815 Make sure you understand the distinction between @dfn{current buffer}
5816 and @dfn{buffer of the selected window}, and the distinction between
5817 @dfn{point} of the current buffer and @dfn{window-point} of the selected
5818 window. (This latter distinction is explained in detail in the section
5821 @node The Text in a Buffer
5822 @section The Text in a Buffer
5824 The text in a buffer consists of a sequence of zero or more
5825 characters. A @dfn{character} is an integer that logically represents
5826 a letter, number, space, or other unit of text. Most of the characters
5827 that you will typically encounter belong to the ASCII set of characters,
5828 but there are also characters for various sorts of accented letters,
5829 special symbols, Chinese and Japanese ideograms (i.e. Kanji, Katakana,
5830 etc.), Cyrillic and Greek letters, etc. The actual number of possible
5831 characters is quite large.
5833 For now, we can view a character as some non-negative integer that
5834 has some shape that defines how it typically appears (e.g. as an
5835 uppercase A). (The exact way in which a character appears depends on the
5836 font used to display the character.) The internal type of characters in
5837 the C code is an @code{Emchar}; this is just an @code{int}, but using a
5838 symbolic type makes the code clearer.
5840 Between every character in a buffer is a @dfn{buffer position} or
5841 @dfn{character position}. We can speak of the character before or after
5842 a particular buffer position, and when you insert a character at a
5843 particular position, all characters after that position end up at new
5844 positions. When we speak of the character @dfn{at} a position, we
5845 really mean the character after the position. (This schizophrenia
5846 between a buffer position being ``between'' a character and ``on'' a
5847 character is rampant in Emacs.)
5849 Buffer positions are numbered starting at 1. This means that
5850 position 1 is before the first character, and position 0 is not
5851 valid. If there are N characters in a buffer, then buffer
5852 position N+1 is after the last one, and position N+2 is not valid.
5854 The internal makeup of the Emchar integer varies depending on whether
5855 we have compiled with MULE support. If not, the Emchar integer is an
5856 8-bit integer with possible values from 0 - 255. 0 - 127 are the
5857 standard ASCII characters, while 128 - 255 are the characters from the
5858 ISO-8859-1 character set. If we have compiled with MULE support, an
5859 Emchar is a 19-bit integer, with the various bits having meanings
5860 according to a complex scheme that will be detailed later. The
5861 characters numbered 0 - 255 still have the same meanings as for the
5862 non-MULE case, though.
5864 Internally, the text in a buffer is represented in a fairly simple
5865 fashion: as a contiguous array of bytes, with a @dfn{gap} of some size
5866 in the middle. Although the gap is of some substantial size in bytes,
5867 there is no text contained within it: From the perspective of the text
5868 in the buffer, it does not exist. The gap logically sits at some buffer
5869 position, between two characters (or possibly at the beginning or end of
5870 the buffer). Insertion of text in a buffer at a particular position is
5871 always accomplished by first moving the gap to that position
5872 (i.e. through some block moving of text), then writing the text into the
5873 beginning of the gap, thereby shrinking the gap. If the gap shrinks
5874 down to nothing, a new gap is created. (What actually happens is that a
5875 new gap is ``created'' at the end of the buffer's text, which requires
5876 nothing more than changing a couple of indices; then the gap is
5877 ``moved'' to the position where the insertion needs to take place by
5878 moving up in memory all the text after that position.) Similarly,
5879 deletion occurs by moving the gap to the place where the text is to be
5880 deleted, and then simply expanding the gap to include the deleted text.
5881 (@dfn{Expanding} and @dfn{shrinking} the gap as just described means
5882 just that the internal indices that keep track of where the gap is
5883 located are changed.)
5885 Note that the total amount of memory allocated for a buffer text never
5886 decreases while the buffer is live. Therefore, if you load up a
5887 20-megabyte file and then delete all but one character, there will be a
5888 20-megabyte gap, which won't get any smaller (except by inserting
5889 characters back again). Once the buffer is killed, the memory allocated
5890 for the buffer text will be freed, but it will still be sitting on the
5891 heap, taking up virtual memory, and will not be released back to the
5892 operating system. (However, if you have compiled XEmacs with rel-alloc,
5893 the situation is different. In this case, the space @emph{will} be
5894 released back to the operating system. However, this tends to result in a
5895 noticeable speed penalty.)
5897 Astute readers may notice that the text in a buffer is represented as
5898 an array of @emph{bytes}, while (at least in the MULE case) an Emchar is
5899 a 19-bit integer, which clearly cannot fit in a byte. This means (of
5900 course) that the text in a buffer uses a different representation from
5901 an Emchar: specifically, the 19-bit Emchar becomes a series of one to
5902 four bytes. The conversion between these two representations is complex
5903 and will be described later.
5905 In the non-MULE case, everything is very simple: An Emchar
5906 is an 8-bit value, which fits neatly into one byte.
5908 If we are given a buffer position and want to retrieve the
5909 character at that position, we need to follow these steps:
5913 Pretend there's no gap, and convert the buffer position into a @dfn{byte
5914 index} that indexes to the appropriate byte in the buffer's stream of
5915 textual bytes. By convention, byte indices begin at 1, just like buffer
5916 positions. In the non-MULE case, byte indices and buffer positions are
5917 identical, since one character equals one byte.
5919 Convert the byte index into a @dfn{memory index}, which takes the gap
5920 into account. The memory index is a direct index into the block of
5921 memory that stores the text of a buffer. This basically just involves
5922 checking to see if the byte index is past the gap, and if so, adding the
5923 size of the gap to it. By convention, memory indices begin at 1, just
5924 like buffer positions and byte indices, and when referring to the
5925 position that is @dfn{at} the gap, we always use the memory position at
5926 the @emph{beginning}, not at the end, of the gap.
5928 Fetch the appropriate bytes at the determined memory position.
5930 Convert these bytes into an Emchar.
5933 In the non-Mule case, (3) and (4) boil down to a simple one-byte
5936 Note that we have defined three types of positions in a buffer:
5940 @dfn{buffer positions} or @dfn{character positions}, typedef @code{Bufpos}
5942 @dfn{byte indices}, typedef @code{Bytind}
5944 @dfn{memory indices}, typedef @code{Memind}
5947 All three typedefs are just @code{int}s, but defining them this way makes
5948 things a lot clearer.
5950 Most code works with buffer positions. In particular, all Lisp code
5951 that refers to text in a buffer uses buffer positions. Lisp code does
5952 not know that byte indices or memory indices exist.
5954 Finally, we have a typedef for the bytes in a buffer. This is a
5955 @code{Bufbyte}, which is an unsigned char. Referring to them as
5956 Bufbytes underscores the fact that we are working with a string of bytes
5957 in the internal Emacs buffer representation rather than in one of a
5958 number of possible alternative representations (e.g. EUC-encoded text,
5962 @section Buffer Lists
5964 Recall earlier that buffers are @dfn{permanent} objects, i.e. that
5965 they remain around until explicitly deleted. This entails that there is
5966 a list of all the buffers in existence. This list is actually an
5967 assoc-list (mapping from the buffer's name to the buffer) and is stored
5968 in the global variable @code{Vbuffer_alist}.
5970 The order of the buffers in the list is important: the buffers are
5971 ordered approximately from most-recently-used to least-recently-used.
5972 Switching to a buffer using @code{switch-to-buffer},
5973 @code{pop-to-buffer}, etc. and switching windows using
5974 @code{other-window}, etc. usually brings the new current buffer to the
5975 front of the list. @code{switch-to-buffer}, @code{other-buffer},
5976 etc. look at the beginning of the list to find an alternative buffer to
5977 suggest. You can also explicitly move a buffer to the end of the list
5978 using @code{bury-buffer}.
5980 In addition to the global ordering in @code{Vbuffer_alist}, each frame
5981 has its own ordering of the list. These lists always contain the same
5982 elements as in @code{Vbuffer_alist} although possibly in a different
5983 order. @code{buffer-list} normally returns the list for the selected
5984 frame. This allows you to work in separate frames without things
5985 interfering with each other.
5987 The standard way to look up a buffer given a name is
5988 @code{get-buffer}, and the standard way to create a new buffer is
5989 @code{get-buffer-create}, which looks up a buffer with a given name,
5990 creating a new one if necessary. These operations correspond exactly
5991 with the symbol operations @code{intern-soft} and @code{intern},
5992 respectively. You can also force a new buffer to be created using
5993 @code{generate-new-buffer}, which takes a name and (if necessary) makes
5994 a unique name from this by appending a number, and then creates the
5995 buffer. This is basically like the symbol operation @code{gensym}.
5997 @node Markers and Extents
5998 @section Markers and Extents
6000 Among the things associated with a buffer are things that are
6001 logically attached to certain buffer positions. This can be used to
6002 keep track of a buffer position when text is inserted and deleted, so
6003 that it remains at the same spot relative to the text around it; to
6004 assign properties to particular sections of text; etc. There are two
6005 such objects that are useful in this regard: they are @dfn{markers} and
6008 A @dfn{marker} is simply a flag placed at a particular buffer
6009 position, which is moved around as text is inserted and deleted.
6010 Markers are used for all sorts of purposes, such as the @code{mark} that
6011 is the other end of textual regions to be cut, copied, etc.
6013 An @dfn{extent} is similar to two markers plus some associated
6014 properties, and is used to keep track of regions in a buffer as text is
6015 inserted and deleted, and to add properties (e.g. fonts) to particular
6016 regions of text. The external interface of extents is explained
6019 The important thing here is that markers and extents simply contain
6020 buffer positions in them as integers, and every time text is inserted or
6021 deleted, these positions must be updated. In order to minimize the
6022 amount of shuffling that needs to be done, the positions in markers and
6023 extents (there's one per marker, two per extent) and stored in Meminds.
6024 This means that they only need to be moved when the text is physically
6025 moved in memory; since the gap structure tries to minimize this, it also
6026 minimizes the number of marker and extent indices that need to be
6027 adjusted. Look in @file{insdel.c} for the details of how this works.
6029 One other important distinction is that markers are @dfn{temporary}
6030 while extents are @dfn{permanent}. This means that markers disappear as
6031 soon as there are no more pointers to them, and correspondingly, there
6032 is no way to determine what markers are in a buffer if you are just
6033 given the buffer. Extents remain in a buffer until they are detached
6034 (which could happen as a result of text being deleted) or the buffer is
6035 deleted, and primitives do exist to enumerate the extents in a buffer.
6037 @node Bufbytes and Emchars
6038 @section Bufbytes and Emchars
6042 @node The Buffer Object
6043 @section The Buffer Object
6045 Buffers contain fields not directly accessible by the Lisp programmer.
6046 We describe them here, naming them by the names used in the C code.
6047 Many are accessible indirectly in Lisp programs via Lisp primitives.
6051 The buffer name is a string that names the buffer. It is guaranteed to
6052 be unique. @xref{Buffer Names,,, lispref, XEmacs Lisp Programmer's
6056 This field contains the time when the buffer was last saved, as an
6057 integer. @xref{Buffer Modification,,, lispref, XEmacs Lisp Programmer's
6061 This field contains the modification time of the visited file. It is
6062 set when the file is written or read. Every time the buffer is written
6063 to the file, this field is compared to the modification time of the
6064 file. @xref{Buffer Modification,,, lispref, XEmacs Lisp Programmer's
6067 @item auto_save_modified
6068 This field contains the time when the buffer was last auto-saved.
6070 @item last_window_start
6071 This field contains the @code{window-start} position in the buffer as of
6072 the last time the buffer was displayed in a window.
6075 This field points to the buffer's undo list. @xref{Undo,,, lispref,
6076 XEmacs Lisp Programmer's Manual}.
6078 @item syntax_table_v
6079 This field contains the syntax table for the buffer. @xref{Syntax
6080 Tables,,, lispref, XEmacs Lisp Programmer's Manual}.
6082 @item downcase_table
6083 This field contains the conversion table for converting text to lower
6084 case. @xref{Case Tables,,, lispref, XEmacs Lisp Programmer's Manual}.
6087 This field contains the conversion table for converting text to upper
6088 case. @xref{Case Tables,,, lispref, XEmacs Lisp Programmer's Manual}.
6090 @item case_canon_table
6091 This field contains the conversion table for canonicalizing text for
6092 case-folding search. @xref{Case Tables,,, lispref, XEmacs Lisp
6093 Programmer's Manual}.
6095 @item case_eqv_table
6096 This field contains the equivalence table for case-folding search.
6097 @xref{Case Tables,,, lispref, XEmacs Lisp Programmer's Manual}.
6100 This field contains the buffer's display table, or @code{nil} if it
6101 doesn't have one. @xref{Display Tables,,, lispref, XEmacs Lisp
6102 Programmer's Manual}.
6105 This field contains the chain of all markers that currently point into
6106 the buffer. Deletion of text in the buffer, and motion of the buffer's
6107 gap, must check each of these markers and perhaps update it.
6108 @xref{Markers,,, lispref, XEmacs Lisp Programmer's Manual}.
6111 This field is a flag that tells whether a backup file has been made for
6112 the visited file of this buffer.
6115 This field contains the mark for the buffer. The mark is a marker,
6116 hence it is also included on the list @code{markers}. @xref{The Mark,,,
6117 lispref, XEmacs Lisp Programmer's Manual}.
6120 This field is non-@code{nil} if the buffer's mark is active.
6122 @item local_var_alist
6123 This field contains the association list describing the variables local
6124 in this buffer, and their values, with the exception of local variables
6125 that have special slots in the buffer object. (Those slots are omitted
6126 from this table.) @xref{Buffer-Local Variables,,, lispref, XEmacs Lisp
6127 Programmer's Manual}.
6129 @item modeline_format
6130 This field contains a Lisp object which controls how to display the mode
6131 line for this buffer. @xref{Modeline Format,,, lispref, XEmacs Lisp
6132 Programmer's Manual}.
6135 This field holds the buffer's base buffer (if it is an indirect buffer),
6139 @node MULE Character Sets and Encodings, The Lisp Reader and Compiler, Buffers and Textual Representation, Top
6140 @chapter MULE Character Sets and Encodings
6142 Recall that there are two primary ways that text is represented in
6143 XEmacs. The @dfn{buffer} representation sees the text as a series of
6144 bytes (Bufbytes), with a variable number of bytes used per character.
6145 The @dfn{character} representation sees the text as a series of integers
6146 (Emchars), one per character. The character representation is a cleaner
6147 representation from a theoretical standpoint, and is thus used in many
6148 cases when lots of manipulations on a string need to be done. However,
6149 the buffer representation is the standard representation used in both
6150 Lisp strings and buffers, and because of this, it is the ``default''
6151 representation that text comes in. The reason for using this
6152 representation is that it's compact and is compatible with ASCII.
6157 * Internal Mule Encodings::
6161 @node Character Sets
6162 @section Character Sets
6164 A character set (or @dfn{charset}) is an ordered set of characters. A
6165 particular character in a charset is indexed using one or more
6166 @dfn{position codes}, which are non-negative integers. The number of
6167 position codes needed to identify a particular character in a charset is
6168 called the @dfn{dimension} of the charset. In XEmacs/Mule, all charsets
6169 have dimension 1 or 2, and the size of all charsets (except for a few
6170 special cases) is either 94, 96, 94 by 94, or 96 by 96. The range of
6171 position codes used to index characters from any of these types of
6172 character sets is as follows:
6175 Charset type Position code 1 Position code 2
6176 ------------------------------------------------------------
6179 94x94 33 - 126 33 - 126
6180 96x96 32 - 127 32 - 127
6183 Note that in the above cases position codes do not start at an
6184 expected value such as 0 or 1. The reason for this will become clear
6187 For example, Latin-1 is a 96-character charset, and JISX0208 (the
6188 Japanese national character set) is a 94x94-character charset.
6190 [Note that, although the ranges above define the @emph{valid} position
6191 codes for a charset, some of the slots in a particular charset may in
6192 fact be empty. This is the case for JISX0208, for example, where (e.g.)
6193 all the slots whose first position code is in the range 118 - 127 are
6196 There are three charsets that do not follow the above rules. All of
6197 them have one dimension, and have ranges of position codes as follows:
6200 Charset name Position code 1
6201 ------------------------------------
6204 Composite 0 - some large number
6207 (The upper bound of the position code for composite characters has not
6208 yet been determined, but it will probably be at least 16,383).
6210 ASCII is the union of two subsidiary character sets: Printing-ASCII
6211 (the printing ASCII character set, consisting of position codes 33 -
6212 126, like for a standard 94-character charset) and Control-ASCII (the
6213 non-printing characters that would appear in a binary file with codes 0
6216 Control-1 contains the non-printing characters that would appear in a
6217 binary file with codes 128 - 159.
6219 Composite contains characters that are generated by overstriking one
6220 or more characters from other charsets.
6222 Note that some characters in ASCII, and all characters in Control-1,
6223 are @dfn{control} (non-printing) characters. These have no printed
6224 representation but instead control some other function of the printing
6225 (e.g. TAB or 8 moves the current character position to the next tab
6226 stop). All other characters in all charsets are @dfn{graphic}
6227 (printing) characters.
6229 When a binary file is read in, the bytes in the file are assigned to
6230 character sets as follows:
6233 Bytes Character set Range
6234 --------------------------------------------------
6235 0 - 127 ASCII 0 - 127
6236 128 - 159 Control-1 0 - 31
6237 160 - 255 Latin-1 32 - 127
6240 This is a bit ad-hoc but gets the job done.
6245 An @dfn{encoding} is a way of numerically representing characters from
6246 one or more character sets. If an encoding only encompasses one
6247 character set, then the position codes for the characters in that
6248 character set could be used directly. This is not possible, however, if
6249 more than one character set is to be used in the encoding.
6251 For example, the conversion detailed above between bytes in a binary
6252 file and characters is effectively an encoding that encompasses the
6253 three character sets ASCII, Control-1, and Latin-1 in a stream of 8-bit
6256 Thus, an encoding can be viewed as a way of encoding characters from a
6257 specified group of character sets using a stream of bytes, each of which
6258 contains a fixed number of bits (but not necessarily 8, as in the common
6261 Here are descriptions of a couple of common
6265 * Japanese EUC (Extended Unix Code)::
6269 @node Japanese EUC (Extended Unix Code)
6270 @subsection Japanese EUC (Extended Unix Code)
6272 This encompasses the character sets Printing-ASCII, Japanese-JISSX0201,
6273 and Japanese-JISX0208-Kana (half-width katakana, the right half of
6274 JISX0201). It uses 8-bit bytes.
6276 Note that Printing-ASCII and Japanese-JISX0201-Kana are 94-character
6277 charsets, while Japanese-JISX0208 is a 94x94-character charset.
6279 The encoding is as follows:
6282 Character set Representation (PC=position-code)
6283 ------------- --------------
6285 Japanese-JISX0201-Kana 0x8E | PC1 + 0x80
6286 Japanese-JISX0208 PC1 + 0x80 | PC2 + 0x80
6287 Japanese-JISX0212 PC1 + 0x80 | PC2 + 0x80
6294 This encompasses the character sets Printing-ASCII,
6295 Japanese-JISX0201-Roman (the left half of JISX0201; this character set
6296 is very similar to Printing-ASCII and is a 94-character charset),
6297 Japanese-JISX0208, and Japanese-JISX0201-Kana. It uses 7-bit bytes.
6299 Unlike Japanese EUC, this is a @dfn{modal} encoding, which
6300 means that there are multiple states that the encoding can
6301 be in, which affect how the bytes are to be interpreted.
6302 Special sequences of bytes (called @dfn{escape sequences})
6303 are used to change states.
6305 The encoding is as follows:
6308 Character set Representation (PC=position-code)
6309 ------------- --------------
6311 Japanese-JISX0201-Roman PC1
6312 Japanese-JISX0201-Kana PC1
6313 Japanese-JISX0208 PC1 PC2
6316 Escape sequence ASCII equivalent Meaning
6317 --------------- ---------------- -------
6318 0x1B 0x28 0x4A ESC ( J invoke Japanese-JISX0201-Roman
6319 0x1B 0x28 0x49 ESC ( I invoke Japanese-JISX0201-Kana
6320 0x1B 0x24 0x42 ESC $ B invoke Japanese-JISX0208
6321 0x1B 0x28 0x42 ESC ( B invoke Printing-ASCII
6324 Initially, Printing-ASCII is invoked.
6326 @node Internal Mule Encodings
6327 @section Internal Mule Encodings
6329 In XEmacs/Mule, each character set is assigned a unique number, called a
6330 @dfn{leading byte}. This is used in the encodings of a character.
6331 Leading bytes are in the range 0x80 - 0xFF (except for ASCII, which has
6332 a leading byte of 0), although some leading bytes are reserved.
6334 Charsets whose leading byte is in the range 0x80 - 0x9F are called
6335 @dfn{official} and are used for built-in charsets. Other charsets are
6336 called @dfn{private} and have leading bytes in the range 0xA0 - 0xFF;
6337 these are user-defined charsets.
6342 Character set Leading byte
6343 ------------- ------------
6346 Dimension-1 Official 0x81 - 0x8D
6349 Dimension-2 Official 0x90 - 0x99
6350 (0x9A - 0x9D are free;
6351 0x9E and 0x9F are reserved)
6352 Dimension-1 Private 0xA0 - 0xEF
6353 Dimension-2 Private 0xF0 - 0xFF
6356 There are two internal encodings for characters in XEmacs/Mule. One is
6357 called @dfn{string encoding} and is an 8-bit encoding that is used for
6358 representing characters in a buffer or string. It uses 1 to 4 bytes per
6359 character. The other is called @dfn{character encoding} and is a 19-bit
6360 encoding that is used for representing characters individually in a
6363 (In the following descriptions, we'll ignore composite characters for
6364 the moment. We also give a general (structural) overview first,
6365 followed later by the exact details.)
6368 * Internal String Encoding::
6369 * Internal Character Encoding::
6372 @node Internal String Encoding
6373 @subsection Internal String Encoding
6375 ASCII characters are encoded using their position code directly. Other
6376 characters are encoded using their leading byte followed by their
6377 position code(s) with the high bit set. Characters in private character
6378 sets have their leading byte prefixed with a @dfn{leading byte prefix},
6379 which is either 0x9E or 0x9F. (No character sets are ever assigned these
6380 leading bytes.) Specifically:
6383 Character set Encoding (PC=position-code, LB=leading-byte)
6384 ------------- --------
6386 Control-1 LB | PC1 + 0xA0 |
6387 Dimension-1 official LB | PC1 + 0x80 |
6388 Dimension-1 private 0x9E | LB | PC1 + 0x80 |
6389 Dimension-2 official LB | PC1 + 0x80 | PC2 + 0x80 |
6390 Dimension-2 private 0x9F | LB | PC1 + 0x80 | PC2 + 0x80
6393 The basic characteristic of this encoding is that the first byte
6394 of all characters is in the range 0x00 - 0x9F, and the second and
6395 following bytes of all characters is in the range 0xA0 - 0xFF.
6396 This means that it is impossible to get out of sync, or more
6401 Given any byte position, the beginning of the character it is
6402 within can be determined in constant time.
6404 Given any byte position at the beginning of a character, the
6405 beginning of the next character can be determined in constant
6408 Given any byte position at the beginning of a character, the
6409 beginning of the previous character can be determined in constant
6412 Textual searches can simply treat encoded strings as if they
6413 were encoded in a one-byte-per-character fashion rather than
6414 the actual multi-byte encoding.
6417 None of the standard non-modal encodings meet all of these
6418 conditions. For example, EUC satisfies only (2) and (3), while
6419 Shift-JIS and Big5 (not yet described) satisfy only (2). (All
6420 non-modal encodings must satisfy (2), in order to be unambiguous.)
6422 @node Internal Character Encoding
6423 @subsection Internal Character Encoding
6425 One 19-bit word represents a single character. The word is
6426 separated into three fields:
6429 Bit number: 18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
6430 <------------> <------------------> <------------------>
6434 Note that fields 2 and 3 hold 7 bits each, while field 1 holds 5 bits.
6437 Character set Field 1 Field 2 Field 3
6438 ------------- ------- ------- -------
6443 Dimension-1 official 0 LB - 0x80 PC1
6444 range: (01 - 0D) (20 - 7F)
6445 Dimension-1 private 0 LB - 0x80 PC1
6446 range: (20 - 6F) (20 - 7F)
6447 Dimension-2 official LB - 0x8F PC1 PC2
6448 range: (01 - 0A) (20 - 7F) (20 - 7F)
6449 Dimension-2 private LB - 0xE1 PC1 PC2
6450 range: (0F - 1E) (20 - 7F) (20 - 7F)
6454 Note that character codes 0 - 255 are the same as the ``binary encoding''
6462 CCL_PROGRAM := (CCL_MAIN_BLOCK
6465 CCL_MAIN_BLOCK := CCL_BLOCK
6466 CCL_EOF_BLOCK := CCL_BLOCK
6468 CCL_BLOCK := STATEMENT | (STATEMENT [STATEMENT ...])
6470 SET | IF | BRANCH | LOOP | REPEAT | BREAK
6473 SET := (REG = EXPRESSION) | (REG SELF_OP EXPRESSION)
6476 EXPRESSION := ARG | (EXPRESSION OP ARG)
6478 IF := (if EXPRESSION CCL_BLOCK CCL_BLOCK)
6479 BRANCH := (branch EXPRESSION CCL_BLOCK [CCL_BLOCK ...])
6480 LOOP := (loop STATEMENT [STATEMENT ...])
6483 | (write-repeat [REG | INT-OR-CHAR | string])
6484 | (write-read-repeat REG [INT-OR-CHAR | string | ARRAY]?)
6485 READ := (read REG) | (read REG REG)
6486 | (read-if REG ARITH_OP ARG CCL_BLOCK CCL_BLOCK)
6487 | (read-branch REG CCL_BLOCK [CCL_BLOCK ...])
6488 WRITE := (write REG) | (write REG REG)
6489 | (write INT-OR-CHAR) | (write STRING) | STRING
6493 REG := r0 | r1 | r2 | r3 | r4 | r5 | r6 | r7
6494 ARG := REG | INT-OR-CHAR
6495 OP := + | - | * | / | % | & | '|' | ^ | << | >> | <8 | >8 | //
6496 | < | > | == | <= | >= | !=
6498 += | -= | *= | /= | %= | &= | '|=' | ^= | <<= | >>=
6499 ARRAY := '[' INT-OR-CHAR ... ']'
6500 INT-OR-CHAR := INT | CHAR
6504 The machine code consists of a vector of 32-bit words.
6505 The first such word specifies the start of the EOF section of the code;
6506 this is the code executed to handle any stuff that needs to be done
6507 (e.g. designating back to ASCII and left-to-right mode) after all
6508 other encoded/decoded data has been written out. This is not used for
6509 charset CCL programs.
6511 REGISTER: 0..7 -- refered by RRR or rrr
6513 OPERATOR BIT FIELD (27-bit): XXXXXXXXXXXXXXX RRR TTTTT
6514 TTTTT (5-bit): operator type
6515 RRR (3-bit): register number
6516 XXXXXXXXXXXXXXXX (15-bit):
6517 CCCCCCCCCCCCCCC: constant or address
6518 000000000000rrr: register number
6545 OPERATORS: TTTTT RRR XX..
6547 SetCS: 00000 RRR C...C RRR = C...C
6548 SetCL: 00001 RRR ..... RRR = c...c
6550 SetR: 00010 RRR ..rrr RRR = rrr
6551 SetA: 00011 RRR ..rrr RRR = array[rrr]
6552 C.............C size of array = C...C
6553 c.............c contents = c...c
6555 Jump: 00100 000 c...c jump to c...c
6556 JumpCond: 00101 RRR c...c if (!RRR) jump to c...c
6557 WriteJump: 00110 RRR c...c Write1 RRR, jump to c...c
6558 WriteReadJump: 00111 RRR c...c Write1, Read1 RRR, jump to c...c
6559 WriteCJump: 01000 000 c...c Write1 C...C, jump to c...c
6561 WriteCReadJump: 01001 RRR c...c Write1 C...C, Read1 RRR,
6562 C.............C and jump to c...c
6563 WriteSJump: 01010 000 c...c WriteS, jump to c...c
6567 WriteSReadJump: 01011 RRR c...c WriteS, Read1 RRR, jump to c...c
6571 WriteAReadJump: 01100 RRR c...c WriteA, Read1 RRR, jump to c...c
6572 C.............C size of array = C...C
6573 c.............c contents = c...c
6575 Branch: 01101 RRR C...C if (RRR >= 0 && RRR < C..)
6576 c.............c branch to (RRR+1)th address
6577 Read1: 01110 RRR ... read 1-byte to RRR
6578 Read2: 01111 RRR ..rrr read 2-byte to RRR and rrr
6579 ReadBranch: 10000 RRR C...C Read1 and Branch
6582 Write1: 10001 RRR ..... write 1-byte RRR
6583 Write2: 10010 RRR ..rrr write 2-byte RRR and rrr
6584 WriteC: 10011 000 ..... write 1-char C...CC
6586 WriteS: 10100 000 ..... write C..-byte of string
6590 WriteA: 10101 RRR ..... write array[RRR]
6591 C.............C size of array = C...C
6592 c.............c contents = c...c
6594 End: 10110 000 ..... terminate the execution
6596 SetSelfCS: 10111 RRR C...C RRR AAAAA= C...C
6598 SetSelfCL: 11000 RRR ..... RRR AAAAA= c...c
6601 SetSelfR: 11001 RRR ..Rrr RRR AAAAA= rrr
6603 SetExprCL: 11010 RRR ..Rrr RRR = rrr AAAAA c...c
6606 SetExprR: 11011 RRR ..rrr RRR = rrr AAAAA Rrr
6609 JumpCondC: 11100 RRR c...c if !(RRR AAAAA C..) jump to c...c
6612 JumpCondR: 11101 RRR c...c if !(RRR AAAAA rrr) jump to c...c
6615 ReadJumpCondC: 11110 RRR c...c Read1 and JumpCondC
6618 ReadJumpCondR: 11111 RRR c...c Read1 and JumpCondR
6623 @node The Lisp Reader and Compiler, Lstreams, MULE Character Sets and Encodings, Top
6624 @chapter The Lisp Reader and Compiler
6628 @node Lstreams, Consoles; Devices; Frames; Windows, The Lisp Reader and Compiler, Top
6631 An @dfn{lstream} is an internal Lisp object that provides a generic
6632 buffering stream implementation. Conceptually, you send data to the
6633 stream or read data from the stream, not caring what's on the other end
6634 of the stream. The other end could be another stream, a file
6635 descriptor, a stdio stream, a fixed block of memory, a reallocating
6636 block of memory, etc. The main purpose of the stream is to provide a
6637 standard interface and to do buffering. Macros are defined to read or
6638 write characters, so the calling functions do not have to worry about
6639 blocking data together in order to achieve efficiency.
6642 * Creating an Lstream:: Creating an lstream object.
6643 * Lstream Types:: Different sorts of things that are streamed.
6644 * Lstream Functions:: Functions for working with lstreams.
6645 * Lstream Methods:: Creating new lstream types.
6648 @node Creating an Lstream
6649 @section Creating an Lstream
6651 Lstreams come in different types, depending on what is being interfaced
6652 to. Although the primitive for creating new lstreams is
6653 @code{Lstream_new()}, generally you do not call this directly. Instead,
6654 you call some type-specific creation function, which creates the lstream
6655 and initializes it as appropriate for the particular type.
6657 All lstream creation functions take a @var{mode} argument, specifying
6658 what mode the lstream should be opened as. This controls whether the
6659 lstream is for input and output, and optionally whether data should be
6660 blocked up in units of MULE characters. Note that some types of
6661 lstreams can only be opened for input; others only for output; and
6662 others can be opened either way. #### Richard Mlynarik thinks that
6663 there should be a strict separation between input and output streams,
6664 and he's probably right.
6666 @var{mode} is a string, one of
6674 Open for reading, but ``read'' never returns partial MULE characters.
6676 Open for writing, but never writes partial MULE characters.
6680 @section Lstream Types
6691 @item resizing-buffer
6704 @node Lstream Functions
6705 @section Lstream Functions
6707 @deftypefun {Lstream *} Lstream_new (Lstream_implementation *@var{imp}, CONST char *@var{mode})
6708 Allocate and return a new Lstream. This function is not really meant to
6709 be called directly; rather, each stream type should provide its own
6710 stream creation function, which creates the stream and does any other
6711 necessary creation stuff (e.g. opening a file).
6714 @deftypefun void Lstream_set_buffering (Lstream *@var{lstr}, Lstream_buffering @var{buffering}, int @var{buffering_size})
6715 Change the buffering of a stream. See @file{lstream.h}. By default the
6716 buffering is @code{STREAM_BLOCK_BUFFERED}.
6719 @deftypefun int Lstream_flush (Lstream *@var{lstr})
6720 Flush out any pending unwritten data in the stream. Clear any buffered
6721 input data. Returns 0 on success, -1 on error.
6724 @deftypefn Macro int Lstream_putc (Lstream *@var{stream}, int @var{c})
6725 Write out one byte to the stream. This is a macro and so it is very
6726 efficient. The @var{c} argument is only evaluated once but the @var{stream}
6727 argument is evaluated more than once. Returns 0 on success, -1 on
6731 @deftypefn Macro int Lstream_getc (Lstream *@var{stream})
6732 Read one byte from the stream. This is a macro and so it is very
6733 efficient. The @var{stream} argument is evaluated more than once. Return
6734 value is -1 for EOF or error.
6737 @deftypefn Macro void Lstream_ungetc (Lstream *@var{stream}, int @var{c})
6738 Push one byte back onto the input queue. This will be the next byte
6739 read from the stream. Any number of bytes can be pushed back and will
6740 be read in the reverse order they were pushed back -- most recent
6741 first. (This is necessary for consistency -- if there are a number of
6742 bytes that have been unread and I read and unread a byte, it needs to be
6743 the first to be read again.) This is a macro and so it is very
6744 efficient. The @var{c} argument is only evaluated once but the @var{stream}
6745 argument is evaluated more than once.
6748 @deftypefun int Lstream_fputc (Lstream *@var{stream}, int @var{c})
6749 @deftypefunx int Lstream_fgetc (Lstream *@var{stream})
6750 @deftypefunx void Lstream_fungetc (Lstream *@var{stream}, int @var{c})
6751 Function equivalents of the above macros.
6754 @deftypefun int Lstream_read (Lstream *@var{stream}, void *@var{data}, int @var{size})
6755 Read @var{size} bytes of @var{data} from the stream. Return the number
6756 of bytes read. 0 means EOF. -1 means an error occurred and no bytes
6760 @deftypefun int Lstream_write (Lstream *@var{stream}, void *@var{data}, int @var{size})
6761 Write @var{size} bytes of @var{data} to the stream. Return the number
6762 of bytes written. -1 means an error occurred and no bytes were written.
6765 @deftypefun void Lstream_unread (Lstream *@var{stream}, void *@var{data}, int @var{size})
6766 Push back @var{size} bytes of @var{data} onto the input queue. The next
6767 call to @code{Lstream_read()} with the same size will read the same
6768 bytes back. Note that this will be the case even if there is other
6769 pending unread data.
6772 @deftypefun int Lstream_close (Lstream *@var{stream})
6773 Close the stream. All data will be flushed out.
6776 @deftypefun void Lstream_reopen (Lstream *@var{stream})
6777 Reopen a closed stream. This enables I/O on it again. This is not
6778 meant to be called except from a wrapper routine that reinitializes
6779 variables and such -- the close routine may well have freed some
6780 necessary storage structures, for example.
6783 @deftypefun void Lstream_rewind (Lstream *@var{stream})
6784 Rewind the stream to the beginning.
6787 @node Lstream Methods
6788 @section Lstream Methods
6790 @deftypefn {Lstream Method} int reader (Lstream *@var{stream}, unsigned char *@var{data}, int @var{size})
6791 Read some data from the stream's end and store it into @var{data}, which
6792 can hold @var{size} bytes. Return the number of bytes read. A return
6793 value of 0 means no bytes can be read at this time. This may be because
6794 of an EOF, or because there is a granularity greater than one byte that
6795 the stream imposes on the returned data, and @var{size} is less than
6796 this granularity. (This will happen frequently for streams that need to
6797 return whole characters, because @code{Lstream_read()} calls the reader
6798 function repeatedly until it has the number of bytes it wants or until 0
6799 is returned.) The lstream functions do not treat a 0 return as EOF or
6800 do anything special; however, the calling function will interpret any 0
6801 it gets back as EOF. This will normally not happen unless the caller
6802 calls @code{Lstream_read()} with a very small size.
6804 This function can be @code{NULL} if the stream is output-only.
6807 @deftypefn {Lstream Method} int writer (Lstream *@var{stream}, CONST unsigned char *@var{data}, int @var{size})
6808 Send some data to the stream's end. Data to be sent is in @var{data}
6809 and is @var{size} bytes. Return the number of bytes sent. This
6810 function can send and return fewer bytes than is passed in; in that
6811 case, the function will just be called again until there is no data left
6812 or 0 is returned. A return value of 0 means that no more data can be
6813 currently stored, but there is no error; the data will be squirreled
6814 away until the writer can accept data. (This is useful, e.g., if you're
6815 dealing with a non-blocking file descriptor and are getting
6816 @code{EWOULDBLOCK} errors.) This function can be @code{NULL} if the
6817 stream is input-only.
6820 @deftypefn {Lstream Method} int rewinder (Lstream *@var{stream})
6821 Rewind the stream. If this is @code{NULL}, the stream is not seekable.
6824 @deftypefn {Lstream Method} int seekable_p (Lstream *@var{stream})
6825 Indicate whether this stream is seekable -- i.e. it can be rewound.
6826 This method is ignored if the stream does not have a rewind method. If
6827 this method is not present, the result is determined by whether a rewind
6831 @deftypefn {Lstream Method} int flusher (Lstream *@var{stream})
6832 Perform any additional operations necessary to flush the data in this
6836 @deftypefn {Lstream Method} int pseudo_closer (Lstream *@var{stream})
6839 @deftypefn {Lstream Method} int closer (Lstream *@var{stream})
6840 Perform any additional operations necessary to close this stream down.
6841 May be @code{NULL}. This function is called when @code{Lstream_close()}
6842 is called or when the stream is garbage-collected. When this function
6843 is called, all pending data in the stream will already have been written
6847 @deftypefn {Lstream Method} Lisp_Object marker (Lisp_Object @var{lstream}, void (*@var{markfun}) (Lisp_Object))
6848 Mark this object for garbage collection. Same semantics as a standard
6849 @code{Lisp_Object} marker. This function can be @code{NULL}.
6852 @node Consoles; Devices; Frames; Windows, The Redisplay Mechanism, Lstreams, Top
6853 @chapter Consoles; Devices; Frames; Windows
6856 * Introduction to Consoles; Devices; Frames; Windows::
6858 * Window Hierarchy::
6859 * The Window Object::
6862 @node Introduction to Consoles; Devices; Frames; Windows
6863 @section Introduction to Consoles; Devices; Frames; Windows
6865 A window-system window that you see on the screen is called a
6866 @dfn{frame} in Emacs terminology. Each frame is subdivided into one or
6867 more non-overlapping panes, called (confusingly) @dfn{windows}. Each
6868 window displays the text of a buffer in it. (See above on Buffers.) Note
6869 that buffers and windows are independent entities: Two or more windows
6870 can be displaying the same buffer (potentially in different locations),
6871 and a buffer can be displayed in no windows.
6873 A single display screen that contains one or more frames is called
6874 a @dfn{display}. Under most circumstances, there is only one display.
6875 However, more than one display can exist, for example if you have
6876 a @dfn{multi-headed} console, i.e. one with a single keyboard but
6877 multiple displays. (Typically in such a situation, the various
6878 displays act like one large display, in that the mouse is only
6879 in one of them at a time, and moving the mouse off of one moves
6880 it into another.) In some cases, the different displays will
6881 have different characteristics, e.g. one color and one mono.
6883 XEmacs can display frames on multiple displays. It can even deal
6884 simultaneously with frames on multiple keyboards (called @dfn{consoles} in
6885 XEmacs terminology). Here is one case where this might be useful: You
6886 are using XEmacs on your workstation at work, and leave it running.
6887 Then you go home and dial in on a TTY line, and you can use the
6888 already-running XEmacs process to display another frame on your local
6891 Thus, there is a hierarchy console -> display -> frame -> window.
6892 There is a separate Lisp object type for each of these four concepts.
6893 Furthermore, there is logically a @dfn{selected console},
6894 @dfn{selected display}, @dfn{selected frame}, and @dfn{selected window}.
6895 Each of these objects is distinguished in various ways, such as being the
6896 default object for various functions that act on objects of that type.
6897 Note that every containing object rememembers the ``selected'' object
6898 among the objects that it contains: e.g. not only is there a selected
6899 window, but every frame remembers the last window in it that was
6900 selected, and changing the selected frame causes the remembered window
6901 within it to become the selected window. Similar relationships apply
6902 for consoles to devices and devices to frames.
6907 Recall that every buffer has a current insertion position, called
6908 @dfn{point}. Now, two or more windows may be displaying the same buffer,
6909 and the text cursor in the two windows (i.e. @code{point}) can be in
6910 two different places. You may ask, how can that be, since each
6911 buffer has only one value of @code{point}? The answer is that each window
6912 also has a value of @code{point} that is squirreled away in it. There
6913 is only one selected window, and the value of ``point'' in that buffer
6914 corresponds to that window. When the selected window is changed
6915 from one window to another displaying the same buffer, the old
6916 value of @code{point} is stored into the old window's ``point'' and the
6917 value of @code{point} from the new window is retrieved and made the
6918 value of @code{point} in the buffer. This means that @code{window-point}
6919 for the selected window is potentially inaccurate, and if you
6920 want to retrieve the correct value of @code{point} for a window,
6921 you must special-case on the selected window and retrieve the
6922 buffer's point instead. This is related to why @code{save-window-excursion}
6923 does not save the selected window's value of @code{point}.
6925 @node Window Hierarchy
6926 @section Window Hierarchy
6927 @cindex window hierarchy
6928 @cindex hierarchy of windows
6930 If a frame contains multiple windows (panes), they are always created
6931 by splitting an existing window along the horizontal or vertical axis.
6932 Terminology is a bit confusing here: to @dfn{split a window
6933 horizontally} means to create two side-by-side windows, i.e. to make a
6934 @emph{vertical} cut in a window. Likewise, to @dfn{split a window
6935 vertically} means to create two windows, one above the other, by making
6936 a @emph{horizontal} cut.
6938 If you split a window and then split again along the same axis, you
6939 will end up with a number of panes all arranged along the same axis.
6940 The precise way in which the splits were made should not be important,
6941 and this is reflected internally. Internally, all windows are arranged
6942 in a tree, consisting of two types of windows, @dfn{combination} windows
6943 (which have children, and are covered completely by those children) and
6944 @dfn{leaf} windows, which have no children and are visible. Every
6945 combination window has two or more children, all arranged along the same
6946 axis. There are (logically) two subtypes of windows, depending on
6947 whether their children are horizontally or vertically arrayed. There is
6948 always one root window, which is either a leaf window (if the frame
6949 contains only one window) or a combination window (if the frame contains
6950 more than one window). In the latter case, the root window will have
6951 two or more children, either horizontally or vertically arrayed, and
6952 each of those children will be either a leaf window or another
6955 Here are some rules:
6959 Horizontal combination windows can never have children that are
6960 horizontal combination windows; same for vertical.
6963 Only leaf windows can be split (obviously) and this splitting does one
6964 of two things: (a) turns the leaf window into a combination window and
6965 creates two new leaf children, or (b) turns the leaf window into one of
6966 the two new leaves and creates the other leaf. Rule (1) dictates which
6967 of these two outcomes happens.
6970 Every combination window must have at least two children.
6973 Leaf windows can never become combination windows. They can be deleted,
6974 however. If this results in a violation of (3), the parent combination
6975 window also gets deleted.
6978 All functions that accept windows must be prepared to accept combination
6979 windows, and do something sane (e.g. signal an error if so).
6980 Combination windows @emph{do} escape to the Lisp level.
6983 All windows have three fields governing their contents:
6984 these are @dfn{hchild} (a list of horizontally-arrayed children),
6985 @dfn{vchild} (a list of vertically-arrayed children), and @dfn{buffer}
6986 (the buffer contained in a leaf window). Exactly one of
6987 these will be non-nil. Remember that @dfn{horizontally-arrayed}
6988 means ``side-by-side'' and @dfn{vertically-arrayed} means
6989 @dfn{one above the other}.
6992 Leaf windows also have markers in their @code{start} (the
6993 first buffer position displayed in the window) and @code{pointm}
6994 (the window's stashed value of @code{point} -- see above) fields,
6995 while combination windows have nil in these fields.
6998 The list of children for a window is threaded through the
6999 @code{next} and @code{prev} fields of each child window.
7002 @strong{Deleted windows can be undeleted}. This happens as a result of
7003 restoring a window configuration, and is unlike frames, displays, and
7004 consoles, which, once deleted, can never be restored. Deleting a window
7005 does nothing except set a special @code{dead} bit to 1 and clear out the
7006 @code{next}, @code{prev}, @code{hchild}, and @code{vchild} fields, for
7010 Most frames actually have two top-level windows -- one for the
7011 minibuffer and one (the @dfn{root}) for everything else. The modeline
7012 (if present) separates these two. The @code{next} field of the root
7013 points to the minibuffer, and the @code{prev} field of the minibuffer
7014 points to the root. The other @code{next} and @code{prev} fields are
7015 @code{nil}, and the frame points to both of these windows.
7016 Minibuffer-less frames have no minibuffer window, and the @code{next}
7017 and @code{prev} of the root window are @code{nil}. Minibuffer-only
7018 frames have no root window, and the @code{next} of the minibuffer window
7019 is @code{nil} but the @code{prev} points to itself. (#### This is an
7020 artifact that should be fixed.)
7023 @node The Window Object
7024 @section The Window Object
7026 Windows have the following accessible fields:
7030 The frame that this window is on.
7033 Non-@code{nil} if this window is a minibuffer window.
7036 The buffer that the window is displaying. This may change often during
7037 the life of the window.
7040 Non-@code{nil} if this window is dedicated to its buffer.
7043 @cindex window point internals
7044 This is the value of point in the current buffer when this window is
7045 selected; when it is not selected, it retains its previous value.
7048 The position in the buffer that is the first character to be displayed
7052 If this flag is non-@code{nil}, it says that the window has been
7053 scrolled explicitly by the Lisp program. This affects what the next
7054 redisplay does if point is off the screen: instead of scrolling the
7055 window to show the text around point, it moves point to a location that
7059 The @code{modified} field of the window's buffer, as of the last time
7060 a redisplay completed in this window.
7063 The buffer's value of point, as of the last time
7064 a redisplay completed in this window.
7067 This is the left-hand edge of the window, measured in columns. (The
7068 leftmost column on the screen is @w{column 0}.)
7071 This is the top edge of the window, measured in lines. (The top line on
7072 the screen is @w{line 0}.)
7075 The height of the window, measured in lines.
7078 The width of the window, measured in columns.
7081 This is the window that is the next in the chain of siblings. It is
7082 @code{nil} in a window that is the rightmost or bottommost of a group of
7086 This is the window that is the previous in the chain of siblings. It is
7087 @code{nil} in a window that is the leftmost or topmost of a group of
7091 Internally, XEmacs arranges windows in a tree; each group of siblings has
7092 a parent window whose area includes all the siblings. This field points
7093 to a window's parent.
7095 Parent windows do not display buffers, and play little role in display
7096 except to shape their child windows. Emacs Lisp programs usually have
7097 no access to the parent windows; they operate on the windows at the
7098 leaves of the tree, which actually display buffers.
7101 This is the number of columns that the display in the window is scrolled
7102 horizontally to the left. Normally, this is 0.
7105 This is the last time that the window was selected. The function
7106 @code{get-lru-window} uses this field.
7109 The window's display table, or @code{nil} if none is specified for it.
7111 @item update_mode_line
7112 Non-@code{nil} means this window's mode line needs to be updated.
7114 @item base_line_number
7115 The line number of a certain position in the buffer, or @code{nil}.
7116 This is used for displaying the line number of point in the mode line.
7119 The position in the buffer for which the line number is known, or
7120 @code{nil} meaning none is known.
7122 @item region_showing
7123 If the region (or part of it) is highlighted in this window, this field
7124 holds the mark position that made one end of that region. Otherwise,
7125 this field is @code{nil}.
7128 @node The Redisplay Mechanism, Extents, Consoles; Devices; Frames; Windows, Top
7129 @chapter The Redisplay Mechanism
7131 The redisplay mechanism is one of the most complicated sections of
7132 XEmacs, especially from a conceptual standpoint. This is doubly so
7133 because, unlike for the basic aspects of the Lisp interpreter, the
7134 computer science theories of how to efficiently handle redisplay are not
7137 When working with the redisplay mechanism, remember the Golden Rules
7142 It Is Better To Be Correct Than Fast.
7144 Thou Shalt Not Run Elisp From Within Redisplay.
7146 It Is Better To Be Fast Than Not To Be.
7150 * Critical Redisplay Sections::
7151 * Line Start Cache::
7154 @node Critical Redisplay Sections
7155 @section Critical Redisplay Sections
7156 @cindex critical redisplay sections
7158 Within this section, we are defenseless and assume that the
7159 following cannot happen:
7165 Lisp code evaluation
7170 We ensure (3) by calling @code{hold_frame_size_changes()}, which
7171 will cause any pending frame size changes to get put on hold
7172 till after the end of the critical section. (1) follows
7173 automatically if (2) is met. #### Unfortunately, there are
7174 some places where Lisp code can be called within this section.
7175 We need to remove them.
7177 If @code{Fsignal()} is called during this critical section, we
7178 will @code{abort()}.
7180 If garbage collection is called during this critical section,
7181 we simply return. #### We should abort instead.
7183 #### If a frame-size change does occur we should probably
7184 actually be preempting redisplay.
7186 @node Line Start Cache
7187 @section Line Start Cache
7188 @cindex line start cache
7190 The traditional scrolling code in Emacs breaks in a variable height
7191 world. It depends on the key assumption that the number of lines that
7192 can be displayed at any given time is fixed. This led to a complete
7193 separation of the scrolling code from the redisplay code. In order to
7194 fully support variable height lines, the scrolling code must actually be
7195 tightly integrated with redisplay. Only redisplay can determine how
7196 many lines will be displayed on a screen for any given starting point.
7198 What is ideally wanted is a complete list of the starting buffer
7199 position for every possible display line of a buffer along with the
7200 height of that display line. Maintaining such a full list would be very
7201 expensive. We settle for having it include information for all areas
7202 which we happen to generate anyhow (i.e. the region currently being
7203 displayed) and for those areas we need to work with.
7205 In order to ensure that the cache accurately represents what redisplay
7206 would actually show, it is necessary to invalidate it in many
7207 situations. If the buffer changes, the starting positions may no longer
7208 be correct. If a face or an extent has changed then the line heights
7209 may have altered. These events happen frequently enough that the cache
7210 can end up being constantly disabled. With this potentially constant
7211 invalidation when is the cache ever useful?
7213 Even if the cache is invalidated before every single usage, it is
7214 necessary. Scrolling often requires knowledge about display lines which
7215 are actually above or below the visible region. The cache provides a
7216 convenient light-weight method of storing this information for multiple
7217 display regions. This knowledge is necessary for the scrolling code to
7218 always obey the First Golden Rule of Redisplay.
7220 If the cache already contains all of the information that the scrolling
7221 routines happen to need so that it doesn't have to go generate it, then
7222 we are able to obey the Third Golden Rule of Redisplay. The first thing
7223 we do to help out the cache is to always add the displayed region. This
7224 region had to be generated anyway, so the cache ends up getting the
7225 information basically for free. In those cases where a user is simply
7226 scrolling around viewing a buffer there is a high probability that this
7227 is sufficient to always provide the needed information. The second
7228 thing we can do is be smart about invalidating the cache.
7230 TODO -- Be smart about invalidating the cache. Potential places:
7234 Insertions at end-of-line which don't cause line-wraps do not alter the
7235 starting positions of any display lines. These types of buffer
7236 modifications should not invalidate the cache. This is actually a large
7237 optimization for redisplay speed as well.
7239 Buffer modifications frequently only affect the display of lines at and
7240 below where they occur. In these situations we should only invalidate
7241 the part of the cache starting at where the modification occurs.
7244 In case you're wondering, the Second Golden Rule of Redisplay is not
7247 @node Extents, Faces and Glyphs, The Redisplay Mechanism, Top
7251 * Introduction to Extents:: Extents are ranges over text, with properties.
7252 * Extent Ordering:: How extents are ordered internally.
7253 * Format of the Extent Info:: The extent information in a buffer or string.
7254 * Zero-Length Extents:: A weird special case.
7255 * Mathematics of Extent Ordering:: A rigorous foundation.
7256 * Extent Fragments:: Cached information useful for redisplay.
7259 @node Introduction to Extents
7260 @section Introduction to Extents
7262 Extents are regions over a buffer, with a start and an end position
7263 denoting the region of the buffer included in the extent. In
7264 addition, either end can be closed or open, meaning that the endpoint
7265 is or is not logically included in the extent. Insertion of a character
7266 at a closed endpoint causes the character to go inside the extent;
7267 insertion at an open endpoint causes the character to go outside.
7269 Extent endpoints are stored using memory indices (see @file{insdel.c}),
7270 to minimize the amount of adjusting that needs to be done when
7271 characters are inserted or deleted.
7273 (Formerly, extent endpoints at the gap could be either before or
7274 after the gap, depending on the open/closedness of the endpoint.
7275 The intent of this was to make it so that insertions would
7276 automatically go inside or out of extents as necessary with no
7277 further work needing to be done. It didn't work out that way,
7278 however, and just ended up complexifying and buggifying all the
7281 @node Extent Ordering
7282 @section Extent Ordering
7284 Extents are compared using memory indices. There are two orderings
7285 for extents and both orders are kept current at all times. The normal
7286 or @dfn{display} order is as follows:
7289 Extent A is ``less than'' extent B, that is, earlier in the display order,
7290 if: A-start < B-start,
7291 or if: A-start = B-start, and A-end > B-end
7294 So if two extents begin at the same position, the larger of them is the
7295 earlier one in the display order (@code{EXTENT_LESS} is true).
7297 For the e-order, the same thing holds:
7300 Extent A is ``less than'' extent B in e-order, that is, later in the buffer,
7302 or if: A-end = B-end, and A-start > B-start
7305 So if two extents end at the same position, the smaller of them is the
7306 earlier one in the e-order (@code{EXTENT_E_LESS} is true).
7308 The display order and the e-order are complementary orders: any
7309 theorem about the display order also applies to the e-order if you swap
7310 all occurrences of ``display order'' and ``e-order'', ``less than'' and
7311 ``greater than'', and ``extent start'' and ``extent end''.
7313 @node Format of the Extent Info
7314 @section Format of the Extent Info
7316 An extent-info structure consists of a list of the buffer or string's
7317 extents and a @dfn{stack of extents} that lists all of the extents over
7318 a particular position. The stack-of-extents info is used for
7319 optimization purposes -- it basically caches some info that might
7320 be expensive to compute. Certain otherwise hard computations are easy
7321 given the stack of extents over a particular position, and if the
7322 stack of extents over a nearby position is known (because it was
7323 calculated at some prior point in time), it's easy to move the stack
7324 of extents to the proper position.
7326 Given that the stack of extents is an optimization, and given that
7327 it requires memory, a string's stack of extents is wiped out each
7328 time a garbage collection occurs. Therefore, any time you retrieve
7329 the stack of extents, it might not be there. If you need it to
7330 be there, use the @code{_force} version.
7332 Similarly, a string may or may not have an extent_info structure.
7333 (Generally it won't if there haven't been any extents added to the
7334 string.) So use the @code{_force} version if you need the extent_info
7335 structure to be there.
7337 A list of extents is maintained as a double gap array: one gap array
7338 is ordered by start index (the @dfn{display order}) and the other is
7339 ordered by end index (the @dfn{e-order}). Note that positions in an
7340 extent list should logically be conceived of as referring @emph{to} a
7341 particular extent (as is the norm in programs) rather than sitting
7342 between two extents. Note also that callers of these functions should
7343 not be aware of the fact that the extent list is implemented as an
7344 array, except for the fact that positions are integers (this should be
7345 generalized to handle integers and linked list equally well).
7347 @node Zero-Length Extents
7348 @section Zero-Length Extents
7350 Extents can be zero-length, and will end up that way if their endpoints
7351 are explicitly set that way or if their detachable property is nil
7352 and all the text in the extent is deleted. (The exception is open-open
7353 zero-length extents, which are barred from existing because there is
7354 no sensible way to define their properties. Deletion of the text in
7355 an open-open extent causes it to be converted into a closed-open
7356 extent.) Zero-length extents are primarily used to represent
7357 annotations, and behave as follows:
7361 Insertion at the position of a zero-length extent expands the extent
7362 if both endpoints are closed; goes after the extent if it is closed-open;
7363 and goes before the extent if it is open-closed.
7366 Deletion of a character on a side of a zero-length extent whose
7367 corresponding endpoint is closed causes the extent to be detached if
7368 it is detachable; if the extent is not detachable or the corresponding
7369 endpoint is open, the extent remains in the buffer, moving as necessary.
7372 Note that closed-open, non-detachable zero-length extents behave
7373 exactly like markers and that open-closed, non-detachable zero-length
7374 extents behave like the ``point-type'' marker in Mule.
7376 @node Mathematics of Extent Ordering
7377 @section Mathematics of Extent Ordering
7378 @cindex extent mathematics
7379 @cindex mathematics of extents
7380 @cindex extent ordering
7382 @cindex display order of extents
7383 @cindex extents, display order
7384 The extents in a buffer are ordered by ``display order'' because that
7385 is that order that the redisplay mechanism needs to process them in.
7386 The e-order is an auxiliary ordering used to facilitate operations
7387 over extents. The operations that can be performed on the ordered
7388 list of extents in a buffer are
7392 Locate where an extent would go if inserted into the list.
7394 Insert an extent into the list.
7396 Remove an extent from the list.
7398 Map over all the extents that overlap a range.
7401 (4) requires being able to determine the first and last extents
7402 that overlap a range.
7404 NOTE: @dfn{overlap} is used as follows:
7408 two ranges overlap if they have at least one point in common.
7409 Whether the endpoints are open or closed makes a difference here.
7411 a point overlaps a range if the point is contained within the
7412 range; this is equivalent to treating a point @math{P} as the range
7415 In the case of an @emph{extent} overlapping a point or range, the extent
7416 is normally treated as having closed endpoints. This applies
7417 consistently in the discussion of stacks of extents and such below.
7418 Note that this definition of overlap is not necessarily consistent with
7419 the extents that @code{map-extents} maps over, since @code{map-extents}
7420 sometimes pays attention to whether the endpoints of an extents are open
7421 or closed. But for our purposes, it greatly simplifies things to treat
7422 all extents as having closed endpoints.
7425 First, define @math{>}, @math{<}, @math{<=}, etc. as applied to extents
7426 to mean comparison according to the display order. Comparison between
7427 an extent @math{E} and an index @math{I} means comparison between
7428 @math{E} and the range @math{[I, I]}.
7430 Also define @math{e>}, @math{e<}, @math{e<=}, etc. to mean comparison
7431 according to the e-order.
7433 For any range @math{R}, define @math{R(0)} to be the starting index of
7434 the range and @math{R(1)} to be the ending index of the range.
7436 For any extent @math{E}, define @math{E(next)} to be the extent directly
7437 following @math{E}, and @math{E(prev)} to be the extent directly
7438 preceding @math{E}. Assume @math{E(next)} and @math{E(prev)} can be
7439 determined from @math{E} in constant time. (This is because we store
7440 the extent list as a doubly linked list.)
7442 Similarly, define @math{E(e-next)} and @math{E(e-prev)} to be the
7443 extents directly following and preceding @math{E} in the e-order.
7447 Let @math{R} be a range.
7448 Let @math{F} be the first extent overlapping @math{R}.
7449 Let @math{L} be the last extent overlapping @math{R}.
7451 Theorem 1: @math{R(1)} lies between @math{L} and @math{L(next)},
7452 i.e. @math{L <= R(1) < L(next)}.
7454 This follows easily from the definition of display order. The
7455 basic reason that this theorem applies is that the display order
7456 sorts by increasing starting index.
7458 Therefore, we can determine @math{L} just by looking at where we would
7459 insert @math{R(1)} into the list, and if we know @math{F} and are moving
7460 forward over extents, we can easily determine when we've hit @math{L} by
7461 comparing the extent we're at to @math{R(1)}.
7464 Theorem 2: @math{F(e-prev) e< [1, R(0)] e<= F}.
7467 This is the analog of Theorem 1, and applies because the e-order
7468 sorts by increasing ending index.
7470 Therefore, @math{F} can be found in the same amount of time as
7471 operation (1), i.e. the time that it takes to locate where an extent
7472 would go if inserted into the e-order list.
7474 If the lists were stored as balanced binary trees, then operation (1)
7475 would take logarithmic time, which is usually quite fast. However,
7476 currently they're stored as simple doubly-linked lists, and instead we
7477 do some caching to try to speed things up.
7479 Define a @dfn{stack of extents} (or @dfn{SOE}) as the set of extents
7480 (ordered in the display order) that overlap an index @math{I}, together
7481 with the SOE's @dfn{previous} extent, which is an extent that precedes
7482 @math{I} in the e-order. (Hopefully there will not be very many extents
7483 between @math{I} and the previous extent.)
7487 Let @math{I} be an index, let @math{S} be the stack of extents on
7488 @math{I}, let @math{F} be the first extent in @math{S}, and let @math{P}
7489 be @math{S}'s previous extent.
7491 Theorem 3: The first extent in @math{S} is the first extent that overlaps
7492 any range @math{[I, J]}.
7494 Proof: Any extent that overlaps @math{[I, J]} but does not include
7495 @math{I} must have a start index @math{> I}, and thus be greater than
7496 any extent in @math{S}.
7498 Therefore, finding the first extent that overlaps a range @math{R} is
7499 the same as finding the first extent that overlaps @math{R(0)}.
7501 Theorem 4: Let @math{I2} be an index such that @math{I2 > I}, and let
7502 @math{F2} be the first extent that overlaps @math{I2}. Then, either
7503 @math{F2} is in @math{S} or @math{F2} is greater than any extent in
7506 Proof: If @math{F2} does not include @math{I} then its start index is
7507 greater than @math{I} and thus it is greater than any extent in
7508 @math{S}, including @math{F}. Otherwise, @math{F2} includes @math{I}
7509 and thus is in @math{S}, and thus @math{F2 >= F}.
7511 @node Extent Fragments
7512 @section Extent Fragments
7513 @cindex extent fragment
7515 Imagine that the buffer is divided up into contiguous, non-overlapping
7516 @dfn{runs} of text such that no extent starts or ends within a run
7517 (extents that abut the run don't count).
7519 An extent fragment is a structure that holds data about the run that
7520 contains a particular buffer position (if the buffer position is at the
7521 junction of two runs, the run after the position is used) -- the
7522 beginning and end of the run, a list of all of the extents in that run,
7523 the @dfn{merged face} that results from merging all of the faces
7524 corresponding to those extents, the begin and end glyphs at the
7525 beginning of the run, etc. This is the information that redisplay needs
7526 in order to display this run.
7528 Extent fragments have to be very quick to update to a new buffer
7529 position when moving linearly through the buffer. They rely on the
7530 stack-of-extents code, which does the heavy-duty algorithmic work of
7531 determining which extents overly a particular position.
7533 @node Faces and Glyphs, Specifiers, Extents, Top
7534 @chapter Faces and Glyphs
7538 @node Specifiers, Menus, Faces and Glyphs, Top
7543 @node Menus, Subprocesses, Specifiers, Top
7546 A menu is set by setting the value of the variable
7547 @code{current-menubar} (which may be buffer-local) and then calling
7548 @code{set-menubar-dirty-flag} to signal a change. This will cause the
7549 menu to be redrawn at the next redisplay. The format of the data in
7550 @code{current-menubar} is described in @file{menubar.c}.
7552 Internally the data in current-menubar is parsed into a tree of
7553 @code{widget_value's} (defined in @file{lwlib.h}); this is accomplished
7554 by the recursive function @code{menu_item_descriptor_to_widget_value()},
7555 called by @code{compute_menubar_data()}. Such a tree is deallocated
7556 using @code{free_widget_value()}.
7558 @code{update_screen_menubars()} is one of the external entry points.
7559 This checks to see, for each screen, if that screen's menubar needs to
7560 be updated. This is the case if
7564 @code{set-menubar-dirty-flag} was called since the last redisplay. (This
7565 function sets the C variable menubar_has_changed.)
7567 The buffer displayed in the screen has changed.
7569 The screen has no menubar currently displayed.
7572 @code{set_screen_menubar()} is called for each such screen. This
7573 function calls @code{compute_menubar_data()} to create the tree of
7574 widget_value's, then calls @code{lw_create_widget()},
7575 @code{lw_modify_all_widgets()}, and/or @code{lw_destroy_all_widgets()}
7576 to create the X-Toolkit widget associated with the menu.
7578 @code{update_psheets()}, the other external entry point, actually
7579 changes the menus being displayed. It uses the widgets fixed by
7580 @code{update_screen_menubars()} and calls various X functions to ensure
7581 that the menus are displayed properly.
7583 The menubar widget is set up so that @code{pre_activate_callback()} is
7584 called when the menu is first selected (i.e. mouse button goes down),
7585 and @code{menubar_selection_callback()} is called when an item is
7586 selected. @code{pre_activate_callback()} calls the function in
7587 activate-menubar-hook, which can change the menubar (this is described
7588 in @file{menubar.c}). If the menubar is changed,
7589 @code{set_screen_menubars()} is called.
7590 @code{menubar_selection_callback()} enqueues a menu event, putting in it
7591 a function to call (either @code{eval} or @code{call-interactively}) and
7592 its argument, which is the callback function or form given in the menu's
7595 @node Subprocesses, Interface to X Windows, Menus, Top
7596 @chapter Subprocesses
7598 The fields of a process are:
7602 A string, the name of the process.
7605 A list containing the command arguments that were used to start this
7609 A function used to accept output from the process instead of a buffer,
7613 A function called whenever the process receives a signal, or @code{nil}.
7616 The associated buffer of the process.
7619 An integer, the Unix process @sc{id}.
7622 A flag, non-@code{nil} if this is really a child process.
7623 It is @code{nil} for a network connection.
7626 A marker indicating the position of the end of the last output from this
7627 process inserted into the buffer. This is often but not always the end
7630 @item kill_without_query
7631 If this is non-@code{nil}, killing XEmacs while this process is still
7632 running does not ask for confirmation about killing the process.
7634 @item raw_status_low
7635 @itemx raw_status_high
7636 These two fields record 16 bits each of the process status returned by
7637 the @code{wait} system call.
7640 The process status, as @code{process-status} should return it.
7644 If these two fields are not equal, a change in the status of the process
7645 needs to be reported, either by running the sentinel or by inserting a
7646 message in the process buffer.
7649 Non-@code{nil} if communication with the subprocess uses a @sc{pty};
7650 @code{nil} if it uses a pipe.
7653 The file descriptor for input from the process.
7656 The file descriptor for output to the process.
7659 The file descriptor for the terminal that the subprocess is using. (On
7660 some systems, there is no need to record this, so the value is
7664 The name of the terminal that the subprocess is using,
7665 or @code{nil} if it is using pipes.
7668 @node Interface to X Windows, Index, Subprocesses, Top
7669 @chapter Interface to X Windows
7675 @c Print the tables of contents