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