XEmacs 21.4.9 "Informed Management".
[chise/xemacs-chise.git.1] / man / internals / internals.texi
1 \input texinfo  @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename ../../info/internals.info
4 @settitle XEmacs Internals Manual
5 @c %**end of header
6
7 @ifinfo
8 @dircategory XEmacs Editor
9 @direntry
10 * Internals: (internals).       XEmacs Internals Manual.
11 @end direntry
12
13 Copyright @copyright{} 1992 - 1996 Ben Wing.
14 Copyright @copyright{} 1996, 1997 Sun Microsystems.
15 Copyright @copyright{} 1994 - 1998 Free Software Foundation.
16 Copyright @copyright{} 1994, 1995 Board of Trustees, University of Illinois.
17
18
19 Permission is granted to make and distribute verbatim copies of this
20 manual provided the copyright notice and this permission notice are
21 preserved on all copies.
22
23 @ignore
24 Permission is granted to process this file through TeX and print the
25 results, provided the printed document carries copying permission notice
26 identical to this one except for the removal of this paragraph (this
27 paragraph not being relevant to the printed manual).
28
29 @end ignore
30 Permission is granted to copy and distribute modified versions of this
31 manual under the conditions for verbatim copying, provided that the
32 entire resulting derived work is distributed under the terms of a
33 permission notice identical to this one.
34
35 Permission is granted to copy and distribute translations of this manual
36 into another language, under the above conditions for modified versions,
37 except that this permission notice may be stated in a translation
38 approved by the Foundation.
39
40 Permission is granted to copy and distribute modified versions of this
41 manual under the conditions for verbatim copying, provided also that the
42 section entitled ``GNU General Public License'' is included exactly as
43 in the original, and provided that the entire resulting derived work is
44 distributed under the terms of a permission notice identical to this
45 one.
46
47 Permission is granted to copy and distribute translations of this manual
48 into another language, under the above conditions for modified versions,
49 except that the section entitled ``GNU General Public License'' may be
50 included in a translation approved by the Free Software Foundation
51 instead of in the original English.
52 @end ifinfo
53
54 @c Combine indices.
55 @synindex cp fn
56 @syncodeindex vr fn
57 @syncodeindex ky fn
58 @syncodeindex pg fn
59 @syncodeindex tp fn
60
61 @setchapternewpage odd
62 @finalout
63
64 @titlepage
65 @title XEmacs Internals Manual
66 @subtitle Version 1.4, March 2001
67
68 @author Ben Wing
69 @author Martin Buchholz
70 @author Hrvoje Niksic
71 @author Matthias Neubauer
72 @author Olivier Galibert
73 @page
74 @vskip 0pt plus 1fill
75
76 @noindent
77 Copyright @copyright{} 1992 - 1996, 2001 Ben Wing. @*
78 Copyright @copyright{} 1996, 1997 Sun Microsystems, Inc. @*
79 Copyright @copyright{} 1994 - 1998 Free Software Foundation. @*
80 Copyright @copyright{} 1994, 1995 Board of Trustees, University of Illinois.
81
82 @sp 2
83 Version 1.4 @*
84 March 2001.@*
85
86 Permission is granted to make and distribute verbatim copies of this
87 manual provided the copyright notice and this permission notice are
88 preserved on all copies.
89
90 Permission is granted to copy and distribute modified versions of this
91 manual under the conditions for verbatim copying, provided also that the
92 section entitled ``GNU General Public License'' is included
93 exactly as in the original, and provided that the entire resulting
94 derived work is distributed under the terms of a permission notice
95 identical to this one.
96
97 Permission is granted to copy and distribute translations of this manual
98 into another language, under the above conditions for modified versions,
99 except that the section entitled ``GNU General Public License'' may be
100 included in a translation approved by the Free Software Foundation
101 instead of in the original English.
102 @end titlepage
103 @page
104
105 @node Top, A History of Emacs, (dir), (dir)
106
107 @ifinfo
108 This Info file contains v1.4 of the XEmacs Internals Manual, March 2001.
109 @end ifinfo
110
111 @menu
112 * A History of Emacs::          Times, dates, important events.
113 * XEmacs From the Outside::     A broad conceptual overview.
114 * The Lisp Language::           An overview.
115 * XEmacs From the Perspective of Building::
116 * XEmacs From the Inside::
117 * The XEmacs Object System (Abstractly Speaking)::
118 * How Lisp Objects Are Represented in C::
119 * Rules When Writing New C Code::
120 * Regression Testing XEmacs::
121 * A Summary of the Various XEmacs Modules::
122 * Allocation of Objects in XEmacs Lisp::
123 * Dumping::
124 * Events and the Event Loop::
125 * Evaluation; Stack Frames; Bindings::
126 * Symbols and Variables::
127 * Buffers and Textual Representation::
128 * MULE Character Sets and Encodings::
129 * The Lisp Reader and Compiler::
130 * Lstreams::
131 * Consoles; Devices; Frames; Windows::
132 * The Redisplay Mechanism::
133 * Extents::
134 * Faces::
135 * Glyphs::
136 * Specifiers::
137 * Menus::
138 * Subprocesses::
139 * Interface to the X Window System::
140 * Index::
141
142 @detailmenu
143
144 --- The Detailed Node Listing ---
145
146 A History of Emacs
147
148 * Through Version 18::          Unification prevails.
149 * Lucid Emacs::                 One version 19 Emacs.
150 * GNU Emacs 19::                The other version 19 Emacs.
151 * GNU Emacs 20::                The other version 20 Emacs.
152 * XEmacs::                      The continuation of Lucid Emacs.
153
154 Rules When Writing New C Code
155
156 * General Coding Rules::
157 * Writing Lisp Primitives::
158 * Adding Global Lisp Variables::
159 * Coding for Mule::
160 * Techniques for XEmacs Developers::
161
162 Coding for Mule
163
164 * Character-Related Data Types::
165 * Working With Character and Byte Positions::
166 * Conversion to and from External Data::
167 * General Guidelines for Writing Mule-Aware Code::
168 * An Example of Mule-Aware Code::
169
170 Regression Testing XEmacs
171
172 A Summary of the Various XEmacs Modules
173
174 * Low-Level Modules::
175 * Basic Lisp Modules::
176 * Modules for Standard Editing Operations::
177 * Editor-Level Control Flow Modules::
178 * Modules for the Basic Displayable Lisp Objects::
179 * Modules for other Display-Related Lisp Objects::
180 * Modules for the Redisplay Mechanism::
181 * Modules for Interfacing with the File System::
182 * Modules for Other Aspects of the Lisp Interpreter and Object System::
183 * Modules for Interfacing with the Operating System::
184 * Modules for Interfacing with X Windows::
185 * Modules for Internationalization::
186 * Modules for Regression Testing::
187
188 Allocation of Objects in XEmacs Lisp
189
190 * Introduction to Allocation::
191 * Garbage Collection::
192 * GCPROing::
193 * Garbage Collection - Step by Step::
194 * Integers and Characters::
195 * Allocation from Frob Blocks::
196 * lrecords::
197 * Low-level allocation::
198 * Cons::
199 * Vector::
200 * Bit Vector::
201 * Symbol::
202 * Marker::
203 * String::
204 * Compiled Function::
205
206 Garbage Collection - Step by Step
207
208 * Invocation::
209 * garbage_collect_1::
210 * mark_object::
211 * gc_sweep::
212 * sweep_lcrecords_1::
213 * compact_string_chars::
214 * sweep_strings::
215 * sweep_bit_vectors_1::
216
217 Dumping
218
219 * Overview::
220 * Data descriptions::
221 * Dumping phase::
222 * Reloading phase::
223
224 Dumping phase
225
226 * Object inventory::
227 * Address allocation::
228 * The header::
229 * Data dumping::
230 * Pointers dumping::
231
232 Events and the Event Loop
233
234 * Introduction to Events::
235 * Main Loop::
236 * Specifics of the Event Gathering Mechanism::
237 * Specifics About the Emacs Event::
238 * The Event Stream Callback Routines::
239 * Other Event Loop Functions::
240 * Converting Events::
241 * Dispatching Events; The Command Builder::
242
243 Evaluation; Stack Frames; Bindings
244
245 * Evaluation::
246 * Dynamic Binding; The specbinding Stack; Unwind-Protects::
247 * Simple Special Forms::
248 * Catch and Throw::
249
250 Symbols and Variables
251
252 * Introduction to Symbols::
253 * Obarrays::
254 * Symbol Values::
255
256 Buffers and Textual Representation
257
258 * Introduction to Buffers::     A buffer holds a block of text such as a file.
259 * The Text in a Buffer::        Representation of the text in a buffer.
260 * Buffer Lists::                Keeping track of all buffers.
261 * Markers and Extents::         Tagging locations within a buffer.
262 * Bufbytes and Emchars::        Representation of individual characters.
263 * The Buffer Object::           The Lisp object corresponding to a buffer.
264
265 MULE Character Sets and Encodings
266
267 * Character Sets::
268 * Encodings::
269 * Internal Mule Encodings::
270 * CCL::
271
272 Encodings
273
274 * Japanese EUC (Extended Unix Code)::
275 * JIS7::
276
277 Internal Mule Encodings
278
279 * Internal String Encoding::
280 * Internal Character Encoding::
281
282 Lstreams
283
284 * Creating an Lstream::         Creating an lstream object.
285 * Lstream Types::               Different sorts of things that are streamed.
286 * Lstream Functions::           Functions for working with lstreams.
287 * Lstream Methods::             Creating new lstream types.
288
289 Consoles; Devices; Frames; Windows
290
291 * Introduction to Consoles; Devices; Frames; Windows::
292 * Point::
293 * Window Hierarchy::
294 * The Window Object::
295
296 The Redisplay Mechanism
297
298 * Critical Redisplay Sections::
299 * Line Start Cache::
300 * Redisplay Piece by Piece::
301
302 Extents
303
304 * Introduction to Extents::     Extents are ranges over text, with properties.
305 * Extent Ordering::             How extents are ordered internally.
306 * Format of the Extent Info::   The extent information in a buffer or string.
307 * Zero-Length Extents::         A weird special case.
308 * Mathematics of Extent Ordering::  A rigorous foundation.
309 * Extent Fragments::            Cached information useful for redisplay.
310
311 @end detailmenu
312 @end menu
313
314 @node A History of Emacs, XEmacs From the Outside, Top, Top
315 @chapter A History of Emacs
316 @cindex history of Emacs, a
317 @cindex Emacs, a history of
318 @cindex Hackers (Steven Levy)
319 @cindex Levy, Steven
320 @cindex ITS (Incompatible Timesharing System)
321 @cindex Stallman, Richard
322 @cindex RMS
323 @cindex MIT
324 @cindex TECO
325 @cindex FSF
326 @cindex Free Software Foundation
327
328   XEmacs is a powerful, customizable text editor and development
329 environment.  It began as Lucid Emacs, which was in turn derived from
330 GNU Emacs, a program written by Richard Stallman of the Free Software
331 Foundation.  GNU Emacs dates back to the 1970's, and was modelled
332 after a package called ``Emacs'', written in 1976, that was a set of
333 macros on top of TECO, an old, old text editor written at MIT on the
334 DEC PDP 10 under one of the earliest time-sharing operating systems,
335 ITS (Incompatible Timesharing System). (ITS dates back well before
336 Unix.) ITS, TECO, and Emacs were products of a group of people at MIT
337 who called themselves ``hackers'', who shared an idealistic belief
338 system about the free exchange of information and were fanatical in
339 their devotion to and time spent with computers. (The hacker
340 subculture dates back to the late 1950's at MIT and is described in
341 detail in Steven Levy's book @cite{Hackers}.  This book also includes
342 a lot of information about Stallman himself and the development of
343 Lisp, a programming language developed at MIT that underlies Emacs.)
344
345 @menu
346 * Through Version 18::          Unification prevails.
347 * Lucid Emacs::                 One version 19 Emacs.
348 * GNU Emacs 19::                The other version 19 Emacs.
349 * GNU Emacs 20::                The other version 20 Emacs.
350 * XEmacs::                      The continuation of Lucid Emacs.
351 @end menu
352
353 @node Through Version 18
354 @section Through Version 18
355 @cindex version 18, through
356 @cindex Gosling, James
357 @cindex Great Usenet Renaming
358
359   Although the history of the early versions of GNU Emacs is unclear,
360 the history is well-known from the middle of 1985.  A time line is:
361
362 @itemize @bullet
363 @item
364 GNU Emacs version 15 (15.34) was released sometime in 1984 or 1985 and
365 shared some code with a version of Emacs written by James Gosling (the
366 same James Gosling who later created the Java language).
367 @item
368 GNU Emacs version 16 (first released version was 16.56) was released on
369 July 15, 1985.  All Gosling code was removed due to potential copyright
370 problems with the code.
371 @item
372 version 16.57: released on September 16, 1985.
373 @item
374 versions 16.58, 16.59: released on September 17, 1985.
375 @item
376 version 16.60: released on September 19, 1985.  These later version 16's
377 incorporated patches from the net, esp. for getting Emacs to work under
378 System V.
379 @item
380 version 17.36 (first official v17 release) released on December 20,
381 1985.  Included a TeX-able user manual.  First official unpatched
382 version that worked on vanilla System V machines.
383 @item
384 version 17.43 (second official v17 release) released on January 25,
385 1986.
386 @item
387 version 17.45 released on January 30, 1986.
388 @item
389 version 17.46 released on February 4, 1986.
390 @item
391 version 17.48 released on February 10, 1986.
392 @item
393 version 17.49 released on February 12, 1986.
394 @item
395 version 17.55 released on March 18, 1986.
396 @item
397 version 17.57 released on March 27, 1986.
398 @item
399 version 17.58 released on April 4, 1986.
400 @item
401 version 17.61 released on April 12, 1986.
402 @item
403 version 17.63 released on May 7, 1986.
404 @item
405 version 17.64 released on May 12, 1986.
406 @item
407 version 18.24 (a beta version) released on October 2, 1986.
408 @item
409 version 18.30 (a beta version) released on November 15, 1986.
410 @item
411 version 18.31 (a beta version) released on November 23, 1986.
412 @item
413 version 18.32 (a beta version) released on December 7, 1986.
414 @item
415 version 18.33 (a beta version) released on December 12, 1986.
416 @item
417 version 18.35 (a beta version) released on January 5, 1987.
418 @item
419 version 18.36 (a beta version) released on January 21, 1987.
420 @item
421 January 27, 1987: The Great Usenet Renaming.  net.emacs is now
422 comp.emacs.
423 @item
424 version 18.37 (a beta version) released on February 12, 1987.
425 @item
426 version 18.38 (a beta version) released on March 3, 1987.
427 @item
428 version 18.39 (a beta version) released on March 14, 1987.
429 @item
430 version 18.40 (a beta version) released on March 18, 1987.
431 @item
432 version 18.41 (the first ``official'' release) released on March 22,
433 1987.
434 @item
435 version 18.45 released on June 2, 1987.
436 @item
437 version 18.46 released on June 9, 1987.
438 @item
439 version 18.47 released on June 18, 1987.
440 @item
441 version 18.48 released on September 3, 1987.
442 @item
443 version 18.49 released on September 18, 1987.
444 @item
445 version 18.50 released on February 13, 1988.
446 @item
447 version 18.51 released on May 7, 1988.
448 @item
449 version 18.52 released on September 1, 1988.
450 @item
451 version 18.53 released on February 24, 1989.
452 @item
453 version 18.54 released on April 26, 1989.
454 @item
455 version 18.55 released on August 23, 1989.  This is the earliest version
456 that is still available by FTP.
457 @item
458 version 18.56 released on January 17, 1991.
459 @item
460 version 18.57 released late January, 1991.
461 @item
462 version 18.58 released ?????.
463 @item
464 version 18.59 released October 31, 1992.
465 @end itemize
466
467 @node Lucid Emacs
468 @section Lucid Emacs
469 @cindex Lucid Emacs
470 @cindex Lucid Inc.
471 @cindex Energize
472 @cindex Epoch
473
474   Lucid Emacs was developed by the (now-defunct) Lucid Inc., a maker of
475 C++ and Lisp development environments.  It began when Lucid decided they
476 wanted to use Emacs as the editor and cornerstone of their C++
477 development environment (called ``Energize'').  They needed many features
478 that were not available in the existing version of GNU Emacs (version
479 18.5something), in particular good and integrated support for GUI
480 elements such as mouse support, multiple fonts, multiple window-system
481 windows, etc.  A branch of GNU Emacs called Epoch, written at the
482 University of Illinois, existed that supplied many of these features;
483 however, Lucid needed more than what existed in Epoch.  At the time, the
484 Free Software Foundation was working on version 19 of Emacs (this was
485 sometime around 1991), which was planned to have similar features, and
486 so Lucid decided to work with the Free Software Foundation.  Their plan
487 was to add features that they needed, and coordinate with the FSF so
488 that the features would get included back into Emacs version 19.
489
490   Delays in the release of version 19 occurred, however (resulting in it
491 finally being released more than a year after what was initially
492 planned), and Lucid encountered unexpected technical resistance in
493 getting their changes merged back into version 19, so they decided to
494 release their own version of Emacs, which became Lucid Emacs 19.0.
495
496 @cindex Zawinski, Jamie
497 @cindex Sexton, Harlan
498 @cindex Benson, Eric
499 @cindex Devin, Matthieu
500   The initial authors of Lucid Emacs were Matthieu Devin, Harlan Sexton,
501 and Eric Benson, and the work was later taken over by Jamie Zawinski,
502 who became ``Mr. Lucid Emacs'' for many releases.
503
504   A time line for Lucid Emacs is
505
506 @itemize @bullet
507 @item
508 version 19.0 shipped with Energize 1.0, April 1992.
509 @item
510 version 19.1 released June 4, 1992.
511 @item
512 version 19.2 released June 19, 1992.
513 @item
514 version 19.3 released September 9, 1992.
515 @item
516 version 19.4 released January 21, 1993.
517 @item
518 version 19.5 was a repackaging of 19.4 with a few bug fixes and
519 shipped with Energize 2.0.  Never released to the net.
520 @item
521 version 19.6 released April 9, 1993.
522 @item
523 version 19.7 was a repackaging of 19.6 with a few bug fixes and
524 shipped with Energize 2.1.  Never released to the net.
525 @item
526 version 19.8 released September 6, 1993.
527 @item
528 version 19.9 released January 12, 1994.
529 @item
530 version 19.10 released May 27, 1994.
531 @item
532 version 19.11 (first XEmacs) released September 13, 1994.
533 @item
534 version 19.12 released June 23, 1995.
535 @item
536 version 19.13 released September 1, 1995.
537 @item
538 version 19.14 released June 23, 1996.
539 @item
540 version 20.0 released February 9, 1997.
541 @item
542 version 19.15 released March 28, 1997.
543 @item
544 version 20.1 (not released to the net) April 15, 1997.
545 @item
546 version 20.2 released May 16, 1997.
547 @item
548 version 19.16 released October 31, 1997.
549 @item
550 version 20.3 (the first stable version of XEmacs 20.x) released November 30,
551 1997.
552 @item
553 version 20.4 released February 28, 1998.
554 @item
555 version 21.1.2 released May 14, 1999. (The version naming scheme was
556 changed at this point: [a] the second version number is odd for stable
557 versions, even for beta versions; [b] a third version number is added,
558 replacing the "beta xxx" ending for beta versions and allowing for
559 periodic maintenance releases for stable versions.  Therefore, 21.0 was
560 never "officially" released; similarly for 21.2, etc.)
561 @item
562 version 21.1.3 released June 26, 1999.
563 @item
564 version 21.1.4 released July 8, 1999.
565 @item
566 version 21.1.6 released August 14, 1999. (There was no 21.1.5.)
567 @item
568 version 21.1.7 released September 26, 1999.
569 @item
570 version 21.1.8 released November 2, 1999.
571 @item
572 version 21.1.9 released February 13, 2000.
573 @item
574 version 21.1.10 released May 7, 2000.
575 @item
576 version 21.1.10a released June 24, 2000.
577 @item
578 version 21.1.11 released July 18, 2000.
579 @item
580 version 21.1.12 released August 5, 2000.
581 @item
582 version 21.1.13 released January 7, 2001.
583 @item
584 version 21.1.14 released January 27, 2001.
585 @end itemize
586
587 @node GNU Emacs 19
588 @section GNU Emacs 19
589 @cindex GNU Emacs 19
590 @cindex Emacs 19, GNU
591 @cindex version 19, GNU Emacs
592 @cindex FSF Emacs
593
594   About a year after the initial release of Lucid Emacs, the FSF
595 released a beta of their version of Emacs 19 (referred to here as ``GNU
596 Emacs'').  By this time, the current version of Lucid Emacs was
597 19.6. (Strangely, the first released beta from the FSF was GNU Emacs
598 19.7.) A time line for GNU Emacs version 19 is
599
600 @itemize @bullet
601 @item
602 version 19.8 (beta) released May 27, 1993.
603 @item
604 version 19.9 (beta) released May 27, 1993.
605 @item
606 version 19.10 (beta) released May 30, 1993.
607 @item
608 version 19.11 (beta) released June 1, 1993.
609 @item
610 version 19.12 (beta) released June 2, 1993.
611 @item
612 version 19.13 (beta) released June 8, 1993.
613 @item
614 version 19.14 (beta) released June 17, 1993.
615 @item
616 version 19.15 (beta) released June 19, 1993.
617 @item
618 version 19.16 (beta) released July 6, 1993.
619 @item
620 version 19.17 (beta) released late July, 1993.
621 @item
622 version 19.18 (beta) released August 9, 1993.
623 @item
624 version 19.19 (beta) released August 15, 1993.
625 @item
626 version 19.20 (beta) released November 17, 1993.
627 @item
628 version 19.21 (beta) released November 17, 1993.
629 @item
630 version 19.22 (beta) released November 28, 1993.
631 @item
632 version 19.23 (beta) released May 17, 1994.
633 @item
634 version 19.24 (beta) released May 16, 1994.
635 @item
636 version 19.25 (beta) released June 3, 1994.
637 @item
638 version 19.26 (beta) released September 11, 1994.
639 @item
640 version 19.27 (beta) released September 14, 1994.
641 @item
642 version 19.28 (first ``official'' release) released November 1, 1994.
643 @item
644 version 19.29 released June 21, 1995.
645 @item
646 version 19.30 released November 24, 1995.
647 @item
648 version 19.31 released May 25, 1996.
649 @item
650 version 19.32 released July 31, 1996.
651 @item
652 version 19.33 released August 11, 1996.
653 @item
654 version 19.34 released August 21, 1996.
655 @item
656 version 19.34b released September 6, 1996.
657 @end itemize
658
659 @cindex Mlynarik, Richard
660   In some ways, GNU Emacs 19 was better than Lucid Emacs; in some ways,
661 worse.  Lucid soon began incorporating features from GNU Emacs 19 into
662 Lucid Emacs; the work was mostly done by Richard Mlynarik, who had been
663 working on and using GNU Emacs for a long time (back as far as version
664 16 or 17).
665
666 @node GNU Emacs 20
667 @section GNU Emacs 20
668 @cindex GNU Emacs 20
669 @cindex Emacs 20, GNU
670 @cindex version 20, GNU Emacs
671 @cindex FSF Emacs
672
673 On February 2, 1997 work began on GNU Emacs to integrate Mule.  The first
674 release was made in September of that year.
675
676 A timeline for Emacs 20 is
677
678 @itemize @bullet
679 @item
680 version 20.1 released September 17, 1997.
681 @item
682 version 20.2 released September 20, 1997.
683 @item
684 version 20.3 released August 19, 1998.
685 @end itemize
686
687 @node XEmacs
688 @section XEmacs
689 @cindex XEmacs
690
691 @cindex Sun Microsystems
692 @cindex University of Illinois
693 @cindex Illinois, University of
694 @cindex SPARCWorks
695 @cindex Andreessen, Marc
696 @cindex Baur, Steve
697 @cindex Buchholz, Martin
698 @cindex Kaplan, Simon
699 @cindex Wing, Ben
700 @cindex Thompson, Chuck
701 @cindex Win-Emacs
702 @cindex Epoch
703 @cindex Amdahl Corporation
704   Around the time that Lucid was developing Energize, Sun Microsystems
705 was developing their own development environment (called ``SPARCWorks'')
706 and also decided to use Emacs.  They joined forces with the Epoch team
707 at the University of Illinois and later with Lucid.  The maintainer of
708 the last-released version of Epoch was Marc Andreessen, but he dropped
709 out and the Epoch project, headed by Simon Kaplan, lured Chuck Thompson
710 away from a system administration job to become the primary Lucid Emacs
711 author for Epoch and Sun.  Chuck's area of specialty became the
712 redisplay engine (he replaced the old Lucid Emacs redisplay engine with
713 a ported version from Epoch and then later rewrote it from scratch).
714 Sun also hired Ben Wing (the author of Win-Emacs, a port of Lucid Emacs
715 to Microsoft Windows 3.1) in 1993, for what was initially a one-month
716 contract to fix some event problems but later became a many-year
717 involvement, punctuated by a six-month contract with Amdahl Corporation.
718
719 @cindex rename to XEmacs
720   In 1994, Sun and Lucid agreed to rename Lucid Emacs to XEmacs (a name
721 not favorable to either company); the first release called XEmacs was
722 version 19.11.  In June 1994, Lucid folded and Jamie quit to work for
723 the newly formed Mosaic Communications Corp., later Netscape
724 Communications Corp. (co-founded by the same Marc Andreessen, who had
725 quit his Epoch job to work on a graphical browser for the World Wide
726 Web).  Chuck then become the primary maintainer of XEmacs, and put out
727 versions 19.11 through 19.14 in conjunction with Ben.  For 19.12 and
728 19.13, Chuck added the new redisplay and many other display improvements
729 and Ben added MULE support (support for Asian and other languages) and
730 redesigned most of the internal Lisp subsystems to better support the
731 MULE work and the various other features being added to XEmacs.  After
732 19.14 Chuck retired as primary maintainer and Steve Baur stepped in.
733
734 @cindex MULE merged XEmacs appears
735   Soon after 19.13 was released, work began in earnest on the MULE
736 internationalization code and the source tree was divided into two
737 development paths.  The MULE version was initially called 19.20, but was
738 soon renamed to 20.0.  In 1996 Martin Buchholz of Sun Microsystems took
739 over the care and feeding of it and worked on it in parallel with the
740 19.14 development that was occurring at the same time.  After much work
741 by Martin, it was decided to release 20.0 ahead of 19.15 in February
742 1997.  The source tree remained divided until 20.2 when the version 19
743 source was finally retired at version 19.16.
744
745 @cindex Baur, Steve
746 @cindex Buchholz, Martin
747 @cindex Jones, Kyle
748 @cindex Niksic, Hrvoje
749 @cindex XEmacs goes it alone
750   In 1997, Sun finally dropped all pretense of support for XEmacs and
751 Martin Buchholz left the company in November.  Since then, and mostly
752 for the previous year, because Steve Baur was never paid to work on
753 XEmacs, XEmacs has existed solely on the contributions of volunteers
754 from the Free Software Community.  Starting from 1997, Hrvoje Niksic and
755 Kyle Jones have figured prominently in XEmacs development.
756
757 @cindex merging attempts
758   Many attempts have been made to merge XEmacs and GNU Emacs, but they
759 have consistently failed.
760
761   A more detailed history is contained in the XEmacs About page.
762
763   A time line for XEmacs is
764
765 @itemize @bullet
766 @item
767 version 19.11 (first XEmacs) released September 13, 1994.
768 @item
769 version 19.12 released June 23, 1995.
770 @item
771 version 19.13 released September 1, 1995.
772 @item
773 version 19.14 released June 23, 1996.
774 @item
775 version 20.0 released February 9, 1997.
776 @item
777 version 19.15 released March 28, 1997.
778 @item
779 version 20.1 (not released to the net) April 15, 1997.
780 @item
781 version 20.2 released May 16, 1997.
782 @item
783 version 19.16 released October 31, 1997.
784 @item
785 version 20.3 (the first stable version of XEmacs 20.x) released November 30,
786 1997.
787 @item
788 version 20.4 released February 28, 1998.
789 @item
790 version 21.0.60 released December 10, 1998. (The version naming scheme was
791 changed at this point: [a] the second version number is odd for stable
792 versions, even for beta versions; [b] a third version number is added,
793 replacing the "beta xxx" ending for beta versions and allowing for
794 periodic maintenance releases for stable versions.  Therefore, 21.0 was
795 never "officially" released; similarly for 21.2, etc.)
796 @item
797 version 21.0.61 released January 4, 1999.
798 @item
799 version 21.0.63 released February 3, 1999.
800 @item
801 version 21.0.64 released March 1, 1999.
802 @item
803 version 21.0.65 released March 5, 1999.
804 @item
805 version 21.0.66 released March 12, 1999.
806 @item
807 version 21.0.67 released March 25, 1999.
808 @item
809 version 21.1.2 released May 14, 1999. (This is the followup to 21.0.67.
810 The second version number was bumped to indicate the beginning of the
811 "stable" series.)
812 @item
813 version 21.1.3 released June 26, 1999.
814 @item
815 version 21.1.4 released July 8, 1999.
816 @item
817 version 21.1.6 released August 14, 1999. (There was no 21.1.5.)
818 @item
819 version 21.1.7 released September 26, 1999.
820 @item
821 version 21.1.8 released November 2, 1999.
822 @item
823 version 21.1.9 released February 13, 2000.
824 @item
825 version 21.1.10 released May 7, 2000.
826 @item
827 version 21.1.10a released June 24, 2000.
828 @item
829 version 21.1.11 released July 18, 2000.
830 @item
831 version 21.1.12 released August 5, 2000.
832 @item
833 version 21.1.13 released January 7, 2001.
834 @item
835 version 21.1.14 released January 27, 2001.
836 @item
837 version 21.2.9 released February 3, 1999.
838 @item
839 version 21.2.10 released February 5, 1999.
840 @item
841 version 21.2.11 released March 1, 1999.
842 @item
843 version 21.2.12 released March 5, 1999.
844 @item
845 version 21.2.13 released March 12, 1999.
846 @item
847 version 21.2.14 released May 14, 1999.
848 @item
849 version 21.2.15 released June 4, 1999.
850 @item
851 version 21.2.16 released June 11, 1999.
852 @item
853 version 21.2.17 released June 22, 1999.
854 @item
855 version 21.2.18 released July 14, 1999.
856 @item
857 version 21.2.19 released July 30, 1999.
858 @item
859 version 21.2.20 released November 10, 1999.
860 @item
861 version 21.2.21 released November 28, 1999.
862 @item
863 version 21.2.22 released November 29, 1999.
864 @item
865 version 21.2.23 released December 7, 1999.
866 @item
867 version 21.2.24 released December 14, 1999.
868 @item
869 version 21.2.25 released December 24, 1999.
870 @item
871 version 21.2.26 released December 31, 1999.
872 @item
873 version 21.2.27 released January 18, 2000.
874 @item
875 version 21.2.28 released February 7, 2000.
876 @item
877 version 21.2.29 released February 16, 2000.
878 @item
879 version 21.2.30 released February 21, 2000.
880 @item
881 version 21.2.31 released February 23, 2000.
882 @item
883 version 21.2.32 released March 20, 2000.
884 @item
885 version 21.2.33 released May 1, 2000.
886 @item
887 version 21.2.34 released May 28, 2000.
888 @item
889 version 21.2.35 released July 19, 2000.
890 @item
891 version 21.2.36 released October 4, 2000.
892 @item
893 version 21.2.37 released November 14, 2000.
894 @item
895 version 21.2.38 released December 5, 2000.
896 @item
897 version 21.2.39 released December 31, 2000.
898 @item
899 version 21.2.40 released January 8, 2001.
900 @item
901 version 21.2.41 released January 17, 2001.
902 @item
903 version 21.2.42 released January 20, 2001.
904 @item
905 version 21.2.43 released January 26, 2001.
906 @item
907 version 21.2.44 released February 8, 2001.
908 @item
909 version 21.2.45 released February 23, 2001.
910 @item
911 version 21.2.46 released March 21, 2001.
912 @end itemize
913
914 @node XEmacs From the Outside, The Lisp Language, A History of Emacs, Top
915 @chapter XEmacs From the Outside
916 @cindex XEmacs from the outside
917 @cindex outside, XEmacs from the
918 @cindex read-eval-print
919
920   XEmacs appears to the outside world as an editor, but it is really a
921 Lisp environment.  At its heart is a Lisp interpreter; it also
922 ``happens'' to contain many specialized object types (e.g. buffers,
923 windows, frames, events) that are useful for implementing an editor.
924 Some of these objects (in particular windows and frames) have
925 displayable representations, and XEmacs provides a function
926 @code{redisplay()} that ensures that the display of all such objects
927 matches their internal state.  Most of the time, a standard Lisp
928 environment is in a @dfn{read-eval-print} loop---i.e. ``read some Lisp
929 code, execute it, and print the results''.  XEmacs has a similar loop:
930
931 @itemize @bullet
932 @item
933 read an event
934 @item
935 dispatch the event (i.e. ``do it'')
936 @item
937 redisplay
938 @end itemize
939
940   Reading an event is done using the Lisp function @code{next-event},
941 which waits for something to happen (typically, the user presses a key
942 or moves the mouse) and returns an event object describing this.
943 Dispatching an event is done using the Lisp function
944 @code{dispatch-event}, which looks up the event in a keymap object (a
945 particular kind of object that associates an event with a Lisp function)
946 and calls that function.  The function ``does'' what the user has
947 requested by changing the state of particular frame objects, buffer
948 objects, etc.  Finally, @code{redisplay()} is called, which updates the
949 display to reflect those changes just made.  Thus is an ``editor'' born.
950
951 @cindex bridge, playing
952 @cindex taxes, doing
953 @cindex pi, calculating
954   Note that you do not have to use XEmacs as an editor; you could just
955 as well make it do your taxes, compute pi, play bridge, etc.  You'd just
956 have to write functions to do those operations in Lisp.
957
958 @node The Lisp Language, XEmacs From the Perspective of Building, XEmacs From the Outside, Top
959 @chapter The Lisp Language
960 @cindex Lisp language, the
961 @cindex Lisp vs. C
962 @cindex C vs. Lisp
963 @cindex Lisp vs. Java
964 @cindex Java vs. Lisp
965 @cindex dynamic scoping
966 @cindex scoping, dynamic
967 @cindex dynamic types
968 @cindex types, dynamic
969 @cindex Java
970 @cindex Common Lisp
971 @cindex Gosling, James
972
973   Lisp is a general-purpose language that is higher-level than C and in
974 many ways more powerful than C.  Powerful dialects of Lisp such as
975 Common Lisp are probably much better languages for writing very large
976 applications than is C. (Unfortunately, for many non-technical
977 reasons C and its successor C++ have become the dominant languages for
978 application development.  These languages are both inadequate for
979 extremely large applications, which is evidenced by the fact that newer,
980 larger programs are becoming ever harder to write and are requiring ever
981 more programmers despite great increases in C development environments;
982 and by the fact that, although hardware speeds and reliability have been
983 growing at an exponential rate, most software is still generally
984 considered to be slow and buggy.)
985
986   The new Java language holds promise as a better general-purpose
987 development language than C.  Java has many features in common with
988 Lisp that are not shared by C (this is not a coincidence, since
989 Java was designed by James Gosling, a former Lisp hacker).  This
990 will be discussed more later.
991
992 For those used to C, here is a summary of the basic differences between
993 C and Lisp:
994
995 @enumerate
996 @item
997 Lisp has an extremely regular syntax.  Every function, expression,
998 and control statement is written in the form
999
1000 @example
1001    (@var{func} @var{arg1} @var{arg2} ...)
1002 @end example
1003
1004 This is as opposed to C, which writes functions as
1005
1006 @example
1007    func(@var{arg1}, @var{arg2}, ...)
1008 @end example
1009
1010 but writes expressions involving operators as (e.g.)
1011
1012 @example
1013    @var{arg1} + @var{arg2}
1014 @end example
1015
1016 and writes control statements as (e.g.)
1017
1018 @example
1019    while (@var{expr}) @{ @var{statement1}; @var{statement2}; ... @}
1020 @end example
1021
1022 Lisp equivalents of the latter two would be
1023
1024 @example
1025    (+ @var{arg1} @var{arg2} ...)
1026 @end example
1027
1028 and
1029
1030 @example
1031    (while @var{expr} @var{statement1} @var{statement2} ...)
1032 @end example
1033
1034 @item
1035 Lisp is a safe language.  Assuming there are no bugs in the Lisp
1036 interpreter/compiler, it is impossible to write a program that ``core
1037 dumps'' or otherwise causes the machine to execute an illegal
1038 instruction.  This is very different from C, where perhaps the most
1039 common outcome of a bug is exactly such a crash.  A corollary of this is that
1040 the C operation of casting a pointer is impossible (and unnecessary) in
1041 Lisp, and that it is impossible to access memory outside the bounds of
1042 an array.
1043
1044 @item
1045 Programs and data are written in the same form.  The
1046 parenthesis-enclosing form described above for statements is the same
1047 form used for the most common data type in Lisp, the list.  Thus, it is
1048 possible to represent any Lisp program using Lisp data types, and for
1049 one program to construct Lisp statements and then dynamically
1050 @dfn{evaluate} them, or cause them to execute.
1051
1052 @item
1053 All objects are @dfn{dynamically typed}.  This means that part of every
1054 object is an indication of what type it is.  A Lisp program can
1055 manipulate an object without knowing what type it is, and can query an
1056 object to determine its type.  This means that, correspondingly,
1057 variables and function parameters can hold objects of any type and are
1058 not normally declared as being of any particular type.  This is opposed
1059 to the @dfn{static typing} of C, where variables can hold exactly one
1060 type of object and must be declared as such, and objects do not contain
1061 an indication of their type because it's implicit in the variables they
1062 are stored in.  It is possible in C to have a variable hold different
1063 types of objects (e.g. through the use of @code{void *} pointers or
1064 variable-argument functions), but the type information must then be
1065 passed explicitly in some other fashion, leading to additional program
1066 complexity.
1067
1068 @item
1069 Allocated memory is automatically reclaimed when it is no longer in use.
1070 This operation is called @dfn{garbage collection} and involves looking
1071 through all variables to see what memory is being pointed to, and
1072 reclaiming any memory that is not pointed to and is thus
1073 ``inaccessible'' and out of use.  This is as opposed to C, in which
1074 allocated memory must be explicitly reclaimed using @code{free()}.  If
1075 you simply drop all pointers to memory without freeing it, it becomes
1076 ``leaked'' memory that still takes up space.  Over a long period of
1077 time, this can cause your program to grow and grow until it runs out of
1078 memory.
1079
1080 @item
1081 Lisp has built-in facilities for handling errors and exceptions.  In C,
1082 when an error occurs, usually either the program exits entirely or the
1083 routine in which the error occurs returns a value indicating this.  If
1084 an error occurs in a deeply-nested routine, then every routine currently
1085 called must unwind itself normally and return an error value back up to
1086 the next routine.  This means that every routine must explicitly check
1087 for an error in all the routines it calls; if it does not do so,
1088 unexpected and often random behavior results.  This is an extremely
1089 common source of bugs in C programs.  An alternative would be to do a
1090 non-local exit using @code{longjmp()}, but that is often very dangerous
1091 because the routines that were exited past had no opportunity to clean
1092 up after themselves and may leave things in an inconsistent state,
1093 causing a crash shortly afterwards.
1094
1095 Lisp provides mechanisms to make such non-local exits safe.  When an
1096 error occurs, a routine simply signals that an error of a particular
1097 class has occurred, and a non-local exit takes place.  Any routine can
1098 trap errors occurring in routines it calls by registering an error
1099 handler for some or all classes of errors. (If no handler is registered,
1100 a default handler, generally installed by the top-level event loop, is
1101 executed; this prints out the error and continues.) Routines can also
1102 specify cleanup code (called an @dfn{unwind-protect}) that will be
1103 called when control exits from a block of code, no matter how that exit
1104 occurs---i.e. even if a function deeply nested below it causes a
1105 non-local exit back to the top level.
1106
1107 Note that this facility has appeared in some recent vintages of C, in
1108 particular Visual C++ and other PC compilers written for the Microsoft
1109 Win32 API.
1110
1111 @item
1112 In Emacs Lisp, local variables are @dfn{dynamically scoped}.  This means
1113 that if you declare a local variable in a particular function, and then
1114 call another function, that subfunction can ``see'' the local variable
1115 you declared.  This is actually considered a bug in Emacs Lisp and in
1116 all other early dialects of Lisp, and was corrected in Common Lisp. (In
1117 Common Lisp, you can still declare dynamically scoped variables if you
1118 want to---they are sometimes useful---but variables by default are
1119 @dfn{lexically scoped} as in C.)
1120 @end enumerate
1121
1122 For those familiar with Lisp, Emacs Lisp is modelled after MacLisp, an
1123 early dialect of Lisp developed at MIT (no relation to the Macintosh
1124 computer).  There is a Common Lisp compatibility package available for
1125 Emacs that provides many of the features of Common Lisp.
1126
1127 The Java language is derived in many ways from C, and shares a similar
1128 syntax, but has the following features in common with Lisp (and different
1129 from C):
1130
1131 @enumerate
1132 @item
1133 Java is a safe language, like Lisp.
1134 @item
1135 Java provides garbage collection, like Lisp.
1136 @item
1137 Java has built-in facilities for handling errors and exceptions, like
1138 Lisp.
1139 @item
1140 Java has a type system that combines the best advantages of both static
1141 and dynamic typing.  Objects (except very simple types) are explicitly
1142 marked with their type, as in dynamic typing; but there is a hierarchy
1143 of types and functions are declared to accept only certain types, thus
1144 providing the increased compile-time error-checking of static typing.
1145 @end enumerate
1146
1147 The Java language also has some negative attributes:
1148
1149 @enumerate
1150 @item
1151 Java uses the edit/compile/run model of software development.  This
1152 makes it hard to use interactively.  For example, to use Java like
1153 @code{bc} it is necessary to write a special purpose, albeit tiny,
1154 application.  In Emacs Lisp, a calculator comes built-in without any
1155 effort - one can always just type an expression in the @code{*scratch*}
1156 buffer.
1157 @item
1158 Java tries too hard to enforce, not merely enable, portability, making
1159 ordinary access to standard OS facilities painful.  Java has an
1160 @dfn{agenda}.  I think this is why @code{chdir} is not part of standard
1161 Java, which is inexcusable.
1162 @end enumerate
1163
1164 Unfortunately, there is no perfect language.  Static typing allows a
1165 compiler to catch programmer errors and produce more efficient code, but
1166 makes programming more tedious and less fun.  For the foreseeable future,
1167 an Ideal Editing and Programming Environment (and that is what XEmacs
1168 aspires to) will be programmable in multiple languages: high level ones
1169 like Lisp for user customization and prototyping, and lower level ones
1170 for infrastructure and industrial strength applications.  If I had my
1171 way, XEmacs would be friendly towards the Python, Scheme, C++, ML,
1172 etc... communities.  But there are serious technical difficulties to
1173 achieving that goal.
1174
1175 The word @dfn{application} in the previous paragraph was used
1176 intentionally.  XEmacs implements an API for programs written in Lisp
1177 that makes it a full-fledged application platform, very much like an OS
1178 inside the real OS.
1179
1180 @node XEmacs From the Perspective of Building, XEmacs From the Inside, The Lisp Language, Top
1181 @chapter XEmacs From the Perspective of Building
1182 @cindex XEmacs from the perspective of building
1183 @cindex building, XEmacs from the perspective of
1184
1185 The heart of XEmacs is the Lisp environment, which is written in C.
1186 This is contained in the @file{src/} subdirectory.  Underneath
1187 @file{src/} are two subdirectories of header files: @file{s/} (header
1188 files for particular operating systems) and @file{m/} (header files for
1189 particular machine types).  In practice the distinction between the two
1190 types of header files is blurred.  These header files define or undefine
1191 certain preprocessor constants and macros to indicate particular
1192 characteristics of the associated machine or operating system.  As part
1193 of the configure process, one @file{s/} file and one @file{m/} file is
1194 identified for the particular environment in which XEmacs is being
1195 built.
1196
1197 XEmacs also contains a great deal of Lisp code.  This implements the
1198 operations that make XEmacs useful as an editor as well as just a Lisp
1199 environment, and also contains many add-on packages that allow XEmacs to
1200 browse directories, act as a mail and Usenet news reader, compile Lisp
1201 code, etc.  There is actually more Lisp code than C code associated with
1202 XEmacs, but much of the Lisp code is peripheral to the actual operation
1203 of the editor.  The Lisp code all lies in subdirectories underneath the
1204 @file{lisp/} directory.
1205
1206 The @file{lwlib/} directory contains C code that implements a
1207 generalized interface onto different X widget toolkits and also
1208 implements some widgets of its own that behave like Motif widgets but
1209 are faster, free, and in some cases more powerful.  The code in this
1210 directory compiles into a library and is mostly independent from XEmacs.
1211
1212 The @file{etc/} directory contains various data files associated with
1213 XEmacs.  Some of them are actually read by XEmacs at startup; others
1214 merely contain useful information of various sorts.
1215
1216 The @file{lib-src/} directory contains C code for various auxiliary
1217 programs that are used in connection with XEmacs.  Some of them are used
1218 during the build process; others are used to perform certain functions
1219 that cannot conveniently be placed in the XEmacs executable (e.g. the
1220 @file{movemail} program for fetching mail out of @file{/var/spool/mail},
1221 which must be setgid to @file{mail} on many systems; and the
1222 @file{gnuclient} program, which allows an external script to communicate
1223 with a running XEmacs process).
1224
1225 The @file{man/} directory contains the sources for the XEmacs
1226 documentation.  It is mostly in a form called Texinfo, which can be
1227 converted into either a printed document (by passing it through @TeX{})
1228 or into on-line documentation called @dfn{info files}.
1229
1230 The @file{info/} directory contains the results of formatting the XEmacs
1231 documentation as @dfn{info files}, for on-line use.  These files are
1232 used when you enter the Info system using @kbd{C-h i} or through the
1233 Help menu.
1234
1235 The @file{dynodump/} directory contains auxiliary code used to build
1236 XEmacs on Solaris platforms.
1237
1238 The other directories contain various miscellaneous code and information
1239 that is not normally used or needed.
1240
1241 The first step of building involves running the @file{configure} program
1242 and passing it various parameters to specify any optional features you
1243 want and compiler arguments and such, as described in the @file{INSTALL}
1244 file.  This determines what the build environment is, chooses the
1245 appropriate @file{s/} and @file{m/} file, and runs a series of tests to
1246 determine many details about your environment, such as which library
1247 functions are available and exactly how they work.  The reason for
1248 running these tests is that it allows XEmacs to be compiled on a much
1249 wider variety of platforms than those that the XEmacs developers happen
1250 to be familiar with, including various sorts of hybrid platforms.  This
1251 is especially important now that many operating systems give you a great
1252 deal of control over exactly what features you want installed, and allow
1253 for easy upgrading of parts of a system without upgrading the rest.  It
1254 would be impossible to pre-determine and pre-specify the information for
1255 all possible configurations.
1256
1257 In fact, the @file{s/} and @file{m/} files are basically @emph{evil},
1258 since they contain unmaintainable platform-specific hard-coded
1259 information.  XEmacs has been moving in the direction of having all
1260 system-specific information be determined dynamically by
1261 @file{configure}.  Perhaps someday we can @code{rm -rf src/s src/m}.
1262
1263 When configure is done running, it generates @file{Makefile}s and
1264 @file{GNUmakefile}s and the file @file{src/config.h} (which describes
1265 the features of your system) from template files.  You then run
1266 @file{make}, which compiles the auxiliary code and programs in
1267 @file{lib-src/} and @file{lwlib/} and the main XEmacs executable in
1268 @file{src/}.  The result of compiling and linking is an executable
1269 called @file{temacs}, which is @emph{not} the final XEmacs executable.
1270 @file{temacs} by itself is not intended to function as an editor or even
1271 display any windows on the screen, and if you simply run it, it will
1272 exit immediately.  The @file{Makefile} runs @file{temacs} with certain
1273 options that cause it to initialize itself, read in a number of basic
1274 Lisp files, and then dump itself out into a new executable called
1275 @file{xemacs}.  This new executable has been pre-initialized and
1276 contains pre-digested Lisp code that is necessary for the editor to
1277 function (this includes most basic editing functions,
1278 e.g. @code{kill-line}, that can be defined in terms of other Lisp
1279 primitives; some initialization code that is called when certain
1280 objects, such as frames, are created; and all of the standard
1281 keybindings and code for the actions they result in).  This executable,
1282 @file{xemacs}, is the executable that you run to use the XEmacs editor.
1283
1284 Although @file{temacs} is not intended to be run as an editor, it can,
1285 by using the incantation @code{temacs -batch -l loadup.el run-temacs}.
1286 This is useful when the dumping procedure described above is broken, or
1287 when using certain program debugging tools such as Purify.  These tools
1288 get mighty confused by the tricks played by the XEmacs build process,
1289 such as allocation memory in one process, and freeing it in the next.
1290
1291 @node XEmacs From the Inside, The XEmacs Object System (Abstractly Speaking), XEmacs From the Perspective of Building, Top
1292 @chapter XEmacs From the Inside
1293 @cindex XEmacs from the inside
1294 @cindex inside, XEmacs from the
1295
1296 Internally, XEmacs is quite complex, and can be very confusing.  To
1297 simplify things, it can be useful to think of XEmacs as containing an
1298 event loop that ``drives'' everything, and a number of other subsystems,
1299 such as a Lisp engine and a redisplay mechanism.  Each of these other
1300 subsystems exists simultaneously in XEmacs, and each has a certain
1301 state.  The flow of control continually passes in and out of these
1302 different subsystems in the course of normal operation of the editor.
1303
1304 It is important to keep in mind that, most of the time, the editor is
1305 ``driven'' by the event loop.  Except during initialization and batch
1306 mode, all subsystems are entered directly or indirectly through the
1307 event loop, and ultimately, control exits out of all subsystems back up
1308 to the event loop.  This cycle of entering a subsystem, exiting back out
1309 to the event loop, and starting another iteration of the event loop
1310 occurs once each keystroke, mouse motion, etc.
1311
1312 If you're trying to understand a particular subsystem (other than the
1313 event loop), think of it as a ``daemon'' process or ``servant'' that is
1314 responsible for one particular aspect of a larger system, and
1315 periodically receives commands or environment changes that cause it to
1316 do something.  Ultimately, these commands and environment changes are
1317 always triggered by the event loop.  For example:
1318
1319 @itemize @bullet
1320 @item
1321 The window and frame mechanism is responsible for keeping track of what
1322 windows and frames exist, what buffers are in them, etc.  It is
1323 periodically given commands (usually from the user) to make a change to
1324 the current window/frame state: i.e. create a new frame, delete a
1325 window, etc.
1326
1327 @item
1328 The buffer mechanism is responsible for keeping track of what buffers
1329 exist and what text is in them.  It is periodically given commands
1330 (usually from the user) to insert or delete text, create a buffer, etc.
1331 When it receives a text-change command, it notifies the redisplay
1332 mechanism.
1333
1334 @item
1335 The redisplay mechanism is responsible for making sure that windows and
1336 frames are displayed correctly.  It is periodically told (by the event
1337 loop) to actually ``do its job'', i.e. snoop around and see what the
1338 current state of the environment (mostly of the currently-existing
1339 windows, frames, and buffers) is, and make sure that state matches
1340 what's actually displayed.  It keeps lots and lots of information around
1341 (such as what is actually being displayed currently, and what the
1342 environment was last time it checked) so that it can minimize the work
1343 it has to do.  It is also helped along in that whenever a relevant
1344 change to the environment occurs, the redisplay mechanism is told about
1345 this, so it has a pretty good idea of where it has to look to find
1346 possible changes and doesn't have to look everywhere.
1347
1348 @item
1349 The Lisp engine is responsible for executing the Lisp code in which most
1350 user commands are written.  It is entered through a call to @code{eval}
1351 or @code{funcall}, which occurs as a result of dispatching an event from
1352 the event loop.  The functions it calls issue commands to the buffer
1353 mechanism, the window/frame subsystem, etc.
1354
1355 @item
1356 The Lisp allocation subsystem is responsible for keeping track of Lisp
1357 objects.  It is given commands from the Lisp engine to allocate objects,
1358 garbage collect, etc.
1359 @end itemize
1360
1361 etc.
1362
1363   The important idea here is that there are a number of independent
1364 subsystems each with its own responsibility and persistent state, just
1365 like different employees in a company, and each subsystem is
1366 periodically given commands from other subsystems.  Commands can flow
1367 from any one subsystem to any other, but there is usually some sort of
1368 hierarchy, with all commands originating from the event subsystem.
1369
1370   XEmacs is entered in @code{main()}, which is in @file{emacs.c}.  When
1371 this is called the first time (in a properly-invoked @file{temacs}), it
1372 does the following:
1373
1374 @enumerate
1375 @item
1376 It does some very basic environment initializations, such as determining
1377 where it and its directories (e.g. @file{lisp/} and @file{etc/}) reside
1378 and setting up signal handlers.
1379 @item
1380 It initializes the entire Lisp interpreter.
1381 @item
1382 It sets the initial values of many built-in variables (including many
1383 variables that are visible to Lisp programs), such as the global keymap
1384 object and the built-in faces (a face is an object that describes the
1385 display characteristics of text).  This involves creating Lisp objects
1386 and thus is dependent on step (2).
1387 @item
1388 It performs various other initializations that are relevant to the
1389 particular environment it is running in, such as retrieving environment
1390 variables, determining the current date and the user who is running the
1391 program, examining its standard input, creating any necessary file
1392 descriptors, etc.
1393 @item
1394 At this point, the C initialization is complete.  A Lisp program that
1395 was specified on the command line (usually @file{loadup.el}) is called
1396 (temacs is normally invoked as @code{temacs -batch -l loadup.el dump}).
1397 @file{loadup.el} loads all of the other Lisp files that are needed for
1398 the operation of the editor, calls the @code{dump-emacs} function to
1399 write out @file{xemacs}, and then kills the temacs process.
1400 @end enumerate
1401
1402   When @file{xemacs} is then run, it only redoes steps (1) and (4)
1403 above; all variables already contain the values they were set to when
1404 the executable was dumped, and all memory that was allocated with
1405 @code{malloc()} is still around. (XEmacs knows whether it is being run
1406 as @file{xemacs} or @file{temacs} because it sets the global variable
1407 @code{initialized} to 1 after step (4) above.) At this point,
1408 @file{xemacs} calls a Lisp function to do any further initialization,
1409 which includes parsing the command-line (the C code can only do limited
1410 command-line parsing, which includes looking for the @samp{-batch} and
1411 @samp{-l} flags and a few other flags that it needs to know about before
1412 initialization is complete), creating the first frame (or @dfn{window}
1413 in standard window-system parlance), running the user's init file
1414 (usually the file @file{.emacs} in the user's home directory), etc.  The
1415 function to do this is usually called @code{normal-top-level};
1416 @file{loadup.el} tells the C code about this function by setting its
1417 name as the value of the Lisp variable @code{top-level}.
1418
1419   When the Lisp initialization code is done, the C code enters the event
1420 loop, and stays there for the duration of the XEmacs process.  The code
1421 for the event loop is contained in @file{cmdloop.c}, and is called
1422 @code{Fcommand_loop_1()}.  Note that this event loop could very well be
1423 written in Lisp, and in fact a Lisp version exists; but apparently,
1424 doing this makes XEmacs run noticeably slower.
1425
1426   Notice how much of the initialization is done in Lisp, not in C.
1427 In general, XEmacs tries to move as much code as is possible
1428 into Lisp.  Code that remains in C is code that implements the
1429 Lisp interpreter itself, or code that needs to be very fast, or
1430 code that needs to do system calls or other such stuff that
1431 needs to be done in C, or code that needs to have access to
1432 ``forbidden'' structures. (One conscious aspect of the design of
1433 Lisp under XEmacs is a clean separation between the external
1434 interface to a Lisp object's functionality and its internal
1435 implementation.  Part of this design is that Lisp programs
1436 are forbidden from accessing the contents of the object other
1437 than through using a standard API.  In this respect, XEmacs Lisp
1438 is similar to modern Lisp dialects but differs from GNU Emacs,
1439 which tends to expose the implementation and allow Lisp
1440 programs to look at it directly.  The major advantage of
1441 hiding the implementation is that it allows the implementation
1442 to be redesigned without affecting any Lisp programs, including
1443 those that might want to be ``clever'' by looking directly at
1444 the object's contents and possibly manipulating them.)
1445
1446   Moving code into Lisp makes the code easier to debug and maintain and
1447 makes it much easier for people who are not XEmacs developers to
1448 customize XEmacs, because they can make a change with much less chance
1449 of obscure and unwanted interactions occurring than if they were to
1450 change the C code.
1451
1452 @node The XEmacs Object System (Abstractly Speaking), How Lisp Objects Are Represented in C, XEmacs From the Inside, Top
1453 @chapter The XEmacs Object System (Abstractly Speaking)
1454 @cindex XEmacs object system (abstractly speaking), the
1455 @cindex object system (abstractly speaking), the XEmacs
1456
1457   At the heart of the Lisp interpreter is its management of objects.
1458 XEmacs Lisp contains many built-in objects, some of which are
1459 simple and others of which can be very complex; and some of which
1460 are very common, and others of which are rarely used or are only
1461 used internally. (Since the Lisp allocation system, with its
1462 automatic reclamation of unused storage, is so much more convenient
1463 than @code{malloc()} and @code{free()}, the C code makes extensive use of it
1464 in its internal operations.)
1465
1466   The basic Lisp objects are
1467
1468 @table @code
1469 @item integer
1470 28 or 31 bits of precision, or 60 or 63 bits on 64-bit machines; the
1471 reason for this is described below when the internal Lisp object
1472 representation is described.
1473 @item float
1474 Same precision as a double in C.
1475 @item cons
1476 A simple container for two Lisp objects, used to implement lists and
1477 most other data structures in Lisp.
1478 @item char
1479 An object representing a single character of text; chars behave like
1480 integers in many ways but are logically considered text rather than
1481 numbers and have a different read syntax. (the read syntax for a char
1482 contains the char itself or some textual encoding of it---for example,
1483 a Japanese Kanji character might be encoded as @samp{^[$(B#&^[(B} using the
1484 ISO-2022 encoding standard---rather than the numerical representation
1485 of the char; this way, if the mapping between chars and integers
1486 changes, which is quite possible for Kanji characters and other extended
1487 characters, the same character will still be created.  Note that some
1488 primitives confuse chars and integers.  The worst culprit is @code{eq},
1489 which makes a special exception and considers a char to be @code{eq} to
1490 its integer equivalent, even though in no other case are objects of two
1491 different types @code{eq}.  The reason for this monstrosity is
1492 compatibility with existing code; the separation of char from integer
1493 came fairly recently.)
1494 @item symbol
1495 An object that contains Lisp objects and is referred to by name;
1496 symbols are used to implement variables and named functions
1497 and to provide the equivalent of preprocessor constants in C.
1498 @item vector
1499 A one-dimensional array of Lisp objects providing constant-time access
1500 to any of the objects; access to an arbitrary object in a vector is
1501 faster than for lists, but the operations that can be done on a vector
1502 are more limited.
1503 @item string
1504 Self-explanatory; behaves much like a vector of chars
1505 but has a different read syntax and is stored and manipulated
1506 more compactly.
1507 @item bit-vector
1508 A vector of bits; similar to a string in spirit.
1509 @item compiled-function
1510 An object containing compiled Lisp code, known as @dfn{byte code}.
1511 @item subr
1512 A Lisp primitive, i.e. a Lisp-callable function implemented in C.
1513 @end table
1514
1515 @cindex closure
1516 Note that there is no basic ``function'' type, as in more powerful
1517 versions of Lisp (where it's called a @dfn{closure}).  XEmacs Lisp does
1518 not provide the closure semantics implemented by Common Lisp and Scheme.
1519 The guts of a function in XEmacs Lisp are represented in one of four
1520 ways: a symbol specifying another function (when one function is an
1521 alias for another), a list (whose first element must be the symbol
1522 @code{lambda}) containing the function's source code, a
1523 compiled-function object, or a subr object. (In other words, given a
1524 symbol specifying the name of a function, calling @code{symbol-function}
1525 to retrieve the contents of the symbol's function cell will return one
1526 of these types of objects.)
1527
1528 XEmacs Lisp also contains numerous specialized objects used to implement
1529 the editor:
1530
1531 @table @code
1532 @item buffer
1533 Stores text like a string, but is optimized for insertion and deletion
1534 and has certain other properties that can be set.
1535 @item frame
1536 An object with various properties whose displayable representation is a
1537 @dfn{window} in window-system parlance.
1538 @item window
1539 A section of a frame that displays the contents of a buffer;
1540 often called a @dfn{pane} in window-system parlance.
1541 @item window-configuration
1542 An object that represents a saved configuration of windows in a frame.
1543 @item device
1544 An object representing a screen on which frames can be displayed;
1545 equivalent to a @dfn{display} in the X Window System and a @dfn{TTY} in
1546 character mode.
1547 @item face
1548 An object specifying the appearance of text or graphics; it has
1549 properties such as font, foreground color, and background color.
1550 @item marker
1551 An object that refers to a particular position in a buffer and moves
1552 around as text is inserted and deleted to stay in the same relative
1553 position to the text around it.
1554 @item extent
1555 Similar to a marker but covers a range of text in a buffer; can also
1556 specify properties of the text, such as a face in which the text is to
1557 be displayed, whether the text is invisible or unmodifiable, etc.
1558 @item event
1559 Generated by calling @code{next-event} and contains information
1560 describing a particular event happening in the system, such as the user
1561 pressing a key or a process terminating.
1562 @item keymap
1563 An object that maps from events (described using lists, vectors, and
1564 symbols rather than with an event object because the mapping is for
1565 classes of events, rather than individual events) to functions to
1566 execute or other events to recursively look up; the functions are
1567 described by name, using a symbol, or using lists to specify the
1568 function's code.
1569 @item glyph
1570 An object that describes the appearance of an image (e.g.  pixmap) on
1571 the screen; glyphs can be attached to the beginning or end of extents
1572 and in some future version of XEmacs will be able to be inserted
1573 directly into a buffer.
1574 @item process
1575 An object that describes a connection to an externally-running process.
1576 @end table
1577
1578   There are some other, less-commonly-encountered general objects:
1579
1580 @table @code
1581 @item hash-table
1582 An object that maps from an arbitrary Lisp object to another arbitrary
1583 Lisp object, using hashing for fast lookup.
1584 @item obarray
1585 A limited form of hash-table that maps from strings to symbols; obarrays
1586 are used to look up a symbol given its name and are not actually their
1587 own object type but are kludgily represented using vectors with hidden
1588 fields (this representation derives from GNU Emacs).
1589 @item specifier
1590 A complex object used to specify the value of a display property; a
1591 default value is given and different values can be specified for
1592 particular frames, buffers, windows, devices, or classes of device.
1593 @item char-table
1594 An object that maps from chars or classes of chars to arbitrary Lisp
1595 objects; internally char tables use a complex nested-vector
1596 representation that is optimized to the way characters are represented
1597 as integers.
1598 @item range-table
1599 An object that maps from ranges of integers to arbitrary Lisp objects.
1600 @end table
1601
1602   And some strange special-purpose objects:
1603
1604 @table @code
1605 @item charset
1606 @itemx coding-system
1607 Objects used when MULE, or multi-lingual/Asian-language, support is
1608 enabled.
1609 @item color-instance
1610 @itemx font-instance
1611 @itemx image-instance
1612 An object that encapsulates a window-system resource; instances are
1613 mostly used internally but are exposed on the Lisp level for cleanness
1614 of the specifier model and because it's occasionally useful for Lisp
1615 program to create or query the properties of instances.
1616 @item subwindow
1617 An object that encapsulate a @dfn{subwindow} resource, i.e. a
1618 window-system child window that is drawn into by an external process;
1619 this object should be integrated into the glyph system but isn't yet,
1620 and may change form when this is done.
1621 @item tooltalk-message
1622 @itemx tooltalk-pattern
1623 Objects that represent resources used in the ToolTalk interprocess
1624 communication protocol.
1625 @item toolbar-button
1626 An object used in conjunction with the toolbar.
1627 @end table
1628
1629   And objects that are only used internally:
1630
1631 @table @code
1632 @item opaque
1633 A generic object for encapsulating arbitrary memory; this allows you the
1634 generality of @code{malloc()} and the convenience of the Lisp object
1635 system.
1636 @item lstream
1637 A buffering I/O stream, used to provide a unified interface to anything
1638 that can accept output or provide input, such as a file descriptor, a
1639 stdio stream, a chunk of memory, a Lisp buffer, a Lisp string, etc.;
1640 it's a Lisp object to make its memory management more convenient.
1641 @item char-table-entry
1642 Subsidiary objects in the internal char-table representation.
1643 @item extent-auxiliary
1644 @itemx menubar-data
1645 @itemx toolbar-data
1646 Various special-purpose objects that are basically just used to
1647 encapsulate memory for particular subsystems, similar to the more
1648 general ``opaque'' object.
1649 @item symbol-value-forward
1650 @itemx symbol-value-buffer-local
1651 @itemx symbol-value-varalias
1652 @itemx symbol-value-lisp-magic
1653 Special internal-only objects that are placed in the value cell of a
1654 symbol to indicate that there is something special with this variable --
1655 e.g. it has no value, it mirrors another variable, or it mirrors some C
1656 variable; there is really only one kind of object, called a
1657 @dfn{symbol-value-magic}, but it is sort-of halfway kludged into
1658 semi-different object types.
1659 @end table
1660
1661 @cindex permanent objects
1662 @cindex temporary objects
1663   Some types of objects are @dfn{permanent}, meaning that once created,
1664 they do not disappear until explicitly destroyed, using a function such
1665 as @code{delete-buffer}, @code{delete-window}, @code{delete-frame}, etc.
1666 Others will disappear once they are not longer used, through the garbage
1667 collection mechanism.  Buffers, frames, windows, devices, and processes
1668 are among the objects that are permanent.  Note that some objects can go
1669 both ways: Faces can be created either way; extents are normally
1670 permanent, but detached extents (extents not referring to any text, as
1671 happens to some extents when the text they are referring to is deleted)
1672 are temporary.  Note that some permanent objects, such as faces and
1673 coding systems, cannot be deleted.  Note also that windows are unique in
1674 that they can be @emph{undeleted} after having previously been
1675 deleted. (This happens as a result of restoring a window configuration.)
1676
1677 @cindex read syntax
1678   Note that many types of objects have a @dfn{read syntax}, i.e. a way of
1679 specifying an object of that type in Lisp code.  When you load a Lisp
1680 file, or type in code to be evaluated, what really happens is that the
1681 function @code{read} is called, which reads some text and creates an object
1682 based on the syntax of that text; then @code{eval} is called, which
1683 possibly does something special; then this loop repeats until there's
1684 no more text to read. (@code{eval} only actually does something special
1685 with symbols, which causes the symbol's value to be returned,
1686 similar to referencing a variable; and with conses [i.e. lists],
1687 which cause a function invocation.  All other values are returned
1688 unchanged.)
1689
1690   The read syntax
1691
1692 @example
1693 17297
1694 @end example
1695
1696 converts to an integer whose value is 17297.
1697
1698 @example
1699 1.983e-4
1700 @end example
1701
1702 converts to a float whose value is 1.983e-4, or .0001983.
1703
1704 @example
1705 ?b
1706 @end example
1707
1708 converts to a char that represents the lowercase letter b.
1709
1710 @example
1711 ?^[$(B#&^[(B
1712 @end example
1713
1714 (where @samp{^[} actually is an @samp{ESC} character) converts to a
1715 particular Kanji character when using an ISO2022-based coding system for
1716 input. (To decode this goo: @samp{ESC} begins an escape sequence;
1717 @samp{ESC $ (} is a class of escape sequences meaning ``switch to a
1718 94x94 character set''; @samp{ESC $ ( B} means ``switch to Japanese
1719 Kanji''; @samp{#} and @samp{&} collectively index into a 94-by-94 array
1720 of characters [subtract 33 from the ASCII value of each character to get
1721 the corresponding index]; @samp{ESC (} is a class of escape sequences
1722 meaning ``switch to a 94 character set''; @samp{ESC (B} means ``switch
1723 to US ASCII''.  It is a coincidence that the letter @samp{B} is used to
1724 denote both Japanese Kanji and US ASCII.  If the first @samp{B} were
1725 replaced with an @samp{A}, you'd be requesting a Chinese Hanzi character
1726 from the GB2312 character set.)
1727
1728 @example
1729 "foobar"
1730 @end example
1731
1732 converts to a string.
1733
1734 @example
1735 foobar
1736 @end example
1737
1738 converts to a symbol whose name is @code{"foobar"}.  This is done by
1739 looking up the string equivalent in the global variable
1740 @code{obarray}, whose contents should be an obarray.  If no symbol
1741 is found, a new symbol with the name @code{"foobar"} is automatically
1742 created and added to @code{obarray}; this process is called
1743 @dfn{interning} the symbol.
1744 @cindex interning
1745
1746 @example
1747 (foo . bar)
1748 @end example
1749
1750 converts to a cons cell containing the symbols @code{foo} and @code{bar}.
1751
1752 @example
1753 (1 a 2.5)
1754 @end example
1755
1756 converts to a three-element list containing the specified objects
1757 (note that a list is actually a set of nested conses; see the
1758 XEmacs Lisp Reference).
1759
1760 @example
1761 [1 a 2.5]
1762 @end example
1763
1764 converts to a three-element vector containing the specified objects.
1765
1766 @example
1767 #[... ... ... ...]
1768 @end example
1769
1770 converts to a compiled-function object (the actual contents are not
1771 shown since they are not relevant here; look at a file that ends with
1772 @file{.elc} for examples).
1773
1774 @example
1775 #*01110110
1776 @end example
1777
1778 converts to a bit-vector.
1779
1780 @example
1781 #s(hash-table ... ...)
1782 @end example
1783
1784 converts to a hash table (the actual contents are not shown).
1785
1786 @example
1787 #s(range-table ... ...)
1788 @end example
1789
1790 converts to a range table (the actual contents are not shown).
1791
1792 @example
1793 #s(char-table ... ...)
1794 @end example
1795
1796 converts to a char table (the actual contents are not shown).
1797
1798 Note that the @code{#s()} syntax is the general syntax for structures,
1799 which are not really implemented in XEmacs Lisp but should be.
1800
1801 When an object is printed out (using @code{print} or a related
1802 function), the read syntax is used, so that the same object can be read
1803 in again.
1804
1805 The other objects do not have read syntaxes, usually because it does not
1806 really make sense to create them in this fashion (i.e.  processes, where
1807 it doesn't make sense to have a subprocess created as a side effect of
1808 reading some Lisp code), or because they can't be created at all
1809 (e.g. subrs).  Permanent objects, as a rule, do not have a read syntax;
1810 nor do most complex objects, which contain too much state to be easily
1811 initialized through a read syntax.
1812
1813 @node How Lisp Objects Are Represented in C, Rules When Writing New C Code, The XEmacs Object System (Abstractly Speaking), Top
1814 @chapter How Lisp Objects Are Represented in C
1815 @cindex Lisp objects are represented in C, how
1816 @cindex objects are represented in C, how Lisp
1817 @cindex represented in C, how Lisp objects are
1818
1819 Lisp objects are represented in C using a 32-bit or 64-bit machine word
1820 (depending on the processor; i.e. DEC Alphas use 64-bit Lisp objects and
1821 most other processors use 32-bit Lisp objects).  The representation
1822 stuffs a pointer together with a tag, as follows:
1823
1824 @example
1825  [ 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 ]
1826  [ 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 ]
1827
1828    <---------------------------------------------------------> <->
1829             a pointer to a structure, or an integer            tag
1830 @end example
1831
1832 A tag of 00 is used for all pointer object types, a tag of 10 is used
1833 for characters, and the other two tags 01 and 11 are joined together to
1834 form the integer object type.  This representation gives us 31 bit
1835 integers and 30 bit characters, while pointers are represented directly
1836 without any bit masking or shifting.  This representation, though,
1837 assumes that pointers to structs are always aligned to multiples of 4,
1838 so the lower 2 bits are always zero.
1839
1840 Lisp objects use the typedef @code{Lisp_Object}, but the actual C type
1841 used for the Lisp object can vary.  It can be either a simple type
1842 (@code{long} on the DEC Alpha, @code{int} on other machines) or a
1843 structure whose fields are bit fields that line up properly (actually, a
1844 union of structures is used).  Generally the simple integral type is
1845 preferable because it ensures that the compiler will actually use a
1846 machine word to represent the object (some compilers will use more
1847 general and less efficient code for unions and structs even if they can
1848 fit in a machine word).  The union type, however, has the advantage of
1849 stricter type checking.  If you accidentally pass an integer where a Lisp
1850 object is desired, you get a compile error.  The choice of which type
1851 to use is determined by the preprocessor constant @code{USE_UNION_TYPE}
1852 which is defined via the @code{--use-union-type} option to
1853 @code{configure}.
1854
1855 Various macros are used to convert between Lisp_Objects and the
1856 corresponding C type.  Macros of the form @code{XINT()}, @code{XCHAR()},
1857 @code{XSTRING()}, @code{XSYMBOL()}, do any required bit shifting and/or
1858 masking and cast it to the appropriate type.  @code{XINT()} needs to be
1859 a bit tricky so that negative numbers are properly sign-extended.  Since
1860 integers are stored left-shifted, if the right-shift operator does an
1861 arithmetic shift (i.e. it leaves the most-significant bit as-is rather
1862 than shifting in a zero, so that it mimics a divide-by-two even for
1863 negative numbers) the shift to remove the tag bit is enough.  This is
1864 the case on all the systems we support.
1865
1866 Note that when @code{ERROR_CHECK_TYPECHECK} is defined, the converter
1867 macros become more complicated---they check the tag bits and/or the
1868 type field in the first four bytes of a record type to ensure that the
1869 object is really of the correct type.  This is great for catching places
1870 where an incorrect type is being dereferenced---this typically results
1871 in a pointer being dereferenced as the wrong type of structure, with
1872 unpredictable (and sometimes not easily traceable) results.
1873
1874 There are similar @code{XSET@var{TYPE}()} macros that construct a Lisp
1875 object.  These macros are of the form @code{XSET@var{TYPE}
1876 (@var{lvalue}, @var{result})}, i.e. they have to be a statement rather
1877 than just used in an expression.  The reason for this is that standard C
1878 doesn't let you ``construct'' a structure (but GCC does).  Granted, this
1879 sometimes isn't too convenient; for the case of integers, at least, you
1880 can use the function @code{make_int()}, which constructs and
1881 @emph{returns} an integer Lisp object.  Note that the
1882 @code{XSET@var{TYPE}()} macros are also affected by
1883 @code{ERROR_CHECK_TYPECHECK} and make sure that the structure is of the
1884 right type in the case of record types, where the type is contained in
1885 the structure.
1886
1887 The C programmer is responsible for @strong{guaranteeing} that a
1888 Lisp_Object is the correct type before using the @code{X@var{TYPE}}
1889 macros.  This is especially important in the case of lists.  Use
1890 @code{XCAR} and @code{XCDR} if a Lisp_Object is certainly a cons cell,
1891 else use @code{Fcar()} and @code{Fcdr()}.  Trust other C code, but not
1892 Lisp code.  On the other hand, if XEmacs has an internal logic error,
1893 it's better to crash immediately, so sprinkle @code{assert()}s and
1894 ``unreachable'' @code{abort()}s liberally about the source code.  Where
1895 performance is an issue, use @code{type_checking_assert},
1896 @code{bufpos_checking_assert}, and @code{gc_checking_assert}, which do
1897 nothing unless the corresponding configure error checking flag was
1898 specified.
1899
1900 @node Rules When Writing New C Code, Regression Testing XEmacs, How Lisp Objects Are Represented in C, Top
1901 @chapter Rules When Writing New C Code
1902 @cindex writing new C code, rules when
1903 @cindex C code, rules when writing new
1904 @cindex code, rules when writing new C
1905
1906 The XEmacs C Code is extremely complex and intricate, and there are many
1907 rules that are more or less consistently followed throughout the code.
1908 Many of these rules are not obvious, so they are explained here.  It is
1909 of the utmost importance that you follow them.  If you don't, you may
1910 get something that appears to work, but which will crash in odd
1911 situations, often in code far away from where the actual breakage is.
1912
1913 @menu
1914 * General Coding Rules::
1915 * Writing Lisp Primitives::
1916 * Writing Good Comments::
1917 * Adding Global Lisp Variables::
1918 * Proper Use of Unsigned Types::
1919 * Coding for Mule::
1920 * Techniques for XEmacs Developers::
1921 @end menu
1922
1923 @node General Coding Rules
1924 @section General Coding Rules
1925 @cindex coding rules, general
1926
1927 The C code is actually written in a dialect of C called @dfn{Clean C},
1928 meaning that it can be compiled, mostly warning-free, with either a C or
1929 C++ compiler.  Coding in Clean C has several advantages over plain C.
1930 C++ compilers are more nit-picking, and a number of coding errors have
1931 been found by compiling with C++.  The ability to use both C and C++
1932 tools means that a greater variety of development tools are available to
1933 the developer.
1934
1935 Every module includes @file{<config.h>} (angle brackets so that
1936 @samp{--srcdir} works correctly; @file{config.h} may or may not be in
1937 the same directory as the C sources) and @file{lisp.h}.  @file{config.h}
1938 must always be included before any other header files (including
1939 system header files) to ensure that certain tricks played by various
1940 @file{s/} and @file{m/} files work out correctly.
1941
1942 When including header files, always use angle brackets, not double
1943 quotes, except when the file to be included is always in the same
1944 directory as the including file.  If either file is a generated file,
1945 then that is not likely to be the case.  In order to understand why we
1946 have this rule, imagine what happens when you do a build in the source
1947 directory using @samp{./configure} and another build in another
1948 directory using @samp{../work/configure}.  There will be two different
1949 @file{config.h} files.  Which one will be used if you @samp{#include
1950 "config.h"}?
1951
1952 Almost every module contains a @code{syms_of_*()} function and a
1953 @code{vars_of_*()} function.  The former declares any Lisp primitives
1954 you have defined and defines any symbols you will be using.  The latter
1955 declares any global Lisp variables you have added and initializes global
1956 C variables in the module.  @strong{Important}: There are stringent
1957 requirements on exactly what can go into these functions.  See the
1958 comment in @file{emacs.c}.  The reason for this is to avoid obscure
1959 unwanted interactions during initialization.  If you don't follow these
1960 rules, you'll be sorry!  If you want to do anything that isn't allowed,
1961 create a @code{complex_vars_of_*()} function for it.  Doing this is
1962 tricky, though: you have to make sure your function is called at the
1963 right time so that all the initialization dependencies work out.
1964
1965 Declare each function of these kinds in @file{symsinit.h}.  Make sure
1966 it's called in the appropriate place in @file{emacs.c}.  You never need
1967 to include @file{symsinit.h} directly, because it is included by
1968 @file{lisp.h}.
1969
1970 @strong{All global and static variables that are to be modifiable must
1971 be declared uninitialized.}  This means that you may not use the
1972 ``declare with initializer'' form for these variables, such as @code{int
1973 some_variable = 0;}.  The reason for this has to do with some kludges
1974 done during the dumping process: If possible, the initialized data
1975 segment is re-mapped so that it becomes part of the (unmodifiable) code
1976 segment in the dumped executable.  This allows this memory to be shared
1977 among multiple running XEmacs processes.  XEmacs is careful to place as
1978 much constant data as possible into initialized variables during the
1979 @file{temacs} phase.
1980
1981 @cindex copy-on-write
1982 @strong{Please note:} This kludge only works on a few systems nowadays,
1983 and is rapidly becoming irrelevant because most modern operating systems
1984 provide @dfn{copy-on-write} semantics.  All data is initially shared
1985 between processes, and a private copy is automatically made (on a
1986 page-by-page basis) when a process first attempts to write to a page of
1987 memory.
1988
1989 Formerly, there was a requirement that static variables not be declared
1990 inside of functions.  This had to do with another hack along the same
1991 vein as what was just described: old USG systems put statically-declared
1992 variables in the initialized data space, so those header files had a
1993 @code{#define static} declaration. (That way, the data-segment remapping
1994 described above could still work.) This fails badly on static variables
1995 inside of functions, which suddenly become automatic variables;
1996 therefore, you weren't supposed to have any of them.  This awful kludge
1997 has been removed in XEmacs because
1998
1999 @enumerate
2000 @item
2001 almost all of the systems that used this kludge ended up having
2002 to disable the data-segment remapping anyway;
2003 @item
2004 the only systems that didn't were extremely outdated ones;
2005 @item
2006 this hack completely messed up inline functions.
2007 @end enumerate
2008
2009 The C source code makes heavy use of C preprocessor macros.  One popular
2010 macro style is:
2011
2012 @example
2013 #define FOO(var, value) do @{            \
2014   Lisp_Object FOO_value = (value);      \
2015   ... /* compute using FOO_value */     \
2016   (var) = bar;                          \
2017 @} while (0)
2018 @end example
2019
2020 The @code{do @{...@} while (0)} is a standard trick to allow FOO to have
2021 statement semantics, so that it can safely be used within an @code{if}
2022 statement in C, for example.  Multiple evaluation is prevented by
2023 copying a supplied argument into a local variable, so that
2024 @code{FOO(var,fun(1))} only calls @code{fun} once.
2025
2026 Lisp lists are popular data structures in the C code as well as in
2027 Elisp.  There are two sets of macros that iterate over lists.
2028 @code{EXTERNAL_LIST_LOOP_@var{n}} should be used when the list has been
2029 supplied by the user, and cannot be trusted to be acyclic and
2030 @code{nil}-terminated.  A @code{malformed-list} or @code{circular-list} error
2031 will be generated if the list being iterated over is not entirely
2032 kosher.  @code{LIST_LOOP_@var{n}}, on the other hand, is faster and less
2033 safe, and can be used only on trusted lists.
2034
2035 Related macros are @code{GET_EXTERNAL_LIST_LENGTH} and
2036 @code{GET_LIST_LENGTH}, which calculate the length of a list, and in the
2037 case of @code{GET_EXTERNAL_LIST_LENGTH}, validating the properness of
2038 the list.  The macros @code{EXTERNAL_LIST_LOOP_DELETE_IF} and
2039 @code{LIST_LOOP_DELETE_IF} delete elements from a lisp list satisfying some
2040 predicate.
2041
2042 @node Writing Lisp Primitives
2043 @section Writing Lisp Primitives
2044 @cindex writing Lisp primitives
2045 @cindex Lisp primitives, writing
2046 @cindex primitives, writing Lisp
2047
2048 Lisp primitives are Lisp functions implemented in C.  The details of
2049 interfacing the C function so that Lisp can call it are handled by a few
2050 C macros.  The only way to really understand how to write new C code is
2051 to read the source, but we can explain some things here.
2052
2053 An example of a special form is the definition of @code{prog1}, from
2054 @file{eval.c}.  (An ordinary function would have the same general
2055 appearance.)
2056
2057 @cindex garbage collection protection
2058 @smallexample
2059 @group
2060 DEFUN ("prog1", Fprog1, 1, UNEVALLED, 0, /*
2061 Similar to `progn', but the value of the first form is returned.
2062 \(prog1 FIRST BODY...): All the arguments are evaluated sequentially.
2063 The value of FIRST is saved during evaluation of the remaining args,
2064 whose values are discarded.
2065 */
2066        (args))
2067 @{
2068   /* This function can GC */
2069   REGISTER Lisp_Object val, form, tail;
2070   struct gcpro gcpro1;
2071
2072   val = Feval (XCAR (args));
2073
2074   GCPRO1 (val);
2075
2076   LIST_LOOP_3 (form, XCDR (args), tail)
2077     Feval (form);
2078
2079   UNGCPRO;
2080   return val;
2081 @}
2082 @end group
2083 @end smallexample
2084
2085   Let's start with a precise explanation of the arguments to the
2086 @code{DEFUN} macro.  Here is a template for them:
2087
2088 @example
2089 @group
2090 DEFUN (@var{lname}, @var{fname}, @var{min_args}, @var{max_args}, @var{interactive}, /*
2091 @var{docstring}
2092 */
2093    (@var{arglist}))
2094 @end group
2095 @end example
2096
2097 @table @var
2098 @item lname
2099 This string is the name of the Lisp symbol to define as the function
2100 name; in the example above, it is @code{"prog1"}.
2101
2102 @item fname
2103 This is the C function name for this function.  This is the name that is
2104 used in C code for calling the function.  The name is, by convention,
2105 @samp{F} prepended to the Lisp name, with all dashes (@samp{-}) in the
2106 Lisp name changed to underscores.  Thus, to call this function from C
2107 code, call @code{Fprog1}.  Remember that the arguments are of type
2108 @code{Lisp_Object}; various macros and functions for creating values of
2109 type @code{Lisp_Object} are declared in the file @file{lisp.h}.
2110
2111 Primitives whose names are special characters (e.g. @code{+} or
2112 @code{<}) are named by spelling out, in some fashion, the special
2113 character: e.g. @code{Fplus()} or @code{Flss()}.  Primitives whose names
2114 begin with normal alphanumeric characters but also contain special
2115 characters are spelled out in some creative way, e.g. @code{let*}
2116 becomes @code{FletX()}.
2117
2118 Each function also has an associated structure that holds the data for
2119 the subr object that represents the function in Lisp.  This structure
2120 conveys the Lisp symbol name to the initialization routine that will
2121 create the symbol and store the subr object as its definition.  The C
2122 variable name of this structure is always @samp{S} prepended to the
2123 @var{fname}.  You hardly ever need to be aware of the existence of this
2124 structure, since @code{DEFUN} plus @code{DEFSUBR} takes care of all the
2125 details.
2126
2127 @item min_args
2128 This is the minimum number of arguments that the function requires.  The
2129 function @code{prog1} allows a minimum of one argument.
2130
2131 @item max_args
2132 This is the maximum number of arguments that the function accepts, if
2133 there is a fixed maximum.  Alternatively, it can be @code{UNEVALLED},
2134 indicating a special form that receives unevaluated arguments, or
2135 @code{MANY}, indicating an unlimited number of evaluated arguments (the
2136 C equivalent of @code{&rest}).  Both @code{UNEVALLED} and @code{MANY}
2137 are macros.  If @var{max_args} is a number, it may not be less than
2138 @var{min_args} and it may not be greater than 8. (If you need to add a
2139 function with more than 8 arguments, use the @code{MANY} form.  Resist
2140 the urge to edit the definition of @code{DEFUN} in @file{lisp.h}.  If
2141 you do it anyways, make sure to also add another clause to the switch
2142 statement in @code{primitive_funcall().})
2143
2144 @item interactive
2145 This is an interactive specification, a string such as might be used as
2146 the argument of @code{interactive} in a Lisp function.  In the case of
2147 @code{prog1}, it is 0 (a null pointer), indicating that @code{prog1}
2148 cannot be called interactively.  A value of @code{""} indicates a
2149 function that should receive no arguments when called interactively.
2150
2151 @item docstring
2152 This is the documentation string.  It is written just like a
2153 documentation string for a function defined in Lisp; in particular, the
2154 first line should be a single sentence.  Note how the documentation
2155 string is enclosed in a comment, none of the documentation is placed on
2156 the same lines as the comment-start and comment-end characters, and the
2157 comment-start characters are on the same line as the interactive
2158 specification.  @file{make-docfile}, which scans the C files for
2159 documentation strings, is very particular about what it looks for, and
2160 will not properly extract the doc string if it's not in this exact format.
2161
2162 In order to make both @file{etags} and @file{make-docfile} happy, make
2163 sure that the @code{DEFUN} line contains the @var{lname} and
2164 @var{fname}, and that the comment-start characters for the doc string
2165 are on the same line as the interactive specification, and put a newline
2166 directly after them (and before the comment-end characters).
2167
2168 @item arglist
2169 This is the comma-separated list of arguments to the C function.  For a
2170 function with a fixed maximum number of arguments, provide a C argument
2171 for each Lisp argument.  In this case, unlike regular C functions, the
2172 types of the arguments are not declared; they are simply always of type
2173 @code{Lisp_Object}.
2174
2175 The names of the C arguments will be used as the names of the arguments
2176 to the Lisp primitive as displayed in its documentation, modulo the same
2177 concerns described above for @code{F...} names (in particular,
2178 underscores in the C arguments become dashes in the Lisp arguments).
2179
2180 There is one additional kludge: A trailing `_' on the C argument is
2181 discarded when forming the Lisp argument.  This allows C language
2182 reserved words (like @code{default}) or global symbols (like
2183 @code{dirname}) to be used as argument names without compiler warnings
2184 or errors.
2185
2186 A Lisp function with @w{@var{max_args} = @code{UNEVALLED}} is a
2187 @w{@dfn{special form}}; its arguments are not evaluated.  Instead it
2188 receives one argument of type @code{Lisp_Object}, a (Lisp) list of the
2189 unevaluated arguments, conventionally named @code{(args)}.
2190
2191 When a Lisp function has no upper limit on the number of arguments,
2192 specify @w{@var{max_args} = @code{MANY}}.  In this case its implementation in
2193 C actually receives exactly two arguments: the number of Lisp arguments
2194 (an @code{int}) and the address of a block containing their values (a
2195 @w{@code{Lisp_Object *}}).  In this case only are the C types specified
2196 in the @var{arglist}: @w{@code{(int nargs, Lisp_Object *args)}}.
2197
2198 @end table
2199
2200 Within the function @code{Fprog1} itself, note the use of the macros
2201 @code{GCPRO1} and @code{UNGCPRO}.  @code{GCPRO1} is used to ``protect''
2202 a variable from garbage collection---to inform the garbage collector
2203 that it must look in that variable and regard the object pointed at by
2204 its contents as an accessible object.  This is necessary whenever you
2205 call @code{Feval} or anything that can directly or indirectly call
2206 @code{Feval} (this includes the @code{QUIT} macro!).  At such a time,
2207 any Lisp object that you intend to refer to again must be protected
2208 somehow.  @code{UNGCPRO} cancels the protection of the variables that
2209 are protected in the current function.  It is necessary to do this
2210 explicitly.
2211
2212 The macro @code{GCPRO1} protects just one local variable.  If you want
2213 to protect two, use @code{GCPRO2} instead; repeating @code{GCPRO1} will
2214 not work.  Macros @code{GCPRO3} and @code{GCPRO4} also exist.
2215
2216 These macros implicitly use local variables such as @code{gcpro1}; you
2217 must declare these explicitly, with type @code{struct gcpro}.  Thus, if
2218 you use @code{GCPRO2}, you must declare @code{gcpro1} and @code{gcpro2}.
2219
2220 @cindex caller-protects (@code{GCPRO} rule)
2221 Note also that the general rule is @dfn{caller-protects}; i.e. you are
2222 only responsible for protecting those Lisp objects that you create.  Any
2223 objects passed to you as arguments should have been protected by whoever
2224 created them, so you don't in general have to protect them.
2225
2226 In particular, the arguments to any Lisp primitive are always
2227 automatically @code{GCPRO}ed, when called ``normally'' from Lisp code or
2228 bytecode.  So only a few Lisp primitives that are called frequently from
2229 C code, such as @code{Fprogn} protect their arguments as a service to
2230 their caller.  You don't need to protect your arguments when writing a
2231 new @code{DEFUN}.
2232
2233 @code{GCPRO}ing is perhaps the trickiest and most error-prone part of
2234 XEmacs coding.  It is @strong{extremely} important that you get this
2235 right and use a great deal of discipline when writing this code.
2236 @xref{GCPROing, ,@code{GCPRO}ing}, for full details on how to do this.
2237
2238 What @code{DEFUN} actually does is declare a global structure of type
2239 @code{Lisp_Subr} whose name begins with capital @samp{SF} and which
2240 contains information about the primitive (e.g. a pointer to the
2241 function, its minimum and maximum allowed arguments, a string describing
2242 its Lisp name); @code{DEFUN} then begins a normal C function declaration
2243 using the @code{F...} name.  The Lisp subr object that is the function
2244 definition of a primitive (i.e. the object in the function slot of the
2245 symbol that names the primitive) actually points to this @samp{SF}
2246 structure; when @code{Feval} encounters a subr, it looks in the
2247 structure to find out how to call the C function.
2248
2249 Defining the C function is not enough to make a Lisp primitive
2250 available; you must also create the Lisp symbol for the primitive (the
2251 symbol is @dfn{interned}; @pxref{Obarrays}) and store a suitable subr
2252 object in its function cell. (If you don't do this, the primitive won't
2253 be seen by Lisp code.) The code looks like this:
2254
2255 @example
2256 DEFSUBR (@var{fname});
2257 @end example
2258
2259 @noindent
2260 Here @var{fname} is the same name you used as the second argument to
2261 @code{DEFUN}.
2262
2263 This call to @code{DEFSUBR} should go in the @code{syms_of_*()} function
2264 at the end of the module.  If no such function exists, create it and
2265 make sure to also declare it in @file{symsinit.h} and call it from the
2266 appropriate spot in @code{main()}.  @xref{General Coding Rules}.
2267
2268 Note that C code cannot call functions by name unless they are defined
2269 in C.  The way to call a function written in Lisp from C is to use
2270 @code{Ffuncall}, which embodies the Lisp function @code{funcall}.  Since
2271 the Lisp function @code{funcall} accepts an unlimited number of
2272 arguments, in C it takes two: the number of Lisp-level arguments, and a
2273 one-dimensional array containing their values.  The first Lisp-level
2274 argument is the Lisp function to call, and the rest are the arguments to
2275 pass to it.  Since @code{Ffuncall} can call the evaluator, you must
2276 protect pointers from garbage collection around the call to
2277 @code{Ffuncall}. (However, @code{Ffuncall} explicitly protects all of
2278 its parameters, so you don't have to protect any pointers passed as
2279 parameters to it.)
2280
2281 The C functions @code{call0}, @code{call1}, @code{call2}, and so on,
2282 provide handy ways to call a Lisp function conveniently with a fixed
2283 number of arguments.  They work by calling @code{Ffuncall}.
2284
2285 @file{eval.c} is a very good file to look through for examples;
2286 @file{lisp.h} contains the definitions for important macros and
2287 functions.
2288
2289 @node Writing Good Comments
2290 @section Writing Good Comments
2291 @cindex writing good comments
2292 @cindex comments, writing good
2293
2294 Comments are a lifeline for programmers trying to understand tricky
2295 code.  In general, the less obvious it is what you are doing, the more
2296 you need a comment, and the more detailed it needs to be.  You should
2297 always be on guard when you're writing code for stuff that's tricky, and
2298 should constantly be putting yourself in someone else's shoes and asking
2299 if that person could figure out without much difficulty what's going
2300 on. (Assume they are a competent programmer who understands the
2301 essentials of how the XEmacs code is structured but doesn't know much
2302 about the module you're working on or any algorithms you're using.) If
2303 you're not sure whether they would be able to, add a comment.  Always
2304 err on the side of more comments, rather than less.
2305
2306 Generally, when making comments, there is no need to attribute them with
2307 your name or initials.  This especially goes for small,
2308 easy-to-understand, non-opinionated ones.  Also, comments indicating
2309 where, when, and by whom a file was changed are @emph{strongly}
2310 discouraged, and in general will be removed as they are discovered.
2311 This is exactly what @file{ChangeLogs} are there for.  However, it can
2312 occasionally be useful to mark exactly where (but not when or by whom)
2313 changes are made, particularly when making small changes to a file
2314 imported from elsewhere.  These marks help when later on a newer version
2315 of the file is imported and the changes need to be merged. (If
2316 everything were always kept in CVS, there would be no need for this.
2317 But in practice, this often doesn't happen, or the CVS repository is
2318 later on lost or unavailable to the person doing the update.)
2319
2320 When putting in an explicit opinion in a comment, you should
2321 @emph{always} attribute it with your name, and optionally the date.
2322 This also goes for long, complex comments explaining in detail the
2323 workings of something -- by putting your name there, you make it
2324 possible for someone who has questions about how that thing works to
2325 determine who wrote the comment so they can write to them.  Preferably,
2326 use your actual name and not your initials, unless your initials are
2327 generally recognized (e.g. @samp{jwz}).  You can use only your first
2328 name if it's obvious who you are; otherwise, give first and last name.
2329 If you're not a regular contributor, you might consider putting your
2330 email address in -- it may be in the ChangeLog, but after awhile
2331 ChangeLogs have a tendency of disappearing or getting
2332 muddled. (E.g. your comment may get copied somewhere else or even into
2333 another program, and tracking down the proper ChangeLog may be very
2334 difficult.)
2335
2336 If you come across an opinion that is not or no longer valid, or you
2337 come across any comment that no longer applies but you want to keep it
2338 around, enclose it in @samp{[[ } and @samp{ ]]} marks and add a comment
2339 afterwards explaining why the preceding comment is no longer valid.  Put
2340 your name on this comment, as explained above.
2341
2342 Just as comments are a lifeline to programmers, incorrect comments are
2343 death.  If you come across an incorrect comment, @strong{immediately}
2344 correct it or flag it as incorrect, as described in the previous
2345 paragraph.  Whenever you work on a section of code, @emph{always} make
2346 sure to update any comments to be correct -- or, at the very least, flag
2347 them as incorrect.
2348
2349 To indicate a "todo" or other problem, use four pound signs --
2350 i.e. @samp{####}.
2351
2352 @node Adding Global Lisp Variables
2353 @section Adding Global Lisp Variables
2354 @cindex global Lisp variables, adding
2355 @cindex variables, adding global Lisp
2356
2357 Global variables whose names begin with @samp{Q} are constants whose
2358 value is a symbol of a particular name.  The name of the variable should
2359 be derived from the name of the symbol using the same rules as for Lisp
2360 primitives.  These variables are initialized using a call to
2361 @code{defsymbol()} in the @code{syms_of_*()} function. (This call
2362 interns a symbol, sets the C variable to the resulting Lisp object, and
2363 calls @code{staticpro()} on the C variable to tell the
2364 garbage-collection mechanism about this variable.  What
2365 @code{staticpro()} does is add a pointer to the variable to a large
2366 global array; when garbage-collection happens, all pointers listed in
2367 the array are used as starting points for marking Lisp objects.  This is
2368 important because it's quite possible that the only current reference to
2369 the object is the C variable.  In the case of symbols, the
2370 @code{staticpro()} doesn't matter all that much because the symbol is
2371 contained in @code{obarray}, which is itself @code{staticpro()}ed.
2372 However, it's possible that a naughty user could do something like
2373 uninterning the symbol out of @code{obarray} or even setting
2374 @code{obarray} to a different value [although this is likely to make
2375 XEmacs crash!].)
2376
2377   @strong{Please note:} It is potentially deadly if you declare a
2378 @samp{Q...}  variable in two different modules.  The two calls to
2379 @code{defsymbol()} are no problem, but some linkers will complain about
2380 multiply-defined symbols.  The most insidious aspect of this is that
2381 often the link will succeed anyway, but then the resulting executable
2382 will sometimes crash in obscure ways during certain operations!  To
2383 avoid this problem, declare any symbols with common names (such as
2384 @code{text}) that are not obviously associated with this particular
2385 module in the module @file{general.c}.
2386
2387   Global variables whose names begin with @samp{V} are variables that
2388 contain Lisp objects.  The convention here is that all global variables
2389 of type @code{Lisp_Object} begin with @samp{V}, and all others don't
2390 (including integer and boolean variables that have Lisp
2391 equivalents). Most of the time, these variables have equivalents in
2392 Lisp, but some don't.  Those that do are declared this way by a call to
2393 @code{DEFVAR_LISP()} in the @code{vars_of_*()} initializer for the
2394 module.  What this does is create a special @dfn{symbol-value-forward}
2395 Lisp object that contains a pointer to the C variable, intern a symbol
2396 whose name is as specified in the call to @code{DEFVAR_LISP()}, and set
2397 its value to the symbol-value-forward Lisp object; it also calls
2398 @code{staticpro()} on the C variable to tell the garbage-collection
2399 mechanism about the variable.  When @code{eval} (or actually
2400 @code{symbol-value}) encounters this special object in the process of
2401 retrieving a variable's value, it follows the indirection to the C
2402 variable and gets its value.  @code{setq} does similar things so that
2403 the C variable gets changed.
2404
2405   Whether or not you @code{DEFVAR_LISP()} a variable, you need to
2406 initialize it in the @code{vars_of_*()} function; otherwise it will end
2407 up as all zeroes, which is the integer 0 (@emph{not} @code{nil}), and
2408 this is probably not what you want.  Also, if the variable is not
2409 @code{DEFVAR_LISP()}ed, @strong{you must call} @code{staticpro()} on the
2410 C variable in the @code{vars_of_*()} function.  Otherwise, the
2411 garbage-collection mechanism won't know that the object in this variable
2412 is in use, and will happily collect it and reuse its storage for another
2413 Lisp object, and you will be the one who's unhappy when you can't figure
2414 out how your variable got overwritten.
2415
2416 @node Proper Use of Unsigned Types
2417 @section Proper Use of Unsigned Types
2418 @cindex unsigned types, proper use of
2419 @cindex types, proper use of unsigned
2420
2421 Avoid using @code{unsigned int} and @code{unsigned long} whenever
2422 possible.  Unsigned types are viral -- any arithmetic or comparisons
2423 involving mixed signed and unsigned types are automatically converted to
2424 unsigned, which is almost certainly not what you want.  Many subtle and
2425 hard-to-find bugs are created by careless use of unsigned types.  In
2426 general, you should almost @emph{never} use an unsigned type to hold a
2427 regular quantity of any sort.  The only exceptions are
2428
2429 @enumerate
2430 @item
2431 When there's a reasonable possibility you will actually need all 32 or
2432 64 bits to store the quantity.
2433 @item
2434 When calling existing API's that require unsigned types.  In this case,
2435 you should still do all manipulation using signed types, and do the
2436 conversion at the very threshold of the API call.
2437 @item
2438 In existing code that you don't want to modify because you don't
2439 maintain it.
2440 @item
2441 In bit-field structures.
2442 @end enumerate
2443
2444 Other reasonable uses of @code{unsigned int} and @code{unsigned long}
2445 are representing non-quantities -- e.g. bit-oriented flags and such.
2446
2447 @node Coding for Mule
2448 @section Coding for Mule
2449 @cindex coding for Mule
2450 @cindex Mule, coding for
2451
2452 Although Mule support is not compiled by default in XEmacs, many people
2453 are using it, and we consider it crucial that new code works correctly
2454 with multibyte characters.  This is not hard; it is only a matter of
2455 following several simple user-interface guidelines.  Even if you never
2456 compile with Mule, with a little practice you will find it quite easy
2457 to code Mule-correctly.
2458
2459 Note that these guidelines are not necessarily tied to the current Mule
2460 implementation; they are also a good idea to follow on the grounds of
2461 code generalization for future I18N work.
2462
2463 @menu
2464 * Character-Related Data Types::
2465 * Working With Character and Byte Positions::
2466 * Conversion to and from External Data::
2467 * General Guidelines for Writing Mule-Aware Code::
2468 * An Example of Mule-Aware Code::
2469 @end menu
2470
2471 @node Character-Related Data Types
2472 @subsection Character-Related Data Types
2473 @cindex character-related data types
2474 @cindex data types, character-related
2475
2476 First, let's review the basic character-related datatypes used by
2477 XEmacs.  Note that the separate @code{typedef}s are not mandatory in the
2478 current implementation (all of them boil down to @code{unsigned char} or
2479 @code{int}), but they improve clarity of code a great deal, because one
2480 glance at the declaration can tell the intended use of the variable.
2481
2482 @table @code
2483 @item Emchar
2484 @cindex Emchar
2485 An @code{Emchar} holds a single Emacs character.
2486
2487 Obviously, the equality between characters and bytes is lost in the Mule
2488 world.  Characters can be represented by one or more bytes in the
2489 buffer, and @code{Emchar} is the C type large enough to hold any
2490 character.
2491
2492 Without Mule support, an @code{Emchar} is equivalent to an
2493 @code{unsigned char}.
2494
2495 @item Bufbyte
2496 @cindex Bufbyte
2497 The data representing the text in a buffer or string is logically a set
2498 of @code{Bufbyte}s.
2499
2500 XEmacs does not work with the same character formats all the time; when
2501 reading characters from the outside, it decodes them to an internal
2502 format, and likewise encodes them when writing.  @code{Bufbyte} (in fact
2503 @code{unsigned char}) is the basic unit of XEmacs internal buffers and
2504 strings format.  A @code{Bufbyte *} is the type that points at text
2505 encoded in the variable-width internal encoding.
2506
2507 One character can correspond to one or more @code{Bufbyte}s.  In the
2508 current Mule implementation, an ASCII character is represented by the
2509 same @code{Bufbyte}, and other characters are represented by a sequence
2510 of two or more @code{Bufbyte}s.
2511
2512 Without Mule support, there are exactly 256 characters, implicitly
2513 Latin-1, and each character is represented using one @code{Bufbyte}, and
2514 there is a one-to-one correspondence between @code{Bufbyte}s and
2515 @code{Emchar}s.
2516
2517 @item Bufpos
2518 @itemx Charcount
2519 @cindex Bufpos
2520 @cindex Charcount
2521 A @code{Bufpos} represents a character position in a buffer or string.
2522 A @code{Charcount} represents a number (count) of characters.
2523 Logically, subtracting two @code{Bufpos} values yields a
2524 @code{Charcount} value.  Although all of these are @code{typedef}ed to
2525 @code{EMACS_INT}, we use them in preference to @code{EMACS_INT} to make
2526 it clear what sort of position is being used.
2527
2528 @code{Bufpos} and @code{Charcount} values are the only ones that are
2529 ever visible to Lisp.
2530
2531 @item Bytind
2532 @itemx Bytecount
2533 @cindex Bytind
2534 @cindex Bytecount
2535 A @code{Bytind} represents a byte position in a buffer or string.  A
2536 @code{Bytecount} represents the distance between two positions, in bytes.
2537 The relationship between @code{Bytind} and @code{Bytecount} is the same
2538 as the relationship between @code{Bufpos} and @code{Charcount}.
2539
2540 @item Extbyte
2541 @itemx Extcount
2542 @cindex Extbyte
2543 @cindex Extcount
2544 When dealing with the outside world, XEmacs works with @code{Extbyte}s,
2545 which are equivalent to @code{unsigned char}.  Obviously, an
2546 @code{Extcount} is the distance between two @code{Extbyte}s.  Extbytes
2547 and Extcounts are not all that frequent in XEmacs code.
2548 @end table
2549
2550 @node Working With Character and Byte Positions
2551 @subsection Working With Character and Byte Positions
2552 @cindex character and byte positions, working with
2553 @cindex byte positions, working with character and
2554 @cindex positions, working with character and byte
2555
2556 Now that we have defined the basic character-related types, we can look
2557 at the macros and functions designed for work with them and for
2558 conversion between them.  Most of these macros are defined in
2559 @file{buffer.h}, and we don't discuss all of them here, but only the
2560 most important ones.  Examining the existing code is the best way to
2561 learn about them.
2562
2563 @table @code
2564 @item MAX_EMCHAR_LEN
2565 @cindex MAX_EMCHAR_LEN
2566 This preprocessor constant is the maximum number of buffer bytes to
2567 represent an Emacs character in the variable width internal encoding.
2568 It is useful when allocating temporary strings to keep a known number of
2569 characters.  For instance:
2570
2571 @example
2572 @group
2573 @{
2574   Charcount cclen;
2575   ...
2576   @{
2577     /* Allocate place for @var{cclen} characters. */
2578     Bufbyte *buf = (Bufbyte *)alloca (cclen * MAX_EMCHAR_LEN);
2579 ...
2580 @end group
2581 @end example
2582
2583 If you followed the previous section, you can guess that, logically,
2584 multiplying a @code{Charcount} value with @code{MAX_EMCHAR_LEN} produces
2585 a @code{Bytecount} value.
2586
2587 In the current Mule implementation, @code{MAX_EMCHAR_LEN} equals 4.
2588 Without Mule, it is 1.
2589
2590 @item charptr_emchar
2591 @itemx set_charptr_emchar
2592 @cindex charptr_emchar
2593 @cindex set_charptr_emchar
2594 The @code{charptr_emchar} macro takes a @code{Bufbyte} pointer and
2595 returns the @code{Emchar} stored at that position.  If it were a
2596 function, its prototype would be:
2597
2598 @example
2599 Emchar charptr_emchar (Bufbyte *p);
2600 @end example
2601
2602 @code{set_charptr_emchar} stores an @code{Emchar} to the specified byte
2603 position.  It returns the number of bytes stored:
2604
2605 @example
2606 Bytecount set_charptr_emchar (Bufbyte *p, Emchar c);
2607 @end example
2608
2609 It is important to note that @code{set_charptr_emchar} is safe only for
2610 appending a character at the end of a buffer, not for overwriting a
2611 character in the middle.  This is because the width of characters
2612 varies, and @code{set_charptr_emchar} cannot resize the string if it
2613 writes, say, a two-byte character where a single-byte character used to
2614 reside.
2615
2616 A typical use of @code{set_charptr_emchar} can be demonstrated by this
2617 example, which copies characters from buffer @var{buf} to a temporary
2618 string of Bufbytes.
2619
2620 @example
2621 @group
2622 @{
2623   Bufpos pos;
2624   for (pos = beg; pos < end; pos++)
2625     @{
2626       Emchar c = BUF_FETCH_CHAR (buf, pos);
2627       p += set_charptr_emchar (buf, c);
2628     @}
2629 @}
2630 @end group
2631 @end example
2632
2633 Note how @code{set_charptr_emchar} is used to store the @code{Emchar}
2634 and increment the counter, at the same time.
2635
2636 @item INC_CHARPTR
2637 @itemx DEC_CHARPTR
2638 @cindex INC_CHARPTR
2639 @cindex DEC_CHARPTR
2640 These two macros increment and decrement a @code{Bufbyte} pointer,
2641 respectively.  They will adjust the pointer by the appropriate number of
2642 bytes according to the byte length of the character stored there.  Both
2643 macros assume that the memory address is located at the beginning of a
2644 valid character.
2645
2646 Without Mule support, @code{INC_CHARPTR (p)} and @code{DEC_CHARPTR (p)}
2647 simply expand to @code{p++} and @code{p--}, respectively.
2648
2649 @item bytecount_to_charcount
2650 @cindex bytecount_to_charcount
2651 Given a pointer to a text string and a length in bytes, return the
2652 equivalent length in characters.
2653
2654 @example
2655 Charcount bytecount_to_charcount (Bufbyte *p, Bytecount bc);
2656 @end example
2657
2658 @item charcount_to_bytecount
2659 @cindex charcount_to_bytecount
2660 Given a pointer to a text string and a length in characters, return the
2661 equivalent length in bytes.
2662
2663 @example
2664 Bytecount charcount_to_bytecount (Bufbyte *p, Charcount cc);
2665 @end example
2666
2667 @item charptr_n_addr
2668 @cindex charptr_n_addr
2669 Return a pointer to the beginning of the character offset @var{cc} (in
2670 characters) from @var{p}.
2671
2672 @example
2673 Bufbyte *charptr_n_addr (Bufbyte *p, Charcount cc);
2674 @end example
2675 @end table
2676
2677 @node Conversion to and from External Data
2678 @subsection Conversion to and from External Data
2679 @cindex conversion to and from external data
2680 @cindex external data, conversion to and from
2681
2682 When an external function, such as a C library function, returns a
2683 @code{char} pointer, you should almost never treat it as @code{Bufbyte}.
2684 This is because these returned strings may contain 8bit characters which
2685 can be misinterpreted by XEmacs, and cause a crash.  Likewise, when
2686 exporting a piece of internal text to the outside world, you should
2687 always convert it to an appropriate external encoding, lest the internal
2688 stuff (such as the infamous \201 characters) leak out.
2689
2690 The interface to conversion between the internal and external
2691 representations of text are the numerous conversion macros defined in
2692 @file{buffer.h}.  There used to be a fixed set of external formats
2693 supported by these macros, but now any coding system can be used with
2694 these macros.  The coding system alias mechanism is used to create the
2695 following logical coding systems, which replace the fixed external
2696 formats.  The (dontusethis-set-symbol-value-handler) mechanism was
2697 enhanced to make this possible (more work on that is needed - like
2698 remove the @code{dontusethis-} prefix).
2699
2700 @table @code
2701 @item Qbinary
2702 This is the simplest format and is what we use in the absence of a more
2703 appropriate format.  This converts according to the @code{binary} coding
2704 system:
2705
2706 @enumerate a
2707 @item
2708 On input, bytes 0--255 are converted into (implicitly Latin-1)
2709 characters 0--255.  A non-Mule xemacs doesn't really know about
2710 different character sets and the fonts to display them, so the bytes can
2711 be treated as text in different 1-byte encodings by simply setting the
2712 appropriate fonts.  So in a sense, non-Mule xemacs is a multi-lingual
2713 editor if, for example, different fonts are used to display text in
2714 different buffers, faces, or windows.  The specifier mechanism gives the
2715 user complete control over this kind of behavior.
2716 @item
2717 On output, characters 0--255 are converted into bytes 0--255 and other
2718 characters are converted into `~'.
2719 @end enumerate
2720
2721 @item Qfile_name
2722 Format used for filenames.  This is user-definable via either the
2723 @code{file-name-coding-system} or @code{pathname-coding-system} (now
2724 obsolete) variables.
2725
2726 @item Qnative
2727 Format used for the external Unix environment---@code{argv[]}, stuff
2728 from @code{getenv()}, stuff from the @file{/etc/passwd} file, etc.
2729 Currently this is the same as Qfile_name.  The two should be
2730 distinguished for clarity and possible future separation.
2731
2732 @item Qctext
2733 Compound--text format.  This is the standard X11 format used for data
2734 stored in properties, selections, and the like.  This is an 8-bit
2735 no-lock-shift ISO2022 coding system.  This is a real coding system,
2736 unlike Qfile_name, which is user-definable.
2737 @end table
2738
2739 There are two fundamental macros to convert between external and
2740 internal format.
2741
2742 @code{TO_INTERNAL_FORMAT} converts external data to internal format, and
2743 @code{TO_EXTERNAL_FORMAT} converts the other way around.  The arguments
2744 each of these receives are a source type, a source, a sink type, a sink,
2745 and a coding system (or a symbol naming a coding system).
2746
2747 A typical call looks like
2748 @example
2749 TO_EXTERNAL_FORMAT (LISP_STRING, str, C_STRING_MALLOC, ptr, Qfile_name);
2750 @end example
2751
2752 which means that the contents of the lisp string @code{str} are written
2753 to a malloc'ed memory area which will be pointed to by @code{ptr}, after
2754 the function returns.  The conversion will be done using the
2755 @code{file-name} coding system, which will be controlled by the user
2756 indirectly by setting or binding the variable
2757 @code{file-name-coding-system}.
2758
2759 Some sources and sinks require two C variables to specify.  We use some
2760 preprocessor magic to allow different source and sink types, and even
2761 different numbers of arguments to specify different types of sources and
2762 sinks.
2763
2764 So we can have a call that looks like
2765 @example
2766 TO_INTERNAL_FORMAT (DATA, (ptr, len),
2767                     MALLOC, (ptr, len),
2768                     coding_system);
2769 @end example
2770
2771 The parenthesized argument pairs are required to make the preprocessor
2772 magic work.
2773
2774 Here are the different source and sink types:
2775
2776 @table @code
2777 @item @code{DATA, (ptr, len),}
2778 input data is a fixed buffer of size @var{len} at address @var{ptr}
2779 @item @code{ALLOCA, (ptr, len),}
2780 output data is placed in an alloca()ed buffer of size @var{len} pointed to by @var{ptr}
2781 @item @code{MALLOC, (ptr, len),}
2782 output data is in a malloc()ed buffer of size @var{len} pointed to by @var{ptr}
2783 @item @code{C_STRING_ALLOCA, ptr,}
2784 equivalent to @code{ALLOCA (ptr, len_ignored)} on output.
2785 @item @code{C_STRING_MALLOC, ptr,}
2786 equivalent to @code{MALLOC (ptr, len_ignored)} on output
2787 @item @code{C_STRING, ptr,}
2788 equivalent to @code{DATA, (ptr, strlen (ptr) + 1)} on input
2789 @item @code{LISP_STRING, string,}
2790 input or output is a Lisp_Object of type string
2791 @item @code{LISP_BUFFER, buffer,}
2792 output is written to @code{(point)} in lisp buffer @var{buffer}
2793 @item @code{LISP_LSTREAM, lstream,}
2794 input or output is a Lisp_Object of type lstream
2795 @item @code{LISP_OPAQUE, object,}
2796 input or output is a Lisp_Object of type opaque
2797 @end table
2798
2799 Often, the data is being converted to a '\0'-byte-terminated string,
2800 which is the format required by many external system C APIs.  For these
2801 purposes, a source type of @code{C_STRING} or a sink type of
2802 @code{C_STRING_ALLOCA} or @code{C_STRING_MALLOC} is appropriate.
2803 Otherwise, we should try to keep XEmacs '\0'-byte-clean, which means
2804 using (ptr, len) pairs.
2805
2806 The sinks to be specified must be lvalues, unless they are the lisp
2807 object types @code{LISP_LSTREAM} or @code{LISP_BUFFER}.
2808
2809 For the sink types @code{ALLOCA} and @code{C_STRING_ALLOCA}, the
2810 resulting text is stored in a stack-allocated buffer, which is
2811 automatically freed on returning from the function.  However, the sink
2812 types @code{MALLOC} and @code{C_STRING_MALLOC} return @code{xmalloc()}ed
2813 memory.  The caller is responsible for freeing this memory using
2814 @code{xfree()}.
2815
2816 Note that it doesn't make sense for @code{LISP_STRING} to be a source
2817 for @code{TO_INTERNAL_FORMAT} or a sink for @code{TO_EXTERNAL_FORMAT}.
2818 You'll get an assertion failure if you try.
2819
2820
2821 @node General Guidelines for Writing Mule-Aware Code
2822 @subsection General Guidelines for Writing Mule-Aware Code
2823 @cindex writing Mule-aware code, general guidelines for
2824 @cindex Mule-aware code, general guidelines for writing
2825 @cindex code, general guidelines for writing Mule-aware
2826
2827 This section contains some general guidance on how to write Mule-aware
2828 code, as well as some pitfalls you should avoid.
2829
2830 @table @emph
2831 @item Never use @code{char} and @code{char *}.
2832 In XEmacs, the use of @code{char} and @code{char *} is almost always a
2833 mistake.  If you want to manipulate an Emacs character from ``C'', use
2834 @code{Emchar}.  If you want to examine a specific octet in the internal
2835 format, use @code{Bufbyte}.  If you want a Lisp-visible character, use a
2836 @code{Lisp_Object} and @code{make_char}.  If you want a pointer to move
2837 through the internal text, use @code{Bufbyte *}.  Also note that you
2838 almost certainly do not need @code{Emchar *}.
2839
2840 @item Be careful not to confuse @code{Charcount}, @code{Bytecount}, and @code{Bufpos}.
2841 The whole point of using different types is to avoid confusion about the
2842 use of certain variables.  Lest this effect be nullified, you need to be
2843 careful about using the right types.
2844
2845 @item Always convert external data
2846 It is extremely important to always convert external data, because
2847 XEmacs can crash if unexpected 8bit sequences are copied to its internal
2848 buffers literally.
2849
2850 This means that when a system function, such as @code{readdir}, returns
2851 a string, you may need to convert it using one of the conversion macros
2852 described in the previous chapter, before passing it further to Lisp.
2853
2854 Actually, most of the basic system functions that accept '\0'-terminated
2855 string arguments, like @code{stat()} and @code{open()}, have been
2856 @strong{encapsulated} so that they are they @code{always} do internal to
2857 external conversion themselves.  This means you must pass internally
2858 encoded data, typically the @code{XSTRING_DATA} of a Lisp_String to
2859 these functions.  This is actually a design bug, since it unexpectedly
2860 changes the semantics of the system functions.  A better design would be
2861 to provide separate versions of these system functions that accepted
2862 Lisp_Objects which were lisp strings in place of their current
2863 @code{char *} arguments.
2864
2865 @example
2866 int stat_lisp (Lisp_Object path, struct stat *buf); /* Implement me */
2867 @end example
2868
2869 Also note that many internal functions, such as @code{make_string},
2870 accept Bufbytes, which removes the need for them to convert the data
2871 they receive.  This increases efficiency because that way external data
2872 needs to be decoded only once, when it is read.  After that, it is
2873 passed around in internal format.
2874 @end table
2875
2876 @node An Example of Mule-Aware Code
2877 @subsection An Example of Mule-Aware Code
2878 @cindex code, an example of Mule-aware
2879 @cindex Mule-aware code, an example of
2880
2881 As an example of Mule-aware code, we will analyze the @code{string}
2882 function, which conses up a Lisp string from the character arguments it
2883 receives.  Here is the definition, pasted from @code{alloc.c}:
2884
2885 @example
2886 @group
2887 DEFUN ("string", Fstring, 0, MANY, 0, /*
2888 Concatenate all the argument characters and make the result a string.
2889 */
2890        (int nargs, Lisp_Object *args))
2891 @{
2892   Bufbyte *storage = alloca_array (Bufbyte, nargs * MAX_EMCHAR_LEN);
2893   Bufbyte *p = storage;
2894
2895   for (; nargs; nargs--, args++)
2896     @{
2897       Lisp_Object lisp_char = *args;
2898       CHECK_CHAR_COERCE_INT (lisp_char);
2899       p += set_charptr_emchar (p, XCHAR (lisp_char));
2900     @}
2901   return make_string (storage, p - storage);
2902 @}
2903 @end group
2904 @end example
2905
2906 Now we can analyze the source line by line.
2907
2908 Obviously, string will be as long as there are arguments to the
2909 function.  This is why we allocate @code{MAX_EMCHAR_LEN} * @var{nargs}
2910 bytes on the stack, i.e. the worst-case number of bytes for @var{nargs}
2911 @code{Emchar}s to fit in the string.
2912
2913 Then, the loop checks that each element is a character, converting
2914 integers in the process.  Like many other functions in XEmacs, this
2915 function silently accepts integers where characters are expected, for
2916 historical and compatibility reasons.  Unless you know what you are
2917 doing, @code{CHECK_CHAR} will also suffice.  @code{XCHAR (lisp_char)}
2918 extracts the @code{Emchar} from the @code{Lisp_Object}, and
2919 @code{set_charptr_emchar} stores it to storage, increasing @code{p} in
2920 the process.
2921
2922 Other instructive examples of correct coding under Mule can be found all
2923 over the XEmacs code.  For starters, I recommend
2924 @code{Fnormalize_menu_item_name} in @file{menubar.c}.  After you have
2925 understood this section of the manual and studied the examples, you can
2926 proceed writing new Mule-aware code.
2927
2928 @node Techniques for XEmacs Developers
2929 @section Techniques for XEmacs Developers
2930 @cindex techniques for XEmacs developers
2931 @cindex developers, techniques for XEmacs
2932
2933 @cindex Purify
2934 @cindex Quantify
2935 To make a purified XEmacs, do: @code{make puremacs}.
2936 To make a quantified XEmacs, do: @code{make quantmacs}.
2937
2938 You simply can't dump Quantified and Purified images (unless using the
2939 portable dumper).  Purify gets confused when xemacs frees memory in one
2940 process that was allocated in a @emph{different} process on a different
2941 machine!.  Run it like so:
2942 @example
2943 temacs -batch -l loadup.el run-temacs @var{xemacs-args...}
2944 @end example
2945
2946 @cindex error checking
2947 Before you go through the trouble, are you compiling with all
2948 debugging and error-checking off?  If not, try that first.  Be warned
2949 that while Quantify is directly responsible for quite a few
2950 optimizations which have been made to XEmacs, doing a run which
2951 generates results which can be acted upon is not necessarily a trivial
2952 task.
2953
2954 Also, if you're still willing to do some runs make sure you configure
2955 with the @samp{--quantify} flag.  That will keep Quantify from starting
2956 to record data until after the loadup is completed and will shut off
2957 recording right before it shuts down (which generates enough bogus data
2958 to throw most results off).  It also enables three additional elisp
2959 commands: @code{quantify-start-recording-data},
2960 @code{quantify-stop-recording-data} and @code{quantify-clear-data}.
2961
2962 If you want to make XEmacs faster, target your favorite slow benchmark,
2963 run a profiler like Quantify, @code{gprof}, or @code{tcov}, and figure
2964 out where the cycles are going.  Specific projects:
2965
2966 @itemize @bullet
2967 @item
2968 Make the garbage collector faster.  Figure out how to write an
2969 incremental garbage collector.
2970 @item
2971 Write a compiler that takes bytecode and spits out C code.
2972 Unfortunately, you will then need a C compiler and a more fully
2973 developed module system.
2974 @item
2975 Speed up redisplay.
2976 @item
2977 Speed up syntax highlighting.  Maybe moving some of the syntax
2978 highlighting capabilities into C would make a difference.
2979 @item
2980 Implement tail recursion in Emacs Lisp (hard!).
2981 @end itemize
2982
2983 Unfortunately, Emacs Lisp is slow, and is going to stay slow.  Function
2984 calls in elisp are especially expensive.  Iterating over a long list is
2985 going to be 30 times faster implemented in C than in Elisp.
2986
2987 Heavily used small code fragments need to be fast.  The traditional way
2988 to implement such code fragments in C is with macros.  But macros in C
2989 are known to be broken.
2990
2991 @cindex macro hygiene
2992 Macro arguments that are repeatedly evaluated may suffer from repeated
2993 side effects or suboptimal performance.
2994
2995 Variable names used in macros may collide with caller's variables,
2996 causing (at least) unwanted compiler warnings.
2997
2998 In order to solve these problems, and maintain statement semantics, one
2999 should use the @code{do @{ ... @} while (0)} trick while trying to
3000 reference macro arguments exactly once using local variables.
3001
3002 Let's take a look at this poor macro definition:
3003
3004 @example
3005 #define MARK_OBJECT(obj) \
3006   if (!marked_p (obj)) mark_object (obj), did_mark = 1
3007 @end example
3008
3009 This macro evaluates its argument twice, and also fails if used like this:
3010 @example
3011   if (flag) MARK_OBJECT (obj); else do_something();
3012 @end example
3013
3014 A much better definition is
3015
3016 @example
3017 #define MARK_OBJECT(obj) do @{ \
3018   Lisp_Object mo_obj = (obj); \
3019   if (!marked_p (mo_obj))     \
3020     @{                         \
3021       mark_object (mo_obj);   \
3022       did_mark = 1;           \
3023     @}                         \
3024 @} while (0)
3025 @end example
3026
3027 Notice the elimination of double evaluation by using the local variable
3028 with the obscure name.  Writing safe and efficient macros requires great
3029 care.  The one problem with macros that cannot be portably worked around
3030 is, since a C block has no value, a macro used as an expression rather
3031 than a statement cannot use the techniques just described to avoid
3032 multiple evaluation.
3033
3034 @cindex inline functions
3035 In most cases where a macro has function semantics, an inline function
3036 is a better implementation technique.  Modern compiler optimizers tend
3037 to inline functions even if they have no @code{inline} keyword, and
3038 configure magic ensures that the @code{inline} keyword can be safely
3039 used as an additional compiler hint.  Inline functions used in a single
3040 .c files are easy.  The function must already be defined to be
3041 @code{static}.  Just add another @code{inline} keyword to the
3042 definition.
3043
3044 @example
3045 inline static int
3046 heavily_used_small_function (int arg)
3047 @{
3048   ...
3049 @}
3050 @end example
3051
3052 Inline functions in header files are trickier, because we would like to
3053 make the following optimization if the function is @emph{not} inlined
3054 (for example, because we're compiling for debugging).  We would like the
3055 function to be defined externally exactly once, and each calling
3056 translation unit would create an external reference to the function,
3057 instead of including a definition of the inline function in the object
3058 code of every translation unit that uses it.  This optimization is
3059 currently only available for gcc.  But you don't have to worry about the
3060 trickiness; just define your inline functions in header files using this
3061 pattern:
3062
3063 @example
3064 INLINE_HEADER int
3065 i_used_to_be_a_crufty_macro_but_look_at_me_now (int arg);
3066 INLINE_HEADER int
3067 i_used_to_be_a_crufty_macro_but_look_at_me_now (int arg)
3068 @{
3069   ...
3070 @}
3071 @end example
3072
3073 The declaration right before the definition is to prevent warnings when
3074 compiling with @code{gcc -Wmissing-declarations}.  I consider issuing
3075 this warning for inline functions a gcc bug, but the gcc maintainers disagree.
3076
3077 @cindex inline functions, headers
3078 @cindex header files, inline functions
3079 Every header which contains inline functions, either directly by using
3080 @code{INLINE_HEADER} or indirectly by using @code{DECLARE_LRECORD} must
3081 be added to @file{inline.c}'s includes to make the optimization
3082 described above work.  (Optimization note: if all INLINE_HEADER
3083 functions are in fact inlined in all translation units, then the linker
3084 can just discard @code{inline.o}, since it contains only unreferenced code).
3085
3086 To get started debugging XEmacs, take a look at the @file{.gdbinit} and
3087 @file{.dbxrc} files in the @file{src} directory.  See the section in the
3088 XEmacs FAQ on How to Debug an XEmacs problem with a debugger.
3089
3090 After making source code changes, run @code{make check} to ensure that
3091 you haven't introduced any regressions.  If you want to make xemacs more
3092 reliable, please improve the test suite in @file{tests/automated}.
3093
3094 Did you make sure you didn't introduce any new compiler warnings?
3095
3096 Before submitting a patch, please try compiling at least once with
3097
3098 @example
3099 configure --with-mule --use-union-type --error-checking=all
3100 @end example
3101
3102 Here are things to know when you create a new source file:
3103
3104 @itemize @bullet
3105 @item
3106 All @file{.c} files should @code{#include <config.h>} first.  Almost all
3107 @file{.c} files should @code{#include "lisp.h"} second.
3108
3109 @item
3110 Generated header files should be included using the @code{#include <...>} syntax,
3111 not the @code{#include "..."} syntax.  The generated headers are:
3112
3113 @file{config.h sheap-adjust.h paths.h Emacs.ad.h}
3114
3115 The basic rule is that you should assume builds using @code{--srcdir}
3116 and the @code{#include <...>} syntax needs to be used when the
3117 to-be-included generated file is in a potentially different directory
3118 @emph{at compile time}.  The non-obvious C rule is that @code{#include "..."}
3119 means to search for the included file in the same directory as the
3120 including file, @emph{not} in the current directory.
3121
3122 @item
3123 Header files should @emph{not} include @code{<config.h>} and
3124 @code{"lisp.h"}.  It is the responsibility of the @file{.c} files that
3125 use it to do so.
3126
3127 @end itemize
3128
3129 @cindex Lisp object types, creating
3130 @cindex creating Lisp object types
3131 @cindex object types, creating Lisp
3132 Here is a checklist of things to do when creating a new lisp object type
3133 named @var{foo}:
3134
3135 @enumerate
3136 @item
3137 create @var{foo}.h
3138 @item
3139 create @var{foo}.c
3140 @item
3141 add definitions of @code{syms_of_@var{foo}}, etc. to @file{@var{foo}.c}
3142 @item
3143 add declarations of @code{syms_of_@var{foo}}, etc. to @file{symsinit.h}
3144 @item
3145 add calls to @code{syms_of_@var{foo}}, etc. to @file{emacs.c}
3146 @item
3147 add definitions of macros like @code{CHECK_@var{FOO}} and
3148 @code{@var{FOO}P} to @file{@var{foo}.h}
3149 @item
3150 add the new type index to @code{enum lrecord_type}
3151 @item
3152 add a DEFINE_LRECORD_IMPLEMENTATION call to @file{@var{foo}.c}
3153 @item
3154 add an INIT_LRECORD_IMPLEMENTATION call to @code{syms_of_@var{foo}.c}
3155 @end enumerate
3156
3157
3158 @node Regression Testing XEmacs, A Summary of the Various XEmacs Modules, Rules When Writing New C Code, Top
3159 @chapter Regression Testing XEmacs
3160 @cindex testing, regression
3161
3162 The source directory @file{tests/automated} contains XEmacs' automated
3163 test suite.  The usual way of running all the tests is running
3164 @code{make check} from the top-level source directory.
3165
3166 The test suite is unfinished and it's still lacking some essential
3167 features.  It is nevertheless recommended that you run the tests to
3168 confirm that XEmacs behaves correctly.
3169
3170 If you want to run a specific test case, you can do it from the
3171 command-line like this:
3172
3173 @example
3174 $ xemacs -batch -l test-harness.elc -f batch-test-emacs TEST-FILE
3175 @end example
3176
3177 If something goes wrong, you can run the test suite interactively by
3178 loading @file{test-harness.el} into a running XEmacs and typing
3179 @kbd{M-x test-emacs-test-file RET <filename> RET}.  You will see a log of
3180 passed and failed tests, which should allow you to investigate the
3181 source of the error and ultimately fix the bug.
3182
3183 Adding a new test file is trivial: just create a new file here and it
3184 will be run.  There is no need to byte-compile any of the files in
3185 this directory---the test-harness will take care of any necessary
3186 byte-compilation.
3187
3188 Look at the existing test cases for the examples of coding test cases.
3189 It all boils down to your imagination and judicious use of the macros
3190 @code{Assert}, @code{Check-Error}, @code{Check-Error-Message}, and
3191 @code{Check-Message}.
3192
3193 Here's a simple example checking case-sensitive and case-insensitive
3194 comparisons from @file{case-tests.el}.
3195
3196 @example
3197 (with-temp-buffer
3198   (insert "Test Buffer")
3199   (let ((case-fold-search t))
3200     (goto-char (point-min))
3201     (Assert (eq (search-forward "test buffer" nil t) 12))
3202     (goto-char (point-min))
3203     (Assert (eq (search-forward "Test buffer" nil t) 12))
3204     (goto-char (point-min))
3205     (Assert (eq (search-forward "Test Buffer" nil t) 12))
3206
3207     (setq case-fold-search nil)
3208     (goto-char (point-min))
3209     (Assert (not (search-forward "test buffer" nil t)))
3210     (goto-char (point-min))
3211     (Assert (not (search-forward "Test buffer" nil t)))
3212     (goto-char (point-min))
3213     (Assert (eq (search-forward "Test Buffer" nil t) 12))))
3214 @end example
3215
3216 This example could be inserted in a file in @file{tests/automated}, and
3217 it would be a complete test, automatically executed when you run
3218 @kbd{make check} after building XEmacs.  More complex tests may require
3219 substantial temporary scaffolding to create the environment that elicits
3220 the bugs, but the top-level Makefile and @file{test-harness.el} handle
3221 the running and collection of results from the @code{Assert},
3222 @code{Check-Error}, @code{Check-Error-Message}, and @code{Check-Message}
3223 macros.
3224
3225 @node A Summary of the Various XEmacs Modules, Allocation of Objects in XEmacs Lisp, Regression Testing XEmacs, Top
3226 @chapter A Summary of the Various XEmacs Modules
3227 @cindex modules, a summary of the various XEmacs
3228
3229   This is accurate as of XEmacs 20.0.
3230
3231 @menu
3232 * Low-Level Modules::
3233 * Basic Lisp Modules::
3234 * Modules for Standard Editing Operations::
3235 * Editor-Level Control Flow Modules::
3236 * Modules for the Basic Displayable Lisp Objects::
3237 * Modules for other Display-Related Lisp Objects::
3238 * Modules for the Redisplay Mechanism::
3239 * Modules for Interfacing with the File System::
3240 * Modules for Other Aspects of the Lisp Interpreter and Object System::
3241 * Modules for Interfacing with the Operating System::
3242 * Modules for Interfacing with X Windows::
3243 * Modules for Internationalization::
3244 * Modules for Regression Testing::
3245 @end menu
3246
3247 @node Low-Level Modules
3248 @section Low-Level Modules
3249 @cindex low-level modules
3250 @cindex modules, low-level
3251
3252 @example
3253 config.h
3254 @end example
3255
3256 This is automatically generated from @file{config.h.in} based on the
3257 results of configure tests and user-selected optional features and
3258 contains preprocessor definitions specifying the nature of the
3259 environment in which XEmacs is being compiled.
3260
3261
3262
3263 @example
3264 paths.h
3265 @end example
3266
3267 This is automatically generated from @file{paths.h.in} based on supplied
3268 configure values, and allows for non-standard installed configurations
3269 of the XEmacs directories.  It's currently broken, though.
3270
3271
3272
3273 @example
3274 emacs.c
3275 signal.c
3276 @end example
3277
3278 @file{emacs.c} contains @code{main()} and other code that performs the most
3279 basic environment initializations and handles shutting down the XEmacs
3280 process (this includes @code{kill-emacs}, the normal way that XEmacs is
3281 exited; @code{dump-emacs}, which is used during the build process to
3282 write out the XEmacs executable; @code{run-emacs-from-temacs}, which can
3283 be used to start XEmacs directly when temacs has finished loading all
3284 the Lisp code; and emergency code to handle crashes [XEmacs tries to
3285 auto-save all files before it crashes]).
3286
3287 Low-level code that directly interacts with the Unix signal mechanism,
3288 however, is in @file{signal.c}.  Note that this code does not handle system
3289 dependencies in interfacing to signals; that is handled using the
3290 @file{syssignal.h} header file, described in section J below.
3291
3292
3293
3294 @example
3295 unexaix.c
3296 unexalpha.c
3297 unexapollo.c
3298 unexconvex.c
3299 unexec.c
3300 unexelf.c
3301 unexelfsgi.c
3302 unexencap.c
3303 unexenix.c
3304 unexfreebsd.c
3305 unexfx2800.c
3306 unexhp9k3.c
3307 unexhp9k800.c
3308 unexmips.c
3309 unexnext.c
3310 unexsol2.c
3311 unexsunos4.c
3312 @end example
3313
3314 These modules contain code dumping out the XEmacs executable on various
3315 different systems. (This process is highly machine-specific and
3316 requires intimate knowledge of the executable format and the memory map
3317 of the process.) Only one of these modules is actually used; this is
3318 chosen by @file{configure}.
3319
3320
3321
3322 @example
3323 ecrt0.c
3324 lastfile.c
3325 pre-crt0.c
3326 @end example
3327
3328 These modules are used in conjunction with the dump mechanism.  On some
3329 systems, an alternative version of the C startup code (the actual code
3330 that receives control from the operating system when the process is
3331 started, and which calls @code{main()}) is required so that the dumping
3332 process works properly; @file{crt0.c} provides this.
3333
3334 @file{pre-crt0.c} and @file{lastfile.c} should be the very first and
3335 very last file linked, respectively. (Actually, this is not really true.
3336 @file{lastfile.c} should be after all Emacs modules whose initialized
3337 data should be made constant, and before all other Emacs files and all
3338 libraries.  In particular, the allocation modules @file{gmalloc.c},
3339 @file{alloca.c}, etc. are normally placed past @file{lastfile.c}, and
3340 all of the files that implement Xt widget classes @emph{must} be placed
3341 after @file{lastfile.c} because they contain various structures that
3342 must be statically initialized and into which Xt writes at various
3343 times.) @file{pre-crt0.c} and @file{lastfile.c} contain exported symbols
3344 that are used to determine the start and end of XEmacs' initialized
3345 data space when dumping.
3346
3347
3348
3349 @example
3350 alloca.c
3351 free-hook.c
3352 getpagesize.h
3353 gmalloc.c
3354 malloc.c
3355 mem-limits.h
3356 ralloc.c
3357 vm-limit.c
3358 @end example
3359
3360 These handle basic C allocation of memory.  @file{alloca.c} is an emulation of
3361 the stack allocation function @code{alloca()} on machines that lack
3362 this. (XEmacs makes extensive use of @code{alloca()} in its code.)
3363
3364 @file{gmalloc.c} and @file{malloc.c} are two implementations of the standard C
3365 functions @code{malloc()}, @code{realloc()} and @code{free()}.  They are
3366 often used in place of the standard system-provided @code{malloc()}
3367 because they usually provide a much faster implementation, at the
3368 expense of additional memory use.  @file{gmalloc.c} is a newer implementation
3369 that is much more memory-efficient for large allocations than @file{malloc.c},
3370 and should always be preferred if it works. (At one point, @file{gmalloc.c}
3371 didn't work on some systems where @file{malloc.c} worked; but this should be
3372 fixed now.)
3373
3374 @cindex relocating allocator
3375 @file{ralloc.c} is the @dfn{relocating allocator}.  It provides
3376 functions similar to @code{malloc()}, @code{realloc()} and @code{free()}
3377 that allocate memory that can be dynamically relocated in memory.  The
3378 advantage of this is that allocated memory can be shuffled around to
3379 place all the free memory at the end of the heap, and the heap can then
3380 be shrunk, releasing the memory back to the operating system.  The use
3381 of this can be controlled with the configure option @code{--rel-alloc};
3382 if enabled, memory allocated for buffers will be relocatable, so that if
3383 a very large file is visited and the buffer is later killed, the memory
3384 can be released to the operating system.  (The disadvantage of this
3385 mechanism is that it can be very slow.  On systems with the
3386 @code{mmap()} system call, the XEmacs version of @file{ralloc.c} uses
3387 this to move memory around without actually having to block-copy it,
3388 which can speed things up; but it can still cause noticeable performance
3389 degradation.)
3390
3391 @file{free-hook.c} contains some debugging functions for checking for invalid
3392 arguments to @code{free()}.
3393
3394 @file{vm-limit.c} contains some functions that warn the user when memory is
3395 getting low.  These are callback functions that are called by @file{gmalloc.c}
3396 and @file{malloc.c} at appropriate times.
3397
3398 @file{getpagesize.h} provides a uniform interface for retrieving the size of a
3399 page in virtual memory.  @file{mem-limits.h} provides a uniform interface for
3400 retrieving the total amount of available virtual memory.  Both are
3401 similar in spirit to the @file{sys*.h} files described in section J, below.
3402
3403
3404
3405 @example
3406 blocktype.c
3407 blocktype.h
3408 dynarr.c
3409 @end example
3410
3411 These implement a couple of basic C data types to facilitate memory
3412 allocation.  The @code{Blocktype} type efficiently manages the
3413 allocation of fixed-size blocks by minimizing the number of times that
3414 @code{malloc()} and @code{free()} are called.  It allocates memory in
3415 large chunks, subdivides the chunks into blocks of the proper size, and
3416 returns the blocks as requested.  When blocks are freed, they are placed
3417 onto a linked list, so they can be efficiently reused.  This data type
3418 is not much used in XEmacs currently, because it's a fairly new
3419 addition.
3420
3421 @cindex dynamic array
3422 The @code{Dynarr} type implements a @dfn{dynamic array}, which is
3423 similar to a standard C array but has no fixed limit on the number of
3424 elements it can contain.  Dynamic arrays can hold elements of any type,
3425 and when you add a new element, the array automatically resizes itself
3426 if it isn't big enough.  Dynarrs are extensively used in the redisplay
3427 mechanism.
3428
3429
3430
3431 @example
3432 inline.c
3433 @end example
3434
3435 This module is used in connection with inline functions (available in
3436 some compilers).  Often, inline functions need to have a corresponding
3437 non-inline function that does the same thing.  This module is where they
3438 reside.  It contains no actual code, but defines some special flags that
3439 cause inline functions defined in header files to be rendered as actual
3440 functions.  It then includes all header files that contain any inline
3441 function definitions, so that each one gets a real function equivalent.
3442
3443
3444
3445 @example
3446 debug.c
3447 debug.h
3448 @end example
3449
3450 These functions provide a system for doing internal consistency checks
3451 during code development.  This system is not currently used; instead the
3452 simpler @code{assert()} macro is used along with the various checks
3453 provided by the @samp{--error-check-*} configuration options.
3454
3455
3456
3457 @example
3458 universe.h
3459 @end example
3460
3461 This is not currently used.
3462
3463
3464
3465 @node Basic Lisp Modules
3466 @section Basic Lisp Modules
3467 @cindex Lisp modules, basic
3468 @cindex modules, basic Lisp
3469
3470 @example
3471 lisp-disunion.h
3472 lisp-union.h
3473 lisp.h
3474 lrecord.h
3475 symsinit.h
3476 @end example
3477
3478 These are the basic header files for all XEmacs modules.  Each module
3479 includes @file{lisp.h}, which brings the other header files in.
3480 @file{lisp.h} contains the definitions of the structures and extractor
3481 and constructor macros for the basic Lisp objects and various other
3482 basic definitions for the Lisp environment, as well as some
3483 general-purpose definitions (e.g. @code{min()} and @code{max()}).
3484 @file{lisp.h} includes either @file{lisp-disunion.h} or
3485 @file{lisp-union.h}, depending on whether @code{USE_UNION_TYPE} is
3486 defined.  These files define the typedef of the Lisp object itself (as
3487 described above) and the low-level macros that hide the actual
3488 implementation of the Lisp object.  All extractor and constructor macros
3489 for particular types of Lisp objects are defined in terms of these
3490 low-level macros.
3491
3492 As a general rule, all typedefs should go into the typedefs section of
3493 @file{lisp.h} rather than into a module-specific header file even if the
3494 structure is defined elsewhere.  This allows function prototypes that
3495 use the typedef to be placed into other header files.  Forward structure
3496 declarations (i.e. a simple declaration like @code{struct foo;} where
3497 the structure itself is defined elsewhere) should be placed into the
3498 typedefs section as necessary.
3499
3500 @file{lrecord.h} contains the basic structures and macros that implement
3501 all record-type Lisp objects---i.e. all objects whose type is a field
3502 in their C structure, which includes all objects except the few most
3503 basic ones.
3504
3505 @file{lisp.h} contains prototypes for most of the exported functions in
3506 the various modules.  Lisp primitives defined using @code{DEFUN} that
3507 need to be called by C code should be declared using @code{EXFUN}.
3508 Other function prototypes should be placed either into the appropriate
3509 section of @code{lisp.h}, or into a module-specific header file,
3510 depending on how general-purpose the function is and whether it has
3511 special-purpose argument types requiring definitions not in
3512 @file{lisp.h}.)  All initialization functions are prototyped in
3513 @file{symsinit.h}.
3514
3515
3516
3517 @example
3518 alloc.c
3519 @end example
3520
3521 The large module @file{alloc.c} implements all of the basic allocation and
3522 garbage collection for Lisp objects.  The most commonly used Lisp
3523 objects are allocated in chunks, similar to the Blocktype data type
3524 described above; others are allocated in individually @code{malloc()}ed
3525 blocks.  This module provides the foundation on which all other aspects
3526 of the Lisp environment sit, and is the first module initialized at
3527 startup.
3528
3529 Note that @file{alloc.c} provides a series of generic functions that are
3530 not dependent on any particular object type, and interfaces to
3531 particular types of objects using a standardized interface of
3532 type-specific methods.  This scheme is a fundamental principle of
3533 object-oriented programming and is heavily used throughout XEmacs.  The
3534 great advantage of this is that it allows for a clean separation of
3535 functionality into different modules---new classes of Lisp objects, new
3536 event interfaces, new device types, new stream interfaces, etc. can be
3537 added transparently without affecting code anywhere else in XEmacs.
3538 Because the different subsystems are divided into general and specific
3539 code, adding a new subtype within a subsystem will in general not
3540 require changes to the generic subsystem code or affect any of the other
3541 subtypes in the subsystem; this provides a great deal of robustness to
3542 the XEmacs code.
3543
3544
3545 @example
3546 eval.c
3547 backtrace.h
3548 @end example
3549
3550 This module contains all of the functions to handle the flow of control.
3551 This includes the mechanisms of defining functions, calling functions,
3552 traversing stack frames, and binding variables; the control primitives
3553 and other special forms such as @code{while}, @code{if}, @code{eval},
3554 @code{let}, @code{and}, @code{or}, @code{progn}, etc.; handling of
3555 non-local exits, unwind-protects, and exception handlers; entering the
3556 debugger; methods for the subr Lisp object type; etc.  It does
3557 @emph{not} include the @code{read} function, the @code{print} function,
3558 or the handling of symbols and obarrays.
3559
3560 @file{backtrace.h} contains some structures related to stack frames and the
3561 flow of control.
3562
3563
3564
3565 @example
3566 lread.c
3567 @end example
3568
3569 This module implements the Lisp reader and the @code{read} function,
3570 which converts text into Lisp objects, according to the read syntax of
3571 the objects, as described above.  This is similar to the parser that is
3572 a part of all compilers.
3573
3574
3575
3576 @example
3577 print.c
3578 @end example
3579
3580 This module implements the Lisp print mechanism and the @code{print}
3581 function and related functions.  This is the inverse of the Lisp reader
3582 -- it converts Lisp objects to a printed, textual representation.
3583 (Hopefully something that can be read back in using @code{read} to get
3584 an equivalent object.)
3585
3586
3587
3588 @example
3589 general.c
3590 symbols.c
3591 symeval.h
3592 @end example
3593
3594 @file{symbols.c} implements the handling of symbols, obarrays, and
3595 retrieving the values of symbols.  Much of the code is devoted to
3596 handling the special @dfn{symbol-value-magic} objects that define
3597 special types of variables---this includes buffer-local variables,
3598 variable aliases, variables that forward into C variables, etc.  This
3599 module is initialized extremely early (right after @file{alloc.c}),
3600 because it is here that the basic symbols @code{t} and @code{nil} are
3601 created, and those symbols are used everywhere throughout XEmacs.
3602
3603 @file{symeval.h} contains the definitions of symbol structures and the
3604 @code{DEFVAR_LISP()} and related macros for declaring variables.
3605
3606
3607
3608 @example
3609 data.c
3610 floatfns.c
3611 fns.c
3612 @end example
3613
3614 These modules implement the methods and standard Lisp primitives for all
3615 the basic Lisp object types other than symbols (which are described
3616 above).  @file{data.c} contains all the predicates (primitives that return
3617 whether an object is of a particular type); the integer arithmetic
3618 functions; and the basic accessor and mutator primitives for the various
3619 object types.  @file{fns.c} contains all the standard predicates for working
3620 with sequences (where, abstractly speaking, a sequence is an ordered set
3621 of objects, and can be represented by a list, string, vector, or
3622 bit-vector); it also contains @code{equal}, perhaps on the grounds that
3623 bulk of the operation of @code{equal} is comparing sequences.
3624 @file{floatfns.c} contains methods and primitives for floats and floating-point
3625 arithmetic.
3626
3627
3628
3629 @example
3630 bytecode.c
3631 bytecode.h
3632 @end example
3633
3634 @file{bytecode.c} implements the byte-code interpreter and
3635 compiled-function objects, and @file{bytecode.h} contains associated
3636 structures.  Note that the byte-code @emph{compiler} is written in Lisp.
3637
3638
3639
3640
3641 @node Modules for Standard Editing Operations
3642 @section Modules for Standard Editing Operations
3643 @cindex modules for standard editing operations
3644 @cindex editing operations, modules for standard
3645
3646 @example
3647 buffer.c
3648 buffer.h
3649 bufslots.h
3650 @end example
3651
3652 @file{buffer.c} implements the @dfn{buffer} Lisp object type.  This
3653 includes functions that create and destroy buffers; retrieve buffers by
3654 name or by other properties; manipulate lists of buffers (remember that
3655 buffers are permanent objects and stored in various ordered lists);
3656 retrieve or change buffer properties; etc.  It also contains the
3657 definitions of all the built-in buffer-local variables (which can be
3658 viewed as buffer properties).  It does @emph{not} contain code to
3659 manipulate buffer-local variables (that's in @file{symbols.c}, described
3660 above); or code to manipulate the text in a buffer.
3661
3662 @file{buffer.h} defines the structures associated with a buffer and the various
3663 macros for retrieving text from a buffer and special buffer positions
3664 (e.g. @code{point}, the default location for text insertion).  It also
3665 contains macros for working with buffer positions and converting between
3666 their representations as character offsets and as byte offsets (under
3667 MULE, they are different, because characters can be multi-byte).  It is
3668 one of the largest header files.
3669
3670 @file{bufslots.h} defines the fields in the buffer structure that correspond to
3671 the built-in buffer-local variables.  It is its own header file because
3672 it is included many times in @file{buffer.c}, as a way of iterating over all
3673 the built-in buffer-local variables.
3674
3675
3676
3677 @example
3678 insdel.c
3679 insdel.h
3680 @end example
3681
3682 @file{insdel.c} contains low-level functions for inserting and deleting text in
3683 a buffer, keeping track of changed regions for use by redisplay, and
3684 calling any before-change and after-change functions that may have been
3685 registered for the buffer.  It also contains the actual functions that
3686 convert between byte offsets and character offsets.
3687
3688 @file{insdel.h} contains associated headers.
3689
3690
3691
3692 @example
3693 marker.c
3694 @end example
3695
3696 This module implements the @dfn{marker} Lisp object type, which
3697 conceptually is a pointer to a text position in a buffer that moves
3698 around as text is inserted and deleted, so as to remain in the same
3699 relative position.  This module doesn't actually move the markers around
3700 -- that's handled in @file{insdel.c}.  This module just creates them and
3701 implements the primitives for working with them.  As markers are simple
3702 objects, this does not entail much.
3703
3704 Note that the standard arithmetic primitives (e.g. @code{+}) accept
3705 markers in place of integers and automatically substitute the value of
3706 @code{marker-position} for the marker, i.e. an integer describing the
3707 current buffer position of the marker.
3708
3709
3710
3711 @example
3712 extents.c
3713 extents.h
3714 @end example
3715
3716 This module implements the @dfn{extent} Lisp object type, which is like
3717 a marker that works over a range of text rather than a single position.
3718 Extents are also much more complex and powerful than markers and have a
3719 more efficient (and more algorithmically complex) implementation.  The
3720 implementation is described in detail in comments in @file{extents.c}.
3721
3722 The code in @file{extents.c} works closely with @file{insdel.c} so that
3723 extents are properly moved around as text is inserted and deleted.
3724 There is also code in @file{extents.c} that provides information needed
3725 by the redisplay mechanism for efficient operation. (Remember that
3726 extents can have display properties that affect [sometimes drastically,
3727 as in the @code{invisible} property] the display of the text they
3728 cover.)
3729
3730
3731
3732 @example
3733 editfns.c
3734 @end example
3735
3736 @file{editfns.c} contains the standard Lisp primitives for working with
3737 a buffer's text, and calls the low-level functions in @file{insdel.c}.
3738 It also contains primitives for working with @code{point} (the default
3739 buffer insertion location).
3740
3741 @file{editfns.c} also contains functions for retrieving various
3742 characteristics from the external environment: the current time, the
3743 process ID of the running XEmacs process, the name of the user who ran
3744 this XEmacs process, etc.  It's not clear why this code is in
3745 @file{editfns.c}.
3746
3747
3748
3749 @example
3750 callint.c
3751 cmds.c
3752 commands.h
3753 @end example
3754
3755 @cindex interactive
3756 These modules implement the basic @dfn{interactive} commands,
3757 i.e. user-callable functions.  Commands, as opposed to other functions,
3758 have special ways of getting their parameters interactively (by querying
3759 the user), as opposed to having them passed in a normal function
3760 invocation.  Many commands are not really meant to be called from other
3761 Lisp functions, because they modify global state in a way that's often
3762 undesired as part of other Lisp functions.
3763
3764 @file{callint.c} implements the mechanism for querying the user for
3765 parameters and calling interactive commands.  The bulk of this module is
3766 code that parses the interactive spec that is supplied with an
3767 interactive command.
3768
3769 @file{cmds.c} implements the basic, most commonly used editing commands:
3770 commands to move around the current buffer and insert and delete
3771 characters.  These commands are implemented using the Lisp primitives
3772 defined in @file{editfns.c}.
3773
3774 @file{commands.h} contains associated structure definitions and prototypes.
3775
3776
3777
3778 @example
3779 regex.c
3780 regex.h
3781 search.c
3782 @end example
3783
3784 @file{search.c} implements the Lisp primitives for searching for text in
3785 a buffer, and some of the low-level algorithms for doing this.  In
3786 particular, the fast fixed-string Boyer-Moore search algorithm is
3787 implemented in @file{search.c}.  The low-level algorithms for doing
3788 regular-expression searching, however, are implemented in @file{regex.c}
3789 and @file{regex.h}.  These two modules are largely independent of
3790 XEmacs, and are similar to (and based upon) the regular-expression
3791 routines used in @file{grep} and other GNU utilities.
3792
3793
3794
3795 @example
3796 doprnt.c
3797 @end example
3798
3799 @file{doprnt.c} implements formatted-string processing, similar to
3800 @code{printf()} command in C.
3801
3802
3803
3804 @example
3805 undo.c
3806 @end example
3807
3808 This module implements the undo mechanism for tracking buffer changes.
3809 Most of this could be implemented in Lisp.
3810
3811
3812
3813 @node Editor-Level Control Flow Modules
3814 @section Editor-Level Control Flow Modules
3815 @cindex control flow modules, editor-level
3816 @cindex modules, editor-level control flow
3817
3818 @example
3819 event-Xt.c
3820 event-msw.c
3821 event-stream.c
3822 event-tty.c
3823 events-mod.h
3824 gpmevent.c
3825 gpmevent.h
3826 events.c
3827 events.h
3828 @end example
3829
3830 These implement the handling of events (user input and other system
3831 notifications).
3832
3833 @file{events.c} and @file{events.h} define the @dfn{event} Lisp object
3834 type and primitives for manipulating it.
3835
3836 @file{event-stream.c} implements the basic functions for working with
3837 event queues, dispatching an event by looking it up in relevant keymaps
3838 and such, and handling timeouts; this includes the primitives
3839 @code{next-event} and @code{dispatch-event}, as well as related
3840 primitives such as @code{sit-for}, @code{sleep-for}, and
3841 @code{accept-process-output}. (@file{event-stream.c} is one of the
3842 hairiest and trickiest modules in XEmacs.  Beware!  You can easily mess
3843 things up here.)
3844
3845 @file{event-Xt.c} and @file{event-tty.c} implement the low-level
3846 interfaces onto retrieving events from Xt (the X toolkit) and from TTY's
3847 (using @code{read()} and @code{select()}), respectively.  The event
3848 interface enforces a clean separation between the specific code for
3849 interfacing with the operating system and the generic code for working
3850 with events, by defining an API of basic, low-level event methods;
3851 @file{event-Xt.c} and @file{event-tty.c} are two different
3852 implementations of this API.  To add support for a new operating system
3853 (e.g. NeXTstep), one merely needs to provide another implementation of
3854 those API functions.
3855
3856 Note that the choice of whether to use @file{event-Xt.c} or
3857 @file{event-tty.c} is made at compile time!  Or at the very latest, it
3858 is made at startup time.  @file{event-Xt.c} handles events for
3859 @emph{both} X and TTY frames; @file{event-tty.c} is only used when X
3860 support is not compiled into XEmacs.  The reason for this is that there
3861 is only one event loop in XEmacs: thus, it needs to be able to receive
3862 events from all different kinds of frames.
3863
3864
3865
3866 @example
3867 keymap.c
3868 keymap.h
3869 @end example
3870
3871 @file{keymap.c} and @file{keymap.h} define the @dfn{keymap} Lisp object
3872 type and associated methods and primitives. (Remember that keymaps are
3873 objects that associate event descriptions with functions to be called to
3874 ``execute'' those events; @code{dispatch-event} looks up events in the
3875 relevant keymaps.)
3876
3877
3878
3879 @example
3880 cmdloop.c
3881 @end example
3882
3883 @file{cmdloop.c} contains functions that implement the actual editor
3884 command loop---i.e. the event loop that cyclically retrieves and
3885 dispatches events.  This code is also rather tricky, just like
3886 @file{event-stream.c}.
3887
3888
3889
3890 @example
3891 macros.c
3892 macros.h
3893 @end example
3894
3895 These two modules contain the basic code for defining keyboard macros.
3896 These functions don't actually do much; most of the code that handles keyboard
3897 macros is mixed in with the event-handling code in @file{event-stream.c}.
3898
3899
3900
3901 @example
3902 minibuf.c
3903 @end example
3904
3905 This contains some miscellaneous code related to the minibuffer (most of
3906 the minibuffer code was moved into Lisp by Richard Mlynarik).  This
3907 includes the primitives for completion (although filename completion is
3908 in @file{dired.c}), the lowest-level interface to the minibuffer (if the
3909 command loop were cleaned up, this too could be in Lisp), and code for
3910 dealing with the echo area (this, too, was mostly moved into Lisp, and
3911 the only code remaining is code to call out to Lisp or provide simple
3912 bootstrapping implementations early in temacs, before the echo-area Lisp
3913 code is loaded).
3914
3915
3916
3917 @node Modules for the Basic Displayable Lisp Objects
3918 @section Modules for the Basic Displayable Lisp Objects
3919 @cindex modules for the basic displayable Lisp objects
3920 @cindex displayable Lisp objects, modules for the basic
3921 @cindex Lisp objects, modules for the basic displayable
3922 @cindex objects, modules for the basic displayable Lisp
3923
3924 @example
3925 console-msw.c
3926 console-msw.h
3927 console-stream.c
3928 console-stream.h
3929 console-tty.c
3930 console-tty.h
3931 console-x.c
3932 console-x.h
3933 console.c
3934 console.h
3935 @end example
3936
3937 These modules implement the @dfn{console} Lisp object type.  A console
3938 contains multiple display devices, but only one keyboard and mouse.
3939 Most of the time, a console will contain exactly one device.
3940
3941 Consoles are the top of a lisp object inclusion hierarchy.  Consoles
3942 contain devices, which contain frames, which contain windows.
3943
3944
3945
3946 @example
3947 device-msw.c
3948 device-tty.c
3949 device-x.c
3950 device.c
3951 device.h
3952 @end example
3953
3954 These modules implement the @dfn{device} Lisp object type.  This
3955 abstracts a particular screen or connection on which frames are
3956 displayed.  As with Lisp objects, event interfaces, and other
3957 subsystems, the device code is separated into a generic component that
3958 contains a standardized interface (in the form of a set of methods) onto
3959 particular device types.
3960
3961 The device subsystem defines all the methods and provides method
3962 services for not only device operations but also for the frame, window,
3963 menubar, scrollbar, toolbar, and other displayable-object subsystems.
3964 The reason for this is that all of these subsystems have the same
3965 subtypes (X, TTY, NeXTstep, Microsoft Windows, etc.) as devices do.
3966
3967
3968
3969 @example
3970 frame-msw.c
3971 frame-tty.c
3972 frame-x.c
3973 frame.c
3974 frame.h
3975 @end example
3976
3977 Each device contains one or more frames in which objects (e.g. text) are
3978 displayed.  A frame corresponds to a window in the window system;
3979 usually this is a top-level window but it could potentially be one of a
3980 number of overlapping child windows within a top-level window, using the
3981 MDI (Multiple Document Interface) protocol in Microsoft Windows or a
3982 similar scheme.
3983
3984 The @file{frame-*} files implement the @dfn{frame} Lisp object type and
3985 provide the generic and device-type-specific operations on frames
3986 (e.g. raising, lowering, resizing, moving, etc.).
3987
3988
3989
3990 @example
3991 window.c
3992 window.h
3993 @end example
3994
3995 @cindex window (in Emacs)
3996 @cindex pane
3997 Each frame consists of one or more non-overlapping @dfn{windows} (better
3998 known as @dfn{panes} in standard window-system terminology) in which a
3999 buffer's text can be displayed.  Windows can also have scrollbars
4000 displayed around their edges.
4001
4002 @file{window.c} and @file{window.h} implement the @dfn{window} Lisp
4003 object type and provide code to manage windows.  Since windows have no
4004 associated resources in the window system (the window system knows only
4005 about the frame; no child windows or anything are used for XEmacs
4006 windows), there is no device-type-specific code here; all of that code
4007 is part of the redisplay mechanism or the code for particular object
4008 types such as scrollbars.
4009
4010
4011
4012 @node Modules for other Display-Related Lisp Objects
4013 @section Modules for other Display-Related Lisp Objects
4014 @cindex modules for other display-related Lisp objects
4015 @cindex display-related Lisp objects, modules for other
4016 @cindex Lisp objects, modules for other display-related
4017
4018 @example
4019 faces.c
4020 faces.h
4021 @end example
4022
4023
4024
4025 @example
4026 bitmaps.h
4027 glyphs-eimage.c
4028 glyphs-msw.c
4029 glyphs-msw.h
4030 glyphs-widget.c
4031 glyphs-x.c
4032 glyphs-x.h
4033 glyphs.c
4034 glyphs.h
4035 @end example
4036
4037
4038
4039 @example
4040 objects-msw.c
4041 objects-msw.h
4042 objects-tty.c
4043 objects-tty.h
4044 objects-x.c
4045 objects-x.h
4046 objects.c
4047 objects.h
4048 @end example
4049
4050
4051
4052 @example
4053 menubar-msw.c
4054 menubar-msw.h
4055 menubar-x.c
4056 menubar.c
4057 menubar.h
4058 @end example
4059
4060
4061
4062 @example
4063 scrollbar-msw.c
4064 scrollbar-msw.h
4065 scrollbar-x.c
4066 scrollbar-x.h
4067 scrollbar.c
4068 scrollbar.h
4069 @end example
4070
4071
4072
4073 @example
4074 toolbar-msw.c
4075 toolbar-x.c
4076 toolbar.c
4077 toolbar.h
4078 @end example
4079
4080
4081
4082 @example
4083 font-lock.c
4084 @end example
4085
4086 This file provides C support for syntax highlighting---i.e.
4087 highlighting different syntactic constructs of a source file in
4088 different colors, for easy reading.  The C support is provided so that
4089 this is fast.
4090
4091
4092
4093 @example
4094 dgif_lib.c
4095 gif_err.c
4096 gif_lib.h
4097 gifalloc.c
4098 @end example
4099
4100 These modules decode GIF-format image files, for use with glyphs.
4101 These files were removed due to Unisys patent infringement concerns.
4102
4103
4104
4105 @node Modules for the Redisplay Mechanism
4106 @section Modules for the Redisplay Mechanism
4107 @cindex modules for the redisplay mechanism
4108 @cindex redisplay mechanism, modules for the
4109
4110 @example
4111 redisplay-output.c
4112 redisplay-msw.c
4113 redisplay-tty.c
4114 redisplay-x.c
4115 redisplay.c
4116 redisplay.h
4117 @end example
4118
4119 These files provide the redisplay mechanism.  As with many other
4120 subsystems in XEmacs, there is a clean separation between the general
4121 and device-specific support.
4122
4123 @file{redisplay.c} contains the bulk of the redisplay engine.  These
4124 functions update the redisplay structures (which describe how the screen
4125 is to appear) to reflect any changes made to the state of any
4126 displayable objects (buffer, frame, window, etc.) since the last time
4127 that redisplay was called.  These functions are highly optimized to
4128 avoid doing more work than necessary (since redisplay is called
4129 extremely often and is potentially a huge time sink), and depend heavily
4130 on notifications from the objects themselves that changes have occurred,
4131 so that redisplay doesn't explicitly have to check each possible object.
4132 The redisplay mechanism also contains a great deal of caching to further
4133 speed things up; some of this caching is contained within the various
4134 displayable objects.
4135
4136 @file{redisplay-output.c} goes through the redisplay structures and converts
4137 them into calls to device-specific methods to actually output the screen
4138 changes.
4139
4140 @file{redisplay-x.c} and @file{redisplay-tty.c} are two implementations
4141 of these redisplay output methods, for X frames and TTY frames,
4142 respectively.
4143
4144
4145
4146 @example
4147 indent.c
4148 @end example
4149
4150 This module contains various functions and Lisp primitives for
4151 converting between buffer positions and screen positions.  These
4152 functions call the redisplay mechanism to do most of the work, and then
4153 examine the redisplay structures to get the necessary information.  This
4154 module needs work.
4155
4156
4157
4158 @example
4159 termcap.c
4160 terminfo.c
4161 tparam.c
4162 @end example
4163
4164 These files contain functions for working with the termcap (BSD-style)
4165 and terminfo (System V style) databases of terminal capabilities and
4166 escape sequences, used when XEmacs is displaying in a TTY.
4167
4168
4169
4170 @example
4171 cm.c
4172 cm.h
4173 @end example
4174
4175 These files provide some miscellaneous TTY-output functions and should
4176 probably be merged into @file{redisplay-tty.c}.
4177
4178
4179
4180 @node Modules for Interfacing with the File System
4181 @section Modules for Interfacing with the File System
4182 @cindex modules for interfacing with the file system
4183 @cindex interfacing with the file system, modules for
4184 @cindex file system, modules for interfacing with the
4185
4186 @example
4187 lstream.c
4188 lstream.h
4189 @end example
4190
4191 These modules implement the @dfn{stream} Lisp object type.  This is an
4192 internal-only Lisp object that implements a generic buffering stream.
4193 The idea is to provide a uniform interface onto all sources and sinks of
4194 data, including file descriptors, stdio streams, chunks of memory, Lisp
4195 buffers, Lisp strings, etc.  That way, I/O functions can be written to
4196 the stream interface and can transparently handle all possible sources
4197 and sinks.  (For example, the @code{read} function can read data from a
4198 file, a string, a buffer, or even a function that is called repeatedly
4199 to return data, without worrying about where the data is coming from or
4200 what-size chunks it is returned in.)
4201
4202 @cindex lstream
4203 Note that in the C code, streams are called @dfn{lstreams} (for ``Lisp
4204 streams'') to distinguish them from other kinds of streams, e.g. stdio
4205 streams and C++ I/O streams.
4206
4207 Similar to other subsystems in XEmacs, lstreams are separated into
4208 generic functions and a set of methods for the different types of
4209 lstreams.  @file{lstream.c} provides implementations of many different
4210 types of streams; others are provided, e.g., in @file{file-coding.c}.
4211
4212
4213
4214 @example
4215 fileio.c
4216 @end example
4217
4218 This implements the basic primitives for interfacing with the file
4219 system.  This includes primitives for reading files into buffers,
4220 writing buffers into files, checking for the presence or accessibility
4221 of files, canonicalizing file names, etc.  Note that these primitives
4222 are usually not invoked directly by the user: There is a great deal of
4223 higher-level Lisp code that implements the user commands such as
4224 @code{find-file} and @code{save-buffer}.  This is similar to the
4225 distinction between the lower-level primitives in @file{editfns.c} and
4226 the higher-level user commands in @file{commands.c} and
4227 @file{simple.el}.
4228
4229
4230
4231 @example
4232 filelock.c
4233 @end example
4234
4235 This file provides functions for detecting clashes between different
4236 processes (e.g. XEmacs and some external process, or two different
4237 XEmacs processes) modifying the same file.  (XEmacs can optionally use
4238 the @file{lock/} subdirectory to provide a form of ``locking'' between
4239 different XEmacs processes.)  This module is also used by the low-level
4240 functions in @file{insdel.c} to ensure that, if the first modification
4241 is being made to a buffer whose corresponding file has been externally
4242 modified, the user is made aware of this so that the buffer can be
4243 synched up with the external changes if necessary.
4244
4245
4246 @example
4247 filemode.c
4248 @end example
4249
4250 This file provides some miscellaneous functions that construct a
4251 @samp{rwxr-xr-x}-type permissions string (as might appear in an
4252 @file{ls}-style directory listing) given the information returned by the
4253 @code{stat()} system call.
4254
4255
4256
4257 @example
4258 dired.c
4259 ndir.h
4260 @end example
4261
4262 These files implement the XEmacs interface to directory searching.  This
4263 includes a number of primitives for determining the files in a directory
4264 and for doing filename completion. (Remember that generic completion is
4265 handled by a different mechanism, in @file{minibuf.c}.)
4266
4267 @file{ndir.h} is a header file used for the directory-searching
4268 emulation functions provided in @file{sysdep.c} (see section J below),
4269 for systems that don't provide any directory-searching functions. (On
4270 those systems, directories can be read directly as files, and parsed.)
4271
4272
4273
4274 @example
4275 realpath.c
4276 @end example
4277
4278 This file provides an implementation of the @code{realpath()} function
4279 for expanding symbolic links, on systems that don't implement it or have
4280 a broken implementation.
4281
4282
4283
4284 @node Modules for Other Aspects of the Lisp Interpreter and Object System
4285 @section Modules for Other Aspects of the Lisp Interpreter and Object System
4286 @cindex modules for other aspects of the Lisp interpreter and object system
4287 @cindex Lisp interpreter and object system, modules for other aspects of the
4288 @cindex interpreter and object system, modules for other aspects of the Lisp
4289 @cindex object system, modules for other aspects of the Lisp interpreter and
4290
4291 @example
4292 elhash.c
4293 elhash.h
4294 hash.c
4295 hash.h
4296 @end example
4297
4298 These files provide two implementations of hash tables.  Files
4299 @file{hash.c} and @file{hash.h} provide a generic C implementation of
4300 hash tables which can stand independently of XEmacs.  Files
4301 @file{elhash.c} and @file{elhash.h} provide a separate implementation of
4302 hash tables that can store only Lisp objects, and knows about Lispy
4303 things like garbage collection, and implement the @dfn{hash-table} Lisp
4304 object type.
4305
4306
4307 @example
4308 specifier.c
4309 specifier.h
4310 @end example
4311
4312 This module implements the @dfn{specifier} Lisp object type.  This is
4313 primarily used for displayable properties, and allows for values that
4314 are specific to a particular buffer, window, frame, device, or device
4315 class, as well as a default value existing.  This is used, for example,
4316 to control the height of the horizontal scrollbar or the appearance of
4317 the @code{default}, @code{bold}, or other faces.  The specifier object
4318 consists of a number of specifications, each of which maps from a
4319 buffer, window, etc. to a value.  The function @code{specifier-instance}
4320 looks up a value given a window (from which a buffer, frame, and device
4321 can be derived).
4322
4323
4324 @example
4325 chartab.c
4326 chartab.h
4327 casetab.c
4328 @end example
4329
4330 @file{chartab.c} and @file{chartab.h} implement the @dfn{char table}
4331 Lisp object type, which maps from characters or certain sorts of
4332 character ranges to Lisp objects.  The implementation of this object
4333 type is optimized for the internal representation of characters.  Char
4334 tables come in different types, which affect the allowed object types to
4335 which a character can be mapped and also dictate certain other
4336 properties of the char table.
4337
4338 @cindex case table
4339 @file{casetab.c} implements one sort of char table, the @dfn{case
4340 table}, which maps characters to other characters of possibly different
4341 case.  These are used by XEmacs to implement case-changing primitives
4342 and to do case-insensitive searching.
4343
4344
4345
4346 @example
4347 syntax.c
4348 syntax.h
4349 @end example
4350
4351 @cindex scanner
4352 This module implements @dfn{syntax tables}, another sort of char table
4353 that maps characters into syntax classes that define the syntax of these
4354 characters (e.g. a parenthesis belongs to a class of @samp{open}
4355 characters that have corresponding @samp{close} characters and can be
4356 nested).  This module also implements the Lisp @dfn{scanner}, a set of
4357 primitives for scanning over text based on syntax tables.  This is used,
4358 for example, to find the matching parenthesis in a command such as
4359 @code{forward-sexp}, and by @file{font-lock.c} to locate quoted strings,
4360 comments, etc.
4361
4362
4363
4364 @example
4365 casefiddle.c
4366 @end example
4367
4368 This module implements various Lisp primitives for upcasing, downcasing
4369 and capitalizing strings or regions of buffers.
4370
4371
4372
4373 @example
4374 rangetab.c
4375 @end example
4376
4377 This module implements the @dfn{range table} Lisp object type, which
4378 provides for a mapping from ranges of integers to arbitrary Lisp
4379 objects.
4380
4381
4382
4383 @example
4384 opaque.c
4385 opaque.h
4386 @end example
4387
4388 This module implements the @dfn{opaque} Lisp object type, an
4389 internal-only Lisp object that encapsulates an arbitrary block of memory
4390 so that it can be managed by the Lisp allocation system.  To create an
4391 opaque object, you call @code{make_opaque()}, passing a pointer to a
4392 block of memory.  An object is created that is big enough to hold the
4393 memory, which is copied into the object's storage.  The object will then
4394 stick around as long as you keep pointers to it, after which it will be
4395 automatically reclaimed.
4396
4397 @cindex mark method
4398 Opaque objects can also have an arbitrary @dfn{mark method} associated
4399 with them, in case the block of memory contains other Lisp objects that
4400 need to be marked for garbage-collection purposes. (If you need other
4401 object methods, such as a finalize method, you should just go ahead and
4402 create a new Lisp object type---it's not hard.)
4403
4404
4405
4406 @example
4407 abbrev.c
4408 @end example
4409
4410 This function provides a few primitives for doing dynamic abbreviation
4411 expansion.  In XEmacs, most of the code for this has been moved into
4412 Lisp.  Some C code remains for speed and because the primitive
4413 @code{self-insert-command} (which is executed for all self-inserting
4414 characters) hooks into the abbrev mechanism. (@code{self-insert-command}
4415 is itself in C only for speed.)
4416
4417
4418
4419 @example
4420 doc.c
4421 @end example
4422
4423 This function provides primitives for retrieving the documentation
4424 strings of functions and variables.  These documentation strings contain
4425 certain special markers that get dynamically expanded (e.g. a
4426 reverse-lookup is performed on some named functions to retrieve their
4427 current key bindings).  Some documentation strings (in particular, for
4428 the built-in primitives and pre-loaded Lisp functions) are stored
4429 externally in a file @file{DOC} in the @file{lib-src/} directory and
4430 need to be fetched from that file. (Part of the build stage involves
4431 building this file, and another part involves constructing an index for
4432 this file and embedding it into the executable, so that the functions in
4433 @file{doc.c} do not have to search the entire @file{DOC} file to find
4434 the appropriate documentation string.)
4435
4436
4437
4438 @example
4439 md5.c
4440 @end example
4441
4442 This function provides a Lisp primitive that implements the MD5 secure
4443 hashing scheme, used to create a large hash value of a string of data such that
4444 the data cannot be derived from the hash value.  This is used for
4445 various security applications on the Internet.
4446
4447
4448
4449
4450 @node Modules for Interfacing with the Operating System
4451 @section Modules for Interfacing with the Operating System
4452 @cindex modules for interfacing with the operating system
4453 @cindex interfacing with the operating system, modules for
4454 @cindex operating system, modules for interfacing with the
4455
4456 @example
4457 callproc.c
4458 process.c
4459 process.h
4460 @end example
4461
4462 These modules allow XEmacs to spawn and communicate with subprocesses
4463 and network connections.
4464
4465 @cindex synchronous subprocesses
4466 @cindex subprocesses, synchronous
4467   @file{callproc.c} implements (through the @code{call-process}
4468 primitive) what are called @dfn{synchronous subprocesses}.  This means
4469 that XEmacs runs a program, waits till it's done, and retrieves its
4470 output.  A typical example might be calling the @file{ls} program to get
4471 a directory listing.
4472
4473 @cindex asynchronous subprocesses
4474 @cindex subprocesses, asynchronous
4475   @file{process.c} and @file{process.h} implement @dfn{asynchronous
4476 subprocesses}.  This means that XEmacs starts a program and then
4477 continues normally, not waiting for the process to finish.  Data can be
4478 sent to the process or retrieved from it as it's running.  This is used
4479 for the @code{shell} command (which provides a front end onto a shell
4480 program such as @file{csh}), the mail and news readers implemented in
4481 XEmacs, etc.  The result of calling @code{start-process} to start a
4482 subprocess is a process object, a particular kind of object used to
4483 communicate with the subprocess.  You can send data to the process by
4484 passing the process object and the data to @code{send-process}, and you
4485 can specify what happens to data retrieved from the process by setting
4486 properties of the process object. (When the process sends data, XEmacs
4487 receives a process event, which says that there is data ready.  When
4488 @code{dispatch-event} is called on this event, it reads the data from
4489 the process and does something with it, as specified by the process
4490 object's properties.  Typically, this means inserting the data into a
4491 buffer or calling a function.) Another property of the process object is
4492 called the @dfn{sentinel}, which is a function that is called when the
4493 process terminates.
4494
4495 @cindex network connections
4496   Process objects are also used for network connections (connections to a
4497 process running on another machine).  Network connections are started
4498 with @code{open-network-stream} but otherwise work just like
4499 subprocesses.
4500
4501
4502
4503 @example
4504 sysdep.c
4505 sysdep.h
4506 @end example
4507
4508   These modules implement most of the low-level, messy operating-system
4509 interface code.  This includes various device control (ioctl) operations
4510 for file descriptors, TTY's, pseudo-terminals, etc. (usually this stuff
4511 is fairly system-dependent; thus the name of this module), and emulation
4512 of standard library functions and system calls on systems that don't
4513 provide them or have broken versions.
4514
4515
4516
4517 @example
4518 sysdir.h
4519 sysfile.h
4520 sysfloat.h
4521 sysproc.h
4522 syspwd.h
4523 syssignal.h
4524 systime.h
4525 systty.h
4526 syswait.h
4527 @end example
4528
4529 These header files provide consistent interfaces onto system-dependent
4530 header files and system calls.  The idea is that, instead of including a
4531 standard header file like @file{<sys/param.h>} (which may or may not
4532 exist on various systems) or having to worry about whether all system
4533 provide a particular preprocessor constant, or having to deal with the
4534 four different paradigms for manipulating signals, you just include the
4535 appropriate @file{sys*.h} header file, which includes all the right
4536 system header files, defines and missing preprocessor constants,
4537 provides a uniform interface onto system calls, etc.
4538
4539 @file{sysdir.h} provides a uniform interface onto directory-querying
4540 functions. (In some cases, this is in conjunction with emulation
4541 functions in @file{sysdep.c}.)
4542
4543 @file{sysfile.h} includes all the necessary header files for standard
4544 system calls (e.g. @code{read()}), ensures that all necessary
4545 @code{open()} and @code{stat()} preprocessor constants are defined, and
4546 possibly (usually) substitutes sugared versions of @code{read()},
4547 @code{write()}, etc. that automatically restart interrupted I/O
4548 operations.
4549
4550 @file{sysfloat.h} includes the necessary header files for floating-point
4551 operations.
4552
4553 @file{sysproc.h} includes the necessary header files for calling
4554 @code{select()}, @code{fork()}, @code{execve()}, socket operations, and
4555 the like, and ensures that the @code{FD_*()} macros for descriptor-set
4556 manipulations are available.
4557
4558 @file{syspwd.h} includes the necessary header files for obtaining
4559 information from @file{/etc/passwd} (the functions are emulated under
4560 VMS).
4561
4562 @file{syssignal.h} includes the necessary header files for
4563 signal-handling and provides a uniform interface onto the different
4564 signal-handling and signal-blocking paradigms.
4565
4566 @file{systime.h} includes the necessary header files and provides
4567 uniform interfaces for retrieving the time of day, setting file
4568 access/modification times, getting the amount of time used by the XEmacs
4569 process, etc.
4570
4571 @file{systty.h} buffers against the infinitude of different ways of
4572 controlling TTY's.
4573
4574 @file{syswait.h} provides a uniform way of retrieving the exit status
4575 from a @code{wait()}ed-on process (some systems use a union, others use
4576 an int).
4577
4578
4579
4580 @example
4581 hpplay.c
4582 libsst.c
4583 libsst.h
4584 libst.h
4585 linuxplay.c
4586 nas.c
4587 sgiplay.c
4588 sound.c
4589 sunplay.c
4590 @end example
4591
4592 These files implement the ability to play various sounds on some types
4593 of computers.  You have to configure your XEmacs with sound support in
4594 order to get this capability.
4595
4596 @file{sound.c} provides the generic interface.  It implements various
4597 Lisp primitives and variables that let you specify which sounds should
4598 be played in certain conditions. (The conditions are identified by
4599 symbols, which are passed to @code{ding} to make a sound.  Various
4600 standard functions call this function at certain times; if sound support
4601 does not exist, a simple beep results.
4602
4603 @cindex native sound
4604 @cindex sound, native
4605 @file{sgiplay.c}, @file{sunplay.c}, @file{hpplay.c}, and
4606 @file{linuxplay.c} interface to the machine's speaker for various
4607 different kind of machines.  This is called @dfn{native} sound.
4608
4609 @cindex sound, network
4610 @cindex network sound
4611 @cindex NAS
4612 @file{nas.c} interfaces to a computer somewhere else on the network
4613 using the NAS (Network Audio Server) protocol, playing sounds on that
4614 machine.  This allows you to run XEmacs on a remote machine, with its
4615 display set to your local machine, and have the sounds be made on your
4616 local machine, provided that you have a NAS server running on your local
4617 machine.
4618
4619 @file{libsst.c}, @file{libsst.h}, and @file{libst.h} provide some
4620 additional functions for playing sound on a Sun SPARC but are not
4621 currently in use.
4622
4623
4624
4625 @example
4626 tooltalk.c
4627 tooltalk.h
4628 @end example
4629
4630 These two modules implement an interface to the ToolTalk protocol, which
4631 is an interprocess communication protocol implemented on some versions
4632 of Unix.  ToolTalk is a high-level protocol that allows processes to
4633 register themselves as providers of particular services; other processes
4634 can then request a service without knowing or caring exactly who is
4635 providing the service.  It is similar in spirit to the DDE protocol
4636 provided under Microsoft Windows.  ToolTalk is a part of the new CDE
4637 (Common Desktop Environment) specification and is used to connect the
4638 parts of the SPARCWorks development environment.
4639
4640
4641
4642 @example
4643 getloadavg.c
4644 @end example
4645
4646 This module provides the ability to retrieve the system's current load
4647 average. (The way to do this is highly system-specific, unfortunately,
4648 and requires a lot of special-case code.)
4649
4650
4651
4652 @example
4653 sunpro.c
4654 @end example
4655
4656 This module provides a small amount of code used internally at Sun to
4657 keep statistics on the usage of XEmacs.
4658
4659
4660
4661 @example
4662 broken-sun.h
4663 strcmp.c
4664 strcpy.c
4665 sunOS-fix.c
4666 @end example
4667
4668 These files provide replacement functions and prototypes to fix numerous
4669 bugs in early releases of SunOS 4.1.
4670
4671
4672
4673 @example
4674 hftctl.c
4675 @end example
4676
4677 This module provides some terminal-control code necessary on versions of
4678 AIX prior to 4.1.
4679
4680
4681
4682 @node Modules for Interfacing with X Windows
4683 @section Modules for Interfacing with X Windows
4684 @cindex modules for interfacing with X Windows
4685 @cindex interfacing with X Windows, modules for
4686 @cindex X Windows, modules for interfacing with
4687
4688 @example
4689 Emacs.ad.h
4690 @end example
4691
4692 A file generated from @file{Emacs.ad}, which contains XEmacs-supplied
4693 fallback resources (so that XEmacs has pretty defaults).
4694
4695
4696
4697 @example
4698 EmacsFrame.c
4699 EmacsFrame.h
4700 EmacsFrameP.h
4701 @end example
4702
4703 These modules implement an Xt widget class that encapsulates a frame.
4704 This is for ease in integrating with Xt.  The EmacsFrame widget covers
4705 the entire X window except for the menubar; the scrollbars are
4706 positioned on top of the EmacsFrame widget.
4707
4708 @strong{Warning:} Abandon hope, all ye who enter here.  This code took
4709 an ungodly amount of time to get right, and is likely to fall apart
4710 mercilessly at the slightest change.  Such is life under Xt.
4711
4712
4713
4714 @example
4715 EmacsManager.c
4716 EmacsManager.h
4717 EmacsManagerP.h
4718 @end example
4719
4720 These modules implement a simple Xt manager (i.e. composite) widget
4721 class that simply lets its children set whatever geometry they want.
4722 It's amazing that Xt doesn't provide this standardly, but on second
4723 thought, it makes sense, considering how amazingly broken Xt is.
4724
4725
4726 @example
4727 EmacsShell-sub.c
4728 EmacsShell.c
4729 EmacsShell.h
4730 EmacsShellP.h
4731 @end example
4732
4733 These modules implement two Xt widget classes that are subclasses of
4734 the TopLevelShell and TransientShell classes.  This is necessary to deal
4735 with more brokenness that Xt has sadistically thrust onto the backs of
4736 developers.
4737
4738
4739
4740 @example
4741 xgccache.c
4742 xgccache.h
4743 @end example
4744
4745 These modules provide functions for maintenance and caching of GC's
4746 (graphics contexts) under the X Window System.  This code is junky and
4747 needs to be rewritten.
4748
4749
4750
4751 @example
4752 select-msw.c
4753 select-x.c
4754 select.c
4755 select.h
4756 @end example
4757
4758 @cindex selections
4759   This module provides an interface to the X Window System's concept of
4760 @dfn{selections}, the standard way for X applications to communicate
4761 with each other.
4762
4763
4764
4765 @example
4766 xintrinsic.h
4767 xintrinsicp.h
4768 xmmanagerp.h
4769 xmprimitivep.h
4770 @end example
4771
4772 These header files are similar in spirit to the @file{sys*.h} files and buffer
4773 against different implementations of Xt and Motif.
4774
4775 @itemize @bullet
4776 @item
4777 @file{xintrinsic.h} should be included in place of @file{<Intrinsic.h>}.
4778 @item
4779 @file{xintrinsicp.h} should be included in place of @file{<IntrinsicP.h>}.
4780 @item
4781 @file{xmmanagerp.h} should be included in place of @file{<XmManagerP.h>}.
4782 @item
4783 @file{xmprimitivep.h} should be included in place of @file{<XmPrimitiveP.h>}.
4784 @end itemize
4785
4786
4787
4788 @example
4789 xmu.c
4790 xmu.h
4791 @end example
4792
4793 These files provide an emulation of the Xmu library for those systems
4794 (i.e. HPUX) that don't provide it as a standard part of X.
4795
4796
4797
4798 @example
4799 ExternalClient-Xlib.c
4800 ExternalClient.c
4801 ExternalClient.h
4802 ExternalClientP.h
4803 ExternalShell.c
4804 ExternalShell.h
4805 ExternalShellP.h
4806 extw-Xlib.c
4807 extw-Xlib.h
4808 extw-Xt.c
4809 extw-Xt.h
4810 @end example
4811
4812 @cindex external widget
4813   These files provide the @dfn{external widget} interface, which allows an
4814 XEmacs frame to appear as a widget in another application.  To do this,
4815 you have to configure with @samp{--external-widget}.
4816
4817 @file{ExternalShell*} provides the server (XEmacs) side of the
4818 connection.
4819
4820 @file{ExternalClient*} provides the client (other application) side of
4821 the connection.  These files are not compiled into XEmacs but are
4822 compiled into libraries that are then linked into your application.
4823
4824 @file{extw-*} is common code that is used for both the client and server.
4825
4826 Don't touch this code; something is liable to break if you do.
4827
4828
4829
4830 @node Modules for Internationalization
4831 @section Modules for Internationalization
4832 @cindex modules for internationalization
4833 @cindex internationalization, modules for
4834
4835 @example
4836 mule-canna.c
4837 mule-ccl.c
4838 mule-charset.c
4839 mule-charset.h
4840 file-coding.c
4841 file-coding.h
4842 mule-mcpath.c
4843 mule-mcpath.h
4844 mule-wnnfns.c
4845 mule.c
4846 @end example
4847
4848 These files implement the MULE (Asian-language) support.  Note that MULE
4849 actually provides a general interface for all sorts of languages, not
4850 just Asian languages (although they are generally the most complicated
4851 to support).  This code is still in beta.
4852
4853 @file{mule-charset.*} and @file{file-coding.*} provide the heart of the
4854 XEmacs MULE support.  @file{mule-charset.*} implements the @dfn{charset}
4855 Lisp object type, which encapsulates a character set (an ordered one- or
4856 two-dimensional set of characters, such as US ASCII or JISX0208 Japanese
4857 Kanji).
4858
4859 @file{file-coding.*} implements the @dfn{coding-system} Lisp object
4860 type, which encapsulates a method of converting between different
4861 encodings.  An encoding is a representation of a stream of characters,
4862 possibly from multiple character sets, using a stream of bytes or words,
4863 and defines (e.g.) which escape sequences are used to specify particular
4864 character sets, how the indices for a character are converted into bytes
4865 (sometimes this involves setting the high bit; sometimes complicated
4866 rearranging of the values takes place, as in the Shift-JIS encoding),
4867 etc.
4868
4869 @file{mule-ccl.c} provides the CCL (Code Conversion Language)
4870 interpreter.  CCL is similar in spirit to Lisp byte code and is used to
4871 implement converters for custom encodings.
4872
4873 @file{mule-canna.c} and @file{mule-wnnfns.c} implement interfaces to
4874 external programs used to implement the Canna and WNN input methods,
4875 respectively.  This is currently in beta.
4876
4877 @file{mule-mcpath.c} provides some functions to allow for pathnames
4878 containing extended characters.  This code is fragmentary, obsolete, and
4879 completely non-working.  Instead, @var{pathname-coding-system} is used
4880 to specify conversions of names of files and directories.  The standard
4881 C I/O functions like @samp{open()} are wrapped so that conversion occurs
4882 automatically.
4883
4884 @file{mule.c} provides a few miscellaneous things that should probably
4885 be elsewhere.
4886
4887
4888
4889 @example
4890 intl.c
4891 @end example
4892
4893 This provides some miscellaneous internationalization code for
4894 implementing message translation and interfacing to the Ximp input
4895 method.  None of this code is currently working.
4896
4897
4898
4899 @example
4900 iso-wide.h
4901 @end example
4902
4903 This contains leftover code from an earlier implementation of
4904 Asian-language support, and is not currently used.
4905
4906
4907
4908
4909 @node Modules for Regression Testing
4910 @section Modules for Regression Testing
4911 @cindex modules for regression testing
4912 @cindex regression testing, modules for
4913
4914 @example
4915 test-harness.el
4916 base64-tests.el
4917 byte-compiler-tests.el
4918 case-tests.el
4919 ccl-tests.el
4920 c-tests.el
4921 database-tests.el
4922 extent-tests.el
4923 hash-table-tests.el
4924 lisp-tests.el
4925 md5-tests.el
4926 mule-tests.el
4927 regexp-tests.el
4928 symbol-tests.el
4929 syntax-tests.el
4930 @end example
4931
4932 @file{test-harness.el} defines the macros @code{Assert},
4933 @code{Check-Error}, @code{Check-Error-Message}, and
4934 @code{Check-Message}.  The other files are test files, testing various
4935 XEmacs modules.
4936
4937
4938
4939 @node Allocation of Objects in XEmacs Lisp, Dumping, A Summary of the Various XEmacs Modules, Top
4940 @chapter Allocation of Objects in XEmacs Lisp
4941 @cindex allocation of objects in XEmacs Lisp
4942 @cindex objects in XEmacs Lisp, allocation of
4943 @cindex Lisp objects, allocation of in XEmacs
4944
4945 @menu
4946 * Introduction to Allocation::
4947 * Garbage Collection::
4948 * GCPROing::
4949 * Garbage Collection - Step by Step::
4950 * Integers and Characters::
4951 * Allocation from Frob Blocks::
4952 * lrecords::
4953 * Low-level allocation::
4954 * Cons::
4955 * Vector::
4956 * Bit Vector::
4957 * Symbol::
4958 * Marker::
4959 * String::
4960 * Compiled Function::
4961 @end menu
4962
4963 @node Introduction to Allocation
4964 @section Introduction to Allocation
4965 @cindex allocation, introduction to
4966
4967   Emacs Lisp, like all Lisps, has garbage collection.  This means that
4968 the programmer never has to explicitly free (destroy) an object; it
4969 happens automatically when the object becomes inaccessible.  Most
4970 experts agree that garbage collection is a necessity in a modern,
4971 high-level language.  Its omission from C stems from the fact that C was
4972 originally designed to be a nice abstract layer on top of assembly
4973 language, for writing kernels and basic system utilities rather than
4974 large applications.
4975
4976   Lisp objects can be created by any of a number of Lisp primitives.
4977 Most object types have one or a small number of basic primitives
4978 for creating objects.  For conses, the basic primitive is @code{cons};
4979 for vectors, the primitives are @code{make-vector} and @code{vector}; for
4980 symbols, the primitives are @code{make-symbol} and @code{intern}; etc.
4981 Some Lisp objects, especially those that are primarily used internally,
4982 have no corresponding Lisp primitives.  Every Lisp object, though,
4983 has at least one C primitive for creating it.
4984
4985   Recall from section (VII) that a Lisp object, as stored in a 32-bit or
4986 64-bit word, has a few tag bits, and a ``value'' that occupies the
4987 remainder of the bits.  We can separate the different Lisp object types
4988 into three broad categories:
4989
4990 @itemize @bullet
4991 @item
4992 (a) Those for whom the value directly represents the contents of the
4993 Lisp object.  Only two types are in this category: integers and
4994 characters.  No special allocation or garbage collection is necessary
4995 for such objects.  Lisp objects of these types do not need to be
4996 @code{GCPRO}ed.
4997 @end itemize
4998
4999   In the remaining two categories, the type is stored in the object
5000 itself.  The tag for all such objects is the generic @dfn{lrecord}
5001 (Lisp_Type_Record) tag.  The first bytes of the object's structure are an
5002 integer (actually a char) characterising the object's type and some
5003 flags, in particular the mark bit used for garbage collection.  A
5004 structure describing the type is accessible thru the
5005 lrecord_implementation_table indexed with said integer.  This structure
5006 includes the method pointers and a pointer to a string naming the type.
5007
5008 @itemize @bullet
5009 @item
5010 (b) Those lrecords that are allocated in frob blocks (see above).  This
5011 includes the objects that are most common and relatively small, and
5012 includes conses, strings, subrs, floats, compiled functions, symbols,
5013 extents, events, and markers.  With the cleanup of frob blocks done in
5014 19.12, it's not terribly hard to add more objects to this category, but
5015 it's a bit trickier than adding an object type to type (c) (esp. if the
5016 object needs a finalization method), and is not likely to save much
5017 space unless the object is small and there are many of them. (In fact,
5018 if there are very few of them, it might actually waste space.)
5019 @item
5020 (c) Those lrecords that are individually @code{malloc()}ed.  These are
5021 called @dfn{lcrecords}.  All other types are in this category.  Adding a
5022 new type to this category is comparatively easy, and all types added
5023 since 19.8 (when the current allocation scheme was devised, by Richard
5024 Mlynarik), with the exception of the character type, have been in this
5025 category.
5026 @end itemize
5027
5028   Note that bit vectors are a bit of a special case.  They are
5029 simple lrecords as in category (b), but are individually @code{malloc()}ed
5030 like vectors.  You can basically view them as exactly like vectors
5031 except that their type is stored in lrecord fashion rather than
5032 in directly-tagged fashion.
5033
5034
5035 @node Garbage Collection
5036 @section Garbage Collection
5037 @cindex garbage collection
5038
5039 @cindex mark and sweep
5040   Garbage collection is simple in theory but tricky to implement.
5041 Emacs Lisp uses the oldest garbage collection method, called
5042 @dfn{mark and sweep}.  Garbage collection begins by starting with
5043 all accessible locations (i.e. all variables and other slots where
5044 Lisp objects might occur) and recursively traversing all objects
5045 accessible from those slots, marking each one that is found.
5046 We then go through all of memory and free each object that is
5047 not marked, and unmarking each object that is marked.  Note
5048 that ``all of memory'' means all currently allocated objects.
5049 Traversing all these objects means traversing all frob blocks,
5050 all vectors (which are chained in one big list), and all
5051 lcrecords (which are likewise chained).
5052
5053   Garbage collection can be invoked explicitly by calling
5054 @code{garbage-collect} but is also called automatically by @code{eval},
5055 once a certain amount of memory has been allocated since the last
5056 garbage collection (according to @code{gc-cons-threshold}).
5057
5058
5059 @node GCPROing
5060 @section @code{GCPRO}ing
5061 @cindex @code{GCPRO}ing
5062 @cindex garbage collection protection
5063 @cindex protection, garbage collection
5064
5065 @code{GCPRO}ing is one of the ugliest and trickiest parts of Emacs
5066 internals.  The basic idea is that whenever garbage collection
5067 occurs, all in-use objects must be reachable somehow or
5068 other from one of the roots of accessibility.  The roots
5069 of accessibility are:
5070
5071 @enumerate
5072 @item
5073 All objects that have been @code{staticpro()}d or
5074 @code{staticpro_nodump()}ed.  This is used for any global C variables
5075 that hold Lisp objects.  A call to @code{staticpro()} happens implicitly
5076 as a result of any symbols declared with @code{defsymbol()} and any
5077 variables declared with @code{DEFVAR_FOO()}.  You need to explicitly
5078 call @code{staticpro()} (in the @code{vars_of_foo()} method of a module)
5079 for other global C variables holding Lisp objects. (This typically
5080 includes internal lists and such things.).  Use
5081 @code{staticpro_nodump()} only in the rare cases when you do not want
5082 the pointed variable to be saved at dump time but rather recompute it at
5083 startup.
5084
5085 Note that @code{obarray} is one of the @code{staticpro()}d things.
5086 Therefore, all functions and variables get marked through this.
5087 @item
5088 Any shadowed bindings that are sitting on the @code{specpdl} stack.
5089 @item
5090 Any objects sitting in currently active (Lisp) stack frames,
5091 catches, and condition cases.
5092 @item
5093 A couple of special-case places where active objects are
5094 located.
5095 @item
5096 Anything currently marked with @code{GCPRO}.
5097 @end enumerate
5098
5099   Marking with @code{GCPRO} is necessary because some C functions (quite
5100 a lot, in fact), allocate objects during their operation.  Quite
5101 frequently, there will be no other pointer to the object while the
5102 function is running, and if a garbage collection occurs and the object
5103 needs to be referenced again, bad things will happen.  The solution is
5104 to mark those objects with @code{GCPRO}.  Unfortunately this is easy to
5105 forget, and there is basically no way around this problem.  Here are
5106 some rules, though:
5107
5108 @enumerate
5109 @item
5110 For every @code{GCPRO@var{n}}, there have to be declarations of
5111 @code{struct gcpro gcpro1, gcpro2}, etc.
5112
5113 @item
5114 You @emph{must} @code{UNGCPRO} anything that's @code{GCPRO}ed, and you
5115 @emph{must not} @code{UNGCPRO} if you haven't @code{GCPRO}ed.  Getting
5116 either of these wrong will lead to crashes, often in completely random
5117 places unrelated to where the problem lies.
5118
5119 @item
5120 The way this actually works is that all currently active @code{GCPRO}s
5121 are chained through the @code{struct gcpro} local variables, with the
5122 variable @samp{gcprolist} pointing to the head of the list and the nth
5123 local @code{gcpro} variable pointing to the first @code{gcpro} variable
5124 in the next enclosing stack frame.  Each @code{GCPRO}ed thing is an
5125 lvalue, and the @code{struct gcpro} local variable contains a pointer to
5126 this lvalue.  This is why things will mess up badly if you don't pair up
5127 the @code{GCPRO}s and @code{UNGCPRO}s---you will end up with
5128 @code{gcprolist}s containing pointers to @code{struct gcpro}s or local
5129 @code{Lisp_Object} variables in no-longer-active stack frames.
5130
5131 @item
5132 It is actually possible for a single @code{struct gcpro} to
5133 protect a contiguous array of any number of values, rather than
5134 just a single lvalue.  To effect this, call @code{GCPRO@var{n}} as usual on
5135 the first object in the array and then set @code{gcpro@var{n}.nvars}.
5136
5137 @item
5138 @strong{Strings are relocated.}  What this means in practice is that the
5139 pointer obtained using @code{XSTRING_DATA()} is liable to change at any
5140 time, and you should never keep it around past any function call, or
5141 pass it as an argument to any function that might cause a garbage
5142 collection.  This is why a number of functions accept either a
5143 ``non-relocatable'' @code{char *} pointer or a relocatable Lisp string,
5144 and only access the Lisp string's data at the very last minute.  In some
5145 cases, you may end up having to @code{alloca()} some space and copy the
5146 string's data into it.
5147
5148 @item
5149 By convention, if you have to nest @code{GCPRO}'s, use @code{NGCPRO@var{n}}
5150 (along with @code{struct gcpro ngcpro1, ngcpro2}, etc.), @code{NNGCPRO@var{n}},
5151 etc.  This avoids compiler warnings about shadowed locals.
5152
5153 @item
5154 It is @emph{always} better to err on the side of extra @code{GCPRO}s
5155 rather than too few.  The extra cycles spent on this are
5156 almost never going to make a whit of difference in the
5157 speed of anything.
5158
5159 @item
5160 The general rule to follow is that caller, not callee, @code{GCPRO}s.
5161 That is, you should not have to explicitly @code{GCPRO} any Lisp objects
5162 that are passed in as parameters.
5163
5164 One exception from this rule is if you ever plan to change the parameter
5165 value, and store a new object in it.  In that case, you @emph{must}
5166 @code{GCPRO} the parameter, because otherwise the new object will not be
5167 protected.
5168
5169 So, if you create any Lisp objects (remember, this happens in all sorts
5170 of circumstances, e.g. with @code{Fcons()}, etc.), you are responsible
5171 for @code{GCPRO}ing them, unless you are @emph{absolutely sure} that
5172 there's no possibility that a garbage-collection can occur while you
5173 need to use the object.  Even then, consider @code{GCPRO}ing.
5174
5175 @item
5176 A garbage collection can occur whenever anything calls @code{Feval}, or
5177 whenever a QUIT can occur where execution can continue past
5178 this. (Remember, this is almost anywhere.)
5179
5180 @item
5181 If you have the @emph{least smidgeon of doubt} about whether
5182 you need to @code{GCPRO}, you should @code{GCPRO}.
5183
5184 @item
5185 Beware of @code{GCPRO}ing something that is uninitialized.  If you have
5186 any shade of doubt about this, initialize all your variables to @code{Qnil}.
5187
5188 @item
5189 Be careful of traps, like calling @code{Fcons()} in the argument to
5190 another function.  By the ``caller protects'' law, you should be
5191 @code{GCPRO}ing the newly-created cons, but you aren't.  A certain
5192 number of functions that are commonly called on freshly created stuff
5193 (e.g. @code{nconc2()}, @code{Fsignal()}), break the ``caller protects''
5194 law and go ahead and @code{GCPRO} their arguments so as to simplify
5195 things, but make sure and check if it's OK whenever doing something like
5196 this.
5197
5198 @item
5199 Once again, remember to @code{GCPRO}!  Bugs resulting from insufficient
5200 @code{GCPRO}ing are intermittent and extremely difficult to track down,
5201 often showing up in crashes inside of @code{garbage-collect} or in
5202 weirdly corrupted objects or even in incorrect values in a totally
5203 different section of code.
5204 @end enumerate
5205
5206 If you don't understand whether to @code{GCPRO} in a particular
5207 instance, ask on the mailing lists.  A general hint is that @code{prog1}
5208 is the canonical example
5209
5210 @cindex garbage collection, conservative
5211 @cindex conservative garbage collection
5212   Given the extremely error-prone nature of the @code{GCPRO} scheme, and
5213 the difficulties in tracking down, it should be considered a deficiency
5214 in the XEmacs code.  A solution to this problem would involve
5215 implementing so-called @dfn{conservative} garbage collection for the C
5216 stack.  That involves looking through all of stack memory and treating
5217 anything that looks like a reference to an object as a reference.  This
5218 will result in a few objects not getting collected when they should, but
5219 it obviates the need for @code{GCPRO}ing, and allows garbage collection
5220 to happen at any point at all, such as during object allocation.
5221
5222 @node Garbage Collection - Step by Step
5223 @section Garbage Collection - Step by Step
5224 @cindex garbage collection - step by step
5225
5226 @menu
5227 * Invocation::
5228 * garbage_collect_1::
5229 * mark_object::
5230 * gc_sweep::
5231 * sweep_lcrecords_1::
5232 * compact_string_chars::
5233 * sweep_strings::
5234 * sweep_bit_vectors_1::
5235 @end menu
5236
5237 @node Invocation
5238 @subsection Invocation
5239 @cindex garbage collection, invocation
5240
5241 The first thing that anyone should know about garbage collection is:
5242 when and how the garbage collector is invoked. One might think that this
5243 could happen every time new memory is allocated, e.g. new objects are
5244 created, but this is @emph{not} the case. Instead, we have the following
5245 situation:
5246
5247 The entry point of any process of garbage collection is an invocation
5248 of the function @code{garbage_collect_1} in file @code{alloc.c}. The
5249 invocation can occur @emph{explicitly} by calling the function
5250 @code{Fgarbage_collect} (in addition this function provides information
5251 about the freed memory), or can occur @emph{implicitly} in four different
5252 situations:
5253 @enumerate
5254 @item
5255 In function @code{main_1} in file @code{emacs.c}. This function is called
5256 at each startup of xemacs. The garbage collection is invoked after all
5257 initial creations are completed, but only if a special internal error
5258 checking-constant @code{ERROR_CHECK_GC} is defined.
5259 @item
5260 In function @code{disksave_object_finalization} in file
5261 @code{alloc.c}. The only purpose of this function is to clear the
5262 objects from memory which need not be stored with xemacs when we dump out
5263 an executable. This is only done by @code{Fdump_emacs} or by
5264 @code{Fdump_emacs_data} respectively (both in @code{emacs.c}). The
5265 actual clearing is accomplished by making these objects unreachable and
5266 starting a garbage collection. The function is only used while building
5267 xemacs.
5268 @item
5269 In function @code{Feval / eval} in file @code{eval.c}. Each time the
5270 well known and often used function eval is called to evaluate a form,
5271 one of the first things that could happen, is a potential call of
5272 @code{garbage_collect_1}. There exist three global variables,
5273 @code{consing_since_gc} (counts the created cons-cells since the last
5274 garbage collection), @code{gc_cons_threshold} (a specified threshold
5275 after which a garbage collection occurs) and @code{always_gc}. If
5276 @code{always_gc} is set or if the threshold is exceeded, the garbage
5277 collection will start.
5278 @item
5279 In function @code{Ffuncall / funcall} in file @code{eval.c}. This
5280 function evaluates calls of elisp functions and works according to
5281 @code{Feval}.
5282 @end enumerate
5283
5284 The upshot is that garbage collection can basically occur everywhere
5285 @code{Feval}, respectively @code{Ffuncall}, is used - either directly or
5286 through another function. Since calls to these two functions are hidden
5287 in various other functions, many calls to @code{garbage_collect_1} are
5288 not obviously foreseeable, and therefore unexpected. Instances where
5289 they are used that are worth remembering are various elisp commands, as
5290 for example @code{or}, @code{and}, @code{if}, @code{cond}, @code{while},
5291 @code{setq}, etc., miscellaneous @code{gui_item_...} functions,
5292 everything related to @code{eval} (@code{Feval_buffer}, @code{call0},
5293 ...) and inside @code{Fsignal}. The latter is used to handle signals, as
5294 for example the ones raised by every @code{QUIT}-macro triggered after
5295 pressing Ctrl-g.
5296
5297 @node garbage_collect_1
5298 @subsection @code{garbage_collect_1}
5299 @cindex @code{garbage_collect_1}
5300
5301 We can now describe exactly what happens after the invocation takes
5302 place.
5303 @enumerate
5304 @item
5305 There are several cases in which the garbage collector is left immediately:
5306 when we are already garbage collecting (@code{gc_in_progress}), when
5307 the garbage collection is somehow forbidden
5308 (@code{gc_currently_forbidden}), when we are currently displaying something
5309 (@code{in_display}) or when we are preparing for the armageddon of the
5310 whole system (@code{preparing_for_armageddon}).
5311 @item
5312 Next the correct frame in which to put
5313 all the output occurring during garbage collecting is determined. In
5314 order to be able to restore the old display's state after displaying the
5315 message, some data about the current cursor position has to be
5316 saved. The variables @code{pre_gc_cursor} and @code{cursor_changed} take
5317 care of that.
5318 @item
5319 The state of @code{gc_currently_forbidden} must be restored after
5320 the garbage collection, no matter what happens during the process. We
5321 accomplish this by @code{record_unwind_protect}ing the suitable function
5322 @code{restore_gc_inhibit} together with the current value of
5323 @code{gc_currently_forbidden}.
5324 @item
5325 If we are concurrently running an interactive xemacs session, the next step
5326 is simply to show the garbage collector's cursor/message.
5327 @item
5328 The following steps are the intrinsic steps of the garbage collector,
5329 therefore @code{gc_in_progress} is set.
5330 @item
5331 For debugging purposes, it is possible to copy the current C stack
5332 frame. However, this seems to be a currently unused feature.
5333 @item
5334 Before actually starting to go over all live objects, references to
5335 objects that are no longer used are pruned. We only have to do this for events
5336 (@code{clear_event_resource}) and for specifiers
5337 (@code{cleanup_specifiers}).
5338 @item
5339 Now the mark phase begins and marks all accessible elements. In order to
5340 start from
5341 all slots that serve as roots of accessibility, the function
5342 @code{mark_object} is called for each root individually to go out from
5343 there to mark all reachable objects. All roots that are traversed are
5344 shown in their processed order:
5345 @itemize @bullet
5346 @item
5347 all constant symbols and static variables that are registered via
5348 @code{staticpro}@ in the dynarr @code{staticpros}.
5349 @xref{Adding Global Lisp Variables}.
5350 @item
5351 all Lisp objects that are created in C functions and that must be
5352 protected from freeing them. They are registered in the global
5353 list @code{gcprolist}.
5354 @xref{GCPROing}.
5355 @item
5356 all local variables (i.e. their name fields @code{symbol} and old
5357 values @code{old_values}) that are bound during the evaluation by the Lisp
5358 engine. They are stored in @code{specbinding} structs pushed on a stack
5359 called @code{specpdl}.
5360 @xref{Dynamic Binding; The specbinding Stack; Unwind-Protects}.
5361 @item
5362 all catch blocks that the Lisp engine encounters during the evaluation
5363 cause the creation of structs @code{catchtag} inserted in the list
5364 @code{catchlist}. Their tag (@code{tag}) and value (@code{val} fields
5365 are freshly created objects and therefore have to be marked.
5366 @xref{Catch and Throw}.
5367 @item
5368 every function application pushes new structs @code{backtrace}
5369 on the call stack of the Lisp engine (@code{backtrace_list}). The unique
5370 parts that have to be marked are the fields for each function
5371 (@code{function}) and all their arguments (@code{args}).
5372 @xref{Evaluation}.
5373 @item
5374 all objects that are used by the redisplay engine that must not be freed
5375 are marked by a special function called @code{mark_redisplay} (in
5376 @code{redisplay.c}).
5377 @item
5378 all objects created for profiling purposes are allocated by C functions
5379 instead of using the lisp allocation mechanisms. In order to receive the
5380 right ones during the sweep phase, they also have to be marked
5381 manually. That is done by the function @code{mark_profiling_info}
5382 @end itemize
5383 @item
5384 Hash tables in XEmacs belong to a kind of special objects that
5385 make use of a concept often called 'weak pointers'.
5386 To make a long story short, these kind of pointers are not followed
5387 during the estimation of the live objects during garbage collection.
5388 Any object referenced only by weak pointers is collected
5389 anyway, and the reference to it is cleared. In hash tables there are
5390 different usage patterns of them, manifesting in different types of hash
5391 tables, namely 'non-weak', 'weak', 'key-weak' and 'value-weak'
5392 (internally also 'key-car-weak' and 'value-car-weak') hash tables, each
5393 clearing entries depending on different conditions. More information can
5394 be found in the documentation to the function @code{make-hash-table}.
5395
5396 Because there are complicated dependency rules about when and what to
5397 mark while processing weak hash tables, the standard @code{marker}
5398 method is only active if it is marking non-weak hash tables. As soon as
5399 a weak component is in the table, the hash table entries are ignored
5400 while marking. Instead their marking is done each separately by the
5401 function @code{finish_marking_weak_hash_tables}. This function iterates
5402 over each hash table entry @code{hentries} for each weak hash table in
5403 @code{Vall_weak_hash_tables}. Depending on the type of a table, the
5404 appropriate action is performed.
5405 If a table is acting as @code{HASH_TABLE_KEY_WEAK}, and a key already marked,
5406 everything reachable from the @code{value} component is marked. If it is
5407 acting as a @code{HASH_TABLE_VALUE_WEAK} and the value component is
5408 already marked, the marking starts beginning only from the
5409 @code{key} component.
5410 If it is a @code{HASH_TABLE_KEY_CAR_WEAK} and the car
5411 of the key entry is already marked, we mark both the @code{key} and
5412 @code{value} components.
5413 Finally, if the table is of the type @code{HASH_TABLE_VALUE_CAR_WEAK}
5414 and the car of the value components is already marked, again both the
5415 @code{key} and the @code{value} components get marked.
5416
5417 Again, there are lists with comparable properties called weak
5418 lists. There exist different peculiarities of their types called
5419 @code{simple}, @code{assoc}, @code{key-assoc} and
5420 @code{value-assoc}. You can find further details about them in the
5421 description to the function @code{make-weak-list}. The scheme of their
5422 marking is similar: all weak lists are listed in @code{Qall_weak_lists},
5423 therefore we iterate over them. The marking is advanced until we hit an
5424 already marked pair. Then we know that during a former run all
5425 the rest has been marked completely. Again, depending on the special
5426 type of the weak list, our jobs differ. If it is a @code{WEAK_LIST_SIMPLE}
5427 and the elem is marked, we mark the @code{cons} part. If it is a
5428 @code{WEAK_LIST_ASSOC} and not a pair or a pair with both marked car and
5429 cdr, we mark the @code{cons} and the @code{elem}. If it is a
5430 @code{WEAK_LIST_KEY_ASSOC} and not a pair or a pair with a marked car of
5431 the elem, we mark the @code{cons} and the @code{elem}. Finally, if it is
5432 a @code{WEAK_LIST_VALUE_ASSOC} and not a pair or a pair with a marked
5433 cdr of the elem, we mark both the @code{cons} and the @code{elem}.
5434
5435 Since, by marking objects in reach from weak hash tables and weak lists,
5436 other objects could get marked, this perhaps implies further marking of
5437 other weak objects, both finishing functions are redone as long as
5438 yet unmarked objects get freshly marked.
5439
5440 @item
5441 After completing the special marking for the weak hash tables and for the weak
5442 lists, all entries that point to objects that are going to be swept in
5443 the further process are useless, and therefore have to be removed from
5444 the table or the list.
5445
5446 The function @code{prune_weak_hash_tables} does the job for weak hash
5447 tables. Totally unmarked hash tables are removed from the list
5448 @code{Vall_weak_hash_tables}. The other ones are treated more carefully
5449 by scanning over all entries and removing one as soon as one of
5450 the components @code{key} and @code{value} is unmarked.
5451
5452 The same idea applies to the weak lists. It is accomplished by
5453 @code{prune_weak_lists}: An unmarked list is pruned from
5454 @code{Vall_weak_lists} immediately. A marked list is treated more
5455 carefully by going over it and removing just the unmarked pairs.
5456
5457 @item
5458 The function @code{prune_specifiers} checks all listed specifiers held
5459 in @code{Vall_specifiers} and removes the ones from the lists that are
5460 unmarked.
5461
5462 @item
5463 All syntax tables are stored in a list called
5464 @code{Vall_syntax_tables}. The function @code{prune_syntax_tables} walks
5465 through it and unlinks the tables that are unmarked.
5466
5467 @item
5468 Next, we will attack the complete sweeping - the function
5469 @code{gc_sweep} which holds the predominance.
5470 @item
5471 First, all the variables with respect to garbage collection are
5472 reset. @code{consing_since_gc} - the counter of the created cells since
5473 the last garbage collection - is set back to 0, and
5474 @code{gc_in_progress} is not @code{true} anymore.
5475 @item
5476 In case the session is interactive, the displayed cursor and message are
5477 removed again.
5478 @item
5479 The state of @code{gc_inhibit} is restored to the former value by
5480 unwinding the stack.
5481 @item
5482 A small memory reserve is always held back that can be reached by
5483 @code{breathing_space}. If nothing more is left, we create a new reserve
5484 and exit.
5485 @end enumerate
5486
5487 @node mark_object
5488 @subsection @code{mark_object}
5489 @cindex @code{mark_object}
5490
5491 The first thing that is checked while marking an object is whether the
5492 object is a real Lisp object @code{Lisp_Type_Record} or just an integer
5493 or a character. Integers and characters are the only two types that are
5494 stored directly - without another level of indirection, and therefore they
5495 don't have to be marked and collected.
5496 @xref{How Lisp Objects Are Represented in C}.
5497
5498 The second case is the one we have to handle. It is the one when we are
5499 dealing with a pointer to a Lisp object. But, there exist also three
5500 possibilities, that prevent us from doing anything while marking: The
5501 object is read only which prevents it from being garbage collected,
5502 i.e. marked (@code{C_READONLY_RECORD_HEADER}). The object in question is
5503 already marked, and need not be marked for the second time (checked by
5504 @code{MARKED_RECORD_HEADER_P}). If it is a special, unmarkable object
5505 (@code{UNMARKABLE_RECORD_HEADER_P}, apparently, these are objects that
5506 sit in some const space, and can therefore not be marked, see
5507 @code{this_one_is_unmarkable} in @code{alloc.c}).
5508
5509 Now, the actual marking is feasible. We do so by once using the macro
5510 @code{MARK_RECORD_HEADER} to mark the object itself (actually the
5511 special flag in the lrecord header), and calling its special marker
5512 "method" @code{marker} if available. The marker method marks every
5513 other object that is in reach from our current object. Note, that these
5514 marker methods should not call @code{mark_object} recursively, but
5515 instead should return the next object from where further marking has to
5516 be performed.
5517
5518 In case another object was returned, as mentioned before, we reiterate
5519 the whole @code{mark_object} process beginning with this next object.
5520
5521 @node gc_sweep
5522 @subsection @code{gc_sweep}
5523 @cindex @code{gc_sweep}
5524
5525 The job of this function is to free all unmarked records from memory. As
5526 we know, there are different types of objects implemented and managed, and
5527 consequently different ways to free them from memory.
5528 @xref{Introduction to Allocation}.
5529
5530 We start with all objects stored through @code{lcrecords}. All
5531 bulkier objects are allocated and handled using that scheme of
5532 @code{lcrecords}. Each object is @code{malloc}ed separately
5533 instead of placing it in one of the contiguous frob blocks. All types
5534 that are currently stored
5535 using @code{lcrecords}'s  @code{alloc_lcrecord} and
5536 @code{make_lcrecord_list} are the types: vectors, buffers,
5537 char-table, char-table-entry, console, weak-list, database, device,
5538 ldap, hash-table, command-builder, extent-auxiliary, extent-info, face,
5539 coding-system, frame, image-instance, glyph, popup-data, gui-item,
5540 keymap, charset, color_instance, font_instance, opaque, opaque-list,
5541 process, range-table, specifier, symbol-value-buffer-local,
5542 symbol-value-lisp-magic, symbol-value-varalias, toolbar-button,
5543 tooltalk-message, tooltalk-pattern, window, and window-configuration. We
5544 take care of them in the fist place
5545 in order to be able to handle and to finalize items stored in them more
5546 easily. The function @code{sweep_lcrecords_1} as described below is
5547 doing the whole job for us.
5548 For a description about the internals: @xref{lrecords}.
5549
5550 Our next candidates are the other objects that behave quite differently
5551 than everything else: the strings. They consists of two parts, a
5552 fixed-size portion (@code{struct Lisp_String}) holding the string's
5553 length, its property list and a pointer to the second part, and the
5554 actual string data, which is stored in string-chars blocks comparable to
5555 frob blocks. In this block, the data is not only freed, but also a
5556 compression of holes is made, i.e. all strings are relocated together.
5557 @xref{String}. This compacting phase is performed by the function
5558 @code{compact_string_chars}, the actual sweeping by the function
5559 @code{sweep_strings} is described below.
5560
5561 After that, the other types are swept step by step using functions
5562 @code{sweep_conses}, @code{sweep_bit_vectors_1},
5563 @code{sweep_compiled_functions}, @code{sweep_floats},
5564 @code{sweep_symbols}, @code{sweep_extents}, @code{sweep_markers} and
5565 @code{sweep_extents}.  They are the fixed-size types cons, floats,
5566 compiled-functions, symbol, marker, extent, and event stored in
5567 so-called "frob blocks", and therefore we can basically do the same on
5568 every type objects, using the same macros, especially defined only to
5569 handle everything with respect to fixed-size blocks. The only fixed-size
5570 type that is not handled here are the fixed-size portion of strings,
5571 because we took special care of them earlier.
5572
5573 The only big exceptions are bit vectors stored differently and
5574 therefore treated differently by the function @code{sweep_bit_vectors_1}
5575 described later.
5576
5577 At first, we need some brief information about how
5578 these fixed-size types are managed in general, in order to understand
5579 how the sweeping is done. They have all a fixed size, and are therefore
5580 stored in big blocks of memory - allocated at once - that can hold a
5581 certain amount of objects of one type. The macro
5582 @code{DECLARE_FIXED_TYPE_ALLOC} creates the suitable structures for
5583 every type. More precisely, we have the block struct
5584 (holding a pointer to the previous block @code{prev} and the
5585 objects in @code{block[]}), a pointer to current block
5586 (@code{current_..._block)}) and its last index
5587 (@code{current_..._block_index}), and a pointer to the free list that
5588 will be created. Also a macro @code{FIXED_TYPE_FROM_BLOCK} plus some
5589 related macros exists that are used to obtain a new object, either from
5590 the free list @code{ALLOCATE_FIXED_TYPE_1} if there is an unused object
5591 of that type stored or by allocating a completely new block using
5592 @code{ALLOCATE_FIXED_TYPE_FROM_BLOCK}.
5593
5594 The rest works as follows: all of them define a
5595 macro @code{UNMARK_...} that is used to unmark the object. They define a
5596 macro @code{ADDITIONAL_FREE_...} that defines additional work that has
5597 to be done when converting an object from in use to not in use (so far,
5598 only markers use it in order to unchain them). Then, they all call
5599 the macro @code{SWEEP_FIXED_TYPE_BLOCK} instantiated with their type name
5600 and their struct name.
5601
5602 This call in particular does the following: we go over all blocks
5603 starting with the current moving towards the oldest.
5604 For each block, we look at every object in it. If the object already
5605 freed (checked with @code{FREE_STRUCT_P} using the first pointer of the
5606 object), or if it is
5607 set to read only (@code{C_READONLY_RECORD_HEADER_P}, nothing must be
5608 done. If it is unmarked (checked with @code{MARKED_RECORD_HEADER_P}), it
5609 is put in the free list and set free (using the macro
5610 @code{FREE_FIXED_TYPE}, otherwise it stays in the block, but is unmarked
5611 (by @code{UNMARK_...}). While going through one block, we note if the
5612 whole block is empty. If so, the whole block is freed (using
5613 @code{xfree}) and the free list state is set to the state it had before
5614 handling this block.
5615
5616 @node sweep_lcrecords_1
5617 @subsection @code{sweep_lcrecords_1}
5618 @cindex @code{sweep_lcrecords_1}
5619
5620 After nullifying the complete lcrecord statistics, we go over all
5621 lcrecords two separate times. They are all chained together in a list with
5622 a head called @code{all_lcrecords}.
5623
5624 The first loop calls for each object its @code{finalizer} method, but only
5625 in the case that it is not read only
5626 (@code{C_READONLY_RECORD_HEADER_P)}, it is not already marked
5627 (@code{MARKED_RECORD_HEADER_P}), it is not already in a free list (list of
5628 freed objects, field @code{free}) and finally it owns a finalizer
5629 method.
5630
5631 The second loop actually frees the appropriate objects again by iterating
5632 through the whole list. In case an object is read only or marked, it
5633 has to persist, otherwise it is manually freed by calling
5634 @code{xfree}. During this loop, the lcrecord statistics are kept up to
5635 date by calling @code{tick_lcrecord_stats} with the right arguments,
5636
5637 @node compact_string_chars
5638 @subsection @code{compact_string_chars}
5639 @cindex @code{compact_string_chars}
5640
5641 The purpose of this function is to compact all the data parts of the
5642 strings that are held in so-called @code{string_chars_block}, i.e. the
5643 strings that do not exceed a certain maximal length.
5644
5645 The procedure with which this is done is as follows. We are keeping two
5646 positions in the @code{string_chars_block}s using two pointer/integer
5647 pairs, namely @code{from_sb}/@code{from_pos} and
5648 @code{to_sb}/@code{to_pos}. They stand for the actual positions, from
5649 where to where, to copy the actually handled string.
5650
5651 While going over all chained @code{string_char_block}s and their held
5652 strings, staring at @code{first_string_chars_block}, both pointers
5653 are advanced and eventually a string is copied from @code{from_sb} to
5654 @code{to_sb}, depending on the status of the pointed at strings.
5655
5656 More precisely, we can distinguish between the following actions.
5657 @itemize @bullet
5658 @item
5659 The string at @code{from_sb}'s position could be marked as free, which
5660 is indicated by an invalid pointer to the pointer that should point back
5661 to the fixed size string object, and which is checked by
5662 @code{FREE_STRUCT_P}. In this case, the @code{from_sb}/@code{from_pos}
5663 is advanced to the next string, and nothing has to be copied.
5664 @item
5665 Also, if a string object itself is unmarked, nothing has to be
5666 copied. We likewise advance the @code{from_sb}/@code{from_pos}
5667 pair as described above.
5668 @item
5669 In all other cases, we have a marked string at hand. The string data
5670 must be moved from the from-position to the to-position. In case
5671 there is not enough space in the actual @code{to_sb}-block, we advance
5672 this pointer to the beginning of the next block before copying. In case the
5673 from and to positions are different, we perform the
5674 actual copying using the library function @code{memmove}.
5675 @end itemize
5676
5677 After compacting, the pointer to the current
5678 @code{string_chars_block}, sitting in @code{current_string_chars_block},
5679 is reset on the last block to which we moved a string,
5680 i.e. @code{to_block}, and all remaining blocks (we know that they just
5681 carry garbage) are explicitly @code{xfree}d.
5682
5683 @node sweep_strings
5684 @subsection @code{sweep_strings}
5685 @cindex @code{sweep_strings}
5686
5687 The sweeping for the fixed sized string objects is essentially exactly
5688 the same as it is for all other fixed size types. As before, the freeing
5689 into the suitable free list is done by using the macro
5690 @code{SWEEP_FIXED_SIZE_BLOCK} after defining the right macros
5691 @code{UNMARK_string} and @code{ADDITIONAL_FREE_string}. These two
5692 definitions are a little bit special compared to the ones used
5693 for the other fixed size types.
5694
5695 @code{UNMARK_string} is defined the same way except some additional code
5696 used for updating the bookkeeping information.
5697
5698 For strings, @code{ADDITIONAL_FREE_string} has to do something in
5699 addition: in case, the string was not allocated in a
5700 @code{string_chars_block} because it exceeded the maximal length, and
5701 therefore it was @code{malloc}ed separately, we know also @code{xfree}
5702 it explicitly.
5703
5704 @node sweep_bit_vectors_1
5705 @subsection @code{sweep_bit_vectors_1}
5706 @cindex @code{sweep_bit_vectors_1}
5707
5708 Bit vectors are also one of the rare types that are @code{malloc}ed
5709 individually. Consequently, while sweeping, all further needless
5710 bit vectors must be freed by hand. This is done, as one might imagine,
5711 the expected way: since they are all registered in a list called
5712 @code{all_bit_vectors}, all elements of that list are traversed,
5713 all unmarked bit vectors are unlinked by calling @code{xfree} and all of
5714 them become unmarked.
5715 In addition, the bookkeeping information used for garbage
5716 collector's output purposes is updated.
5717
5718 @node Integers and Characters
5719 @section Integers and Characters
5720 @cindex integers and characters
5721 @cindex characters, integers and
5722
5723   Integer and character Lisp objects are created from integers using the
5724 macros @code{XSETINT()} and @code{XSETCHAR()} or the equivalent
5725 functions @code{make_int()} and @code{make_char()}. (These are actually
5726 macros on most systems.)  These functions basically just do some moving
5727 of bits around, since the integral value of the object is stored
5728 directly in the @code{Lisp_Object}.
5729
5730   @code{XSETINT()} and the like will truncate values given to them that
5731 are too big; i.e. you won't get the value you expected but the tag bits
5732 will at least be correct.
5733
5734 @node Allocation from Frob Blocks
5735 @section Allocation from Frob Blocks
5736 @cindex allocation from frob blocks
5737 @cindex frob blocks, allocation from
5738
5739 The uninitialized memory required by a @code{Lisp_Object} of a particular type
5740 is allocated using
5741 @code{ALLOCATE_FIXED_TYPE()}.  This only occurs inside of the
5742 lowest-level object-creating functions in @file{alloc.c}:
5743 @code{Fcons()}, @code{make_float()}, @code{Fmake_byte_code()},
5744 @code{Fmake_symbol()}, @code{allocate_extent()},
5745 @code{allocate_event()}, @code{Fmake_marker()}, and
5746 @code{make_uninit_string()}.  The idea is that, for each type, there are
5747 a number of frob blocks (each 2K in size); each frob block is divided up
5748 into object-sized chunks.  Each frob block will have some of these
5749 chunks that are currently assigned to objects, and perhaps some that are
5750 free. (If a frob block has nothing but free chunks, it is freed at the
5751 end of the garbage collection cycle.)  The free chunks are stored in a
5752 free list, which is chained by storing a pointer in the first four bytes
5753 of the chunk. (Except for the free chunks at the end of the last frob
5754 block, which are handled using an index which points past the end of the
5755 last-allocated chunk in the last frob block.)
5756 @code{ALLOCATE_FIXED_TYPE()} first tries to retrieve a chunk from the
5757 free list; if that fails, it calls
5758 @code{ALLOCATE_FIXED_TYPE_FROM_BLOCK()}, which looks at the end of the
5759 last frob block for space, and creates a new frob block if there is
5760 none. (There are actually two versions of these macros, one of which is
5761 more defensive but less efficient and is used for error-checking.)
5762
5763 @node lrecords
5764 @section lrecords
5765 @cindex lrecords
5766
5767   [see @file{lrecord.h}]
5768
5769   All lrecords have at the beginning of their structure a @code{struct
5770 lrecord_header}.  This just contains a type number and some flags,
5771 including the mark bit.  All builtin type numbers are defined as
5772 constants in @code{enum lrecord_type}, to allow the compiler to generate
5773 more efficient code for @code{@var{type}P}.  The type number, thru the
5774 @code{lrecord_implementation_table}, gives access to a @code{struct
5775 lrecord_implementation}, which is a structure containing method pointers
5776 and such.  There is one of these for each type, and it is a global,
5777 constant, statically-declared structure that is declared in the
5778 @code{DEFINE_LRECORD_IMPLEMENTATION()} macro.
5779
5780   Simple lrecords (of type (b) above) just have a @code{struct
5781 lrecord_header} at their beginning.  lcrecords, however, actually have a
5782 @code{struct lcrecord_header}.  This, in turn, has a @code{struct
5783 lrecord_header} at its beginning, so sanity is preserved; but it also
5784 has a pointer used to chain all lcrecords together, and a special ID
5785 field used to distinguish one lcrecord from another. (This field is used
5786 only for debugging and could be removed, but the space gain is not
5787 significant.)
5788
5789   Simple lrecords are created using @code{ALLOCATE_FIXED_TYPE()}, just
5790 like for other frob blocks.  The only change is that the implementation
5791 pointer must be initialized correctly. (The implementation structure for
5792 an lrecord, or rather the pointer to it, is named @code{lrecord_float},
5793 @code{lrecord_extent}, @code{lrecord_buffer}, etc.)
5794
5795   lcrecords are created using @code{alloc_lcrecord()}.  This takes a
5796 size to allocate and an implementation pointer. (The size needs to be
5797 passed because some lcrecords, such as window configurations, are of
5798 variable size.) This basically just @code{malloc()}s the storage,
5799 initializes the @code{struct lcrecord_header}, and chains the lcrecord
5800 onto the head of the list of all lcrecords, which is stored in the
5801 variable @code{all_lcrecords}.  The calls to @code{alloc_lcrecord()}
5802 generally occur in the lowest-level allocation function for each lrecord
5803 type.
5804
5805 Whenever you create an lrecord, you need to call either
5806 @code{DEFINE_LRECORD_IMPLEMENTATION()} or
5807 @code{DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION()}.  This needs to be
5808 specified in a @file{.c} file, at the top level.  What this actually
5809 does is define and initialize the implementation structure for the
5810 lrecord. (And possibly declares a function @code{error_check_foo()} that
5811 implements the @code{XFOO()} macro when error-checking is enabled.)  The
5812 arguments to the macros are the actual type name (this is used to
5813 construct the C variable name of the lrecord implementation structure
5814 and related structures using the @samp{##} macro concatenation
5815 operator), a string that names the type on the Lisp level (this may not
5816 be the same as the C type name; typically, the C type name has
5817 underscores, while the Lisp string has dashes), various method pointers,
5818 and the name of the C structure that contains the object.  The methods
5819 are used to encapsulate type-specific information about the object, such
5820 as how to print it or mark it for garbage collection, so that it's easy
5821 to add new object types without having to add a specific case for each
5822 new type in a bunch of different places.
5823
5824   The difference between @code{DEFINE_LRECORD_IMPLEMENTATION()} and
5825 @code{DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION()} is that the former is
5826 used for fixed-size object types and the latter is for variable-size
5827 object types.  Most object types are fixed-size; some complex
5828 types, however (e.g. window configurations), are variable-size.
5829 Variable-size object types have an extra method, which is called
5830 to determine the actual size of a particular object of that type.
5831 (Currently this is only used for keeping allocation statistics.)
5832
5833   For the purpose of keeping allocation statistics, the allocation
5834 engine keeps a list of all the different types that exist.  Note that,
5835 since @code{DEFINE_LRECORD_IMPLEMENTATION()} is a macro that is
5836 specified at top-level, there is no way for it to initialize the global
5837 data structures containing type information, like
5838 @code{lrecord_implementations_table}.  For this reason a call to
5839 @code{INIT_LRECORD_IMPLEMENTATION} must be added to the same source file
5840 containing @code{DEFINE_LRECORD_IMPLEMENTATION}, but instead of to the
5841 top level, to one of the init functions, typically
5842 @code{syms_of_@var{foo}.c}.  @code{INIT_LRECORD_IMPLEMENTATION} must be
5843 called before an object of this type is used.
5844
5845 The type number is also used to index into an array holding the number
5846 of objects of each type and the total memory allocated for objects of
5847 that type.  The statistics in this array are computed during the sweep
5848 stage.  These statistics are returned by the call to
5849 @code{garbage-collect}.
5850
5851   Note that for every type defined with a @code{DEFINE_LRECORD_*()}
5852 macro, there needs to be a @code{DECLARE_LRECORD_IMPLEMENTATION()}
5853 somewhere in a @file{.h} file, and this @file{.h} file needs to be
5854 included by @file{inline.c}.
5855
5856   Furthermore, there should generally be a set of @code{XFOOBAR()},
5857 @code{FOOBARP()}, etc. macros in a @file{.h} (or occasionally @file{.c})
5858 file.  To create one of these, copy an existing model and modify as
5859 necessary.
5860
5861   @strong{Please note:} If you define an lrecord in an external
5862 dynamically-loaded module, you must use @code{DECLARE_EXTERNAL_LRECORD},
5863 @code{DEFINE_EXTERNAL_LRECORD_IMPLEMENTATION}, and
5864 @code{DEFINE_EXTERNAL_LRECORD_SEQUENCE_IMPLEMENTATION} instead of the
5865 non-EXTERNAL forms. These macros will dynamically add new type numbers
5866 to the global enum that records them, whereas the non-EXTERNAL forms
5867 assume that the programmer has already inserted the correct type numbers
5868 into the enum's code at compile-time.
5869
5870   The various methods in the lrecord implementation structure are:
5871
5872 @enumerate
5873 @item
5874 @cindex mark method
5875 A @dfn{mark} method.  This is called during the marking stage and passed
5876 a function pointer (usually the @code{mark_object()} function), which is
5877 used to mark an object.  All Lisp objects that are contained within the
5878 object need to be marked by applying this function to them.  The mark
5879 method should also return a Lisp object, which should be either @code{nil} or
5880 an object to mark. (This can be used in lieu of calling
5881 @code{mark_object()} on the object, to reduce the recursion depth, and
5882 consequently should be the most heavily nested sub-object, such as a
5883 long list.)
5884
5885 @strong{Please note:} When the mark method is called, garbage collection
5886 is in progress, and special precautions need to be taken when accessing
5887 objects; see section (B) above.
5888
5889 If your mark method does not need to do anything, it can be
5890 @code{NULL}.
5891
5892 @item
5893 A @dfn{print} method.  This is called to create a printed representation
5894 of the object, whenever @code{princ}, @code{prin1}, or the like is
5895 called.  It is passed the object, a stream to which the output is to be
5896 directed, and an @code{escapeflag} which indicates whether the object's
5897 printed representation should be @dfn{escaped} so that it is
5898 readable. (This corresponds to the difference between @code{princ} and
5899 @code{prin1}.) Basically, @dfn{escaped} means that strings will have
5900 quotes around them and confusing characters in the strings such as
5901 quotes, backslashes, and newlines will be backslashed; and that special
5902 care will be taken to make symbols print in a readable fashion
5903 (e.g. symbols that look like numbers will be backslashed).  Other
5904 readable objects should perhaps pass @code{escapeflag} on when
5905 sub-objects are printed, so that readability is preserved when necessary
5906 (or if not, always pass in a 1 for @code{escapeflag}).  Non-readable
5907 objects should in general ignore @code{escapeflag}, except that some use
5908 it as an indication that more verbose output should be given.
5909
5910 Sub-objects are printed using @code{print_internal()}, which takes
5911 exactly the same arguments as are passed to the print method.
5912
5913 Literal C strings should be printed using @code{write_c_string()},
5914 or @code{write_string_1()} for non-null-terminated strings.
5915
5916 Functions that do not have a readable representation should check the
5917 @code{print_readably} flag and signal an error if it is set.
5918
5919 If you specify NULL for the print method, the
5920 @code{default_object_printer()} will be used.
5921
5922 @item
5923 A @dfn{finalize} method.  This is called at the beginning of the sweep
5924 stage on lcrecords that are about to be freed, and should be used to
5925 perform any extra object cleanup.  This typically involves freeing any
5926 extra @code{malloc()}ed memory associated with the object, releasing any
5927 operating-system and window-system resources associated with the object
5928 (e.g. pixmaps, fonts), etc.
5929
5930 The finalize method can be NULL if nothing needs to be done.
5931
5932 WARNING #1: The finalize method is also called at the end of the dump
5933 phase; this time with the for_disksave parameter set to non-zero.  The
5934 object is @emph{not} about to disappear, so you have to make sure to
5935 @emph{not} free any extra @code{malloc()}ed memory if you're going to
5936 need it later.  (Also, signal an error if there are any operating-system
5937 and window-system resources here, because they can't be dumped.)
5938
5939 Finalize methods should, as a rule, set to zero any pointers after
5940 they've been freed, and check to make sure pointers are not zero before
5941 freeing.  Although I'm pretty sure that finalize methods are not called
5942 twice on the same object (except for the @code{for_disksave} proviso),
5943 we've gotten nastily burned in some cases by not doing this.
5944
5945 WARNING #2: The finalize method is @emph{only} called for
5946 lcrecords, @emph{not} for simply lrecords.  If you need a
5947 finalize method for simple lrecords, you have to stick
5948 it in the @code{ADDITIONAL_FREE_foo()} macro in @file{alloc.c}.
5949
5950 WARNING #3: Things are in an @emph{extremely} bizarre state
5951 when @code{ADDITIONAL_FREE_foo()} is called, so you have to
5952 be incredibly careful when writing one of these functions.
5953 See the comment in @code{gc_sweep()}.  If you ever have to add
5954 one of these, consider using an lcrecord or dealing with
5955 the problem in a different fashion.
5956
5957 @item
5958 An @dfn{equal} method.  This compares the two objects for similarity,
5959 when @code{equal} is called.  It should compare the contents of the
5960 objects in some reasonable fashion.  It is passed the two objects and a
5961 @dfn{depth} value, which is used to catch circular objects.  To compare
5962 sub-Lisp-objects, call @code{internal_equal()} and bump the depth value
5963 by one.  If this value gets too high, a @code{circular-object} error
5964 will be signaled.
5965
5966 If this is NULL, objects are @code{equal} only when they are @code{eq},
5967 i.e. identical.
5968
5969 @item
5970 A @dfn{hash} method.  This is used to hash objects when they are to be
5971 compared with @code{equal}.  The rule here is that if two objects are
5972 @code{equal}, they @emph{must} hash to the same value; i.e. your hash
5973 function should use some subset of the sub-fields of the object that are
5974 compared in the ``equal'' method.  If you specify this method as
5975 @code{NULL}, the object's pointer will be used as the hash, which will
5976 @emph{fail} if the object has an @code{equal} method, so don't do this.
5977
5978 To hash a sub-Lisp-object, call @code{internal_hash()}.  Bump the
5979 depth by one, just like in the ``equal'' method.
5980
5981 To convert a Lisp object directly into a hash value (using
5982 its pointer), use @code{LISP_HASH()}.  This is what happens when
5983 the hash method is NULL.
5984
5985 To hash two or more values together into a single value, use
5986 @code{HASH2()}, @code{HASH3()}, @code{HASH4()}, etc.
5987
5988 @item
5989 @dfn{getprop}, @dfn{putprop}, @dfn{remprop}, and @dfn{plist} methods.
5990 These are used for object types that have properties.  I don't feel like
5991 documenting them here.  If you create one of these objects, you have to
5992 use different macros to define them,
5993 i.e. @code{DEFINE_LRECORD_IMPLEMENTATION_WITH_PROPS()} or
5994 @code{DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION_WITH_PROPS()}.
5995
5996 @item
5997 A @dfn{size_in_bytes} method, when the object is of variable-size.
5998 (i.e. declared with a @code{_SEQUENCE_IMPLEMENTATION} macro.)  This should
5999 simply return the object's size in bytes, exactly as you might expect.
6000 For an example, see the methods for window configurations and opaques.
6001 @end enumerate
6002
6003 @node Low-level allocation
6004 @section Low-level allocation
6005 @cindex low-level allocation
6006 @cindex allocation, low-level
6007
6008   Memory that you want to allocate directly should be allocated using
6009 @code{xmalloc()} rather than @code{malloc()}.  This implements
6010 error-checking on the return value, and once upon a time did some more
6011 vital stuff (i.e. @code{BLOCK_INPUT}, which is no longer necessary).
6012 Free using @code{xfree()}, and realloc using @code{xrealloc()}.  Note
6013 that @code{xmalloc()} will do a non-local exit if the memory can't be
6014 allocated. (Many functions, however, do not expect this, and thus XEmacs
6015 will likely crash if this happens.  @strong{This is a bug.}  If you can,
6016 you should strive to make your function handle this OK.  However, it's
6017 difficult in the general circumstance, perhaps requiring extra
6018 unwind-protects and such.)
6019
6020   Note that XEmacs provides two separate replacements for the standard
6021 @code{malloc()} library function.  These are called @dfn{old GNU malloc}
6022 (@file{malloc.c}) and @dfn{new GNU malloc} (@file{gmalloc.c}),
6023 respectively.  New GNU malloc is better in pretty much every way than
6024 old GNU malloc, and should be used if possible.  (It used to be that on
6025 some systems, the old one worked but the new one didn't.  I think this
6026 was due specifically to a bug in SunOS, which the new one now works
6027 around; so I don't think the old one ever has to be used any more.) The
6028 primary difference between both of these mallocs and the standard system
6029 malloc is that they are much faster, at the expense of increased space.
6030 The basic idea is that memory is allocated in fixed chunks of powers of
6031 two.  This allows for basically constant malloc time, since the various
6032 chunks can just be kept on a number of free lists. (The standard system
6033 malloc typically allocates arbitrary-sized chunks and has to spend some
6034 time, sometimes a significant amount of time, walking the heap looking
6035 for a free block to use and cleaning things up.)  The new GNU malloc
6036 improves on things by allocating large objects in chunks of 4096 bytes
6037 rather than in ever larger powers of two, which results in ever larger
6038 wastage.  There is a slight speed loss here, but it's of doubtful
6039 significance.
6040
6041   NOTE: Apparently there is a third-generation GNU malloc that is
6042 significantly better than the new GNU malloc, and should probably
6043 be included in XEmacs.
6044
6045   There is also the relocating allocator, @file{ralloc.c}.  This actually
6046 moves blocks of memory around so that the @code{sbrk()} pointer shrunk
6047 and virtual memory released back to the system.  On some systems,
6048 this is a big win.  On all systems, it causes a noticeable (and
6049 sometimes huge) speed penalty, so I turn it off by default.
6050 @file{ralloc.c} only works with the new GNU malloc in @file{gmalloc.c}.
6051 There are also two versions of @file{ralloc.c}, one that uses @code{mmap()}
6052 rather than block copies to move data around.  This purports to
6053 be faster, although that depends on the amount of data that would
6054 have had to be block copied and the system-call overhead for
6055 @code{mmap()}.  I don't know exactly how this works, except that the
6056 relocating-allocation routines are pretty much used only for
6057 the memory allocated for a buffer, which is the biggest consumer
6058 of space, esp. of space that may get freed later.
6059
6060   Note that the GNU mallocs have some ``memory warning'' facilities.
6061 XEmacs taps into them and issues a warning through the standard
6062 warning system, when memory gets to 75%, 85%, and 95% full.
6063 (On some systems, the memory warnings are not functional.)
6064
6065   Allocated memory that is going to be used to make a Lisp object
6066 is created using @code{allocate_lisp_storage()}.  This just calls
6067 @code{xmalloc()}.  It used to verify that the pointer to the memory can
6068 fit into a Lisp word, before the current Lisp object representation was
6069 introduced.  @code{allocate_lisp_storage()} is called by
6070 @code{alloc_lcrecord()}, @code{ALLOCATE_FIXED_TYPE()}, and the vector
6071 and bit-vector creation routines.  These routines also call
6072 @code{INCREMENT_CONS_COUNTER()} at the appropriate times; this keeps
6073 statistics on how much memory is allocated, so that garbage-collection
6074 can be invoked when the threshold is reached.
6075
6076 @node Cons
6077 @section Cons
6078 @cindex cons
6079
6080   Conses are allocated in standard frob blocks.  The only thing to
6081 note is that conses can be explicitly freed using @code{free_cons()}
6082 and associated functions @code{free_list()} and @code{free_alist()}.  This
6083 immediately puts the conses onto the cons free list, and decrements
6084 the statistics on memory allocation appropriately.  This is used
6085 to good effect by some extremely commonly-used code, to avoid
6086 generating extra objects and thereby triggering GC sooner.
6087 However, you have to be @emph{extremely} careful when doing this.
6088 If you mess this up, you will get BADLY BURNED, and it has happened
6089 before.
6090
6091 @node Vector
6092 @section Vector
6093 @cindex vector
6094
6095   As mentioned above, each vector is @code{malloc()}ed individually, and
6096 all are threaded through the variable @code{all_vectors}.  Vectors are
6097 marked strangely during garbage collection, by kludging the size field.
6098 Note that the @code{struct Lisp_Vector} is declared with its
6099 @code{contents} field being a @emph{stretchy} array of one element.  It
6100 is actually @code{malloc()}ed with the right size, however, and access
6101 to any element through the @code{contents} array works fine.
6102
6103 @node Bit Vector
6104 @section Bit Vector
6105 @cindex bit vector
6106 @cindex vector, bit
6107
6108   Bit vectors work exactly like vectors, except for more complicated
6109 code to access an individual bit, and except for the fact that bit
6110 vectors are lrecords while vectors are not. (The only difference here is
6111 that there's an lrecord implementation pointer at the beginning and the
6112 tag field in bit vector Lisp words is ``lrecord'' rather than
6113 ``vector''.)
6114
6115 @node Symbol
6116 @section Symbol
6117 @cindex symbol
6118
6119   Symbols are also allocated in frob blocks.  Symbols in the awful
6120 horrible obarray structure are chained through their @code{next} field.
6121
6122 Remember that @code{intern} looks up a symbol in an obarray, creating
6123 one if necessary.
6124
6125 @node Marker
6126 @section Marker
6127 @cindex marker
6128
6129   Markers are allocated in frob blocks, as usual.  They are kept
6130 in a buffer unordered, but in a doubly-linked list so that they
6131 can easily be removed. (Formerly this was a singly-linked list,
6132 but in some cases garbage collection took an extraordinarily
6133 long time due to the O(N^2) time required to remove lots of
6134 markers from a buffer.) Markers are removed from a buffer in
6135 the finalize stage, in @code{ADDITIONAL_FREE_marker()}.
6136
6137 @node String
6138 @section String
6139 @cindex string
6140
6141   As mentioned above, strings are a special case.  A string is logically
6142 two parts, a fixed-size object (containing the length, property list,
6143 and a pointer to the actual data), and the actual data in the string.
6144 The fixed-size object is a @code{struct Lisp_String} and is allocated in
6145 frob blocks, as usual.  The actual data is stored in special
6146 @dfn{string-chars blocks}, which are 8K blocks of memory.
6147 Currently-allocated strings are simply laid end to end in these
6148 string-chars blocks, with a pointer back to the @code{struct Lisp_String}
6149 stored before each string in the string-chars block.  When a new string
6150 needs to be allocated, the remaining space at the end of the last
6151 string-chars block is used if there's enough, and a new string-chars
6152 block is created otherwise.
6153
6154   There are never any holes in the string-chars blocks due to the string
6155 compaction and relocation that happens at the end of garbage collection.
6156 During the sweep stage of garbage collection, when objects are
6157 reclaimed, the garbage collector goes through all string-chars blocks,
6158 looking for unused strings.  Each chunk of string data is preceded by a
6159 pointer to the corresponding @code{struct Lisp_String}, which indicates
6160 both whether the string is used and how big the string is, i.e. how to
6161 get to the next chunk of string data.  Holes are compressed by
6162 block-copying the next string into the empty space and relocating the
6163 pointer stored in the corresponding @code{struct Lisp_String}.
6164 @strong{This means you have to be careful with strings in your code.}
6165 See the section above on @code{GCPRO}ing.
6166
6167   Note that there is one situation not handled: a string that is too big
6168 to fit into a string-chars block.  Such strings, called @dfn{big
6169 strings}, are all @code{malloc()}ed as their own block. (#### Although it
6170 would make more sense for the threshold for big strings to be somewhat
6171 lower, e.g. 1/2 or 1/4 the size of a string-chars block.  It seems that
6172 this was indeed the case formerly---indeed, the threshold was set at
6173 1/8---but Mly forgot about this when rewriting things for 19.8.)
6174
6175 Note also that the string data in string-chars blocks is padded as
6176 necessary so that proper alignment constraints on the @code{struct
6177 Lisp_String} back pointers are maintained.
6178
6179   Finally, strings can be resized.  This happens in Mule when a
6180 character is substituted with a different-length character, or during
6181 modeline frobbing. (You could also export this to Lisp, but it's not
6182 done so currently.) Resizing a string is a potentially tricky process.
6183 If the change is small enough that the padding can absorb it, nothing
6184 other than a simple memory move needs to be done.  Keep in mind,
6185 however, that the string can't shrink too much because the offset to the
6186 next string in the string-chars block is computed by looking at the
6187 length and rounding to the nearest multiple of four or eight.  If the
6188 string would shrink or expand beyond the correct padding, new string
6189 data needs to be allocated at the end of the last string-chars block and
6190 the data moved appropriately.  This leaves some dead string data, which
6191 is marked by putting a special marker of 0xFFFFFFFF in the @code{struct
6192 Lisp_String} pointer before the data (there's no real @code{struct
6193 Lisp_String} to point to and relocate), and storing the size of the dead
6194 string data (which would normally be obtained from the now-non-existent
6195 @code{struct Lisp_String}) at the beginning of the dead string data gap.
6196 The string compactor recognizes this special 0xFFFFFFFF marker and
6197 handles it correctly.
6198
6199 @node Compiled Function
6200 @section Compiled Function
6201 @cindex compiled function
6202 @cindex function, compiled
6203
6204   Not yet documented.
6205
6206
6207 @node Dumping, Events and the Event Loop, Allocation of Objects in XEmacs Lisp, Top
6208 @chapter Dumping
6209 @cindex dumping
6210
6211 @section What is dumping and its justification
6212 @cindex dumping and its justification, what is
6213
6214 The C code of XEmacs is just a Lisp engine with a lot of built-in
6215 primitives useful for writing an editor.  The editor itself is written
6216 mostly in Lisp, and represents around 100K lines of code.  Loading and
6217 executing the initialization of all this code takes a bit a time (five
6218 to ten times the usual startup time of current xemacs) and requires
6219 having all the lisp source files around.  Having to reload them each
6220 time the editor is started would not be acceptable.
6221
6222 The traditional solution to this problem is called dumping: the build
6223 process first creates the lisp engine under the name @file{temacs}, then
6224 runs it until it has finished loading and initializing all the lisp
6225 code, and eventually creates a new executable called @file{xemacs}
6226 including both the object code in @file{temacs} and all the contents of
6227 the memory after the initialization.
6228
6229 This solution, while working, has a huge problem: the creation of the
6230 new executable from the actual contents of memory is an extremely
6231 system-specific process, quite error-prone, and which interferes with a
6232 lot of system libraries (like malloc).  It is even getting worse
6233 nowadays with libraries using constructors which are automatically
6234 called when the program is started (even before main()) which tend to
6235 crash when they are called multiple times, once before dumping and once
6236 after (IRIX 6.x libz.so pulls in some C++ image libraries thru
6237 dependencies which have this problem).  Writing the dumper is also one
6238 of the most difficult parts of porting XEmacs to a new operating system.
6239 Basically, `dumping' is an operation that is just not officially
6240 supported on many operating systems.
6241
6242 The aim of the portable dumper is to solve the same problem as the
6243 system-specific dumper, that is to be able to reload quickly, using only
6244 a small number of files, the fully initialized lisp part of the editor,
6245 without any system-specific hacks.
6246
6247 @menu
6248 * Overview::
6249 * Data descriptions::
6250 * Dumping phase::
6251 * Reloading phase::
6252 * Remaining issues::
6253 @end menu
6254
6255 @node Overview
6256 @section Overview
6257 @cindex dumping overview
6258
6259 The portable dumping system has to:
6260
6261 @enumerate
6262 @item
6263 At dump time, write all initialized, non-quickly-rebuildable data to a
6264 file [Note: currently named @file{xemacs.dmp}, but the name will
6265 change], along with all informations needed for the reloading.
6266
6267 @item
6268 When starting xemacs, reload the dump file, relocate it to its new
6269 starting address if needed, and reinitialize all pointers to this
6270 data.  Also, rebuild all the quickly rebuildable data.
6271 @end enumerate
6272
6273 @node Data descriptions
6274 @section Data descriptions
6275 @cindex dumping data descriptions
6276
6277 The more complex task of the dumper is to be able to write lisp objects
6278 (lrecords) and C structs to disk and reload them at a different address,
6279 updating all the pointers they include in the process.  This is done by
6280 using external data descriptions that give information about the layout
6281 of the structures in memory.
6282
6283 The specification of these descriptions is in lrecord.h.  A description
6284 of an lrecord is an array of struct lrecord_description.  Each of these
6285 structs include a type, an offset in the structure and some optional
6286 parameters depending on the type.  For instance, here is the string
6287 description:
6288
6289 @example
6290 static const struct lrecord_description string_description[] = @{
6291   @{ XD_BYTECOUNT,         offsetof (Lisp_String, size) @},
6292   @{ XD_OPAQUE_DATA_PTR,   offsetof (Lisp_String, data), XD_INDIRECT(0, 1) @},
6293   @{ XD_LISP_OBJECT,       offsetof (Lisp_String, plist) @},
6294   @{ XD_END @}
6295 @};
6296 @end example
6297
6298 The first line indicates a member of type Bytecount, which is used by
6299 the next, indirect directive.  The second means "there is a pointer to
6300 some opaque data in the field @code{data}".  The length of said data is
6301 given by the expression @code{XD_INDIRECT(0, 1)}, which means "the value
6302 in the 0th line of the description (welcome to C) plus one".  The third
6303 line means "there is a Lisp_Object member @code{plist} in the Lisp_String
6304 structure".  @code{XD_END} then ends the description.
6305
6306 This gives us all the information we need to move around what is pointed
6307 to by a structure (C or lrecord) and, by transitivity, everything that
6308 it points to.  The only missing information for dumping is the size of
6309 the structure.  For lrecords, this is part of the
6310 lrecord_implementation, so we don't need to duplicate it.  For C
6311 structures we use a struct struct_description, which includes a size
6312 field and a pointer to an associated array of lrecord_description.
6313
6314 @node Dumping phase
6315 @section Dumping phase
6316 @cindex dumping phase
6317
6318 Dumping is done by calling the function pdump() (in dumper.c) which is
6319 invoked from Fdump_emacs (in emacs.c).  This function performs a number
6320 of tasks.
6321
6322 @menu
6323 * Object inventory::
6324 * Address allocation::
6325 * The header::
6326 * Data dumping::
6327 * Pointers dumping::
6328 @end menu
6329
6330 @node Object inventory
6331 @subsection Object inventory
6332 @cindex dumping object inventory
6333
6334 The first task is to build the list of the objects to dump.  This
6335 includes:
6336
6337 @itemize @bullet
6338 @item lisp objects
6339 @item C structures
6340 @end itemize
6341
6342 We end up with one @code{pdump_entry_list_elmt} per object group (arrays
6343 of C structs are kept together) which includes a pointer to the first
6344 object of the group, the per-object size and the count of objects in the
6345 group, along with some other information which is initialized later.
6346
6347 These entries are linked together in @code{pdump_entry_list} structures
6348 and can be enumerated thru either:
6349
6350 @enumerate
6351 @item
6352 the @code{pdump_object_table}, an array of @code{pdump_entry_list}, one
6353 per lrecord type, indexed by type number.
6354
6355 @item
6356 the @code{pdump_opaque_data_list}, used for the opaque data which does
6357 not include pointers, and hence does not need descriptions.
6358
6359 @item
6360 the @code{pdump_struct_table}, which is a vector of
6361 @code{struct_description}/@code{pdump_entry_list} pairs, used for
6362 non-opaque C structures.
6363 @end enumerate
6364
6365 This uses a marking strategy similar to the garbage collector.  Some
6366 differences though:
6367
6368 @enumerate
6369 @item
6370 We do not use the mark bit (which does not exist for C structures
6371 anyway); we use a big hash table instead.
6372
6373 @item
6374 We do not use the mark function of lrecords but instead rely on the
6375 external descriptions.  This happens essentially because we need to
6376 follow pointers to C structures and opaque data in addition to
6377 Lisp_Object members.
6378 @end enumerate
6379
6380 This is done by @code{pdump_register_object()}, which handles Lisp_Object
6381 variables, and @code{pdump_register_struct()} which handles C structures,
6382 which both delegate the description management to @code{pdump_register_sub()}.
6383
6384 The hash table doubles as a map object to pdump_entry_list_elmt (i.e.
6385 allows us to look up a pdump_entry_list_elmt with the object it points
6386 to).  Entries are added with @code{pdump_add_entry()} and looked up with
6387 @code{pdump_get_entry()}.  There is no need for entry removal.  The hash
6388 value is computed quite simply from the object pointer by
6389 @code{pdump_make_hash()}.
6390
6391 The roots for the marking are:
6392
6393 @enumerate
6394 @item
6395 the @code{staticpro}'ed variables (there is a special @code{staticpro_nodump()}
6396 call for protected variables we do not want to dump).
6397
6398 @item
6399 the variables registered via @code{dump_add_root_object}
6400 (@code{staticpro()} is equivalent to @code{staticpro_nodump()} +
6401 @code{dump_add_root_object()}).
6402
6403 @item
6404 the variables registered via @code{dump_add_root_struct_ptr}, each of
6405 which points to a C structure.
6406 @end enumerate
6407
6408 This does not include the GCPRO'ed variables, the specbinds, the
6409 catchtags, the backlist, the redisplay or the profiling info, since we
6410 do not want to rebuild the actual chain of lisp calls which end up to
6411 the dump-emacs call, only the global variables.
6412
6413 Weak lists and weak hash tables are dumped as if they were their
6414 non-weak equivalent (without changing their type, of course).  This has
6415 not yet been a problem.
6416
6417 @node Address allocation
6418 @subsection Address allocation
6419 @cindex dumping address allocation
6420
6421
6422 The next step is to allocate the offsets of each of the objects in the
6423 final dump file.  This is done by @code{pdump_allocate_offset()} which
6424 is called indirectly by @code{pdump_scan_by_alignment()}.
6425
6426 The strategy to deal with alignment problems uses these facts:
6427
6428 @enumerate
6429 @item
6430 real world alignment requirements are powers of two.
6431
6432 @item
6433 the C compiler is required to adjust the size of a struct so that you
6434 can have an array of them next to each other.  This means you can have an
6435 upper bound of the alignment requirements of a given structure by
6436 looking at which power of two its size is a multiple.
6437
6438 @item
6439 the non-variant part of variable size lrecords has an alignment
6440 requirement of 4.
6441 @end enumerate
6442
6443 Hence, for each lrecord type, C struct type or opaque data block the
6444 alignment requirement is computed as a power of two, with a minimum of
6445 2^2 for lrecords.  @code{pdump_scan_by_alignment()} then scans all the
6446 @code{pdump_entry_list_elmt}'s, the ones with the highest requirements
6447 first.  This ensures the best packing.
6448
6449 The maximum alignment requirement we take into account is 2^8.
6450
6451 @code{pdump_allocate_offset()} only has to do a linear allocation,
6452 starting at offset 256 (this leaves room for the header and keeps the
6453 alignments happy).
6454
6455 @node The header
6456 @subsection The header
6457 @cindex dumping, the header
6458
6459 The next step creates the file and writes a header with a signature and
6460 some random information in it.  The @code{reloc_address} field, which
6461 indicates at which address the file should be loaded if we want to avoid
6462 post-reload relocation, is set to 0.  It then seeks to offset 256 (base
6463 offset for the objects).
6464
6465 @node Data dumping
6466 @subsection Data dumping
6467 @cindex data dumping
6468 @cindex dumping, data
6469
6470 The data is dumped in the same order as the addresses were allocated by
6471 @code{pdump_dump_data()}, called from @code{pdump_scan_by_alignment()}.
6472 This function copies the data to a temporary buffer, relocates all
6473 pointers in the object to the addresses allocated in step Address
6474 Allocation, and writes it to the file.  Using the same order means that,
6475 if we are careful with lrecords whose size is not a multiple of 4, we
6476 are ensured that the object is always written at the offset in the file
6477 allocated in step Address Allocation.
6478
6479 @node Pointers dumping
6480 @subsection Pointers dumping
6481 @cindex pointers dumping
6482 @cindex dumping, pointers
6483
6484 A bunch of tables needed to reassign properly the global pointers are
6485 then written.  They are:
6486
6487 @enumerate
6488 @item
6489 the pdump_root_struct_ptrs dynarr
6490 @item
6491 the pdump_opaques dynarr
6492 @item
6493 a vector of all the offsets to the objects in the file that include a
6494 description (for faster relocation at reload time)
6495 @item
6496 the pdump_root_objects and pdump_weak_object_chains dynarrs.
6497 @end enumerate
6498
6499 For each of the dynarrs we write both the pointer to the variables and
6500 the relocated offset of the object they point to.  Since these variables
6501 are global, the pointers are still valid when restarting the program and
6502 are used to regenerate the global pointers.
6503
6504 The @code{pdump_weak_object_chains} dynarr is a special case.  The
6505 variables it points to are the head of weak linked lists of lisp objects
6506 of the same type.  Not all objects of this list are dumped so the
6507 relocated pointer we associate with them points to the first dumped
6508 object of the list, or Qnil if none is available.  This is also the
6509 reason why they are not used as roots for the purpose of object
6510 enumeration.
6511
6512 Some very important information like the @code{staticpros} and
6513 @code{lrecord_implementations_table} are handled indirectly using
6514 @code{dump_add_opaque} or @code{dump_add_root_struct_ptr}.
6515
6516 This is the end of the dumping part.
6517
6518 @node Reloading phase
6519 @section Reloading phase
6520 @cindex reloading phase
6521 @cindex dumping, reloading phase
6522
6523 @subsection File loading
6524 @cindex dumping, file loading
6525
6526 The file is mmap'ed in memory (which ensures a PAGESIZE alignment, at
6527 least 4096), or if mmap is unavailable or fails, a 256-bytes aligned
6528 malloc is done and the file is loaded.
6529
6530 Some variables are reinitialized from the values found in the header.
6531
6532 The difference between the actual loading address and the reloc_address
6533 is computed and will be used for all the relocations.
6534
6535
6536 @subsection Putting back the pdump_opaques
6537 @cindex dumping, putting back the pdump_opaques
6538
6539 The memory contents are restored in the obvious and trivial way.
6540
6541
6542 @subsection Putting back the pdump_root_struct_ptrs
6543 @cindex dumping, putting back the pdump_root_struct_ptrs
6544
6545 The variables pointed to by pdump_root_struct_ptrs in the dump phase are
6546 reset to the right relocated object addresses.
6547
6548
6549 @subsection Object relocation
6550 @cindex dumping, object relocation
6551
6552 All the objects are relocated using their description and their offset
6553 by @code{pdump_reloc_one}.  This step is unnecessary if the
6554 reloc_address is equal to the file loading address.
6555
6556
6557 @subsection Putting back the pdump_root_objects and pdump_weak_object_chains
6558 @cindex dumping, putting back the pdump_root_objects and pdump_weak_object_chains
6559
6560 Same as Putting back the pdump_root_struct_ptrs.
6561
6562
6563 @subsection Reorganize the hash tables
6564 @cindex dumping, reorganize the hash tables
6565
6566 Since some of the hash values in the lisp hash tables are
6567 address-dependent, their layout is now wrong.  So we go through each of
6568 them and have them resorted by calling @code{pdump_reorganize_hash_table}.
6569
6570 @node Remaining issues
6571 @section Remaining issues
6572 @cindex dumping, remaining issues
6573
6574 The build process will have to start a post-dump xemacs, ask it the
6575 loading address (which will, hopefully, be always the same between
6576 different xemacs invocations) and relocate the file to the new address.
6577 This way the object relocation phase will not have to be done, which
6578 means no writes in the objects and that, because of the use of mmap, the
6579 dumped data will be shared between all the xemacs running on the
6580 computer.
6581
6582 Some executable signature will be necessary to ensure that a given dump
6583 file is really associated with a given executable, or random crashes
6584 will occur.  Maybe a random number set at compile or configure time thru
6585 a define.  This will also allow for having differently-compiled xemacsen
6586 on the same system (mule and no-mule comes to mind).
6587
6588 The DOC file contents should probably end up in the dump file.
6589
6590
6591 @node Events and the Event Loop, Evaluation; Stack Frames; Bindings, Dumping, Top
6592 @chapter Events and the Event Loop
6593 @cindex events and the event loop
6594 @cindex event loop, events and the
6595
6596 @menu
6597 * Introduction to Events::
6598 * Main Loop::
6599 * Specifics of the Event Gathering Mechanism::
6600 * Specifics About the Emacs Event::
6601 * The Event Stream Callback Routines::
6602 * Other Event Loop Functions::
6603 * Converting Events::
6604 * Dispatching Events; The Command Builder::
6605 @end menu
6606
6607 @node Introduction to Events
6608 @section Introduction to Events
6609 @cindex events, introduction to
6610
6611   An event is an object that encapsulates information about an
6612 interesting occurrence in the operating system.  Events are
6613 generated either by user action, direct (e.g. typing on the
6614 keyboard or moving the mouse) or indirect (moving another
6615 window, thereby generating an expose event on an Emacs frame),
6616 or as a result of some other typically asynchronous action happening,
6617 such as output from a subprocess being ready or a timer expiring.
6618 Events come into the system in an asynchronous fashion (typically
6619 through a callback being called) and are converted into a
6620 synchronous event queue (first-in, first-out) in a process that
6621 we will call @dfn{collection}.
6622
6623   Note that each application has its own event queue. (It is
6624 immaterial whether the collection process directly puts the
6625 events in the proper application's queue, or puts them into
6626 a single system queue, which is later split up.)
6627
6628   The most basic level of event collection is done by the
6629 operating system or window system.  Typically, XEmacs does
6630 its own event collection as well.  Often there are multiple
6631 layers of collection in XEmacs, with events from various
6632 sources being collected into a queue, which is then combined
6633 with other sources to go into another queue (i.e. a second
6634 level of collection), with perhaps another level on top of
6635 this, etc.
6636
6637   XEmacs has its own types of events (called @dfn{Emacs events}),
6638 which provides an abstract layer on top of the system-dependent
6639 nature of the most basic events that are received.  Part of the
6640 complex nature of the XEmacs event collection process involves
6641 converting from the operating-system events into the proper
6642 Emacs events---there may not be a one-to-one correspondence.
6643
6644   Emacs events are documented in @file{events.h}; I'll discuss them
6645 later.
6646
6647 @node Main Loop
6648 @section Main Loop
6649 @cindex main loop
6650 @cindex events, main loop
6651
6652   The @dfn{command loop} is the top-level loop that the editor is always
6653 running.  It loops endlessly, calling @code{next-event} to retrieve an
6654 event and @code{dispatch-event} to execute it. @code{dispatch-event} does
6655 the appropriate thing with non-user events (process, timeout,
6656 magic, eval, mouse motion); this involves calling a Lisp handler
6657 function, redrawing a newly-exposed part of a frame, reading
6658 subprocess output, etc.  For user events, @code{dispatch-event}
6659 looks up the event in relevant keymaps or menubars; when a
6660 full key sequence or menubar selection is reached, the appropriate
6661 function is executed. @code{dispatch-event} may have to keep state
6662 across calls; this is done in the ``command-builder'' structure
6663 associated with each console (remember, there's usually only
6664 one console), and the engine that looks up keystrokes and
6665 constructs full key sequences is called the @dfn{command builder}.
6666 This is documented elsewhere.
6667
6668   The guts of the command loop are in @code{command_loop_1()}.  This
6669 function doesn't catch errors, though---that's the job of
6670 @code{command_loop_2()}, which is a condition-case (i.e. error-trapping)
6671 wrapper around @code{command_loop_1()}.  @code{command_loop_1()} never
6672 returns, but may get thrown out of.
6673
6674   When an error occurs, @code{cmd_error()} is called, which usually
6675 invokes the Lisp error handler in @code{command-error}; however, a
6676 default error handler is provided if @code{command-error} is @code{nil}
6677 (e.g. during startup).  The purpose of the error handler is simply to
6678 display the error message and do associated cleanup; it does not need to
6679 throw anywhere.  When the error handler finishes, the condition-case in
6680 @code{command_loop_2()} will finish and @code{command_loop_2()} will
6681 reinvoke @code{command_loop_1()}.
6682
6683   @code{command_loop_2()} is invoked from three places: from
6684 @code{initial_command_loop()} (called from @code{main()} at the end of
6685 internal initialization), from the Lisp function @code{recursive-edit},
6686 and from @code{call_command_loop()}.
6687
6688   @code{call_command_loop()} is called when a macro is started and when
6689 the minibuffer is entered; normal termination of the macro or minibuffer
6690 causes a throw out of the recursive command loop. (To
6691 @code{execute-kbd-macro} for macros and @code{exit} for minibuffers.
6692 Note also that the low-level minibuffer-entering function,
6693 @code{read-minibuffer-internal}, provides its own error handling and
6694 does not need @code{command_loop_2()}'s error encapsulation; so it tells
6695 @code{call_command_loop()} to invoke @code{command_loop_1()} directly.)
6696
6697   Note that both read-minibuffer-internal and recursive-edit set up a
6698 catch for @code{exit}; this is why @code{abort-recursive-edit}, which
6699 throws to this catch, exits out of either one.
6700
6701   @code{initial_command_loop()}, called from @code{main()}, sets up a
6702 catch for @code{top-level} when invoking @code{command_loop_2()},
6703 allowing functions to throw all the way to the top level if they really
6704 need to.  Before invoking @code{command_loop_2()},
6705 @code{initial_command_loop()} calls @code{top_level_1()}, which handles
6706 all of the startup stuff (creating the initial frame, handling the
6707 command-line options, loading the user's @file{.emacs} file, etc.).  The
6708 function that actually does this is in Lisp and is pointed to by the
6709 variable @code{top-level}; normally this function is
6710 @code{normal-top-level}.  @code{top_level_1()} is just an error-handling
6711 wrapper similar to @code{command_loop_2()}.  Note also that
6712 @code{initial_command_loop()} sets up a catch for @code{top-level} when
6713 invoking @code{top_level_1()}, just like when it invokes
6714 @code{command_loop_2()}.
6715
6716 @node Specifics of the Event Gathering Mechanism
6717 @section Specifics of the Event Gathering Mechanism
6718 @cindex event gathering mechanism, specifics of the
6719
6720   Here is an approximate diagram of the collection processes
6721 at work in XEmacs, under TTY's (TTY's are simpler than X
6722 so we'll look at this first):
6723
6724 @noindent
6725 @example
6726  asynch.      asynch.    asynch.   asynch.             [Collectors in
6727 kbd events  kbd events   process   process                the OS]
6728       |         |         output    output
6729       |         |           |         |
6730       |         |           |         |      SIGINT,   [signal handlers
6731       |         |           |         |      SIGQUIT,     in XEmacs]
6732       V         V           V         V      SIGWINCH,
6733      file      file        file      file    SIGALRM
6734      desc.     desc.       desc.     desc.     |
6735      (TTY)     (TTY)       (pipe)    (pipe)    |
6736       |          |          |         |      fake    timeouts
6737       |          |          |         |      file        |
6738       |          |          |         |      desc.       |
6739       |          |          |         |      (pipe)      |
6740       |          |          |         |        |         |
6741       |          |          |         |        |         |
6742       |          |          |         |        |         |
6743       V          V          V         V        V         V
6744       ------>-----------<----------------<----------------
6745                   |
6746                   |
6747                   | [collected using select() in emacs_tty_next_event()
6748                   |  and converted to the appropriate Emacs event]
6749                   |
6750                   |
6751                   V          (above this line is TTY-specific)
6752                 Emacs -----------------------------------------------
6753                 event (below this line is the generic event mechanism)
6754                   |
6755                   |
6756 was there     if not, call
6757 a SIGINT?  emacs_tty_next_event()
6758     |             |
6759     |             |
6760     |             |
6761     V             V
6762     --->------<----
6763            |
6764            |     [collected in event_stream_next_event();
6765            |      SIGINT is converted using maybe_read_quit_event()]
6766            V
6767          Emacs
6768          event
6769            |
6770            \---->------>----- maybe_kbd_translate() ---->---\
6771                                                             |
6772                                                             |
6773                                                             |
6774      command event queue                                    |
6775                                                if not from command
6776   (contains events that were                   event queue, call
6777   read earlier but not processed,              event_stream_next_event()
6778   typically when waiting in a                               |
6779   sit-for, sleep-for, etc. for                              |
6780  a particular event to be received)                         |
6781                |                                            |
6782                |                                            |
6783                V                                            V
6784                ---->------------------------------------<----
6785                                                |
6786                                                | [collected in
6787                                                |  next_event_internal()]
6788                                                |
6789  unread-     unread-       event from          |
6790  command-    command-       keyboard       else, call
6791  events      event           macro      next_event_internal()
6792    |           |               |               |
6793    |           |               |               |
6794    |           |               |               |
6795    V           V               V               V
6796    --------->----------------------<------------
6797                      |
6798                      |      [collected in `next-event', which may loop
6799                      |       more than once if the event it gets is on
6800                      |       a dead frame, device, etc.]
6801                      |
6802                      |
6803                      V
6804             feed into top-level event loop,
6805             which repeatedly calls `next-event'
6806             and then dispatches the event
6807             using `dispatch-event'
6808 @end example
6809
6810 Notice the separation between TTY-specific and generic event mechanism.
6811 When using the Xt-based event loop, the TTY-specific stuff is replaced
6812 but the rest stays the same.
6813
6814 It's also important to realize that only one different kind of
6815 system-specific event loop can be operating at a time, and must be able
6816 to receive all kinds of events simultaneously.  For the two existing
6817 event loops (implemented in @file{event-tty.c} and @file{event-Xt.c},
6818 respectively), the TTY event loop @emph{only} handles TTY consoles,
6819 while the Xt event loop handles @emph{both} TTY and X consoles.  This
6820 situation is different from all of the output handlers, where you simply
6821 have one per console type.
6822
6823   Here's the Xt Event Loop Diagram (notice that below a certain point,
6824 it's the same as the above diagram):
6825
6826 @example
6827 asynch. asynch. asynch. asynch.                 [Collectors in
6828  kbd     kbd    process process                    the OS]
6829 events  events  output  output
6830   |       |       |       |
6831   |       |       |       |     asynch. asynch. [Collectors in the
6832   |       |       |       |       X        X     OS and X Window System]
6833   |       |       |       |     events  events
6834   |       |       |       |       |        |
6835   |       |       |       |       |        |
6836   |       |       |       |       |        |    SIGINT, [signal handlers
6837   |       |       |       |       |        |    SIGQUIT,   in XEmacs]
6838   |       |       |       |       |        |    SIGWINCH,
6839   |       |       |       |       |        |    SIGALRM
6840   |       |       |       |       |        |       |
6841   |       |       |       |       |        |       |
6842   |       |       |       |       |        |       |      timeouts
6843   |       |       |       |       |        |       |          |
6844   |       |       |       |       |        |       |          |
6845   |       |       |       |       |        |       V          |
6846   V       V       V       V       V        V      fake        |
6847  file    file    file    file    file     file    file        |
6848  desc.   desc.   desc.   desc.   desc.    desc.   desc.       |
6849  (TTY)   (TTY)   (pipe)  (pipe) (socket) (socket) (pipe)      |
6850   |       |       |       |       |        |       |          |
6851   |       |       |       |       |        |       |          |
6852   |       |       |       |       |        |       |          |
6853   V       V       V       V       V        V       V          V
6854   --->----------------------------------------<---------<------
6855        |              |               |
6856        |              |               |[collected using select() in
6857        |              |               | _XtWaitForSomething(), called
6858        |              |               | from XtAppProcessEvent(), called
6859        |              |               | in emacs_Xt_next_event();
6860        |              |               | dispatched to various callbacks]
6861        |              |               |
6862        |              |               |
6863   emacs_Xt_        p_s_callback(),    | [popup_selection_callback]
6864   event_handler()  x_u_v_s_callback(),| [x_update_vertical_scrollbar_
6865        |           x_u_h_s_callback(),|  callback]
6866        |           search_callback()  | [x_update_horizontal_scrollbar_
6867        |              |               |  callback]
6868        |              |               |
6869        |              |               |
6870   enqueue_Xt_       signal_special_   |
6871   dispatch_event()  Xt_user_event()   |
6872   [maybe multiple     |               |
6873    times, maybe 0     |               |
6874    times]             |               |
6875        |            enqueue_Xt_       |
6876        |            dispatch_event()  |
6877        |              |               |
6878        |              |               |
6879        V              V               |
6880        -->----------<--               |
6881               |                       |
6882               |                       |
6883            dispatch             Xt_what_callback()
6884            event                  sets flags
6885            queue                      |
6886               |                       |
6887               |                       |
6888               |                       |
6889               |                       |
6890               ---->-----------<--------
6891                    |
6892                    |
6893                    |     [collected and converted as appropriate in
6894                    |            emacs_Xt_next_event()]
6895                    |
6896                    |
6897                    V          (above this line is Xt-specific)
6898                  Emacs ------------------------------------------------
6899                  event (below this line is the generic event mechanism)
6900                    |
6901                    |
6902 was there      if not, call
6903 a SIGINT?   emacs_Xt_next_event()
6904     |              |
6905     |              |
6906     |              |
6907     V              V
6908     --->-------<----
6909            |
6910            |        [collected in event_stream_next_event();
6911            |         SIGINT is converted using maybe_read_quit_event()]
6912            V
6913          Emacs
6914          event
6915            |
6916            \---->------>----- maybe_kbd_translate() -->-----\
6917                                                             |
6918                                                             |
6919                                                             |
6920      command event queue                                    |
6921                                               if not from command
6922   (contains events that were                  event queue, call
6923   read earlier but not processed,             event_stream_next_event()
6924   typically when waiting in a                               |
6925   sit-for, sleep-for, etc. for                              |
6926  a particular event to be received)                         |
6927                |                                            |
6928                |                                            |
6929                V                                            V
6930                ---->----------------------------------<------
6931                                                |
6932                                                | [collected in
6933                                                |  next_event_internal()]
6934                                                |
6935  unread-     unread-       event from          |
6936  command-    command-       keyboard       else, call
6937  events      event           macro      next_event_internal()
6938    |           |               |               |
6939    |           |               |               |
6940    |           |               |               |
6941    V           V               V               V
6942    --------->----------------------<------------
6943                      |
6944                      |      [collected in `next-event', which may loop
6945                      |       more than once if the event it gets is on
6946                      |       a dead frame, device, etc.]
6947                      |
6948                      |
6949                      V
6950             feed into top-level event loop,
6951             which repeatedly calls `next-event'
6952             and then dispatches the event
6953             using `dispatch-event'
6954 @end example
6955
6956 @node Specifics About the Emacs Event
6957 @section Specifics About the Emacs Event
6958 @cindex event, specifics about the Lisp object
6959
6960 @node The Event Stream Callback Routines
6961 @section The Event Stream Callback Routines
6962 @cindex event stream callback routines, the
6963 @cindex callback routines, the event stream
6964
6965 @node Other Event Loop Functions
6966 @section Other Event Loop Functions
6967 @cindex event loop functions, other
6968
6969   @code{detect_input_pending()} and @code{input-pending-p} look for
6970 input by calling @code{event_stream->event_pending_p} and looking in
6971 @code{[V]unread-command-event} and the @code{command_event_queue} (they
6972 do not check for an executing keyboard macro, though).
6973
6974   @code{discard-input} cancels any command events pending (and any
6975 keyboard macros currently executing), and puts the others onto the
6976 @code{command_event_queue}.  There is a comment about a ``race
6977 condition'', which is not a good sign.
6978
6979   @code{next-command-event} and @code{read-char} are higher-level
6980 interfaces to @code{next-event}.  @code{next-command-event} gets the
6981 next @dfn{command} event (i.e.  keypress, mouse event, menu selection,
6982 or scrollbar action), calling @code{dispatch-event} on any others.
6983 @code{read-char} calls @code{next-command-event} and uses
6984 @code{event_to_character()} to return the character equivalent.  With
6985 the right kind of input method support, it is possible for (read-char)
6986 to return a Kanji character.
6987
6988 @node Converting Events
6989 @section Converting Events
6990 @cindex converting events
6991 @cindex events, converting
6992
6993   @code{character_to_event()}, @code{event_to_character()},
6994 @code{event-to-character}, and @code{character-to-event} convert between
6995 characters and keypress events corresponding to the characters.  If the
6996 event was not a keypress, @code{event_to_character()} returns -1 and
6997 @code{event-to-character} returns @code{nil}.  These functions convert
6998 between character representation and the split-up event representation
6999 (keysym plus mod keys).
7000
7001 @node Dispatching Events; The Command Builder
7002 @section Dispatching Events; The Command Builder
7003 @cindex dispatching events; the command builder
7004 @cindex events; the command builder, dispatching
7005 @cindex command builder, dispatching events; the
7006
7007 Not yet documented.
7008
7009 @node Evaluation; Stack Frames; Bindings, Symbols and Variables, Events and the Event Loop, Top
7010 @chapter Evaluation; Stack Frames; Bindings
7011 @cindex evaluation; stack frames; bindings
7012 @cindex stack frames; bindings, evaluation;
7013 @cindex bindings, evaluation; stack frames;
7014
7015 @menu
7016 * Evaluation::
7017 * Dynamic Binding; The specbinding Stack; Unwind-Protects::
7018 * Simple Special Forms::
7019 * Catch and Throw::
7020 @end menu
7021
7022 @node Evaluation
7023 @section Evaluation
7024 @cindex evaluation
7025
7026   @code{Feval()} evaluates the form (a Lisp object) that is passed to
7027 it.  Note that evaluation is only non-trivial for two types of objects:
7028 symbols and conses.  A symbol is evaluated simply by calling
7029 @code{symbol-value} on it and returning the value.
7030
7031   Evaluating a cons means calling a function.  First, @code{eval} checks
7032 to see if garbage-collection is necessary, and calls
7033 @code{garbage_collect_1()} if so.  It then increases the evaluation
7034 depth by 1 (@code{lisp_eval_depth}, which is always less than
7035 @code{max_lisp_eval_depth}) and adds an element to the linked list of
7036 @code{struct backtrace}'s (@code{backtrace_list}).  Each such structure
7037 contains a pointer to the function being called plus a list of the
7038 function's arguments.  Originally these values are stored unevalled, and
7039 as they are evaluated, the backtrace structure is updated.  Garbage
7040 collection pays attention to the objects pointed to in the backtrace
7041 structures (garbage collection might happen while a function is being
7042 called or while an argument is being evaluated, and there could easily
7043 be no other references to the arguments in the argument list; once an
7044 argument is evaluated, however, the unevalled version is not needed by
7045 eval, and so the backtrace structure is changed).
7046
7047 At this point, the function to be called is determined by looking at
7048 the car of the cons (if this is a symbol, its function definition is
7049 retrieved and the process repeated).  The function should then consist
7050 of either a @code{Lisp_Subr} (built-in function written in C), a
7051 @code{Lisp_Compiled_Function} object, or a cons whose car is one of the
7052 symbols @code{autoload}, @code{macro} or @code{lambda}.
7053
7054 If the function is a @code{Lisp_Subr}, the lisp object points to a
7055 @code{struct Lisp_Subr} (created by @code{DEFUN()}), which contains a
7056 pointer to the C function, a minimum and maximum number of arguments
7057 (or possibly the special constants @code{MANY} or @code{UNEVALLED}), a
7058 pointer to the symbol referring to that subr, and a couple of other
7059 things.  If the subr wants its arguments @code{UNEVALLED}, they are
7060 passed raw as a list.  Otherwise, an array of evaluated arguments is
7061 created and put into the backtrace structure, and either passed whole
7062 (@code{MANY}) or each argument is passed as a C argument.
7063
7064 If the function is a @code{Lisp_Compiled_Function},
7065 @code{funcall_compiled_function()} is called.  If the function is a
7066 lambda list, @code{funcall_lambda()} is called.  If the function is a
7067 macro, [..... fill in] is done.  If the function is an autoload,
7068 @code{do_autoload()} is called to load the definition and then eval
7069 starts over [explain this more].
7070
7071 When @code{Feval()} exits, the evaluation depth is reduced by one, the
7072 debugger is called if appropriate, and the current backtrace structure
7073 is removed from the list.
7074
7075 Both @code{funcall_compiled_function()} and @code{funcall_lambda()} need
7076 to go through the list of formal parameters to the function and bind
7077 them to the actual arguments, checking for @code{&rest} and
7078 @code{&optional} symbols in the formal parameters and making sure the
7079 number of actual arguments is correct.
7080 @code{funcall_compiled_function()} can do this a little more
7081 efficiently, since the formal parameter list can be checked for sanity
7082 when the compiled function object is created.
7083
7084 @code{funcall_lambda()} simply calls @code{Fprogn} to execute the code
7085 in the lambda list.
7086
7087 @code{funcall_compiled_function()} calls the real byte-code interpreter
7088 @code{execute_optimized_program()} on the byte-code instructions, which
7089 are converted into an internal form for faster execution.
7090
7091 When a compiled function is executed for the first time by
7092 @code{funcall_compiled_function()}, or during the dump phase of building
7093 XEmacs, the byte-code instructions are converted from a
7094 @code{Lisp_String} (which is inefficient to access, especially in the
7095 presence of MULE) into a @code{Lisp_Opaque} object containing an array
7096 of unsigned char, which can be directly executed by the byte-code
7097 interpreter.  At this time the byte code is also analyzed for validity
7098 and transformed into a more optimized form, so that
7099 @code{execute_optimized_program()} can really fly.
7100
7101 Here are some of the optimizations performed by the internal byte-code
7102 transformer:
7103 @enumerate
7104 @item
7105 References to the @code{constants} array are checked for out-of-range
7106 indices, so that the byte interpreter doesn't have to.
7107 @item
7108 References to the @code{constants} array that will be used as a Lisp
7109 variable are checked for being correct non-constant (i.e. not @code{t},
7110 @code{nil}, or @code{keywordp}) symbols, so that the byte interpreter
7111 doesn't have to.
7112 @item
7113 The maximum number of variable bindings in the byte-code is
7114 pre-computed, so that space on the @code{specpdl} stack can be
7115 pre-reserved once for the whole function execution.
7116 @item
7117 All byte-code jumps are relative to the current program counter instead
7118 of the start of the program, thereby saving a register.
7119 @item
7120 One-byte relative jumps are converted from the byte-code form of unsigned
7121 chars offset by 127 to machine-friendly signed chars.
7122 @end enumerate
7123
7124 Of course, this transformation of the @code{instructions} should not be
7125 visible to the user, so @code{Fcompiled_function_instructions()} needs
7126 to know how to convert the optimized opaque object back into a Lisp
7127 string that is identical to the original string from the @file{.elc}
7128 file.  (Actually, the resulting string may (rarely) contain slightly
7129 different, yet equivalent, byte code.)
7130
7131 @code{Ffuncall()} implements Lisp @code{funcall}.  @code{(funcall fun
7132 x1 x2 x3 ...)} is equivalent to @code{(eval (list fun (quote x1) (quote
7133 x2) (quote x3) ...))}.  @code{Ffuncall()} contains its own code to do
7134 the evaluation, however, and is very similar to @code{Feval()}.
7135
7136 From the performance point of view, it is worth knowing that most of the
7137 time in Lisp evaluation is spent executing @code{Lisp_Subr} and
7138 @code{Lisp_Compiled_Function} objects via @code{Ffuncall()} (not
7139 @code{Feval()}).
7140
7141 @code{Fapply()} implements Lisp @code{apply}, which is very similar to
7142 @code{funcall} except that if the last argument is a list, the result is the
7143 same as if each of the arguments in the list had been passed separately.
7144 @code{Fapply()} does some business to expand the last argument if it's a
7145 list, then calls @code{Ffuncall()} to do the work.
7146
7147 @code{apply1()}, @code{call0()}, @code{call1()}, @code{call2()}, and
7148 @code{call3()} call a function, passing it the argument(s) given (the
7149 arguments are given as separate C arguments rather than being passed as
7150 an array).  @code{apply1()} uses @code{Fapply()} while the others use
7151 @code{Ffuncall()} to do the real work.
7152
7153 @node Dynamic Binding; The specbinding Stack; Unwind-Protects
7154 @section Dynamic Binding; The specbinding Stack; Unwind-Protects
7155 @cindex dynamic binding; the specbinding stack; unwind-protects
7156 @cindex binding; the specbinding stack; unwind-protects, dynamic
7157 @cindex specbinding stack; unwind-protects, dynamic binding; the
7158 @cindex unwind-protects, dynamic binding; the specbinding stack;
7159
7160 @example
7161 struct specbinding
7162 @{
7163   Lisp_Object symbol;
7164   Lisp_Object old_value;
7165   Lisp_Object (*func) (Lisp_Object); /* for unwind-protect */
7166 @};
7167 @end example
7168
7169   @code{struct specbinding} is used for local-variable bindings and
7170 unwind-protects.  @code{specpdl} holds an array of @code{struct specbinding}'s,
7171 @code{specpdl_ptr} points to the beginning of the free bindings in the
7172 array, @code{specpdl_size} specifies the total number of binding slots
7173 in the array, and @code{max_specpdl_size} specifies the maximum number
7174 of bindings the array can be expanded to hold.  @code{grow_specpdl()}
7175 increases the size of the @code{specpdl} array, multiplying its size by
7176 2 but never exceeding @code{max_specpdl_size} (except that if this
7177 number is less than 400, it is first set to 400).
7178
7179   @code{specbind()} binds a symbol to a value and is used for local
7180 variables and @code{let} forms.  The symbol and its old value (which
7181 might be @code{Qunbound}, indicating no prior value) are recorded in the
7182 specpdl array, and @code{specpdl_size} is increased by 1.
7183
7184   @code{record_unwind_protect()} implements an @dfn{unwind-protect},
7185 which, when placed around a section of code, ensures that some specified
7186 cleanup routine will be executed even if the code exits abnormally
7187 (e.g. through a @code{throw} or quit).  @code{record_unwind_protect()}
7188 simply adds a new specbinding to the @code{specpdl} array and stores the
7189 appropriate information in it.  The cleanup routine can either be a C
7190 function, which is stored in the @code{func} field, or a @code{progn}
7191 form, which is stored in the @code{old_value} field.
7192
7193   @code{unbind_to()} removes specbindings from the @code{specpdl} array
7194 until the specified position is reached.  Each specbinding can be one of
7195 three types:
7196
7197 @enumerate
7198 @item
7199 an unwind-protect with a C cleanup function (@code{func} is not 0, and
7200 @code{old_value} holds an argument to be passed to the function);
7201 @item
7202 an unwind-protect with a Lisp form (@code{func} is 0, @code{symbol}
7203 is @code{nil}, and @code{old_value} holds the form to be executed with
7204 @code{Fprogn()}); or
7205 @item
7206 a local-variable binding (@code{func} is 0, @code{symbol} is not
7207 @code{nil}, and @code{old_value} holds the old value, which is stored as
7208 the symbol's value).
7209 @end enumerate
7210
7211 @node Simple Special Forms
7212 @section Simple Special Forms
7213 @cindex special forms, simple
7214
7215 @code{or}, @code{and}, @code{if}, @code{cond}, @code{progn},
7216 @code{prog1}, @code{prog2}, @code{setq}, @code{quote}, @code{function},
7217 @code{let*}, @code{let}, @code{while}
7218
7219 All of these are very simple and work as expected, calling
7220 @code{Feval()} or @code{Fprogn()} as necessary and (in the case of
7221 @code{let} and @code{let*}) using @code{specbind()} to create bindings
7222 and @code{unbind_to()} to undo the bindings when finished.
7223
7224 Note that, with the exception of @code{Fprogn}, these functions are
7225 typically called in real life only in interpreted code, since the byte
7226 compiler knows how to convert calls to these functions directly into
7227 byte code.
7228
7229 @node Catch and Throw
7230 @section Catch and Throw
7231 @cindex catch and throw
7232 @cindex throw, catch and
7233
7234 @example
7235 struct catchtag
7236 @{
7237   Lisp_Object tag;
7238   Lisp_Object val;
7239   struct catchtag *next;
7240   struct gcpro *gcpro;
7241   jmp_buf jmp;
7242   struct backtrace *backlist;
7243   int lisp_eval_depth;
7244   int pdlcount;
7245 @};
7246 @end example
7247
7248   @code{catch} is a Lisp function that places a catch around a body of
7249 code.  A catch is a means of non-local exit from the code.  When a catch
7250 is created, a tag is specified, and executing a @code{throw} to this tag
7251 will exit from the body of code caught with this tag, and its value will
7252 be the value given in the call to @code{throw}.  If there is no such
7253 call, the code will be executed normally.
7254
7255   Information pertaining to a catch is held in a @code{struct catchtag},
7256 which is placed at the head of a linked list pointed to by
7257 @code{catchlist}.  @code{internal_catch()} is passed a C function to
7258 call (@code{Fprogn()} when Lisp @code{catch} is called) and arguments to
7259 give it, and places a catch around the function.  Each @code{struct
7260 catchtag} is held in the stack frame of the @code{internal_catch()}
7261 instance that created the catch.
7262
7263   @code{internal_catch()} is fairly straightforward.  It stores into the
7264 @code{struct catchtag} the tag name and the current values of
7265 @code{backtrace_list}, @code{lisp_eval_depth}, @code{gcprolist}, and the
7266 offset into the @code{specpdl} array, sets a jump point with @code{_setjmp()}
7267 (storing the jump point into the @code{struct catchtag}), and calls the
7268 function.  Control will return to @code{internal_catch()} either when
7269 the function exits normally or through a @code{_longjmp()} to this jump
7270 point.  In the latter case, @code{throw} will store the value to be
7271 returned into the @code{struct catchtag} before jumping.  When it's
7272 done, @code{internal_catch()} removes the @code{struct catchtag} from
7273 the catchlist and returns the proper value.
7274
7275   @code{Fthrow()} goes up through the catchlist until it finds one with
7276 a matching tag.  It then calls @code{unbind_catch()} to restore
7277 everything to what it was when the appropriate catch was set, stores the
7278 return value in the @code{struct catchtag}, and jumps (with
7279 @code{_longjmp()}) to its jump point.
7280
7281   @code{unbind_catch()} removes all catches from the catchlist until it
7282 finds the correct one.  Some of the catches might have been placed for
7283 error-trapping, and if so, the appropriate entries on the handlerlist
7284 must be removed (see ``errors'').  @code{unbind_catch()} also restores
7285 the values of @code{gcprolist}, @code{backtrace_list}, and
7286 @code{lisp_eval}, and calls @code{unbind_to()} to undo any specbindings
7287 created since the catch.
7288
7289
7290 @node Symbols and Variables, Buffers and Textual Representation, Evaluation; Stack Frames; Bindings, Top
7291 @chapter Symbols and Variables
7292 @cindex symbols and variables
7293 @cindex variables, symbols and
7294
7295 @menu
7296 * Introduction to Symbols::
7297 * Obarrays::
7298 * Symbol Values::
7299 @end menu
7300
7301 @node Introduction to Symbols
7302 @section Introduction to Symbols
7303 @cindex symbols, introduction to
7304
7305   A symbol is basically just an object with four fields: a name (a
7306 string), a value (some Lisp object), a function (some Lisp object), and
7307 a property list (usually a list of alternating keyword/value pairs).
7308 What makes symbols special is that there is usually only one symbol with
7309 a given name, and the symbol is referred to by name.  This makes a
7310 symbol a convenient way of calling up data by name, i.e. of implementing
7311 variables. (The variable's value is stored in the @dfn{value slot}.)
7312 Similarly, functions are referenced by name, and the definition of the
7313 function is stored in a symbol's @dfn{function slot}.  This means that
7314 there can be a distinct function and variable with the same name.  The
7315 property list is used as a more general mechanism of associating
7316 additional values with particular names, and once again the namespace is
7317 independent of the function and variable namespaces.
7318
7319 @node Obarrays
7320 @section Obarrays
7321 @cindex obarrays
7322
7323   The identity of symbols with their names is accomplished through a
7324 structure called an obarray, which is just a poorly-implemented hash
7325 table mapping from strings to symbols whose name is that string. (I say
7326 ``poorly implemented'' because an obarray appears in Lisp as a vector
7327 with some hidden fields rather than as its own opaque type.  This is an
7328 Emacs Lisp artifact that should be fixed.)
7329
7330   Obarrays are implemented as a vector of some fixed size (which should
7331 be a prime for best results), where each ``bucket'' of the vector
7332 contains one or more symbols, threaded through a hidden @code{next}
7333 field in the symbol.  Lookup of a symbol in an obarray, and adding a
7334 symbol to an obarray, is accomplished through standard hash-table
7335 techniques.
7336
7337   The standard Lisp function for working with symbols and obarrays is
7338 @code{intern}.  This looks up a symbol in an obarray given its name; if
7339 it's not found, a new symbol is automatically created with the specified
7340 name, added to the obarray, and returned.  This is what happens when the
7341 Lisp reader encounters a symbol (or more precisely, encounters the name
7342 of a symbol) in some text that it is reading.  There is a standard
7343 obarray called @code{obarray} that is used for this purpose, although
7344 the Lisp programmer is free to create his own obarrays and @code{intern}
7345 symbols in them.
7346
7347   Note that, once a symbol is in an obarray, it stays there until
7348 something is done about it, and the standard obarray @code{obarray}
7349 always stays around, so once you use any particular variable name, a
7350 corresponding symbol will stay around in @code{obarray} until you exit
7351 XEmacs.
7352
7353   Note that @code{obarray} itself is a variable, and as such there is a
7354 symbol in @code{obarray} whose name is @code{"obarray"} and which
7355 contains @code{obarray} as its value.
7356
7357   Note also that this call to @code{intern} occurs only when in the Lisp
7358 reader, not when the code is executed (at which point the symbol is
7359 already around, stored as such in the definition of the function).
7360
7361   You can create your own obarray using @code{make-vector} (this is
7362 horrible but is an artifact) and intern symbols into that obarray.
7363 Doing that will result in two or more symbols with the same name.
7364 However, at most one of these symbols is in the standard @code{obarray}:
7365 You cannot have two symbols of the same name in any particular obarray.
7366 Note that you cannot add a symbol to an obarray in any fashion other
7367 than using @code{intern}: i.e. you can't take an existing symbol and put
7368 it in an existing obarray.  Nor can you change the name of an existing
7369 symbol. (Since obarrays are vectors, you can violate the consistency of
7370 things by storing directly into the vector, but let's ignore that
7371 possibility.)
7372
7373   Usually symbols are created by @code{intern}, but if you really want,
7374 you can explicitly create a symbol using @code{make-symbol}, giving it
7375 some name.  The resulting symbol is not in any obarray (i.e. it is
7376 @dfn{uninterned}), and you can't add it to any obarray.  Therefore its
7377 primary purpose is as a symbol to use in macros to avoid namespace
7378 pollution.  It can also be used as a carrier of information, but cons
7379 cells could probably be used just as well.
7380
7381   You can also use @code{intern-soft} to look up a symbol but not create
7382 a new one, and @code{unintern} to remove a symbol from an obarray.  This
7383 returns the removed symbol. (Remember: You can't put the symbol back
7384 into any obarray.) Finally, @code{mapatoms} maps over all of the symbols
7385 in an obarray.
7386
7387 @node Symbol Values
7388 @section Symbol Values
7389 @cindex symbol values
7390 @cindex values, symbol
7391
7392   The value field of a symbol normally contains a Lisp object.  However,
7393 a symbol can be @dfn{unbound}, meaning that it logically has no value.
7394 This is internally indicated by storing a special Lisp object, called
7395 @dfn{the unbound marker} and stored in the global variable
7396 @code{Qunbound}.  The unbound marker is of a special Lisp object type
7397 called @dfn{symbol-value-magic}.  It is impossible for the Lisp
7398 programmer to directly create or access any object of this type.
7399
7400   @strong{You must not let any ``symbol-value-magic'' object escape to
7401 the Lisp level.}  Printing any of these objects will cause the message
7402 @samp{INTERNAL EMACS BUG} to appear as part of the print representation.
7403 (You may see this normally when you call @code{debug_print()} from the
7404 debugger on a Lisp object.) If you let one of these objects escape to
7405 the Lisp level, you will violate a number of assumptions contained in
7406 the C code and make the unbound marker not function right.
7407
7408   When a symbol is created, its value field (and function field) are set
7409 to @code{Qunbound}.  The Lisp programmer can restore these conditions
7410 later using @code{makunbound} or @code{fmakunbound}, and can query to
7411 see whether the value of function fields are @dfn{bound} (i.e. have a
7412 value other than @code{Qunbound}) using @code{boundp} and
7413 @code{fboundp}.  The fields are set to a normal Lisp object using
7414 @code{set} (or @code{setq}) and @code{fset}.
7415
7416   Other symbol-value-magic objects are used as special markers to
7417 indicate variables that have non-normal properties.  This includes any
7418 variables that are tied into C variables (setting the variable magically
7419 sets some global variable in the C code, and likewise for retrieving the
7420 variable's value), variables that magically tie into slots in the
7421 current buffer, variables that are buffer-local, etc.  The
7422 symbol-value-magic object is stored in the value cell in place of
7423 a normal object, and the code to retrieve a symbol's value
7424 (i.e. @code{symbol-value}) knows how to do special things with them.
7425 This means that you should not just fetch the value cell directly if you
7426 want a symbol's value.
7427
7428   The exact workings of this are rather complex and involved and are
7429 well-documented in comments in @file{buffer.c}, @file{symbols.c}, and
7430 @file{lisp.h}.
7431
7432 @node Buffers and Textual Representation, MULE Character Sets and Encodings, Symbols and Variables, Top
7433 @chapter Buffers and Textual Representation
7434 @cindex buffers and textual representation
7435 @cindex textual representation, buffers and
7436
7437 @menu
7438 * Introduction to Buffers::     A buffer holds a block of text such as a file.
7439 * The Text in a Buffer::        Representation of the text in a buffer.
7440 * Buffer Lists::                Keeping track of all buffers.
7441 * Markers and Extents::         Tagging locations within a buffer.
7442 * Bufbytes and Emchars::        Representation of individual characters.
7443 * The Buffer Object::           The Lisp object corresponding to a buffer.
7444 @end menu
7445
7446 @node Introduction to Buffers
7447 @section Introduction to Buffers
7448 @cindex buffers, introduction to
7449
7450   A buffer is logically just a Lisp object that holds some text.
7451 In this, it is like a string, but a buffer is optimized for
7452 frequent insertion and deletion, while a string is not.  Furthermore:
7453
7454 @enumerate
7455 @item
7456 Buffers are @dfn{permanent} objects, i.e. once you create them, they
7457 remain around, and need to be explicitly deleted before they go away.
7458 @item
7459 Each buffer has a unique name, which is a string.  Buffers are
7460 normally referred to by name.  In this respect, they are like
7461 symbols.
7462 @item
7463 Buffers have a default insertion position, called @dfn{point}.
7464 Inserting text (unless you explicitly give a position) goes at point,
7465 and moves point forward past the text.  This is what is going on when
7466 you type text into Emacs.
7467 @item
7468 Buffers have lots of extra properties associated with them.
7469 @item
7470 Buffers can be @dfn{displayed}.  What this means is that there
7471 exist a number of @dfn{windows}, which are objects that correspond
7472 to some visible section of your display, and each window has
7473 an associated buffer, and the current contents of the buffer
7474 are shown in that section of the display.  The redisplay mechanism
7475 (which takes care of doing this) knows how to look at the
7476 text of a buffer and come up with some reasonable way of displaying
7477 this.  Many of the properties of a buffer control how the
7478 buffer's text is displayed.
7479 @item
7480 One buffer is distinguished and called the @dfn{current buffer}.  It is
7481 stored in the variable @code{current_buffer}.  Buffer operations operate
7482 on this buffer by default.  When you are typing text into a buffer, the
7483 buffer you are typing into is always @code{current_buffer}.  Switching
7484 to a different window changes the current buffer.  Note that Lisp code
7485 can temporarily change the current buffer using @code{set-buffer} (often
7486 enclosed in a @code{save-excursion} so that the former current buffer
7487 gets restored when the code is finished).  However, calling
7488 @code{set-buffer} will NOT cause a permanent change in the current
7489 buffer.  The reason for this is that the top-level event loop sets
7490 @code{current_buffer} to the buffer of the selected window, each time
7491 it finishes executing a user command.
7492 @end enumerate
7493
7494   Make sure you understand the distinction between @dfn{current buffer}
7495 and @dfn{buffer of the selected window}, and the distinction between
7496 @dfn{point} of the current buffer and @dfn{window-point} of the selected
7497 window. (This latter distinction is explained in detail in the section
7498 on windows.)
7499
7500 @node The Text in a Buffer
7501 @section The Text in a Buffer
7502 @cindex text in a buffer, the
7503 @cindex buffer, the text in a
7504
7505   The text in a buffer consists of a sequence of zero or more
7506 characters.  A @dfn{character} is an integer that logically represents
7507 a letter, number, space, or other unit of text.  Most of the characters
7508 that you will typically encounter belong to the ASCII set of characters,
7509 but there are also characters for various sorts of accented letters,
7510 special symbols, Chinese and Japanese ideograms (i.e. Kanji, Katakana,
7511 etc.), Cyrillic and Greek letters, etc.  The actual number of possible
7512 characters is quite large.
7513
7514   For now, we can view a character as some non-negative integer that
7515 has some shape that defines how it typically appears (e.g. as an
7516 uppercase A). (The exact way in which a character appears depends on the
7517 font used to display the character.) The internal type of characters in
7518 the C code is an @code{Emchar}; this is just an @code{int}, but using a
7519 symbolic type makes the code clearer.
7520
7521   Between every character in a buffer is a @dfn{buffer position} or
7522 @dfn{character position}.  We can speak of the character before or after
7523 a particular buffer position, and when you insert a character at a
7524 particular position, all characters after that position end up at new
7525 positions.  When we speak of the character @dfn{at} a position, we
7526 really mean the character after the position.  (This schizophrenia
7527 between a buffer position being ``between'' a character and ``on'' a
7528 character is rampant in Emacs.)
7529
7530   Buffer positions are numbered starting at 1.  This means that
7531 position 1 is before the first character, and position 0 is not
7532 valid.  If there are N characters in a buffer, then buffer
7533 position N+1 is after the last one, and position N+2 is not valid.
7534
7535   The internal makeup of the Emchar integer varies depending on whether
7536 we have compiled with MULE support.  If not, the Emchar integer is an
7537 8-bit integer with possible values from 0 - 255.  0 - 127 are the
7538 standard ASCII characters, while 128 - 255 are the characters from the
7539 ISO-8859-1 character set.  If we have compiled with MULE support, an
7540 Emchar is a 19-bit integer, with the various bits having meanings
7541 according to a complex scheme that will be detailed later.  The
7542 characters numbered 0 - 255 still have the same meanings as for the
7543 non-MULE case, though.
7544
7545   Internally, the text in a buffer is represented in a fairly simple
7546 fashion: as a contiguous array of bytes, with a @dfn{gap} of some size
7547 in the middle.  Although the gap is of some substantial size in bytes,
7548 there is no text contained within it: From the perspective of the text
7549 in the buffer, it does not exist.  The gap logically sits at some buffer
7550 position, between two characters (or possibly at the beginning or end of
7551 the buffer).  Insertion of text in a buffer at a particular position is
7552 always accomplished by first moving the gap to that position
7553 (i.e. through some block moving of text), then writing the text into the
7554 beginning of the gap, thereby shrinking the gap.  If the gap shrinks
7555 down to nothing, a new gap is created. (What actually happens is that a
7556 new gap is ``created'' at the end of the buffer's text, which requires
7557 nothing more than changing a couple of indices; then the gap is
7558 ``moved'' to the position where the insertion needs to take place by
7559 moving up in memory all the text after that position.)  Similarly,
7560 deletion occurs by moving the gap to the place where the text is to be
7561 deleted, and then simply expanding the gap to include the deleted text.
7562 (@dfn{Expanding} and @dfn{shrinking} the gap as just described means
7563 just that the internal indices that keep track of where the gap is
7564 located are changed.)
7565
7566   Note that the total amount of memory allocated for a buffer text never
7567 decreases while the buffer is live.  Therefore, if you load up a
7568 20-megabyte file and then delete all but one character, there will be a
7569 20-megabyte gap, which won't get any smaller (except by inserting
7570 characters back again).  Once the buffer is killed, the memory allocated
7571 for the buffer text will be freed, but it will still be sitting on the
7572 heap, taking up virtual memory, and will not be released back to the
7573 operating system. (However, if you have compiled XEmacs with rel-alloc,
7574 the situation is different.  In this case, the space @emph{will} be
7575 released back to the operating system.  However, this tends to result in a
7576 noticeable speed penalty.)
7577
7578   Astute readers may notice that the text in a buffer is represented as
7579 an array of @emph{bytes}, while (at least in the MULE case) an Emchar is
7580 a 19-bit integer, which clearly cannot fit in a byte.  This means (of
7581 course) that the text in a buffer uses a different representation from
7582 an Emchar: specifically, the 19-bit Emchar becomes a series of one to
7583 four bytes.  The conversion between these two representations is complex
7584 and will be described later.
7585
7586   In the non-MULE case, everything is very simple: An Emchar
7587 is an 8-bit value, which fits neatly into one byte.
7588
7589   If we are given a buffer position and want to retrieve the
7590 character at that position, we need to follow these steps:
7591
7592 @enumerate
7593 @item
7594 Pretend there's no gap, and convert the buffer position into a @dfn{byte
7595 index} that indexes to the appropriate byte in the buffer's stream of
7596 textual bytes.  By convention, byte indices begin at 1, just like buffer
7597 positions.  In the non-MULE case, byte indices and buffer positions are
7598 identical, since one character equals one byte.
7599 @item
7600 Convert the byte index into a @dfn{memory index}, which takes the gap
7601 into account.  The memory index is a direct index into the block of
7602 memory that stores the text of a buffer.  This basically just involves
7603 checking to see if the byte index is past the gap, and if so, adding the
7604 size of the gap to it.  By convention, memory indices begin at 1, just
7605 like buffer positions and byte indices, and when referring to the
7606 position that is @dfn{at} the gap, we always use the memory position at
7607 the @emph{beginning}, not at the end, of the gap.
7608 @item
7609 Fetch the appropriate bytes at the determined memory position.
7610 @item
7611 Convert these bytes into an Emchar.
7612 @end enumerate
7613
7614   In the non-Mule case, (3) and (4) boil down to a simple one-byte
7615 memory access.
7616
7617   Note that we have defined three types of positions in a buffer:
7618
7619 @enumerate
7620 @item
7621 @dfn{buffer positions} or @dfn{character positions}, typedef @code{Bufpos}
7622 @item
7623 @dfn{byte indices}, typedef @code{Bytind}
7624 @item
7625 @dfn{memory indices}, typedef @code{Memind}
7626 @end enumerate
7627
7628   All three typedefs are just @code{int}s, but defining them this way makes
7629 things a lot clearer.
7630
7631   Most code works with buffer positions.  In particular, all Lisp code
7632 that refers to text in a buffer uses buffer positions.  Lisp code does
7633 not know that byte indices or memory indices exist.
7634
7635   Finally, we have a typedef for the bytes in a buffer.  This is a
7636 @code{Bufbyte}, which is an unsigned char.  Referring to them as
7637 Bufbytes underscores the fact that we are working with a string of bytes
7638 in the internal Emacs buffer representation rather than in one of a
7639 number of possible alternative representations (e.g. EUC-encoded text,
7640 etc.).
7641
7642 @node Buffer Lists
7643 @section Buffer Lists
7644 @cindex buffer lists
7645
7646   Recall earlier that buffers are @dfn{permanent} objects, i.e.  that
7647 they remain around until explicitly deleted.  This entails that there is
7648 a list of all the buffers in existence.  This list is actually an
7649 assoc-list (mapping from the buffer's name to the buffer) and is stored
7650 in the global variable @code{Vbuffer_alist}.
7651
7652   The order of the buffers in the list is important: the buffers are
7653 ordered approximately from most-recently-used to least-recently-used.
7654 Switching to a buffer using @code{switch-to-buffer},
7655 @code{pop-to-buffer}, etc. and switching windows using
7656 @code{other-window}, etc.  usually brings the new current buffer to the
7657 front of the list.  @code{switch-to-buffer}, @code{other-buffer},
7658 etc. look at the beginning of the list to find an alternative buffer to
7659 suggest.  You can also explicitly move a buffer to the end of the list
7660 using @code{bury-buffer}.
7661
7662   In addition to the global ordering in @code{Vbuffer_alist}, each frame
7663 has its own ordering of the list.  These lists always contain the same
7664 elements as in @code{Vbuffer_alist} although possibly in a different
7665 order.  @code{buffer-list} normally returns the list for the selected
7666 frame.  This allows you to work in separate frames without things
7667 interfering with each other.
7668
7669   The standard way to look up a buffer given a name is
7670 @code{get-buffer}, and the standard way to create a new buffer is
7671 @code{get-buffer-create}, which looks up a buffer with a given name,
7672 creating a new one if necessary.  These operations correspond exactly
7673 with the symbol operations @code{intern-soft} and @code{intern},
7674 respectively.  You can also force a new buffer to be created using
7675 @code{generate-new-buffer}, which takes a name and (if necessary) makes
7676 a unique name from this by appending a number, and then creates the
7677 buffer.  This is basically like the symbol operation @code{gensym}.
7678
7679 @node Markers and Extents
7680 @section Markers and Extents
7681 @cindex markers and extents
7682 @cindex extents, markers and
7683
7684   Among the things associated with a buffer are things that are
7685 logically attached to certain buffer positions.  This can be used to
7686 keep track of a buffer position when text is inserted and deleted, so
7687 that it remains at the same spot relative to the text around it; to
7688 assign properties to particular sections of text; etc.  There are two
7689 such objects that are useful in this regard: they are @dfn{markers} and
7690 @dfn{extents}.
7691
7692   A @dfn{marker} is simply a flag placed at a particular buffer
7693 position, which is moved around as text is inserted and deleted.
7694 Markers are used for all sorts of purposes, such as the @code{mark} that
7695 is the other end of textual regions to be cut, copied, etc.
7696
7697   An @dfn{extent} is similar to two markers plus some associated
7698 properties, and is used to keep track of regions in a buffer as text is
7699 inserted and deleted, and to add properties (e.g. fonts) to particular
7700 regions of text.  The external interface of extents is explained
7701 elsewhere.
7702
7703   The important thing here is that markers and extents simply contain
7704 buffer positions in them as integers, and every time text is inserted or
7705 deleted, these positions must be updated.  In order to minimize the
7706 amount of shuffling that needs to be done, the positions in markers and
7707 extents (there's one per marker, two per extent) are stored in Meminds.
7708 This means that they only need to be moved when the text is physically
7709 moved in memory; since the gap structure tries to minimize this, it also
7710 minimizes the number of marker and extent indices that need to be
7711 adjusted.  Look in @file{insdel.c} for the details of how this works.
7712
7713   One other important distinction is that markers are @dfn{temporary}
7714 while extents are @dfn{permanent}.  This means that markers disappear as
7715 soon as there are no more pointers to them, and correspondingly, there
7716 is no way to determine what markers are in a buffer if you are just
7717 given the buffer.  Extents remain in a buffer until they are detached
7718 (which could happen as a result of text being deleted) or the buffer is
7719 deleted, and primitives do exist to enumerate the extents in a buffer.
7720
7721 @node Bufbytes and Emchars
7722 @section Bufbytes and Emchars
7723 @cindex Bufbytes and Emchars
7724 @cindex Emchars, Bufbytes and
7725
7726   Not yet documented.
7727
7728 @node The Buffer Object
7729 @section The Buffer Object
7730 @cindex buffer object, the
7731 @cindex object, the buffer
7732
7733   Buffers contain fields not directly accessible by the Lisp programmer.
7734 We describe them here, naming them by the names used in the C code.
7735 Many are accessible indirectly in Lisp programs via Lisp primitives.
7736
7737 @table @code
7738 @item name
7739 The buffer name is a string that names the buffer.  It is guaranteed to
7740 be unique.  @xref{Buffer Names,,, lispref, XEmacs Lisp Reference
7741 Manual}.
7742
7743 @item save_modified
7744 This field contains the time when the buffer was last saved, as an
7745 integer.  @xref{Buffer Modification,,, lispref, XEmacs Lisp Reference
7746 Manual}.
7747
7748 @item modtime
7749 This field contains the modification time of the visited file.  It is
7750 set when the file is written or read.  Every time the buffer is written
7751 to the file, this field is compared to the modification time of the
7752 file.  @xref{Buffer Modification,,, lispref, XEmacs Lisp Reference
7753 Manual}.
7754
7755 @item auto_save_modified
7756 This field contains the time when the buffer was last auto-saved.
7757
7758 @item last_window_start
7759 This field contains the @code{window-start} position in the buffer as of
7760 the last time the buffer was displayed in a window.
7761
7762 @item undo_list
7763 This field points to the buffer's undo list.  @xref{Undo,,, lispref,
7764 XEmacs Lisp Reference Manual}.
7765
7766 @item syntax_table_v
7767 This field contains the syntax table for the buffer.  @xref{Syntax
7768 Tables,,, lispref, XEmacs Lisp Reference Manual}.
7769
7770 @item downcase_table
7771 This field contains the conversion table for converting text to lower
7772 case.  @xref{Case Tables,,, lispref, XEmacs Lisp Reference Manual}.
7773
7774 @item upcase_table
7775 This field contains the conversion table for converting text to upper
7776 case.  @xref{Case Tables,,, lispref, XEmacs Lisp Reference Manual}.
7777
7778 @item case_canon_table
7779 This field contains the conversion table for canonicalizing text for
7780 case-folding search.  @xref{Case Tables,,, lispref, XEmacs Lisp
7781 Reference Manual}.
7782
7783 @item case_eqv_table
7784 This field contains the equivalence table for case-folding search.
7785 @xref{Case Tables,,, lispref, XEmacs Lisp Reference Manual}.
7786
7787 @item display_table
7788 This field contains the buffer's display table, or @code{nil} if it
7789 doesn't have one.  @xref{Display Tables,,, lispref, XEmacs Lisp
7790 Reference Manual}.
7791
7792 @item markers
7793 This field contains the chain of all markers that currently point into
7794 the buffer.  Deletion of text in the buffer, and motion of the buffer's
7795 gap, must check each of these markers and perhaps update it.
7796 @xref{Markers,,, lispref, XEmacs Lisp Reference Manual}.
7797
7798 @item backed_up
7799 This field is a flag that tells whether a backup file has been made for
7800 the visited file of this buffer.
7801
7802 @item mark
7803 This field contains the mark for the buffer.  The mark is a marker,
7804 hence it is also included on the list @code{markers}.  @xref{The Mark,,,
7805 lispref, XEmacs Lisp Reference Manual}.
7806
7807 @item mark_active
7808 This field is non-@code{nil} if the buffer's mark is active.
7809
7810 @item local_var_alist
7811 This field contains the association list describing the variables local
7812 in this buffer, and their values, with the exception of local variables
7813 that have special slots in the buffer object.  (Those slots are omitted
7814 from this table.)  @xref{Buffer-Local Variables,,, lispref, XEmacs Lisp
7815 Reference Manual}.
7816
7817 @item modeline_format
7818 This field contains a Lisp object which controls how to display the mode
7819 line for this buffer.  @xref{Modeline Format,,, lispref, XEmacs Lisp
7820 Reference Manual}.
7821
7822 @item base_buffer
7823 This field holds the buffer's base buffer (if it is an indirect buffer),
7824 or @code{nil}.
7825 @end table
7826
7827 @node MULE Character Sets and Encodings, The Lisp Reader and Compiler, Buffers and Textual Representation, Top
7828 @chapter MULE Character Sets and Encodings
7829 @cindex Mule character sets and encodings
7830 @cindex character sets and encodings, Mule
7831 @cindex encodings, Mule character sets and
7832
7833   Recall that there are two primary ways that text is represented in
7834 XEmacs.  The @dfn{buffer} representation sees the text as a series of
7835 bytes (Bufbytes), with a variable number of bytes used per character.
7836 The @dfn{character} representation sees the text as a series of integers
7837 (Emchars), one per character.  The character representation is a cleaner
7838 representation from a theoretical standpoint, and is thus used in many
7839 cases when lots of manipulations on a string need to be done.  However,
7840 the buffer representation is the standard representation used in both
7841 Lisp strings and buffers, and because of this, it is the ``default''
7842 representation that text comes in.  The reason for using this
7843 representation is that it's compact and is compatible with ASCII.
7844
7845 @menu
7846 * Character Sets::
7847 * Encodings::
7848 * Internal Mule Encodings::
7849 * CCL::
7850 @end menu
7851
7852 @node Character Sets
7853 @section Character Sets
7854 @cindex character sets
7855
7856   A character set (or @dfn{charset}) is an ordered set of characters.  A
7857 particular character in a charset is indexed using one or more
7858 @dfn{position codes}, which are non-negative integers.  The number of
7859 position codes needed to identify a particular character in a charset is
7860 called the @dfn{dimension} of the charset.  In XEmacs/Mule, all charsets
7861 have dimension 1 or 2, and the size of all charsets (except for a few
7862 special cases) is either 94, 96, 94 by 94, or 96 by 96.  The range of
7863 position codes used to index characters from any of these types of
7864 character sets is as follows:
7865
7866 @example
7867 Charset type            Position code 1         Position code 2
7868 ------------------------------------------------------------
7869 94                      33 - 126                N/A
7870 96                      32 - 127                N/A
7871 94x94                   33 - 126                33 - 126
7872 96x96                   32 - 127                32 - 127
7873 @end example
7874
7875   Note that in the above cases position codes do not start at an
7876 expected value such as 0 or 1.  The reason for this will become clear
7877 later.
7878
7879   For example, Latin-1 is a 96-character charset, and JISX0208 (the
7880 Japanese national character set) is a 94x94-character charset.
7881
7882   [Note that, although the ranges above define the @emph{valid} position
7883 codes for a charset, some of the slots in a particular charset may in
7884 fact be empty.  This is the case for JISX0208, for example, where (e.g.)
7885 all the slots whose first position code is in the range 118 - 127 are
7886 empty.]
7887
7888   There are three charsets that do not follow the above rules.  All of
7889 them have one dimension, and have ranges of position codes as follows:
7890
7891 @example
7892 Charset name            Position code 1
7893 ------------------------------------
7894 ASCII                   0 - 127
7895 Control-1               0 - 31
7896 Composite               0 - some large number
7897 @end example
7898
7899   (The upper bound of the position code for composite characters has not
7900 yet been determined, but it will probably be at least 16,383).
7901
7902   ASCII is the union of two subsidiary character sets: Printing-ASCII
7903 (the printing ASCII character set, consisting of position codes 33 -
7904 126, like for a standard 94-character charset) and Control-ASCII (the
7905 non-printing characters that would appear in a binary file with codes 0
7906 - 32 and 127).
7907
7908   Control-1 contains the non-printing characters that would appear in a
7909 binary file with codes 128 - 159.
7910
7911   Composite contains characters that are generated by overstriking one
7912 or more characters from other charsets.
7913
7914   Note that some characters in ASCII, and all characters in Control-1,
7915 are @dfn{control} (non-printing) characters.  These have no printed
7916 representation but instead control some other function of the printing
7917 (e.g. TAB or 8 moves the current character position to the next tab
7918 stop).  All other characters in all charsets are @dfn{graphic}
7919 (printing) characters.
7920
7921   When a binary file is read in, the bytes in the file are assigned to
7922 character sets as follows:
7923
7924 @example
7925 Bytes           Character set           Range
7926 --------------------------------------------------
7927 0 - 127         ASCII                   0 - 127
7928 128 - 159       Control-1               0 - 31
7929 160 - 255       Latin-1                 32 - 127
7930 @end example
7931
7932   This is a bit ad-hoc but gets the job done.
7933
7934 @node Encodings
7935 @section Encodings
7936 @cindex encodings, Mule
7937 @cindex Mule encodings
7938
7939   An @dfn{encoding} is a way of numerically representing characters from
7940 one or more character sets.  If an encoding only encompasses one
7941 character set, then the position codes for the characters in that
7942 character set could be used directly.  This is not possible, however, if
7943 more than one character set is to be used in the encoding.
7944
7945   For example, the conversion detailed above between bytes in a binary
7946 file and characters is effectively an encoding that encompasses the
7947 three character sets ASCII, Control-1, and Latin-1 in a stream of 8-bit
7948 bytes.
7949
7950   Thus, an encoding can be viewed as a way of encoding characters from a
7951 specified group of character sets using a stream of bytes, each of which
7952 contains a fixed number of bits (but not necessarily 8, as in the common
7953 usage of ``byte'').
7954
7955   Here are descriptions of a couple of common
7956 encodings:
7957
7958 @menu
7959 * Japanese EUC (Extended Unix Code)::
7960 * JIS7::
7961 @end menu
7962
7963 @node Japanese EUC (Extended Unix Code)
7964 @subsection Japanese EUC (Extended Unix Code)
7965 @cindex Japanese EUC (Extended Unix Code)
7966 @cindex EUC (Extended Unix Code), Japanese
7967 @cindex Extended Unix Code, Japanese EUC
7968
7969 This encompasses the character sets Printing-ASCII, Japanese-JISX0201,
7970 and Japanese-JISX0208-Kana (half-width katakana, the right half of
7971 JISX0201).  It uses 8-bit bytes.
7972
7973 Note that Printing-ASCII and Japanese-JISX0201-Kana are 94-character
7974 charsets, while Japanese-JISX0208 is a 94x94-character charset.
7975
7976 The encoding is as follows:
7977
7978 @example
7979 Character set            Representation (PC=position-code)
7980 -------------            --------------
7981 Printing-ASCII           PC1
7982 Japanese-JISX0201-Kana   0x8E       | PC1 + 0x80
7983 Japanese-JISX0208        PC1 + 0x80 | PC2 + 0x80
7984 Japanese-JISX0212        PC1 + 0x80 | PC2 + 0x80
7985 @end example
7986
7987
7988 @node JIS7
7989 @subsection JIS7
7990 @cindex JIS7
7991
7992 This encompasses the character sets Printing-ASCII,
7993 Japanese-JISX0201-Roman (the left half of JISX0201; this character set
7994 is very similar to Printing-ASCII and is a 94-character charset),
7995 Japanese-JISX0208, and Japanese-JISX0201-Kana.  It uses 7-bit bytes.
7996
7997 Unlike Japanese EUC, this is a @dfn{modal} encoding, which
7998 means that there are multiple states that the encoding can
7999 be in, which affect how the bytes are to be interpreted.
8000 Special sequences of bytes (called @dfn{escape sequences})
8001 are used to change states.
8002
8003   The encoding is as follows:
8004
8005 @example
8006 Character set              Representation (PC=position-code)
8007 -------------              --------------
8008 Printing-ASCII             PC1
8009 Japanese-JISX0201-Roman    PC1
8010 Japanese-JISX0201-Kana     PC1
8011 Japanese-JISX0208          PC1 PC2
8012
8013
8014 Escape sequence   ASCII equivalent   Meaning
8015 ---------------   ----------------   -------
8016 0x1B 0x28 0x4A    ESC ( J            invoke Japanese-JISX0201-Roman
8017 0x1B 0x28 0x49    ESC ( I            invoke Japanese-JISX0201-Kana
8018 0x1B 0x24 0x42    ESC $ B            invoke Japanese-JISX0208
8019 0x1B 0x28 0x42    ESC ( B            invoke Printing-ASCII
8020 @end example
8021
8022   Initially, Printing-ASCII is invoked.
8023
8024 @node Internal Mule Encodings
8025 @section Internal Mule Encodings
8026 @cindex internal Mule encodings
8027 @cindex Mule encodings, internal
8028 @cindex encodings, internal Mule
8029
8030 In XEmacs/Mule, each character set is assigned a unique number, called a
8031 @dfn{leading byte}.  This is used in the encodings of a character.
8032 Leading bytes are in the range 0x80 - 0xFF (except for ASCII, which has
8033 a leading byte of 0), although some leading bytes are reserved.
8034
8035 Charsets whose leading byte is in the range 0x80 - 0x9F are called
8036 @dfn{official} and are used for built-in charsets.  Other charsets are
8037 called @dfn{private} and have leading bytes in the range 0xA0 - 0xFF;
8038 these are user-defined charsets.
8039
8040   More specifically:
8041
8042 @example
8043 Character set           Leading byte
8044 -------------           ------------
8045 ASCII                   0
8046 Composite               0x80
8047 Dimension-1 Official    0x81 - 0x8D
8048                           (0x8E is free)
8049 Control-1               0x8F
8050 Dimension-2 Official    0x90 - 0x99
8051                           (0x9A - 0x9D are free;
8052                            0x9E and 0x9F are reserved)
8053 Dimension-1 Private     0xA0 - 0xEF
8054 Dimension-2 Private     0xF0 - 0xFF
8055 @end example
8056
8057 There are two internal encodings for characters in XEmacs/Mule.  One is
8058 called @dfn{string encoding} and is an 8-bit encoding that is used for
8059 representing characters in a buffer or string.  It uses 1 to 4 bytes per
8060 character.  The other is called @dfn{character encoding} and is a 19-bit
8061 encoding that is used for representing characters individually in a
8062 variable.
8063
8064 (In the following descriptions, we'll ignore composite characters for
8065 the moment.  We also give a general (structural) overview first,
8066 followed later by the exact details.)
8067
8068 @menu
8069 * Internal String Encoding::
8070 * Internal Character Encoding::
8071 @end menu
8072
8073 @node Internal String Encoding
8074 @subsection Internal String Encoding
8075 @cindex internal string encoding
8076 @cindex string encoding, internal
8077 @cindex encoding, internal string
8078
8079 ASCII characters are encoded using their position code directly.  Other
8080 characters are encoded using their leading byte followed by their
8081 position code(s) with the high bit set.  Characters in private character
8082 sets have their leading byte prefixed with a @dfn{leading byte prefix},
8083 which is either 0x9E or 0x9F. (No character sets are ever assigned these
8084 leading bytes.) Specifically:
8085
8086 @example
8087 Character set           Encoding (PC=position-code, LB=leading-byte)
8088 -------------           --------
8089 ASCII                   PC-1 |
8090 Control-1               LB   |  PC1 + 0xA0 |
8091 Dimension-1 official    LB   |  PC1 + 0x80 |
8092 Dimension-1 private     0x9E |  LB         | PC1 + 0x80 |
8093 Dimension-2 official    LB   |  PC1 + 0x80 | PC2 + 0x80 |
8094 Dimension-2 private     0x9F |  LB         | PC1 + 0x80 | PC2 + 0x80
8095 @end example
8096
8097   The basic characteristic of this encoding is that the first byte
8098 of all characters is in the range 0x00 - 0x9F, and the second and
8099 following bytes of all characters is in the range 0xA0 - 0xFF.
8100 This means that it is impossible to get out of sync, or more
8101 specifically:
8102
8103 @enumerate
8104 @item
8105 Given any byte position, the beginning of the character it is
8106 within can be determined in constant time.
8107 @item
8108 Given any byte position at the beginning of a character, the
8109 beginning of the next character can be determined in constant
8110 time.
8111 @item
8112 Given any byte position at the beginning of a character, the
8113 beginning of the previous character can be determined in constant
8114 time.
8115 @item
8116 Textual searches can simply treat encoded strings as if they
8117 were encoded in a one-byte-per-character fashion rather than
8118 the actual multi-byte encoding.
8119 @end enumerate
8120
8121   None of the standard non-modal encodings meet all of these
8122 conditions.  For example, EUC satisfies only (2) and (3), while
8123 Shift-JIS and Big5 (not yet described) satisfy only (2). (All
8124 non-modal encodings must satisfy (2), in order to be unambiguous.)
8125
8126 @node Internal Character Encoding
8127 @subsection Internal Character Encoding
8128 @cindex internal character encoding
8129 @cindex character encoding, internal
8130 @cindex encoding, internal character
8131
8132   One 19-bit word represents a single character.  The word is
8133 separated into three fields:
8134
8135 @example
8136 Bit number:     18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
8137                 <------------> <------------------> <------------------>
8138 Field:                1                  2                    3
8139 @end example
8140
8141   Note that fields 2 and 3 hold 7 bits each, while field 1 holds 5 bits.
8142
8143 @example
8144 Character set           Field 1         Field 2         Field 3
8145 -------------           -------         -------         -------
8146 ASCII                      0               0              PC1
8147    range:                                                   (00 - 7F)
8148 Control-1                  0               1              PC1
8149    range:                                                   (00 - 1F)
8150 Dimension-1 official       0            LB - 0x80         PC1
8151    range:                                    (01 - 0D)      (20 - 7F)
8152 Dimension-1 private        0            LB - 0x80         PC1
8153    range:                                    (20 - 6F)      (20 - 7F)
8154 Dimension-2 official    LB - 0x8F         PC1             PC2
8155    range:                    (01 - 0A)       (20 - 7F)      (20 - 7F)
8156 Dimension-2 private     LB - 0xE1         PC1             PC2
8157    range:                    (0F - 1E)       (20 - 7F)      (20 - 7F)
8158 Composite                 0x1F             ?               ?
8159 @end example
8160
8161   Note that character codes 0 - 255 are the same as the ``binary encoding''
8162 described above.
8163
8164 @node CCL
8165 @section CCL
8166 @cindex CCL
8167
8168 @example
8169 CCL PROGRAM SYNTAX:
8170      CCL_PROGRAM := (CCL_MAIN_BLOCK
8171                      [ CCL_EOF_BLOCK ])
8172
8173      CCL_MAIN_BLOCK := CCL_BLOCK
8174      CCL_EOF_BLOCK := CCL_BLOCK
8175
8176      CCL_BLOCK := STATEMENT | (STATEMENT [STATEMENT ...])
8177      STATEMENT :=
8178              SET | IF | BRANCH | LOOP | REPEAT | BREAK
8179              | READ | WRITE
8180
8181      SET := (REG = EXPRESSION) | (REG SELF_OP EXPRESSION)
8182             | INT-OR-CHAR
8183
8184      EXPRESSION := ARG | (EXPRESSION OP ARG)
8185
8186      IF := (if EXPRESSION CCL_BLOCK CCL_BLOCK)
8187      BRANCH := (branch EXPRESSION CCL_BLOCK [CCL_BLOCK ...])
8188      LOOP := (loop STATEMENT [STATEMENT ...])
8189      BREAK := (break)
8190      REPEAT := (repeat)
8191              | (write-repeat [REG | INT-OR-CHAR | string])
8192              | (write-read-repeat REG [INT-OR-CHAR | string | ARRAY]?)
8193      READ := (read REG) | (read REG REG)
8194              | (read-if REG ARITH_OP ARG CCL_BLOCK CCL_BLOCK)
8195              | (read-branch REG CCL_BLOCK [CCL_BLOCK ...])
8196      WRITE := (write REG) | (write REG REG)
8197              | (write INT-OR-CHAR) | (write STRING) | STRING
8198              | (write REG ARRAY)
8199      END := (end)
8200
8201      REG := r0 | r1 | r2 | r3 | r4 | r5 | r6 | r7
8202      ARG := REG | INT-OR-CHAR
8203      OP :=   + | - | * | / | % | & | '|' | ^ | << | >> | <8 | >8 | //
8204              | < | > | == | <= | >= | !=
8205      SELF_OP :=
8206              += | -= | *= | /= | %= | &= | '|=' | ^= | <<= | >>=
8207      ARRAY := '[' INT-OR-CHAR ... ']'
8208      INT-OR-CHAR := INT | CHAR
8209
8210 MACHINE CODE:
8211
8212 The machine code consists of a vector of 32-bit words.
8213 The first such word specifies the start of the EOF section of the code;
8214 this is the code executed to handle any stuff that needs to be done
8215 (e.g. designating back to ASCII and left-to-right mode) after all
8216 other encoded/decoded data has been written out.  This is not used for
8217 charset CCL programs.
8218
8219 REGISTER: 0..7  -- referred by RRR or rrr
8220
8221 OPERATOR BIT FIELD (27-bit): XXXXXXXXXXXXXXX RRR TTTTT
8222         TTTTT (5-bit): operator type
8223         RRR (3-bit): register number
8224         XXXXXXXXXXXXXXXX (15-bit):
8225                 CCCCCCCCCCCCCCC: constant or address
8226                 000000000000rrr: register number
8227
8228 AAAA:   00000 +
8229         00001 -
8230         00010 *
8231         00011 /
8232         00100 %
8233         00101 &
8234         00110 |
8235         00111 ~
8236
8237         01000 <<
8238         01001 >>
8239         01010 <8
8240         01011 >8
8241         01100 //
8242         01101 not used
8243         01110 not used
8244         01111 not used
8245
8246         10000 <
8247         10001 >
8248         10010 ==
8249         10011 <=
8250         10100 >=
8251         10101 !=
8252
8253 OPERATORS:      TTTTT RRR XX..
8254
8255 SetCS:          00000 RRR C...C      RRR = C...C
8256 SetCL:          00001 RRR .....      RRR = c...c
8257                 c.............c
8258 SetR:           00010 RRR ..rrr      RRR = rrr
8259 SetA:           00011 RRR ..rrr      RRR = array[rrr]
8260                 C.............C      size of array = C...C
8261                 c.............c      contents = c...c
8262
8263 Jump:           00100 000 c...c      jump to c...c
8264 JumpCond:       00101 RRR c...c      if (!RRR) jump to c...c
8265 WriteJump:      00110 RRR c...c      Write1 RRR, jump to c...c
8266 WriteReadJump:  00111 RRR c...c      Write1, Read1 RRR, jump to c...c
8267 WriteCJump:     01000 000 c...c      Write1 C...C, jump to c...c
8268                 C...C
8269 WriteCReadJump: 01001 RRR c...c      Write1 C...C, Read1 RRR,
8270                 C.............C      and jump to c...c
8271 WriteSJump:     01010 000 c...c      WriteS, jump to c...c
8272                 C.............C
8273                 S.............S
8274                 ...
8275 WriteSReadJump: 01011 RRR c...c      WriteS, Read1 RRR, jump to c...c
8276                 C.............C
8277                 S.............S
8278                 ...
8279 WriteAReadJump: 01100 RRR c...c      WriteA, Read1 RRR, jump to c...c
8280                 C.............C      size of array = C...C
8281                 c.............c      contents = c...c
8282                 ...
8283 Branch:         01101 RRR C...C      if (RRR >= 0 && RRR < C..)
8284                 c.............c      branch to (RRR+1)th address
8285 Read1:          01110 RRR ...        read 1-byte to RRR
8286 Read2:          01111 RRR ..rrr      read 2-byte to RRR and rrr
8287 ReadBranch:     10000 RRR C...C      Read1 and Branch
8288                 c.............c
8289                 ...
8290 Write1:         10001 RRR .....      write 1-byte RRR
8291 Write2:         10010 RRR ..rrr      write 2-byte RRR and rrr
8292 WriteC:         10011 000 .....      write 1-char C...CC
8293                 C.............C
8294 WriteS:         10100 000 .....      write C..-byte of string
8295                 C.............C
8296                 S.............S
8297                 ...
8298 WriteA:         10101 RRR .....      write array[RRR]
8299                 C.............C      size of array = C...C
8300                 c.............c      contents = c...c
8301                 ...
8302 End:            10110 000 .....      terminate the execution
8303
8304 SetSelfCS:      10111 RRR C...C      RRR AAAAA= C...C
8305                 ..........AAAAA
8306 SetSelfCL:      11000 RRR .....      RRR AAAAA= c...c
8307                 c.............c
8308                 ..........AAAAA
8309 SetSelfR:       11001 RRR ..Rrr      RRR AAAAA= rrr
8310                 ..........AAAAA
8311 SetExprCL:      11010 RRR ..Rrr      RRR = rrr AAAAA c...c
8312                 c.............c
8313                 ..........AAAAA
8314 SetExprR:       11011 RRR ..rrr      RRR = rrr AAAAA Rrr
8315                 ............Rrr
8316                 ..........AAAAA
8317 JumpCondC:      11100 RRR c...c      if !(RRR AAAAA C..) jump to c...c
8318                 C.............C
8319                 ..........AAAAA
8320 JumpCondR:      11101 RRR c...c      if !(RRR AAAAA rrr) jump to c...c
8321                 ............rrr
8322                 ..........AAAAA
8323 ReadJumpCondC:  11110 RRR c...c      Read1 and JumpCondC
8324                 C.............C
8325                 ..........AAAAA
8326 ReadJumpCondR:  11111 RRR c...c      Read1 and JumpCondR
8327                 ............rrr
8328                 ..........AAAAA
8329 @end example
8330
8331 @node The Lisp Reader and Compiler, Lstreams, MULE Character Sets and Encodings, Top
8332 @chapter The Lisp Reader and Compiler
8333 @cindex Lisp reader and compiler, the
8334 @cindex reader and compiler, the Lisp
8335 @cindex compiler, the Lisp reader and
8336
8337 Not yet documented.
8338
8339 @node Lstreams, Consoles; Devices; Frames; Windows, The Lisp Reader and Compiler, Top
8340 @chapter Lstreams
8341 @cindex lstreams
8342
8343   An @dfn{lstream} is an internal Lisp object that provides a generic
8344 buffering stream implementation.  Conceptually, you send data to the
8345 stream or read data from the stream, not caring what's on the other end
8346 of the stream.  The other end could be another stream, a file
8347 descriptor, a stdio stream, a fixed block of memory, a reallocating
8348 block of memory, etc.  The main purpose of the stream is to provide a
8349 standard interface and to do buffering.  Macros are defined to read or
8350 write characters, so the calling functions do not have to worry about
8351 blocking data together in order to achieve efficiency.
8352
8353 @menu
8354 * Creating an Lstream::         Creating an lstream object.
8355 * Lstream Types::               Different sorts of things that are streamed.
8356 * Lstream Functions::           Functions for working with lstreams.
8357 * Lstream Methods::             Creating new lstream types.
8358 @end menu
8359
8360 @node Creating an Lstream
8361 @section Creating an Lstream
8362 @cindex lstream, creating an
8363
8364 Lstreams come in different types, depending on what is being interfaced
8365 to.  Although the primitive for creating new lstreams is
8366 @code{Lstream_new()}, generally you do not call this directly.  Instead,
8367 you call some type-specific creation function, which creates the lstream
8368 and initializes it as appropriate for the particular type.
8369
8370 All lstream creation functions take a @var{mode} argument, specifying
8371 what mode the lstream should be opened as.  This controls whether the
8372 lstream is for input and output, and optionally whether data should be
8373 blocked up in units of MULE characters.  Note that some types of
8374 lstreams can only be opened for input; others only for output; and
8375 others can be opened either way.  #### Richard Mlynarik thinks that
8376 there should be a strict separation between input and output streams,
8377 and he's probably right.
8378
8379   @var{mode} is a string, one of
8380
8381 @table @code
8382 @item "r"
8383   Open for reading.
8384 @item "w"
8385   Open for writing.
8386 @item "rc"
8387   Open for reading, but ``read'' never returns partial MULE characters.
8388 @item "wc"
8389   Open for writing, but never writes partial MULE characters.
8390 @end table
8391
8392 @node Lstream Types
8393 @section Lstream Types
8394 @cindex lstream types
8395 @cindex types, lstream
8396
8397 @table @asis
8398 @item stdio
8399
8400 @item filedesc
8401
8402 @item lisp-string
8403
8404 @item fixed-buffer
8405
8406 @item resizing-buffer
8407
8408 @item dynarr
8409
8410 @item lisp-buffer
8411
8412 @item print
8413
8414 @item decoding
8415
8416 @item encoding
8417 @end table
8418
8419 @node Lstream Functions
8420 @section Lstream Functions
8421 @cindex lstream functions
8422
8423 @deftypefun {Lstream *} Lstream_new (Lstream_implementation *@var{imp}, const char *@var{mode})
8424 Allocate and return a new Lstream.  This function is not really meant to
8425 be called directly; rather, each stream type should provide its own
8426 stream creation function, which creates the stream and does any other
8427 necessary creation stuff (e.g. opening a file).
8428 @end deftypefun
8429
8430 @deftypefun void Lstream_set_buffering (Lstream *@var{lstr}, Lstream_buffering @var{buffering}, int @var{buffering_size})
8431 Change the buffering of a stream.  See @file{lstream.h}.  By default the
8432 buffering is @code{STREAM_BLOCK_BUFFERED}.
8433 @end deftypefun
8434
8435 @deftypefun int Lstream_flush (Lstream *@var{lstr})
8436 Flush out any pending unwritten data in the stream.  Clear any buffered
8437 input data.  Returns 0 on success, -1 on error.
8438 @end deftypefun
8439
8440 @deftypefn Macro int Lstream_putc (Lstream *@var{stream}, int @var{c})
8441 Write out one byte to the stream.  This is a macro and so it is very
8442 efficient.  The @var{c} argument is only evaluated once but the @var{stream}
8443 argument is evaluated more than once.  Returns 0 on success, -1 on
8444 error.
8445 @end deftypefn
8446
8447 @deftypefn Macro int Lstream_getc (Lstream *@var{stream})
8448 Read one byte from the stream.  This is a macro and so it is very
8449 efficient.  The @var{stream} argument is evaluated more than once.  Return
8450 value is -1 for EOF or error.
8451 @end deftypefn
8452
8453 @deftypefn Macro void Lstream_ungetc (Lstream *@var{stream}, int @var{c})
8454 Push one byte back onto the input queue.  This will be the next byte
8455 read from the stream.  Any number of bytes can be pushed back and will
8456 be read in the reverse order they were pushed back---most recent
8457 first. (This is necessary for consistency---if there are a number of
8458 bytes that have been unread and I read and unread a byte, it needs to be
8459 the first to be read again.) This is a macro and so it is very
8460 efficient.  The @var{c} argument is only evaluated once but the @var{stream}
8461 argument is evaluated more than once.
8462 @end deftypefn
8463
8464 @deftypefun int Lstream_fputc (Lstream *@var{stream}, int @var{c})
8465 @deftypefunx int Lstream_fgetc (Lstream *@var{stream})
8466 @deftypefunx void Lstream_fungetc (Lstream *@var{stream}, int @var{c})
8467 Function equivalents of the above macros.
8468 @end deftypefun
8469
8470 @deftypefun ssize_t Lstream_read (Lstream *@var{stream}, void *@var{data}, size_t @var{size})
8471 Read @var{size} bytes of @var{data} from the stream.  Return the number
8472 of bytes read.  0 means EOF. -1 means an error occurred and no bytes
8473 were read.
8474 @end deftypefun
8475
8476 @deftypefun ssize_t Lstream_write (Lstream *@var{stream}, void *@var{data}, size_t @var{size})
8477 Write @var{size} bytes of @var{data} to the stream.  Return the number
8478 of bytes written.  -1 means an error occurred and no bytes were written.
8479 @end deftypefun
8480
8481 @deftypefun void Lstream_unread (Lstream *@var{stream}, void *@var{data}, size_t @var{size})
8482 Push back @var{size} bytes of @var{data} onto the input queue.  The next
8483 call to @code{Lstream_read()} with the same size will read the same
8484 bytes back.  Note that this will be the case even if there is other
8485 pending unread data.
8486 @end deftypefun
8487
8488 @deftypefun int Lstream_close (Lstream *@var{stream})
8489 Close the stream.  All data will be flushed out.
8490 @end deftypefun
8491
8492 @deftypefun void Lstream_reopen (Lstream *@var{stream})
8493 Reopen a closed stream.  This enables I/O on it again.  This is not
8494 meant to be called except from a wrapper routine that reinitializes
8495 variables and such---the close routine may well have freed some
8496 necessary storage structures, for example.
8497 @end deftypefun
8498
8499 @deftypefun void Lstream_rewind (Lstream *@var{stream})
8500 Rewind the stream to the beginning.
8501 @end deftypefun
8502
8503 @node Lstream Methods
8504 @section Lstream Methods
8505 @cindex lstream methods
8506
8507 @deftypefn {Lstream Method} ssize_t reader (Lstream *@var{stream}, unsigned char *@var{data}, size_t @var{size})
8508 Read some data from the stream's end and store it into @var{data}, which
8509 can hold @var{size} bytes.  Return the number of bytes read.  A return
8510 value of 0 means no bytes can be read at this time.  This may be because
8511 of an EOF, or because there is a granularity greater than one byte that
8512 the stream imposes on the returned data, and @var{size} is less than
8513 this granularity. (This will happen frequently for streams that need to
8514 return whole characters, because @code{Lstream_read()} calls the reader
8515 function repeatedly until it has the number of bytes it wants or until 0
8516 is returned.)  The lstream functions do not treat a 0 return as EOF or
8517 do anything special; however, the calling function will interpret any 0
8518 it gets back as EOF.  This will normally not happen unless the caller
8519 calls @code{Lstream_read()} with a very small size.
8520
8521 This function can be @code{NULL} if the stream is output-only.
8522 @end deftypefn
8523
8524 @deftypefn {Lstream Method} ssize_t writer (Lstream *@var{stream}, const unsigned char *@var{data}, size_t @var{size})
8525 Send some data to the stream's end.  Data to be sent is in @var{data}
8526 and is @var{size} bytes.  Return the number of bytes sent.  This
8527 function can send and return fewer bytes than is passed in; in that
8528 case, the function will just be called again until there is no data left
8529 or 0 is returned.  A return value of 0 means that no more data can be
8530 currently stored, but there is no error; the data will be squirreled
8531 away until the writer can accept data. (This is useful, e.g., if you're
8532 dealing with a non-blocking file descriptor and are getting
8533 @code{EWOULDBLOCK} errors.)  This function can be @code{NULL} if the
8534 stream is input-only.
8535 @end deftypefn
8536
8537 @deftypefn {Lstream Method} int rewinder (Lstream *@var{stream})
8538 Rewind the stream.  If this is @code{NULL}, the stream is not seekable.
8539 @end deftypefn
8540
8541 @deftypefn {Lstream Method} int seekable_p (Lstream *@var{stream})
8542 Indicate whether this stream is seekable---i.e. it can be rewound.
8543 This method is ignored if the stream does not have a rewind method.  If
8544 this method is not present, the result is determined by whether a rewind
8545 method is present.
8546 @end deftypefn
8547
8548 @deftypefn {Lstream Method} int flusher (Lstream *@var{stream})
8549 Perform any additional operations necessary to flush the data in this
8550 stream.
8551 @end deftypefn
8552
8553 @deftypefn {Lstream Method} int pseudo_closer (Lstream *@var{stream})
8554 @end deftypefn
8555
8556 @deftypefn {Lstream Method} int closer (Lstream *@var{stream})
8557 Perform any additional operations necessary to close this stream down.
8558 May be @code{NULL}.  This function is called when @code{Lstream_close()}
8559 is called or when the stream is garbage-collected.  When this function
8560 is called, all pending data in the stream will already have been written
8561 out.
8562 @end deftypefn
8563
8564 @deftypefn {Lstream Method} Lisp_Object marker (Lisp_Object @var{lstream}, void (*@var{markfun}) (Lisp_Object))
8565 Mark this object for garbage collection.  Same semantics as a standard
8566 @code{Lisp_Object} marker.  This function can be @code{NULL}.
8567 @end deftypefn
8568
8569 @node Consoles; Devices; Frames; Windows, The Redisplay Mechanism, Lstreams, Top
8570 @chapter Consoles; Devices; Frames; Windows
8571 @cindex consoles; devices; frames; windows
8572 @cindex devices; frames; windows, consoles;
8573 @cindex frames; windows, consoles; devices;
8574 @cindex windows, consoles; devices; frames;
8575
8576 @menu
8577 * Introduction to Consoles; Devices; Frames; Windows::
8578 * Point::
8579 * Window Hierarchy::
8580 * The Window Object::
8581 @end menu
8582
8583 @node Introduction to Consoles; Devices; Frames; Windows
8584 @section Introduction to Consoles; Devices; Frames; Windows
8585 @cindex consoles; devices; frames; windows, introduction to
8586 @cindex devices; frames; windows, introduction to consoles;
8587 @cindex frames; windows, introduction to consoles; devices;
8588 @cindex windows, introduction to consoles; devices; frames;
8589
8590 A window-system window that you see on the screen is called a
8591 @dfn{frame} in Emacs terminology.  Each frame is subdivided into one or
8592 more non-overlapping panes, called (confusingly) @dfn{windows}.  Each
8593 window displays the text of a buffer in it. (See above on Buffers.) Note
8594 that buffers and windows are independent entities: Two or more windows
8595 can be displaying the same buffer (potentially in different locations),
8596 and a buffer can be displayed in no windows.
8597
8598   A single display screen that contains one or more frames is called
8599 a @dfn{display}.  Under most circumstances, there is only one display.
8600 However, more than one display can exist, for example if you have
8601 a @dfn{multi-headed} console, i.e. one with a single keyboard but
8602 multiple displays. (Typically in such a situation, the various
8603 displays act like one large display, in that the mouse is only
8604 in one of them at a time, and moving the mouse off of one moves
8605 it into another.) In some cases, the different displays will
8606 have different characteristics, e.g. one color and one mono.
8607
8608   XEmacs can display frames on multiple displays.  It can even deal
8609 simultaneously with frames on multiple keyboards (called @dfn{consoles} in
8610 XEmacs terminology).  Here is one case where this might be useful: You
8611 are using XEmacs on your workstation at work, and leave it running.
8612 Then you go home and dial in on a TTY line, and you can use the
8613 already-running XEmacs process to display another frame on your local
8614 TTY.
8615
8616   Thus, there is a hierarchy console -> display -> frame -> window.
8617 There is a separate Lisp object type for each of these four concepts.
8618 Furthermore, there is logically a @dfn{selected console},
8619 @dfn{selected display}, @dfn{selected frame}, and @dfn{selected window}.
8620 Each of these objects is distinguished in various ways, such as being the
8621 default object for various functions that act on objects of that type.
8622 Note that every containing object remembers the ``selected'' object
8623 among the objects that it contains: e.g. not only is there a selected
8624 window, but every frame remembers the last window in it that was
8625 selected, and changing the selected frame causes the remembered window
8626 within it to become the selected window.  Similar relationships apply
8627 for consoles to devices and devices to frames.
8628
8629 @node Point
8630 @section Point
8631 @cindex point
8632
8633   Recall that every buffer has a current insertion position, called
8634 @dfn{point}.  Now, two or more windows may be displaying the same buffer,
8635 and the text cursor in the two windows (i.e. @code{point}) can be in
8636 two different places.  You may ask, how can that be, since each
8637 buffer has only one value of @code{point}?  The answer is that each window
8638 also has a value of @code{point} that is squirreled away in it.  There
8639 is only one selected window, and the value of ``point'' in that buffer
8640 corresponds to that window.  When the selected window is changed
8641 from one window to another displaying the same buffer, the old
8642 value of @code{point} is stored into the old window's ``point'' and the
8643 value of @code{point} from the new window is retrieved and made the
8644 value of @code{point} in the buffer.  This means that @code{window-point}
8645 for the selected window is potentially inaccurate, and if you
8646 want to retrieve the correct value of @code{point} for a window,
8647 you must special-case on the selected window and retrieve the
8648 buffer's point instead.  This is related to why @code{save-window-excursion}
8649 does not save the selected window's value of @code{point}.
8650
8651 @node Window Hierarchy
8652 @section Window Hierarchy
8653 @cindex window hierarchy
8654 @cindex hierarchy of windows
8655
8656   If a frame contains multiple windows (panes), they are always created
8657 by splitting an existing window along the horizontal or vertical axis.
8658 Terminology is a bit confusing here: to @dfn{split a window
8659 horizontally} means to create two side-by-side windows, i.e. to make a
8660 @emph{vertical} cut in a window.  Likewise, to @dfn{split a window
8661 vertically} means to create two windows, one above the other, by making
8662 a @emph{horizontal} cut.
8663
8664   If you split a window and then split again along the same axis, you
8665 will end up with a number of panes all arranged along the same axis.
8666 The precise way in which the splits were made should not be important,
8667 and this is reflected internally.  Internally, all windows are arranged
8668 in a tree, consisting of two types of windows, @dfn{combination} windows
8669 (which have children, and are covered completely by those children) and
8670 @dfn{leaf} windows, which have no children and are visible.  Every
8671 combination window has two or more children, all arranged along the same
8672 axis.  There are (logically) two subtypes of windows, depending on
8673 whether their children are horizontally or vertically arrayed.  There is
8674 always one root window, which is either a leaf window (if the frame
8675 contains only one window) or a combination window (if the frame contains
8676 more than one window).  In the latter case, the root window will have
8677 two or more children, either horizontally or vertically arrayed, and
8678 each of those children will be either a leaf window or another
8679 combination window.
8680
8681   Here are some rules:
8682
8683 @enumerate
8684 @item
8685 Horizontal combination windows can never have children that are
8686 horizontal combination windows; same for vertical.
8687
8688 @item
8689 Only leaf windows can be split (obviously) and this splitting does one
8690 of two things: (a) turns the leaf window into a combination window and
8691 creates two new leaf children, or (b) turns the leaf window into one of
8692 the two new leaves and creates the other leaf.  Rule (1) dictates which
8693 of these two outcomes happens.
8694
8695 @item
8696 Every combination window must have at least two children.
8697
8698 @item
8699 Leaf windows can never become combination windows.  They can be deleted,
8700 however.  If this results in a violation of (3), the parent combination
8701 window also gets deleted.
8702
8703 @item
8704 All functions that accept windows must be prepared to accept combination
8705 windows, and do something sane (e.g. signal an error if so).
8706 Combination windows @emph{do} escape to the Lisp level.
8707
8708 @item
8709 All windows have three fields governing their contents:
8710 these are @dfn{hchild} (a list of horizontally-arrayed children),
8711 @dfn{vchild} (a list of vertically-arrayed children), and @dfn{buffer}
8712 (the buffer contained in a leaf window).  Exactly one of
8713 these will be non-@code{nil}.  Remember that @dfn{horizontally-arrayed}
8714 means ``side-by-side'' and @dfn{vertically-arrayed} means
8715 @dfn{one above the other}.
8716
8717 @item
8718 Leaf windows also have markers in their @code{start} (the
8719 first buffer position displayed in the window) and @code{pointm}
8720 (the window's stashed value of @code{point}---see above) fields,
8721 while combination windows have @code{nil} in these fields.
8722
8723 @item
8724 The list of children for a window is threaded through the
8725 @code{next} and @code{prev} fields of each child window.
8726
8727 @item
8728 @strong{Deleted windows can be undeleted}.  This happens as a result of
8729 restoring a window configuration, and is unlike frames, displays, and
8730 consoles, which, once deleted, can never be restored.  Deleting a window
8731 does nothing except set a special @code{dead} bit to 1 and clear out the
8732 @code{next}, @code{prev}, @code{hchild}, and @code{vchild} fields, for
8733 GC purposes.
8734
8735 @item
8736 Most frames actually have two top-level windows---one for the
8737 minibuffer and one (the @dfn{root}) for everything else.  The modeline
8738 (if present) separates these two.  The @code{next} field of the root
8739 points to the minibuffer, and the @code{prev} field of the minibuffer
8740 points to the root.  The other @code{next} and @code{prev} fields are
8741 @code{nil}, and the frame points to both of these windows.
8742 Minibuffer-less frames have no minibuffer window, and the @code{next}
8743 and @code{prev} of the root window are @code{nil}.  Minibuffer-only
8744 frames have no root window, and the @code{next} of the minibuffer window
8745 is @code{nil} but the @code{prev} points to itself. (#### This is an
8746 artifact that should be fixed.)
8747 @end enumerate
8748
8749 @node The Window Object
8750 @section The Window Object
8751 @cindex window object, the
8752 @cindex object, the window
8753
8754   Windows have the following accessible fields:
8755
8756 @table @code
8757 @item frame
8758 The frame that this window is on.
8759
8760 @item mini_p
8761 Non-@code{nil} if this window is a minibuffer window.
8762
8763 @item buffer
8764 The buffer that the window is displaying.  This may change often during
8765 the life of the window.
8766
8767 @item dedicated
8768 Non-@code{nil} if this window is dedicated to its buffer.
8769
8770 @item pointm
8771 @cindex window point internals
8772 This is the value of point in the current buffer when this window is
8773 selected; when it is not selected, it retains its previous value.
8774
8775 @item start
8776 The position in the buffer that is the first character to be displayed
8777 in the window.
8778
8779 @item force_start
8780 If this flag is non-@code{nil}, it says that the window has been
8781 scrolled explicitly by the Lisp program.  This affects what the next
8782 redisplay does if point is off the screen: instead of scrolling the
8783 window to show the text around point, it moves point to a location that
8784 is on the screen.
8785
8786 @item last_modified
8787 The @code{modified} field of the window's buffer, as of the last time
8788 a redisplay completed in this window.
8789
8790 @item last_point
8791 The buffer's value of point, as of the last time
8792 a redisplay completed in this window.
8793
8794 @item left
8795 This is the left-hand edge of the window, measured in columns.  (The
8796 leftmost column on the screen is @w{column 0}.)
8797
8798 @item top
8799 This is the top edge of the window, measured in lines.  (The top line on
8800 the screen is @w{line 0}.)
8801
8802 @item height
8803 The height of the window, measured in lines.
8804
8805 @item width
8806 The width of the window, measured in columns.
8807
8808 @item next
8809 This is the window that is the next in the chain of siblings.  It is
8810 @code{nil} in a window that is the rightmost or bottommost of a group of
8811 siblings.
8812
8813 @item prev
8814 This is the window that is the previous in the chain of siblings.  It is
8815 @code{nil} in a window that is the leftmost or topmost of a group of
8816 siblings.
8817
8818 @item parent
8819 Internally, XEmacs arranges windows in a tree; each group of siblings has
8820 a parent window whose area includes all the siblings.  This field points
8821 to a window's parent.
8822
8823 Parent windows do not display buffers, and play little role in display
8824 except to shape their child windows.  Emacs Lisp programs usually have
8825 no access to the parent windows; they operate on the windows at the
8826 leaves of the tree, which actually display buffers.
8827
8828 @item hscroll
8829 This is the number of columns that the display in the window is scrolled
8830 horizontally to the left.  Normally, this is 0.
8831
8832 @item use_time
8833 This is the last time that the window was selected.  The function
8834 @code{get-lru-window} uses this field.
8835
8836 @item display_table
8837 The window's display table, or @code{nil} if none is specified for it.
8838
8839 @item update_mode_line
8840 Non-@code{nil} means this window's mode line needs to be updated.
8841
8842 @item base_line_number
8843 The line number of a certain position in the buffer, or @code{nil}.
8844 This is used for displaying the line number of point in the mode line.
8845
8846 @item base_line_pos
8847 The position in the buffer for which the line number is known, or
8848 @code{nil} meaning none is known.
8849
8850 @item region_showing
8851 If the region (or part of it) is highlighted in this window, this field
8852 holds the mark position that made one end of that region.  Otherwise,
8853 this field is @code{nil}.
8854 @end table
8855
8856 @node The Redisplay Mechanism, Extents, Consoles; Devices; Frames; Windows, Top
8857 @chapter The Redisplay Mechanism
8858 @cindex redisplay mechanism, the
8859
8860   The redisplay mechanism is one of the most complicated sections of
8861 XEmacs, especially from a conceptual standpoint.  This is doubly so
8862 because, unlike for the basic aspects of the Lisp interpreter, the
8863 computer science theories of how to efficiently handle redisplay are not
8864 well-developed.
8865
8866   When working with the redisplay mechanism, remember the Golden Rules
8867 of Redisplay:
8868
8869 @enumerate
8870 @item
8871 It Is Better To Be Correct Than Fast.
8872 @item
8873 Thou Shalt Not Run Elisp From Within Redisplay.
8874 @item
8875 It Is Better To Be Fast Than Not To Be.
8876 @end enumerate
8877
8878 @menu
8879 * Critical Redisplay Sections::
8880 * Line Start Cache::
8881 * Redisplay Piece by Piece::
8882 @end menu
8883
8884 @node Critical Redisplay Sections
8885 @section Critical Redisplay Sections
8886 @cindex redisplay sections, critical
8887 @cindex critical redisplay sections
8888
8889 Within this section, we are defenseless and assume that the
8890 following cannot happen:
8891
8892 @enumerate
8893 @item
8894 garbage collection
8895 @item
8896 Lisp code evaluation
8897 @item
8898 frame size changes
8899 @end enumerate
8900
8901 We ensure (3) by calling @code{hold_frame_size_changes()}, which
8902 will cause any pending frame size changes to get put on hold
8903 till after the end of the critical section.  (1) follows
8904 automatically if (2) is met.  #### Unfortunately, there are
8905 some places where Lisp code can be called within this section.
8906 We need to remove them.
8907
8908 If @code{Fsignal()} is called during this critical section, we
8909 will @code{abort()}.
8910
8911 If garbage collection is called during this critical section,
8912 we simply return. #### We should abort instead.
8913
8914 #### If a frame-size change does occur we should probably
8915 actually be preempting redisplay.
8916
8917 @node Line Start Cache
8918 @section Line Start Cache
8919 @cindex line start cache
8920
8921   The traditional scrolling code in Emacs breaks in a variable height
8922 world.  It depends on the key assumption that the number of lines that
8923 can be displayed at any given time is fixed.  This led to a complete
8924 separation of the scrolling code from the redisplay code.  In order to
8925 fully support variable height lines, the scrolling code must actually be
8926 tightly integrated with redisplay.  Only redisplay can determine how
8927 many lines will be displayed on a screen for any given starting point.
8928
8929   What is ideally wanted is a complete list of the starting buffer
8930 position for every possible display line of a buffer along with the
8931 height of that display line.  Maintaining such a full list would be very
8932 expensive.  We settle for having it include information for all areas
8933 which we happen to generate anyhow (i.e. the region currently being
8934 displayed) and for those areas we need to work with.
8935
8936   In order to ensure that the cache accurately represents what redisplay
8937 would actually show, it is necessary to invalidate it in many
8938 situations.  If the buffer changes, the starting positions may no longer
8939 be correct.  If a face or an extent has changed then the line heights
8940 may have altered.  These events happen frequently enough that the cache
8941 can end up being constantly disabled.  With this potentially constant
8942 invalidation when is the cache ever useful?
8943
8944   Even if the cache is invalidated before every single usage, it is
8945 necessary.  Scrolling often requires knowledge about display lines which
8946 are actually above or below the visible region.  The cache provides a
8947 convenient light-weight method of storing this information for multiple
8948 display regions.  This knowledge is necessary for the scrolling code to
8949 always obey the First Golden Rule of Redisplay.
8950
8951   If the cache already contains all of the information that the scrolling
8952 routines happen to need so that it doesn't have to go generate it, then
8953 we are able to obey the Third Golden Rule of Redisplay.  The first thing
8954 we do to help out the cache is to always add the displayed region.  This
8955 region had to be generated anyway, so the cache ends up getting the
8956 information basically for free.  In those cases where a user is simply
8957 scrolling around viewing a buffer there is a high probability that this
8958 is sufficient to always provide the needed information.  The second
8959 thing we can do is be smart about invalidating the cache.
8960
8961   TODO---Be smart about invalidating the cache.  Potential places:
8962
8963 @itemize @bullet
8964 @item
8965 Insertions at end-of-line which don't cause line-wraps do not alter the
8966 starting positions of any display lines.  These types of buffer
8967 modifications should not invalidate the cache.  This is actually a large
8968 optimization for redisplay speed as well.
8969 @item
8970 Buffer modifications frequently only affect the display of lines at and
8971 below where they occur.  In these situations we should only invalidate
8972 the part of the cache starting at where the modification occurs.
8973 @end itemize
8974
8975   In case you're wondering, the Second Golden Rule of Redisplay is not
8976 applicable.
8977
8978 @node Redisplay Piece by Piece
8979 @section Redisplay Piece by Piece
8980 @cindex redisplay piece by piece
8981
8982 As you can begin to see redisplay is complex and also not well
8983 documented. Chuck no longer works on XEmacs so this section is my take
8984 on the workings of redisplay.
8985
8986 Redisplay happens in three phases:
8987
8988 @enumerate
8989 @item
8990 Determine desired display in area that needs redisplay.
8991 Implemented by @code{redisplay.c}
8992 @item
8993 Compare desired display with current display
8994 Implemented by @code{redisplay-output.c}
8995 @item
8996 Output changes Implemented by @code{redisplay-output.c},
8997 @code{redisplay-x.c}, @code{redisplay-msw.c} and @code{redisplay-tty.c}
8998 @end enumerate
8999
9000 Steps 1 and 2 are device-independent and relatively complex.  Step 3 is
9001 mostly device-dependent.
9002
9003 Determining the desired display
9004
9005 Display attributes are stored in @code{display_line} structures. Each
9006 @code{display_line} consists of a set of @code{display_block}'s and each
9007 @code{display_block} contains a number of @code{rune}'s. Generally
9008 dynarr's of @code{display_line}'s are held by each window representing
9009 the current display and the desired display.
9010
9011 The @code{display_line} structures are tightly tied to buffers which
9012 presents a problem for redisplay as this connection is bogus for the
9013 modeline. Hence the @code{display_line} generation routines are
9014 duplicated for generating the modeline. This means that the modeline
9015 display code has many bugs that the standard redisplay code does not.
9016
9017 The guts of @code{display_line} generation are in
9018 @code{create_text_block}, which creates a single display line for the
9019 desired locale. This incrementally parses the characters on the current
9020 line and generates redisplay structures for each.
9021
9022 Gutter redisplay is different. Because the data to display is stored in
9023 a string we cannot use @code{create_text_block}. Instead we use
9024 @code{create_text_string_block} which performs the same function as
9025 @code{create_text_block} but for strings. Many of the complexities of
9026 @code{create_text_block} to do with cursor handling and selective
9027 display have been removed.
9028
9029 @node Extents, Faces, The Redisplay Mechanism, Top
9030 @chapter Extents
9031 @cindex extents
9032
9033 @menu
9034 * Introduction to Extents::     Extents are ranges over text, with properties.
9035 * Extent Ordering::             How extents are ordered internally.
9036 * Format of the Extent Info::   The extent information in a buffer or string.
9037 * Zero-Length Extents::         A weird special case.
9038 * Mathematics of Extent Ordering::  A rigorous foundation.
9039 * Extent Fragments::            Cached information useful for redisplay.
9040 @end menu
9041
9042 @node Introduction to Extents
9043 @section Introduction to Extents
9044 @cindex extents, introduction to
9045
9046   Extents are regions over a buffer, with a start and an end position
9047 denoting the region of the buffer included in the extent.  In
9048 addition, either end can be closed or open, meaning that the endpoint
9049 is or is not logically included in the extent.  Insertion of a character
9050 at a closed endpoint causes the character to go inside the extent;
9051 insertion at an open endpoint causes the character to go outside.
9052
9053   Extent endpoints are stored using memory indices (see @file{insdel.c}),
9054 to minimize the amount of adjusting that needs to be done when
9055 characters are inserted or deleted.
9056
9057   (Formerly, extent endpoints at the gap could be either before or
9058 after the gap, depending on the open/closedness of the endpoint.
9059 The intent of this was to make it so that insertions would
9060 automatically go inside or out of extents as necessary with no
9061 further work needing to be done.  It didn't work out that way,
9062 however, and just ended up complexifying and buggifying all the
9063 rest of the code.)
9064
9065 @node Extent Ordering
9066 @section Extent Ordering
9067 @cindex extent ordering
9068
9069   Extents are compared using memory indices.  There are two orderings
9070 for extents and both orders are kept current at all times.  The normal
9071 or @dfn{display} order is as follows:
9072
9073 @example
9074 Extent A is ``less than'' extent B,
9075 that is, earlier in the display order,
9076   if:    A-start < B-start,
9077   or if: A-start = B-start, and A-end > B-end
9078 @end example
9079
9080   So if two extents begin at the same position, the larger of them is the
9081 earlier one in the display order (@code{EXTENT_LESS} is true).
9082
9083   For the e-order, the same thing holds:
9084
9085 @example
9086 Extent A is ``less than'' extent B in e-order,
9087 that is, later in the buffer,
9088   if:    A-end < B-end,
9089   or if: A-end = B-end, and A-start > B-start
9090 @end example
9091
9092   So if two extents end at the same position, the smaller of them is the
9093 earlier one in the e-order (@code{EXTENT_E_LESS} is true).
9094
9095   The display order and the e-order are complementary orders: any
9096 theorem about the display order also applies to the e-order if you swap
9097 all occurrences of ``display order'' and ``e-order'', ``less than'' and
9098 ``greater than'', and ``extent start'' and ``extent end''.
9099
9100 @node Format of the Extent Info
9101 @section Format of the Extent Info
9102 @cindex extent info, format of the
9103
9104   An extent-info structure consists of a list of the buffer or string's
9105 extents and a @dfn{stack of extents} that lists all of the extents over
9106 a particular position.  The stack-of-extents info is used for
9107 optimization purposes---it basically caches some info that might
9108 be expensive to compute.  Certain otherwise hard computations are easy
9109 given the stack of extents over a particular position, and if the
9110 stack of extents over a nearby position is known (because it was
9111 calculated at some prior point in time), it's easy to move the stack
9112 of extents to the proper position.
9113
9114   Given that the stack of extents is an optimization, and given that
9115 it requires memory, a string's stack of extents is wiped out each
9116 time a garbage collection occurs.  Therefore, any time you retrieve
9117 the stack of extents, it might not be there.  If you need it to
9118 be there, use the @code{_force} version.
9119
9120   Similarly, a string may or may not have an extent_info structure.
9121 (Generally it won't if there haven't been any extents added to the
9122 string.) So use the @code{_force} version if you need the extent_info
9123 structure to be there.
9124
9125   A list of extents is maintained as a double gap array: one gap array
9126 is ordered by start index (the @dfn{display order}) and the other is
9127 ordered by end index (the @dfn{e-order}).  Note that positions in an
9128 extent list should logically be conceived of as referring @emph{to} a
9129 particular extent (as is the norm in programs) rather than sitting
9130 between two extents.  Note also that callers of these functions should
9131 not be aware of the fact that the extent list is implemented as an
9132 array, except for the fact that positions are integers (this should be
9133 generalized to handle integers and linked list equally well).
9134
9135 @node Zero-Length Extents
9136 @section Zero-Length Extents
9137 @cindex zero-length extents
9138 @cindex extents, zero-length
9139
9140   Extents can be zero-length, and will end up that way if their endpoints
9141 are explicitly set that way or if their detachable property is @code{nil}
9142 and all the text in the extent is deleted. (The exception is open-open
9143 zero-length extents, which are barred from existing because there is
9144 no sensible way to define their properties.  Deletion of the text in
9145 an open-open extent causes it to be converted into a closed-open
9146 extent.)  Zero-length extents are primarily used to represent
9147 annotations, and behave as follows:
9148
9149 @enumerate
9150 @item
9151 Insertion at the position of a zero-length extent expands the extent
9152 if both endpoints are closed; goes after the extent if it is closed-open;
9153 and goes before the extent if it is open-closed.
9154
9155 @item
9156 Deletion of a character on a side of a zero-length extent whose
9157 corresponding endpoint is closed causes the extent to be detached if
9158 it is detachable; if the extent is not detachable or the corresponding
9159 endpoint is open, the extent remains in the buffer, moving as necessary.
9160 @end enumerate
9161
9162   Note that closed-open, non-detachable zero-length extents behave
9163 exactly like markers and that open-closed, non-detachable zero-length
9164 extents behave like the ``point-type'' marker in Mule.
9165
9166 @node Mathematics of Extent Ordering
9167 @section Mathematics of Extent Ordering
9168 @cindex mathematics of extent ordering
9169 @cindex extent mathematics
9170 @cindex extent ordering
9171
9172 @cindex display order of extents
9173 @cindex extents, display order
9174   The extents in a buffer are ordered by ``display order'' because that
9175 is that order that the redisplay mechanism needs to process them in.
9176 The e-order is an auxiliary ordering used to facilitate operations
9177 over extents.  The operations that can be performed on the ordered
9178 list of extents in a buffer are
9179
9180 @enumerate
9181 @item
9182 Locate where an extent would go if inserted into the list.
9183 @item
9184 Insert an extent into the list.
9185 @item
9186 Remove an extent from the list.
9187 @item
9188 Map over all the extents that overlap a range.
9189 @end enumerate
9190
9191   (4) requires being able to determine the first and last extents
9192 that overlap a range.
9193
9194   NOTE: @dfn{overlap} is used as follows:
9195
9196 @itemize @bullet
9197 @item
9198 two ranges overlap if they have at least one point in common.
9199 Whether the endpoints are open or closed makes a difference here.
9200 @item
9201 a point overlaps a range if the point is contained within the
9202 range; this is equivalent to treating a point @math{P} as the range
9203 @math{[P, P]}.
9204 @item
9205 In the case of an @emph{extent} overlapping a point or range, the extent
9206 is normally treated as having closed endpoints.  This applies
9207 consistently in the discussion of stacks of extents and such below.
9208 Note that this definition of overlap is not necessarily consistent with
9209 the extents that @code{map-extents} maps over, since @code{map-extents}
9210 sometimes pays attention to whether the endpoints of an extents are open
9211 or closed.  But for our purposes, it greatly simplifies things to treat
9212 all extents as having closed endpoints.
9213 @end itemize
9214
9215 First, define @math{>}, @math{<}, @math{<=}, etc. as applied to extents
9216 to mean comparison according to the display order.  Comparison between
9217 an extent @math{E} and an index @math{I} means comparison between
9218 @math{E} and the range @math{[I, I]}.
9219
9220 Also define @math{e>}, @math{e<}, @math{e<=}, etc. to mean comparison
9221 according to the e-order.
9222
9223 For any range @math{R}, define @math{R(0)} to be the starting index of
9224 the range and @math{R(1)} to be the ending index of the range.
9225
9226 For any extent @math{E}, define @math{E(next)} to be the extent directly
9227 following @math{E}, and @math{E(prev)} to be the extent directly
9228 preceding @math{E}.  Assume @math{E(next)} and @math{E(prev)} can be
9229 determined from @math{E} in constant time.  (This is because we store
9230 the extent list as a doubly linked list.)
9231
9232 Similarly, define @math{E(e-next)} and @math{E(e-prev)} to be the
9233 extents directly following and preceding @math{E} in the e-order.
9234
9235 Now:
9236
9237 Let @math{R} be a range.
9238 Let @math{F} be the first extent overlapping @math{R}.
9239 Let @math{L} be the last extent overlapping @math{R}.
9240
9241 Theorem 1: @math{R(1)} lies between @math{L} and @math{L(next)},
9242 i.e. @math{L <= R(1) < L(next)}.
9243
9244   This follows easily from the definition of display order.  The
9245 basic reason that this theorem applies is that the display order
9246 sorts by increasing starting index.
9247
9248   Therefore, we can determine @math{L} just by looking at where we would
9249 insert @math{R(1)} into the list, and if we know @math{F} and are moving
9250 forward over extents, we can easily determine when we've hit @math{L} by
9251 comparing the extent we're at to @math{R(1)}.
9252
9253 @example
9254 Theorem 2: @math{F(e-prev) e< [1, R(0)] e<= F}.
9255 @end example
9256
9257   This is the analog of Theorem 1, and applies because the e-order
9258 sorts by increasing ending index.
9259
9260   Therefore, @math{F} can be found in the same amount of time as
9261 operation (1), i.e. the time that it takes to locate where an extent
9262 would go if inserted into the e-order list.
9263
9264   If the lists were stored as balanced binary trees, then operation (1)
9265 would take logarithmic time, which is usually quite fast.  However,
9266 currently they're stored as simple doubly-linked lists, and instead we
9267 do some caching to try to speed things up.
9268
9269   Define a @dfn{stack of extents} (or @dfn{SOE}) as the set of extents
9270 (ordered in the display order) that overlap an index @math{I}, together
9271 with the SOE's @dfn{previous} extent, which is an extent that precedes
9272 @math{I} in the e-order. (Hopefully there will not be very many extents
9273 between @math{I} and the previous extent.)
9274
9275 Now:
9276
9277 Let @math{I} be an index, let @math{S} be the stack of extents on
9278 @math{I}, let @math{F} be the first extent in @math{S}, and let @math{P}
9279 be @math{S}'s previous extent.
9280
9281 Theorem 3: The first extent in @math{S} is the first extent that overlaps
9282 any range @math{[I, J]}.
9283
9284 Proof: Any extent that overlaps @math{[I, J]} but does not include
9285 @math{I} must have a start index @math{> I}, and thus be greater than
9286 any extent in @math{S}.
9287
9288 Therefore, finding the first extent that overlaps a range @math{R} is
9289 the same as finding the first extent that overlaps @math{R(0)}.
9290
9291 Theorem 4: Let @math{I2} be an index such that @math{I2 > I}, and let
9292 @math{F2} be the first extent that overlaps @math{I2}.  Then, either
9293 @math{F2} is in @math{S} or @math{F2} is greater than any extent in
9294 @math{S}.
9295
9296 Proof: If @math{F2} does not include @math{I} then its start index is
9297 greater than @math{I} and thus it is greater than any extent in
9298 @math{S}, including @math{F}.  Otherwise, @math{F2} includes @math{I}
9299 and thus is in @math{S}, and thus @math{F2 >= F}.
9300
9301 @node Extent Fragments
9302 @section Extent Fragments
9303 @cindex extent fragments
9304 @cindex fragments, extent
9305
9306   Imagine that the buffer is divided up into contiguous, non-overlapping
9307 @dfn{runs} of text such that no extent starts or ends within a run
9308 (extents that abut the run don't count).
9309
9310   An extent fragment is a structure that holds data about the run that
9311 contains a particular buffer position (if the buffer position is at the
9312 junction of two runs, the run after the position is used)---the
9313 beginning and end of the run, a list of all of the extents in that run,
9314 the @dfn{merged face} that results from merging all of the faces
9315 corresponding to those extents, the begin and end glyphs at the
9316 beginning of the run, etc.  This is the information that redisplay needs
9317 in order to display this run.
9318
9319   Extent fragments have to be very quick to update to a new buffer
9320 position when moving linearly through the buffer.  They rely on the
9321 stack-of-extents code, which does the heavy-duty algorithmic work of
9322 determining which extents overly a particular position.
9323
9324 @node Faces, Glyphs, Extents, Top
9325 @chapter Faces
9326 @cindex faces
9327
9328 Not yet documented.
9329
9330 @node Glyphs, Specifiers, Faces, Top
9331 @chapter Glyphs
9332 @cindex glyphs
9333
9334 Glyphs are graphical elements that can be displayed in XEmacs buffers or
9335 gutters. We use the term graphical element here in the broadest possible
9336 sense since glyphs can be as mundane as text or as arcane as a native
9337 tab widget.
9338
9339 In XEmacs, glyphs represent the uninstantiated state of graphical
9340 elements, i.e. they hold all the information necessary to produce an
9341 image on-screen but the image need not exist at this stage, and multiple
9342 screen images can be instantiated from a single glyph.
9343
9344 Glyphs are lazily instantiated by calling one of the glyph
9345 functions. This usually occurs within redisplay when
9346 @code{Fglyph_height} is called. Instantiation causes an image-instance
9347 to be created and cached. This cache is on a per-device basis for all glyphs
9348 except widget-glyphs, and on a per-window basis for widgets-glyphs.  The
9349 caching is done by @code{image_instantiate} and is necessary because it
9350 is generally possible to display an image-instance in multiple
9351 domains. For instance if we create a Pixmap, we can actually display
9352 this on multiple windows - even though we only need a single Pixmap
9353 instance to do this. If caching wasn't done then it would be necessary
9354 to create image-instances for every displayable occurrence of a glyph -
9355 and every usage - and this would be extremely memory and cpu intensive.
9356
9357 Widget-glyphs (a.k.a native widgets) are not cached in this way. This is
9358 because widget-glyph image-instances on screen are toolkit windows, and
9359 thus cannot be reused in multiple XEmacs domains. Thus widget-glyphs are
9360 cached on an XEmacs window basis.  
9361
9362 Any action on a glyph first consults the cache before actually
9363 instantiating a widget.
9364
9365 @section Glyph Instantiation
9366 @cindex glyph instantiation
9367 @cindex instantiation, glyph
9368
9369 Glyph instantiation is a hairy topic and requires some explanation. The
9370 guts of glyph instantiation is contained within
9371 @code{image_instantiate}. A glyph contains an image which is a
9372 specifier. When a glyph function - for instance @code{Fglyph_height} -
9373 asks for a property of the glyph that can only be determined from its
9374 instantiated state, then the glyph image is instantiated and an image
9375 instance created. The instantiation process is governed by the specifier
9376 code and goes through a series of steps:
9377
9378 @itemize @bullet
9379 @item
9380 Validation. Instantiation of image instances happens dynamically - often
9381 within the guts of redisplay. Thus it is often not feasible to catch
9382 instantiator errors at instantiation time. Instead the instantiator is
9383 validated at the time it is added to the image specifier. This function
9384 is defined by @code{image_validate} and at a simple level validates
9385 keyword value pairs.
9386 @item
9387 Duplication. The specifier code by default takes a copy of the
9388 instantiator. This is reasonable for most specifiers but in the case of
9389 widget-glyphs can be problematic, since some of the properties in the
9390 instantiator - for instance callbacks - could cause infinite recursion
9391 in the copying process. Thus the image code defines a function -
9392 @code{image_copy_instantiator} - which will selectively copy values.
9393 This is controlled by the way that a keyword is defined either using
9394 @code{IIFORMAT_VALID_KEYWORD} or
9395 @code{IIFORMAT_VALID_NONCOPY_KEYWORD}. Note that the image caching and
9396 redisplay code relies on instantiator copying to ensure that current and
9397 new instantiators are actually different rather than referring to the
9398 same thing.
9399 @item
9400 Normalization. Once the instantiator has been copied it must be
9401 converted into a form that is viable at instantiation time. This can
9402 involve no changes at all, but typically involves things like converting
9403 file names to the actual data. This function is defined by
9404 @code{image_going_to_add} and @code{normalize_image_instantiator}.
9405 @item
9406 Instantiation. When an image instance is actually required for display
9407 it is instantiated using @code{image_instantiate}. This involves calling
9408 instantiate methods that are specific to the type of image being
9409 instantiated.
9410 @end itemize
9411
9412 The final instantiation phase also involves a number of steps. In order
9413 to understand these we need to describe a number of concepts.
9414
9415 An image is instantiated in a @dfn{domain}, where a domain can be any
9416 one of a device, frame, window or image-instance. The domain gives the
9417 image-instance context and identity and properties that affect the
9418 appearance of the image-instance may be different for the same glyph
9419 instantiated in different domains. An example is the face used to
9420 display the image-instance.
9421
9422 Although an image is instantiated in a particular domain the
9423 instantiation domain is not necessarily the domain in which the
9424 image-instance is cached. For example a pixmap can be instantiated in a
9425 window be actually be cached on a per-device basis. The domain in which
9426 the image-instance is actually cached is called the
9427 @dfn{governing-domain}. A governing-domain is currently either a device
9428 or a window. Widget-glyphs and text-glyphs have a window as a
9429 governing-domain, all other image-instances have a device as the
9430 governing-domain. The governing domain for an image-instance is
9431 determined using the governing_domain image-instance method.
9432
9433 @section Widget-Glyphs
9434 @cindex widget-glyphs
9435
9436 @section Widget-Glyphs in the MS-Windows Environment
9437 @cindex widget-glyphs in the MS-Windows environment
9438 @cindex MS-Windows environment, widget-glyphs in the
9439
9440 To Do
9441
9442 @section Widget-Glyphs in the X Environment
9443 @cindex widget-glyphs in the X environment
9444 @cindex X environment, widget-glyphs in the
9445
9446 Widget-glyphs under X make heavy use of lwlib (@pxref{Lucid Widget
9447 Library}) for manipulating the native toolkit objects. This is primarily
9448 so that different toolkits can be supported for widget-glyphs, just as
9449 they are supported for features such as menubars etc.
9450
9451 Lwlib is extremely poorly documented and quite hairy so here is my
9452 understanding of what goes on.
9453
9454 Lwlib maintains a set of widget_instances which mirror the hierarchical
9455 state of Xt widgets. I think this is so that widgets can be updated and
9456 manipulated generically by the lwlib library. For instance
9457 update_one_widget_instance can cope with multiple types of widget and
9458 multiple types of toolkit. Each element in the widget hierarchy is updated
9459 from its corresponding widget_instance by walking the widget_instance
9460 tree recursively.
9461
9462 This has desirable properties such as lw_modify_all_widgets which is
9463 called from @file{glyphs-x.c} and updates all the properties of a widget
9464 without having to know what the widget is or what toolkit it is from.
9465 Unfortunately this also has hairy properties such as making the lwlib
9466 code quite complex. And of course lwlib has to know at some level what
9467 the widget is and how to set its properties.
9468
9469 @node Specifiers, Menus, Glyphs, Top
9470 @chapter Specifiers
9471 @cindex specifiers
9472
9473 Not yet documented.
9474
9475 @node Menus, Subprocesses, Specifiers, Top
9476 @chapter Menus
9477 @cindex menus
9478
9479   A menu is set by setting the value of the variable
9480 @code{current-menubar} (which may be buffer-local) and then calling
9481 @code{set-menubar-dirty-flag} to signal a change.  This will cause the
9482 menu to be redrawn at the next redisplay.  The format of the data in
9483 @code{current-menubar} is described in @file{menubar.c}.
9484
9485   Internally the data in current-menubar is parsed into a tree of
9486 @code{widget_value's} (defined in @file{lwlib.h}); this is accomplished
9487 by the recursive function @code{menu_item_descriptor_to_widget_value()},
9488 called by @code{compute_menubar_data()}.  Such a tree is deallocated
9489 using @code{free_widget_value()}.
9490
9491   @code{update_screen_menubars()} is one of the external entry points.
9492 This checks to see, for each screen, if that screen's menubar needs to
9493 be updated.  This is the case if
9494
9495 @enumerate
9496 @item
9497 @code{set-menubar-dirty-flag} was called since the last redisplay.  (This
9498 function sets the C variable menubar_has_changed.)
9499 @item
9500 The buffer displayed in the screen has changed.
9501 @item
9502 The screen has no menubar currently displayed.
9503 @end enumerate
9504
9505   @code{set_screen_menubar()} is called for each such screen.  This
9506 function calls @code{compute_menubar_data()} to create the tree of
9507 widget_value's, then calls @code{lw_create_widget()},
9508 @code{lw_modify_all_widgets()}, and/or @code{lw_destroy_all_widgets()}
9509 to create the X-Toolkit widget associated with the menu.
9510
9511   @code{update_psheets()}, the other external entry point, actually
9512 changes the menus being displayed.  It uses the widgets fixed by
9513 @code{update_screen_menubars()} and calls various X functions to ensure
9514 that the menus are displayed properly.
9515
9516   The menubar widget is set up so that @code{pre_activate_callback()} is
9517 called when the menu is first selected (i.e. mouse button goes down),
9518 and @code{menubar_selection_callback()} is called when an item is
9519 selected.  @code{pre_activate_callback()} calls the function in
9520 activate-menubar-hook, which can change the menubar (this is described
9521 in @file{menubar.c}).  If the menubar is changed,
9522 @code{set_screen_menubars()} is called.
9523 @code{menubar_selection_callback()} enqueues a menu event, putting in it
9524 a function to call (either @code{eval} or @code{call-interactively}) and
9525 its argument, which is the callback function or form given in the menu's
9526 description.
9527
9528 @node Subprocesses, Interface to the X Window System, Menus, Top
9529 @chapter Subprocesses
9530 @cindex subprocesses
9531
9532   The fields of a process are:
9533
9534 @table @code
9535 @item name
9536 A string, the name of the process.
9537
9538 @item command
9539 A list containing the command arguments that were used to start this
9540 process.
9541
9542 @item filter
9543 A function used to accept output from the process instead of a buffer,
9544 or @code{nil}.
9545
9546 @item sentinel
9547 A function called whenever the process receives a signal, or @code{nil}.
9548
9549 @item buffer
9550 The associated buffer of the process.
9551
9552 @item pid
9553 An integer, the Unix process @sc{id}.
9554
9555 @item childp
9556 A flag, non-@code{nil} if this is really a child process.
9557 It is @code{nil} for a network connection.
9558
9559 @item mark
9560 A marker indicating the position of the end of the last output from this
9561 process inserted into the buffer.  This is often but not always the end
9562 of the buffer.
9563
9564 @item kill_without_query
9565 If this is non-@code{nil}, killing XEmacs while this process is still
9566 running does not ask for confirmation about killing the process.
9567
9568 @item raw_status_low
9569 @itemx raw_status_high
9570 These two fields record 16 bits each of the process status returned by
9571 the @code{wait} system call.
9572
9573 @item status
9574 The process status, as @code{process-status} should return it.
9575
9576 @item tick
9577 @itemx update_tick
9578 If these two fields are not equal, a change in the status of the process
9579 needs to be reported, either by running the sentinel or by inserting a
9580 message in the process buffer.
9581
9582 @item pty_flag
9583 Non-@code{nil} if communication with the subprocess uses a @sc{pty};
9584 @code{nil} if it uses a pipe.
9585
9586 @item infd
9587 The file descriptor for input from the process.
9588
9589 @item outfd
9590 The file descriptor for output to the process.
9591
9592 @item subtty
9593 The file descriptor for the terminal that the subprocess is using.  (On
9594 some systems, there is no need to record this, so the value is
9595 @code{-1}.)
9596
9597 @item tty_name
9598 The name of the terminal that the subprocess is using,
9599 or @code{nil} if it is using pipes.
9600 @end table
9601
9602 @node Interface to the X Window System, Index, Subprocesses, Top
9603 @chapter Interface to the X Window System
9604 @cindex X Window System, interface to the
9605
9606 Mostly undocumented.
9607
9608 @menu
9609 * Lucid Widget Library::        An interface to various widget sets.
9610 @end menu
9611
9612 @node Lucid Widget Library
9613 @section Lucid Widget Library
9614 @cindex Lucid Widget Library
9615 @cindex widget library, Lucid
9616 @cindex library, Lucid Widget
9617
9618 Lwlib is extremely poorly documented and quite hairy.  The author(s)
9619 blame that on X, Xt, and Motif, with some justice, but also sufficient
9620 hypocrisy to avoid drawing the obvious conclusion about their own work.
9621
9622 The Lucid Widget Library is composed of two more or less independent
9623 pieces.  The first, as the name suggests, is a set of widgets.  These
9624 widgets are intended to resemble and improve on widgets provided in the
9625 Motif toolkit but not in the Athena widgets, including menubars and
9626 scrollbars.  Recent additions by Andy Piper integrate some ``modern''
9627 widgets by Edward Falk, including checkboxes, radio buttons, progress
9628 gauges, and index tab controls (aka notebooks).
9629
9630 The second piece of the Lucid widget library is a generic interface to
9631 several toolkits for X (including Xt, the Athena widget set, and Motif,
9632 as well as the Lucid widgets themselves) so that core XEmacs code need
9633 not know which widget set has been used to build the graphical user
9634 interface.
9635
9636 @menu
9637 * Generic Widget Interface::    The lwlib generic widget interface.
9638 * Scrollbars::
9639 * Menubars::
9640 * Checkboxes and Radio Buttons::
9641 * Progress Bars::
9642 * Tab Controls::
9643 @end menu
9644
9645 @node Generic Widget Interface
9646 @subsection Generic Widget Interface
9647 @cindex widget interface, generic
9648
9649 In general in any toolkit a widget may be a composite object.  In Xt,
9650 all widgets have an X window that they manage, but typically a complex
9651 widget will have widget children, each of which manages a subwindow of
9652 the parent widget's X window.  These children may themselves be
9653 composite widgets.  Thus a widget is actually a tree or hierarchy of
9654 widgets.
9655
9656 For each toolkit widget, lwlib maintains a tree of @code{widget_values}
9657 which mirror the hierarchical state of Xt widgets (including Motif,
9658 Athena, 3D Athena, and Falk's widget sets).  Each @code{widget_value}
9659 has @code{contents} member, which points to the head of a linked list of
9660 its children.  The linked list of siblings is chained through the
9661 @code{next} member of @code{widget_value}.
9662
9663 @example
9664            +-----------+
9665            | composite |
9666            +-----------+
9667                  |
9668                  | contents
9669                  V
9670              +-------+ next +-------+ next +-------+
9671              | child |----->| child |----->| child |
9672              +-------+      +-------+      +-------+
9673                                 |
9674                                 | contents
9675                                 V
9676                          +-------------+ next +-------------+
9677                          | grand child |----->| grand child |
9678                          +-------------+      +-------------+
9679
9680 The @code{widget_value} hierarchy of a composite widget with two simple
9681 children and one composite child.
9682 @end example
9683
9684 The @code{widget_instance} structure maintains the inverse view of the
9685 tree.  As for the @code{widget_value}, siblings are chained through the
9686 @code{next} member.  However, rather than naming children, the
9687 @code{widget_instance} tree links to parents.
9688
9689 @example
9690            +-----------+
9691            | composite |
9692            +-----------+
9693                  A
9694                  | parent
9695                  |
9696              +-------+ next +-------+ next +-------+
9697              | child |----->| child |----->| child |
9698              +-------+      +-------+      +-------+
9699                                 A
9700                                 | parent
9701                                 |
9702                          +-------------+ next +-------------+
9703                          | grand child |----->| grand child |
9704                          +-------------+      +-------------+
9705
9706 The @code{widget_value} hierarchy of a composite widget with two simple
9707 children and one composite child.
9708 @end example
9709
9710 This permits widgets derived from different toolkits to be updated and
9711 manipulated generically by the lwlib library. For instance
9712 @code{update_one_widget_instance} can cope with multiple types of widget
9713 and multiple types of toolkit. Each element in the widget hierarchy is
9714 updated from its corresponding @code{widget_value} by walking the
9715 @code{widget_value} tree.  This has desirable properties.  For example,
9716 @code{lw_modify_all_widgets} is called from @file{glyphs-x.c} and
9717 updates all the properties of a widget without having to know what the
9718 widget is or what toolkit it is from.  Unfortunately this also has its
9719 hairy properties; the lwlib code quite complex. And of course lwlib has
9720 to know at some level what the widget is and how to set its properties.
9721
9722 The @code{widget_instance} structure also contains a pointer to the root
9723 of its tree.  Widget instances are further confi
9724
9725
9726 @node Scrollbars
9727 @subsection Scrollbars
9728 @cindex scrollbars
9729
9730 @node Menubars
9731 @subsection Menubars
9732 @cindex menubars
9733
9734 @node Checkboxes and Radio Buttons
9735 @subsection Checkboxes and Radio Buttons
9736 @cindex checkboxes and radio buttons
9737 @cindex radio buttons, checkboxes and
9738 @cindex buttons, checkboxes and radio
9739
9740 @node Progress Bars
9741 @subsection Progress Bars
9742 @cindex progress bars
9743 @cindex bars, progress
9744
9745 @node Tab Controls
9746 @subsection Tab Controls
9747 @cindex tab controls
9748
9749 @include index.texi
9750
9751 @c Print the tables of contents
9752 @summarycontents
9753 @contents
9754 @c That's all
9755
9756 @bye