db7c9568756ea8f2bf6b3afde6fba4ac7c288984
[chise/xemacs-chise.git-] / info / internals.info-1
1 This is ../info/internals.info, produced by makeinfo version 4.8 from
2 internals/internals.texi.
3
4 INFO-DIR-SECTION XEmacs Editor
5 START-INFO-DIR-ENTRY
6 * Internals: (internals).       XEmacs Internals Manual.
7 END-INFO-DIR-ENTRY
8
9    Copyright (C) 1992 - 1996 Ben Wing.  Copyright (C) 1996, 1997 Sun
10 Microsystems.  Copyright (C) 1994 - 1998, 2002, 2003 Free Software
11 Foundation.  Copyright (C) 1994, 1995 Board of Trustees, University of
12 Illinois.
13
14    Permission is granted to make and distribute verbatim copies of this
15 manual provided the copyright notice and this permission notice are
16 preserved on all copies.
17
18    Permission is granted to copy and distribute modified versions of
19 this manual under the conditions for verbatim copying, provided that the
20 entire resulting derived work is distributed under the terms of a
21 permission notice identical to this one.
22
23    Permission is granted to copy and distribute translations of this
24 manual into another language, under the above conditions for modified
25 versions, except that this permission notice may be stated in a
26 translation approved by the Foundation.
27
28    Permission is granted to copy and distribute modified versions of
29 this manual under the conditions for verbatim copying, provided also
30 that the section entitled "GNU General Public License" is included
31 exactly as in the original, and provided that the entire resulting
32 derived work is distributed under the terms of a permission notice
33 identical to this one.
34
35    Permission is granted to copy and distribute translations of this
36 manual into another language, under the above conditions for modified
37 versions, except that the section entitled "GNU General Public License"
38 may be included in a translation approved by the Free Software
39 Foundation instead of in the original English.
40
41 \1f
42 File: internals.info,  Node: Top,  Next: A History of Emacs,  Prev: (dir),  Up: (dir)
43
44    This Info file contains v1.4 of the XEmacs Internals Manual, March
45 2001.
46
47 * Menu:
48
49 * A History of Emacs::          Times, dates, important events.
50 * XEmacs From the Outside::     A broad conceptual overview.
51 * The Lisp Language::           An overview.
52 * XEmacs From the Perspective of Building::
53 * XEmacs From the Inside::
54 * The XEmacs Object System (Abstractly Speaking)::
55 * How Lisp Objects Are Represented in C::
56 * Rules When Writing New C Code::
57 * Regression Testing XEmacs::
58 * A Summary of the Various XEmacs Modules::
59 * Allocation of Objects in XEmacs Lisp::
60 * Dumping::
61 * Events and the Event Loop::
62 * Evaluation; Stack Frames; Bindings::
63 * Symbols and Variables::
64 * Buffers and Textual Representation::
65 * MULE Character Sets and Encodings::
66 * The Lisp Reader and Compiler::
67 * Lstreams::
68 * Consoles; Devices; Frames; Windows::
69 * The Redisplay Mechanism::
70 * Extents::
71 * Faces::
72 * Glyphs::
73 * Specifiers::
74 * Menus::
75 * Subprocesses::
76 * Interface to the X Window System::
77 * Index::
78
79
80 --- The Detailed Node Listing ---
81
82 A History of Emacs
83
84 * Through Version 18::          Unification prevails.
85 * Lucid Emacs::                 One version 19 Emacs.
86 * GNU Emacs 19::                The other version 19 Emacs.
87 * GNU Emacs 20::                The other version 20 Emacs.
88 * XEmacs::                      The continuation of Lucid Emacs.
89
90 Rules When Writing New C Code
91
92 * General Coding Rules::
93 * Writing Lisp Primitives::
94 * Adding Global Lisp Variables::
95 * Coding for Mule::
96 * Techniques for XEmacs Developers::
97
98 Coding for Mule
99
100 * Character-Related Data Types::
101 * Working With Character and Byte Positions::
102 * Conversion to and from External Data::
103 * General Guidelines for Writing Mule-Aware Code::
104 * An Example of Mule-Aware Code::
105
106 Regression Testing XEmacs
107
108 A Summary of the Various XEmacs Modules
109
110 * Low-Level Modules::
111 * Basic Lisp Modules::
112 * Modules for Standard Editing Operations::
113 * Editor-Level Control Flow Modules::
114 * Modules for the Basic Displayable Lisp Objects::
115 * Modules for other Display-Related Lisp Objects::
116 * Modules for the Redisplay Mechanism::
117 * Modules for Interfacing with the File System::
118 * Modules for Other Aspects of the Lisp Interpreter and Object System::
119 * Modules for Interfacing with the Operating System::
120 * Modules for Interfacing with X Windows::
121 * Modules for Internationalization::
122 * Modules for Regression Testing::
123
124 Allocation of Objects in XEmacs Lisp
125
126 * Introduction to Allocation::
127 * Garbage Collection::
128 * GCPROing::
129 * Garbage Collection - Step by Step::
130 * Integers and Characters::
131 * Allocation from Frob Blocks::
132 * lrecords::
133 * Low-level allocation::
134 * Cons::
135 * Vector::
136 * Bit Vector::
137 * Symbol::
138 * Marker::
139 * String::
140 * Compiled Function::
141
142 Garbage Collection - Step by Step
143
144 * Invocation::
145 * garbage_collect_1::
146 * mark_object::
147 * gc_sweep::
148 * sweep_lcrecords_1::
149 * compact_string_chars::
150 * sweep_strings::
151 * sweep_bit_vectors_1::
152
153 Dumping
154
155 * Overview::
156 * Data descriptions::
157 * Dumping phase::
158 * Reloading phase::
159
160 Dumping phase
161
162 * Object inventory::
163 * Address allocation::
164 * The header::
165 * Data dumping::
166 * Pointers dumping::
167
168 Events and the Event Loop
169
170 * Introduction to Events::
171 * Main Loop::
172 * Specifics of the Event Gathering Mechanism::
173 * Specifics About the Emacs Event::
174 * The Event Stream Callback Routines::
175 * Other Event Loop Functions::
176 * Converting Events::
177 * Dispatching Events; The Command Builder::
178
179 Evaluation; Stack Frames; Bindings
180
181 * Evaluation::
182 * Dynamic Binding; The specbinding Stack; Unwind-Protects::
183 * Simple Special Forms::
184 * Catch and Throw::
185
186 Symbols and Variables
187
188 * Introduction to Symbols::
189 * Obarrays::
190 * Symbol Values::
191
192 Buffers and Textual Representation
193
194 * Introduction to Buffers::     A buffer holds a block of text such as a file.
195 * The Text in a Buffer::        Representation of the text in a buffer.
196 * Buffer Lists::                Keeping track of all buffers.
197 * Markers and Extents::         Tagging locations within a buffer.
198 * Bufbytes and Emchars::        Representation of individual characters.
199 * The Buffer Object::           The Lisp object corresponding to a buffer.
200
201 MULE Character Sets and Encodings
202
203 * Character Sets::
204 * Encodings::
205 * Internal Mule Encodings::
206 * CCL::
207
208 Encodings
209
210 * Japanese EUC (Extended Unix Code)::
211 * JIS7::
212
213 Internal Mule Encodings
214
215 * Internal String Encoding::
216 * Internal Character Encoding::
217
218 Lstreams
219
220 * Creating an Lstream::         Creating an lstream object.
221 * Lstream Types::               Different sorts of things that are streamed.
222 * Lstream Functions::           Functions for working with lstreams.
223 * Lstream Methods::             Creating new lstream types.
224
225 Consoles; Devices; Frames; Windows
226
227 * Introduction to Consoles; Devices; Frames; Windows::
228 * Point::
229 * Window Hierarchy::
230 * The Window Object::
231
232 The Redisplay Mechanism
233
234 * Critical Redisplay Sections::
235 * Line Start Cache::
236 * Redisplay Piece by Piece::
237
238 Extents
239
240 * Introduction to Extents::     Extents are ranges over text, with properties.
241 * Extent Ordering::             How extents are ordered internally.
242 * Format of the Extent Info::   The extent information in a buffer or string.
243 * Zero-Length Extents::         A weird special case.
244 * Mathematics of Extent Ordering::  A rigorous foundation.
245 * Extent Fragments::            Cached information useful for redisplay.
246
247 \1f
248 File: internals.info,  Node: A History of Emacs,  Next: XEmacs From the Outside,  Prev: Top,  Up: Top
249
250 1 A History of Emacs
251 ********************
252
253 XEmacs is a powerful, customizable text editor and development
254 environment.  It began as Lucid Emacs, which was in turn derived from
255 GNU Emacs, a program written by Richard Stallman of the Free Software
256 Foundation.  GNU Emacs dates back to the 1970's, and was modelled after
257 a package called "Emacs", written in 1976, that was a set of macros on
258 top of TECO, an old, old text editor written at MIT on the DEC PDP 10
259 under one of the earliest time-sharing operating systems, ITS
260 (Incompatible Timesharing System). (ITS dates back well before Unix.)
261 ITS, TECO, and Emacs were products of a group of people at MIT who
262 called themselves "hackers", who shared an idealistic belief system
263 about the free exchange of information and were fanatical in their
264 devotion to and time spent with computers. (The hacker subculture dates
265 back to the late 1950's at MIT and is described in detail in Steven
266 Levy's book `Hackers'.  This book also includes a lot of information
267 about Stallman himself and the development of Lisp, a programming
268 language developed at MIT that underlies Emacs.)
269
270 * Menu:
271
272 * Through Version 18::          Unification prevails.
273 * Lucid Emacs::                 One version 19 Emacs.
274 * GNU Emacs 19::                The other version 19 Emacs.
275 * GNU Emacs 20::                The other version 20 Emacs.
276 * XEmacs::                      The continuation of Lucid Emacs.
277
278 \1f
279 File: internals.info,  Node: Through Version 18,  Next: Lucid Emacs,  Up: A History of Emacs
280
281 1.1 Through Version 18
282 ======================
283
284 Although the history of the early versions of GNU Emacs is unclear, the
285 history is well-known from the middle of 1985.  A time line is:
286
287    * GNU Emacs version 15 (15.34) was released sometime in 1984 or 1985
288      and shared some code with a version of Emacs written by James
289      Gosling (the same James Gosling who later created the Java
290      language).
291
292    * GNU Emacs version 16 (first released version was 16.56) was
293      released on July 15, 1985.  All Gosling code was removed due to
294      potential copyright problems with the code.
295
296    * version 16.57: released on September 16, 1985.
297
298    * versions 16.58, 16.59: released on September 17, 1985.
299
300    * version 16.60: released on September 19, 1985.  These later
301      version 16's incorporated patches from the net, esp. for getting
302      Emacs to work under System V.
303
304    * version 17.36 (first official v17 release) released on December 20,
305      1985.  Included a TeX-able user manual.  First official unpatched
306      version that worked on vanilla System V machines.
307
308    * version 17.43 (second official v17 release) released on January 25,
309      1986.
310
311    * version 17.45 released on January 30, 1986.
312
313    * version 17.46 released on February 4, 1986.
314
315    * version 17.48 released on February 10, 1986.
316
317    * version 17.49 released on February 12, 1986.
318
319    * version 17.55 released on March 18, 1986.
320
321    * version 17.57 released on March 27, 1986.
322
323    * version 17.58 released on April 4, 1986.
324
325    * version 17.61 released on April 12, 1986.
326
327    * version 17.63 released on May 7, 1986.
328
329    * version 17.64 released on May 12, 1986.
330
331    * version 18.24 (a beta version) released on October 2, 1986.
332
333    * version 18.30 (a beta version) released on November 15, 1986.
334
335    * version 18.31 (a beta version) released on November 23, 1986.
336
337    * version 18.32 (a beta version) released on December 7, 1986.
338
339    * version 18.33 (a beta version) released on December 12, 1986.
340
341    * version 18.35 (a beta version) released on January 5, 1987.
342
343    * version 18.36 (a beta version) released on January 21, 1987.
344
345    * January 27, 1987: The Great Usenet Renaming.  net.emacs is now
346      comp.emacs.
347
348    * version 18.37 (a beta version) released on February 12, 1987.
349
350    * version 18.38 (a beta version) released on March 3, 1987.
351
352    * version 18.39 (a beta version) released on March 14, 1987.
353
354    * version 18.40 (a beta version) released on March 18, 1987.
355
356    * version 18.41 (the first "official" release) released on March 22,
357      1987.
358
359    * version 18.45 released on June 2, 1987.
360
361    * version 18.46 released on June 9, 1987.
362
363    * version 18.47 released on June 18, 1987.
364
365    * version 18.48 released on September 3, 1987.
366
367    * version 18.49 released on September 18, 1987.
368
369    * version 18.50 released on February 13, 1988.
370
371    * version 18.51 released on May 7, 1988.
372
373    * version 18.52 released on September 1, 1988.
374
375    * version 18.53 released on February 24, 1989.
376
377    * version 18.54 released on April 26, 1989.
378
379    * version 18.55 released on August 23, 1989.  This is the earliest
380      version that is still available by FTP.
381
382    * version 18.56 released on January 17, 1991.
383
384    * version 18.57 released late January, 1991.
385
386    * version 18.58 released ?????.
387
388    * version 18.59 released October 31, 1992.
389
390 \1f
391 File: internals.info,  Node: Lucid Emacs,  Next: GNU Emacs 19,  Prev: Through Version 18,  Up: A History of Emacs
392
393 1.2 Lucid Emacs
394 ===============
395
396 Lucid Emacs was developed by the (now-defunct) Lucid Inc., a maker of
397 C++ and Lisp development environments.  It began when Lucid decided they
398 wanted to use Emacs as the editor and cornerstone of their C++
399 development environment (called "Energize").  They needed many features
400 that were not available in the existing version of GNU Emacs (version
401 18.5something), in particular good and integrated support for GUI
402 elements such as mouse support, multiple fonts, multiple window-system
403 windows, etc.  A branch of GNU Emacs called Epoch, written at the
404 University of Illinois, existed that supplied many of these features;
405 however, Lucid needed more than what existed in Epoch.  At the time, the
406 Free Software Foundation was working on version 19 of Emacs (this was
407 sometime around 1991), which was planned to have similar features, and
408 so Lucid decided to work with the Free Software Foundation.  Their plan
409 was to add features that they needed, and coordinate with the FSF so
410 that the features would get included back into Emacs version 19.
411
412    Delays in the release of version 19 occurred, however (resulting in
413 it finally being released more than a year after what was initially
414 planned), and Lucid encountered unexpected technical resistance in
415 getting their changes merged back into version 19, so they decided to
416 release their own version of Emacs, which became Lucid Emacs 19.0.
417
418    The initial authors of Lucid Emacs were Matthieu Devin, Harlan
419 Sexton, and Eric Benson, and the work was later taken over by Jamie
420 Zawinski, who became "Mr. Lucid Emacs" for many releases.
421
422    A time line for Lucid Emacs is
423
424    * version 19.0 shipped with Energize 1.0, April 1992.
425
426    * version 19.1 released June 4, 1992.
427
428    * version 19.2 released June 19, 1992.
429
430    * version 19.3 released September 9, 1992.
431
432    * version 19.4 released January 21, 1993.
433
434    * version 19.5 was a repackaging of 19.4 with a few bug fixes and
435      shipped with Energize 2.0.  Never released to the net.
436
437    * version 19.6 released April 9, 1993.
438
439    * version 19.7 was a repackaging of 19.6 with a few bug fixes and
440      shipped with Energize 2.1.  Never released to the net.
441
442    * version 19.8 released September 6, 1993.
443
444    * version 19.9 released January 12, 1994.
445
446    * version 19.10 released May 27, 1994.
447
448    * version 19.11 (first XEmacs) released September 13, 1994.
449
450    * version 19.12 released June 23, 1995.
451
452    * version 19.13 released September 1, 1995.
453
454    * version 19.14 released June 23, 1996.
455
456    * version 20.0 released February 9, 1997.
457
458    * version 19.15 released March 28, 1997.
459
460    * version 20.1 (not released to the net) April 15, 1997.
461
462    * version 20.2 released May 16, 1997.
463
464    * version 19.16 released October 31, 1997.
465
466    * version 20.3 (the first stable version of XEmacs 20.x) released
467      November 30, 1997.
468
469    * version 20.4 released February 28, 1998.
470
471    * version 21.1.2 released May 14, 1999. (The version naming scheme
472      was changed at this point: [a] the second version number is odd
473      for stable versions, even for beta versions; [b] a third version
474      number is added, replacing the "beta xxx" ending for beta versions
475      and allowing for periodic maintenance releases for stable
476      versions.  Therefore, 21.0 was never "officially" released;
477      similarly for 21.2, etc.)
478
479    * version 21.1.3 released June 26, 1999.
480
481    * version 21.1.4 released July 8, 1999.
482
483    * version 21.1.6 released August 14, 1999. (There was no 21.1.5.)
484
485    * version 21.1.7 released September 26, 1999.
486
487    * version 21.1.8 released November 2, 1999.
488
489    * version 21.1.9 released February 13, 2000.
490
491    * version 21.1.10 released May 7, 2000.
492
493    * version 21.1.10a released June 24, 2000.
494
495    * version 21.1.11 released July 18, 2000.
496
497    * version 21.1.12 released August 5, 2000.
498
499    * version 21.1.13 released January 7, 2001.
500
501    * version 21.1.14 released January 27, 2001.
502
503 \1f
504 File: internals.info,  Node: GNU Emacs 19,  Next: GNU Emacs 20,  Prev: Lucid Emacs,  Up: A History of Emacs
505
506 1.3 GNU Emacs 19
507 ================
508
509 About a year after the initial release of Lucid Emacs, the FSF released
510 a beta of their version of Emacs 19 (referred to here as "GNU Emacs").
511 By this time, the current version of Lucid Emacs was 19.6. (Strangely,
512 the first released beta from the FSF was GNU Emacs 19.7.) A time line
513 for GNU Emacs version 19 is
514
515    * version 19.8 (beta) released May 27, 1993.
516
517    * version 19.9 (beta) released May 27, 1993.
518
519    * version 19.10 (beta) released May 30, 1993.
520
521    * version 19.11 (beta) released June 1, 1993.
522
523    * version 19.12 (beta) released June 2, 1993.
524
525    * version 19.13 (beta) released June 8, 1993.
526
527    * version 19.14 (beta) released June 17, 1993.
528
529    * version 19.15 (beta) released June 19, 1993.
530
531    * version 19.16 (beta) released July 6, 1993.
532
533    * version 19.17 (beta) released late July, 1993.
534
535    * version 19.18 (beta) released August 9, 1993.
536
537    * version 19.19 (beta) released August 15, 1993.
538
539    * version 19.20 (beta) released November 17, 1993.
540
541    * version 19.21 (beta) released November 17, 1993.
542
543    * version 19.22 (beta) released November 28, 1993.
544
545    * version 19.23 (beta) released May 17, 1994.
546
547    * version 19.24 (beta) released May 16, 1994.
548
549    * version 19.25 (beta) released June 3, 1994.
550
551    * version 19.26 (beta) released September 11, 1994.
552
553    * version 19.27 (beta) released September 14, 1994.
554
555    * version 19.28 (first "official" release) released November 1, 1994.
556
557    * version 19.29 released June 21, 1995.
558
559    * version 19.30 released November 24, 1995.
560
561    * version 19.31 released May 25, 1996.
562
563    * version 19.32 released July 31, 1996.
564
565    * version 19.33 released August 11, 1996.
566
567    * version 19.34 released August 21, 1996.
568
569    * version 19.34b released September 6, 1996.
570
571    In some ways, GNU Emacs 19 was better than Lucid Emacs; in some ways,
572 worse.  Lucid soon began incorporating features from GNU Emacs 19 into
573 Lucid Emacs; the work was mostly done by Richard Mlynarik, who had been
574 working on and using GNU Emacs for a long time (back as far as version
575 16 or 17).
576
577 \1f
578 File: internals.info,  Node: GNU Emacs 20,  Next: XEmacs,  Prev: GNU Emacs 19,  Up: A History of Emacs
579
580 1.4 GNU Emacs 20
581 ================
582
583 On February 2, 1997 work began on GNU Emacs to integrate Mule.  The
584 first release was made in September of that year.
585
586    A timeline for Emacs 20 is
587
588    * version 20.1 released September 17, 1997.
589
590    * version 20.2 released September 20, 1997.
591
592    * version 20.3 released August 19, 1998.
593
594 \1f
595 File: internals.info,  Node: XEmacs,  Prev: GNU Emacs 20,  Up: A History of Emacs
596
597 1.5 XEmacs
598 ==========
599
600 Around the time that Lucid was developing Energize, Sun Microsystems
601 was developing their own development environment (called "SPARCWorks")
602 and also decided to use Emacs.  They joined forces with the Epoch team
603 at the University of Illinois and later with Lucid.  The maintainer of
604 the last-released version of Epoch was Marc Andreessen, but he dropped
605 out and the Epoch project, headed by Simon Kaplan, lured Chuck Thompson
606 away from a system administration job to become the primary Lucid Emacs
607 author for Epoch and Sun.  Chuck's area of specialty became the
608 redisplay engine (he replaced the old Lucid Emacs redisplay engine with
609 a ported version from Epoch and then later rewrote it from scratch).
610 Sun also hired Ben Wing (the author of Win-Emacs, a port of Lucid Emacs
611 to Microsoft Windows 3.1) in 1993, for what was initially a one-month
612 contract to fix some event problems but later became a many-year
613 involvement, punctuated by a six-month contract with Amdahl Corporation.
614
615    In 1994, Sun and Lucid agreed to rename Lucid Emacs to XEmacs (a name
616 not favorable to either company); the first release called XEmacs was
617 version 19.11.  In June 1994, Lucid folded and Jamie quit to work for
618 the newly formed Mosaic Communications Corp., later Netscape
619 Communications Corp. (co-founded by the same Marc Andreessen, who had
620 quit his Epoch job to work on a graphical browser for the World Wide
621 Web).  Chuck then become the primary maintainer of XEmacs, and put out
622 versions 19.11 through 19.14 in conjunction with Ben.  For 19.12 and
623 19.13, Chuck added the new redisplay and many other display improvements
624 and Ben added MULE support (support for Asian and other languages) and
625 redesigned most of the internal Lisp subsystems to better support the
626 MULE work and the various other features being added to XEmacs.  After
627 19.14 Chuck retired as primary maintainer and Steve Baur stepped in.
628
629    Soon after 19.13 was released, work began in earnest on the MULE
630 internationalization code and the source tree was divided into two
631 development paths.  The MULE version was initially called 19.20, but was
632 soon renamed to 20.0.  In 1996 Martin Buchholz of Sun Microsystems took
633 over the care and feeding of it and worked on it in parallel with the
634 19.14 development that was occurring at the same time.  After much work
635 by Martin, it was decided to release 20.0 ahead of 19.15 in February
636 1997.  The source tree remained divided until 20.2 when the version 19
637 source was finally retired at version 19.16.
638
639    In 1997, Sun finally dropped all pretense of support for XEmacs and
640 Martin Buchholz left the company in November.  Since then, and mostly
641 for the previous year, because Steve Baur was never paid to work on
642 XEmacs, XEmacs has existed solely on the contributions of volunteers
643 from the Free Software Community.  Starting from 1997, Hrvoje Niksic and
644 Kyle Jones have figured prominently in XEmacs development.
645
646    Many attempts have been made to merge XEmacs and GNU Emacs, but they
647 have consistently failed.
648
649    A more detailed history is contained in the XEmacs About page.
650
651    A time line for XEmacs is
652
653    * version 19.11 (first XEmacs) released September 13, 1994.
654
655    * version 19.12 released June 23, 1995.
656
657    * version 19.13 released September 1, 1995.
658
659    * version 19.14 released June 23, 1996.
660
661    * version 20.0 released February 9, 1997.
662
663    * version 19.15 released March 28, 1997.
664
665    * version 20.1 (not released to the net) April 15, 1997.
666
667    * version 20.2 released May 16, 1997.
668
669    * version 19.16 released October 31, 1997.
670
671    * version 20.3 (the first stable version of XEmacs 20.x) released
672      November 30, 1997.
673
674    * version 20.4 released February 28, 1998.
675
676    * version 21.0.60 released December 10, 1998. (The version naming
677      scheme was changed at this point: [a] the second version number is
678      odd for stable versions, even for beta versions; [b] a third
679      version number is added, replacing the "beta xxx" ending for beta
680      versions and allowing for periodic maintenance releases for stable
681      versions.  Therefore, 21.0 was never "officially" released;
682      similarly for 21.2, etc.)
683
684    * version 21.0.61 released January 4, 1999.
685
686    * version 21.0.63 released February 3, 1999.
687
688    * version 21.0.64 released March 1, 1999.
689
690    * version 21.0.65 released March 5, 1999.
691
692    * version 21.0.66 released March 12, 1999.
693
694    * version 21.0.67 released March 25, 1999.
695
696    * version 21.1.2 released May 14, 1999. (This is the followup to
697      21.0.67.  The second version number was bumped to indicate the
698      beginning of the "stable" series.)
699
700    * version 21.1.3 released June 26, 1999.
701
702    * version 21.1.4 released July 8, 1999.
703
704    * version 21.1.6 released August 14, 1999. (There was no 21.1.5.)
705
706    * version 21.1.7 released September 26, 1999.
707
708    * version 21.1.8 released November 2, 1999.
709
710    * version 21.1.9 released February 13, 2000.
711
712    * version 21.1.10 released May 7, 2000.
713
714    * version 21.1.10a released June 24, 2000.
715
716    * version 21.1.11 released July 18, 2000.
717
718    * version 21.1.12 released August 5, 2000.
719
720    * version 21.1.13 released January 7, 2001.
721
722    * version 21.1.14 released January 27, 2001.
723
724    * version 21.2.9 released February 3, 1999.
725
726    * version 21.2.10 released February 5, 1999.
727
728    * version 21.2.11 released March 1, 1999.
729
730    * version 21.2.12 released March 5, 1999.
731
732    * version 21.2.13 released March 12, 1999.
733
734    * version 21.2.14 released May 14, 1999.
735
736    * version 21.2.15 released June 4, 1999.
737
738    * version 21.2.16 released June 11, 1999.
739
740    * version 21.2.17 released June 22, 1999.
741
742    * version 21.2.18 released July 14, 1999.
743
744    * version 21.2.19 released July 30, 1999.
745
746    * version 21.2.20 released November 10, 1999.
747
748    * version 21.2.21 released November 28, 1999.
749
750    * version 21.2.22 released November 29, 1999.
751
752    * version 21.2.23 released December 7, 1999.
753
754    * version 21.2.24 released December 14, 1999.
755
756    * version 21.2.25 released December 24, 1999.
757
758    * version 21.2.26 released December 31, 1999.
759
760    * version 21.2.27 released January 18, 2000.
761
762    * version 21.2.28 released February 7, 2000.
763
764    * version 21.2.29 released February 16, 2000.
765
766    * version 21.2.30 released February 21, 2000.
767
768    * version 21.2.31 released February 23, 2000.
769
770    * version 21.2.32 released March 20, 2000.
771
772    * version 21.2.33 released May 1, 2000.
773
774    * version 21.2.34 released May 28, 2000.
775
776    * version 21.2.35 released July 19, 2000.
777
778    * version 21.2.36 released October 4, 2000.
779
780    * version 21.2.37 released November 14, 2000.
781
782    * version 21.2.38 released December 5, 2000.
783
784    * version 21.2.39 released December 31, 2000.
785
786    * version 21.2.40 released January 8, 2001.
787
788    * version 21.2.41 released January 17, 2001.
789
790    * version 21.2.42 released January 20, 2001.
791
792    * version 21.2.43 released January 26, 2001.
793
794    * version 21.2.44 released February 8, 2001.
795
796    * version 21.2.45 released February 23, 2001.
797
798    * version 21.2.46 released March 21, 2001.
799
800 \1f
801 File: internals.info,  Node: XEmacs From the Outside,  Next: The Lisp Language,  Prev: A History of Emacs,  Up: Top
802
803 2 XEmacs From the Outside
804 *************************
805
806 XEmacs appears to the outside world as an editor, but it is really a
807 Lisp environment.  At its heart is a Lisp interpreter; it also
808 "happens" to contain many specialized object types (e.g. buffers,
809 windows, frames, events) that are useful for implementing an editor.
810 Some of these objects (in particular windows and frames) have
811 displayable representations, and XEmacs provides a function
812 `redisplay()' that ensures that the display of all such objects matches
813 their internal state.  Most of the time, a standard Lisp environment is
814 in a "read-eval-print" loop--i.e. "read some Lisp code, execute it, and
815 print the results".  XEmacs has a similar loop:
816
817    * read an event
818
819    * dispatch the event (i.e. "do it")
820
821    * redisplay
822
823    Reading an event is done using the Lisp function `next-event', which
824 waits for something to happen (typically, the user presses a key or
825 moves the mouse) and returns an event object describing this.
826 Dispatching an event is done using the Lisp function `dispatch-event',
827 which looks up the event in a keymap object (a particular kind of
828 object that associates an event with a Lisp function) and calls that
829 function.  The function "does" what the user has requested by changing
830 the state of particular frame objects, buffer objects, etc.  Finally,
831 `redisplay()' is called, which updates the display to reflect those
832 changes just made.  Thus is an "editor" born.
833
834    Note that you do not have to use XEmacs as an editor; you could just
835 as well make it do your taxes, compute pi, play bridge, etc.  You'd just
836 have to write functions to do those operations in Lisp.
837
838 \1f
839 File: internals.info,  Node: The Lisp Language,  Next: XEmacs From the Perspective of Building,  Prev: XEmacs From the Outside,  Up: Top
840
841 3 The Lisp Language
842 *******************
843
844 Lisp is a general-purpose language that is higher-level than C and in
845 many ways more powerful than C.  Powerful dialects of Lisp such as
846 Common Lisp are probably much better languages for writing very large
847 applications than is C. (Unfortunately, for many non-technical reasons
848 C and its successor C++ have become the dominant languages for
849 application development.  These languages are both inadequate for
850 extremely large applications, which is evidenced by the fact that newer,
851 larger programs are becoming ever harder to write and are requiring ever
852 more programmers despite great increases in C development environments;
853 and by the fact that, although hardware speeds and reliability have been
854 growing at an exponential rate, most software is still generally
855 considered to be slow and buggy.)
856
857    The new Java language holds promise as a better general-purpose
858 development language than C.  Java has many features in common with
859 Lisp that are not shared by C (this is not a coincidence, since Java
860 was designed by James Gosling, a former Lisp hacker).  This will be
861 discussed more later.
862
863    For those used to C, here is a summary of the basic differences
864 between C and Lisp:
865
866   1. Lisp has an extremely regular syntax.  Every function, expression,
867      and control statement is written in the form
868
869              (FUNC ARG1 ARG2 ...)
870
871      This is as opposed to C, which writes functions as
872
873              func(ARG1, ARG2, ...)
874
875      but writes expressions involving operators as (e.g.)
876
877              ARG1 + ARG2
878
879      and writes control statements as (e.g.)
880
881              while (EXPR) { STATEMENT1; STATEMENT2; ... }
882
883      Lisp equivalents of the latter two would be
884
885              (+ ARG1 ARG2 ...)
886
887      and
888
889              (while EXPR STATEMENT1 STATEMENT2 ...)
890
891   2. Lisp is a safe language.  Assuming there are no bugs in the Lisp
892      interpreter/compiler, it is impossible to write a program that
893      "core dumps" or otherwise causes the machine to execute an illegal
894      instruction.  This is very different from C, where perhaps the most
895      common outcome of a bug is exactly such a crash.  A corollary of
896      this is that the C operation of casting a pointer is impossible
897      (and unnecessary) in Lisp, and that it is impossible to access
898      memory outside the bounds of an array.
899
900   3. Programs and data are written in the same form.  The
901      parenthesis-enclosing form described above for statements is the
902      same form used for the most common data type in Lisp, the list.
903      Thus, it is possible to represent any Lisp program using Lisp data
904      types, and for one program to construct Lisp statements and then
905      dynamically "evaluate" them, or cause them to execute.
906
907   4. All objects are "dynamically typed".  This means that part of every
908      object is an indication of what type it is.  A Lisp program can
909      manipulate an object without knowing what type it is, and can
910      query an object to determine its type.  This means that,
911      correspondingly, variables and function parameters can hold
912      objects of any type and are not normally declared as being of any
913      particular type.  This is opposed to the "static typing" of C,
914      where variables can hold exactly one type of object and must be
915      declared as such, and objects do not contain an indication of
916      their type because it's implicit in the variables they are stored
917      in.  It is possible in C to have a variable hold different types
918      of objects (e.g. through the use of `void *' pointers or
919      variable-argument functions), but the type information must then be
920      passed explicitly in some other fashion, leading to additional
921      program complexity.
922
923   5. Allocated memory is automatically reclaimed when it is no longer
924      in use.  This operation is called "garbage collection" and
925      involves looking through all variables to see what memory is being
926      pointed to, and reclaiming any memory that is not pointed to and
927      is thus "inaccessible" and out of use.  This is as opposed to C,
928      in which allocated memory must be explicitly reclaimed using
929      `free()'.  If you simply drop all pointers to memory without
930      freeing it, it becomes "leaked" memory that still takes up space.
931      Over a long period of time, this can cause your program to grow
932      and grow until it runs out of memory.
933
934   6. Lisp has built-in facilities for handling errors and exceptions.
935      In C, when an error occurs, usually either the program exits
936      entirely or the routine in which the error occurs returns a value
937      indicating this.  If an error occurs in a deeply-nested routine,
938      then every routine currently called must unwind itself normally
939      and return an error value back up to the next routine.  This means
940      that every routine must explicitly check for an error in all the
941      routines it calls; if it does not do so, unexpected and often
942      random behavior results.  This is an extremely common source of
943      bugs in C programs.  An alternative would be to do a non-local
944      exit using `longjmp()', but that is often very dangerous because
945      the routines that were exited past had no opportunity to clean up
946      after themselves and may leave things in an inconsistent state,
947      causing a crash shortly afterwards.
948
949      Lisp provides mechanisms to make such non-local exits safe.  When
950      an error occurs, a routine simply signals that an error of a
951      particular class has occurred, and a non-local exit takes place.
952      Any routine can trap errors occurring in routines it calls by
953      registering an error handler for some or all classes of errors.
954      (If no handler is registered, a default handler, generally
955      installed by the top-level event loop, is executed; this prints
956      out the error and continues.) Routines can also specify cleanup
957      code (called an "unwind-protect") that will be called when control
958      exits from a block of code, no matter how that exit occurs--i.e.
959      even if a function deeply nested below it causes a non-local exit
960      back to the top level.
961
962      Note that this facility has appeared in some recent vintages of C,
963      in particular Visual C++ and other PC compilers written for the
964      Microsoft Win32 API.
965
966   7. In Emacs Lisp, local variables are "dynamically scoped".  This
967      means that if you declare a local variable in a particular
968      function, and then call another function, that subfunction can
969      "see" the local variable you declared.  This is actually
970      considered a bug in Emacs Lisp and in all other early dialects of
971      Lisp, and was corrected in Common Lisp. (In Common Lisp, you can
972      still declare dynamically scoped variables if you want to--they
973      are sometimes useful--but variables by default are "lexically
974      scoped" as in C.)
975
976    For those familiar with Lisp, Emacs Lisp is modelled after MacLisp,
977 an early dialect of Lisp developed at MIT (no relation to the Macintosh
978 computer).  There is a Common Lisp compatibility package available for
979 Emacs that provides many of the features of Common Lisp.
980
981    The Java language is derived in many ways from C, and shares a
982 similar syntax, but has the following features in common with Lisp (and
983 different from C):
984
985   1. Java is a safe language, like Lisp.
986
987   2. Java provides garbage collection, like Lisp.
988
989   3. Java has built-in facilities for handling errors and exceptions,
990      like Lisp.
991
992   4. Java has a type system that combines the best advantages of both
993      static and dynamic typing.  Objects (except very simple types) are
994      explicitly marked with their type, as in dynamic typing; but there
995      is a hierarchy of types and functions are declared to accept only
996      certain types, thus providing the increased compile-time
997      error-checking of static typing.
998
999    The Java language also has some negative attributes:
1000
1001   1. Java uses the edit/compile/run model of software development.  This
1002      makes it hard to use interactively.  For example, to use Java like
1003      `bc' it is necessary to write a special purpose, albeit tiny,
1004      application.  In Emacs Lisp, a calculator comes built-in without
1005      any effort - one can always just type an expression in the
1006      `*scratch*' buffer.
1007
1008   2. Java tries too hard to enforce, not merely enable, portability,
1009      making ordinary access to standard OS facilities painful.  Java
1010      has an "agenda".  I think this is why `chdir' is not part of
1011      standard Java, which is inexcusable.
1012
1013    Unfortunately, there is no perfect language.  Static typing allows a
1014 compiler to catch programmer errors and produce more efficient code, but
1015 makes programming more tedious and less fun.  For the foreseeable
1016 future, an Ideal Editing and Programming Environment (and that is what
1017 XEmacs aspires to) will be programmable in multiple languages: high
1018 level ones like Lisp for user customization and prototyping, and lower
1019 level ones for infrastructure and industrial strength applications.  If
1020 I had my way, XEmacs would be friendly towards the Python, Scheme, C++,
1021 ML, etc... communities.  But there are serious technical difficulties to
1022 achieving that goal.
1023
1024    The word "application" in the previous paragraph was used
1025 intentionally.  XEmacs implements an API for programs written in Lisp
1026 that makes it a full-fledged application platform, very much like an OS
1027 inside the real OS.
1028
1029 \1f
1030 File: internals.info,  Node: XEmacs From the Perspective of Building,  Next: XEmacs From the Inside,  Prev: The Lisp Language,  Up: Top
1031
1032 4 XEmacs From the Perspective of Building
1033 *****************************************
1034
1035 The heart of XEmacs is the Lisp environment, which is written in C.
1036 This is contained in the `src/' subdirectory.  Underneath `src/' are
1037 two subdirectories of header files: `s/' (header files for particular
1038 operating systems) and `m/' (header files for particular machine
1039 types).  In practice the distinction between the two types of header
1040 files is blurred.  These header files define or undefine certain
1041 preprocessor constants and macros to indicate particular
1042 characteristics of the associated machine or operating system.  As part
1043 of the configure process, one `s/' file and one `m/' file is identified
1044 for the particular environment in which XEmacs is being built.
1045
1046    XEmacs also contains a great deal of Lisp code.  This implements the
1047 operations that make XEmacs useful as an editor as well as just a Lisp
1048 environment, and also contains many add-on packages that allow XEmacs to
1049 browse directories, act as a mail and Usenet news reader, compile Lisp
1050 code, etc.  There is actually more Lisp code than C code associated with
1051 XEmacs, but much of the Lisp code is peripheral to the actual operation
1052 of the editor.  The Lisp code all lies in subdirectories underneath the
1053 `lisp/' directory.
1054
1055    The `lwlib/' directory contains C code that implements a generalized
1056 interface onto different X widget toolkits and also implements some
1057 widgets of its own that behave like Motif widgets but are faster, free,
1058 and in some cases more powerful.  The code in this directory compiles
1059 into a library and is mostly independent from XEmacs.
1060
1061    The `etc/' directory contains various data files associated with
1062 XEmacs.  Some of them are actually read by XEmacs at startup; others
1063 merely contain useful information of various sorts.
1064
1065    The `lib-src/' directory contains C code for various auxiliary
1066 programs that are used in connection with XEmacs.  Some of them are used
1067 during the build process; others are used to perform certain functions
1068 that cannot conveniently be placed in the XEmacs executable (e.g. the
1069 `movemail' program for fetching mail out of `/var/spool/mail', which
1070 must be setgid to `mail' on many systems; and the `gnuclient' program,
1071 which allows an external script to communicate with a running XEmacs
1072 process).
1073
1074    The `man/' directory contains the sources for the XEmacs
1075 documentation.  It is mostly in a form called Texinfo, which can be
1076 converted into either a printed document (by passing it through TeX) or
1077 into on-line documentation called "info files".
1078
1079    The `info/' directory contains the results of formatting the XEmacs
1080 documentation as "info files", for on-line use.  These files are used
1081 when you enter the Info system using `C-h i' or through the Help menu.
1082
1083    The `dynodump/' directory contains auxiliary code used to build
1084 XEmacs on Solaris platforms.
1085
1086    The other directories contain various miscellaneous code and
1087 information that is not normally used or needed.
1088
1089    The first step of building involves running the `configure' program
1090 and passing it various parameters to specify any optional features you
1091 want and compiler arguments and such, as described in the `INSTALL'
1092 file.  This determines what the build environment is, chooses the
1093 appropriate `s/' and `m/' file, and runs a series of tests to determine
1094 many details about your environment, such as which library functions
1095 are available and exactly how they work.  The reason for running these
1096 tests is that it allows XEmacs to be compiled on a much wider variety
1097 of platforms than those that the XEmacs developers happen to be
1098 familiar with, including various sorts of hybrid platforms.  This is
1099 especially important now that many operating systems give you a great
1100 deal of control over exactly what features you want installed, and allow
1101 for easy upgrading of parts of a system without upgrading the rest.  It
1102 would be impossible to pre-determine and pre-specify the information for
1103 all possible configurations.
1104
1105    In fact, the `s/' and `m/' files are basically _evil_, since they
1106 contain unmaintainable platform-specific hard-coded information.
1107 XEmacs has been moving in the direction of having all system-specific
1108 information be determined dynamically by `configure'.  Perhaps someday
1109 we can `rm -rf src/s src/m'.
1110
1111    When configure is done running, it generates `Makefile's and
1112 `GNUmakefile's and the file `src/config.h' (which describes the
1113 features of your system) from template files.  You then run `make',
1114 which compiles the auxiliary code and programs in `lib-src/' and
1115 `lwlib/' and the main XEmacs executable in `src/'.  The result of
1116 compiling and linking is an executable called `temacs', which is _not_
1117 the final XEmacs executable.  `temacs' by itself is not intended to
1118 function as an editor or even display any windows on the screen, and if
1119 you simply run it, it will exit immediately.  The `Makefile' runs
1120 `temacs' with certain options that cause it to initialize itself, read
1121 in a number of basic Lisp files, and then dump itself out into a new
1122 executable called `xemacs'.  This new executable has been
1123 pre-initialized and contains pre-digested Lisp code that is necessary
1124 for the editor to function (this includes most basic editing functions,
1125 e.g. `kill-line', that can be defined in terms of other Lisp
1126 primitives; some initialization code that is called when certain
1127 objects, such as frames, are created; and all of the standard
1128 keybindings and code for the actions they result in).  This executable,
1129 `xemacs', is the executable that you run to use the XEmacs editor.
1130
1131    Although `temacs' is not intended to be run as an editor, it can, by
1132 using the incantation `temacs -batch -l loadup.el run-temacs'.  This is
1133 useful when the dumping procedure described above is broken, or when
1134 using certain program debugging tools such as Purify.  These tools get
1135 mighty confused by the tricks played by the XEmacs build process, such
1136 as allocation memory in one process, and freeing it in the next.
1137
1138 \1f
1139 File: internals.info,  Node: XEmacs From the Inside,  Next: The XEmacs Object System (Abstractly Speaking),  Prev: XEmacs From the Perspective of Building,  Up: Top
1140
1141 5 XEmacs From the Inside
1142 ************************
1143
1144 Internally, XEmacs is quite complex, and can be very confusing.  To
1145 simplify things, it can be useful to think of XEmacs as containing an
1146 event loop that "drives" everything, and a number of other subsystems,
1147 such as a Lisp engine and a redisplay mechanism.  Each of these other
1148 subsystems exists simultaneously in XEmacs, and each has a certain
1149 state.  The flow of control continually passes in and out of these
1150 different subsystems in the course of normal operation of the editor.
1151
1152    It is important to keep in mind that, most of the time, the editor is
1153 "driven" by the event loop.  Except during initialization and batch
1154 mode, all subsystems are entered directly or indirectly through the
1155 event loop, and ultimately, control exits out of all subsystems back up
1156 to the event loop.  This cycle of entering a subsystem, exiting back out
1157 to the event loop, and starting another iteration of the event loop
1158 occurs once each keystroke, mouse motion, etc.
1159
1160    If you're trying to understand a particular subsystem (other than the
1161 event loop), think of it as a "daemon" process or "servant" that is
1162 responsible for one particular aspect of a larger system, and
1163 periodically receives commands or environment changes that cause it to
1164 do something.  Ultimately, these commands and environment changes are
1165 always triggered by the event loop.  For example:
1166
1167    * The window and frame mechanism is responsible for keeping track of
1168      what windows and frames exist, what buffers are in them, etc.  It
1169      is periodically given commands (usually from the user) to make a
1170      change to the current window/frame state: i.e. create a new frame,
1171      delete a window, etc.
1172
1173    * The buffer mechanism is responsible for keeping track of what
1174      buffers exist and what text is in them.  It is periodically given
1175      commands (usually from the user) to insert or delete text, create
1176      a buffer, etc.  When it receives a text-change command, it
1177      notifies the redisplay mechanism.
1178
1179    * The redisplay mechanism is responsible for making sure that
1180      windows and frames are displayed correctly.  It is periodically
1181      told (by the event loop) to actually "do its job", i.e. snoop
1182      around and see what the current state of the environment (mostly
1183      of the currently-existing windows, frames, and buffers) is, and
1184      make sure that state matches what's actually displayed.  It keeps
1185      lots and lots of information around (such as what is actually
1186      being displayed currently, and what the environment was last time
1187      it checked) so that it can minimize the work it has to do.  It is
1188      also helped along in that whenever a relevant change to the
1189      environment occurs, the redisplay mechanism is told about this, so
1190      it has a pretty good idea of where it has to look to find possible
1191      changes and doesn't have to look everywhere.
1192
1193    * The Lisp engine is responsible for executing the Lisp code in
1194      which most user commands are written.  It is entered through a
1195      call to `eval' or `funcall', which occurs as a result of
1196      dispatching an event from the event loop.  The functions it calls
1197      issue commands to the buffer mechanism, the window/frame
1198      subsystem, etc.
1199
1200    * The Lisp allocation subsystem is responsible for keeping track of
1201      Lisp objects.  It is given commands from the Lisp engine to
1202      allocate objects, garbage collect, etc.
1203
1204    etc.
1205
1206    The important idea here is that there are a number of independent
1207 subsystems each with its own responsibility and persistent state, just
1208 like different employees in a company, and each subsystem is
1209 periodically given commands from other subsystems.  Commands can flow
1210 from any one subsystem to any other, but there is usually some sort of
1211 hierarchy, with all commands originating from the event subsystem.
1212
1213    XEmacs is entered in `main()', which is in `emacs.c'.  When this is
1214 called the first time (in a properly-invoked `temacs'), it does the
1215 following:
1216
1217   1. It does some very basic environment initializations, such as
1218      determining where it and its directories (e.g. `lisp/' and `etc/')
1219      reside and setting up signal handlers.
1220
1221   2. It initializes the entire Lisp interpreter.
1222
1223   3. It sets the initial values of many built-in variables (including
1224      many variables that are visible to Lisp programs), such as the
1225      global keymap object and the built-in faces (a face is an object
1226      that describes the display characteristics of text).  This
1227      involves creating Lisp objects and thus is dependent on step (2).
1228
1229   4. It performs various other initializations that are relevant to the
1230      particular environment it is running in, such as retrieving
1231      environment variables, determining the current date and the user
1232      who is running the program, examining its standard input, creating
1233      any necessary file descriptors, etc.
1234
1235   5. At this point, the C initialization is complete.  A Lisp program
1236      that was specified on the command line (usually `loadup.el') is
1237      called (temacs is normally invoked as `temacs -batch -l loadup.el
1238      dump').  `loadup.el' loads all of the other Lisp files that are
1239      needed for the operation of the editor, calls the `dump-emacs'
1240      function to write out `xemacs', and then kills the temacs process.
1241
1242    When `xemacs' is then run, it only redoes steps (1) and (4) above;
1243 all variables already contain the values they were set to when the
1244 executable was dumped, and all memory that was allocated with
1245 `malloc()' is still around. (XEmacs knows whether it is being run as
1246 `xemacs' or `temacs' because it sets the global variable `initialized'
1247 to 1 after step (4) above.) At this point, `xemacs' calls a Lisp
1248 function to do any further initialization, which includes parsing the
1249 command-line (the C code can only do limited command-line parsing,
1250 which includes looking for the `-batch' and `-l' flags and a few other
1251 flags that it needs to know about before initialization is complete),
1252 creating the first frame (or "window" in standard window-system
1253 parlance), running the user's init file (usually the file `.emacs' in
1254 the user's home directory), etc.  The function to do this is usually
1255 called `normal-top-level'; `loadup.el' tells the C code about this
1256 function by setting its name as the value of the Lisp variable
1257 `top-level'.
1258
1259    When the Lisp initialization code is done, the C code enters the
1260 event loop, and stays there for the duration of the XEmacs process.
1261 The code for the event loop is contained in `cmdloop.c', and is called
1262 `Fcommand_loop_1()'.  Note that this event loop could very well be
1263 written in Lisp, and in fact a Lisp version exists; but apparently,
1264 doing this makes XEmacs run noticeably slower.
1265
1266    Notice how much of the initialization is done in Lisp, not in C.  In
1267 general, XEmacs tries to move as much code as is possible into Lisp.
1268 Code that remains in C is code that implements the Lisp interpreter
1269 itself, or code that needs to be very fast, or code that needs to do
1270 system calls or other such stuff that needs to be done in C, or code
1271 that needs to have access to "forbidden" structures. (One conscious
1272 aspect of the design of Lisp under XEmacs is a clean separation between
1273 the external interface to a Lisp object's functionality and its internal
1274 implementation.  Part of this design is that Lisp programs are
1275 forbidden from accessing the contents of the object other than through
1276 using a standard API.  In this respect, XEmacs Lisp is similar to
1277 modern Lisp dialects but differs from GNU Emacs, which tends to expose
1278 the implementation and allow Lisp programs to look at it directly.  The
1279 major advantage of hiding the implementation is that it allows the
1280 implementation to be redesigned without affecting any Lisp programs,
1281 including those that might want to be "clever" by looking directly at
1282 the object's contents and possibly manipulating them.)
1283
1284    Moving code into Lisp makes the code easier to debug and maintain and
1285 makes it much easier for people who are not XEmacs developers to
1286 customize XEmacs, because they can make a change with much less chance
1287 of obscure and unwanted interactions occurring than if they were to
1288 change the C code.
1289
1290 \1f
1291 File: internals.info,  Node: The XEmacs Object System (Abstractly Speaking),  Next: How Lisp Objects Are Represented in C,  Prev: XEmacs From the Inside,  Up: Top
1292
1293 6 The XEmacs Object System (Abstractly Speaking)
1294 ************************************************
1295
1296 At the heart of the Lisp interpreter is its management of objects.
1297 XEmacs Lisp contains many built-in objects, some of which are simple
1298 and others of which can be very complex; and some of which are very
1299 common, and others of which are rarely used or are only used
1300 internally. (Since the Lisp allocation system, with its automatic
1301 reclamation of unused storage, is so much more convenient than
1302 `malloc()' and `free()', the C code makes extensive use of it in its
1303 internal operations.)
1304
1305    The basic Lisp objects are
1306
1307 `integer'
1308      28 or 31 bits of precision, or 60 or 63 bits on 64-bit machines;
1309      the reason for this is described below when the internal Lisp
1310      object representation is described.
1311
1312 `float'
1313      Same precision as a double in C.
1314
1315 `cons'
1316      A simple container for two Lisp objects, used to implement lists
1317      and most other data structures in Lisp.
1318
1319 `char'
1320      An object representing a single character of text; chars behave
1321      like integers in many ways but are logically considered text
1322      rather than numbers and have a different read syntax. (the read
1323      syntax for a char contains the char itself or some textual
1324      encoding of it--for example, a Japanese Kanji character might be
1325      encoded as `^[$(B#&^[(B' using the ISO-2022 encoding
1326      standard--rather than the numerical representation of the char;
1327      this way, if the mapping between chars and integers changes, which
1328      is quite possible for Kanji characters and other extended
1329      characters, the same character will still be created.  Note that
1330      some primitives confuse chars and integers.  The worst culprit is
1331      `eq', which makes a special exception and considers a char to be
1332      `eq' to its integer equivalent, even though in no other case are
1333      objects of two different types `eq'.  The reason for this
1334      monstrosity is compatibility with existing code; the separation of
1335      char from integer came fairly recently.)
1336
1337 `symbol'
1338      An object that contains Lisp objects and is referred to by name;
1339      symbols are used to implement variables and named functions and to
1340      provide the equivalent of preprocessor constants in C.
1341
1342 `vector'
1343      A one-dimensional array of Lisp objects providing constant-time
1344      access to any of the objects; access to an arbitrary object in a
1345      vector is faster than for lists, but the operations that can be
1346      done on a vector are more limited.
1347
1348 `string'
1349      Self-explanatory; behaves much like a vector of chars but has a
1350      different read syntax and is stored and manipulated more compactly.
1351
1352 `bit-vector'
1353      A vector of bits; similar to a string in spirit.
1354
1355 `compiled-function'
1356      An object containing compiled Lisp code, known as "byte code".
1357
1358 `subr'
1359      A Lisp primitive, i.e. a Lisp-callable function implemented in C.
1360
1361    Note that there is no basic "function" type, as in more powerful
1362 versions of Lisp (where it's called a "closure").  XEmacs Lisp does not
1363 provide the closure semantics implemented by Common Lisp and Scheme.
1364 The guts of a function in XEmacs Lisp are represented in one of four
1365 ways: a symbol specifying another function (when one function is an
1366 alias for another), a list (whose first element must be the symbol
1367 `lambda') containing the function's source code, a compiled-function
1368 object, or a subr object. (In other words, given a symbol specifying
1369 the name of a function, calling `symbol-function' to retrieve the
1370 contents of the symbol's function cell will return one of these types
1371 of objects.)
1372
1373    XEmacs Lisp also contains numerous specialized objects used to
1374 implement the editor:
1375
1376 `buffer'
1377      Stores text like a string, but is optimized for insertion and
1378      deletion and has certain other properties that can be set.
1379
1380 `frame'
1381      An object with various properties whose displayable representation
1382      is a "window" in window-system parlance.
1383
1384 `window'
1385      A section of a frame that displays the contents of a buffer; often
1386      called a "pane" in window-system parlance.
1387
1388 `window-configuration'
1389      An object that represents a saved configuration of windows in a
1390      frame.
1391
1392 `device'
1393      An object representing a screen on which frames can be displayed;
1394      equivalent to a "display" in the X Window System and a "TTY" in
1395      character mode.
1396
1397 `face'
1398      An object specifying the appearance of text or graphics; it has
1399      properties such as font, foreground color, and background color.
1400
1401 `marker'
1402      An object that refers to a particular position in a buffer and
1403      moves around as text is inserted and deleted to stay in the same
1404      relative position to the text around it.
1405
1406 `extent'
1407      Similar to a marker but covers a range of text in a buffer; can
1408      also specify properties of the text, such as a face in which the
1409      text is to be displayed, whether the text is invisible or
1410      unmodifiable, etc.
1411
1412 `event'
1413      Generated by calling `next-event' and contains information
1414      describing a particular event happening in the system, such as the
1415      user pressing a key or a process terminating.
1416
1417 `keymap'
1418      An object that maps from events (described using lists, vectors,
1419      and symbols rather than with an event object because the mapping
1420      is for classes of events, rather than individual events) to
1421      functions to execute or other events to recursively look up; the
1422      functions are described by name, using a symbol, or using lists to
1423      specify the function's code.
1424
1425 `glyph'
1426      An object that describes the appearance of an image (e.g.  pixmap)
1427      on the screen; glyphs can be attached to the beginning or end of
1428      extents and in some future version of XEmacs will be able to be
1429      inserted directly into a buffer.
1430
1431 `process'
1432      An object that describes a connection to an externally-running
1433      process.
1434
1435    There are some other, less-commonly-encountered general objects:
1436
1437 `hash-table'
1438      An object that maps from an arbitrary Lisp object to another
1439      arbitrary Lisp object, using hashing for fast lookup.
1440
1441 `obarray'
1442      A limited form of hash-table that maps from strings to symbols;
1443      obarrays are used to look up a symbol given its name and are not
1444      actually their own object type but are kludgily represented using
1445      vectors with hidden fields (this representation derives from GNU
1446      Emacs).
1447
1448 `specifier'
1449      A complex object used to specify the value of a display property; a
1450      default value is given and different values can be specified for
1451      particular frames, buffers, windows, devices, or classes of device.
1452
1453 `char-table'
1454      An object that maps from chars or classes of chars to arbitrary
1455      Lisp objects; internally char tables use a complex nested-vector
1456      representation that is optimized to the way characters are
1457      represented as integers.
1458
1459 `range-table'
1460      An object that maps from ranges of integers to arbitrary Lisp
1461      objects.
1462
1463    And some strange special-purpose objects:
1464
1465 `charset'
1466 `coding-system'
1467      Objects used when MULE, or multi-lingual/Asian-language, support is
1468      enabled.
1469
1470 `color-instance'
1471 `font-instance'
1472 `image-instance'
1473      An object that encapsulates a window-system resource; instances are
1474      mostly used internally but are exposed on the Lisp level for
1475      cleanness of the specifier model and because it's occasionally
1476      useful for Lisp program to create or query the properties of
1477      instances.
1478
1479 `subwindow'
1480      An object that encapsulate a "subwindow" resource, i.e. a
1481      window-system child window that is drawn into by an external
1482      process; this object should be integrated into the glyph system
1483      but isn't yet, and may change form when this is done.
1484
1485 `tooltalk-message'
1486 `tooltalk-pattern'
1487      Objects that represent resources used in the ToolTalk interprocess
1488      communication protocol.
1489
1490 `toolbar-button'
1491      An object used in conjunction with the toolbar.
1492
1493    And objects that are only used internally:
1494
1495 `opaque'
1496      A generic object for encapsulating arbitrary memory; this allows
1497      you the generality of `malloc()' and the convenience of the Lisp
1498      object system.
1499
1500 `lstream'
1501      A buffering I/O stream, used to provide a unified interface to
1502      anything that can accept output or provide input, such as a file
1503      descriptor, a stdio stream, a chunk of memory, a Lisp buffer, a
1504      Lisp string, etc.; it's a Lisp object to make its memory
1505      management more convenient.
1506
1507 `char-table-entry'
1508      Subsidiary objects in the internal char-table representation.
1509
1510 `extent-auxiliary'
1511 `menubar-data'
1512 `toolbar-data'
1513      Various special-purpose objects that are basically just used to
1514      encapsulate memory for particular subsystems, similar to the more
1515      general "opaque" object.
1516
1517 `symbol-value-forward'
1518 `symbol-value-buffer-local'
1519 `symbol-value-varalias'
1520 `symbol-value-lisp-magic'
1521      Special internal-only objects that are placed in the value cell of
1522      a symbol to indicate that there is something special with this
1523      variable - e.g. it has no value, it mirrors another variable, or
1524      it mirrors some C variable; there is really only one kind of
1525      object, called a "symbol-value-magic", but it is sort-of halfway
1526      kludged into semi-different object types.
1527
1528    Some types of objects are "permanent", meaning that once created,
1529 they do not disappear until explicitly destroyed, using a function such
1530 as `delete-buffer', `delete-window', `delete-frame', etc.  Others will
1531 disappear once they are not longer used, through the garbage collection
1532 mechanism.  Buffers, frames, windows, devices, and processes are among
1533 the objects that are permanent.  Note that some objects can go both
1534 ways: Faces can be created either way; extents are normally permanent,
1535 but detached extents (extents not referring to any text, as happens to
1536 some extents when the text they are referring to is deleted) are
1537 temporary.  Note that some permanent objects, such as faces and coding
1538 systems, cannot be deleted.  Note also that windows are unique in that
1539 they can be _undeleted_ after having previously been deleted. (This
1540 happens as a result of restoring a window configuration.)
1541
1542    Note that many types of objects have a "read syntax", i.e. a way of
1543 specifying an object of that type in Lisp code.  When you load a Lisp
1544 file, or type in code to be evaluated, what really happens is that the
1545 function `read' is called, which reads some text and creates an object
1546 based on the syntax of that text; then `eval' is called, which possibly
1547 does something special; then this loop repeats until there's no more
1548 text to read. (`eval' only actually does something special with
1549 symbols, which causes the symbol's value to be returned, similar to
1550 referencing a variable; and with conses [i.e. lists], which cause a
1551 function invocation.  All other values are returned unchanged.)
1552
1553    The read syntax
1554
1555      17297
1556
1557    converts to an integer whose value is 17297.
1558
1559      1.983e-4
1560
1561    converts to a float whose value is 1.983e-4, or .0001983.
1562
1563      ?b
1564
1565    converts to a char that represents the lowercase letter b.
1566
1567      ?^[$(B#&^[(B
1568
1569    (where `^[' actually is an `ESC' character) converts to a particular
1570 Kanji character when using an ISO2022-based coding system for input.
1571 (To decode this goo: `ESC' begins an escape sequence; `ESC $ (' is a
1572 class of escape sequences meaning "switch to a 94x94 character set";
1573 `ESC $ ( B' means "switch to Japanese Kanji"; `#' and `&' collectively
1574 index into a 94-by-94 array of characters [subtract 33 from the ASCII
1575 value of each character to get the corresponding index]; `ESC (' is a
1576 class of escape sequences meaning "switch to a 94 character set"; `ESC
1577 (B' means "switch to US ASCII".  It is a coincidence that the letter
1578 `B' is used to denote both Japanese Kanji and US ASCII.  If the first
1579 `B' were replaced with an `A', you'd be requesting a Chinese Hanzi
1580 character from the GB2312 character set.)
1581
1582      "foobar"
1583
1584    converts to a string.
1585
1586      foobar
1587
1588    converts to a symbol whose name is `"foobar"'.  This is done by
1589 looking up the string equivalent in the global variable `obarray',
1590 whose contents should be an obarray.  If no symbol is found, a new
1591 symbol with the name `"foobar"' is automatically created and added to
1592 `obarray'; this process is called "interning" the symbol.  
1593
1594      (foo . bar)
1595
1596    converts to a cons cell containing the symbols `foo' and `bar'.
1597
1598      (1 a 2.5)
1599
1600    converts to a three-element list containing the specified objects
1601 (note that a list is actually a set of nested conses; see the XEmacs
1602 Lisp Reference).
1603
1604      [1 a 2.5]
1605
1606    converts to a three-element vector containing the specified objects.
1607
1608      #[... ... ... ...]
1609
1610    converts to a compiled-function object (the actual contents are not
1611 shown since they are not relevant here; look at a file that ends with
1612 `.elc' for examples).
1613
1614      #*01110110
1615
1616    converts to a bit-vector.
1617
1618      #s(hash-table ... ...)
1619
1620    converts to a hash table (the actual contents are not shown).
1621
1622      #s(range-table ... ...)
1623
1624    converts to a range table (the actual contents are not shown).
1625
1626      #s(char-table ... ...)
1627
1628    converts to a char table (the actual contents are not shown).
1629
1630    Note that the `#s()' syntax is the general syntax for structures,
1631 which are not really implemented in XEmacs Lisp but should be.
1632
1633    When an object is printed out (using `print' or a related function),
1634 the read syntax is used, so that the same object can be read in again.
1635
1636    The other objects do not have read syntaxes, usually because it does
1637 not really make sense to create them in this fashion (i.e.  processes,
1638 where it doesn't make sense to have a subprocess created as a side
1639 effect of reading some Lisp code), or because they can't be created at
1640 all (e.g. subrs).  Permanent objects, as a rule, do not have a read
1641 syntax; nor do most complex objects, which contain too much state to be
1642 easily initialized through a read syntax.
1643
1644 \1f
1645 File: internals.info,  Node: How Lisp Objects Are Represented in C,  Next: Rules When Writing New C Code,  Prev: The XEmacs Object System (Abstractly Speaking),  Up: Top
1646
1647 7 How Lisp Objects Are Represented in C
1648 ***************************************
1649
1650 Lisp objects are represented in C using a 32-bit or 64-bit machine word
1651 (depending on the processor; i.e. DEC Alphas use 64-bit Lisp objects and
1652 most other processors use 32-bit Lisp objects).  The representation
1653 stuffs a pointer together with a tag, as follows:
1654
1655       [ 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 ]
1656       [ 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 ]
1657
1658         <---------------------------------------------------------> <->
1659                  a pointer to a structure, or an integer            tag
1660
1661    A tag of 00 is used for all pointer object types, a tag of 10 is used
1662 for characters, and the other two tags 01 and 11 are joined together to
1663 form the integer object type.  This representation gives us 31 bit
1664 integers and 30 bit characters, while pointers are represented directly
1665 without any bit masking or shifting.  This representation, though,
1666 assumes that pointers to structs are always aligned to multiples of 4,
1667 so the lower 2 bits are always zero.
1668
1669    Lisp objects use the typedef `Lisp_Object', but the actual C type
1670 used for the Lisp object can vary.  It can be either a simple type
1671 (`long' on the DEC Alpha, `int' on other machines) or a structure whose
1672 fields are bit fields that line up properly (actually, a union of
1673 structures is used).  The choice of which type to use is determined by
1674 the preprocessor constant `USE_UNION_TYPE' which is defined via the
1675 `--use-union-type' option to `configure'.
1676
1677    Generally the simple integral type is preferable because it ensures
1678 that the compiler will actually use a machine word to represent the
1679 object (some compilers will use more general and less efficient code
1680 for unions and structs even if they can fit in a machine word).  The
1681 union type, however, has the advantage of stricter _static_ type
1682 checking.  Places where a `Lisp_Object' is mistakenly passed to a
1683 routine expecting an `int' (or vice-versa), or a check is written `if
1684 (foo)' (instead of `if (!NILP (foo))', will be flagged as errors.  None
1685 of these lead to the expected results!  `Qnil' is not represented as 0
1686 (so `if (foo)' will *ALWAYS* be true for a `Lisp_Object'), and the
1687 representation of an integer as a `Lisp_Object' is not just the
1688 integer's numeric value, but usually 2x the integer +/- 1.)
1689
1690    There used to be a claim that the union type simplified debugging.
1691 There may have been a grain of truth to this pre-19.8, when there was no
1692 `lrecord' type and all objects had a separate type appearing in the
1693 tag.  Nowadays, however, there is no debugging gain, and in fact
1694 frequent debugging *_loss_*, since many debuggers don't handle unions
1695 very well, and usually there is no way to directly specify a union from
1696 a debugging prompt.
1697
1698    Furthermore, release builds should *_not_* be done with union type
1699 because (a) you may get less efficiency, with compilers that can't
1700 figure out how to optimize the union into a machine word; (b) even
1701 worse, the union type often triggers miscompilation, especially when
1702 combined with Mule and error-checking.  This has been the case at
1703 various times when using GCC and MS VC, at least with `--pdump'.
1704 Therefore, be warned!
1705
1706    As of 2002 4Q, miscompilation is known to happen with current
1707 versions of *Microsoft VC++* and *GCC in combination with Mule, pdump,
1708 and KKCC* (no error checking).
1709
1710    Various macros are used to convert between Lisp_Objects and the
1711 corresponding C type.  Macros of the form `XINT()', `XCHAR()',
1712 `XSTRING()', `XSYMBOL()', do any required bit shifting and/or masking
1713 and cast it to the appropriate type.  `XINT()' needs to be a bit tricky
1714 so that negative numbers are properly sign-extended.  Since integers
1715 are stored left-shifted, if the right-shift operator does an arithmetic
1716 shift (i.e. it leaves the most-significant bit as-is rather than
1717 shifting in a zero, so that it mimics a divide-by-two even for negative
1718 numbers) the shift to remove the tag bit is enough.  This is the case
1719 on all the systems we support.
1720
1721    Note that when `ERROR_CHECK_TYPECHECK' is defined, the converter
1722 macros become more complicated--they check the tag bits and/or the type
1723 field in the first four bytes of a record type to ensure that the
1724 object is really of the correct type.  This is great for catching places
1725 where an incorrect type is being dereferenced--this typically results
1726 in a pointer being dereferenced as the wrong type of structure, with
1727 unpredictable (and sometimes not easily traceable) results.
1728
1729    There are similar `XSETTYPE()' macros that construct a Lisp object.
1730 These macros are of the form `XSETTYPE (LVALUE, RESULT)', i.e. they
1731 have to be a statement rather than just used in an expression.  The
1732 reason for this is that standard C doesn't let you "construct" a
1733 structure (but GCC does).  Granted, this sometimes isn't too
1734 convenient; for the case of integers, at least, you can use the
1735 function `make_int()', which constructs and _returns_ an integer Lisp
1736 object.  Note that the `XSETTYPE()' macros are also affected by
1737 `ERROR_CHECK_TYPECHECK' and make sure that the structure is of the
1738 right type in the case of record types, where the type is contained in
1739 the structure.
1740
1741    The C programmer is responsible for *guaranteeing* that a
1742 Lisp_Object is the correct type before using the `XTYPE' macros.  This
1743 is especially important in the case of lists.  Use `XCAR' and `XCDR' if
1744 a Lisp_Object is certainly a cons cell, else use `Fcar()' and `Fcdr()'.
1745 Trust other C code, but not Lisp code.  On the other hand, if XEmacs
1746 has an internal logic error, it's better to crash immediately, so
1747 sprinkle `assert()'s and "unreachable" `abort()'s liberally about the
1748 source code.  Where performance is an issue, use `type_checking_assert',
1749 `bufpos_checking_assert', and `gc_checking_assert', which do nothing
1750 unless the corresponding configure error checking flag was specified.
1751
1752 \1f
1753 File: internals.info,  Node: Rules When Writing New C Code,  Next: Regression Testing XEmacs,  Prev: How Lisp Objects Are Represented in C,  Up: Top
1754
1755 8 Rules When Writing New C Code
1756 *******************************
1757
1758 The XEmacs C Code is extremely complex and intricate, and there are many
1759 rules that are more or less consistently followed throughout the code.
1760 Many of these rules are not obvious, so they are explained here.  It is
1761 of the utmost importance that you follow them.  If you don't, you may
1762 get something that appears to work, but which will crash in odd
1763 situations, often in code far away from where the actual breakage is.
1764
1765 * Menu:
1766
1767 * A Reader's Guide to XEmacs Coding Conventions::
1768 * General Coding Rules::
1769 * Writing Lisp Primitives::
1770 * Writing Good Comments::
1771 * Adding Global Lisp Variables::
1772 * Proper Use of Unsigned Types::
1773 * Coding for Mule::
1774 * Techniques for XEmacs Developers::
1775
1776 \1f
1777 File: internals.info,  Node: A Reader's Guide to XEmacs Coding Conventions,  Next: General Coding Rules,  Up: Rules When Writing New C Code
1778
1779 8.1 A Reader's Guide to XEmacs Coding Conventions
1780 =================================================
1781
1782 Of course the low-level implementation language of XEmacs is C, but much
1783 of that uses the Lisp engine to do its work.  However, because the code
1784 is "inside" of the protective containment shell around the "reactor
1785 core," you'll see lots of complex "plumbing" needed to do the work and
1786 "safety mechanisms," whose failure results in a meltdown.  This section
1787 provides a quick overview (or review) of the various components of the
1788 implementation of Lisp objects.
1789
1790    Two typographic conventions help to identify C objects that implement
1791 Lisp objects.  The first is that capitalized identifiers, especially
1792 beginning with the letters `Q', `V', `F', and `S', for C variables and
1793 functions, and C macros with beginning with the letter `X', are used to
1794 implement Lisp.  The second is that where Lisp uses the hyphen `-' in
1795 symbol names, the corresponding C identifiers use the underscore `_'.
1796 Of course, since XEmacs Lisp contains interfaces to many external
1797 libraries, those external names will follow the coding conventions
1798 their authors chose, and may overlap the "XEmacs name space."  However
1799 these cases are usually pretty obvious.
1800
1801    All Lisp objects are handled indirectly.  The `Lisp_Object' type is
1802 usually a pointer to a structure, except for a very small number of
1803 types with immediate representations (currently characters and
1804 integers).  However, these types cannot be directly operated on in C
1805 code, either, so they can also be considered indirect.  Types that do
1806 not have an immediate representation always have a C typedef
1807 `Lisp_TYPE' for a corresponding structure.
1808
1809    In older code, it was common practice to pass around pointers to
1810 `Lisp_TYPE', but this is now deprecated in favor of using `Lisp_Object'
1811 for all function arguments and return values that are Lisp objects.
1812 The `XTYPE' macro is used to extract the pointer and cast it to
1813 `(Lisp_TYPE *)' for the desired type.
1814
1815    *Convention*: macros whose names begin with `X' operate on
1816 `Lisp_Object's and do no type-checking.  Many such macros are type
1817 extractors, but others implement Lisp operations in C (_e.g._, `XCAR'
1818 implements the Lisp `car' function).  These are unsafe, and must only
1819 be used where types of all data have already been checked.  Such macros
1820 are only applied to `Lisp_Object's.  In internal implementations where
1821 the pointer has already been converted, the structure is operated on
1822 directly using the C `->' member access operator.
1823
1824    The `TYPEP', `CHECK_TYPE', and `CONCHECK_TYPE' macros are used to
1825 test types.  The first returns a Boolean value, and the latter signal
1826 errors.  (The `CONCHECK' variety allows execution to be CONtinued under
1827 some circumstances, thus the name.)  Functions which expect to be
1828 passed user data invariably call `CHECK' macros on arguments.
1829
1830    There are many types of specialized Lisp objects implemented in C,
1831 but the most pervasive type is the "symbol".  Symbols are used as
1832 identifiers, variables, and functions.
1833
1834    *Convention*: Global variables whose names begin with `Q' are
1835 constants whose value is a symbol.  The name of the variable should be
1836 derived from the name of the symbol using the same rules as for Lisp
1837 primitives.  Such variables allow the C code to check whether a
1838 particular `Lisp_Object' is equal to a given symbol.  Symbols are Lisp
1839 objects, so these variables may be passed to Lisp primitives.  (An
1840 alternative to the use of `Q...' variables is to call the `intern'
1841 function at initialization in the `vars_of_MODULE' function, which is
1842 hardly less efficient.)
1843
1844    *Convention*: Global variables whose names begin with `V' are
1845 variables that contain Lisp objects.  The convention here is that all
1846 global variables of type `Lisp_Object' begin with `V', and no others do
1847 (not even integer and boolean variables that have Lisp equivalents).
1848 Most of the time, these variables have equivalents in Lisp, which are
1849 defined via the `DEFVAR' family of macros, but some don't.  Since the
1850 variable's value is a `Lisp_Object', it can be passed to Lisp
1851 primitives.
1852
1853    The implementation of Lisp primitives is more complex.
1854 *Convention*: Global variables with names beginning with `S' contain a
1855 structure that allows the Lisp engine to identify and call a C
1856 function.  In modern versions of XEmacs, these identifiers are almost
1857 always completely hidden in the `DEFUN' and `SUBR' macros, but you will
1858 encounter them if you look at very old versions of XEmacs or at GNU
1859 Emacs.  *Convention*: Functions with names beginning with `F' implement
1860 Lisp primitives.  Of course all their arguments and their return values
1861 must be Lisp_Objects.  (This is hidden in the `DEFUN' macro.)
1862
1863 \1f
1864 File: internals.info,  Node: General Coding Rules,  Next: Writing Lisp Primitives,  Prev: A Reader's Guide to XEmacs Coding Conventions,  Up: Rules When Writing New C Code
1865
1866 8.2 General Coding Rules
1867 ========================
1868
1869 The C code is actually written in a dialect of C called "Clean C",
1870 meaning that it can be compiled, mostly warning-free, with either a C or
1871 C++ compiler.  Coding in Clean C has several advantages over plain C.
1872 C++ compilers are more nit-picking, and a number of coding errors have
1873 been found by compiling with C++.  The ability to use both C and C++
1874 tools means that a greater variety of development tools are available to
1875 the developer.
1876
1877    Every module includes `<config.h>' (angle brackets so that
1878 `--srcdir' works correctly; `config.h' may or may not be in the same
1879 directory as the C sources) and `lisp.h'.  `config.h' must always be
1880 included before any other header files (including system header files)
1881 to ensure that certain tricks played by various `s/' and `m/' files
1882 work out correctly.
1883
1884    When including header files, always use angle brackets, not double
1885 quotes, except when the file to be included is always in the same
1886 directory as the including file.  If either file is a generated file,
1887 then that is not likely to be the case.  In order to understand why we
1888 have this rule, imagine what happens when you do a build in the source
1889 directory using `./configure' and another build in another directory
1890 using `../work/configure'.  There will be two different `config.h'
1891 files.  Which one will be used if you `#include "config.h"'?
1892
1893    Almost every module contains a `syms_of_*()' function and a
1894 `vars_of_*()' function.  The former declares any Lisp primitives you
1895 have defined and defines any symbols you will be using.  The latter
1896 declares any global Lisp variables you have added and initializes global
1897 C variables in the module.  *Important*: There are stringent
1898 requirements on exactly what can go into these functions.  See the
1899 comment in `emacs.c'.  The reason for this is to avoid obscure unwanted
1900 interactions during initialization.  If you don't follow these rules,
1901 you'll be sorry!  If you want to do anything that isn't allowed, create
1902 a `complex_vars_of_*()' function for it.  Doing this is tricky, though:
1903 you have to make sure your function is called at the right time so that
1904 all the initialization dependencies work out.
1905
1906    Declare each function of these kinds in `symsinit.h'.  Make sure
1907 it's called in the appropriate place in `emacs.c'.  You never need to
1908 include `symsinit.h' directly, because it is included by `lisp.h'.
1909
1910    *All global and static variables that are to be modifiable must be
1911 declared uninitialized.*  This means that you may not use the "declare
1912 with initializer" form for these variables, such as `int some_variable
1913 = 0;'.  The reason for this has to do with some kludges done during the
1914 dumping process: If possible, the initialized data segment is re-mapped
1915 so that it becomes part of the (unmodifiable) code segment in the
1916 dumped executable.  This allows this memory to be shared among multiple
1917 running XEmacs processes.  XEmacs is careful to place as much constant
1918 data as possible into initialized variables during the `temacs' phase.
1919
1920    *Please note:* This kludge only works on a few systems nowadays, and
1921 is rapidly becoming irrelevant because most modern operating systems
1922 provide "copy-on-write" semantics.  All data is initially shared
1923 between processes, and a private copy is automatically made (on a
1924 page-by-page basis) when a process first attempts to write to a page of
1925 memory.
1926
1927    Formerly, there was a requirement that static variables not be
1928 declared inside of functions.  This had to do with another hack along
1929 the same vein as what was just described: old USG systems put
1930 statically-declared variables in the initialized data space, so those
1931 header files had a `#define static' declaration. (That way, the
1932 data-segment remapping described above could still work.) This fails
1933 badly on static variables inside of functions, which suddenly become
1934 automatic variables; therefore, you weren't supposed to have any of
1935 them.  This awful kludge has been removed in XEmacs because
1936
1937   1. almost all of the systems that used this kludge ended up having to
1938      disable the data-segment remapping anyway;
1939
1940   2. the only systems that didn't were extremely outdated ones;
1941
1942   3. this hack completely messed up inline functions.
1943
1944    The C source code makes heavy use of C preprocessor macros.  One
1945 popular macro style is:
1946
1947      #define FOO(var, value) do {            \
1948        Lisp_Object FOO_value = (value);      \
1949        ... /* compute using FOO_value */     \
1950        (var) = bar;                          \
1951      } while (0)
1952
1953    The `do {...} while (0)' is a standard trick to allow FOO to have
1954 statement semantics, so that it can safely be used within an `if'
1955 statement in C, for example.  Multiple evaluation is prevented by
1956 copying a supplied argument into a local variable, so that
1957 `FOO(var,fun(1))' only calls `fun' once.
1958
1959    Lisp lists are popular data structures in the C code as well as in
1960 Elisp.  There are two sets of macros that iterate over lists.
1961 `EXTERNAL_LIST_LOOP_N' should be used when the list has been supplied
1962 by the user, and cannot be trusted to be acyclic and `nil'-terminated.
1963 A `malformed-list' or `circular-list' error will be generated if the
1964 list being iterated over is not entirely kosher.  `LIST_LOOP_N', on the
1965 other hand, is faster and less safe, and can be used only on trusted
1966 lists.
1967
1968    Related macros are `GET_EXTERNAL_LIST_LENGTH' and `GET_LIST_LENGTH',
1969 which calculate the length of a list, and in the case of
1970 `GET_EXTERNAL_LIST_LENGTH', validating the properness of the list.  The
1971 macros `EXTERNAL_LIST_LOOP_DELETE_IF' and `LIST_LOOP_DELETE_IF' delete
1972 elements from a lisp list satisfying some predicate.
1973
1974 \1f
1975 File: internals.info,  Node: Writing Lisp Primitives,  Next: Writing Good Comments,  Prev: General Coding Rules,  Up: Rules When Writing New C Code
1976
1977 8.3 Writing Lisp Primitives
1978 ===========================
1979
1980 Lisp primitives are Lisp functions implemented in C.  The details of
1981 interfacing the C function so that Lisp can call it are handled by a few
1982 C macros.  The only way to really understand how to write new C code is
1983 to read the source, but we can explain some things here.
1984
1985    An example of a special form is the definition of `prog1', from
1986 `eval.c'.  (An ordinary function would have the same general
1987 appearance.)
1988
1989      DEFUN ("prog1", Fprog1, 1, UNEVALLED, 0, /*
1990      Similar to `progn', but the value of the first form is returned.
1991      \(prog1 FIRST BODY...): All the arguments are evaluated sequentially.
1992      The value of FIRST is saved during evaluation of the remaining args,
1993      whose values are discarded.
1994      */
1995             (args))
1996      {
1997        /* This function can GC */
1998        REGISTER Lisp_Object val, form, tail;
1999        struct gcpro gcpro1;
2000
2001        val = Feval (XCAR (args));
2002
2003        GCPRO1 (val);
2004
2005        LIST_LOOP_3 (form, XCDR (args), tail)
2006          Feval (form);
2007
2008        UNGCPRO;
2009        return val;
2010      }
2011
2012    Let's start with a precise explanation of the arguments to the
2013 `DEFUN' macro.  Here is a template for them:
2014
2015      DEFUN (LNAME, FNAME, MIN_ARGS, MAX_ARGS, INTERACTIVE, /*
2016      DOCSTRING
2017      */
2018         (ARGLIST))
2019
2020 LNAME
2021      This string is the name of the Lisp symbol to define as the
2022      function name; in the example above, it is `"prog1"'.
2023
2024 FNAME
2025      This is the C function name for this function.  This is the name
2026      that is used in C code for calling the function.  The name is, by
2027      convention, `F' prepended to the Lisp name, with all dashes (`-')
2028      in the Lisp name changed to underscores.  Thus, to call this
2029      function from C code, call `Fprog1'.  Remember that the arguments
2030      are of type `Lisp_Object'; various macros and functions for
2031      creating values of type `Lisp_Object' are declared in the file
2032      `lisp.h'.
2033
2034      Primitives whose names are special characters (e.g. `+' or `<')
2035      are named by spelling out, in some fashion, the special character:
2036      e.g. `Fplus()' or `Flss()'.  Primitives whose names begin with
2037      normal alphanumeric characters but also contain special characters
2038      are spelled out in some creative way, e.g. `let*' becomes
2039      `FletX()'.
2040
2041      Each function also has an associated structure that holds the data
2042      for the subr object that represents the function in Lisp.  This
2043      structure conveys the Lisp symbol name to the initialization
2044      routine that will create the symbol and store the subr object as
2045      its definition.  The C variable name of this structure is always
2046      `S' prepended to the FNAME.  You hardly ever need to be aware of
2047      the existence of this structure, since `DEFUN' plus `DEFSUBR'
2048      takes care of all the details.
2049
2050 MIN_ARGS
2051      This is the minimum number of arguments that the function
2052      requires.  The function `prog1' allows a minimum of one argument.
2053
2054 MAX_ARGS
2055      This is the maximum number of arguments that the function accepts,
2056      if there is a fixed maximum.  Alternatively, it can be `UNEVALLED',
2057      indicating a special form that receives unevaluated arguments, or
2058      `MANY', indicating an unlimited number of evaluated arguments (the
2059      C equivalent of `&rest').  Both `UNEVALLED' and `MANY' are macros.
2060      If MAX_ARGS is a number, it may not be less than MIN_ARGS and it
2061      may not be greater than 8. (If you need to add a function with
2062      more than 8 arguments, use the `MANY' form.  Resist the urge to
2063      edit the definition of `DEFUN' in `lisp.h'.  If you do it anyways,
2064      make sure to also add another clause to the switch statement in
2065      `primitive_funcall().')
2066
2067 INTERACTIVE
2068      This is an interactive specification, a string such as might be
2069      used as the argument of `interactive' in a Lisp function.  In the
2070      case of `prog1', it is 0 (a null pointer), indicating that `prog1'
2071      cannot be called interactively.  A value of `""' indicates a
2072      function that should receive no arguments when called
2073      interactively.
2074
2075 DOCSTRING
2076      This is the documentation string.  It is written just like a
2077      documentation string for a function defined in Lisp; in
2078      particular, the first line should be a single sentence.  Note how
2079      the documentation string is enclosed in a comment, none of the
2080      documentation is placed on the same lines as the comment-start and
2081      comment-end characters, and the comment-start characters are on
2082      the same line as the interactive specification.  `make-docfile',
2083      which scans the C files for documentation strings, is very
2084      particular about what it looks for, and will not properly extract
2085      the doc string if it's not in this exact format.
2086
2087      In order to make both `etags' and `make-docfile' happy, make sure
2088      that the `DEFUN' line contains the LNAME and FNAME, and that the
2089      comment-start characters for the doc string are on the same line
2090      as the interactive specification, and put a newline directly after
2091      them (and before the comment-end characters).
2092
2093 ARGLIST
2094      This is the comma-separated list of arguments to the C function.
2095      For a function with a fixed maximum number of arguments, provide a
2096      C argument for each Lisp argument.  In this case, unlike regular C
2097      functions, the types of the arguments are not declared; they are
2098      simply always of type `Lisp_Object'.
2099
2100      The names of the C arguments will be used as the names of the
2101      arguments to the Lisp primitive as displayed in its documentation,
2102      modulo the same concerns described above for `F...' names (in
2103      particular, underscores in the C arguments become dashes in the
2104      Lisp arguments).
2105
2106      There is one additional kludge: A trailing `_' on the C argument is
2107      discarded when forming the Lisp argument.  This allows C language
2108      reserved words (like `default') or global symbols (like `dirname')
2109      to be used as argument names without compiler warnings or errors.
2110
2111      A Lisp function with MAX_ARGS = `UNEVALLED' is a "special form";
2112      its arguments are not evaluated.  Instead it receives one argument
2113      of type `Lisp_Object', a (Lisp) list of the unevaluated arguments,
2114      conventionally named `(args)'.
2115
2116      When a Lisp function has no upper limit on the number of arguments,
2117      specify MAX_ARGS = `MANY'.  In this case its implementation in C
2118      actually receives exactly two arguments: the number of Lisp
2119      arguments (an `int') and the address of a block containing their
2120      values (a `Lisp_Object *').  In this case only are the C types
2121      specified in the ARGLIST: `(int nargs, Lisp_Object *args)'.
2122
2123
2124    Within the function `Fprog1' itself, note the use of the macros
2125 `GCPRO1' and `UNGCPRO'.  `GCPRO1' is used to "protect" a variable from
2126 garbage collection--to inform the garbage collector that it must look
2127 in that variable and regard the object pointed at by its contents as an
2128 accessible object.  This is necessary whenever you call `Feval' or
2129 anything that can directly or indirectly call `Feval' (this includes
2130 the `QUIT' macro!).  At such a time, any Lisp object that you intend to
2131 refer to again must be protected somehow.  `UNGCPRO' cancels the
2132 protection of the variables that are protected in the current function.
2133 It is necessary to do this explicitly.
2134
2135    The macro `GCPRO1' protects just one local variable.  If you want to
2136 protect two, use `GCPRO2' instead; repeating `GCPRO1' will not work.
2137 Macros `GCPRO3' and `GCPRO4' also exist.
2138
2139    These macros implicitly use local variables such as `gcpro1'; you
2140 must declare these explicitly, with type `struct gcpro'.  Thus, if you
2141 use `GCPRO2', you must declare `gcpro1' and `gcpro2'.
2142
2143    Note also that the general rule is "caller-protects"; i.e. you are
2144 only responsible for protecting those Lisp objects that you create.  Any
2145 objects passed to you as arguments should have been protected by whoever
2146 created them, so you don't in general have to protect them.
2147
2148    In particular, the arguments to any Lisp primitive are always
2149 automatically `GCPRO'ed, when called "normally" from Lisp code or
2150 bytecode.  So only a few Lisp primitives that are called frequently from
2151 C code, such as `Fprogn' protect their arguments as a service to their
2152 caller.  You don't need to protect your arguments when writing a new
2153 `DEFUN'.
2154
2155    `GCPRO'ing is perhaps the trickiest and most error-prone part of
2156 XEmacs coding.  It is *extremely* important that you get this right and
2157 use a great deal of discipline when writing this code.  *Note
2158 `GCPRO'ing: GCPROing, for full details on how to do this.
2159
2160    What `DEFUN' actually does is declare a global structure of type
2161 `Lisp_Subr' whose name begins with capital `SF' and which contains
2162 information about the primitive (e.g. a pointer to the function, its
2163 minimum and maximum allowed arguments, a string describing its Lisp
2164 name); `DEFUN' then begins a normal C function declaration using the
2165 `F...' name.  The Lisp subr object that is the function definition of a
2166 primitive (i.e. the object in the function slot of the symbol that
2167 names the primitive) actually points to this `SF' structure; when
2168 `Feval' encounters a subr, it looks in the structure to find out how to
2169 call the C function.
2170
2171    Defining the C function is not enough to make a Lisp primitive
2172 available; you must also create the Lisp symbol for the primitive (the
2173 symbol is "interned"; *note Obarrays::) and store a suitable subr
2174 object in its function cell. (If you don't do this, the primitive won't
2175 be seen by Lisp code.) The code looks like this:
2176
2177      DEFSUBR (FNAME);
2178
2179 Here FNAME is the same name you used as the second argument to `DEFUN'.
2180
2181    This call to `DEFSUBR' should go in the `syms_of_*()' function at
2182 the end of the module.  If no such function exists, create it and make
2183 sure to also declare it in `symsinit.h' and call it from the
2184 appropriate spot in `main()'.  *Note General Coding Rules::.
2185
2186    Note that C code cannot call functions by name unless they are
2187 defined in C.  The way to call a function written in Lisp from C is to
2188 use `Ffuncall', which embodies the Lisp function `funcall'.  Since the
2189 Lisp function `funcall' accepts an unlimited number of arguments, in C
2190 it takes two: the number of Lisp-level arguments, and a one-dimensional
2191 array containing their values.  The first Lisp-level argument is the
2192 Lisp function to call, and the rest are the arguments to pass to it.
2193 Since `Ffuncall' can call the evaluator, you must protect pointers from
2194 garbage collection around the call to `Ffuncall'. (However, `Ffuncall'
2195 explicitly protects all of its parameters, so you don't have to protect
2196 any pointers passed as parameters to it.)
2197
2198    The C functions `call0', `call1', `call2', and so on, provide handy
2199 ways to call a Lisp function conveniently with a fixed number of
2200 arguments.  They work by calling `Ffuncall'.
2201
2202    `eval.c' is a very good file to look through for examples; `lisp.h'
2203 contains the definitions for important macros and functions.
2204
2205 \1f
2206 File: internals.info,  Node: Writing Good Comments,  Next: Adding Global Lisp Variables,  Prev: Writing Lisp Primitives,  Up: Rules When Writing New C Code
2207
2208 8.4 Writing Good Comments
2209 =========================
2210
2211 Comments are a lifeline for programmers trying to understand tricky
2212 code.  In general, the less obvious it is what you are doing, the more
2213 you need a comment, and the more detailed it needs to be.  You should
2214 always be on guard when you're writing code for stuff that's tricky, and
2215 should constantly be putting yourself in someone else's shoes and asking
2216 if that person could figure out without much difficulty what's going
2217 on. (Assume they are a competent programmer who understands the
2218 essentials of how the XEmacs code is structured but doesn't know much
2219 about the module you're working on or any algorithms you're using.) If
2220 you're not sure whether they would be able to, add a comment.  Always
2221 err on the side of more comments, rather than less.
2222
2223    Generally, when making comments, there is no need to attribute them
2224 with your name or initials.  This especially goes for small,
2225 easy-to-understand, non-opinionated ones.  Also, comments indicating
2226 where, when, and by whom a file was changed are _strongly_ discouraged,
2227 and in general will be removed as they are discovered.  This is exactly
2228 what `ChangeLogs' are there for.  However, it can occasionally be
2229 useful to mark exactly where (but not when or by whom) changes are
2230 made, particularly when making small changes to a file imported from
2231 elsewhere.  These marks help when later on a newer version of the file
2232 is imported and the changes need to be merged. (If everything were
2233 always kept in CVS, there would be no need for this.  But in practice,
2234 this often doesn't happen, or the CVS repository is later on lost or
2235 unavailable to the person doing the update.)
2236
2237    When putting in an explicit opinion in a comment, you should
2238 _always_ attribute it with your name, and optionally the date.  This
2239 also goes for long, complex comments explaining in detail the workings
2240 of something - by putting your name there, you make it possible for
2241 someone who has questions about how that thing works to determine who
2242 wrote the comment so they can write to them.  Preferably, use your
2243 actual name and not your initials, unless your initials are generally
2244 recognized (e.g. `jwz').  You can use only your first name if it's
2245 obvious who you are; otherwise, give first and last name.  If you're
2246 not a regular contributor, you might consider putting your email
2247 address in - it may be in the ChangeLog, but after awhile ChangeLogs
2248 have a tendency of disappearing or getting muddled. (E.g. your comment
2249 may get copied somewhere else or even into another program, and
2250 tracking down the proper ChangeLog may be very difficult.)
2251
2252    If you come across an opinion that is not or no longer valid, or you
2253 come across any comment that no longer applies but you want to keep it
2254 around, enclose it in `[[ ' and ` ]]' marks and add a comment
2255 afterwards explaining why the preceding comment is no longer valid.  Put
2256 your name on this comment, as explained above.
2257
2258    Just as comments are a lifeline to programmers, incorrect comments
2259 are death.  If you come across an incorrect comment, *immediately*
2260 correct it or flag it as incorrect, as described in the previous
2261 paragraph.  Whenever you work on a section of code, _always_ make sure
2262 to update any comments to be correct - or, at the very least, flag them
2263 as incorrect.
2264
2265    To indicate a "todo" or other problem, use four pound signs - i.e.
2266 `####'.
2267
2268 \1f
2269 File: internals.info,  Node: Adding Global Lisp Variables,  Next: Proper Use of Unsigned Types,  Prev: Writing Good Comments,  Up: Rules When Writing New C Code
2270
2271 8.5 Adding Global Lisp Variables
2272 ================================
2273
2274 Global variables whose names begin with `Q' are constants whose value
2275 is a symbol of a particular name.  The name of the variable should be
2276 derived from the name of the symbol using the same rules as for Lisp
2277 primitives.  These variables are initialized using a call to
2278 `defsymbol()' in the `syms_of_*()' function. (This call interns a
2279 symbol, sets the C variable to the resulting Lisp object, and calls
2280 `staticpro()' on the C variable to tell the garbage-collection
2281 mechanism about this variable.  What `staticpro()' does is add a
2282 pointer to the variable to a large global array; when
2283 garbage-collection happens, all pointers listed in the array are used
2284 as starting points for marking Lisp objects.  This is important because
2285 it's quite possible that the only current reference to the object is
2286 the C variable.  In the case of symbols, the `staticpro()' doesn't
2287 matter all that much because the symbol is contained in `obarray',
2288 which is itself `staticpro()'ed.  However, it's possible that a naughty
2289 user could do something like uninterning the symbol out of `obarray' or
2290 even setting `obarray' to a different value [although this is likely to
2291 make XEmacs crash!].)
2292
2293    *Please note:* It is potentially deadly if you declare a `Q...'
2294 variable in two different modules.  The two calls to `defsymbol()' are
2295 no problem, but some linkers will complain about multiply-defined
2296 symbols.  The most insidious aspect of this is that often the link will
2297 succeed anyway, but then the resulting executable will sometimes crash
2298 in obscure ways during certain operations!
2299
2300    To avoid this problem, declare any symbols with common names (such as
2301 `text') that are not obviously associated with this particular module
2302 in the file `general-slots.h'.  The "-slots" suffix indicates that this
2303 is a file that is included multiple times in `general.c'.  Redefinition
2304 of preprocessor macros allows the effects to be different in each
2305 context, so this is actually more convenient and less error-prone than
2306 doing it in your module.
2307
2308    Global variables whose names begin with `V' are variables that
2309 contain Lisp objects.  The convention here is that all global variables
2310 of type `Lisp_Object' begin with `V', and all others don't (including
2311 integer and boolean variables that have Lisp equivalents). Most of the
2312 time, these variables have equivalents in Lisp, but some don't.  Those
2313 that do are declared this way by a call to `DEFVAR_LISP()' in the
2314 `vars_of_*()' initializer for the module.  What this does is create a
2315 special "symbol-value-forward" Lisp object that contains a pointer to
2316 the C variable, intern a symbol whose name is as specified in the call
2317 to `DEFVAR_LISP()', and set its value to the symbol-value-forward Lisp
2318 object; it also calls `staticpro()' on the C variable to tell the
2319 garbage-collection mechanism about the variable.  When `eval' (or
2320 actually `symbol-value') encounters this special object in the process
2321 of retrieving a variable's value, it follows the indirection to the C
2322 variable and gets its value.  `setq' does similar things so that the C
2323 variable gets changed.
2324
2325    Whether or not you `DEFVAR_LISP()' a variable, you need to
2326 initialize it in the `vars_of_*()' function; otherwise it will end up
2327 as all zeroes, which is the integer 0 (_not_ `nil'), and this is
2328 probably not what you want.  Also, if the variable is not
2329 `DEFVAR_LISP()'ed, *you must call* `staticpro()' on the C variable in
2330 the `vars_of_*()' function.  Otherwise, the garbage-collection
2331 mechanism won't know that the object in this variable is in use, and
2332 will happily collect it and reuse its storage for another Lisp object,
2333 and you will be the one who's unhappy when you can't figure out how
2334 your variable got overwritten.
2335
2336 \1f
2337 File: internals.info,  Node: Proper Use of Unsigned Types,  Next: Coding for Mule,  Prev: Adding Global Lisp Variables,  Up: Rules When Writing New C Code
2338
2339 8.6 Proper Use of Unsigned Types
2340 ================================
2341
2342 Avoid using `unsigned int' and `unsigned long' whenever possible.
2343 Unsigned types are viral - any arithmetic or comparisons involving
2344 mixed signed and unsigned types are automatically converted to
2345 unsigned, which is almost certainly not what you want.  Many subtle and
2346 hard-to-find bugs are created by careless use of unsigned types.  In
2347 general, you should almost _never_ use an unsigned type to hold a
2348 regular quantity of any sort.  The only exceptions are
2349
2350   1. When there's a reasonable possibility you will actually need all
2351      32 or 64 bits to store the quantity.
2352
2353   2. When calling existing API's that require unsigned types.  In this
2354      case, you should still do all manipulation using signed types, and
2355      do the conversion at the very threshold of the API call.
2356
2357   3. In existing code that you don't want to modify because you don't
2358      maintain it.
2359
2360   4. In bit-field structures.
2361
2362    Other reasonable uses of `unsigned int' and `unsigned long' are
2363 representing non-quantities - e.g. bit-oriented flags and such.
2364
2365 \1f
2366 File: internals.info,  Node: Coding for Mule,  Next: Techniques for XEmacs Developers,  Prev: Proper Use of Unsigned Types,  Up: Rules When Writing New C Code
2367
2368 8.7 Coding for Mule
2369 ===================
2370
2371 Although Mule support is not compiled by default in XEmacs, many people
2372 are using it, and we consider it crucial that new code works correctly
2373 with multibyte characters.  This is not hard; it is only a matter of
2374 following several simple user-interface guidelines.  Even if you never
2375 compile with Mule, with a little practice you will find it quite easy
2376 to code Mule-correctly.
2377
2378    Note that these guidelines are not necessarily tied to the current
2379 Mule implementation; they are also a good idea to follow on the grounds
2380 of code generalization for future I18N work.
2381
2382 * Menu:
2383
2384 * Character-Related Data Types::
2385 * Working With Character and Byte Positions::
2386 * Conversion to and from External Data::
2387 * General Guidelines for Writing Mule-Aware Code::
2388 * An Example of Mule-Aware Code::
2389
2390 \1f
2391 File: internals.info,  Node: Character-Related Data Types,  Next: Working With Character and Byte Positions,  Up: Coding for Mule
2392
2393 8.7.1 Character-Related Data Types
2394 ----------------------------------
2395
2396 First, let's review the basic character-related datatypes used by
2397 XEmacs.  Note that the separate `typedef's are not mandatory in the
2398 current implementation (all of them boil down to `unsigned char' or
2399 `int'), but they improve clarity of code a great deal, because one
2400 glance at the declaration can tell the intended use of the variable.
2401
2402 `Emchar'
2403      An `Emchar' holds a single Emacs character.
2404
2405      Obviously, the equality between characters and bytes is lost in
2406      the Mule world.  Characters can be represented by one or more
2407      bytes in the buffer, and `Emchar' is the C type large enough to
2408      hold any character.
2409
2410      Without Mule support, an `Emchar' is equivalent to an `unsigned
2411      char'.
2412
2413 `Bufbyte'
2414      The data representing the text in a buffer or string is logically
2415      a set of `Bufbyte's.
2416
2417      XEmacs does not work with the same character formats all the time;
2418      when reading characters from the outside, it decodes them to an
2419      internal format, and likewise encodes them when writing.
2420      `Bufbyte' (in fact `unsigned char') is the basic unit of XEmacs
2421      internal buffers and strings format.  A `Bufbyte *' is the type
2422      that points at text encoded in the variable-width internal
2423      encoding.
2424
2425      One character can correspond to one or more `Bufbyte's.  In the
2426      current Mule implementation, an ASCII character is represented by
2427      the same `Bufbyte', and other characters are represented by a
2428      sequence of two or more `Bufbyte's.
2429
2430      Without Mule support, there are exactly 256 characters, implicitly
2431      Latin-1, and each character is represented using one `Bufbyte', and
2432      there is a one-to-one correspondence between `Bufbyte's and
2433      `Emchar's.
2434
2435 `Bufpos'
2436 `Charcount'
2437      A `Bufpos' represents a character position in a buffer or string.
2438      A `Charcount' represents a number (count) of characters.
2439      Logically, subtracting two `Bufpos' values yields a `Charcount'
2440      value.  Although all of these are `typedef'ed to `EMACS_INT', we
2441      use them in preference to `EMACS_INT' to make it clear what sort
2442      of position is being used.
2443
2444      `Bufpos' and `Charcount' values are the only ones that are ever
2445      visible to Lisp.
2446
2447 `Bytind'
2448 `Bytecount'
2449      A `Bytind' represents a byte position in a buffer or string.  A
2450      `Bytecount' represents the distance between two positions, in
2451      bytes.  The relationship between `Bytind' and `Bytecount' is the
2452      same as the relationship between `Bufpos' and `Charcount'.
2453
2454 `Extbyte'
2455 `Extcount'
2456      When dealing with the outside world, XEmacs works with `Extbyte's,
2457      which are equivalent to `unsigned char'.  Obviously, an `Extcount'
2458      is the distance between two `Extbyte's.  Extbytes and Extcounts
2459      are not all that frequent in XEmacs code.
2460
2461 \1f
2462 File: internals.info,  Node: Working With Character and Byte Positions,  Next: Conversion to and from External Data,  Prev: Character-Related Data Types,  Up: Coding for Mule
2463
2464 8.7.2 Working With Character and Byte Positions
2465 -----------------------------------------------
2466
2467 Now that we have defined the basic character-related types, we can look
2468 at the macros and functions designed for work with them and for
2469 conversion between them.  Most of these macros are defined in
2470 `buffer.h', and we don't discuss all of them here, but only the most
2471 important ones.  Examining the existing code is the best way to learn
2472 about them.
2473
2474 `MAX_EMCHAR_LEN'
2475      This preprocessor constant is the maximum number of buffer bytes to
2476      represent an Emacs character in the variable width internal
2477      encoding.  It is useful when allocating temporary strings to keep
2478      a known number of characters.  For instance:
2479
2480           {
2481             Charcount cclen;
2482             ...
2483             {
2484               /* Allocate place for CCLEN characters. */
2485               Bufbyte *buf = (Bufbyte *)alloca (cclen * MAX_EMCHAR_LEN);
2486           ...
2487
2488      If you followed the previous section, you can guess that,
2489      logically, multiplying a `Charcount' value with `MAX_EMCHAR_LEN'
2490      produces a `Bytecount' value.
2491
2492      In the current Mule implementation, `MAX_EMCHAR_LEN' equals 4.
2493      Without Mule, it is 1.
2494
2495 `charptr_emchar'
2496 `set_charptr_emchar'
2497      The `charptr_emchar' macro takes a `Bufbyte' pointer and returns
2498      the `Emchar' stored at that position.  If it were a function, its
2499      prototype would be:
2500
2501           Emchar charptr_emchar (Bufbyte *p);
2502
2503      `set_charptr_emchar' stores an `Emchar' to the specified byte
2504      position.  It returns the number of bytes stored:
2505
2506           Bytecount set_charptr_emchar (Bufbyte *p, Emchar c);
2507
2508      It is important to note that `set_charptr_emchar' is safe only for
2509      appending a character at the end of a buffer, not for overwriting a
2510      character in the middle.  This is because the width of characters
2511      varies, and `set_charptr_emchar' cannot resize the string if it
2512      writes, say, a two-byte character where a single-byte character
2513      used to reside.
2514
2515      A typical use of `set_charptr_emchar' can be demonstrated by this
2516      example, which copies characters from buffer BUF to a temporary
2517      string of Bufbytes.
2518
2519           {
2520             Bufpos pos;
2521             for (pos = beg; pos < end; pos++)
2522               {
2523                 Emchar c = BUF_FETCH_CHAR (buf, pos);
2524                 p += set_charptr_emchar (buf, c);
2525               }
2526           }
2527
2528      Note how `set_charptr_emchar' is used to store the `Emchar' and
2529      increment the counter, at the same time.
2530
2531 `INC_CHARPTR'
2532 `DEC_CHARPTR'
2533      These two macros increment and decrement a `Bufbyte' pointer,
2534      respectively.  They will adjust the pointer by the appropriate
2535      number of bytes according to the byte length of the character
2536      stored there.  Both macros assume that the memory address is
2537      located at the beginning of a valid character.
2538
2539      Without Mule support, `INC_CHARPTR (p)' and `DEC_CHARPTR (p)'
2540      simply expand to `p++' and `p--', respectively.
2541
2542 `bytecount_to_charcount'
2543      Given a pointer to a text string and a length in bytes, return the
2544      equivalent length in characters.
2545
2546           Charcount bytecount_to_charcount (Bufbyte *p, Bytecount bc);
2547
2548 `charcount_to_bytecount'
2549      Given a pointer to a text string and a length in characters,
2550      return the equivalent length in bytes.
2551
2552           Bytecount charcount_to_bytecount (Bufbyte *p, Charcount cc);
2553
2554 `charptr_n_addr'
2555      Return a pointer to the beginning of the character offset CC (in
2556      characters) from P.
2557
2558           Bufbyte *charptr_n_addr (Bufbyte *p, Charcount cc);
2559
2560 \1f
2561 File: internals.info,  Node: Conversion to and from External Data,  Next: General Guidelines for Writing Mule-Aware Code,  Prev: Working With Character and Byte Positions,  Up: Coding for Mule
2562
2563 8.7.3 Conversion to and from External Data
2564 ------------------------------------------
2565
2566 When an external function, such as a C library function, returns a
2567 `char' pointer, you should almost never treat it as `Bufbyte'.  This is
2568 because these returned strings may contain 8bit characters which can be
2569 misinterpreted by XEmacs, and cause a crash.  Likewise, when exporting
2570 a piece of internal text to the outside world, you should always
2571 convert it to an appropriate external encoding, lest the internal stuff
2572 (such as the infamous \201 characters) leak out.
2573
2574    The interface to conversion between the internal and external
2575 representations of text are the numerous conversion macros defined in
2576 `buffer.h'.  There used to be a fixed set of external formats supported
2577 by these macros, but now any coding system can be used with these
2578 macros.  The coding system alias mechanism is used to create the
2579 following logical coding systems, which replace the fixed external
2580 formats.  The (dontusethis-set-symbol-value-handler) mechanism was
2581 enhanced to make this possible (more work on that is needed - like
2582 remove the `dontusethis-' prefix).
2583
2584 `Qbinary'
2585      This is the simplest format and is what we use in the absence of a
2586      more appropriate format.  This converts according to the `binary'
2587      coding system:
2588
2589        a. On input, bytes 0-255 are converted into (implicitly Latin-1)
2590           characters 0-255.  A non-Mule xemacs doesn't really know about
2591           different character sets and the fonts to display them, so
2592           the bytes can be treated as text in different 1-byte
2593           encodings by simply setting the appropriate fonts.  So in a
2594           sense, non-Mule xemacs is a multi-lingual editor if, for
2595           example, different fonts are used to display text in
2596           different buffers, faces, or windows.  The specifier
2597           mechanism gives the user complete control over this kind of
2598           behavior.
2599
2600        b. On output, characters 0-255 are converted into bytes 0-255
2601           and other characters are converted into `~'.
2602
2603 `Qfile_name'
2604      Format used for filenames.  This is user-definable via either the
2605      `file-name-coding-system' or `pathname-coding-system' (now
2606      obsolete) variables.
2607
2608 `Qnative'
2609      Format used for the external Unix environment--`argv[]', stuff
2610      from `getenv()', stuff from the `/etc/passwd' file, etc.
2611      Currently this is the same as Qfile_name.  The two should be
2612      distinguished for clarity and possible future separation.
2613
2614 `Qctext'
2615      Compound-text format.  This is the standard X11 format used for
2616      data stored in properties, selections, and the like.  This is an
2617      8-bit no-lock-shift ISO2022 coding system.  This is a real coding
2618      system, unlike Qfile_name, which is user-definable.
2619
2620    There are two fundamental macros to convert between external and
2621 internal format.
2622
2623    `TO_INTERNAL_FORMAT' converts external data to internal format, and
2624 `TO_EXTERNAL_FORMAT' converts the other way around.  The arguments each
2625 of these receives are a source type, a source, a sink type, a sink, and
2626 a coding system (or a symbol naming a coding system).
2627
2628    A typical call looks like
2629      TO_EXTERNAL_FORMAT (LISP_STRING, str, C_STRING_MALLOC, ptr, Qfile_name);
2630
2631    which means that the contents of the lisp string `str' are written
2632 to a malloc'ed memory area which will be pointed to by `ptr', after the
2633 function returns.  The conversion will be done using the `file-name'
2634 coding system, which will be controlled by the user indirectly by
2635 setting or binding the variable `file-name-coding-system'.
2636
2637    Some sources and sinks require two C variables to specify.  We use
2638 some preprocessor magic to allow different source and sink types, and
2639 even different numbers of arguments to specify different types of
2640 sources and sinks.
2641
2642    So we can have a call that looks like
2643      TO_INTERNAL_FORMAT (DATA, (ptr, len),
2644                          MALLOC, (ptr, len),
2645                          coding_system);
2646
2647    The parenthesized argument pairs are required to make the
2648 preprocessor magic work.
2649
2650    Here are the different source and sink types:
2651
2652 ``DATA, (ptr, len),''
2653      input data is a fixed buffer of size LEN at address PTR
2654
2655 ``ALLOCA, (ptr, len),''
2656      output data is placed in an alloca()ed buffer of size LEN pointed
2657      to by PTR
2658
2659 ``MALLOC, (ptr, len),''
2660      output data is in a malloc()ed buffer of size LEN pointed to by PTR
2661
2662 ``C_STRING_ALLOCA, ptr,''
2663      equivalent to `ALLOCA (ptr, len_ignored)' on output.
2664
2665 ``C_STRING_MALLOC, ptr,''
2666      equivalent to `MALLOC (ptr, len_ignored)' on output
2667
2668 ``C_STRING, ptr,''
2669      equivalent to `DATA, (ptr, strlen (ptr) + 1)' on input
2670
2671 ``LISP_STRING, string,''
2672      input or output is a Lisp_Object of type string
2673
2674 ``LISP_BUFFER, buffer,''
2675      output is written to `(point)' in lisp buffer BUFFER
2676
2677 ``LISP_LSTREAM, lstream,''
2678      input or output is a Lisp_Object of type lstream
2679
2680 ``LISP_OPAQUE, object,''
2681      input or output is a Lisp_Object of type opaque
2682
2683    Often, the data is being converted to a '\0'-byte-terminated string,
2684 which is the format required by many external system C APIs.  For these
2685 purposes, a source type of `C_STRING' or a sink type of
2686 `C_STRING_ALLOCA' or `C_STRING_MALLOC' is appropriate.  Otherwise, we
2687 should try to keep XEmacs '\0'-byte-clean, which means using (ptr, len)
2688 pairs.
2689
2690    The sinks to be specified must be lvalues, unless they are the lisp
2691 object types `LISP_LSTREAM' or `LISP_BUFFER'.
2692
2693    For the sink types `ALLOCA' and `C_STRING_ALLOCA', the resulting
2694 text is stored in a stack-allocated buffer, which is automatically
2695 freed on returning from the function.  However, the sink types `MALLOC'
2696 and `C_STRING_MALLOC' return `xmalloc()'ed memory.  The caller is
2697 responsible for freeing this memory using `xfree()'.
2698
2699    Note that it doesn't make sense for `LISP_STRING' to be a source for
2700 `TO_INTERNAL_FORMAT' or a sink for `TO_EXTERNAL_FORMAT'.  You'll get an
2701 assertion failure if you try.
2702
2703 \1f
2704 File: internals.info,  Node: General Guidelines for Writing Mule-Aware Code,  Next: An Example of Mule-Aware Code,  Prev: Conversion to and from External Data,  Up: Coding for Mule
2705
2706 8.7.4 General Guidelines for Writing Mule-Aware Code
2707 ----------------------------------------------------
2708
2709 This section contains some general guidance on how to write Mule-aware
2710 code, as well as some pitfalls you should avoid.
2711
2712 _Never use `char' and `char *'._
2713      In XEmacs, the use of `char' and `char *' is almost always a
2714      mistake.  If you want to manipulate an Emacs character from "C",
2715      use `Emchar'.  If you want to examine a specific octet in the
2716      internal format, use `Bufbyte'.  If you want a Lisp-visible
2717      character, use a `Lisp_Object' and `make_char'.  If you want a
2718      pointer to move through the internal text, use `Bufbyte *'.  Also
2719      note that you almost certainly do not need `Emchar *'.
2720
2721 _Be careful not to confuse `Charcount', `Bytecount', and `Bufpos'._
2722      The whole point of using different types is to avoid confusion
2723      about the use of certain variables.  Lest this effect be
2724      nullified, you need to be careful about using the right types.
2725
2726 _Always convert external data_
2727      It is extremely important to always convert external data, because
2728      XEmacs can crash if unexpected 8bit sequences are copied to its
2729      internal buffers literally.
2730
2731      This means that when a system function, such as `readdir', returns
2732      a string, you may need to convert it using one of the conversion
2733      macros described in the previous chapter, before passing it
2734      further to Lisp.
2735
2736      Actually, most of the basic system functions that accept
2737      '\0'-terminated string arguments, like `stat()' and `open()', have
2738      been *encapsulated* so that they are they `always' do internal to
2739      external conversion themselves.  This means you must pass
2740      internally encoded data, typically the `XSTRING_DATA' of a
2741      Lisp_String to these functions.  This is actually a design bug,
2742      since it unexpectedly changes the semantics of the system
2743      functions.  A better design would be to provide separate versions
2744      of these system functions that accepted Lisp_Objects which were
2745      lisp strings in place of their current `char *' arguments.
2746
2747           int stat_lisp (Lisp_Object path, struct stat *buf); /* Implement me */
2748
2749      Also note that many internal functions, such as `make_string',
2750      accept Bufbytes, which removes the need for them to convert the
2751      data they receive.  This increases efficiency because that way
2752      external data needs to be decoded only once, when it is read.
2753      After that, it is passed around in internal format.
2754
2755 \1f
2756 File: internals.info,  Node: An Example of Mule-Aware Code,  Prev: General Guidelines for Writing Mule-Aware Code,  Up: Coding for Mule
2757
2758 8.7.5 An Example of Mule-Aware Code
2759 -----------------------------------
2760
2761 As an example of Mule-aware code, we will analyze the `string'
2762 function, which conses up a Lisp string from the character arguments it
2763 receives.  Here is the definition, pasted from `alloc.c':
2764
2765      DEFUN ("string", Fstring, 0, MANY, 0, /*
2766      Concatenate all the argument characters and make the result a string.
2767      */
2768             (int nargs, Lisp_Object *args))
2769      {
2770        Bufbyte *storage = alloca_array (Bufbyte, nargs * MAX_EMCHAR_LEN);
2771        Bufbyte *p = storage;
2772
2773        for (; nargs; nargs--, args++)
2774          {
2775            Lisp_Object lisp_char = *args;
2776            CHECK_CHAR_COERCE_INT (lisp_char);
2777            p += set_charptr_emchar (p, XCHAR (lisp_char));
2778          }
2779        return make_string (storage, p - storage);
2780      }
2781
2782    Now we can analyze the source line by line.
2783
2784    Obviously, string will be as long as there are arguments to the
2785 function.  This is why we allocate `MAX_EMCHAR_LEN' * NARGS bytes on
2786 the stack, i.e. the worst-case number of bytes for NARGS `Emchar's to
2787 fit in the string.
2788
2789    Then, the loop checks that each element is a character, converting
2790 integers in the process.  Like many other functions in XEmacs, this
2791 function silently accepts integers where characters are expected, for
2792 historical and compatibility reasons.  Unless you know what you are
2793 doing, `CHECK_CHAR' will also suffice.  `XCHAR (lisp_char)' extracts
2794 the `Emchar' from the `Lisp_Object', and `set_charptr_emchar' stores it
2795 to storage, increasing `p' in the process.
2796
2797    Other instructive examples of correct coding under Mule can be found
2798 all over the XEmacs code.  For starters, I recommend
2799 `Fnormalize_menu_item_name' in `menubar.c'.  After you have understood
2800 this section of the manual and studied the examples, you can proceed
2801 writing new Mule-aware code.
2802
2803 \1f
2804 File: internals.info,  Node: Techniques for XEmacs Developers,  Prev: Coding for Mule,  Up: Rules When Writing New C Code
2805
2806 8.8 Techniques for XEmacs Developers
2807 ====================================
2808
2809 To make a purified XEmacs, do: `make puremacs'.  To make a quantified
2810 XEmacs, do: `make quantmacs'.
2811
2812    You simply can't dump Quantified and Purified images (unless using
2813 the portable dumper).  Purify gets confused when xemacs frees memory in
2814 one process that was allocated in a _different_ process on a different
2815 machine!.  Run it like so:
2816      temacs -batch -l loadup.el run-temacs XEMACS-ARGS...
2817
2818    Before you go through the trouble, are you compiling with all
2819 debugging and error-checking off?  If not, try that first.  Be warned
2820 that while Quantify is directly responsible for quite a few
2821 optimizations which have been made to XEmacs, doing a run which
2822 generates results which can be acted upon is not necessarily a trivial
2823 task.
2824
2825    Also, if you're still willing to do some runs make sure you configure
2826 with the `--quantify' flag.  That will keep Quantify from starting to
2827 record data until after the loadup is completed and will shut off
2828 recording right before it shuts down (which generates enough bogus data
2829 to throw most results off).  It also enables three additional elisp
2830 commands: `quantify-start-recording-data',
2831 `quantify-stop-recording-data' and `quantify-clear-data'.
2832
2833    If you want to make XEmacs faster, target your favorite slow
2834 benchmark, run a profiler like Quantify, `gprof', or `tcov', and figure
2835 out where the cycles are going.  In many cases you can localize the
2836 problem (because a particular new feature or even a single patch
2837 elicited it).  Don't hesitate to use brute force techniques like a
2838 global counter incremented at strategic places, especially in
2839 combination with other performance indications (_e.g._, degree of
2840 buffer fragmentation into extents).
2841
2842    Specific projects:
2843
2844    * Make the garbage collector faster.  Figure out how to write an
2845      incremental garbage collector.
2846
2847    * Write a compiler that takes bytecode and spits out C code.
2848      Unfortunately, you will then need a C compiler and a more fully
2849      developed module system.
2850
2851    * Speed up redisplay.
2852
2853    * Speed up syntax highlighting.  It was suggested that "maybe moving
2854      some of the syntax highlighting capabilities into C would make a
2855      difference."  Wrong idea, I think.  When processing one 400kB file
2856      a particular low-level routine was being called 40 _million_ times
2857      simply for _one_ call to `newline-and-indent'.  Syntax
2858      highlighting needs to be rewritten to use a reliable, fast parser,
2859      then to trust the pre-parsed structure, and only do
2860      re-highlighting locally to a text change.  Modern machines are
2861      fast enough to implement such parsers in Lisp; but no machine will
2862      ever be fast enough to deal with quadratic (or worse) algorithms!
2863
2864    * Implement tail recursion in Emacs Lisp (hard!).
2865
2866    Unfortunately, Emacs Lisp is slow, and is going to stay slow.
2867 Function calls in elisp are especially expensive.  Iterating over a
2868 long list is going to be 30 times faster implemented in C than in Elisp.
2869
2870    Heavily used small code fragments need to be fast.  The traditional
2871 way to implement such code fragments in C is with macros.  But macros
2872 in C are known to be broken.
2873
2874    Macro arguments that are repeatedly evaluated may suffer from
2875 repeated side effects or suboptimal performance.
2876
2877    Variable names used in macros may collide with caller's variables,
2878 causing (at least) unwanted compiler warnings.
2879
2880    In order to solve these problems, and maintain statement semantics,
2881 one should use the `do { ... } while (0)' trick while trying to
2882 reference macro arguments exactly once using local variables.
2883
2884    Let's take a look at this poor macro definition:
2885
2886      #define MARK_OBJECT(obj) \
2887        if (!marked_p (obj)) mark_object (obj), did_mark = 1
2888
2889    This macro evaluates its argument twice, and also fails if used like
2890 this:
2891        if (flag) MARK_OBJECT (obj); else do_something();
2892
2893    A much better definition is
2894
2895      #define MARK_OBJECT(obj) do { \
2896        Lisp_Object mo_obj = (obj); \
2897        if (!marked_p (mo_obj))     \
2898          {                         \
2899            mark_object (mo_obj);   \
2900            did_mark = 1;           \
2901          }                         \
2902      } while (0)
2903
2904    Notice the elimination of double evaluation by using the local
2905 variable with the obscure name.  Writing safe and efficient macros
2906 requires great care.  The one problem with macros that cannot be
2907 portably worked around is, since a C block has no value, a macro used
2908 as an expression rather than a statement cannot use the techniques just
2909 described to avoid multiple evaluation.
2910
2911    In most cases where a macro has function semantics, an inline
2912 function is a better implementation technique.  Modern compiler
2913 optimizers tend to inline functions even if they have no `inline'
2914 keyword, and configure magic ensures that the `inline' keyword can be
2915 safely used as an additional compiler hint.  Inline functions used in a
2916 single .c files are easy.  The function must already be defined to be
2917 `static'.  Just add another `inline' keyword to the definition.
2918
2919      inline static int
2920      heavily_used_small_function (int arg)
2921      {
2922        ...
2923      }
2924
2925    Inline functions in header files are trickier, because we would like
2926 to make the following optimization if the function is _not_ inlined
2927 (for example, because we're compiling for debugging).  We would like the
2928 function to be defined externally exactly once, and each calling
2929 translation unit would create an external reference to the function,
2930 instead of including a definition of the inline function in the object
2931 code of every translation unit that uses it.  This optimization is
2932 currently only available for gcc.  But you don't have to worry about the
2933 trickiness; just define your inline functions in header files using this
2934 pattern:
2935
2936      INLINE_HEADER int
2937      i_used_to_be_a_crufty_macro_but_look_at_me_now (int arg);
2938      INLINE_HEADER int
2939      i_used_to_be_a_crufty_macro_but_look_at_me_now (int arg)
2940      {
2941        ...
2942      }
2943
2944    The declaration right before the definition is to prevent warnings
2945 when compiling with `gcc -Wmissing-declarations'.  I consider issuing
2946 this warning for inline functions a gcc bug, but the gcc maintainers
2947 disagree.
2948
2949    Every header which contains inline functions, either directly by
2950 using `INLINE_HEADER' or indirectly by using `DECLARE_LRECORD' must be
2951 added to `inline.c''s includes to make the optimization described above
2952 work.  (Optimization note: if all INLINE_HEADER functions are in fact
2953 inlined in all translation units, then the linker can just discard
2954 `inline.o', since it contains only unreferenced code).
2955
2956    To get started debugging XEmacs, take a look at the `.gdbinit' and
2957 `.dbxrc' files in the `src' directory.  See the section in the XEmacs
2958 FAQ on How to Debug an XEmacs problem with a debugger.
2959
2960    After making source code changes, run `make check' to ensure that
2961 you haven't introduced any regressions.  If you want to make xemacs more
2962 reliable, please improve the test suite in `tests/automated'.
2963
2964    Did you make sure you didn't introduce any new compiler warnings?
2965
2966    Before submitting a patch, please try compiling at least once with
2967
2968      configure --with-mule --use-union-type --error-checking=all
2969
2970    Here are things to know when you create a new source file:
2971
2972    * All `.c' files should `#include <config.h>' first.  Almost all
2973      `.c' files should `#include "lisp.h"' second.
2974
2975    * Generated header files should be included using the `#include
2976      <...>' syntax, not the `#include "..."' syntax.  The generated
2977      headers are:
2978
2979      `config.h sheap-adjust.h paths.h Emacs.ad.h'
2980
2981      The basic rule is that you should assume builds using `--srcdir'
2982      and the `#include <...>' syntax needs to be used when the
2983      to-be-included generated file is in a potentially different
2984      directory _at compile time_.  The non-obvious C rule is that
2985      `#include "..."' means to search for the included file in the same
2986      directory as the including file, _not_ in the current directory.
2987      Normally this is not a problem but when building with `--srcdir',
2988      `make' will search the `VPATH' for you, while the C compiler knows
2989      nothing about it.
2990
2991    * Header files should _not_ include `<config.h>' and `"lisp.h"'.  It
2992      is the responsibility of the `.c' files that use it to do so.
2993
2994
2995    Here is a checklist of things to do when creating a new lisp object
2996 type named FOO:
2997
2998   1. create FOO.h
2999
3000   2. create FOO.c
3001
3002   3. add definitions of `syms_of_FOO', etc. to `FOO.c'
3003
3004   4. add declarations of `syms_of_FOO', etc. to `symsinit.h'
3005
3006   5. add calls to `syms_of_FOO', etc. to `emacs.c'
3007
3008   6. add definitions of macros like `CHECK_FOO' and `FOOP' to `FOO.h'
3009
3010   7. add the new type index to `enum lrecord_type'
3011
3012   8. add a DEFINE_LRECORD_IMPLEMENTATION call to `FOO.c'
3013
3014   9. add an INIT_LRECORD_IMPLEMENTATION call to `syms_of_FOO.c'
3015
3016 \1f
3017 File: internals.info,  Node: Regression Testing XEmacs,  Next: A Summary of the Various XEmacs Modules,  Prev: Rules When Writing New C Code,  Up: Top
3018
3019 9 Regression Testing XEmacs
3020 ***************************
3021
3022 The source directory `tests/automated' contains XEmacs' automated test
3023 suite.  The usual way of running all the tests is running `make check'
3024 from the top-level source directory.
3025
3026    The test suite is unfinished and it's still lacking some essential
3027 features.  It is nevertheless recommended that you run the tests to
3028 confirm that XEmacs behaves correctly.
3029
3030    If you want to run a specific test case, you can do it from the
3031 command-line like this:
3032
3033      $ xemacs -batch -l test-harness.elc -f batch-test-emacs TEST-FILE
3034
3035    If something goes wrong, you can run the test suite interactively by
3036 loading `test-harness.el' into a running XEmacs and typing `M-x
3037 test-emacs-test-file RET <filename> RET'.  You will see a log of passed
3038 and failed tests, which should allow you to investigate the source of
3039 the error and ultimately fix the bug.
3040
3041    Adding a new test file is trivial: just create a new file here and it
3042 will be run.  There is no need to byte-compile any of the files in this
3043 directory--the test-harness will take care of any necessary
3044 byte-compilation.
3045
3046    Look at the existing test cases for the examples of coding test
3047 cases.  It all boils down to your imagination and judicious use of the
3048 macros `Assert', `Check-Error', `Check-Error-Message', and
3049 `Check-Message'.
3050
3051    Here's a simple example checking case-sensitive and case-insensitive
3052 comparisons from `case-tests.el'.
3053
3054      (with-temp-buffer
3055        (insert "Test Buffer")
3056        (let ((case-fold-search t))
3057          (goto-char (point-min))
3058          (Assert (eq (search-forward "test buffer" nil t) 12))
3059          (goto-char (point-min))
3060          (Assert (eq (search-forward "Test buffer" nil t) 12))
3061          (goto-char (point-min))
3062          (Assert (eq (search-forward "Test Buffer" nil t) 12))
3063
3064          (setq case-fold-search nil)
3065          (goto-char (point-min))
3066          (Assert (not (search-forward "test buffer" nil t)))
3067          (goto-char (point-min))
3068          (Assert (not (search-forward "Test buffer" nil t)))
3069          (goto-char (point-min))
3070          (Assert (eq (search-forward "Test Buffer" nil t) 12))))
3071
3072    This example could be inserted in a file in `tests/automated', and
3073 it would be a complete test, automatically executed when you run `make
3074 check' after building XEmacs.  More complex tests may require
3075 substantial temporary scaffolding to create the environment that elicits
3076 the bugs, but the top-level Makefile and `test-harness.el' handle the
3077 running and collection of results from the `Assert', `Check-Error',
3078 `Check-Error-Message', and `Check-Message' macros.
3079
3080    In general, you should avoid using functionality from packages in
3081 your tests, because you can't be sure that everyone will have the
3082 required package.  However, if you've got a test that works, by all
3083 means add it.  Simply wrap the test in an appropriate test, add a
3084 notice that the test was skipped, and update the `skipped-test-reasons'
3085 hashtable.  Here's an example from `syntax-tests.el':
3086
3087      ;; Test forward-comment at buffer boundaries
3088      (with-temp-buffer
3089
3090        ;; try to use exactly what you need: featurep, boundp, fboundp
3091        (if (not (fboundp 'c-mode))
3092
3093            ;; We should provide a standard function for this boilerplate,
3094            ;; probably called `Skip-Test' -- check for that API with C-h f
3095            (let* ((reason "c-mode unavailable")
3096              (count (gethash reason skipped-test-reasons)))
3097         (puthash reason (if (null count) 1 (1+ count))
3098                  skipped-test-reasons)
3099         (Print-Skip "comment and parse-partial-sexp tests" reason))
3100
3101          ;; and here's the test code
3102          (c-mode)
3103          (insert "// comment\n")
3104          (forward-comment -2)
3105          (Assert (eq (point) (point-min)))
3106          (let ((point (point)))
3107            (insert "/* comment */")
3108            (goto-char point)
3109            (forward-comment 2)
3110            (Assert (eq (point) (point-max)))
3111            (parse-partial-sexp point (point-max)))))
3112
3113    `Skip-Test' is intended for use with features that are normally
3114 present in typical configurations.  For truly optional features, or
3115 tests that apply to one of several alternative implementations (eg, to
3116 GTK widgets, but not Athena, Motif, MS Windows, or Carbon), simply
3117 silently omit the test.
3118
3119 \1f
3120 File: internals.info,  Node: A Summary of the Various XEmacs Modules,  Next: Allocation of Objects in XEmacs Lisp,  Prev: Regression Testing XEmacs,  Up: Top
3121
3122 10 A Summary of the Various XEmacs Modules
3123 ******************************************
3124
3125 This is accurate as of XEmacs 20.0.
3126
3127 * Menu:
3128
3129 * Low-Level Modules::
3130 * Basic Lisp Modules::
3131 * Modules for Standard Editing Operations::
3132 * Editor-Level Control Flow Modules::
3133 * Modules for the Basic Displayable Lisp Objects::
3134 * Modules for other Display-Related Lisp Objects::
3135 * Modules for the Redisplay Mechanism::
3136 * Modules for Interfacing with the File System::
3137 * Modules for Other Aspects of the Lisp Interpreter and Object System::
3138 * Modules for Interfacing with the Operating System::
3139 * Modules for Interfacing with X Windows::
3140 * Modules for Internationalization::
3141 * Modules for Regression Testing::
3142
3143 \1f
3144 File: internals.info,  Node: Low-Level Modules,  Next: Basic Lisp Modules,  Up: A Summary of the Various XEmacs Modules
3145
3146 10.1 Low-Level Modules
3147 ======================
3148
3149      config.h
3150
3151    This is automatically generated from `config.h.in' based on the
3152 results of configure tests and user-selected optional features and
3153 contains preprocessor definitions specifying the nature of the
3154 environment in which XEmacs is being compiled.
3155
3156      paths.h
3157
3158    This is automatically generated from `paths.h.in' based on supplied
3159 configure values, and allows for non-standard installed configurations
3160 of the XEmacs directories.  It's currently broken, though.
3161
3162      emacs.c
3163      signal.c
3164
3165    `emacs.c' contains `main()' and other code that performs the most
3166 basic environment initializations and handles shutting down the XEmacs
3167 process (this includes `kill-emacs', the normal way that XEmacs is
3168 exited; `dump-emacs', which is used during the build process to write
3169 out the XEmacs executable; `run-emacs-from-temacs', which can be used
3170 to start XEmacs directly when temacs has finished loading all the Lisp
3171 code; and emergency code to handle crashes [XEmacs tries to auto-save
3172 all files before it crashes]).
3173
3174    Low-level code that directly interacts with the Unix signal
3175 mechanism, however, is in `signal.c'.  Note that this code does not
3176 handle system dependencies in interfacing to signals; that is handled
3177 using the `syssignal.h' header file, described in section J below.
3178
3179      unexaix.c
3180      unexalpha.c
3181      unexapollo.c
3182      unexconvex.c
3183      unexec.c
3184      unexelf.c
3185      unexelfsgi.c
3186      unexencap.c
3187      unexenix.c
3188      unexfreebsd.c
3189      unexfx2800.c
3190      unexhp9k3.c
3191      unexhp9k800.c
3192      unexmips.c
3193      unexnext.c
3194      unexsol2.c
3195      unexsunos4.c
3196
3197    These modules contain code dumping out the XEmacs executable on
3198 various different systems. (This process is highly machine-specific and
3199 requires intimate knowledge of the executable format and the memory map
3200 of the process.) Only one of these modules is actually used; this is
3201 chosen by `configure'.
3202
3203      ecrt0.c
3204      lastfile.c
3205      pre-crt0.c
3206
3207    These modules are used in conjunction with the dump mechanism.  On
3208 some systems, an alternative version of the C startup code (the actual
3209 code that receives control from the operating system when the process is
3210 started, and which calls `main()') is required so that the dumping
3211 process works properly; `crt0.c' provides this.
3212
3213    `pre-crt0.c' and `lastfile.c' should be the very first and very last
3214 file linked, respectively. (Actually, this is not really true.
3215 `lastfile.c' should be after all Emacs modules whose initialized data
3216 should be made constant, and before all other Emacs files and all
3217 libraries.  In particular, the allocation modules `gmalloc.c',
3218 `alloca.c', etc. are normally placed past `lastfile.c', and all of the
3219 files that implement Xt widget classes _must_ be placed after
3220 `lastfile.c' because they contain various structures that must be
3221 statically initialized and into which Xt writes at various times.)
3222 `pre-crt0.c' and `lastfile.c' contain exported symbols that are used to
3223 determine the start and end of XEmacs' initialized data space when
3224 dumping.
3225
3226      alloca.c
3227      free-hook.c
3228      getpagesize.h
3229      gmalloc.c
3230      malloc.c
3231      mem-limits.h
3232      ralloc.c
3233      vm-limit.c
3234
3235    These handle basic C allocation of memory.  `alloca.c' is an
3236 emulation of the stack allocation function `alloca()' on machines that
3237 lack this. (XEmacs makes extensive use of `alloca()' in its code.)
3238
3239    `gmalloc.c' and `malloc.c' are two implementations of the standard C
3240 functions `malloc()', `realloc()' and `free()'.  They are often used in
3241 place of the standard system-provided `malloc()' because they usually
3242 provide a much faster implementation, at the expense of additional
3243 memory use.  `gmalloc.c' is a newer implementation that is much more
3244 memory-efficient for large allocations than `malloc.c', and should
3245 always be preferred if it works. (At one point, `gmalloc.c' didn't work
3246 on some systems where `malloc.c' worked; but this should be fixed now.)
3247
3248    `ralloc.c' is the "relocating allocator".  It provides functions
3249 similar to `malloc()', `realloc()' and `free()' that allocate memory
3250 that can be dynamically relocated in memory.  The advantage of this is
3251 that allocated memory can be shuffled around to place all the free
3252 memory at the end of the heap, and the heap can then be shrunk,
3253 releasing the memory back to the operating system.  The use of this can
3254 be controlled with the configure option `--rel-alloc'; if enabled,
3255 memory allocated for buffers will be relocatable, so that if a very
3256 large file is visited and the buffer is later killed, the memory can be
3257 released to the operating system.  (The disadvantage of this mechanism
3258 is that it can be very slow.  On systems with the `mmap()' system call,
3259 the XEmacs version of `ralloc.c' uses this to move memory around
3260 without actually having to block-copy it, which can speed things up;
3261 but it can still cause noticeable performance degradation.)
3262
3263    `free-hook.c' contains some debugging functions for checking for
3264 invalid arguments to `free()'.
3265
3266    `vm-limit.c' contains some functions that warn the user when memory
3267 is getting low.  These are callback functions that are called by
3268 `gmalloc.c' and `malloc.c' at appropriate times.
3269
3270    `getpagesize.h' provides a uniform interface for retrieving the size
3271 of a page in virtual memory.  `mem-limits.h' provides a uniform
3272 interface for retrieving the total amount of available virtual memory.
3273 Both are similar in spirit to the `sys*.h' files described in section
3274 J, below.
3275
3276      blocktype.c
3277      blocktype.h
3278      dynarr.c
3279
3280    These implement a couple of basic C data types to facilitate memory
3281 allocation.  The `Blocktype' type efficiently manages the allocation of
3282 fixed-size blocks by minimizing the number of times that `malloc()' and
3283 `free()' are called.  It allocates memory in large chunks, subdivides
3284 the chunks into blocks of the proper size, and returns the blocks as
3285 requested.  When blocks are freed, they are placed onto a linked list,
3286 so they can be efficiently reused.  This data type is not much used in
3287 XEmacs currently, because it's a fairly new addition.
3288
3289    The `Dynarr' type implements a "dynamic array", which is similar to
3290 a standard C array but has no fixed limit on the number of elements it
3291 can contain.  Dynamic arrays can hold elements of any type, and when
3292 you add a new element, the array automatically resizes itself if it
3293 isn't big enough.  Dynarrs are extensively used in the redisplay
3294 mechanism.
3295
3296      inline.c
3297
3298    This module is used in connection with inline functions (available in
3299 some compilers).  Often, inline functions need to have a corresponding
3300 non-inline function that does the same thing.  This module is where they
3301 reside.  It contains no actual code, but defines some special flags that
3302 cause inline functions defined in header files to be rendered as actual
3303 functions.  It then includes all header files that contain any inline
3304 function definitions, so that each one gets a real function equivalent.
3305
3306      debug.c
3307      debug.h
3308
3309    These functions provide a system for doing internal consistency
3310 checks during code development.  This system is not currently used;
3311 instead the simpler `assert()' macro is used along with the various
3312 checks provided by the `--error-check-*' configuration options.
3313
3314      universe.h
3315
3316    This is not currently used.
3317
3318 \1f
3319 File: internals.info,  Node: Basic Lisp Modules,  Next: Modules for Standard Editing Operations,  Prev: Low-Level Modules,  Up: A Summary of the Various XEmacs Modules
3320
3321 10.2 Basic Lisp Modules
3322 =======================
3323
3324      lisp-disunion.h
3325      lisp-union.h
3326      lisp.h
3327      lrecord.h
3328      symsinit.h
3329
3330    These are the basic header files for all XEmacs modules.  Each module
3331 includes `lisp.h', which brings the other header files in.  `lisp.h'
3332 contains the definitions of the structures and extractor and
3333 constructor macros for the basic Lisp objects and various other basic
3334 definitions for the Lisp environment, as well as some general-purpose
3335 definitions (e.g. `min()' and `max()').  `lisp.h' includes either
3336 `lisp-disunion.h' or `lisp-union.h', depending on whether
3337 `USE_UNION_TYPE' is defined.  These files define the typedef of the
3338 Lisp object itself (as described above) and the low-level macros that
3339 hide the actual implementation of the Lisp object.  All extractor and
3340 constructor macros for particular types of Lisp objects are defined in
3341 terms of these low-level macros.
3342
3343    As a general rule, all typedefs should go into the typedefs section
3344 of `lisp.h' rather than into a module-specific header file even if the
3345 structure is defined elsewhere.  This allows function prototypes that
3346 use the typedef to be placed into other header files.  Forward structure
3347 declarations (i.e. a simple declaration like `struct foo;' where the
3348 structure itself is defined elsewhere) should be placed into the
3349 typedefs section as necessary.
3350
3351    `lrecord.h' contains the basic structures and macros that implement
3352 all record-type Lisp objects--i.e. all objects whose type is a field in
3353 their C structure, which includes all objects except the few most basic
3354 ones.
3355
3356    `lisp.h' contains prototypes for most of the exported functions in
3357 the various modules.  Lisp primitives defined using `DEFUN' that need
3358 to be called by C code should be declared using `EXFUN'.  Other
3359 function prototypes should be placed either into the appropriate
3360 section of `lisp.h', or into a module-specific header file, depending
3361 on how general-purpose the function is and whether it has
3362 special-purpose argument types requiring definitions not in `lisp.h'.)
3363 All initialization functions are prototyped in `symsinit.h'.
3364
3365      alloc.c
3366
3367    The large module `alloc.c' implements all of the basic allocation and
3368 garbage collection for Lisp objects.  The most commonly used Lisp
3369 objects are allocated in chunks, similar to the Blocktype data type
3370 described above; others are allocated in individually `malloc()'ed
3371 blocks.  This module provides the foundation on which all other aspects
3372 of the Lisp environment sit, and is the first module initialized at
3373 startup.
3374
3375    Note that `alloc.c' provides a series of generic functions that are
3376 not dependent on any particular object type, and interfaces to
3377 particular types of objects using a standardized interface of
3378 type-specific methods.  This scheme is a fundamental principle of
3379 object-oriented programming and is heavily used throughout XEmacs.  The
3380 great advantage of this is that it allows for a clean separation of
3381 functionality into different modules--new classes of Lisp objects, new
3382 event interfaces, new device types, new stream interfaces, etc. can be
3383 added transparently without affecting code anywhere else in XEmacs.
3384 Because the different subsystems are divided into general and specific
3385 code, adding a new subtype within a subsystem will in general not
3386 require changes to the generic subsystem code or affect any of the other
3387 subtypes in the subsystem; this provides a great deal of robustness to
3388 the XEmacs code.
3389
3390      eval.c
3391      backtrace.h
3392
3393    This module contains all of the functions to handle the flow of
3394 control.  This includes the mechanisms of defining functions, calling
3395 functions, traversing stack frames, and binding variables; the control
3396 primitives and other special forms such as `while', `if', `eval',
3397 `let', `and', `or', `progn', etc.; handling of non-local exits,
3398 unwind-protects, and exception handlers; entering the debugger; methods
3399 for the subr Lisp object type; etc.  It does _not_ include the `read'
3400 function, the `print' function, or the handling of symbols and obarrays.
3401
3402    `backtrace.h' contains some structures related to stack frames and
3403 the flow of control.
3404
3405      lread.c
3406
3407    This module implements the Lisp reader and the `read' function,
3408 which converts text into Lisp objects, according to the read syntax of
3409 the objects, as described above.  This is similar to the parser that is
3410 a part of all compilers.
3411
3412      print.c
3413
3414    This module implements the Lisp print mechanism and the `print'
3415 function and related functions.  This is the inverse of the Lisp reader
3416 - it converts Lisp objects to a printed, textual representation.
3417 (Hopefully something that can be read back in using `read' to get an
3418 equivalent object.)
3419
3420      general.c
3421      symbols.c
3422      symeval.h
3423
3424    `symbols.c' implements the handling of symbols, obarrays, and
3425 retrieving the values of symbols.  Much of the code is devoted to
3426 handling the special "symbol-value-magic" objects that define special
3427 types of variables--this includes buffer-local variables, variable
3428 aliases, variables that forward into C variables, etc.  This module is
3429 initialized extremely early (right after `alloc.c'), because it is here
3430 that the basic symbols `t' and `nil' are created, and those symbols are
3431 used everywhere throughout XEmacs.
3432
3433    `symeval.h' contains the definitions of symbol structures and the
3434 `DEFVAR_LISP()' and related macros for declaring variables.
3435
3436      data.c
3437      floatfns.c
3438      fns.c
3439
3440    These modules implement the methods and standard Lisp primitives for
3441 all the basic Lisp object types other than symbols (which are described
3442 above).  `data.c' contains all the predicates (primitives that return
3443 whether an object is of a particular type); the integer arithmetic
3444 functions; and the basic accessor and mutator primitives for the various
3445 object types.  `fns.c' contains all the standard predicates for working
3446 with sequences (where, abstractly speaking, a sequence is an ordered set
3447 of objects, and can be represented by a list, string, vector, or
3448 bit-vector); it also contains `equal', perhaps on the grounds that bulk
3449 of the operation of `equal' is comparing sequences.  `floatfns.c'
3450 contains methods and primitives for floats and floating-point
3451 arithmetic.
3452
3453      bytecode.c
3454      bytecode.h
3455
3456    `bytecode.c' implements the byte-code interpreter and
3457 compiled-function objects, and `bytecode.h' contains associated
3458 structures.  Note that the byte-code _compiler_ is written in Lisp.
3459
3460 \1f
3461 File: internals.info,  Node: Modules for Standard Editing Operations,  Next: Editor-Level Control Flow Modules,  Prev: Basic Lisp Modules,  Up: A Summary of the Various XEmacs Modules
3462
3463 10.3 Modules for Standard Editing Operations
3464 ============================================
3465
3466      buffer.c
3467      buffer.h
3468      bufslots.h
3469
3470    `buffer.c' implements the "buffer" Lisp object type.  This includes
3471 functions that create and destroy buffers; retrieve buffers by name or
3472 by other properties; manipulate lists of buffers (remember that buffers
3473 are permanent objects and stored in various ordered lists); retrieve or
3474 change buffer properties; etc.  It also contains the definitions of all
3475 the built-in buffer-local variables (which can be viewed as buffer
3476 properties).  It does _not_ contain code to manipulate buffer-local
3477 variables (that's in `symbols.c', described above); or code to
3478 manipulate the text in a buffer.
3479
3480    `buffer.h' defines the structures associated with a buffer and the
3481 various macros for retrieving text from a buffer and special buffer
3482 positions (e.g. `point', the default location for text insertion).  It
3483 also contains macros for working with buffer positions and converting
3484 between their representations as character offsets and as byte offsets
3485 (under MULE, they are different, because characters can be multi-byte).
3486 It is one of the largest header files.
3487
3488    `bufslots.h' defines the fields in the buffer structure that
3489 correspond to the built-in buffer-local variables.  It is its own
3490 header file because it is included many times in `buffer.c', as a way
3491 of iterating over all the built-in buffer-local variables.
3492
3493      insdel.c
3494      insdel.h
3495
3496    `insdel.c' contains low-level functions for inserting and deleting
3497 text in a buffer, keeping track of changed regions for use by
3498 redisplay, and calling any before-change and after-change functions
3499 that may have been registered for the buffer.  It also contains the
3500 actual functions that convert between byte offsets and character
3501 offsets.
3502
3503    `insdel.h' contains associated headers.
3504
3505      marker.c
3506
3507    This module implements the "marker" Lisp object type, which
3508 conceptually is a pointer to a text position in a buffer that moves
3509 around as text is inserted and deleted, so as to remain in the same
3510 relative position.  This module doesn't actually move the markers around
3511 - that's handled in `insdel.c'.  This module just creates them and
3512 implements the primitives for working with them.  As markers are simple
3513 objects, this does not entail much.
3514
3515    Note that the standard arithmetic primitives (e.g. `+') accept
3516 markers in place of integers and automatically substitute the value of
3517 `marker-position' for the marker, i.e. an integer describing the
3518 current buffer position of the marker.
3519
3520      extents.c
3521      extents.h
3522
3523    This module implements the "extent" Lisp object type, which is like
3524 a marker that works over a range of text rather than a single position.
3525 Extents are also much more complex and powerful than markers and have a
3526 more efficient (and more algorithmically complex) implementation.  The
3527 implementation is described in detail in comments in `extents.c'.
3528
3529    The code in `extents.c' works closely with `insdel.c' so that
3530 extents are properly moved around as text is inserted and deleted.
3531 There is also code in `extents.c' that provides information needed by
3532 the redisplay mechanism for efficient operation. (Remember that extents
3533 can have display properties that affect [sometimes drastically, as in
3534 the `invisible' property] the display of the text they cover.)
3535
3536      editfns.c
3537
3538    `editfns.c' contains the standard Lisp primitives for working with a
3539 buffer's text, and calls the low-level functions in `insdel.c'.  It
3540 also contains primitives for working with `point' (the default buffer
3541 insertion location).
3542
3543    `editfns.c' also contains functions for retrieving various
3544 characteristics from the external environment: the current time, the
3545 process ID of the running XEmacs process, the name of the user who ran
3546 this XEmacs process, etc.  It's not clear why this code is in
3547 `editfns.c'.
3548
3549      callint.c
3550      cmds.c
3551      commands.h
3552
3553    These modules implement the basic "interactive" commands, i.e.
3554 user-callable functions.  Commands, as opposed to other functions, have
3555 special ways of getting their parameters interactively (by querying the
3556 user), as opposed to having them passed in a normal function
3557 invocation.  Many commands are not really meant to be called from other
3558 Lisp functions, because they modify global state in a way that's often
3559 undesired as part of other Lisp functions.
3560
3561    `callint.c' implements the mechanism for querying the user for
3562 parameters and calling interactive commands.  The bulk of this module is
3563 code that parses the interactive spec that is supplied with an
3564 interactive command.
3565
3566    `cmds.c' implements the basic, most commonly used editing commands:
3567 commands to move around the current buffer and insert and delete
3568 characters.  These commands are implemented using the Lisp primitives
3569 defined in `editfns.c'.
3570
3571    `commands.h' contains associated structure definitions and
3572 prototypes.
3573
3574      regex.c
3575      regex.h
3576      search.c
3577
3578    `search.c' implements the Lisp primitives for searching for text in
3579 a buffer, and some of the low-level algorithms for doing this.  In
3580 particular, the fast fixed-string Boyer-Moore search algorithm is
3581 implemented in `search.c'.  The low-level algorithms for doing
3582 regular-expression searching, however, are implemented in `regex.c' and
3583 `regex.h'.  These two modules are largely independent of XEmacs, and
3584 are similar to (and based upon) the regular-expression routines used in
3585 `grep' and other GNU utilities.
3586
3587      doprnt.c
3588
3589    `doprnt.c' implements formatted-string processing, similar to
3590 `printf()' command in C.
3591
3592      undo.c
3593
3594    This module implements the undo mechanism for tracking buffer
3595 changes.  Most of this could be implemented in Lisp.
3596
3597 \1f
3598 File: internals.info,  Node: Editor-Level Control Flow Modules,  Next: Modules for the Basic Displayable Lisp Objects,  Prev: Modules for Standard Editing Operations,  Up: A Summary of the Various XEmacs Modules
3599
3600 10.4 Editor-Level Control Flow Modules
3601 ======================================
3602
3603      event-Xt.c
3604      event-msw.c
3605      event-stream.c
3606      event-tty.c
3607      events-mod.h
3608      gpmevent.c
3609      gpmevent.h
3610      events.c
3611      events.h
3612
3613    These implement the handling of events (user input and other system
3614 notifications).
3615
3616    `events.c' and `events.h' define the "event" Lisp object type and
3617 primitives for manipulating it.
3618
3619    `event-stream.c' implements the basic functions for working with
3620 event queues, dispatching an event by looking it up in relevant keymaps
3621 and such, and handling timeouts; this includes the primitives
3622 `next-event' and `dispatch-event', as well as related primitives such
3623 as `sit-for', `sleep-for', and `accept-process-output'.
3624 (`event-stream.c' is one of the hairiest and trickiest modules in
3625 XEmacs.  Beware!  You can easily mess things up here.)
3626
3627    `event-Xt.c' and `event-tty.c' implement the low-level interfaces
3628 onto retrieving events from Xt (the X toolkit) and from TTY's (using
3629 `read()' and `select()'), respectively.  The event interface enforces a
3630 clean separation between the specific code for interfacing with the
3631 operating system and the generic code for working with events, by
3632 defining an API of basic, low-level event methods; `event-Xt.c' and
3633 `event-tty.c' are two different implementations of this API.  To add
3634 support for a new operating system (e.g. NeXTstep), one merely needs to
3635 provide another implementation of those API functions.
3636
3637    Note that the choice of whether to use `event-Xt.c' or `event-tty.c'
3638 is made at compile time!  Or at the very latest, it is made at startup
3639 time.  `event-Xt.c' handles events for _both_ X and TTY frames;
3640 `event-tty.c' is only used when X support is not compiled into XEmacs.
3641 The reason for this is that there is only one event loop in XEmacs:
3642 thus, it needs to be able to receive events from all different kinds of
3643 frames.
3644
3645      keymap.c
3646      keymap.h
3647
3648    `keymap.c' and `keymap.h' define the "keymap" Lisp object type and
3649 associated methods and primitives. (Remember that keymaps are objects
3650 that associate event descriptions with functions to be called to
3651 "execute" those events; `dispatch-event' looks up events in the
3652 relevant keymaps.)
3653
3654      cmdloop.c
3655
3656    `cmdloop.c' contains functions that implement the actual editor
3657 command loop--i.e. the event loop that cyclically retrieves and
3658 dispatches events.  This code is also rather tricky, just like
3659 `event-stream.c'.
3660
3661      macros.c
3662      macros.h
3663
3664    These two modules contain the basic code for defining keyboard
3665 macros.  These functions don't actually do much; most of the code that
3666 handles keyboard macros is mixed in with the event-handling code in
3667 `event-stream.c'.
3668
3669      minibuf.c
3670
3671    This contains some miscellaneous code related to the minibuffer
3672 (most of the minibuffer code was moved into Lisp by Richard Mlynarik).
3673 This includes the primitives for completion (although filename
3674 completion is in `dired.c'), the lowest-level interface to the
3675 minibuffer (if the command loop were cleaned up, this too could be in
3676 Lisp), and code for dealing with the echo area (this, too, was mostly
3677 moved into Lisp, and the only code remaining is code to call out to
3678 Lisp or provide simple bootstrapping implementations early in temacs,
3679 before the echo-area Lisp code is loaded).
3680
3681 \1f
3682 File: internals.info,  Node: Modules for the Basic Displayable Lisp Objects,  Next: Modules for other Display-Related Lisp Objects,  Prev: Editor-Level Control Flow Modules,  Up: A Summary of the Various XEmacs Modules
3683
3684 10.5 Modules for the Basic Displayable Lisp Objects
3685 ===================================================
3686
3687      console-msw.c
3688      console-msw.h
3689      console-stream.c
3690      console-stream.h
3691      console-tty.c
3692      console-tty.h
3693      console-x.c
3694      console-x.h
3695      console.c
3696      console.h
3697
3698    These modules implement the "console" Lisp object type.  A console
3699 contains multiple display devices, but only one keyboard and mouse.
3700 Most of the time, a console will contain exactly one device.
3701
3702    Consoles are the top of a lisp object inclusion hierarchy.  Consoles
3703 contain devices, which contain frames, which contain windows.
3704
3705      device-msw.c
3706      device-tty.c
3707      device-x.c
3708      device.c
3709      device.h
3710
3711    These modules implement the "device" Lisp object type.  This
3712 abstracts a particular screen or connection on which frames are
3713 displayed.  As with Lisp objects, event interfaces, and other
3714 subsystems, the device code is separated into a generic component that
3715 contains a standardized interface (in the form of a set of methods) onto
3716 particular device types.
3717
3718    The device subsystem defines all the methods and provides method
3719 services for not only device operations but also for the frame, window,
3720 menubar, scrollbar, toolbar, and other displayable-object subsystems.
3721 The reason for this is that all of these subsystems have the same
3722 subtypes (X, TTY, NeXTstep, Microsoft Windows, etc.) as devices do.
3723
3724      frame-msw.c
3725      frame-tty.c
3726      frame-x.c
3727      frame.c
3728      frame.h
3729
3730    Each device contains one or more frames in which objects (e.g. text)
3731 are displayed.  A frame corresponds to a window in the window system;
3732 usually this is a top-level window but it could potentially be one of a
3733 number of overlapping child windows within a top-level window, using the
3734 MDI (Multiple Document Interface) protocol in Microsoft Windows or a
3735 similar scheme.
3736
3737    The `frame-*' files implement the "frame" Lisp object type and
3738 provide the generic and device-type-specific operations on frames (e.g.
3739 raising, lowering, resizing, moving, etc.).
3740
3741      window.c
3742      window.h
3743
3744    Each frame consists of one or more non-overlapping "windows" (better
3745 known as "panes" in standard window-system terminology) in which a
3746 buffer's text can be displayed.  Windows can also have scrollbars
3747 displayed around their edges.
3748
3749    `window.c' and `window.h' implement the "window" Lisp object type
3750 and provide code to manage windows.  Since windows have no associated
3751 resources in the window system (the window system knows only about the
3752 frame; no child windows or anything are used for XEmacs windows), there
3753 is no device-type-specific code here; all of that code is part of the
3754 redisplay mechanism or the code for particular object types such as
3755 scrollbars.
3756
3757 \1f
3758 File: internals.info,  Node: Modules for other Display-Related Lisp Objects,  Next: Modules for the Redisplay Mechanism,  Prev: Modules for the Basic Displayable Lisp Objects,  Up: A Summary of the Various XEmacs Modules
3759
3760 10.6 Modules for other Display-Related Lisp Objects
3761 ===================================================
3762
3763      faces.c
3764      faces.h
3765
3766      bitmaps.h
3767      glyphs-eimage.c
3768      glyphs-msw.c
3769      glyphs-msw.h
3770      glyphs-widget.c
3771      glyphs-x.c
3772      glyphs-x.h
3773      glyphs.c
3774      glyphs.h
3775
3776      objects-msw.c
3777      objects-msw.h
3778      objects-tty.c
3779      objects-tty.h
3780      objects-x.c
3781      objects-x.h
3782      objects.c
3783      objects.h
3784
3785      menubar-msw.c
3786      menubar-msw.h
3787      menubar-x.c
3788      menubar.c
3789      menubar.h
3790
3791      scrollbar-msw.c
3792      scrollbar-msw.h
3793      scrollbar-x.c
3794      scrollbar-x.h
3795      scrollbar.c
3796      scrollbar.h
3797
3798      toolbar-msw.c
3799      toolbar-x.c
3800      toolbar.c
3801      toolbar.h
3802
3803      font-lock.c
3804
3805    This file provides C support for syntax highlighting--i.e.
3806 highlighting different syntactic constructs of a source file in
3807 different colors, for easy reading.  The C support is provided so that
3808 this is fast.
3809
3810    As of 21.4.10, bugs introduced at the very end of the 21.2 series in
3811 the "syntax properties" code were fixed, and highlighting is acceptably
3812 quick again.  However, presumably more improvements are possible, and
3813 the places to look are probably here, in the defun-traversing code, and
3814 in `syntax.c', in the comment-traversing code.
3815
3816      dgif_lib.c
3817      gif_err.c
3818      gif_lib.h
3819      gifalloc.c
3820
3821    These modules decode GIF-format image files, for use with glyphs.
3822 These files were removed due to Unisys patent infringement concerns.
3823
3824 \1f
3825 File: internals.info,  Node: Modules for the Redisplay Mechanism,  Next: Modules for Interfacing with the File System,  Prev: Modules for other Display-Related Lisp Objects,  Up: A Summary of the Various XEmacs Modules
3826
3827 10.7 Modules for the Redisplay Mechanism
3828 ========================================
3829
3830      redisplay-output.c
3831      redisplay-msw.c
3832      redisplay-tty.c
3833      redisplay-x.c
3834      redisplay.c
3835      redisplay.h
3836
3837    These files provide the redisplay mechanism.  As with many other
3838 subsystems in XEmacs, there is a clean separation between the general
3839 and device-specific support.
3840
3841    `redisplay.c' contains the bulk of the redisplay engine.  These
3842 functions update the redisplay structures (which describe how the screen
3843 is to appear) to reflect any changes made to the state of any
3844 displayable objects (buffer, frame, window, etc.) since the last time
3845 that redisplay was called.  These functions are highly optimized to
3846 avoid doing more work than necessary (since redisplay is called
3847 extremely often and is potentially a huge time sink), and depend heavily
3848 on notifications from the objects themselves that changes have occurred,
3849 so that redisplay doesn't explicitly have to check each possible object.
3850 The redisplay mechanism also contains a great deal of caching to further
3851 speed things up; some of this caching is contained within the various
3852 displayable objects.
3853
3854    `redisplay-output.c' goes through the redisplay structures and
3855 converts them into calls to device-specific methods to actually output
3856 the screen changes.
3857
3858    `redisplay-x.c' and `redisplay-tty.c' are two implementations of
3859 these redisplay output methods, for X frames and TTY frames,
3860 respectively.
3861
3862      indent.c
3863
3864    This module contains various functions and Lisp primitives for
3865 converting between buffer positions and screen positions.  These
3866 functions call the redisplay mechanism to do most of the work, and then
3867 examine the redisplay structures to get the necessary information.  This
3868 module needs work.
3869
3870      termcap.c
3871      terminfo.c
3872      tparam.c
3873
3874    These files contain functions for working with the termcap
3875 (BSD-style) and terminfo (System V style) databases of terminal
3876 capabilities and escape sequences, used when XEmacs is displaying in a
3877 TTY.
3878
3879      cm.c
3880      cm.h
3881
3882    These files provide some miscellaneous TTY-output functions and
3883 should probably be merged into `redisplay-tty.c'.
3884
3885 \1f
3886 File: internals.info,  Node: Modules for Interfacing with the File System,  Next: Modules for Other Aspects of the Lisp Interpreter and Object System,  Prev: Modules for the Redisplay Mechanism,  Up: A Summary of the Various XEmacs Modules
3887
3888 10.8 Modules for Interfacing with the File System
3889 =================================================
3890
3891      lstream.c
3892      lstream.h
3893
3894    These modules implement the "stream" Lisp object type.  This is an
3895 internal-only Lisp object that implements a generic buffering stream.
3896 The idea is to provide a uniform interface onto all sources and sinks of
3897 data, including file descriptors, stdio streams, chunks of memory, Lisp
3898 buffers, Lisp strings, etc.  That way, I/O functions can be written to
3899 the stream interface and can transparently handle all possible sources
3900 and sinks.  (For example, the `read' function can read data from a
3901 file, a string, a buffer, or even a function that is called repeatedly
3902 to return data, without worrying about where the data is coming from or
3903 what-size chunks it is returned in.)
3904
3905    Note that in the C code, streams are called "lstreams" (for "Lisp
3906 streams") to distinguish them from other kinds of streams, e.g. stdio
3907 streams and C++ I/O streams.
3908
3909    Similar to other subsystems in XEmacs, lstreams are separated into
3910 generic functions and a set of methods for the different types of
3911 lstreams.  `lstream.c' provides implementations of many different types
3912 of streams; others are provided, e.g., in `file-coding.c'.
3913
3914      fileio.c
3915
3916    This implements the basic primitives for interfacing with the file
3917 system.  This includes primitives for reading files into buffers,
3918 writing buffers into files, checking for the presence or accessibility
3919 of files, canonicalizing file names, etc.  Note that these primitives
3920 are usually not invoked directly by the user: There is a great deal of
3921 higher-level Lisp code that implements the user commands such as
3922 `find-file' and `save-buffer'.  This is similar to the distinction
3923 between the lower-level primitives in `editfns.c' and the higher-level
3924 user commands in `commands.c' and `simple.el'.
3925
3926      filelock.c
3927
3928    This file provides functions for detecting clashes between different
3929 processes (e.g. XEmacs and some external process, or two different
3930 XEmacs processes) modifying the same file.  (XEmacs can optionally use
3931 the `lock/' subdirectory to provide a form of "locking" between
3932 different XEmacs processes.)  This module is also used by the low-level
3933 functions in `insdel.c' to ensure that, if the first modification is
3934 being made to a buffer whose corresponding file has been externally
3935 modified, the user is made aware of this so that the buffer can be
3936 synched up with the external changes if necessary.
3937
3938      filemode.c
3939
3940    This file provides some miscellaneous functions that construct a
3941 `rwxr-xr-x'-type permissions string (as might appear in an `ls'-style
3942 directory listing) given the information returned by the `stat()'
3943 system call.
3944
3945      dired.c
3946      ndir.h
3947
3948    These files implement the XEmacs interface to directory searching.
3949 This includes a number of primitives for determining the files in a
3950 directory and for doing filename completion. (Remember that generic
3951 completion is handled by a different mechanism, in `minibuf.c'.)
3952
3953    `ndir.h' is a header file used for the directory-searching emulation
3954 functions provided in `sysdep.c' (see section J below), for systems
3955 that don't provide any directory-searching functions. (On those
3956 systems, directories can be read directly as files, and parsed.)
3957
3958      realpath.c
3959
3960    This file provides an implementation of the `realpath()' function
3961 for expanding symbolic links, on systems that don't implement it or have
3962 a broken implementation.
3963
3964 \1f
3965 File: internals.info,  Node: Modules for Other Aspects of the Lisp Interpreter and Object System,  Next: Modules for Interfacing with the Operating System,  Prev: Modules for Interfacing with the File System,  Up: A Summary of the Various XEmacs Modules
3966
3967 10.9 Modules for Other Aspects of the Lisp Interpreter and Object System
3968 ========================================================================
3969
3970      elhash.c
3971      elhash.h
3972      hash.c
3973      hash.h
3974
3975    These files provide two implementations of hash tables.  Files
3976 `hash.c' and `hash.h' provide a generic C implementation of hash tables
3977 which can stand independently of XEmacs.  Files `elhash.c' and
3978 `elhash.h' provide a separate implementation of hash tables that can
3979 store only Lisp objects, and knows about Lispy things like garbage
3980 collection, and implement the "hash-table" Lisp object type.
3981
3982      specifier.c
3983      specifier.h
3984
3985    This module implements the "specifier" Lisp object type.  This is
3986 primarily used for displayable properties, and allows for values that
3987 are specific to a particular buffer, window, frame, device, or device
3988 class, as well as a default value existing.  This is used, for example,
3989 to control the height of the horizontal scrollbar or the appearance of
3990 the `default', `bold', or other faces.  The specifier object consists
3991 of a number of specifications, each of which maps from a buffer,
3992 window, etc. to a value.  The function `specifier-instance' looks up a
3993 value given a window (from which a buffer, frame, and device can be
3994 derived).
3995
3996      chartab.c
3997      chartab.h
3998      casetab.c
3999
4000    `chartab.c' and `chartab.h' implement the "char table" Lisp object
4001 type, which maps from characters or certain sorts of character ranges
4002 to Lisp objects.  The implementation of this object type is optimized
4003 for the internal representation of characters.  Char tables come in
4004 different types, which affect the allowed object types to which a
4005 character can be mapped and also dictate certain other properties of
4006 the char table.
4007
4008    `casetab.c' implements one sort of char table, the "case table",
4009 which maps characters to other characters of possibly different case.
4010 These are used by XEmacs to implement case-changing primitives and to
4011 do case-insensitive searching.
4012
4013      syntax.c
4014      syntax.h
4015
4016    This module implements "syntax tables", another sort of char table
4017 that maps characters into syntax classes that define the syntax of these
4018 characters (e.g. a parenthesis belongs to a class of `open' characters
4019 that have corresponding `close' characters and can be nested).  This
4020 module also implements the Lisp "scanner", a set of primitives for
4021 scanning over text based on syntax tables.  This is used, for example,
4022 to find the matching parenthesis in a command such as `forward-sexp',
4023 and by `font-lock.c' to locate quoted strings, comments, etc.
4024
4025    Syntax codes are implemented as bitfields in an int.  Bits 0-6
4026 contain the syntax code itself, bit 7 is a special prefix flag used for
4027 Lisp, and bits 16-23 contain comment syntax flags.  From the Lisp
4028 programmer's point of view, there are 11 flags: 2 styles X 2 characters
4029 X {start, end} flags for two-character comment delimiters, 2 style
4030 flags for one-character comment delimiters, and the prefix flag.
4031
4032    Internally, however, the characters used in multi-character
4033 delimiters will have non-comment-character syntax classes (_e.g._, the
4034 `/' in C's `/*' comment-start delimiter has "punctuation" (here meaning
4035 "operator-like") class in C modes).  Thus in a mixed comment style,
4036 such as C++'s `//' to end of line, is represented by giving `/' the
4037 "punctuation" class and the "style b first character of start sequence"
4038 and "style b second character of start sequence" flags.  The fact that
4039 class is _not_ punctuation allows the syntax scanner to recognize that
4040 this is a multi-character delimiter.  The `newline' character is given
4041 (single-character) "comment-end" _class_ and the "style b first
4042 character of end sequence" _flag_.  The "comment-end" class allows the
4043 scanner to determine that no second character is needed to terminate
4044 the comment.
4045
4046    There used to be a syntax class `Sextword'.  A character of
4047 `Sextword' class is a word-constituent but a word boundary may exist
4048 between two such characters.  Ken'ichi HANDA <handa@etl.go.jp> explains
4049 the purpose of the Sextword syntax category:
4050
4051      Japanese words are not separated by spaces, which makes finding
4052      word boundaries very difficult.  Theoretically it's impossible
4053      without using natural language processing techniques.  But, by
4054      defining pseudo-words as below (much simplified for letting you
4055      understand it easily) for Japanese, we can have a convenient
4056      forward-word function for Japanese.
4057
4058           A Japanese word is a sequence of characters that consists of
4059           zero or more Kanji characters followed by zero or more
4060           Hiragana characters.
4061
4062      Then, the problem is that now we can't say that a sequence of
4063      word-constituents makes up a word.  For instance, both Hiragana "A"
4064      and Kanji "KAN" are word-constituents but the sequence of these two
4065      letters can't be a single word.
4066
4067      So, we introduced Sextword for Japanese letters.
4068
4069    There seems to have been some controversy about this category, as it
4070 has been removed, readded, and removed again.  Currently neither GNU
4071 Emacs (21.3.99) nor XEmacs (21.5.17) seems to use it.
4072
4073      casefiddle.c
4074
4075    This module implements various Lisp primitives for upcasing,
4076 downcasing and capitalizing strings or regions of buffers.
4077
4078      rangetab.c
4079
4080    This module implements the "range table" Lisp object type, which
4081 provides for a mapping from ranges of integers to arbitrary Lisp
4082 objects.
4083
4084      opaque.c
4085      opaque.h
4086
4087    This module implements the "opaque" Lisp object type, an
4088 internal-only Lisp object that encapsulates an arbitrary block of memory
4089 so that it can be managed by the Lisp allocation system.  To create an
4090 opaque object, you call `make_opaque()', passing a pointer to a block
4091 of memory.  An object is created that is big enough to hold the memory,
4092 which is copied into the object's storage.  The object will then stick
4093 around as long as you keep pointers to it, after which it will be
4094 automatically reclaimed.
4095
4096    Opaque objects can also have an arbitrary "mark method" associated
4097 with them, in case the block of memory contains other Lisp objects that
4098 need to be marked for garbage-collection purposes. (If you need other
4099 object methods, such as a finalize method, you should just go ahead and
4100 create a new Lisp object type--it's not hard.)
4101
4102      abbrev.c
4103
4104    This function provides a few primitives for doing dynamic
4105 abbreviation expansion.  In XEmacs, most of the code for this has been
4106 moved into Lisp.  Some C code remains for speed and because the
4107 primitive `self-insert-command' (which is executed for all
4108 self-inserting characters) hooks into the abbrev mechanism.
4109 (`self-insert-command' is itself in C only for speed.)
4110
4111      doc.c
4112
4113    This function provides primitives for retrieving the documentation
4114 strings of functions and variables.  These documentation strings contain
4115 certain special markers that get dynamically expanded (e.g. a
4116 reverse-lookup is performed on some named functions to retrieve their
4117 current key bindings).  Some documentation strings (in particular, for
4118 the built-in primitives and pre-loaded Lisp functions) are stored
4119 externally in a file `DOC' in the `lib-src/' directory and need to be
4120 fetched from that file. (Part of the build stage involves building this
4121 file, and another part involves constructing an index for this file and
4122 embedding it into the executable, so that the functions in `doc.c' do
4123 not have to search the entire `DOC' file to find the appropriate
4124 documentation string.)
4125
4126      md5.c
4127
4128    This function provides a Lisp primitive that implements the MD5
4129 secure hashing scheme, used to create a large hash value of a string of
4130 data such that the data cannot be derived from the hash value.  This is
4131 used for various security applications on the Internet.
4132
4133 \1f
4134 File: internals.info,  Node: Modules for Interfacing with the Operating System,  Next: Modules for Interfacing with X Windows,  Prev: Modules for Other Aspects of the Lisp Interpreter and Object System,  Up: A Summary of the Various XEmacs Modules
4135
4136 10.10 Modules for Interfacing with the Operating System
4137 =======================================================
4138
4139      callproc.c
4140      process.c
4141      process.h
4142
4143    These modules allow XEmacs to spawn and communicate with subprocesses
4144 and network connections.
4145
4146    `callproc.c' implements (through the `call-process' primitive) what
4147 are called "synchronous subprocesses".  This means that XEmacs runs a
4148 program, waits till it's done, and retrieves its output.  A typical
4149 example might be calling the `ls' program to get a directory listing.
4150
4151    `process.c' and `process.h' implement "asynchronous subprocesses".
4152 This means that XEmacs starts a program and then continues normally,
4153 not waiting for the process to finish.  Data can be sent to the process
4154 or retrieved from it as it's running.  This is used for the `shell'
4155 command (which provides a front end onto a shell program such as
4156 `csh'), the mail and news readers implemented in XEmacs, etc.  The
4157 result of calling `start-process' to start a subprocess is a process
4158 object, a particular kind of object used to communicate with the
4159 subprocess.  You can send data to the process by passing the process
4160 object and the data to `send-process', and you can specify what happens
4161 to data retrieved from the process by setting properties of the process
4162 object. (When the process sends data, XEmacs receives a process event,
4163 which says that there is data ready.  When `dispatch-event' is called
4164 on this event, it reads the data from the process and does something
4165 with it, as specified by the process object's properties.  Typically,
4166 this means inserting the data into a buffer or calling a function.)
4167 Another property of the process object is called the "sentinel", which
4168 is a function that is called when the process terminates.
4169
4170    Process objects are also used for network connections (connections
4171 to a process running on another machine).  Network connections are
4172 started with `open-network-stream' but otherwise work just like
4173 subprocesses.
4174
4175      sysdep.c
4176      sysdep.h
4177
4178    These modules implement most of the low-level, messy operating-system
4179 interface code.  This includes various device control (ioctl) operations
4180 for file descriptors, TTY's, pseudo-terminals, etc. (usually this stuff
4181 is fairly system-dependent; thus the name of this module), and emulation
4182 of standard library functions and system calls on systems that don't
4183 provide them or have broken versions.
4184
4185      sysdir.h
4186      sysfile.h
4187      sysfloat.h
4188      sysproc.h
4189      syspwd.h
4190      syssignal.h
4191      systime.h
4192      systty.h
4193      syswait.h
4194
4195    These header files provide consistent interfaces onto
4196 system-dependent header files and system calls.  The idea is that,
4197 instead of including a standard header file like `<sys/param.h>' (which
4198 may or may not exist on various systems) or having to worry about
4199 whether all system provide a particular preprocessor constant, or
4200 having to deal with the four different paradigms for manipulating
4201 signals, you just include the appropriate `sys*.h' header file, which
4202 includes all the right system header files, defines and missing
4203 preprocessor constants, provides a uniform interface onto system calls,
4204 etc.
4205
4206    `sysdir.h' provides a uniform interface onto directory-querying
4207 functions. (In some cases, this is in conjunction with emulation
4208 functions in `sysdep.c'.)
4209
4210    `sysfile.h' includes all the necessary header files for standard
4211 system calls (e.g. `read()'), ensures that all necessary `open()' and
4212 `stat()' preprocessor constants are defined, and possibly (usually)
4213 substitutes sugared versions of `read()', `write()', etc. that
4214 automatically restart interrupted I/O operations.
4215
4216    `sysfloat.h' includes the necessary header files for floating-point
4217 operations.
4218
4219    `sysproc.h' includes the necessary header files for calling
4220 `select()', `fork()', `execve()', socket operations, and the like, and
4221 ensures that the `FD_*()' macros for descriptor-set manipulations are
4222 available.
4223
4224    `syspwd.h' includes the necessary header files for obtaining
4225 information from `/etc/passwd' (the functions are emulated under VMS).
4226
4227    `syssignal.h' includes the necessary header files for
4228 signal-handling and provides a uniform interface onto the different
4229 signal-handling and signal-blocking paradigms.
4230
4231    `systime.h' includes the necessary header files and provides uniform
4232 interfaces for retrieving the time of day, setting file
4233 access/modification times, getting the amount of time used by the XEmacs
4234 process, etc.
4235
4236    `systty.h' buffers against the infinitude of different ways of
4237 controlling TTY's.
4238
4239    `syswait.h' provides a uniform way of retrieving the exit status
4240 from a `wait()'ed-on process (some systems use a union, others use an
4241 int).
4242
4243      hpplay.c
4244      libsst.c
4245      libsst.h
4246      libst.h
4247      linuxplay.c
4248      nas.c
4249      sgiplay.c
4250      sound.c
4251      sunplay.c
4252
4253    These files implement the ability to play various sounds on some
4254 types of computers.  You have to configure your XEmacs with sound
4255 support in order to get this capability.
4256
4257    `sound.c' provides the generic interface.  It implements various
4258 Lisp primitives and variables that let you specify which sounds should
4259 be played in certain conditions. (The conditions are identified by
4260 symbols, which are passed to `ding' to make a sound.  Various standard
4261 functions call this function at certain times; if sound support does
4262 not exist, a simple beep results.
4263
4264    `sgiplay.c', `sunplay.c', `hpplay.c', and `linuxplay.c' interface to
4265 the machine's speaker for various different kind of machines.  This is
4266 called "native" sound.
4267
4268    `nas.c' interfaces to a computer somewhere else on the network using
4269 the NAS (Network Audio Server) protocol, playing sounds on that
4270 machine.  This allows you to run XEmacs on a remote machine, with its
4271 display set to your local machine, and have the sounds be made on your
4272 local machine, provided that you have a NAS server running on your local
4273 machine.
4274
4275    `libsst.c', `libsst.h', and `libst.h' provide some additional
4276 functions for playing sound on a Sun SPARC but are not currently in use.
4277
4278      tooltalk.c
4279      tooltalk.h
4280
4281    These two modules implement an interface to the ToolTalk protocol,
4282 which is an interprocess communication protocol implemented on some
4283 versions of Unix.  ToolTalk is a high-level protocol that allows
4284 processes to register themselves as providers of particular services;
4285 other processes can then request a service without knowing or caring
4286 exactly who is providing the service.  It is similar in spirit to the
4287 DDE protocol provided under Microsoft Windows.  ToolTalk is a part of
4288 the new CDE (Common Desktop Environment) specification and is used to
4289 connect the parts of the SPARCWorks development environment.
4290
4291      getloadavg.c
4292
4293    This module provides the ability to retrieve the system's current
4294 load average. (The way to do this is highly system-specific,
4295 unfortunately, and requires a lot of special-case code.)
4296
4297      sunpro.c
4298
4299    This module provides a small amount of code used internally at Sun to
4300 keep statistics on the usage of XEmacs.
4301
4302      broken-sun.h
4303      strcmp.c
4304      strcpy.c
4305      sunOS-fix.c
4306
4307    These files provide replacement functions and prototypes to fix
4308 numerous bugs in early releases of SunOS 4.1.
4309
4310      hftctl.c
4311
4312    This module provides some terminal-control code necessary on
4313 versions of AIX prior to 4.1.
4314
4315 \1f
4316 File: internals.info,  Node: Modules for Interfacing with X Windows,  Next: Modules for Internationalization,  Prev: Modules for Interfacing with the Operating System,  Up: A Summary of the Various XEmacs Modules
4317
4318 10.11 Modules for Interfacing with X Windows
4319 ============================================
4320
4321      Emacs.ad.h
4322
4323    A file generated from `Emacs.ad', which contains XEmacs-supplied
4324 fallback resources (so that XEmacs has pretty defaults).
4325
4326      EmacsFrame.c
4327      EmacsFrame.h
4328      EmacsFrameP.h
4329
4330    These modules implement an Xt widget class that encapsulates a frame.
4331 This is for ease in integrating with Xt.  The EmacsFrame widget covers
4332 the entire X window except for the menubar; the scrollbars are
4333 positioned on top of the EmacsFrame widget.
4334
4335    *Warning:* Abandon hope, all ye who enter here.  This code took an
4336 ungodly amount of time to get right, and is likely to fall apart
4337 mercilessly at the slightest change.  Such is life under Xt.
4338
4339      EmacsManager.c
4340      EmacsManager.h
4341      EmacsManagerP.h
4342
4343    These modules implement a simple Xt manager (i.e. composite) widget
4344 class that simply lets its children set whatever geometry they want.
4345 It's amazing that Xt doesn't provide this standardly, but on second
4346 thought, it makes sense, considering how amazingly broken Xt is.
4347
4348      EmacsShell-sub.c
4349      EmacsShell.c
4350      EmacsShell.h
4351      EmacsShellP.h
4352
4353    These modules implement two Xt widget classes that are subclasses of
4354 the TopLevelShell and TransientShell classes.  This is necessary to deal
4355 with more brokenness that Xt has sadistically thrust onto the backs of
4356 developers.
4357
4358      xgccache.c
4359      xgccache.h
4360
4361    These modules provide functions for maintenance and caching of GC's
4362 (graphics contexts) under the X Window System.  This code is junky and
4363 needs to be rewritten.
4364
4365      select-msw.c
4366      select-x.c
4367      select.c
4368      select.h
4369
4370    This module provides an interface to the X Window System's concept of
4371 "selections", the standard way for X applications to communicate with
4372 each other.
4373
4374      xintrinsic.h
4375      xintrinsicp.h
4376      xmmanagerp.h
4377      xmprimitivep.h
4378
4379    These header files are similar in spirit to the `sys*.h' files and
4380 buffer against different implementations of Xt and Motif.
4381
4382    * `xintrinsic.h' should be included in place of `<Intrinsic.h>'.
4383
4384    * `xintrinsicp.h' should be included in place of `<IntrinsicP.h>'.
4385
4386    * `xmmanagerp.h' should be included in place of `<XmManagerP.h>'.
4387
4388    * `xmprimitivep.h' should be included in place of `<XmPrimitiveP.h>'.
4389
4390      xmu.c
4391      xmu.h
4392
4393    These files provide an emulation of the Xmu library for those systems
4394 (i.e. HPUX) that don't provide it as a standard part of X.
4395
4396      ExternalClient-Xlib.c
4397      ExternalClient.c
4398      ExternalClient.h
4399      ExternalClientP.h
4400      ExternalShell.c
4401      ExternalShell.h
4402      ExternalShellP.h
4403      extw-Xlib.c
4404      extw-Xlib.h
4405      extw-Xt.c
4406      extw-Xt.h
4407
4408    These files provide the "external widget" interface, which allows an
4409 XEmacs frame to appear as a widget in another application.  To do this,
4410 you have to configure with `--external-widget'.
4411
4412    `ExternalShell*' provides the server (XEmacs) side of the connection.
4413
4414    `ExternalClient*' provides the client (other application) side of
4415 the connection.  These files are not compiled into XEmacs but are
4416 compiled into libraries that are then linked into your application.
4417
4418    `extw-*' is common code that is used for both the client and server.
4419
4420    Don't touch this code; something is liable to break if you do.
4421
4422 \1f
4423 File: internals.info,  Node: Modules for Internationalization,  Next: Modules for Regression Testing,  Prev: Modules for Interfacing with X Windows,  Up: A Summary of the Various XEmacs Modules
4424
4425 10.12 Modules for Internationalization
4426 ======================================
4427
4428      mule-canna.c
4429      mule-ccl.c
4430      mule-charset.c
4431      mule-charset.h
4432      file-coding.c
4433      file-coding.h
4434      mule-mcpath.c
4435      mule-mcpath.h
4436      mule-wnnfns.c
4437      mule.c
4438
4439    These files implement the MULE (Asian-language) support.  Note that
4440 MULE actually provides a general interface for all sorts of languages,
4441 not just Asian languages (although they are generally the most
4442 complicated to support).  This code is still in beta.
4443
4444    `mule-charset.*' and `file-coding.*' provide the heart of the XEmacs
4445 MULE support.  `mule-charset.*' implements the "charset" Lisp object
4446 type, which encapsulates a character set (an ordered one- or
4447 two-dimensional set of characters, such as US ASCII or JISX0208 Japanese
4448 Kanji).
4449
4450    `file-coding.*' implements the "coding-system" Lisp object type,
4451 which encapsulates a method of converting between different encodings.
4452 An encoding is a representation of a stream of characters, possibly
4453 from multiple character sets, using a stream of bytes or words, and
4454 defines (e.g.) which escape sequences are used to specify particular
4455 character sets, how the indices for a character are converted into bytes
4456 (sometimes this involves setting the high bit; sometimes complicated
4457 rearranging of the values takes place, as in the Shift-JIS encoding),
4458 etc.
4459
4460    `mule-ccl.c' provides the CCL (Code Conversion Language)
4461 interpreter.  CCL is similar in spirit to Lisp byte code and is used to
4462 implement converters for custom encodings.
4463
4464    `mule-canna.c' and `mule-wnnfns.c' implement interfaces to external
4465 programs used to implement the Canna and WNN input methods,
4466 respectively.  This is currently in beta.
4467
4468    `mule-mcpath.c' provides some functions to allow for pathnames
4469 containing extended characters.  This code is fragmentary, obsolete, and
4470 completely non-working.  Instead, `pathname-coding-system' is used to
4471 specify conversions of names of files and directories.  The standard C
4472 I/O functions like `open()' are wrapped so that conversion occurs
4473 automatically.
4474
4475    `mule.c' contains a few miscellaneous things.  It currently seems to
4476 be unused and probably should be removed.
4477
4478      intl.c
4479
4480    This provides some miscellaneous internationalization code for
4481 implementing message translation and interfacing to the Ximp input
4482 method.  None of this code is currently working.
4483
4484      iso-wide.h
4485
4486    This contains leftover code from an earlier implementation of
4487 Asian-language support, and is not currently used.
4488
4489 \1f
4490 File: internals.info,  Node: Modules for Regression Testing,  Prev: Modules for Internationalization,  Up: A Summary of the Various XEmacs Modules
4491
4492 10.13 Modules for Regression Testing
4493 ====================================
4494
4495      test-harness.el
4496      base64-tests.el
4497      byte-compiler-tests.el
4498      case-tests.el
4499      ccl-tests.el
4500      c-tests.el
4501      database-tests.el
4502      extent-tests.el
4503      hash-table-tests.el
4504      lisp-tests.el
4505      md5-tests.el
4506      mule-tests.el
4507      regexp-tests.el
4508      symbol-tests.el
4509      syntax-tests.el
4510      tag-tests.el
4511
4512    `test-harness.el' defines the macros `Assert', `Check-Error',
4513 `Check-Error-Message', and `Check-Message'.  The other files are test
4514 files, testing various XEmacs modules.
4515
4516 \1f
4517 File: internals.info,  Node: Allocation of Objects in XEmacs Lisp,  Next: Dumping,  Prev: A Summary of the Various XEmacs Modules,  Up: Top
4518
4519 11 Allocation of Objects in XEmacs Lisp
4520 ***************************************
4521
4522 * Menu:
4523
4524 * Introduction to Allocation::
4525 * Garbage Collection::
4526 * GCPROing::
4527 * Garbage Collection - Step by Step::
4528 * Integers and Characters::
4529 * Allocation from Frob Blocks::
4530 * lrecords::
4531 * Low-level allocation::
4532 * Cons::
4533 * Vector::
4534 * Bit Vector::
4535 * Symbol::
4536 * Marker::
4537 * String::
4538 * Compiled Function::
4539
4540 \1f
4541 File: internals.info,  Node: Introduction to Allocation,  Next: Garbage Collection,  Up: Allocation of Objects in XEmacs Lisp
4542
4543 11.1 Introduction to Allocation
4544 ===============================
4545
4546 Emacs Lisp, like all Lisps, has garbage collection.  This means that
4547 the programmer never has to explicitly free (destroy) an object; it
4548 happens automatically when the object becomes inaccessible.  Most
4549 experts agree that garbage collection is a necessity in a modern,
4550 high-level language.  Its omission from C stems from the fact that C was
4551 originally designed to be a nice abstract layer on top of assembly
4552 language, for writing kernels and basic system utilities rather than
4553 large applications.
4554
4555    Lisp objects can be created by any of a number of Lisp primitives.
4556 Most object types have one or a small number of basic primitives for
4557 creating objects.  For conses, the basic primitive is `cons'; for
4558 vectors, the primitives are `make-vector' and `vector'; for symbols,
4559 the primitives are `make-symbol' and `intern'; etc.  Some Lisp objects,
4560 especially those that are primarily used internally, have no
4561 corresponding Lisp primitives.  Every Lisp object, though, has at least
4562 one C primitive for creating it.
4563
4564    Recall from section (VII) that a Lisp object, as stored in a 32-bit
4565 or 64-bit word, has a few tag bits, and a "value" that occupies the
4566 remainder of the bits.  We can separate the different Lisp object types
4567 into three broad categories:
4568
4569    * (a) Those for whom the value directly represents the contents of
4570      the Lisp object.  Only two types are in this category: integers and
4571      characters.  No special allocation or garbage collection is
4572      necessary for such objects.  Lisp objects of these types do not
4573      need to be `GCPRO'ed.
4574
4575    In the remaining two categories, the type is stored in the object
4576 itself.  The tag for all such objects is the generic "lrecord"
4577 (Lisp_Type_Record) tag.  The first bytes of the object's structure are
4578 an integer (actually a char) characterising the object's type and some
4579 flags, in particular the mark bit used for garbage collection.  A
4580 structure describing the type is accessible thru the
4581 lrecord_implementation_table indexed with said integer.  This structure
4582 includes the method pointers and a pointer to a string naming the type.
4583
4584    * (b) Those lrecords that are allocated in frob blocks (see above).
4585      This includes the objects that are most common and relatively
4586      small, and includes conses, strings, subrs, floats, compiled
4587      functions, symbols, extents, events, and markers.  With the
4588      cleanup of frob blocks done in 19.12, it's not terribly hard to
4589      add more objects to this category, but it's a bit trickier than
4590      adding an object type to type (c) (esp. if the object needs a
4591      finalization method), and is not likely to save much space unless
4592      the object is small and there are many of them. (In fact, if there
4593      are very few of them, it might actually waste space.)
4594
4595    * (c) Those lrecords that are individually `malloc()'ed.  These are
4596      called "lcrecords".  All other types are in this category.  Adding
4597      a new type to this category is comparatively easy, and all types
4598      added since 19.8 (when the current allocation scheme was devised,
4599      by Richard Mlynarik), with the exception of the character type,
4600      have been in this category.
4601
4602    Note that bit vectors are a bit of a special case.  They are simple
4603 lrecords as in category (b), but are individually `malloc()'ed like
4604 vectors.  You can basically view them as exactly like vectors except
4605 that their type is stored in lrecord fashion rather than in
4606 directly-tagged fashion.
4607
4608 \1f
4609 File: internals.info,  Node: Garbage Collection,  Next: GCPROing,  Prev: Introduction to Allocation,  Up: Allocation of Objects in XEmacs Lisp
4610
4611 11.2 Garbage Collection
4612 =======================
4613
4614 Garbage collection is simple in theory but tricky to implement.  Emacs
4615 Lisp uses the oldest garbage collection method, called "mark and
4616 sweep".  Garbage collection begins by starting with all accessible
4617 locations (i.e. all variables and other slots where Lisp objects might
4618 occur) and recursively traversing all objects accessible from those
4619 slots, marking each one that is found.  We then go through all of
4620 memory and free each object that is not marked, and unmarking each
4621 object that is marked.  Note that "all of memory" means all currently
4622 allocated objects.  Traversing all these objects means traversing all
4623 frob blocks, all vectors (which are chained in one big list), and all
4624 lcrecords (which are likewise chained).
4625
4626    Garbage collection can be invoked explicitly by calling
4627 `garbage-collect' but is also called automatically by `eval', once a
4628 certain amount of memory has been allocated since the last garbage
4629 collection (according to `gc-cons-threshold').
4630
4631 \1f
4632 File: internals.info,  Node: GCPROing,  Next: Garbage Collection - Step by Step,  Prev: Garbage Collection,  Up: Allocation of Objects in XEmacs Lisp
4633
4634 11.3 `GCPRO'ing
4635 ===============
4636
4637 `GCPRO'ing is one of the ugliest and trickiest parts of Emacs
4638 internals.  The basic idea is that whenever garbage collection occurs,
4639 all in-use objects must be reachable somehow or other from one of the
4640 roots of accessibility.  The roots of accessibility are:
4641
4642   1. All objects that have been `staticpro()'d or
4643      `staticpro_nodump()'ed.  This is used for any global C variables
4644      that hold Lisp objects.  A call to `staticpro()' happens implicitly
4645      as a result of any symbols declared with `defsymbol()' and any
4646      variables declared with `DEFVAR_FOO()'.  You need to explicitly
4647      call `staticpro()' (in the `vars_of_foo()' method of a module) for
4648      other global C variables holding Lisp objects. (This typically
4649      includes internal lists and such things.).  Use
4650      `staticpro_nodump()' only in the rare cases when you do not want
4651      the pointed variable to be saved at dump time but rather recompute
4652      it at startup.
4653
4654      Note that `obarray' is one of the `staticpro()'d things.
4655      Therefore, all functions and variables get marked through this.
4656
4657   2. Any shadowed bindings that are sitting on the `specpdl' stack.
4658
4659   3. Any objects sitting in currently active (Lisp) stack frames,
4660      catches, and condition cases.
4661
4662   4. A couple of special-case places where active objects are located.
4663
4664   5. Anything currently marked with `GCPRO'.
4665
4666    Marking with `GCPRO' is necessary because some C functions (quite a
4667 lot, in fact), allocate objects during their operation.  Quite
4668 frequently, there will be no other pointer to the object while the
4669 function is running, and if a garbage collection occurs and the object
4670 needs to be referenced again, bad things will happen.  The solution is
4671 to mark those objects with `GCPRO'.  Unfortunately this is easy to
4672 forget, and there is basically no way around this problem.  Here are
4673 some rules, though:
4674
4675   1. For every `GCPRON', there have to be declarations of `struct gcpro
4676      gcpro1, gcpro2', etc.
4677
4678   2. You _must_ `UNGCPRO' anything that's `GCPRO'ed, and you _must not_
4679      `UNGCPRO' if you haven't `GCPRO'ed.  Getting either of these wrong
4680      will lead to crashes, often in completely random places unrelated
4681      to where the problem lies.
4682
4683   3. The way this actually works is that all currently active `GCPRO's
4684      are chained through the `struct gcpro' local variables, with the
4685      variable `gcprolist' pointing to the head of the list and the nth
4686      local `gcpro' variable pointing to the first `gcpro' variable in
4687      the next enclosing stack frame.  Each `GCPRO'ed thing is an
4688      lvalue, and the `struct gcpro' local variable contains a pointer to
4689      this lvalue.  This is why things will mess up badly if you don't
4690      pair up the `GCPRO's and `UNGCPRO's--you will end up with
4691      `gcprolist's containing pointers to `struct gcpro's or local
4692      `Lisp_Object' variables in no-longer-active stack frames.
4693
4694   4. It is actually possible for a single `struct gcpro' to protect a
4695      contiguous array of any number of values, rather than just a
4696      single lvalue.  To effect this, call `GCPRON' as usual on the
4697      first object in the array and then set `gcproN.nvars'.
4698
4699   5. *Strings are relocated.*  What this means in practice is that the
4700      pointer obtained using `XSTRING_DATA()' is liable to change at any
4701      time, and you should never keep it around past any function call,
4702      or pass it as an argument to any function that might cause a
4703      garbage collection.  This is why a number of functions accept
4704      either a "non-relocatable" `char *' pointer or a relocatable Lisp
4705      string, and only access the Lisp string's data at the very last
4706      minute.  In some cases, you may end up having to `alloca()' some
4707      space and copy the string's data into it.
4708
4709   6. By convention, if you have to nest `GCPRO''s, use `NGCPRON' (along
4710      with `struct gcpro ngcpro1, ngcpro2', etc.), `NNGCPRON', etc.
4711      This avoids compiler warnings about shadowed locals.
4712
4713   7. It is _always_ better to err on the side of extra `GCPRO's rather
4714      than too few.  The extra cycles spent on this are almost never
4715      going to make a whit of difference in the speed of anything.
4716
4717   8. The general rule to follow is that caller, not callee, `GCPRO's.
4718      That is, you should not have to explicitly `GCPRO' any Lisp objects
4719      that are passed in as parameters.
4720
4721      One exception from this rule is if you ever plan to change the
4722      parameter value, and store a new object in it.  In that case, you
4723      _must_ `GCPRO' the parameter, because otherwise the new object
4724      will not be protected.
4725
4726      So, if you create any Lisp objects (remember, this happens in all
4727      sorts of circumstances, e.g. with `Fcons()', etc.), you are
4728      responsible for `GCPRO'ing them, unless you are _absolutely sure_
4729      that there's no possibility that a garbage-collection can occur
4730      while you need to use the object.  Even then, consider `GCPRO'ing.
4731
4732   9. A garbage collection can occur whenever anything calls `Feval', or
4733      whenever a QUIT can occur where execution can continue past this.
4734      (Remember, this is almost anywhere.)
4735
4736  10. If you have the _least smidgeon of doubt_ about whether you need
4737      to `GCPRO', you should `GCPRO'.
4738
4739  11. Beware of `GCPRO'ing something that is uninitialized.  If you have
4740      any shade of doubt about this, initialize all your variables to
4741      `Qnil'.
4742
4743  12. Be careful of traps, like calling `Fcons()' in the argument to
4744      another function.  By the "caller protects" law, you should be
4745      `GCPRO'ing the newly-created cons, but you aren't.  A certain
4746      number of functions that are commonly called on freshly created
4747      stuff (e.g. `nconc2()', `Fsignal()'), break the "caller protects"
4748      law and go ahead and `GCPRO' their arguments so as to simplify
4749      things, but make sure and check if it's OK whenever doing
4750      something like this.
4751
4752  13. Once again, remember to `GCPRO'!  Bugs resulting from insufficient
4753      `GCPRO'ing are intermittent and extremely difficult to track down,
4754      often showing up in crashes inside of `garbage-collect' or in
4755      weirdly corrupted objects or even in incorrect values in a totally
4756      different section of code.
4757
4758    If you don't understand whether to `GCPRO' in a particular instance,
4759 ask on the mailing lists.  A general hint is that `prog1' is the
4760 canonical example.
4761
4762    Given the extremely error-prone nature of the `GCPRO' scheme, and
4763 the difficulties in tracking down, it should be considered a deficiency
4764 in the XEmacs code.  A solution to this problem would involve
4765 implementing so-called "conservative" garbage collection for the C
4766 stack.  That involves looking through all of stack memory and treating
4767 anything that looks like a reference to an object as a reference.  This
4768 will result in a few objects not getting collected when they should, but
4769 it obviates the need for `GCPRO'ing, and allows garbage collection to
4770 happen at any point at all, such as during object allocation.
4771
4772 \1f
4773 File: internals.info,  Node: Garbage Collection - Step by Step,  Next: Integers and Characters,  Prev: GCPROing,  Up: Allocation of Objects in XEmacs Lisp
4774
4775 11.4 Garbage Collection - Step by Step
4776 ======================================
4777
4778 * Menu:
4779
4780 * Invocation::
4781 * garbage_collect_1::
4782 * mark_object::
4783 * gc_sweep::
4784 * sweep_lcrecords_1::
4785 * compact_string_chars::
4786 * sweep_strings::
4787 * sweep_bit_vectors_1::
4788
4789 \1f
4790 File: internals.info,  Node: Invocation,  Next: garbage_collect_1,  Up: Garbage Collection - Step by Step
4791
4792 11.4.1 Invocation
4793 -----------------
4794
4795 The first thing that anyone should know about garbage collection is:
4796 when and how the garbage collector is invoked. One might think that this
4797 could happen every time new memory is allocated, e.g. new objects are
4798 created, but this is _not_ the case. Instead, we have the following
4799 situation:
4800
4801    The entry point of any process of garbage collection is an invocation
4802 of the function `garbage_collect_1' in file `alloc.c'. The invocation
4803 can occur _explicitly_ by calling the function `Fgarbage_collect' (in
4804 addition this function provides information about the freed memory), or
4805 can occur _implicitly_ in four different situations:
4806   1. In function `main_1' in file `emacs.c'. This function is called at
4807      each startup of xemacs. The garbage collection is invoked after all
4808      initial creations are completed, but only if a special internal
4809      error checking-constant `ERROR_CHECK_GC' is defined.
4810
4811   2. In function `disksave_object_finalization' in file `alloc.c'. The
4812      only purpose of this function is to clear the objects from memory
4813      which need not be stored with xemacs when we dump out an
4814      executable. This is only done by `Fdump_emacs' or by
4815      `Fdump_emacs_data' respectively (both in `emacs.c'). The actual
4816      clearing is accomplished by making these objects unreachable and
4817      starting a garbage collection. The function is only used while
4818      building xemacs.
4819
4820   3. In function `Feval / eval' in file `eval.c'. Each time the well
4821      known and often used function eval is called to evaluate a form,
4822      one of the first things that could happen, is a potential call of
4823      `garbage_collect_1'. There exist three global variables,
4824      `consing_since_gc' (counts the created cons-cells since the last
4825      garbage collection), `gc_cons_threshold' (a specified threshold
4826      after which a garbage collection occurs) and `always_gc'. If
4827      `always_gc' is set or if the threshold is exceeded, the garbage
4828      collection will start.
4829
4830   4. In function `Ffuncall / funcall' in file `eval.c'. This function
4831      evaluates calls of elisp functions and works according to `Feval'.
4832
4833    The upshot is that garbage collection can basically occur everywhere
4834 `Feval', respectively `Ffuncall', is used - either directly or through
4835 another function. Since calls to these two functions are hidden in
4836 various other functions, many calls to `garbage_collect_1' are not
4837 obviously foreseeable, and therefore unexpected. Instances where they
4838 are used that are worth remembering are various elisp commands, as for
4839 example `or', `and', `if', `cond', `while', `setq', etc., miscellaneous
4840 `gui_item_...' functions, everything related to `eval' (`Feval_buffer',
4841 `call0', ...) and inside `Fsignal'. The latter is used to handle
4842 signals, as for example the ones raised by every `QUIT'-macro triggered
4843 after pressing Ctrl-g.
4844
4845 \1f
4846 File: internals.info,  Node: garbage_collect_1,  Next: mark_object,  Prev: Invocation,  Up: Garbage Collection - Step by Step
4847
4848 11.4.2 `garbage_collect_1'
4849 --------------------------
4850
4851 We can now describe exactly what happens after the invocation takes
4852 place.
4853   1. There are several cases in which the garbage collector is left
4854      immediately: when we are already garbage collecting
4855      (`gc_in_progress'), when the garbage collection is somehow
4856      forbidden (`gc_currently_forbidden'), when we are currently
4857      displaying something (`in_display') or when we are preparing for
4858      the armageddon of the whole system (`preparing_for_armageddon').
4859
4860   2. Next the correct frame in which to put all the output occurring
4861      during garbage collecting is determined. In order to be able to
4862      restore the old display's state after displaying the message, some
4863      data about the current cursor position has to be saved. The
4864      variables `pre_gc_cursor' and `cursor_changed' take care of that.
4865
4866   3. The state of `gc_currently_forbidden' must be restored after the
4867      garbage collection, no matter what happens during the process. We
4868      accomplish this by `record_unwind_protect'ing the suitable function
4869      `restore_gc_inhibit' together with the current value of
4870      `gc_currently_forbidden'.
4871
4872   4. If we are concurrently running an interactive xemacs session, the
4873      next step is simply to show the garbage collector's cursor/message.
4874
4875   5. The following steps are the intrinsic steps of the garbage
4876      collector, therefore `gc_in_progress' is set.
4877
4878   6. For debugging purposes, it is possible to copy the current C stack
4879      frame. However, this seems to be a currently unused feature.
4880
4881   7. Before actually starting to go over all live objects, references to
4882      objects that are no longer used are pruned. We only have to do
4883      this for events (`clear_event_resource') and for specifiers
4884      (`cleanup_specifiers').
4885
4886   8. Now the mark phase begins and marks all accessible elements. In
4887      order to start from all slots that serve as roots of
4888      accessibility, the function `mark_object' is called for each root
4889      individually to go out from there to mark all reachable objects.
4890      All roots that are traversed are shown in their processed order:
4891         * all constant symbols and static variables that are registered
4892           via `staticpro' in the dynarr `staticpros'.  *Note Adding
4893           Global Lisp Variables::.
4894
4895         * all Lisp objects that are created in C functions and that
4896           must be protected from freeing them. They are registered in
4897           the global list `gcprolist'.  *Note GCPROing::.
4898
4899         * all local variables (i.e. their name fields `symbol' and old
4900           values `old_values') that are bound during the evaluation by
4901           the Lisp engine. They are stored in `specbinding' structs
4902           pushed on a stack called `specpdl'.  *Note Dynamic Binding;
4903           The specbinding Stack; Unwind-Protects::.
4904
4905         * all catch blocks that the Lisp engine encounters during the
4906           evaluation cause the creation of structs `catchtag' inserted
4907           in the list `catchlist'. Their tag (`tag') and value (`val'
4908           fields are freshly created objects and therefore have to be
4909           marked.  *Note Catch and Throw::.
4910
4911         * every function application pushes new structs `backtrace' on
4912           the call stack of the Lisp engine (`backtrace_list'). The
4913           unique parts that have to be marked are the fields for each
4914           function (`function') and all their arguments (`args').
4915           *Note Evaluation::.
4916
4917         * all objects that are used by the redisplay engine that must
4918           not be freed are marked by a special function called
4919           `mark_redisplay' (in `redisplay.c').
4920
4921         * all objects created for profiling purposes are allocated by C
4922           functions instead of using the lisp allocation mechanisms. In
4923           order to receive the right ones during the sweep phase, they
4924           also have to be marked manually. That is done by the function
4925           `mark_profiling_info'
4926
4927   9. Hash tables in XEmacs belong to a kind of special objects that
4928      make use of a concept often called 'weak pointers'.  To make a
4929      long story short, these kind of pointers are not followed during
4930      the estimation of the live objects during garbage collection.  Any
4931      object referenced only by weak pointers is collected anyway, and
4932      the reference to it is cleared. In hash tables there are different
4933      usage patterns of them, manifesting in different types of hash
4934      tables, namely 'non-weak', 'weak', 'key-weak' and 'value-weak'
4935      (internally also 'key-car-weak' and 'value-car-weak') hash tables,
4936      each clearing entries depending on different conditions. More
4937      information can be found in the documentation to the function
4938      `make-hash-table'.
4939
4940      Because there are complicated dependency rules about when and what
4941      to mark while processing weak hash tables, the standard `marker'
4942      method is only active if it is marking non-weak hash tables. As
4943      soon as a weak component is in the table, the hash table entries
4944      are ignored while marking. Instead their marking is done each
4945      separately by the function `finish_marking_weak_hash_tables'. This
4946      function iterates over each hash table entry `hentries' for each
4947      weak hash table in `Vall_weak_hash_tables'. Depending on the type
4948      of a table, the appropriate action is performed.  If a table is
4949      acting as `HASH_TABLE_KEY_WEAK', and a key already marked,
4950      everything reachable from the `value' component is marked. If it is
4951      acting as a `HASH_TABLE_VALUE_WEAK' and the value component is
4952      already marked, the marking starts beginning only from the `key'
4953      component.  If it is a `HASH_TABLE_KEY_CAR_WEAK' and the car of
4954      the key entry is already marked, we mark both the `key' and
4955      `value' components.  Finally, if the table is of the type
4956      `HASH_TABLE_VALUE_CAR_WEAK' and the car of the value components is
4957      already marked, again both the `key' and the `value' components
4958      get marked.
4959
4960      Again, there are lists with comparable properties called weak
4961      lists. There exist different peculiarities of their types called
4962      `simple', `assoc', `key-assoc' and `value-assoc'. You can find
4963      further details about them in the description to the function
4964      `make-weak-list'. The scheme of their marking is similar: all weak
4965      lists are listed in `Qall_weak_lists', therefore we iterate over
4966      them. The marking is advanced until we hit an already marked pair.
4967      Then we know that during a former run all the rest has been marked
4968      completely. Again, depending on the special type of the weak list,
4969      our jobs differ. If it is a `WEAK_LIST_SIMPLE' and the elem is
4970      marked, we mark the `cons' part. If it is a `WEAK_LIST_ASSOC' and
4971      not a pair or a pair with both marked car and cdr, we mark the
4972      `cons' and the `elem'. If it is a `WEAK_LIST_KEY_ASSOC' and not a
4973      pair or a pair with a marked car of the elem, we mark the `cons'
4974      and the `elem'. Finally, if it is a `WEAK_LIST_VALUE_ASSOC' and
4975      not a pair or a pair with a marked cdr of the elem, we mark both
4976      the `cons' and the `elem'.
4977
4978      Since, by marking objects in reach from weak hash tables and weak
4979      lists, other objects could get marked, this perhaps implies
4980      further marking of other weak objects, both finishing functions
4981      are redone as long as yet unmarked objects get freshly marked.
4982
4983  10. After completing the special marking for the weak hash tables and
4984      for the weak lists, all entries that point to objects that are
4985      going to be swept in the further process are useless, and
4986      therefore have to be removed from the table or the list.
4987
4988      The function `prune_weak_hash_tables' does the job for weak hash
4989      tables. Totally unmarked hash tables are removed from the list
4990      `Vall_weak_hash_tables'. The other ones are treated more carefully
4991      by scanning over all entries and removing one as soon as one of
4992      the components `key' and `value' is unmarked.
4993
4994      The same idea applies to the weak lists. It is accomplished by
4995      `prune_weak_lists': An unmarked list is pruned from
4996      `Vall_weak_lists' immediately. A marked list is treated more
4997      carefully by going over it and removing just the unmarked pairs.
4998
4999  11. The function `prune_specifiers' checks all listed specifiers held
5000      in `Vall_specifiers' and removes the ones from the lists that are
5001      unmarked.
5002
5003  12. All syntax tables are stored in a list called
5004      `Vall_syntax_tables'. The function `prune_syntax_tables' walks
5005      through it and unlinks the tables that are unmarked.
5006
5007  13. Next, we will attack the complete sweeping - the function
5008      `gc_sweep' which holds the predominance.
5009
5010  14. First, all the variables with respect to garbage collection are
5011      reset. `consing_since_gc' - the counter of the created cells since
5012      the last garbage collection - is set back to 0, and
5013      `gc_in_progress' is not `true' anymore.
5014
5015  15. In case the session is interactive, the displayed cursor and
5016      message are removed again.
5017
5018  16. The state of `gc_inhibit' is restored to the former value by
5019      unwinding the stack.
5020
5021  17. A small memory reserve is always held back that can be reached by
5022      `breathing_space'. If nothing more is left, we create a new reserve
5023      and exit.
5024
5025 \1f
5026 File: internals.info,  Node: mark_object,  Next: gc_sweep,  Prev: garbage_collect_1,  Up: Garbage Collection - Step by Step
5027
5028 11.4.3 `mark_object'
5029 --------------------
5030
5031 The first thing that is checked while marking an object is whether the
5032 object is a real Lisp object `Lisp_Type_Record' or just an integer or a
5033 character. Integers and characters are the only two types that are
5034 stored directly - without another level of indirection, and therefore
5035 they don't have to be marked and collected.  *Note How Lisp Objects Are
5036 Represented in C::.
5037
5038    The second case is the one we have to handle. It is the one when we
5039 are dealing with a pointer to a Lisp object. But, there exist also three
5040 possibilities, that prevent us from doing anything while marking: The
5041 object is read only which prevents it from being garbage collected,
5042 i.e. marked (`C_READONLY_RECORD_HEADER'). The object in question is
5043 already marked, and need not be marked for the second time (checked by
5044 `MARKED_RECORD_HEADER_P'). If it is a special, unmarkable object
5045 (`UNMARKABLE_RECORD_HEADER_P', apparently, these are objects that sit
5046 in some const space, and can therefore not be marked, see
5047 `this_one_is_unmarkable' in `alloc.c').
5048
5049    Now, the actual marking is feasible. We do so by once using the macro
5050 `MARK_RECORD_HEADER' to mark the object itself (actually the special
5051 flag in the lrecord header), and calling its special marker "method"
5052 `marker' if available. The marker method marks every other object that
5053 is in reach from our current object. Note, that these marker methods
5054 should not call `mark_object' recursively, but instead should return
5055 the next object from where further marking has to be performed.
5056
5057    In case another object was returned, as mentioned before, we
5058 reiterate the whole `mark_object' process beginning with this next
5059 object.
5060
5061 \1f
5062 File: internals.info,  Node: gc_sweep,  Next: sweep_lcrecords_1,  Prev: mark_object,  Up: Garbage Collection - Step by Step
5063
5064 11.4.4 `gc_sweep'
5065 -----------------
5066
5067 The job of this function is to free all unmarked records from memory. As
5068 we know, there are different types of objects implemented and managed,
5069 and consequently different ways to free them from memory.  *Note
5070 Introduction to Allocation::.
5071
5072    We start with all objects stored through `lcrecords'. All bulkier
5073 objects are allocated and handled using that scheme of `lcrecords'.
5074 Each object is `malloc'ed separately instead of placing it in one of
5075 the contiguous frob blocks. All types that are currently stored using
5076 `lcrecords''s  `alloc_lcrecord' and `make_lcrecord_list' are the types:
5077 vectors, buffers, char-table, char-table-entry, console, weak-list,
5078 database, device, ldap, hash-table, command-builder, extent-auxiliary,
5079 extent-info, face, coding-system, frame, image-instance, glyph,
5080 popup-data, gui-item, keymap, charset, color_instance, font_instance,
5081 opaque, opaque-list, process, range-table, specifier,
5082 symbol-value-buffer-local, symbol-value-lisp-magic,
5083 symbol-value-varalias, toolbar-button, tooltalk-message,
5084 tooltalk-pattern, window, and window-configuration. We take care of
5085 them in the fist place in order to be able to handle and to finalize
5086 items stored in them more easily. The function `sweep_lcrecords_1' as
5087 described below is doing the whole job for us.  For a description about
5088 the internals: *Note lrecords::.
5089
5090    Our next candidates are the other objects that behave quite
5091 differently than everything else: the strings. They consists of two
5092 parts, a fixed-size portion (`struct Lisp_String') holding the string's
5093 length, its property list and a pointer to the second part, and the
5094 actual string data, which is stored in string-chars blocks comparable to
5095 frob blocks. In this block, the data is not only freed, but also a
5096 compression of holes is made, i.e. all strings are relocated together.
5097 *Note String::. This compacting phase is performed by the function
5098 `compact_string_chars', the actual sweeping by the function
5099 `sweep_strings' is described below.
5100
5101    After that, the other types are swept step by step using functions
5102 `sweep_conses', `sweep_bit_vectors_1', `sweep_compiled_functions',
5103 `sweep_floats', `sweep_symbols', `sweep_extents', `sweep_markers' and
5104 `sweep_extents'.  They are the fixed-size types cons, floats,
5105 compiled-functions, symbol, marker, extent, and event stored in
5106 so-called "frob blocks", and therefore we can basically do the same on
5107 every type objects, using the same macros, especially defined only to
5108 handle everything with respect to fixed-size blocks. The only fixed-size
5109 type that is not handled here are the fixed-size portion of strings,
5110 because we took special care of them earlier.
5111
5112    The only big exceptions are bit vectors stored differently and
5113 therefore treated differently by the function `sweep_bit_vectors_1'
5114 described later.
5115
5116    At first, we need some brief information about how these fixed-size
5117 types are managed in general, in order to understand how the sweeping
5118 is done. They have all a fixed size, and are therefore stored in big
5119 blocks of memory - allocated at once - that can hold a certain amount
5120 of objects of one type. The macro `DECLARE_FIXED_TYPE_ALLOC' creates
5121 the suitable structures for every type. More precisely, we have the
5122 block struct (holding a pointer to the previous block `prev' and the
5123 objects in `block[]'), a pointer to current block
5124 (`current_..._block)') and its last index (`current_..._block_index'),
5125 and a pointer to the free list that will be created. Also a macro
5126 `FIXED_TYPE_FROM_BLOCK' plus some related macros exists that are used
5127 to obtain a new object, either from the free list
5128 `ALLOCATE_FIXED_TYPE_1' if there is an unused object of that type
5129 stored or by allocating a completely new block using
5130 `ALLOCATE_FIXED_TYPE_FROM_BLOCK'.
5131
5132    The rest works as follows: all of them define a macro `UNMARK_...'
5133 that is used to unmark the object. They define a macro
5134 `ADDITIONAL_FREE_...' that defines additional work that has to be done
5135 when converting an object from in use to not in use (so far, only
5136 markers use it in order to unchain them). Then, they all call the macro
5137 `SWEEP_FIXED_TYPE_BLOCK' instantiated with their type name and their
5138 struct name.
5139
5140    This call in particular does the following: we go over all blocks
5141 starting with the current moving towards the oldest.  For each block,
5142 we look at every object in it. If the object already freed (checked
5143 with `FREE_STRUCT_P' using the first pointer of the object), or if it is
5144 set to read only (`C_READONLY_RECORD_HEADER_P', nothing must be done.
5145 If it is unmarked (checked with `MARKED_RECORD_HEADER_P'), it is put in
5146 the free list and set free (using the macro `FREE_FIXED_TYPE',
5147 otherwise it stays in the block, but is unmarked (by `UNMARK_...').
5148 While going through one block, we note if the whole block is empty. If
5149 so, the whole block is freed (using `xfree') and the free list state is
5150 set to the state it had before handling this block.
5151
5152 \1f
5153 File: internals.info,  Node: sweep_lcrecords_1,  Next: compact_string_chars,  Prev: gc_sweep,  Up: Garbage Collection - Step by Step
5154
5155 11.4.5 `sweep_lcrecords_1'
5156 --------------------------
5157
5158 After nullifying the complete lcrecord statistics, we go over all
5159 lcrecords two separate times. They are all chained together in a list
5160 with a head called `all_lcrecords'.
5161
5162    The first loop calls for each object its `finalizer' method, but only
5163 in the case that it is not read only (`C_READONLY_RECORD_HEADER_P)', it
5164 is not already marked (`MARKED_RECORD_HEADER_P'), it is not already in
5165 a free list (list of freed objects, field `free') and finally it owns a
5166 finalizer method.
5167
5168    The second loop actually frees the appropriate objects again by
5169 iterating through the whole list. In case an object is read only or
5170 marked, it has to persist, otherwise it is manually freed by calling
5171 `xfree'. During this loop, the lcrecord statistics are kept up to date
5172 by calling `tick_lcrecord_stats' with the right arguments,
5173
5174 \1f
5175 File: internals.info,  Node: compact_string_chars,  Next: sweep_strings,  Prev: sweep_lcrecords_1,  Up: Garbage Collection - Step by Step
5176
5177 11.4.6 `compact_string_chars'
5178 -----------------------------
5179
5180 The purpose of this function is to compact all the data parts of the
5181 strings that are held in so-called `string_chars_block', i.e. the
5182 strings that do not exceed a certain maximal length.
5183
5184    The procedure with which this is done is as follows. We are keeping
5185 two positions in the `string_chars_block's using two pointer/integer
5186 pairs, namely `from_sb'/`from_pos' and `to_sb'/`to_pos'. They stand for
5187 the actual positions, from where to where, to copy the actually handled
5188 string.
5189
5190    While going over all chained `string_char_block's and their held
5191 strings, staring at `first_string_chars_block', both pointers are
5192 advanced and eventually a string is copied from `from_sb' to `to_sb',
5193 depending on the status of the pointed at strings.
5194
5195    More precisely, we can distinguish between the following actions.
5196    * The string at `from_sb''s position could be marked as free, which
5197      is indicated by an invalid pointer to the pointer that should
5198      point back to the fixed size string object, and which is checked by
5199      `FREE_STRUCT_P'. In this case, the `from_sb'/`from_pos' is
5200      advanced to the next string, and nothing has to be copied.
5201
5202    * Also, if a string object itself is unmarked, nothing has to be
5203      copied. We likewise advance the `from_sb'/`from_pos' pair as
5204      described above.
5205
5206    * In all other cases, we have a marked string at hand. The string
5207      data must be moved from the from-position to the to-position. In
5208      case there is not enough space in the actual `to_sb'-block, we
5209      advance this pointer to the beginning of the next block before
5210      copying. In case the from and to positions are different, we
5211      perform the actual copying using the library function `memmove'.
5212
5213    After compacting, the pointer to the current `string_chars_block',
5214 sitting in `current_string_chars_block', is reset on the last block to
5215 which we moved a string, i.e. `to_block', and all remaining blocks (we
5216 know that they just carry garbage) are explicitly `xfree'd.
5217
5218 \1f
5219 File: internals.info,  Node: sweep_strings,  Next: sweep_bit_vectors_1,  Prev: compact_string_chars,  Up: Garbage Collection - Step by Step
5220
5221 11.4.7 `sweep_strings'
5222 ----------------------
5223
5224 The sweeping for the fixed sized string objects is essentially exactly
5225 the same as it is for all other fixed size types. As before, the freeing
5226 into the suitable free list is done by using the macro
5227 `SWEEP_FIXED_SIZE_BLOCK' after defining the right macros
5228 `UNMARK_string' and `ADDITIONAL_FREE_string'. These two definitions are
5229 a little bit special compared to the ones used for the other fixed size
5230 types.
5231
5232    `UNMARK_string' is defined the same way except some additional code
5233 used for updating the bookkeeping information.
5234
5235    For strings, `ADDITIONAL_FREE_string' has to do something in
5236 addition: in case, the string was not allocated in a
5237 `string_chars_block' because it exceeded the maximal length, and
5238 therefore it was `malloc'ed separately, we know also `xfree' it
5239 explicitly.
5240
5241 \1f
5242 File: internals.info,  Node: sweep_bit_vectors_1,  Prev: sweep_strings,  Up: Garbage Collection - Step by Step
5243
5244 11.4.8 `sweep_bit_vectors_1'
5245 ----------------------------
5246
5247 Bit vectors are also one of the rare types that are `malloc'ed
5248 individually. Consequently, while sweeping, all further needless bit
5249 vectors must be freed by hand. This is done, as one might imagine, the
5250 expected way: since they are all registered in a list called
5251 `all_bit_vectors', all elements of that list are traversed, all
5252 unmarked bit vectors are unlinked by calling `xfree' and all of them
5253 become unmarked.  In addition, the bookkeeping information used for
5254 garbage collector's output purposes is updated.
5255
5256 \1f
5257 File: internals.info,  Node: Integers and Characters,  Next: Allocation from Frob Blocks,  Prev: Garbage Collection - Step by Step,  Up: Allocation of Objects in XEmacs Lisp
5258
5259 11.5 Integers and Characters
5260 ============================
5261
5262 Integer and character Lisp objects are created from integers using the
5263 macros `XSETINT()' and `XSETCHAR()' or the equivalent functions
5264 `make_int()' and `make_char()'. (These are actually macros on most
5265 systems.)  These functions basically just do some moving of bits
5266 around, since the integral value of the object is stored directly in
5267 the `Lisp_Object'.
5268
5269    `XSETINT()' and the like will truncate values given to them that are
5270 too big; i.e. you won't get the value you expected but the tag bits
5271 will at least be correct.
5272
5273 \1f
5274 File: internals.info,  Node: Allocation from Frob Blocks,  Next: lrecords,  Prev: Integers and Characters,  Up: Allocation of Objects in XEmacs Lisp
5275
5276 11.6 Allocation from Frob Blocks
5277 ================================
5278
5279 The uninitialized memory required by a `Lisp_Object' of a particular
5280 type is allocated using `ALLOCATE_FIXED_TYPE()'.  This only occurs
5281 inside of the lowest-level object-creating functions in `alloc.c':
5282 `Fcons()', `make_float()', `Fmake_byte_code()', `Fmake_symbol()',
5283 `allocate_extent()', `allocate_event()', `Fmake_marker()', and
5284 `make_uninit_string()'.  The idea is that, for each type, there are a
5285 number of frob blocks (each 2K in size); each frob block is divided up
5286 into object-sized chunks.  Each frob block will have some of these
5287 chunks that are currently assigned to objects, and perhaps some that are
5288 free. (If a frob block has nothing but free chunks, it is freed at the
5289 end of the garbage collection cycle.)  The free chunks are stored in a
5290 free list, which is chained by storing a pointer in the first four bytes
5291 of the chunk. (Except for the free chunks at the end of the last frob
5292 block, which are handled using an index which points past the end of the
5293 last-allocated chunk in the last frob block.)  `ALLOCATE_FIXED_TYPE()'
5294 first tries to retrieve a chunk from the free list; if that fails, it
5295 calls `ALLOCATE_FIXED_TYPE_FROM_BLOCK()', which looks at the end of the
5296 last frob block for space, and creates a new frob block if there is
5297 none. (There are actually two versions of these macros, one of which is
5298 more defensive but less efficient and is used for error-checking.)
5299
5300 \1f
5301 File: internals.info,  Node: lrecords,  Next: Low-level allocation,  Prev: Allocation from Frob Blocks,  Up: Allocation of Objects in XEmacs Lisp
5302
5303 11.7 lrecords
5304 =============
5305
5306 [see `lrecord.h']
5307
5308    All lrecords have at the beginning of their structure a `struct
5309 lrecord_header'.  This just contains a type number and some flags,
5310 including the mark bit.  All builtin type numbers are defined as
5311 constants in `enum lrecord_type', to allow the compiler to generate
5312 more efficient code for `TYPEP'.  The type number, thru the
5313 `lrecord_implementation_table', gives access to a `struct
5314 lrecord_implementation', which is a structure containing method pointers
5315 and such.  There is one of these for each type, and it is a global,
5316 constant, statically-declared structure that is declared in the
5317 `DEFINE_LRECORD_IMPLEMENTATION()' macro.
5318
5319    Simple lrecords (of type (b) above) just have a `struct
5320 lrecord_header' at their beginning.  lcrecords, however, actually have a
5321 `struct lcrecord_header'.  This, in turn, has a `struct lrecord_header'
5322 at its beginning, so sanity is preserved; but it also has a pointer
5323 used to chain all lcrecords together, and a special ID field used to
5324 distinguish one lcrecord from another. (This field is used only for
5325 debugging and could be removed, but the space gain is not significant.)
5326
5327    Simple lrecords are created using `ALLOCATE_FIXED_TYPE()', just like
5328 for other frob blocks.  The only change is that the implementation
5329 pointer must be initialized correctly. (The implementation structure for
5330 an lrecord, or rather the pointer to it, is named `lrecord_float',
5331 `lrecord_extent', `lrecord_buffer', etc.)
5332
5333    lcrecords are created using `alloc_lcrecord()'.  This takes a size
5334 to allocate and an implementation pointer. (The size needs to be passed
5335 because some lcrecords, such as window configurations, are of variable
5336 size.) This basically just `malloc()'s the storage, initializes the
5337 `struct lcrecord_header', and chains the lcrecord onto the head of the
5338 list of all lcrecords, which is stored in the variable `all_lcrecords'.
5339 The calls to `alloc_lcrecord()' generally occur in the lowest-level
5340 allocation function for each lrecord type.
5341
5342    Whenever you create an lrecord, you need to call either
5343 `DEFINE_LRECORD_IMPLEMENTATION()' or
5344 `DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION()'.  This needs to be specified
5345 in a `.c' file, at the top level.  What this actually does is define
5346 and initialize the implementation structure for the lrecord. (And
5347 possibly declares a function `error_check_foo()' that implements the
5348 `XFOO()' macro when error-checking is enabled.)  The arguments to the
5349 macros are the actual type name (this is used to construct the C
5350 variable name of the lrecord implementation structure and related
5351 structures using the `##' macro concatenation operator), a string that
5352 names the type on the Lisp level (this may not be the same as the C
5353 type name; typically, the C type name has underscores, while the Lisp
5354 string has dashes), various method pointers, and the name of the C
5355 structure that contains the object.  The methods are used to
5356 encapsulate type-specific information about the object, such as how to
5357 print it or mark it for garbage collection, so that it's easy to add
5358 new object types without having to add a specific case for each new
5359 type in a bunch of different places.
5360
5361    The difference between `DEFINE_LRECORD_IMPLEMENTATION()' and
5362 `DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION()' is that the former is used
5363 for fixed-size object types and the latter is for variable-size object
5364 types.  Most object types are fixed-size; some complex types, however
5365 (e.g. window configurations), are variable-size.  Variable-size object
5366 types have an extra method, which is called to determine the actual
5367 size of a particular object of that type.  (Currently this is only used
5368 for keeping allocation statistics.)
5369
5370    For the purpose of keeping allocation statistics, the allocation
5371 engine keeps a list of all the different types that exist.  Note that,
5372 since `DEFINE_LRECORD_IMPLEMENTATION()' is a macro that is specified at
5373 top-level, there is no way for it to initialize the global data
5374 structures containing type information, like
5375 `lrecord_implementations_table'.  For this reason a call to
5376 `INIT_LRECORD_IMPLEMENTATION' must be added to the same source file
5377 containing `DEFINE_LRECORD_IMPLEMENTATION', but instead of to the top
5378 level, to one of the init functions, typically `syms_of_FOO.c'.
5379 `INIT_LRECORD_IMPLEMENTATION' must be called before an object of this
5380 type is used.
5381
5382    The type number is also used to index into an array holding the
5383 number of objects of each type and the total memory allocated for
5384 objects of that type.  The statistics in this array are computed during
5385 the sweep stage.  These statistics are returned by the call to
5386 `garbage-collect'.
5387
5388    Note that for every type defined with a `DEFINE_LRECORD_*()' macro,
5389 there needs to be a `DECLARE_LRECORD_IMPLEMENTATION()' somewhere in a
5390 `.h' file, and this `.h' file needs to be included by `inline.c'.
5391
5392    Furthermore, there should generally be a set of `XFOOBAR()',
5393 `FOOBARP()', etc. macros in a `.h' (or occasionally `.c') file.  To
5394 create one of these, copy an existing model and modify as necessary.
5395
5396    *Please note:* If you define an lrecord in an external
5397 dynamically-loaded module, you must use `DECLARE_EXTERNAL_LRECORD',
5398 `DEFINE_EXTERNAL_LRECORD_IMPLEMENTATION', and
5399 `DEFINE_EXTERNAL_LRECORD_SEQUENCE_IMPLEMENTATION' instead of the
5400 non-EXTERNAL forms. These macros will dynamically add new type numbers
5401 to the global enum that records them, whereas the non-EXTERNAL forms
5402 assume that the programmer has already inserted the correct type numbers
5403 into the enum's code at compile-time.
5404
5405    The various methods in the lrecord implementation structure are:
5406
5407   1. A "mark" method.  This is called during the marking stage and
5408      passed a function pointer (usually the `mark_object()' function),
5409      which is used to mark an object.  All Lisp objects that are
5410      contained within the object need to be marked by applying this
5411      function to them.  The mark method should also return a Lisp
5412      object, which should be either `nil' or an object to mark. (This
5413      can be used in lieu of calling `mark_object()' on the object, to
5414      reduce the recursion depth, and consequently should be the most
5415      heavily nested sub-object, such as a long list.)
5416
5417      *Please note:* When the mark method is called, garbage collection
5418      is in progress, and special precautions need to be taken when
5419      accessing objects; see section (B) above.
5420
5421      If your mark method does not need to do anything, it can be `NULL'.
5422
5423   2. A "print" method.  This is called to create a printed
5424      representation of the object, whenever `princ', `prin1', or the
5425      like is called.  It is passed the object, a stream to which the
5426      output is to be directed, and an `escapeflag' which indicates
5427      whether the object's printed representation should be "escaped" so
5428      that it is readable. (This corresponds to the difference between
5429      `princ' and `prin1'.) Basically, "escaped" means that strings will
5430      have quotes around them and confusing characters in the strings
5431      such as quotes, backslashes, and newlines will be backslashed; and
5432      that special care will be taken to make symbols print in a
5433      readable fashion (e.g. symbols that look like numbers will be
5434      backslashed).  Other readable objects should perhaps pass
5435      `escapeflag' on when sub-objects are printed, so that readability
5436      is preserved when necessary (or if not, always pass in a 1 for
5437      `escapeflag').  Non-readable objects should in general ignore
5438      `escapeflag', except that some use it as an indication that more
5439      verbose output should be given.
5440
5441      Sub-objects are printed using `print_internal()', which takes
5442      exactly the same arguments as are passed to the print method.
5443
5444      Literal C strings should be printed using `write_c_string()', or
5445      `write_string_1()' for non-null-terminated strings.
5446
5447      Functions that do not have a readable representation should check
5448      the `print_readably' flag and signal an error if it is set.
5449
5450      If you specify NULL for the print method, the
5451      `default_object_printer()' will be used.
5452
5453   3. A "finalize" method.  This is called at the beginning of the sweep
5454      stage on lcrecords that are about to be freed, and should be used
5455      to perform any extra object cleanup.  This typically involves
5456      freeing any extra `malloc()'ed memory associated with the object,
5457      releasing any operating-system and window-system resources
5458      associated with the object (e.g. pixmaps, fonts), etc.
5459
5460      The finalize method can be NULL if nothing needs to be done.
5461
5462      WARNING #1: The finalize method is also called at the end of the
5463      dump phase; this time with the for_disksave parameter set to
5464      non-zero.  The object is _not_ about to disappear, so you have to
5465      make sure to _not_ free any extra `malloc()'ed memory if you're
5466      going to need it later.  (Also, signal an error if there are any
5467      operating-system and window-system resources here, because they
5468      can't be dumped.)
5469
5470      Finalize methods should, as a rule, set to zero any pointers after
5471      they've been freed, and check to make sure pointers are not zero
5472      before freeing.  Although I'm pretty sure that finalize methods
5473      are not called twice on the same object (except for the
5474      `for_disksave' proviso), we've gotten nastily burned in some cases
5475      by not doing this.
5476
5477      WARNING #2: The finalize method is _only_ called for lcrecords,
5478      _not_ for simply lrecords.  If you need a finalize method for
5479      simple lrecords, you have to stick it in the
5480      `ADDITIONAL_FREE_foo()' macro in `alloc.c'.
5481
5482      WARNING #3: Things are in an _extremely_ bizarre state when
5483      `ADDITIONAL_FREE_foo()' is called, so you have to be incredibly
5484      careful when writing one of these functions.  See the comment in
5485      `gc_sweep()'.  If you ever have to add one of these, consider
5486      using an lcrecord or dealing with the problem in a different
5487      fashion.
5488
5489   4. An "equal" method.  This compares the two objects for similarity,
5490      when `equal' is called.  It should compare the contents of the
5491      objects in some reasonable fashion.  It is passed the two objects
5492      and a "depth" value, which is used to catch circular objects.  To
5493      compare sub-Lisp-objects, call `internal_equal()' and bump the
5494      depth value by one.  If this value gets too high, a
5495      `circular-object' error will be signaled.
5496
5497      If this is NULL, objects are `equal' only when they are `eq', i.e.
5498      identical.
5499
5500   5. A "hash" method.  This is used to hash objects when they are to be
5501      compared with `equal'.  The rule here is that if two objects are
5502      `equal', they _must_ hash to the same value; i.e. your hash
5503      function should use some subset of the sub-fields of the object
5504      that are compared in the "equal" method.  If you specify this
5505      method as `NULL', the object's pointer will be used as the hash,
5506      which will _fail_ if the object has an `equal' method, so don't do
5507      this.
5508
5509      To hash a sub-Lisp-object, call `internal_hash()'.  Bump the depth
5510      by one, just like in the "equal" method.
5511
5512      To convert a Lisp object directly into a hash value (using its
5513      pointer), use `LISP_HASH()'.  This is what happens when the hash
5514      method is NULL.
5515
5516      To hash two or more values together into a single value, use
5517      `HASH2()', `HASH3()', `HASH4()', etc.
5518
5519   6. "getprop", "putprop", "remprop", and "plist" methods.  These are
5520      used for object types that have properties.  I don't feel like
5521      documenting them here.  If you create one of these objects, you
5522      have to use different macros to define them, i.e.
5523      `DEFINE_LRECORD_IMPLEMENTATION_WITH_PROPS()' or
5524      `DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION_WITH_PROPS()'.
5525
5526   7. A "size_in_bytes" method, when the object is of variable-size.
5527      (i.e. declared with a `_SEQUENCE_IMPLEMENTATION' macro.)  This
5528      should simply return the object's size in bytes, exactly as you
5529      might expect.  For an example, see the methods for window
5530      configurations and opaques.
5531
5532 \1f
5533 File: internals.info,  Node: Low-level allocation,  Next: Cons,  Prev: lrecords,  Up: Allocation of Objects in XEmacs Lisp
5534
5535 11.8 Low-level allocation
5536 =========================
5537
5538 Memory that you want to allocate directly should be allocated using
5539 `xmalloc()' rather than `malloc()'.  This implements error-checking on
5540 the return value, and once upon a time did some more vital stuff (i.e.
5541 `BLOCK_INPUT', which is no longer necessary).  Free using `xfree()',
5542 and realloc using `xrealloc()'.  Note that `xmalloc()' will do a
5543 non-local exit if the memory can't be allocated. (Many functions,
5544 however, do not expect this, and thus XEmacs will likely crash if this
5545 happens.  *This is a bug.*  If you can, you should strive to make your
5546 function handle this OK.  However, it's difficult in the general
5547 circumstance, perhaps requiring extra unwind-protects and such.)
5548
5549    Note that XEmacs provides two separate replacements for the standard
5550 `malloc()' library function.  These are called "old GNU malloc"
5551 (`malloc.c') and "new GNU malloc" (`gmalloc.c'), respectively.  New GNU
5552 malloc is better in pretty much every way than old GNU malloc, and
5553 should be used if possible.  (It used to be that on some systems, the
5554 old one worked but the new one didn't.  I think this was due
5555 specifically to a bug in SunOS, which the new one now works around; so
5556 I don't think the old one ever has to be used any more.) The primary
5557 difference between both of these mallocs and the standard system malloc
5558 is that they are much faster, at the expense of increased space.  The
5559 basic idea is that memory is allocated in fixed chunks of powers of
5560 two.  This allows for basically constant malloc time, since the various
5561 chunks can just be kept on a number of free lists. (The standard system
5562 malloc typically allocates arbitrary-sized chunks and has to spend some
5563 time, sometimes a significant amount of time, walking the heap looking
5564 for a free block to use and cleaning things up.)  The new GNU malloc
5565 improves on things by allocating large objects in chunks of 4096 bytes
5566 rather than in ever larger powers of two, which results in ever larger
5567 wastage.  There is a slight speed loss here, but it's of doubtful
5568 significance.
5569
5570    NOTE: Apparently there is a third-generation GNU malloc that is
5571 significantly better than the new GNU malloc, and should probably be
5572 included in XEmacs.
5573
5574    There is also the relocating allocator, `ralloc.c'.  This actually
5575 moves blocks of memory around so that the `sbrk()' pointer shrunk and
5576 virtual memory released back to the system.  On some systems, this is a
5577 big win.  On all systems, it causes a noticeable (and sometimes huge)
5578 speed penalty, so I turn it off by default.  `ralloc.c' only works with
5579 the new GNU malloc in `gmalloc.c'.  There are also two versions of
5580 `ralloc.c', one that uses `mmap()' rather than block copies to move
5581 data around.  This purports to be faster, although that depends on the
5582 amount of data that would have had to be block copied and the
5583 system-call overhead for `mmap()'.  I don't know exactly how this
5584 works, except that the relocating-allocation routines are pretty much
5585 used only for the memory allocated for a buffer, which is the biggest
5586 consumer of space, esp. of space that may get freed later.
5587
5588    Note that the GNU mallocs have some "memory warning" facilities.
5589 XEmacs taps into them and issues a warning through the standard warning
5590 system, when memory gets to 75%, 85%, and 95% full.  (On some systems,
5591 the memory warnings are not functional.)
5592
5593    Allocated memory that is going to be used to make a Lisp object is
5594 created using `allocate_lisp_storage()'.  This just calls `xmalloc()'.
5595 It used to verify that the pointer to the memory can fit into a Lisp
5596 word, before the current Lisp object representation was introduced.
5597 `allocate_lisp_storage()' is called by `alloc_lcrecord()',
5598 `ALLOCATE_FIXED_TYPE()', and the vector and bit-vector creation
5599 routines.  These routines also call `INCREMENT_CONS_COUNTER()' at the
5600 appropriate times; this keeps statistics on how much memory is
5601 allocated, so that garbage-collection can be invoked when the threshold
5602 is reached.
5603
5604 \1f
5605 File: internals.info,  Node: Cons,  Next: Vector,  Prev: Low-level allocation,  Up: Allocation of Objects in XEmacs Lisp
5606
5607 11.9 Cons
5608 =========
5609
5610 Conses are allocated in standard frob blocks.  The only thing to note
5611 is that conses can be explicitly freed using `free_cons()' and
5612 associated functions `free_list()' and `free_alist()'.  This
5613 immediately puts the conses onto the cons free list, and decrements the
5614 statistics on memory allocation appropriately.  This is used to good
5615 effect by some extremely commonly-used code, to avoid generating extra
5616 objects and thereby triggering GC sooner.  However, you have to be
5617 _extremely_ careful when doing this.  If you mess this up, you will get
5618 BADLY BURNED, and it has happened before.
5619
5620 \1f
5621 File: internals.info,  Node: Vector,  Next: Bit Vector,  Prev: Cons,  Up: Allocation of Objects in XEmacs Lisp
5622
5623 11.10 Vector
5624 ============
5625
5626 As mentioned above, each vector is `malloc()'ed individually, and all
5627 are threaded through the variable `all_vectors'.  Vectors are marked
5628 strangely during garbage collection, by kludging the size field.  Note
5629 that the `struct Lisp_Vector' is declared with its `contents' field
5630 being a _stretchy_ array of one element.  It is actually `malloc()'ed
5631 with the right size, however, and access to any element through the
5632 `contents' array works fine.
5633
5634 \1f
5635 File: internals.info,  Node: Bit Vector,  Next: Symbol,  Prev: Vector,  Up: Allocation of Objects in XEmacs Lisp
5636
5637 11.11 Bit Vector
5638 ================
5639
5640 Bit vectors work exactly like vectors, except for more complicated code
5641 to access an individual bit, and except for the fact that bit vectors
5642 are lrecords while vectors are not. (The only difference here is that
5643 there's an lrecord implementation pointer at the beginning and the tag
5644 field in bit vector Lisp words is "lrecord" rather than "vector".)
5645
5646 \1f
5647 File: internals.info,  Node: Symbol,  Next: Marker,  Prev: Bit Vector,  Up: Allocation of Objects in XEmacs Lisp
5648
5649 11.12 Symbol
5650 ============
5651
5652 Symbols are also allocated in frob blocks.  Symbols in the awful
5653 horrible obarray structure are chained through their `next' field.
5654
5655    Remember that `intern' looks up a symbol in an obarray, creating one
5656 if necessary.
5657
5658 \1f
5659 File: internals.info,  Node: Marker,  Next: String,  Prev: Symbol,  Up: Allocation of Objects in XEmacs Lisp
5660
5661 11.13 Marker
5662 ============
5663
5664 Markers are allocated in frob blocks, as usual.  They are kept in a
5665 buffer unordered, but in a doubly-linked list so that they can easily
5666 be removed. (Formerly this was a singly-linked list, but in some cases
5667 garbage collection took an extraordinarily long time due to the O(N^2)
5668 time required to remove lots of markers from a buffer.) Markers are
5669 removed from a buffer in the finalize stage, in
5670 `ADDITIONAL_FREE_marker()'.
5671
5672 \1f
5673 File: internals.info,  Node: String,  Next: Compiled Function,  Prev: Marker,  Up: Allocation of Objects in XEmacs Lisp
5674
5675 11.14 String
5676 ============
5677
5678 As mentioned above, strings are a special case.  A string is logically
5679 two parts, a fixed-size object (containing the length, property list,
5680 and a pointer to the actual data), and the actual data in the string.
5681 The fixed-size object is a `struct Lisp_String' and is allocated in
5682 frob blocks, as usual.  The actual data is stored in special
5683 "string-chars blocks", which are 8K blocks of memory.
5684 Currently-allocated strings are simply laid end to end in these
5685 string-chars blocks, with a pointer back to the `struct Lisp_String'
5686 stored before each string in the string-chars block.  When a new string
5687 needs to be allocated, the remaining space at the end of the last
5688 string-chars block is used if there's enough, and a new string-chars
5689 block is created otherwise.
5690
5691    There are never any holes in the string-chars blocks due to the
5692 string compaction and relocation that happens at the end of garbage
5693 collection.  During the sweep stage of garbage collection, when objects
5694 are reclaimed, the garbage collector goes through all string-chars
5695 blocks, looking for unused strings.  Each chunk of string data is
5696 preceded by a pointer to the corresponding `struct Lisp_String', which
5697 indicates both whether the string is used and how big the string is,
5698 i.e. how to get to the next chunk of string data.  Holes are compressed
5699 by block-copying the next string into the empty space and relocating the
5700 pointer stored in the corresponding `struct Lisp_String'.  *This means
5701 you have to be careful with strings in your code.* See the section
5702 above on `GCPRO'ing.
5703
5704    Note that there is one situation not handled: a string that is too
5705 big to fit into a string-chars block.  Such strings, called "big
5706 strings", are all `malloc()'ed as their own block. (#### Although it
5707 would make more sense for the threshold for big strings to be somewhat
5708 lower, e.g. 1/2 or 1/4 the size of a string-chars block.  It seems that
5709 this was indeed the case formerly--indeed, the threshold was set at
5710 1/8--but Mly forgot about this when rewriting things for 19.8.)
5711
5712    Note also that the string data in string-chars blocks is padded as
5713 necessary so that proper alignment constraints on the `struct
5714 Lisp_String' back pointers are maintained.
5715
5716    Finally, strings can be resized.  This happens in Mule when a
5717 character is substituted with a different-length character, or during
5718 modeline frobbing. (You could also export this to Lisp, but it's not
5719 done so currently.) Resizing a string is a potentially tricky process.
5720 If the change is small enough that the padding can absorb it, nothing
5721 other than a simple memory move needs to be done.  Keep in mind,
5722 however, that the string can't shrink too much because the offset to the
5723 next string in the string-chars block is computed by looking at the
5724 length and rounding to the nearest multiple of four or eight.  If the
5725 string would shrink or expand beyond the correct padding, new string
5726 data needs to be allocated at the end of the last string-chars block and
5727 the data moved appropriately.  This leaves some dead string data, which
5728 is marked by putting a special marker of 0xFFFFFFFF in the `struct
5729 Lisp_String' pointer before the data (there's no real `struct
5730 Lisp_String' to point to and relocate), and storing the size of the dead
5731 string data (which would normally be obtained from the now-non-existent
5732 `struct Lisp_String') at the beginning of the dead string data gap.
5733 The string compactor recognizes this special 0xFFFFFFFF marker and
5734 handles it correctly.
5735
5736 \1f
5737 File: internals.info,  Node: Compiled Function,  Prev: String,  Up: Allocation of Objects in XEmacs Lisp
5738
5739 11.15 Compiled Function
5740 =======================
5741
5742 Not yet documented.
5743
5744 \1f
5745 File: internals.info,  Node: Dumping,  Next: Events and the Event Loop,  Prev: Allocation of Objects in XEmacs Lisp,  Up: Top
5746
5747 12 Dumping
5748 **********
5749
5750 12.1 What is dumping and its justification
5751 ==========================================
5752
5753 The C code of XEmacs is just a Lisp engine with a lot of built-in
5754 primitives useful for writing an editor.  The editor itself is written
5755 mostly in Lisp, and represents around 100K lines of code.  Loading and
5756 executing the initialization of all this code takes a bit a time (five
5757 to ten times the usual startup time of current xemacs) and requires
5758 having all the lisp source files around.  Having to reload them each
5759 time the editor is started would not be acceptable.
5760
5761    The traditional solution to this problem is called dumping: the build
5762 process first creates the lisp engine under the name `temacs', then
5763 runs it until it has finished loading and initializing all the lisp
5764 code, and eventually creates a new executable called `xemacs' including
5765 both the object code in `temacs' and all the contents of the memory
5766 after the initialization.
5767
5768    This solution, while working, has a huge problem: the creation of the
5769 new executable from the actual contents of memory is an extremely
5770 system-specific process, quite error-prone, and which interferes with a
5771 lot of system libraries (like malloc).  It is even getting worse
5772 nowadays with libraries using constructors which are automatically
5773 called when the program is started (even before main()) which tend to
5774 crash when they are called multiple times, once before dumping and once
5775 after (IRIX 6.x libz.so pulls in some C++ image libraries thru
5776 dependencies which have this problem).  Writing the dumper is also one
5777 of the most difficult parts of porting XEmacs to a new operating system.
5778 Basically, `dumping' is an operation that is just not officially
5779 supported on many operating systems.
5780
5781    The aim of the portable dumper is to solve the same problem as the
5782 system-specific dumper, that is to be able to reload quickly, using only
5783 a small number of files, the fully initialized lisp part of the editor,
5784 without any system-specific hacks.
5785
5786 * Menu:
5787
5788 * Overview::
5789 * Data descriptions::
5790 * Dumping phase::
5791 * Reloading phase::
5792 * Remaining issues::
5793
5794 \1f
5795 File: internals.info,  Node: Overview,  Next: Data descriptions,  Up: Dumping
5796
5797 12.2 Overview
5798 =============
5799
5800 The portable dumping system has to:
5801
5802   1. At dump time, write all initialized, non-quickly-rebuildable data
5803      to a file [Note: currently named `xemacs.dmp', but the name will
5804      change], along with all informations needed for the reloading.
5805
5806   2. When starting xemacs, reload the dump file, relocate it to its new
5807      starting address if needed, and reinitialize all pointers to this
5808      data.  Also, rebuild all the quickly rebuildable data.
5809
5810 \1f
5811 File: internals.info,  Node: Data descriptions,  Next: Dumping phase,  Prev: Overview,  Up: Dumping
5812
5813 12.3 Data descriptions
5814 ======================
5815
5816 The more complex task of the dumper is to be able to write lisp objects
5817 (lrecords) and C structs to disk and reload them at a different address,
5818 updating all the pointers they include in the process.  This is done by
5819 using external data descriptions that give information about the layout
5820 of the structures in memory.
5821
5822    The specification of these descriptions is in lrecord.h.  A
5823 description of an lrecord is an array of struct lrecord_description.
5824 Each of these structs include a type, an offset in the structure and
5825 some optional parameters depending on the type.  For instance, here is
5826 the string description:
5827
5828      static const struct lrecord_description string_description[] = {
5829        { XD_BYTECOUNT,         offsetof (Lisp_String, size) },
5830        { XD_OPAQUE_DATA_PTR,   offsetof (Lisp_String, data), XD_INDIRECT(0, 1) },
5831        { XD_LISP_OBJECT,       offsetof (Lisp_String, plist) },
5832        { XD_END }
5833      };
5834
5835    The first line indicates a member of type Bytecount, which is used by
5836 the next, indirect directive.  The second means "there is a pointer to
5837 some opaque data in the field `data'".  The length of said data is
5838 given by the expression `XD_INDIRECT(0, 1)', which means "the value in
5839 the 0th line of the description (welcome to C) plus one".  The third
5840 line means "there is a Lisp_Object member `plist' in the Lisp_String
5841 structure".  `XD_END' then ends the description.
5842
5843    This gives us all the information we need to move around what is
5844 pointed to by a structure (C or lrecord) and, by transitivity,
5845 everything that it points to.  The only missing information for dumping
5846 is the size of the structure.  For lrecords, this is part of the
5847 lrecord_implementation, so we don't need to duplicate it.  For C
5848 structures we use a struct struct_description, which includes a size
5849 field and a pointer to an associated array of lrecord_description.
5850
5851 \1f
5852 File: internals.info,  Node: Dumping phase,  Next: Reloading phase,  Prev: Data descriptions,  Up: Dumping
5853
5854 12.4 Dumping phase
5855 ==================
5856
5857 Dumping is done by calling the function pdump() (in dumper.c) which is
5858 invoked from Fdump_emacs (in emacs.c).  This function performs a number
5859 of tasks.
5860
5861 * Menu:
5862
5863 * Object inventory::
5864 * Address allocation::
5865 * The header::
5866 * Data dumping::
5867 * Pointers dumping::
5868
5869 \1f
5870 File: internals.info,  Node: Object inventory,  Next: Address allocation,  Up: Dumping phase
5871
5872 12.4.1 Object inventory
5873 -----------------------
5874
5875 The first task is to build the list of the objects to dump.  This
5876 includes:
5877
5878    * lisp objects
5879
5880    * C structures
5881
5882    We end up with one `pdump_entry_list_elmt' per object group (arrays
5883 of C structs are kept together) which includes a pointer to the first
5884 object of the group, the per-object size and the count of objects in the
5885 group, along with some other information which is initialized later.
5886
5887    These entries are linked together in `pdump_entry_list' structures
5888 and can be enumerated thru either:
5889
5890   1. the `pdump_object_table', an array of `pdump_entry_list', one per
5891      lrecord type, indexed by type number.
5892
5893   2. the `pdump_opaque_data_list', used for the opaque data which does
5894      not include pointers, and hence does not need descriptions.
5895
5896   3. the `pdump_struct_table', which is a vector of
5897      `struct_description'/`pdump_entry_list' pairs, used for non-opaque
5898      C structures.
5899
5900    This uses a marking strategy similar to the garbage collector.  Some
5901 differences though:
5902
5903   1. We do not use the mark bit (which does not exist for C structures
5904      anyway); we use a big hash table instead.
5905
5906   2. We do not use the mark function of lrecords but instead rely on the
5907      external descriptions.  This happens essentially because we need to
5908      follow pointers to C structures and opaque data in addition to
5909      Lisp_Object members.
5910
5911    This is done by `pdump_register_object()', which handles Lisp_Object
5912 variables, and `pdump_register_struct()' which handles C structures,
5913 which both delegate the description management to
5914 `pdump_register_sub()'.
5915
5916    The hash table doubles as a map object to pdump_entry_list_elmt (i.e.
5917 allows us to look up a pdump_entry_list_elmt with the object it points
5918 to).  Entries are added with `pdump_add_entry()' and looked up with
5919 `pdump_get_entry()'.  There is no need for entry removal.  The hash
5920 value is computed quite simply from the object pointer by
5921 `pdump_make_hash()'.
5922
5923    The roots for the marking are:
5924
5925   1. the `staticpro''ed variables (there is a special
5926      `staticpro_nodump()' call for protected variables we do not want
5927      to dump).
5928
5929   2. the variables registered via `dump_add_root_object' (`staticpro()'
5930      is equivalent to `staticpro_nodump()' + `dump_add_root_object()').
5931
5932   3. the variables registered via `dump_add_root_struct_ptr', each of
5933      which points to a C structure.
5934
5935    This does not include the GCPRO'ed variables, the specbinds, the
5936 catchtags, the backlist, the redisplay or the profiling info, since we
5937 do not want to rebuild the actual chain of lisp calls which end up to
5938 the dump-emacs call, only the global variables.
5939
5940    Weak lists and weak hash tables are dumped as if they were their
5941 non-weak equivalent (without changing their type, of course).  This has
5942 not yet been a problem.
5943
5944 \1f
5945 File: internals.info,  Node: Address allocation,  Next: The header,  Prev: Object inventory,  Up: Dumping phase
5946
5947 12.4.2 Address allocation
5948 -------------------------
5949
5950 The next step is to allocate the offsets of each of the objects in the
5951 final dump file.  This is done by `pdump_allocate_offset()' which is
5952 called indirectly by `pdump_scan_by_alignment()'.
5953
5954    The strategy to deal with alignment problems uses these facts:
5955
5956   1. real world alignment requirements are powers of two.
5957
5958   2. the C compiler is required to adjust the size of a struct so that
5959      you can have an array of them next to each other.  This means you
5960      can have an upper bound of the alignment requirements of a given
5961      structure by looking at which power of two its size is a multiple.
5962
5963   3. the non-variant part of variable size lrecords has an alignment
5964      requirement of 4.
5965
5966    Hence, for each lrecord type, C struct type or opaque data block the
5967 alignment requirement is computed as a power of two, with a minimum of
5968 2^2 for lrecords.  `pdump_scan_by_alignment()' then scans all the
5969 `pdump_entry_list_elmt''s, the ones with the highest requirements
5970 first.  This ensures the best packing.
5971
5972    The maximum alignment requirement we take into account is 2^8.
5973
5974    `pdump_allocate_offset()' only has to do a linear allocation,
5975 starting at offset 256 (this leaves room for the header and keeps the
5976 alignments happy).
5977
5978 \1f
5979 File: internals.info,  Node: The header,  Next: Data dumping,  Prev: Address allocation,  Up: Dumping phase
5980
5981 12.4.3 The header
5982 -----------------
5983
5984 The next step creates the file and writes a header with a signature and
5985 some random information in it.  The `reloc_address' field, which
5986 indicates at which address the file should be loaded if we want to avoid
5987 post-reload relocation, is set to 0.  It then seeks to offset 256 (base
5988 offset for the objects).
5989
5990 \1f
5991 File: internals.info,  Node: Data dumping,  Next: Pointers dumping,  Prev: The header,  Up: Dumping phase
5992
5993 12.4.4 Data dumping
5994 -------------------
5995
5996 The data is dumped in the same order as the addresses were allocated by
5997 `pdump_dump_data()', called from `pdump_scan_by_alignment()'.  This
5998 function copies the data to a temporary buffer, relocates all pointers
5999 in the object to the addresses allocated in step Address Allocation,
6000 and writes it to the file.  Using the same order means that, if we are
6001 careful with lrecords whose size is not a multiple of 4, we are ensured
6002 that the object is always written at the offset in the file allocated
6003 in step Address Allocation.
6004
6005 \1f
6006 File: internals.info,  Node: Pointers dumping,  Prev: Data dumping,  Up: Dumping phase
6007
6008 12.4.5 Pointers dumping
6009 -----------------------
6010
6011 A bunch of tables needed to reassign properly the global pointers are
6012 then written.  They are:
6013
6014   1. the pdump_root_struct_ptrs dynarr
6015
6016   2. the pdump_opaques dynarr
6017
6018   3. a vector of all the offsets to the objects in the file that
6019      include a description (for faster relocation at reload time)
6020
6021   4. the pdump_root_objects and pdump_weak_object_chains dynarrs.
6022
6023    For each of the dynarrs we write both the pointer to the variables
6024 and the relocated offset of the object they point to.  Since these
6025 variables are global, the pointers are still valid when restarting the
6026 program and are used to regenerate the global pointers.
6027
6028    The `pdump_weak_object_chains' dynarr is a special case.  The
6029 variables it points to are the head of weak linked lists of lisp objects
6030 of the same type.  Not all objects of this list are dumped so the
6031 relocated pointer we associate with them points to the first dumped
6032 object of the list, or Qnil if none is available.  This is also the
6033 reason why they are not used as roots for the purpose of object
6034 enumeration.
6035
6036    Some very important information like the `staticpros' and
6037 `lrecord_implementations_table' are handled indirectly using
6038 `dump_add_opaque' or `dump_add_root_struct_ptr'.
6039
6040    This is the end of the dumping part.
6041
6042 \1f
6043 File: internals.info,  Node: Reloading phase,  Next: Remaining issues,  Prev: Dumping phase,  Up: Dumping
6044
6045 12.5 Reloading phase
6046 ====================
6047
6048 12.5.1 File loading
6049 -------------------
6050
6051 The file is mmap'ed in memory (which ensures a PAGESIZE alignment, at
6052 least 4096), or if mmap is unavailable or fails, a 256-bytes aligned
6053 malloc is done and the file is loaded.
6054
6055    Some variables are reinitialized from the values found in the header.
6056
6057    The difference between the actual loading address and the
6058 reloc_address is computed and will be used for all the relocations.
6059
6060 12.5.2 Putting back the pdump_opaques
6061 -------------------------------------
6062
6063 The memory contents are restored in the obvious and trivial way.
6064
6065 12.5.3 Putting back the pdump_root_struct_ptrs
6066 ----------------------------------------------
6067
6068 The variables pointed to by pdump_root_struct_ptrs in the dump phase are
6069 reset to the right relocated object addresses.
6070
6071 12.5.4 Object relocation
6072 ------------------------
6073
6074 All the objects are relocated using their description and their offset
6075 by `pdump_reloc_one'.  This step is unnecessary if the reloc_address is
6076 equal to the file loading address.
6077
6078 12.5.5 Putting back the pdump_root_objects and pdump_weak_object_chains
6079 -----------------------------------------------------------------------
6080
6081 Same as Putting back the pdump_root_struct_ptrs.
6082
6083 12.5.6 Reorganize the hash tables
6084 ---------------------------------
6085
6086 Since some of the hash values in the lisp hash tables are
6087 address-dependent, their layout is now wrong.  So we go through each of
6088 them and have them resorted by calling `pdump_reorganize_hash_table'.
6089
6090 \1f
6091 File: internals.info,  Node: Remaining issues,  Prev: Reloading phase,  Up: Dumping
6092
6093 12.6 Remaining issues
6094 =====================
6095
6096 The build process will have to start a post-dump xemacs, ask it the
6097 loading address (which will, hopefully, be always the same between
6098 different xemacs invocations) and relocate the file to the new address.
6099 This way the object relocation phase will not have to be done, which
6100 means no writes in the objects and that, because of the use of mmap, the
6101 dumped data will be shared between all the xemacs running on the
6102 computer.
6103
6104    Some executable signature will be necessary to ensure that a given
6105 dump file is really associated with a given executable, or random
6106 crashes will occur.  Maybe a random number set at compile or configure
6107 time thru a define.  This will also allow for having
6108 differently-compiled xemacsen on the same system (mule and no-mule
6109 comes to mind).
6110
6111    The DOC file contents should probably end up in the dump file.
6112
6113 \1f
6114 File: internals.info,  Node: Events and the Event Loop,  Next: Evaluation; Stack Frames; Bindings,  Prev: Dumping,  Up: Top
6115
6116 13 Events and the Event Loop
6117 ****************************
6118
6119 * Menu:
6120
6121 * Introduction to Events::
6122 * Main Loop::
6123 * Specifics of the Event Gathering Mechanism::
6124 * Specifics About the Emacs Event::
6125 * The Event Stream Callback Routines::
6126 * Other Event Loop Functions::
6127 * Converting Events::
6128 * Dispatching Events; The Command Builder::
6129
6130 \1f
6131 File: internals.info,  Node: Introduction to Events,  Next: Main Loop,  Up: Events and the Event Loop
6132
6133 13.1 Introduction to Events
6134 ===========================
6135
6136 An event is an object that encapsulates information about an
6137 interesting occurrence in the operating system.  Events are generated
6138 either by user action, direct (e.g. typing on the keyboard or moving
6139 the mouse) or indirect (moving another window, thereby generating an
6140 expose event on an Emacs frame), or as a result of some other typically
6141 asynchronous action happening, such as output from a subprocess being
6142 ready or a timer expiring.  Events come into the system in an
6143 asynchronous fashion (typically through a callback being called) and
6144 are converted into a synchronous event queue (first-in, first-out) in a
6145 process that we will call "collection".
6146
6147    Note that each application has its own event queue. (It is
6148 immaterial whether the collection process directly puts the events in
6149 the proper application's queue, or puts them into a single system
6150 queue, which is later split up.)
6151
6152    The most basic level of event collection is done by the operating
6153 system or window system.  Typically, XEmacs does its own event
6154 collection as well.  Often there are multiple layers of collection in
6155 XEmacs, with events from various sources being collected into a queue,
6156 which is then combined with other sources to go into another queue
6157 (i.e. a second level of collection), with perhaps another level on top
6158 of this, etc.
6159
6160    XEmacs has its own types of events (called "Emacs events"), which
6161 provides an abstract layer on top of the system-dependent nature of the
6162 most basic events that are received.  Part of the complex nature of the
6163 XEmacs event collection process involves converting from the
6164 operating-system events into the proper Emacs events--there may not be
6165 a one-to-one correspondence.
6166
6167    Emacs events are documented in `events.h'; I'll discuss them later.
6168
6169 \1f
6170 File: internals.info,  Node: Main Loop,  Next: Specifics of the Event Gathering Mechanism,  Prev: Introduction to Events,  Up: Events and the Event Loop
6171
6172 13.2 Main Loop
6173 ==============
6174
6175 The "command loop" is the top-level loop that the editor is always
6176 running.  It loops endlessly, calling `next-event' to retrieve an event
6177 and `dispatch-event' to execute it. `dispatch-event' does the
6178 appropriate thing with non-user events (process, timeout, magic, eval,
6179 mouse motion); this involves calling a Lisp handler function, redrawing
6180 a newly-exposed part of a frame, reading subprocess output, etc.  For
6181 user events, `dispatch-event' looks up the event in relevant keymaps or
6182 menubars; when a full key sequence or menubar selection is reached, the
6183 appropriate function is executed. `dispatch-event' may have to keep
6184 state across calls; this is done in the "command-builder" structure
6185 associated with each console (remember, there's usually only one
6186 console), and the engine that looks up keystrokes and constructs full
6187 key sequences is called the "command builder".  This is documented
6188 elsewhere.
6189
6190    The guts of the command loop are in `command_loop_1()'.  This
6191 function doesn't catch errors, though--that's the job of
6192 `command_loop_2()', which is a condition-case (i.e. error-trapping)
6193 wrapper around `command_loop_1()'.  `command_loop_1()' never returns,
6194 but may get thrown out of.
6195
6196    When an error occurs, `cmd_error()' is called, which usually invokes
6197 the Lisp error handler in `command-error'; however, a default error
6198 handler is provided if `command-error' is `nil' (e.g. during startup).
6199 The purpose of the error handler is simply to display the error message
6200 and do associated cleanup; it does not need to throw anywhere.  When
6201 the error handler finishes, the condition-case in `command_loop_2()'
6202 will finish and `command_loop_2()' will reinvoke `command_loop_1()'.
6203
6204    `command_loop_2()' is invoked from three places: from
6205 `initial_command_loop()' (called from `main()' at the end of internal
6206 initialization), from the Lisp function `recursive-edit', and from
6207 `call_command_loop()'.
6208
6209    `call_command_loop()' is called when a macro is started and when the
6210 minibuffer is entered; normal termination of the macro or minibuffer
6211 causes a throw out of the recursive command loop. (To
6212 `execute-kbd-macro' for macros and `exit' for minibuffers.  Note also
6213 that the low-level minibuffer-entering function,
6214 `read-minibuffer-internal', provides its own error handling and does
6215 not need `command_loop_2()''s error encapsulation; so it tells
6216 `call_command_loop()' to invoke `command_loop_1()' directly.)
6217
6218    Note that both read-minibuffer-internal and recursive-edit set up a
6219 catch for `exit'; this is why `abort-recursive-edit', which throws to
6220 this catch, exits out of either one.
6221
6222    `initial_command_loop()', called from `main()', sets up a catch for
6223 `top-level' when invoking `command_loop_2()', allowing functions to
6224 throw all the way to the top level if they really need to.  Before
6225 invoking `command_loop_2()', `initial_command_loop()' calls
6226 `top_level_1()', which handles all of the startup stuff (creating the
6227 initial frame, handling the command-line options, loading the user's
6228 `.emacs' file, etc.).  The function that actually does this is in Lisp
6229 and is pointed to by the variable `top-level'; normally this function is
6230 `normal-top-level'.  `top_level_1()' is just an error-handling wrapper
6231 similar to `command_loop_2()'.  Note also that `initial_command_loop()'
6232 sets up a catch for `top-level' when invoking `top_level_1()', just
6233 like when it invokes `command_loop_2()'.
6234
6235 \1f
6236 File: internals.info,  Node: Specifics of the Event Gathering Mechanism,  Next: Specifics About the Emacs Event,  Prev: Main Loop,  Up: Events and the Event Loop
6237
6238 13.3 Specifics of the Event Gathering Mechanism
6239 ===============================================
6240
6241 Here is an approximate diagram of the collection processes at work in
6242 XEmacs, under TTY's (TTY's are simpler than X so we'll look at this
6243 first):
6244
6245
6246       asynch.      asynch.    asynch.   asynch.             [Collectors in
6247      kbd events  kbd events   process   process                the OS]
6248            |         |         output    output
6249            |         |           |         |
6250            |         |           |         |      SIGINT,   [signal handlers
6251            |         |           |         |      SIGQUIT,     in XEmacs]
6252            V         V           V         V      SIGWINCH,
6253           file      file        file      file    SIGALRM
6254           desc.     desc.       desc.     desc.     |
6255           (TTY)     (TTY)       (pipe)    (pipe)    |
6256            |          |          |         |      fake    timeouts
6257            |          |          |         |      file        |
6258            |          |          |         |      desc.       |
6259            |          |          |         |      (pipe)      |
6260            |          |          |         |        |         |
6261            |          |          |         |        |         |
6262            |          |          |         |        |         |
6263            V          V          V         V        V         V
6264            ------>-----------<----------------<----------------
6265                        |
6266                        |
6267                        | [collected using select() in emacs_tty_next_event()
6268                        |  and converted to the appropriate Emacs event]
6269                        |
6270                        |
6271                        V          (above this line is TTY-specific)
6272                      Emacs -----------------------------------------------
6273                      event (below this line is the generic event mechanism)
6274                        |
6275                        |
6276      was there     if not, call
6277      a SIGINT?  emacs_tty_next_event()
6278          |             |
6279          |             |
6280          |             |
6281          V             V
6282          --->------<----
6283                 |
6284                 |     [collected in event_stream_next_event();
6285                 |      SIGINT is converted using maybe_read_quit_event()]
6286                 V
6287               Emacs
6288               event
6289                 |
6290                 \---->------>----- maybe_kbd_translate() ---->---\
6291                                                                  |
6292                                                                  |
6293                                                                  |
6294           command event queue                                    |
6295                                                     if not from command
6296        (contains events that were                   event queue, call
6297        read earlier but not processed,              event_stream_next_event()
6298        typically when waiting in a                               |
6299        sit-for, sleep-for, etc. for                              |
6300       a particular event to be received)                         |
6301                     |                                            |
6302                     |                                            |
6303                     V                                            V
6304                     ---->------------------------------------<----
6305                                                     |
6306                                                     | [collected in
6307                                                     |  next_event_internal()]
6308                                                     |
6309       unread-     unread-       event from          |
6310       command-    command-       keyboard       else, call
6311       events      event           macro      next_event_internal()
6312         |           |               |               |
6313         |           |               |               |
6314         |           |               |               |
6315         V           V               V               V
6316         --------->----------------------<------------
6317                           |
6318                           |      [collected in `next-event', which may loop
6319                           |       more than once if the event it gets is on
6320                           |       a dead frame, device, etc.]
6321                           |
6322                           |
6323                           V
6324                  feed into top-level event loop,
6325                  which repeatedly calls `next-event'
6326                  and then dispatches the event
6327                  using `dispatch-event'
6328
6329    Notice the separation between TTY-specific and generic event
6330 mechanism.  When using the Xt-based event loop, the TTY-specific stuff
6331 is replaced but the rest stays the same.
6332
6333    It's also important to realize that only one different kind of
6334 system-specific event loop can be operating at a time, and must be able
6335 to receive all kinds of events simultaneously.  For the two existing
6336 event loops (implemented in `event-tty.c' and `event-Xt.c',
6337 respectively), the TTY event loop _only_ handles TTY consoles, while
6338 the Xt event loop handles _both_ TTY and X consoles.  This situation is
6339 different from all of the output handlers, where you simply have one
6340 per console type.
6341
6342    Here's the Xt Event Loop Diagram (notice that below a certain point,
6343 it's the same as the above diagram):
6344
6345      asynch. asynch. asynch. asynch.                 [Collectors in
6346       kbd     kbd    process process                    the OS]
6347      events  events  output  output
6348        |       |       |       |
6349        |       |       |       |     asynch. asynch. [Collectors in the
6350        |       |       |       |       X        X     OS and X Window System]
6351        |       |       |       |     events  events
6352        |       |       |       |       |        |
6353        |       |       |       |       |        |
6354        |       |       |       |       |        |    SIGINT, [signal handlers
6355        |       |       |       |       |        |    SIGQUIT,   in XEmacs]
6356        |       |       |       |       |        |    SIGWINCH,
6357        |       |       |       |       |        |    SIGALRM
6358        |       |       |       |       |        |       |
6359        |       |       |       |       |        |       |
6360        |       |       |       |       |        |       |      timeouts
6361        |       |       |       |       |        |       |          |
6362        |       |       |       |       |        |       |          |
6363        |       |       |       |       |        |       V          |
6364        V       V       V       V       V        V      fake        |
6365       file    file    file    file    file     file    file        |
6366       desc.   desc.   desc.   desc.   desc.    desc.   desc.       |
6367       (TTY)   (TTY)   (pipe)  (pipe) (socket) (socket) (pipe)      |
6368        |       |       |       |       |        |       |          |
6369        |       |       |       |       |        |       |          |
6370        |       |       |       |       |        |       |          |
6371        V       V       V       V       V        V       V          V
6372        --->----------------------------------------<---------<------
6373             |              |               |
6374             |              |               |[collected using select() in
6375             |              |               | _XtWaitForSomething(), called
6376             |              |               | from XtAppProcessEvent(), called
6377             |              |               | in emacs_Xt_next_event();
6378             |              |               | dispatched to various callbacks]
6379             |              |               |
6380             |              |               |
6381        emacs_Xt_        p_s_callback(),    | [popup_selection_callback]
6382        event_handler()  x_u_v_s_callback(),| [x_update_vertical_scrollbar_
6383             |           x_u_h_s_callback(),|  callback]
6384             |           search_callback()  | [x_update_horizontal_scrollbar_
6385             |              |               |  callback]
6386             |              |               |
6387             |              |               |
6388        enqueue_Xt_       signal_special_   |
6389        dispatch_event()  Xt_user_event()   |
6390        [maybe multiple     |               |
6391         times, maybe 0     |               |
6392         times]             |               |
6393             |            enqueue_Xt_       |
6394             |            dispatch_event()  |
6395             |              |               |
6396             |              |               |
6397             V              V               |
6398             -->----------<--               |
6399                    |                       |
6400                    |                       |
6401                 dispatch             Xt_what_callback()
6402                 event                  sets flags
6403                 queue                      |
6404                    |                       |
6405                    |                       |
6406                    |                       |
6407                    |                       |
6408                    ---->-----------<--------
6409                         |
6410                         |
6411                         |     [collected and converted as appropriate in
6412                         |            emacs_Xt_next_event()]
6413                         |
6414                         |
6415                         V          (above this line is Xt-specific)
6416                       Emacs ------------------------------------------------
6417                       event (below this line is the generic event mechanism)
6418                         |
6419                         |
6420      was there      if not, call
6421      a SIGINT?   emacs_Xt_next_event()
6422          |              |
6423          |              |
6424          |              |
6425          V              V
6426          --->-------<----
6427                 |
6428                 |        [collected in event_stream_next_event();
6429                 |         SIGINT is converted using maybe_read_quit_event()]
6430                 V
6431               Emacs
6432               event
6433                 |
6434                 \---->------>----- maybe_kbd_translate() -->-----\
6435                                                                  |
6436                                                                  |
6437                                                                  |
6438           command event queue                                    |
6439                                                    if not from command
6440        (contains events that were                  event queue, call
6441        read earlier but not processed,             event_stream_next_event()
6442        typically when waiting in a                               |
6443        sit-for, sleep-for, etc. for                              |
6444       a particular event to be received)                         |
6445                     |                                            |
6446                     |                                            |
6447                     V                                            V
6448                     ---->----------------------------------<------
6449                                                     |
6450                                                     | [collected in
6451                                                     |  next_event_internal()]
6452                                                     |
6453       unread-     unread-       event from          |
6454       command-    command-       keyboard       else, call
6455       events      event           macro      next_event_internal()
6456         |           |               |               |
6457         |           |               |               |
6458         |           |               |               |
6459         V           V               V               V
6460         --------->----------------------<------------
6461                           |
6462                           |      [collected in `next-event', which may loop
6463                           |       more than once if the event it gets is on
6464                           |       a dead frame, device, etc.]
6465                           |
6466                           |
6467                           V
6468                  feed into top-level event loop,
6469                  which repeatedly calls `next-event'
6470                  and then dispatches the event
6471                  using `dispatch-event'
6472
6473 \1f
6474 File: internals.info,  Node: Specifics About the Emacs Event,  Next: The Event Stream Callback Routines,  Prev: Specifics of the Event Gathering Mechanism,  Up: Events and the Event Loop
6475
6476 13.4 Specifics About the Emacs Event
6477 ====================================
6478
6479 \1f
6480 File: internals.info,  Node: The Event Stream Callback Routines,  Next: Other Event Loop Functions,  Prev: Specifics About the Emacs Event,  Up: Events and the Event Loop
6481
6482 13.5 The Event Stream Callback Routines
6483 =======================================
6484
6485 \1f
6486 File: internals.info,  Node: Other Event Loop Functions,  Next: Converting Events,  Prev: The Event Stream Callback Routines,  Up: Events and the Event Loop
6487
6488 13.6 Other Event Loop Functions
6489 ===============================
6490
6491 `detect_input_pending()' and `input-pending-p' look for input by
6492 calling `event_stream->event_pending_p' and looking in
6493 `[V]unread-command-event' and the `command_event_queue' (they do not
6494 check for an executing keyboard macro, though).
6495
6496    `discard-input' cancels any command events pending (and any keyboard
6497 macros currently executing), and puts the others onto the
6498 `command_event_queue'.  There is a comment about a "race condition",
6499 which is not a good sign.
6500
6501    `next-command-event' and `read-char' are higher-level interfaces to
6502 `next-event'.  `next-command-event' gets the next "command" event (i.e.
6503 keypress, mouse event, menu selection, or scrollbar action), calling
6504 `dispatch-event' on any others.  `read-char' calls `next-command-event'
6505 and uses `event_to_character()' to return the character equivalent.
6506 With the right kind of input method support, it is possible for
6507 (read-char) to return a Kanji character.
6508
6509 \1f
6510 File: internals.info,  Node: Converting Events,  Next: Dispatching Events; The Command Builder,  Prev: Other Event Loop Functions,  Up: Events and the Event Loop
6511
6512 13.7 Converting Events
6513 ======================
6514
6515 `character_to_event()', `event_to_character()', `event-to-character',
6516 and `character-to-event' convert between characters and keypress events
6517 corresponding to the characters.  If the event was not a keypress,
6518 `event_to_character()' returns -1 and `event-to-character' returns
6519 `nil'.  These functions convert between character representation and
6520 the split-up event representation (keysym plus mod keys).
6521
6522 \1f
6523 File: internals.info,  Node: Dispatching Events; The Command Builder,  Prev: Converting Events,  Up: Events and the Event Loop
6524
6525 13.8 Dispatching Events; The Command Builder
6526 ============================================
6527
6528 Not yet documented.
6529
6530 \1f
6531 File: internals.info,  Node: Evaluation; Stack Frames; Bindings,  Next: Symbols and Variables,  Prev: Events and the Event Loop,  Up: Top
6532
6533 14 Evaluation; Stack Frames; Bindings
6534 *************************************
6535
6536 * Menu:
6537
6538 * Evaluation::
6539 * Dynamic Binding; The specbinding Stack; Unwind-Protects::
6540 * Simple Special Forms::
6541 * Catch and Throw::
6542
6543 \1f
6544 File: internals.info,  Node: Evaluation,  Next: Dynamic Binding; The specbinding Stack; Unwind-Protects,  Up: Evaluation; Stack Frames; Bindings
6545
6546 14.1 Evaluation
6547 ===============
6548
6549 `Feval()' evaluates the form (a Lisp object) that is passed to it.
6550 Note that evaluation is only non-trivial for two types of objects:
6551 symbols and conses.  A symbol is evaluated simply by calling
6552 `symbol-value' on it and returning the value.
6553
6554    Evaluating a cons means calling a function.  First, `eval' checks to
6555 see if garbage-collection is necessary, and calls `garbage_collect_1()'
6556 if so.  It then increases the evaluation depth by 1 (`lisp_eval_depth',
6557 which is always less than `max_lisp_eval_depth') and adds an element to
6558 the linked list of `struct backtrace''s (`backtrace_list').  Each such
6559 structure contains a pointer to the function being called plus a list
6560 of the function's arguments.  Originally these values are stored
6561 unevalled, and as they are evaluated, the backtrace structure is
6562 updated.  Garbage collection pays attention to the objects pointed to
6563 in the backtrace structures (garbage collection might happen while a
6564 function is being called or while an argument is being evaluated, and
6565 there could easily be no other references to the arguments in the
6566 argument list; once an argument is evaluated, however, the unevalled
6567 version is not needed by eval, and so the backtrace structure is
6568 changed).
6569
6570    At this point, the function to be called is determined by looking at
6571 the car of the cons (if this is a symbol, its function definition is
6572 retrieved and the process repeated).  The function should then consist
6573 of either a `Lisp_Subr' (built-in function written in C), a
6574 `Lisp_Compiled_Function' object, or a cons whose car is one of the
6575 symbols `autoload', `macro' or `lambda'.
6576
6577    If the function is a `Lisp_Subr', the lisp object points to a
6578 `struct Lisp_Subr' (created by `DEFUN()'), which contains a pointer to
6579 the C function, a minimum and maximum number of arguments (or possibly
6580 the special constants `MANY' or `UNEVALLED'), a pointer to the symbol
6581 referring to that subr, and a couple of other things.  If the subr
6582 wants its arguments `UNEVALLED', they are passed raw as a list.
6583 Otherwise, an array of evaluated arguments is created and put into the
6584 backtrace structure, and either passed whole (`MANY') or each argument
6585 is passed as a C argument.
6586
6587    If the function is a `Lisp_Compiled_Function',
6588 `funcall_compiled_function()' is called.  If the function is a lambda
6589 list, `funcall_lambda()' is called.  If the function is a macro, [.....
6590 fill in] is done.  If the function is an autoload, `do_autoload()' is
6591 called to load the definition and then eval starts over [explain this
6592 more].
6593
6594    When `Feval()' exits, the evaluation depth is reduced by one, the
6595 debugger is called if appropriate, and the current backtrace structure
6596 is removed from the list.
6597
6598    Both `funcall_compiled_function()' and `funcall_lambda()' need to go
6599 through the list of formal parameters to the function and bind them to
6600 the actual arguments, checking for `&rest' and `&optional' symbols in
6601 the formal parameters and making sure the number of actual arguments is
6602 correct.  `funcall_compiled_function()' can do this a little more
6603 efficiently, since the formal parameter list can be checked for sanity
6604 when the compiled function object is created.
6605
6606    `funcall_lambda()' simply calls `Fprogn' to execute the code in the
6607 lambda list.
6608
6609    `funcall_compiled_function()' calls the real byte-code interpreter
6610 `execute_optimized_program()' on the byte-code instructions, which are
6611 converted into an internal form for faster execution.
6612
6613    When a compiled function is executed for the first time by
6614 `funcall_compiled_function()', or during the dump phase of building
6615 XEmacs, the byte-code instructions are converted from a `Lisp_String'
6616 (which is inefficient to access, especially in the presence of MULE)
6617 into a `Lisp_Opaque' object containing an array of unsigned char, which
6618 can be directly executed by the byte-code interpreter.  At this time
6619 the byte code is also analyzed for validity and transformed into a more
6620 optimized form, so that `execute_optimized_program()' can really fly.
6621
6622    Here are some of the optimizations performed by the internal
6623 byte-code transformer:
6624   1. References to the `constants' array are checked for out-of-range
6625      indices, so that the byte interpreter doesn't have to.
6626
6627   2. References to the `constants' array that will be used as a Lisp
6628      variable are checked for being correct non-constant (i.e. not `t',
6629      `nil', or `keywordp') symbols, so that the byte interpreter
6630      doesn't have to.
6631
6632   3. The maximum number of variable bindings in the byte-code is
6633      pre-computed, so that space on the `specpdl' stack can be
6634      pre-reserved once for the whole function execution.
6635
6636   4. All byte-code jumps are relative to the current program counter
6637      instead of the start of the program, thereby saving a register.
6638
6639   5. One-byte relative jumps are converted from the byte-code form of
6640      unsigned chars offset by 127 to machine-friendly signed chars.
6641
6642    Of course, this transformation of the `instructions' should not be
6643 visible to the user, so `Fcompiled_function_instructions()' needs to
6644 know how to convert the optimized opaque object back into a Lisp string
6645 that is identical to the original string from the `.elc' file.
6646 (Actually, the resulting string may (rarely) contain slightly
6647 different, yet equivalent, byte code.)
6648
6649    `Ffuncall()' implements Lisp `funcall'.  `(funcall fun x1 x2 x3
6650 ...)' is equivalent to `(eval (list fun (quote x1) (quote x2) (quote
6651 x3) ...))'.  `Ffuncall()' contains its own code to do the evaluation,
6652 however, and is very similar to `Feval()'.
6653
6654    From the performance point of view, it is worth knowing that most of
6655 the time in Lisp evaluation is spent executing `Lisp_Subr' and
6656 `Lisp_Compiled_Function' objects via `Ffuncall()' (not `Feval()').
6657
6658    `Fapply()' implements Lisp `apply', which is very similar to
6659 `funcall' except that if the last argument is a list, the result is the
6660 same as if each of the arguments in the list had been passed separately.
6661 `Fapply()' does some business to expand the last argument if it's a
6662 list, then calls `Ffuncall()' to do the work.
6663
6664    `apply1()', `call0()', `call1()', `call2()', and `call3()' call a
6665 function, passing it the argument(s) given (the arguments are given as
6666 separate C arguments rather than being passed as an array).  `apply1()'
6667 uses `Fapply()' while the others use `Ffuncall()' to do the real work.
6668
6669 \1f
6670 File: internals.info,  Node: Dynamic Binding; The specbinding Stack; Unwind-Protects,  Next: Simple Special Forms,  Prev: Evaluation,  Up: Evaluation; Stack Frames; Bindings
6671
6672 14.2 Dynamic Binding; The specbinding Stack; Unwind-Protects
6673 ============================================================
6674
6675      struct specbinding
6676      {
6677        Lisp_Object symbol;
6678        Lisp_Object old_value;
6679        Lisp_Object (*func) (Lisp_Object); /* for unwind-protect */
6680      };
6681
6682    `struct specbinding' is used for local-variable bindings and
6683 unwind-protects.  `specpdl' holds an array of `struct specbinding''s,
6684 `specpdl_ptr' points to the beginning of the free bindings in the
6685 array, `specpdl_size' specifies the total number of binding slots in
6686 the array, and `max_specpdl_size' specifies the maximum number of
6687 bindings the array can be expanded to hold.  `grow_specpdl()' increases
6688 the size of the `specpdl' array, multiplying its size by 2 but never
6689 exceeding `max_specpdl_size' (except that if this number is less than
6690 400, it is first set to 400).
6691
6692    `specbind()' binds a symbol to a value and is used for local
6693 variables and `let' forms.  The symbol and its old value (which might
6694 be `Qunbound', indicating no prior value) are recorded in the specpdl
6695 array, and `specpdl_size' is increased by 1.
6696
6697    `record_unwind_protect()' implements an "unwind-protect", which,
6698 when placed around a section of code, ensures that some specified
6699 cleanup routine will be executed even if the code exits abnormally
6700 (e.g. through a `throw' or quit).  `record_unwind_protect()' simply
6701 adds a new specbinding to the `specpdl' array and stores the
6702 appropriate information in it.  The cleanup routine can either be a C
6703 function, which is stored in the `func' field, or a `progn' form, which
6704 is stored in the `old_value' field.
6705
6706    `unbind_to()' removes specbindings from the `specpdl' array until
6707 the specified position is reached.  Each specbinding can be one of
6708 three types:
6709
6710   1. an unwind-protect with a C cleanup function (`func' is not 0, and
6711      `old_value' holds an argument to be passed to the function);
6712
6713   2. an unwind-protect with a Lisp form (`func' is 0, `symbol' is
6714      `nil', and `old_value' holds the form to be executed with
6715      `Fprogn()'); or
6716
6717   3. a local-variable binding (`func' is 0, `symbol' is not `nil', and
6718      `old_value' holds the old value, which is stored as the symbol's
6719      value).
6720
6721 \1f
6722 File: internals.info,  Node: Simple Special Forms,  Next: Catch and Throw,  Prev: Dynamic Binding; The specbinding Stack; Unwind-Protects,  Up: Evaluation; Stack Frames; Bindings
6723
6724 14.3 Simple Special Forms
6725 =========================
6726
6727 `or', `and', `if', `cond', `progn', `prog1', `prog2', `setq', `quote',
6728 `function', `let*', `let', `while'
6729
6730    All of these are very simple and work as expected, calling `Feval()'
6731 or `Fprogn()' as necessary and (in the case of `let' and `let*') using
6732 `specbind()' to create bindings and `unbind_to()' to undo the bindings
6733 when finished.
6734
6735    Note that, with the exception of `Fprogn', these functions are
6736 typically called in real life only in interpreted code, since the byte
6737 compiler knows how to convert calls to these functions directly into
6738 byte code.
6739