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