06a85c5c14bb4346b3945d6dadff461a32c86895
[chise/xemacs-chise.git.1] / info / internals.info-1
1 This is ../info/internals.info, produced by makeinfo version 4.6 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 large 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
2988    * Header files should _not_ include `<config.h>' and `"lisp.h"'.  It
2989      is the responsibility of the `.c' files that use it to do so.
2990
2991
2992    Here is a checklist of things to do when creating a new lisp object
2993 type named FOO:
2994
2995   1. create FOO.h
2996
2997   2. create FOO.c
2998
2999   3. add definitions of `syms_of_FOO', etc. to `FOO.c'
3000
3001   4. add declarations of `syms_of_FOO', etc. to `symsinit.h'
3002
3003   5. add calls to `syms_of_FOO', etc. to `emacs.c'
3004
3005   6. add definitions of macros like `CHECK_FOO' and `FOOP' to `FOO.h'
3006
3007   7. add the new type index to `enum lrecord_type'
3008
3009   8. add a DEFINE_LRECORD_IMPLEMENTATION call to `FOO.c'
3010
3011   9. add an INIT_LRECORD_IMPLEMENTATION call to `syms_of_FOO.c'
3012
3013 \1f
3014 File: internals.info,  Node: Regression Testing XEmacs,  Next: A Summary of the Various XEmacs Modules,  Prev: Rules When Writing New C Code,  Up: Top
3015
3016 Regression Testing XEmacs
3017 *************************
3018
3019 The source directory `tests/automated' contains XEmacs' automated test
3020 suite.  The usual way of running all the tests is running `make check'
3021 from the top-level source directory.
3022
3023    The test suite is unfinished and it's still lacking some essential
3024 features.  It is nevertheless recommended that you run the tests to
3025 confirm that XEmacs behaves correctly.
3026
3027    If you want to run a specific test case, you can do it from the
3028 command-line like this:
3029
3030      $ xemacs -batch -l test-harness.elc -f batch-test-emacs TEST-FILE
3031
3032    If something goes wrong, you can run the test suite interactively by
3033 loading `test-harness.el' into a running XEmacs and typing `M-x
3034 test-emacs-test-file RET <filename> RET'.  You will see a log of passed
3035 and failed tests, which should allow you to investigate the source of
3036 the error and ultimately fix the bug.
3037
3038    Adding a new test file is trivial: just create a new file here and it
3039 will be run.  There is no need to byte-compile any of the files in this
3040 directory--the test-harness will take care of any necessary
3041 byte-compilation.
3042
3043    Look at the existing test cases for the examples of coding test
3044 cases.  It all boils down to your imagination and judicious use of the
3045 macros `Assert', `Check-Error', `Check-Error-Message', and
3046 `Check-Message'.
3047
3048    Here's a simple example checking case-sensitive and case-insensitive
3049 comparisons from `case-tests.el'.
3050
3051      (with-temp-buffer
3052        (insert "Test Buffer")
3053        (let ((case-fold-search t))
3054          (goto-char (point-min))
3055          (Assert (eq (search-forward "test buffer" nil t) 12))
3056          (goto-char (point-min))
3057          (Assert (eq (search-forward "Test buffer" nil t) 12))
3058          (goto-char (point-min))
3059          (Assert (eq (search-forward "Test Buffer" nil t) 12))
3060      
3061          (setq case-fold-search nil)
3062          (goto-char (point-min))
3063          (Assert (not (search-forward "test buffer" nil t)))
3064          (goto-char (point-min))
3065          (Assert (not (search-forward "Test buffer" nil t)))
3066          (goto-char (point-min))
3067          (Assert (eq (search-forward "Test Buffer" nil t) 12))))
3068
3069    This example could be inserted in a file in `tests/automated', and
3070 it would be a complete test, automatically executed when you run `make
3071 check' after building XEmacs.  More complex tests may require
3072 substantial temporary scaffolding to create the environment that elicits
3073 the bugs, but the top-level Makefile and `test-harness.el' handle the
3074 running and collection of results from the `Assert', `Check-Error',
3075 `Check-Error-Message', and `Check-Message' macros.
3076
3077    In general, you should avoid using functionality from packages in
3078 your tests, because you can't be sure that everyone will have the
3079 required package.  However, if you've got a test that works, by all
3080 means add it.  Simply wrap the test in an appropriate test, add a
3081 notice that the test was skipped, and update the `skipped-test-reasons'
3082 hashtable.  Here's an example from `syntax-tests.el':
3083
3084      ;; Test forward-comment at buffer boundaries
3085      (with-temp-buffer
3086      
3087        ;; try to use exactly what you need: featurep, boundp, fboundp
3088        (if (not (fboundp 'c-mode))
3089      
3090            ;; We should provide a standard function for this boilerplate,
3091            ;; probably called `Skip-Test' -- check for that API with C-h f
3092            (let* ((reason "c-mode unavailable")
3093              (count (gethash reason skipped-test-reasons)))
3094         (puthash reason (if (null count) 1 (1+ count))
3095                  skipped-test-reasons)
3096         (Print-Skip "comment and parse-partial-sexp tests" reason))
3097      
3098          ;; and here's the test code
3099          (c-mode)
3100          (insert "// comment\n")
3101          (forward-comment -2)
3102          (Assert (eq (point) (point-min)))
3103          (let ((point (point)))
3104            (insert "/* comment */")
3105            (goto-char point)
3106            (forward-comment 2)
3107            (Assert (eq (point) (point-max)))
3108            (parse-partial-sexp point (point-max)))))
3109
3110    `Skip-Test' is intended for use with features that are normally
3111 present in typical configurations.  For truly optional features, or
3112 tests that apply to one of several alternative implementations (eg, to
3113 GTK widgets, but not Athena, Motif, MS Windows, or Carbon), simply
3114 silently omit the test.
3115
3116 \1f
3117 File: internals.info,  Node: A Summary of the Various XEmacs Modules,  Next: Allocation of Objects in XEmacs Lisp,  Prev: Regression Testing XEmacs,  Up: Top
3118
3119 A Summary of the Various XEmacs Modules
3120 ***************************************
3121
3122 This is accurate as of XEmacs 20.0.
3123
3124 * Menu:
3125
3126 * Low-Level Modules::
3127 * Basic Lisp Modules::
3128 * Modules for Standard Editing Operations::
3129 * Editor-Level Control Flow Modules::
3130 * Modules for the Basic Displayable Lisp Objects::
3131 * Modules for other Display-Related Lisp Objects::
3132 * Modules for the Redisplay Mechanism::
3133 * Modules for Interfacing with the File System::
3134 * Modules for Other Aspects of the Lisp Interpreter and Object System::
3135 * Modules for Interfacing with the Operating System::
3136 * Modules for Interfacing with X Windows::
3137 * Modules for Internationalization::
3138 * Modules for Regression Testing::
3139
3140 \1f
3141 File: internals.info,  Node: Low-Level Modules,  Next: Basic Lisp Modules,  Up: A Summary of the Various XEmacs Modules
3142
3143 Low-Level Modules
3144 =================
3145
3146      config.h
3147
3148    This is automatically generated from `config.h.in' based on the
3149 results of configure tests and user-selected optional features and
3150 contains preprocessor definitions specifying the nature of the
3151 environment in which XEmacs is being compiled.
3152
3153      paths.h
3154
3155    This is automatically generated from `paths.h.in' based on supplied
3156 configure values, and allows for non-standard installed configurations
3157 of the XEmacs directories.  It's currently broken, though.
3158
3159      emacs.c
3160      signal.c
3161
3162    `emacs.c' contains `main()' and other code that performs the most
3163 basic environment initializations and handles shutting down the XEmacs
3164 process (this includes `kill-emacs', the normal way that XEmacs is
3165 exited; `dump-emacs', which is used during the build process to write
3166 out the XEmacs executable; `run-emacs-from-temacs', which can be used
3167 to start XEmacs directly when temacs has finished loading all the Lisp
3168 code; and emergency code to handle crashes [XEmacs tries to auto-save
3169 all files before it crashes]).
3170
3171    Low-level code that directly interacts with the Unix signal
3172 mechanism, however, is in `signal.c'.  Note that this code does not
3173 handle system dependencies in interfacing to signals; that is handled
3174 using the `syssignal.h' header file, described in section J below.
3175
3176      unexaix.c
3177      unexalpha.c
3178      unexapollo.c
3179      unexconvex.c
3180      unexec.c
3181      unexelf.c
3182      unexelfsgi.c
3183      unexencap.c
3184      unexenix.c
3185      unexfreebsd.c
3186      unexfx2800.c
3187      unexhp9k3.c
3188      unexhp9k800.c
3189      unexmips.c
3190      unexnext.c
3191      unexsol2.c
3192      unexsunos4.c
3193
3194    These modules contain code dumping out the XEmacs executable on
3195 various different systems. (This process is highly machine-specific and
3196 requires intimate knowledge of the executable format and the memory map
3197 of the process.) Only one of these modules is actually used; this is
3198 chosen by `configure'.
3199
3200      ecrt0.c
3201      lastfile.c
3202      pre-crt0.c
3203
3204    These modules are used in conjunction with the dump mechanism.  On
3205 some systems, an alternative version of the C startup code (the actual
3206 code that receives control from the operating system when the process is
3207 started, and which calls `main()') is required so that the dumping
3208 process works properly; `crt0.c' provides this.
3209
3210    `pre-crt0.c' and `lastfile.c' should be the very first and very last
3211 file linked, respectively. (Actually, this is not really true.
3212 `lastfile.c' should be after all Emacs modules whose initialized data
3213 should be made constant, and before all other Emacs files and all
3214 libraries.  In particular, the allocation modules `gmalloc.c',
3215 `alloca.c', etc. are normally placed past `lastfile.c', and all of the
3216 files that implement Xt widget classes _must_ be placed after
3217 `lastfile.c' because they contain various structures that must be
3218 statically initialized and into which Xt writes at various times.)
3219 `pre-crt0.c' and `lastfile.c' contain exported symbols that are used to
3220 determine the start and end of XEmacs' initialized data space when
3221 dumping.
3222
3223      alloca.c
3224      free-hook.c
3225      getpagesize.h
3226      gmalloc.c
3227      malloc.c
3228      mem-limits.h
3229      ralloc.c
3230      vm-limit.c
3231
3232    These handle basic C allocation of memory.  `alloca.c' is an
3233 emulation of the stack allocation function `alloca()' on machines that
3234 lack this. (XEmacs makes extensive use of `alloca()' in its code.)
3235
3236    `gmalloc.c' and `malloc.c' are two implementations of the standard C
3237 functions `malloc()', `realloc()' and `free()'.  They are often used in
3238 place of the standard system-provided `malloc()' because they usually
3239 provide a much faster implementation, at the expense of additional
3240 memory use.  `gmalloc.c' is a newer implementation that is much more
3241 memory-efficient for large allocations than `malloc.c', and should
3242 always be preferred if it works. (At one point, `gmalloc.c' didn't work
3243 on some systems where `malloc.c' worked; but this should be fixed now.)
3244
3245    `ralloc.c' is the "relocating allocator".  It provides functions
3246 similar to `malloc()', `realloc()' and `free()' that allocate memory
3247 that can be dynamically relocated in memory.  The advantage of this is
3248 that allocated memory can be shuffled around to place all the free
3249 memory at the end of the heap, and the heap can then be shrunk,
3250 releasing the memory back to the operating system.  The use of this can
3251 be controlled with the configure option `--rel-alloc'; if enabled,
3252 memory allocated for buffers will be relocatable, so that if a very
3253 large file is visited and the buffer is later killed, the memory can be
3254 released to the operating system.  (The disadvantage of this mechanism
3255 is that it can be very slow.  On systems with the `mmap()' system call,
3256 the XEmacs version of `ralloc.c' uses this to move memory around
3257 without actually having to block-copy it, which can speed things up;
3258 but it can still cause noticeable performance degradation.)
3259
3260    `free-hook.c' contains some debugging functions for checking for
3261 invalid arguments to `free()'.
3262
3263    `vm-limit.c' contains some functions that warn the user when memory
3264 is getting low.  These are callback functions that are called by
3265 `gmalloc.c' and `malloc.c' at appropriate times.
3266
3267    `getpagesize.h' provides a uniform interface for retrieving the size
3268 of a page in virtual memory.  `mem-limits.h' provides a uniform
3269 interface for retrieving the total amount of available virtual memory.
3270 Both are similar in spirit to the `sys*.h' files described in section
3271 J, below.
3272
3273      blocktype.c
3274      blocktype.h
3275      dynarr.c
3276
3277    These implement a couple of basic C data types to facilitate memory
3278 allocation.  The `Blocktype' type efficiently manages the allocation of
3279 fixed-size blocks by minimizing the number of times that `malloc()' and
3280 `free()' are called.  It allocates memory in large chunks, subdivides
3281 the chunks into blocks of the proper size, and returns the blocks as
3282 requested.  When blocks are freed, they are placed onto a linked list,
3283 so they can be efficiently reused.  This data type is not much used in
3284 XEmacs currently, because it's a fairly new addition.
3285
3286    The `Dynarr' type implements a "dynamic array", which is similar to
3287 a standard C array but has no fixed limit on the number of elements it
3288 can contain.  Dynamic arrays can hold elements of any type, and when
3289 you add a new element, the array automatically resizes itself if it
3290 isn't big enough.  Dynarrs are extensively used in the redisplay
3291 mechanism.
3292
3293      inline.c
3294
3295    This module is used in connection with inline functions (available in
3296 some compilers).  Often, inline functions need to have a corresponding
3297 non-inline function that does the same thing.  This module is where they
3298 reside.  It contains no actual code, but defines some special flags that
3299 cause inline functions defined in header files to be rendered as actual
3300 functions.  It then includes all header files that contain any inline
3301 function definitions, so that each one gets a real function equivalent.
3302
3303      debug.c
3304      debug.h
3305
3306    These functions provide a system for doing internal consistency
3307 checks during code development.  This system is not currently used;
3308 instead the simpler `assert()' macro is used along with the various
3309 checks provided by the `--error-check-*' configuration options.
3310
3311      universe.h
3312
3313    This is not currently used.
3314
3315 \1f
3316 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
3317
3318 Basic Lisp Modules
3319 ==================
3320
3321      lisp-disunion.h
3322      lisp-union.h
3323      lisp.h
3324      lrecord.h
3325      symsinit.h
3326
3327    These are the basic header files for all XEmacs modules.  Each module
3328 includes `lisp.h', which brings the other header files in.  `lisp.h'
3329 contains the definitions of the structures and extractor and
3330 constructor macros for the basic Lisp objects and various other basic
3331 definitions for the Lisp environment, as well as some general-purpose
3332 definitions (e.g. `min()' and `max()').  `lisp.h' includes either
3333 `lisp-disunion.h' or `lisp-union.h', depending on whether
3334 `USE_UNION_TYPE' is defined.  These files define the typedef of the
3335 Lisp object itself (as described above) and the low-level macros that
3336 hide the actual implementation of the Lisp object.  All extractor and
3337 constructor macros for particular types of Lisp objects are defined in
3338 terms of these low-level macros.
3339
3340    As a general rule, all typedefs should go into the typedefs section
3341 of `lisp.h' rather than into a module-specific header file even if the
3342 structure is defined elsewhere.  This allows function prototypes that
3343 use the typedef to be placed into other header files.  Forward structure
3344 declarations (i.e. a simple declaration like `struct foo;' where the
3345 structure itself is defined elsewhere) should be placed into the
3346 typedefs section as necessary.
3347
3348    `lrecord.h' contains the basic structures and macros that implement
3349 all record-type Lisp objects--i.e. all objects whose type is a field in
3350 their C structure, which includes all objects except the few most basic
3351 ones.
3352
3353    `lisp.h' contains prototypes for most of the exported functions in
3354 the various modules.  Lisp primitives defined using `DEFUN' that need
3355 to be called by C code should be declared using `EXFUN'.  Other
3356 function prototypes should be placed either into the appropriate
3357 section of `lisp.h', or into a module-specific header file, depending
3358 on how general-purpose the function is and whether it has
3359 special-purpose argument types requiring definitions not in `lisp.h'.)
3360 All initialization functions are prototyped in `symsinit.h'.
3361
3362      alloc.c
3363
3364    The large module `alloc.c' implements all of the basic allocation and
3365 garbage collection for Lisp objects.  The most commonly used Lisp
3366 objects are allocated in chunks, similar to the Blocktype data type
3367 described above; others are allocated in individually `malloc()'ed
3368 blocks.  This module provides the foundation on which all other aspects
3369 of the Lisp environment sit, and is the first module initialized at
3370 startup.
3371
3372    Note that `alloc.c' provides a series of generic functions that are
3373 not dependent on any particular object type, and interfaces to
3374 particular types of objects using a standardized interface of
3375 type-specific methods.  This scheme is a fundamental principle of
3376 object-oriented programming and is heavily used throughout XEmacs.  The
3377 great advantage of this is that it allows for a clean separation of
3378 functionality into different modules--new classes of Lisp objects, new
3379 event interfaces, new device types, new stream interfaces, etc. can be
3380 added transparently without affecting code anywhere else in XEmacs.
3381 Because the different subsystems are divided into general and specific
3382 code, adding a new subtype within a subsystem will in general not
3383 require changes to the generic subsystem code or affect any of the other
3384 subtypes in the subsystem; this provides a great deal of robustness to
3385 the XEmacs code.
3386
3387      eval.c
3388      backtrace.h
3389
3390    This module contains all of the functions to handle the flow of
3391 control.  This includes the mechanisms of defining functions, calling
3392 functions, traversing stack frames, and binding variables; the control
3393 primitives and other special forms such as `while', `if', `eval',
3394 `let', `and', `or', `progn', etc.; handling of non-local exits,
3395 unwind-protects, and exception handlers; entering the debugger; methods
3396 for the subr Lisp object type; etc.  It does _not_ include the `read'
3397 function, the `print' function, or the handling of symbols and obarrays.
3398
3399    `backtrace.h' contains some structures related to stack frames and
3400 the flow of control.
3401
3402      lread.c
3403
3404    This module implements the Lisp reader and the `read' function,
3405 which converts text into Lisp objects, according to the read syntax of
3406 the objects, as described above.  This is similar to the parser that is
3407 a part of all compilers.
3408
3409      print.c
3410
3411    This module implements the Lisp print mechanism and the `print'
3412 function and related functions.  This is the inverse of the Lisp reader
3413 - it converts Lisp objects to a printed, textual representation.
3414 (Hopefully something that can be read back in using `read' to get an
3415 equivalent object.)
3416
3417      general.c
3418      symbols.c
3419      symeval.h
3420
3421    `symbols.c' implements the handling of symbols, obarrays, and
3422 retrieving the values of symbols.  Much of the code is devoted to
3423 handling the special "symbol-value-magic" objects that define special
3424 types of variables--this includes buffer-local variables, variable
3425 aliases, variables that forward into C variables, etc.  This module is
3426 initialized extremely early (right after `alloc.c'), because it is here
3427 that the basic symbols `t' and `nil' are created, and those symbols are
3428 used everywhere throughout XEmacs.
3429
3430    `symeval.h' contains the definitions of symbol structures and the
3431 `DEFVAR_LISP()' and related macros for declaring variables.
3432
3433      data.c
3434      floatfns.c
3435      fns.c
3436
3437    These modules implement the methods and standard Lisp primitives for
3438 all the basic Lisp object types other than symbols (which are described
3439 above).  `data.c' contains all the predicates (primitives that return
3440 whether an object is of a particular type); the integer arithmetic
3441 functions; and the basic accessor and mutator primitives for the various
3442 object types.  `fns.c' contains all the standard predicates for working
3443 with sequences (where, abstractly speaking, a sequence is an ordered set
3444 of objects, and can be represented by a list, string, vector, or
3445 bit-vector); it also contains `equal', perhaps on the grounds that bulk
3446 of the operation of `equal' is comparing sequences.  `floatfns.c'
3447 contains methods and primitives for floats and floating-point
3448 arithmetic.
3449
3450      bytecode.c
3451      bytecode.h
3452
3453    `bytecode.c' implements the byte-code interpreter and
3454 compiled-function objects, and `bytecode.h' contains associated
3455 structures.  Note that the byte-code _compiler_ is written in Lisp.
3456
3457 \1f
3458 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
3459
3460 Modules for Standard Editing Operations
3461 =======================================
3462
3463      buffer.c
3464      buffer.h
3465      bufslots.h
3466
3467    `buffer.c' implements the "buffer" Lisp object type.  This includes
3468 functions that create and destroy buffers; retrieve buffers by name or
3469 by other properties; manipulate lists of buffers (remember that buffers
3470 are permanent objects and stored in various ordered lists); retrieve or
3471 change buffer properties; etc.  It also contains the definitions of all
3472 the built-in buffer-local variables (which can be viewed as buffer
3473 properties).  It does _not_ contain code to manipulate buffer-local
3474 variables (that's in `symbols.c', described above); or code to
3475 manipulate the text in a buffer.
3476
3477    `buffer.h' defines the structures associated with a buffer and the
3478 various macros for retrieving text from a buffer and special buffer
3479 positions (e.g. `point', the default location for text insertion).  It
3480 also contains macros for working with buffer positions and converting
3481 between their representations as character offsets and as byte offsets
3482 (under MULE, they are different, because characters can be multi-byte).
3483 It is one of the largest header files.
3484
3485    `bufslots.h' defines the fields in the buffer structure that
3486 correspond to the built-in buffer-local variables.  It is its own
3487 header file because it is included many times in `buffer.c', as a way
3488 of iterating over all the built-in buffer-local variables.
3489
3490      insdel.c
3491      insdel.h
3492
3493    `insdel.c' contains low-level functions for inserting and deleting
3494 text in a buffer, keeping track of changed regions for use by
3495 redisplay, and calling any before-change and after-change functions
3496 that may have been registered for the buffer.  It also contains the
3497 actual functions that convert between byte offsets and character
3498 offsets.
3499
3500    `insdel.h' contains associated headers.
3501
3502      marker.c
3503
3504    This module implements the "marker" Lisp object type, which
3505 conceptually is a pointer to a text position in a buffer that moves
3506 around as text is inserted and deleted, so as to remain in the same
3507 relative position.  This module doesn't actually move the markers around
3508 - that's handled in `insdel.c'.  This module just creates them and
3509 implements the primitives for working with them.  As markers are simple
3510 objects, this does not entail much.
3511
3512    Note that the standard arithmetic primitives (e.g. `+') accept
3513 markers in place of integers and automatically substitute the value of
3514 `marker-position' for the marker, i.e. an integer describing the
3515 current buffer position of the marker.
3516
3517      extents.c
3518      extents.h
3519
3520    This module implements the "extent" Lisp object type, which is like
3521 a marker that works over a range of text rather than a single position.
3522 Extents are also much more complex and powerful than markers and have a
3523 more efficient (and more algorithmically complex) implementation.  The
3524 implementation is described in detail in comments in `extents.c'.
3525
3526    The code in `extents.c' works closely with `insdel.c' so that
3527 extents are properly moved around as text is inserted and deleted.
3528 There is also code in `extents.c' that provides information needed by
3529 the redisplay mechanism for efficient operation. (Remember that extents
3530 can have display properties that affect [sometimes drastically, as in
3531 the `invisible' property] the display of the text they cover.)
3532
3533      editfns.c
3534
3535    `editfns.c' contains the standard Lisp primitives for working with a
3536 buffer's text, and calls the low-level functions in `insdel.c'.  It
3537 also contains primitives for working with `point' (the default buffer
3538 insertion location).
3539
3540    `editfns.c' also contains functions for retrieving various
3541 characteristics from the external environment: the current time, the
3542 process ID of the running XEmacs process, the name of the user who ran
3543 this XEmacs process, etc.  It's not clear why this code is in
3544 `editfns.c'.
3545
3546      callint.c
3547      cmds.c
3548      commands.h
3549
3550    These modules implement the basic "interactive" commands, i.e.
3551 user-callable functions.  Commands, as opposed to other functions, have
3552 special ways of getting their parameters interactively (by querying the
3553 user), as opposed to having them passed in a normal function
3554 invocation.  Many commands are not really meant to be called from other
3555 Lisp functions, because they modify global state in a way that's often
3556 undesired as part of other Lisp functions.
3557
3558    `callint.c' implements the mechanism for querying the user for
3559 parameters and calling interactive commands.  The bulk of this module is
3560 code that parses the interactive spec that is supplied with an
3561 interactive command.
3562
3563    `cmds.c' implements the basic, most commonly used editing commands:
3564 commands to move around the current buffer and insert and delete
3565 characters.  These commands are implemented using the Lisp primitives
3566 defined in `editfns.c'.
3567
3568    `commands.h' contains associated structure definitions and
3569 prototypes.
3570
3571      regex.c
3572      regex.h
3573      search.c
3574
3575    `search.c' implements the Lisp primitives for searching for text in
3576 a buffer, and some of the low-level algorithms for doing this.  In
3577 particular, the fast fixed-string Boyer-Moore search algorithm is
3578 implemented in `search.c'.  The low-level algorithms for doing
3579 regular-expression searching, however, are implemented in `regex.c' and
3580 `regex.h'.  These two modules are largely independent of XEmacs, and
3581 are similar to (and based upon) the regular-expression routines used in
3582 `grep' and other GNU utilities.
3583
3584      doprnt.c
3585
3586    `doprnt.c' implements formatted-string processing, similar to
3587 `printf()' command in C.
3588
3589      undo.c
3590
3591    This module implements the undo mechanism for tracking buffer
3592 changes.  Most of this could be implemented in Lisp.
3593
3594 \1f
3595 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
3596
3597 Editor-Level Control Flow Modules
3598 =================================
3599
3600      event-Xt.c
3601      event-msw.c
3602      event-stream.c
3603      event-tty.c
3604      events-mod.h
3605      gpmevent.c
3606      gpmevent.h
3607      events.c
3608      events.h
3609
3610    These implement the handling of events (user input and other system
3611 notifications).
3612
3613    `events.c' and `events.h' define the "event" Lisp object type and
3614 primitives for manipulating it.
3615
3616    `event-stream.c' implements the basic functions for working with
3617 event queues, dispatching an event by looking it up in relevant keymaps
3618 and such, and handling timeouts; this includes the primitives
3619 `next-event' and `dispatch-event', as well as related primitives such
3620 as `sit-for', `sleep-for', and `accept-process-output'.
3621 (`event-stream.c' is one of the hairiest and trickiest modules in
3622 XEmacs.  Beware!  You can easily mess things up here.)
3623
3624    `event-Xt.c' and `event-tty.c' implement the low-level interfaces
3625 onto retrieving events from Xt (the X toolkit) and from TTY's (using
3626 `read()' and `select()'), respectively.  The event interface enforces a
3627 clean separation between the specific code for interfacing with the
3628 operating system and the generic code for working with events, by
3629 defining an API of basic, low-level event methods; `event-Xt.c' and
3630 `event-tty.c' are two different implementations of this API.  To add
3631 support for a new operating system (e.g. NeXTstep), one merely needs to
3632 provide another implementation of those API functions.
3633
3634    Note that the choice of whether to use `event-Xt.c' or `event-tty.c'
3635 is made at compile time!  Or at the very latest, it is made at startup
3636 time.  `event-Xt.c' handles events for _both_ X and TTY frames;
3637 `event-tty.c' is only used when X support is not compiled into XEmacs.
3638 The reason for this is that there is only one event loop in XEmacs:
3639 thus, it needs to be able to receive events from all different kinds of
3640 frames.
3641
3642      keymap.c
3643      keymap.h
3644
3645    `keymap.c' and `keymap.h' define the "keymap" Lisp object type and
3646 associated methods and primitives. (Remember that keymaps are objects
3647 that associate event descriptions with functions to be called to
3648 "execute" those events; `dispatch-event' looks up events in the
3649 relevant keymaps.)
3650
3651      cmdloop.c
3652
3653    `cmdloop.c' contains functions that implement the actual editor
3654 command loop--i.e. the event loop that cyclically retrieves and
3655 dispatches events.  This code is also rather tricky, just like
3656 `event-stream.c'.
3657
3658      macros.c
3659      macros.h
3660
3661    These two modules contain the basic code for defining keyboard
3662 macros.  These functions don't actually do much; most of the code that
3663 handles keyboard macros is mixed in with the event-handling code in
3664 `event-stream.c'.
3665
3666      minibuf.c
3667
3668    This contains some miscellaneous code related to the minibuffer
3669 (most of the minibuffer code was moved into Lisp by Richard Mlynarik).
3670 This includes the primitives for completion (although filename
3671 completion is in `dired.c'), the lowest-level interface to the
3672 minibuffer (if the command loop were cleaned up, this too could be in
3673 Lisp), and code for dealing with the echo area (this, too, was mostly
3674 moved into Lisp, and the only code remaining is code to call out to
3675 Lisp or provide simple bootstrapping implementations early in temacs,
3676 before the echo-area Lisp code is loaded).
3677
3678 \1f
3679 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
3680
3681 Modules for the Basic Displayable Lisp Objects
3682 ==============================================
3683
3684      console-msw.c
3685      console-msw.h
3686      console-stream.c
3687      console-stream.h
3688      console-tty.c
3689      console-tty.h
3690      console-x.c
3691      console-x.h
3692      console.c
3693      console.h
3694
3695    These modules implement the "console" Lisp object type.  A console
3696 contains multiple display devices, but only one keyboard and mouse.
3697 Most of the time, a console will contain exactly one device.
3698
3699    Consoles are the top of a lisp object inclusion hierarchy.  Consoles
3700 contain devices, which contain frames, which contain windows.
3701
3702      device-msw.c
3703      device-tty.c
3704      device-x.c
3705      device.c
3706      device.h
3707
3708    These modules implement the "device" Lisp object type.  This
3709 abstracts a particular screen or connection on which frames are
3710 displayed.  As with Lisp objects, event interfaces, and other
3711 subsystems, the device code is separated into a generic component that
3712 contains a standardized interface (in the form of a set of methods) onto
3713 particular device types.
3714
3715    The device subsystem defines all the methods and provides method
3716 services for not only device operations but also for the frame, window,
3717 menubar, scrollbar, toolbar, and other displayable-object subsystems.
3718 The reason for this is that all of these subsystems have the same
3719 subtypes (X, TTY, NeXTstep, Microsoft Windows, etc.) as devices do.
3720
3721      frame-msw.c
3722      frame-tty.c
3723      frame-x.c
3724      frame.c
3725      frame.h
3726
3727    Each device contains one or more frames in which objects (e.g. text)
3728 are displayed.  A frame corresponds to a window in the window system;
3729 usually this is a top-level window but it could potentially be one of a
3730 number of overlapping child windows within a top-level window, using the
3731 MDI (Multiple Document Interface) protocol in Microsoft Windows or a
3732 similar scheme.
3733
3734    The `frame-*' files implement the "frame" Lisp object type and
3735 provide the generic and device-type-specific operations on frames (e.g.
3736 raising, lowering, resizing, moving, etc.).
3737
3738      window.c
3739      window.h
3740
3741    Each frame consists of one or more non-overlapping "windows" (better
3742 known as "panes" in standard window-system terminology) in which a
3743 buffer's text can be displayed.  Windows can also have scrollbars
3744 displayed around their edges.
3745
3746    `window.c' and `window.h' implement the "window" Lisp object type
3747 and provide code to manage windows.  Since windows have no associated
3748 resources in the window system (the window system knows only about the
3749 frame; no child windows or anything are used for XEmacs windows), there
3750 is no device-type-specific code here; all of that code is part of the
3751 redisplay mechanism or the code for particular object types such as
3752 scrollbars.
3753
3754 \1f
3755 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
3756
3757 Modules for other Display-Related Lisp Objects
3758 ==============================================
3759
3760      faces.c
3761      faces.h
3762
3763      bitmaps.h
3764      glyphs-eimage.c
3765      glyphs-msw.c
3766      glyphs-msw.h
3767      glyphs-widget.c
3768      glyphs-x.c
3769      glyphs-x.h
3770      glyphs.c
3771      glyphs.h
3772
3773      objects-msw.c
3774      objects-msw.h
3775      objects-tty.c
3776      objects-tty.h
3777      objects-x.c
3778      objects-x.h
3779      objects.c
3780      objects.h
3781
3782      menubar-msw.c
3783      menubar-msw.h
3784      menubar-x.c
3785      menubar.c
3786      menubar.h
3787
3788      scrollbar-msw.c
3789      scrollbar-msw.h
3790      scrollbar-x.c
3791      scrollbar-x.h
3792      scrollbar.c
3793      scrollbar.h
3794
3795      toolbar-msw.c
3796      toolbar-x.c
3797      toolbar.c
3798      toolbar.h
3799
3800      font-lock.c
3801
3802    This file provides C support for syntax highlighting--i.e.
3803 highlighting different syntactic constructs of a source file in
3804 different colors, for easy reading.  The C support is provided so that
3805 this is fast.
3806
3807    As of 21.4.10, bugs introduced at the very end of the 21.2 series in
3808 the "syntax properties" code were fixed, and highlighting is acceptably
3809 quick again.  However, presumably more improvements are possible, and
3810 the places to look are probably here, in the defun-traversing code, and
3811 in `syntax.c', in the comment-traversing code.
3812
3813      dgif_lib.c
3814      gif_err.c
3815      gif_lib.h
3816      gifalloc.c
3817
3818    These modules decode GIF-format image files, for use with glyphs.
3819 These files were removed due to Unisys patent infringement concerns.
3820
3821 \1f
3822 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
3823
3824 Modules for the Redisplay Mechanism
3825 ===================================
3826
3827      redisplay-output.c
3828      redisplay-msw.c
3829      redisplay-tty.c
3830      redisplay-x.c
3831      redisplay.c
3832      redisplay.h
3833
3834    These files provide the redisplay mechanism.  As with many other
3835 subsystems in XEmacs, there is a clean separation between the general
3836 and device-specific support.
3837
3838    `redisplay.c' contains the bulk of the redisplay engine.  These
3839 functions update the redisplay structures (which describe how the screen
3840 is to appear) to reflect any changes made to the state of any
3841 displayable objects (buffer, frame, window, etc.) since the last time
3842 that redisplay was called.  These functions are highly optimized to
3843 avoid doing more work than necessary (since redisplay is called
3844 extremely often and is potentially a huge time sink), and depend heavily
3845 on notifications from the objects themselves that changes have occurred,
3846 so that redisplay doesn't explicitly have to check each possible object.
3847 The redisplay mechanism also contains a great deal of caching to further
3848 speed things up; some of this caching is contained within the various
3849 displayable objects.
3850
3851    `redisplay-output.c' goes through the redisplay structures and
3852 converts them into calls to device-specific methods to actually output
3853 the screen changes.
3854
3855    `redisplay-x.c' and `redisplay-tty.c' are two implementations of
3856 these redisplay output methods, for X frames and TTY frames,
3857 respectively.
3858
3859      indent.c
3860
3861    This module contains various functions and Lisp primitives for
3862 converting between buffer positions and screen positions.  These
3863 functions call the redisplay mechanism to do most of the work, and then
3864 examine the redisplay structures to get the necessary information.  This
3865 module needs work.
3866
3867      termcap.c
3868      terminfo.c
3869      tparam.c
3870
3871    These files contain functions for working with the termcap
3872 (BSD-style) and terminfo (System V style) databases of terminal
3873 capabilities and escape sequences, used when XEmacs is displaying in a
3874 TTY.
3875
3876      cm.c
3877      cm.h
3878
3879    These files provide some miscellaneous TTY-output functions and
3880 should probably be merged into `redisplay-tty.c'.
3881
3882 \1f
3883 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
3884
3885 Modules for Interfacing with the File System
3886 ============================================
3887
3888      lstream.c
3889      lstream.h
3890
3891    These modules implement the "stream" Lisp object type.  This is an
3892 internal-only Lisp object that implements a generic buffering stream.
3893 The idea is to provide a uniform interface onto all sources and sinks of
3894 data, including file descriptors, stdio streams, chunks of memory, Lisp
3895 buffers, Lisp strings, etc.  That way, I/O functions can be written to
3896 the stream interface and can transparently handle all possible sources
3897 and sinks.  (For example, the `read' function can read data from a
3898 file, a string, a buffer, or even a function that is called repeatedly
3899 to return data, without worrying about where the data is coming from or
3900 what-size chunks it is returned in.)
3901
3902    Note that in the C code, streams are called "lstreams" (for "Lisp
3903 streams") to distinguish them from other kinds of streams, e.g. stdio
3904 streams and C++ I/O streams.
3905
3906    Similar to other subsystems in XEmacs, lstreams are separated into
3907 generic functions and a set of methods for the different types of
3908 lstreams.  `lstream.c' provides implementations of many different types
3909 of streams; others are provided, e.g., in `file-coding.c'.
3910
3911      fileio.c
3912
3913    This implements the basic primitives for interfacing with the file
3914 system.  This includes primitives for reading files into buffers,
3915 writing buffers into files, checking for the presence or accessibility
3916 of files, canonicalizing file names, etc.  Note that these primitives
3917 are usually not invoked directly by the user: There is a great deal of
3918 higher-level Lisp code that implements the user commands such as
3919 `find-file' and `save-buffer'.  This is similar to the distinction
3920 between the lower-level primitives in `editfns.c' and the higher-level
3921 user commands in `commands.c' and `simple.el'.
3922
3923      filelock.c
3924
3925    This file provides functions for detecting clashes between different
3926 processes (e.g. XEmacs and some external process, or two different
3927 XEmacs processes) modifying the same file.  (XEmacs can optionally use
3928 the `lock/' subdirectory to provide a form of "locking" between
3929 different XEmacs processes.)  This module is also used by the low-level
3930 functions in `insdel.c' to ensure that, if the first modification is
3931 being made to a buffer whose corresponding file has been externally
3932 modified, the user is made aware of this so that the buffer can be
3933 synched up with the external changes if necessary.
3934
3935      filemode.c
3936
3937    This file provides some miscellaneous functions that construct a
3938 `rwxr-xr-x'-type permissions string (as might appear in an `ls'-style
3939 directory listing) given the information returned by the `stat()'
3940 system call.
3941
3942      dired.c
3943      ndir.h
3944
3945    These files implement the XEmacs interface to directory searching.
3946 This includes a number of primitives for determining the files in a
3947 directory and for doing filename completion. (Remember that generic
3948 completion is handled by a different mechanism, in `minibuf.c'.)
3949
3950    `ndir.h' is a header file used for the directory-searching emulation
3951 functions provided in `sysdep.c' (see section J below), for systems
3952 that don't provide any directory-searching functions. (On those
3953 systems, directories can be read directly as files, and parsed.)
3954
3955      realpath.c
3956
3957    This file provides an implementation of the `realpath()' function
3958 for expanding symbolic links, on systems that don't implement it or have
3959 a broken implementation.
3960
3961 \1f
3962 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
3963
3964 Modules for Other Aspects of the Lisp Interpreter and Object System
3965 ===================================================================
3966
3967      elhash.c
3968      elhash.h
3969      hash.c
3970      hash.h
3971
3972    These files provide two implementations of hash tables.  Files
3973 `hash.c' and `hash.h' provide a generic C implementation of hash tables
3974 which can stand independently of XEmacs.  Files `elhash.c' and
3975 `elhash.h' provide a separate implementation of hash tables that can
3976 store only Lisp objects, and knows about Lispy things like garbage
3977 collection, and implement the "hash-table" Lisp object type.
3978
3979      specifier.c
3980      specifier.h
3981
3982    This module implements the "specifier" Lisp object type.  This is
3983 primarily used for displayable properties, and allows for values that
3984 are specific to a particular buffer, window, frame, device, or device
3985 class, as well as a default value existing.  This is used, for example,
3986 to control the height of the horizontal scrollbar or the appearance of
3987 the `default', `bold', or other faces.  The specifier object consists
3988 of a number of specifications, each of which maps from a buffer,
3989 window, etc. to a value.  The function `specifier-instance' looks up a
3990 value given a window (from which a buffer, frame, and device can be
3991 derived).
3992
3993      chartab.c
3994      chartab.h
3995      casetab.c
3996
3997    `chartab.c' and `chartab.h' implement the "char table" Lisp object
3998 type, which maps from characters or certain sorts of character ranges
3999 to Lisp objects.  The implementation of this object type is optimized
4000 for the internal representation of characters.  Char tables come in
4001 different types, which affect the allowed object types to which a
4002 character can be mapped and also dictate certain other properties of
4003 the char table.
4004
4005    `casetab.c' implements one sort of char table, the "case table",
4006 which maps characters to other characters of possibly different case.
4007 These are used by XEmacs to implement case-changing primitives and to
4008 do case-insensitive searching.
4009
4010      syntax.c
4011      syntax.h
4012
4013    This module implements "syntax tables", another sort of char table
4014 that maps characters into syntax classes that define the syntax of these
4015 characters (e.g. a parenthesis belongs to a class of `open' characters
4016 that have corresponding `close' characters and can be nested).  This
4017 module also implements the Lisp "scanner", a set of primitives for
4018 scanning over text based on syntax tables.  This is used, for example,
4019 to find the matching parenthesis in a command such as `forward-sexp',
4020 and by `font-lock.c' to locate quoted strings, comments, etc.
4021
4022    Syntax codes are implemented as bitfields in an int.  Bits 0-6
4023 contain the syntax code itself, bit 7 is a special prefix flag used for
4024 Lisp, and bits 16-23 contain comment syntax flags.  From the Lisp
4025 programmer's point of view, there are 11 flags: 2 styles X 2 characters
4026 X {start, end} flags for two-character comment delimiters, 2 style
4027 flags for one-character comment delimiters, and the prefix flag.
4028
4029    Internally, however, the characters used in multi-character
4030 delimiters will have non-comment-character syntax classes (_e.g._, the
4031 `/' in C's `/*' comment-start delimiter has "punctuation" (here meaning
4032 "operator-like") class in C modes).  Thus in a mixed comment style,
4033 such as C++'s `//' to end of line, is represented by giving `/' the
4034 "punctuation" class and the "style b first character of start sequence"
4035 and "style b second character of start sequence" flags.  The fact that
4036 class is _not_ punctuation allows the syntax scanner to recognize that
4037 this is a multi-character delimiter.  The `newline' character is given
4038 (single-character) "comment-end" _class_ and the "style b first
4039 character of end sequence" _flag_.  The "comment-end" class allows the
4040 scanner to determine that no second character is needed to terminate
4041 the comment.
4042
4043      casefiddle.c
4044
4045    This module implements various Lisp primitives for upcasing,
4046 downcasing and capitalizing strings or regions of buffers.
4047
4048      rangetab.c
4049
4050    This module implements the "range table" Lisp object type, which
4051 provides for a mapping from ranges of integers to arbitrary Lisp
4052 objects.
4053
4054      opaque.c
4055      opaque.h
4056
4057    This module implements the "opaque" Lisp object type, an
4058 internal-only Lisp object that encapsulates an arbitrary block of memory
4059 so that it can be managed by the Lisp allocation system.  To create an
4060 opaque object, you call `make_opaque()', passing a pointer to a block
4061 of memory.  An object is created that is big enough to hold the memory,
4062 which is copied into the object's storage.  The object will then stick
4063 around as long as you keep pointers to it, after which it will be
4064 automatically reclaimed.
4065
4066    Opaque objects can also have an arbitrary "mark method" associated
4067 with them, in case the block of memory contains other Lisp objects that
4068 need to be marked for garbage-collection purposes. (If you need other
4069 object methods, such as a finalize method, you should just go ahead and
4070 create a new Lisp object type--it's not hard.)
4071
4072      abbrev.c
4073
4074    This function provides a few primitives for doing dynamic
4075 abbreviation expansion.  In XEmacs, most of the code for this has been
4076 moved into Lisp.  Some C code remains for speed and because the
4077 primitive `self-insert-command' (which is executed for all
4078 self-inserting characters) hooks into the abbrev mechanism.
4079 (`self-insert-command' is itself in C only for speed.)
4080
4081      doc.c
4082
4083    This function provides primitives for retrieving the documentation
4084 strings of functions and variables.  These documentation strings contain
4085 certain special markers that get dynamically expanded (e.g. a
4086 reverse-lookup is performed on some named functions to retrieve their
4087 current key bindings).  Some documentation strings (in particular, for
4088 the built-in primitives and pre-loaded Lisp functions) are stored
4089 externally in a file `DOC' in the `lib-src/' directory and need to be
4090 fetched from that file. (Part of the build stage involves building this
4091 file, and another part involves constructing an index for this file and
4092 embedding it into the executable, so that the functions in `doc.c' do
4093 not have to search the entire `DOC' file to find the appropriate
4094 documentation string.)
4095
4096      md5.c
4097
4098    This function provides a Lisp primitive that implements the MD5
4099 secure hashing scheme, used to create a large hash value of a string of
4100 data such that the data cannot be derived from the hash value.  This is
4101 used for various security applications on the Internet.
4102
4103 \1f
4104 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
4105
4106 Modules for Interfacing with the Operating System
4107 =================================================
4108
4109      callproc.c
4110      process.c
4111      process.h
4112
4113    These modules allow XEmacs to spawn and communicate with subprocesses
4114 and network connections.
4115
4116    `callproc.c' implements (through the `call-process' primitive) what
4117 are called "synchronous subprocesses".  This means that XEmacs runs a
4118 program, waits till it's done, and retrieves its output.  A typical
4119 example might be calling the `ls' program to get a directory listing.
4120
4121    `process.c' and `process.h' implement "asynchronous subprocesses".
4122 This means that XEmacs starts a program and then continues normally,
4123 not waiting for the process to finish.  Data can be sent to the process
4124 or retrieved from it as it's running.  This is used for the `shell'
4125 command (which provides a front end onto a shell program such as
4126 `csh'), the mail and news readers implemented in XEmacs, etc.  The
4127 result of calling `start-process' to start a subprocess is a process
4128 object, a particular kind of object used to communicate with the
4129 subprocess.  You can send data to the process by passing the process
4130 object and the data to `send-process', and you can specify what happens
4131 to data retrieved from the process by setting properties of the process
4132 object. (When the process sends data, XEmacs receives a process event,
4133 which says that there is data ready.  When `dispatch-event' is called
4134 on this event, it reads the data from the process and does something
4135 with it, as specified by the process object's properties.  Typically,
4136 this means inserting the data into a buffer or calling a function.)
4137 Another property of the process object is called the "sentinel", which
4138 is a function that is called when the process terminates.
4139
4140    Process objects are also used for network connections (connections
4141 to a process running on another machine).  Network connections are
4142 started with `open-network-stream' but otherwise work just like
4143 subprocesses.
4144
4145      sysdep.c
4146      sysdep.h
4147
4148    These modules implement most of the low-level, messy operating-system
4149 interface code.  This includes various device control (ioctl) operations
4150 for file descriptors, TTY's, pseudo-terminals, etc. (usually this stuff
4151 is fairly system-dependent; thus the name of this module), and emulation
4152 of standard library functions and system calls on systems that don't
4153 provide them or have broken versions.
4154
4155      sysdir.h
4156      sysfile.h
4157      sysfloat.h
4158      sysproc.h
4159      syspwd.h
4160      syssignal.h
4161      systime.h
4162      systty.h
4163      syswait.h
4164
4165    These header files provide consistent interfaces onto
4166 system-dependent header files and system calls.  The idea is that,
4167 instead of including a standard header file like `<sys/param.h>' (which
4168 may or may not exist on various systems) or having to worry about
4169 whether all system provide a particular preprocessor constant, or
4170 having to deal with the four different paradigms for manipulating
4171 signals, you just include the appropriate `sys*.h' header file, which
4172 includes all the right system header files, defines and missing
4173 preprocessor constants, provides a uniform interface onto system calls,
4174 etc.
4175
4176    `sysdir.h' provides a uniform interface onto directory-querying
4177 functions. (In some cases, this is in conjunction with emulation
4178 functions in `sysdep.c'.)
4179
4180    `sysfile.h' includes all the necessary header files for standard
4181 system calls (e.g. `read()'), ensures that all necessary `open()' and
4182 `stat()' preprocessor constants are defined, and possibly (usually)
4183 substitutes sugared versions of `read()', `write()', etc. that
4184 automatically restart interrupted I/O operations.
4185
4186    `sysfloat.h' includes the necessary header files for floating-point
4187 operations.
4188
4189    `sysproc.h' includes the necessary header files for calling
4190 `select()', `fork()', `execve()', socket operations, and the like, and
4191 ensures that the `FD_*()' macros for descriptor-set manipulations are
4192 available.
4193
4194    `syspwd.h' includes the necessary header files for obtaining
4195 information from `/etc/passwd' (the functions are emulated under VMS).
4196
4197    `syssignal.h' includes the necessary header files for
4198 signal-handling and provides a uniform interface onto the different
4199 signal-handling and signal-blocking paradigms.
4200
4201    `systime.h' includes the necessary header files and provides uniform
4202 interfaces for retrieving the time of day, setting file
4203 access/modification times, getting the amount of time used by the XEmacs
4204 process, etc.
4205
4206    `systty.h' buffers against the infinitude of different ways of
4207 controlling TTY's.
4208
4209    `syswait.h' provides a uniform way of retrieving the exit status
4210 from a `wait()'ed-on process (some systems use a union, others use an
4211 int).
4212
4213      hpplay.c
4214      libsst.c
4215      libsst.h
4216      libst.h
4217      linuxplay.c
4218      nas.c
4219      sgiplay.c
4220      sound.c
4221      sunplay.c
4222
4223    These files implement the ability to play various sounds on some
4224 types of computers.  You have to configure your XEmacs with sound
4225 support in order to get this capability.
4226
4227    `sound.c' provides the generic interface.  It implements various
4228 Lisp primitives and variables that let you specify which sounds should
4229 be played in certain conditions. (The conditions are identified by
4230 symbols, which are passed to `ding' to make a sound.  Various standard
4231 functions call this function at certain times; if sound support does
4232 not exist, a simple beep results.
4233
4234    `sgiplay.c', `sunplay.c', `hpplay.c', and `linuxplay.c' interface to
4235 the machine's speaker for various different kind of machines.  This is
4236 called "native" sound.
4237
4238    `nas.c' interfaces to a computer somewhere else on the network using
4239 the NAS (Network Audio Server) protocol, playing sounds on that
4240 machine.  This allows you to run XEmacs on a remote machine, with its
4241 display set to your local machine, and have the sounds be made on your
4242 local machine, provided that you have a NAS server running on your local
4243 machine.
4244
4245    `libsst.c', `libsst.h', and `libst.h' provide some additional
4246 functions for playing sound on a Sun SPARC but are not currently in use.
4247
4248      tooltalk.c
4249      tooltalk.h
4250
4251    These two modules implement an interface to the ToolTalk protocol,
4252 which is an interprocess communication protocol implemented on some
4253 versions of Unix.  ToolTalk is a high-level protocol that allows
4254 processes to register themselves as providers of particular services;
4255 other processes can then request a service without knowing or caring
4256 exactly who is providing the service.  It is similar in spirit to the
4257 DDE protocol provided under Microsoft Windows.  ToolTalk is a part of
4258 the new CDE (Common Desktop Environment) specification and is used to
4259 connect the parts of the SPARCWorks development environment.
4260
4261      getloadavg.c
4262
4263    This module provides the ability to retrieve the system's current
4264 load average. (The way to do this is highly system-specific,
4265 unfortunately, and requires a lot of special-case code.)
4266
4267      sunpro.c
4268
4269    This module provides a small amount of code used internally at Sun to
4270 keep statistics on the usage of XEmacs.
4271
4272      broken-sun.h
4273      strcmp.c
4274      strcpy.c
4275      sunOS-fix.c
4276
4277    These files provide replacement functions and prototypes to fix
4278 numerous bugs in early releases of SunOS 4.1.
4279
4280      hftctl.c
4281
4282    This module provides some terminal-control code necessary on
4283 versions of AIX prior to 4.1.
4284
4285 \1f
4286 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
4287
4288 Modules for Interfacing with X Windows
4289 ======================================
4290
4291      Emacs.ad.h
4292
4293    A file generated from `Emacs.ad', which contains XEmacs-supplied
4294 fallback resources (so that XEmacs has pretty defaults).
4295
4296      EmacsFrame.c
4297      EmacsFrame.h
4298      EmacsFrameP.h
4299
4300    These modules implement an Xt widget class that encapsulates a frame.
4301 This is for ease in integrating with Xt.  The EmacsFrame widget covers
4302 the entire X window except for the menubar; the scrollbars are
4303 positioned on top of the EmacsFrame widget.
4304
4305    *Warning:* Abandon hope, all ye who enter here.  This code took an
4306 ungodly amount of time to get right, and is likely to fall apart
4307 mercilessly at the slightest change.  Such is life under Xt.
4308
4309      EmacsManager.c
4310      EmacsManager.h
4311      EmacsManagerP.h
4312
4313    These modules implement a simple Xt manager (i.e. composite) widget
4314 class that simply lets its children set whatever geometry they want.
4315 It's amazing that Xt doesn't provide this standardly, but on second
4316 thought, it makes sense, considering how amazingly broken Xt is.
4317
4318      EmacsShell-sub.c
4319      EmacsShell.c
4320      EmacsShell.h
4321      EmacsShellP.h
4322
4323    These modules implement two Xt widget classes that are subclasses of
4324 the TopLevelShell and TransientShell classes.  This is necessary to deal
4325 with more brokenness that Xt has sadistically thrust onto the backs of
4326 developers.
4327
4328      xgccache.c
4329      xgccache.h
4330
4331    These modules provide functions for maintenance and caching of GC's
4332 (graphics contexts) under the X Window System.  This code is junky and
4333 needs to be rewritten.
4334
4335      select-msw.c
4336      select-x.c
4337      select.c
4338      select.h
4339
4340    This module provides an interface to the X Window System's concept of
4341 "selections", the standard way for X applications to communicate with
4342 each other.
4343
4344      xintrinsic.h
4345      xintrinsicp.h
4346      xmmanagerp.h
4347      xmprimitivep.h
4348
4349    These header files are similar in spirit to the `sys*.h' files and
4350 buffer against different implementations of Xt and Motif.
4351
4352    * `xintrinsic.h' should be included in place of `<Intrinsic.h>'.
4353
4354    * `xintrinsicp.h' should be included in place of `<IntrinsicP.h>'.
4355
4356    * `xmmanagerp.h' should be included in place of `<XmManagerP.h>'.
4357
4358    * `xmprimitivep.h' should be included in place of `<XmPrimitiveP.h>'.
4359
4360      xmu.c
4361      xmu.h
4362
4363    These files provide an emulation of the Xmu library for those systems
4364 (i.e. HPUX) that don't provide it as a standard part of X.
4365
4366      ExternalClient-Xlib.c
4367      ExternalClient.c
4368      ExternalClient.h
4369      ExternalClientP.h
4370      ExternalShell.c
4371      ExternalShell.h
4372      ExternalShellP.h
4373      extw-Xlib.c
4374      extw-Xlib.h
4375      extw-Xt.c
4376      extw-Xt.h
4377
4378    These files provide the "external widget" interface, which allows an
4379 XEmacs frame to appear as a widget in another application.  To do this,
4380 you have to configure with `--external-widget'.
4381
4382    `ExternalShell*' provides the server (XEmacs) side of the connection.
4383
4384    `ExternalClient*' provides the client (other application) side of
4385 the connection.  These files are not compiled into XEmacs but are
4386 compiled into libraries that are then linked into your application.
4387
4388    `extw-*' is common code that is used for both the client and server.
4389
4390    Don't touch this code; something is liable to break if you do.
4391
4392 \1f
4393 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
4394
4395 Modules for Internationalization
4396 ================================
4397
4398      mule-canna.c
4399      mule-ccl.c
4400      mule-charset.c
4401      mule-charset.h
4402      file-coding.c
4403      file-coding.h
4404      mule-mcpath.c
4405      mule-mcpath.h
4406      mule-wnnfns.c
4407      mule.c
4408
4409    These files implement the MULE (Asian-language) support.  Note that
4410 MULE actually provides a general interface for all sorts of languages,
4411 not just Asian languages (although they are generally the most
4412 complicated to support).  This code is still in beta.
4413
4414    `mule-charset.*' and `file-coding.*' provide the heart of the XEmacs
4415 MULE support.  `mule-charset.*' implements the "charset" Lisp object
4416 type, which encapsulates a character set (an ordered one- or
4417 two-dimensional set of characters, such as US ASCII or JISX0208 Japanese
4418 Kanji).
4419
4420    `file-coding.*' implements the "coding-system" Lisp object type,
4421 which encapsulates a method of converting between different encodings.
4422 An encoding is a representation of a stream of characters, possibly
4423 from multiple character sets, using a stream of bytes or words, and
4424 defines (e.g.) which escape sequences are used to specify particular
4425 character sets, how the indices for a character are converted into bytes
4426 (sometimes this involves setting the high bit; sometimes complicated
4427 rearranging of the values takes place, as in the Shift-JIS encoding),
4428 etc.
4429
4430    `mule-ccl.c' provides the CCL (Code Conversion Language)
4431 interpreter.  CCL is similar in spirit to Lisp byte code and is used to
4432 implement converters for custom encodings.
4433
4434    `mule-canna.c' and `mule-wnnfns.c' implement interfaces to external
4435 programs used to implement the Canna and WNN input methods,
4436 respectively.  This is currently in beta.
4437
4438    `mule-mcpath.c' provides some functions to allow for pathnames
4439 containing extended characters.  This code is fragmentary, obsolete, and
4440 completely non-working.  Instead, `pathname-coding-system' is used to
4441 specify conversions of names of files and directories.  The standard C
4442 I/O functions like `open()' are wrapped so that conversion occurs
4443 automatically.
4444
4445    `mule.c' provides a few miscellaneous things that should probably be
4446 elsewhere.
4447
4448      intl.c
4449
4450    This provides some miscellaneous internationalization code for
4451 implementing message translation and interfacing to the Ximp input
4452 method.  None of this code is currently working.
4453
4454      iso-wide.h
4455
4456    This contains leftover code from an earlier implementation of
4457 Asian-language support, and is not currently used.
4458
4459 \1f
4460 File: internals.info,  Node: Modules for Regression Testing,  Prev: Modules for Internationalization,  Up: A Summary of the Various XEmacs Modules
4461
4462 Modules for Regression Testing
4463 ==============================
4464
4465      test-harness.el
4466      base64-tests.el
4467      byte-compiler-tests.el
4468      case-tests.el
4469      ccl-tests.el
4470      c-tests.el
4471      database-tests.el
4472      extent-tests.el
4473      hash-table-tests.el
4474      lisp-tests.el
4475      md5-tests.el
4476      mule-tests.el
4477      regexp-tests.el
4478      symbol-tests.el
4479      syntax-tests.el
4480
4481    `test-harness.el' defines the macros `Assert', `Check-Error',
4482 `Check-Error-Message', and `Check-Message'.  The other files are test
4483 files, testing various XEmacs modules.
4484
4485 \1f
4486 File: internals.info,  Node: Allocation of Objects in XEmacs Lisp,  Next: Dumping,  Prev: A Summary of the Various XEmacs Modules,  Up: Top
4487
4488 Allocation of Objects in XEmacs Lisp
4489 ************************************
4490
4491 * Menu:
4492
4493 * Introduction to Allocation::
4494 * Garbage Collection::
4495 * GCPROing::
4496 * Garbage Collection - Step by Step::
4497 * Integers and Characters::
4498 * Allocation from Frob Blocks::
4499 * lrecords::
4500 * Low-level allocation::
4501 * Cons::
4502 * Vector::
4503 * Bit Vector::
4504 * Symbol::
4505 * Marker::
4506 * String::
4507 * Compiled Function::
4508
4509 \1f
4510 File: internals.info,  Node: Introduction to Allocation,  Next: Garbage Collection,  Up: Allocation of Objects in XEmacs Lisp
4511
4512 Introduction to Allocation
4513 ==========================
4514
4515 Emacs Lisp, like all Lisps, has garbage collection.  This means that
4516 the programmer never has to explicitly free (destroy) an object; it
4517 happens automatically when the object becomes inaccessible.  Most
4518 experts agree that garbage collection is a necessity in a modern,
4519 high-level language.  Its omission from C stems from the fact that C was
4520 originally designed to be a nice abstract layer on top of assembly
4521 language, for writing kernels and basic system utilities rather than
4522 large applications.
4523
4524    Lisp objects can be created by any of a number of Lisp primitives.
4525 Most object types have one or a small number of basic primitives for
4526 creating objects.  For conses, the basic primitive is `cons'; for
4527 vectors, the primitives are `make-vector' and `vector'; for symbols,
4528 the primitives are `make-symbol' and `intern'; etc.  Some Lisp objects,
4529 especially those that are primarily used internally, have no
4530 corresponding Lisp primitives.  Every Lisp object, though, has at least
4531 one C primitive for creating it.
4532
4533    Recall from section (VII) that a Lisp object, as stored in a 32-bit
4534 or 64-bit word, has a few tag bits, and a "value" that occupies the
4535 remainder of the bits.  We can separate the different Lisp object types
4536 into three broad categories:
4537
4538    * (a) Those for whom the value directly represents the contents of
4539      the Lisp object.  Only two types are in this category: integers and
4540      characters.  No special allocation or garbage collection is
4541      necessary for such objects.  Lisp objects of these types do not
4542      need to be `GCPRO'ed.
4543
4544    In the remaining two categories, the type is stored in the object
4545 itself.  The tag for all such objects is the generic "lrecord"
4546 (Lisp_Type_Record) tag.  The first bytes of the object's structure are
4547 an integer (actually a char) characterising the object's type and some
4548 flags, in particular the mark bit used for garbage collection.  A
4549 structure describing the type is accessible thru the
4550 lrecord_implementation_table indexed with said integer.  This structure
4551 includes the method pointers and a pointer to a string naming the type.
4552
4553    * (b) Those lrecords that are allocated in frob blocks (see above).
4554      This includes the objects that are most common and relatively
4555      small, and includes conses, strings, subrs, floats, compiled
4556      functions, symbols, extents, events, and markers.  With the
4557      cleanup of frob blocks done in 19.12, it's not terribly hard to
4558      add more objects to this category, but it's a bit trickier than
4559      adding an object type to type (c) (esp. if the object needs a
4560      finalization method), and is not likely to save much space unless
4561      the object is small and there are many of them. (In fact, if there
4562      are very few of them, it might actually waste space.)
4563
4564    * (c) Those lrecords that are individually `malloc()'ed.  These are
4565      called "lcrecords".  All other types are in this category.  Adding
4566      a new type to this category is comparatively easy, and all types
4567      added since 19.8 (when the current allocation scheme was devised,
4568      by Richard Mlynarik), with the exception of the character type,
4569      have been in this category.
4570
4571    Note that bit vectors are a bit of a special case.  They are simple
4572 lrecords as in category (b), but are individually `malloc()'ed like
4573 vectors.  You can basically view them as exactly like vectors except
4574 that their type is stored in lrecord fashion rather than in
4575 directly-tagged fashion.
4576
4577 \1f
4578 File: internals.info,  Node: Garbage Collection,  Next: GCPROing,  Prev: Introduction to Allocation,  Up: Allocation of Objects in XEmacs Lisp
4579
4580 Garbage Collection
4581 ==================
4582
4583 Garbage collection is simple in theory but tricky to implement.  Emacs
4584 Lisp uses the oldest garbage collection method, called "mark and
4585 sweep".  Garbage collection begins by starting with all accessible
4586 locations (i.e. all variables and other slots where Lisp objects might
4587 occur) and recursively traversing all objects accessible from those
4588 slots, marking each one that is found.  We then go through all of
4589 memory and free each object that is not marked, and unmarking each
4590 object that is marked.  Note that "all of memory" means all currently
4591 allocated objects.  Traversing all these objects means traversing all
4592 frob blocks, all vectors (which are chained in one big list), and all
4593 lcrecords (which are likewise chained).
4594
4595    Garbage collection can be invoked explicitly by calling
4596 `garbage-collect' but is also called automatically by `eval', once a
4597 certain amount of memory has been allocated since the last garbage
4598 collection (according to `gc-cons-threshold').
4599
4600 \1f
4601 File: internals.info,  Node: GCPROing,  Next: Garbage Collection - Step by Step,  Prev: Garbage Collection,  Up: Allocation of Objects in XEmacs Lisp
4602
4603 `GCPRO'ing
4604 ==========
4605
4606 `GCPRO'ing is one of the ugliest and trickiest parts of Emacs
4607 internals.  The basic idea is that whenever garbage collection occurs,
4608 all in-use objects must be reachable somehow or other from one of the
4609 roots of accessibility.  The roots of accessibility are:
4610
4611   1. All objects that have been `staticpro()'d or
4612      `staticpro_nodump()'ed.  This is used for any global C variables
4613      that hold Lisp objects.  A call to `staticpro()' happens implicitly
4614      as a result of any symbols declared with `defsymbol()' and any
4615      variables declared with `DEFVAR_FOO()'.  You need to explicitly
4616      call `staticpro()' (in the `vars_of_foo()' method of a module) for
4617      other global C variables holding Lisp objects. (This typically
4618      includes internal lists and such things.).  Use
4619      `staticpro_nodump()' only in the rare cases when you do not want
4620      the pointed variable to be saved at dump time but rather recompute
4621      it at startup.
4622
4623      Note that `obarray' is one of the `staticpro()'d things.
4624      Therefore, all functions and variables get marked through this.
4625
4626   2. Any shadowed bindings that are sitting on the `specpdl' stack.
4627
4628   3. Any objects sitting in currently active (Lisp) stack frames,
4629      catches, and condition cases.
4630
4631   4. A couple of special-case places where active objects are located.
4632
4633   5. Anything currently marked with `GCPRO'.
4634
4635    Marking with `GCPRO' is necessary because some C functions (quite a
4636 lot, in fact), allocate objects during their operation.  Quite
4637 frequently, there will be no other pointer to the object while the
4638 function is running, and if a garbage collection occurs and the object
4639 needs to be referenced again, bad things will happen.  The solution is
4640 to mark those objects with `GCPRO'.  Unfortunately this is easy to
4641 forget, and there is basically no way around this problem.  Here are
4642 some rules, though:
4643
4644   1. For every `GCPRON', there have to be declarations of `struct gcpro
4645      gcpro1, gcpro2', etc.
4646
4647   2. You _must_ `UNGCPRO' anything that's `GCPRO'ed, and you _must not_
4648      `UNGCPRO' if you haven't `GCPRO'ed.  Getting either of these wrong
4649      will lead to crashes, often in completely random places unrelated
4650      to where the problem lies.
4651
4652   3. The way this actually works is that all currently active `GCPRO's
4653      are chained through the `struct gcpro' local variables, with the
4654      variable `gcprolist' pointing to the head of the list and the nth
4655      local `gcpro' variable pointing to the first `gcpro' variable in
4656      the next enclosing stack frame.  Each `GCPRO'ed thing is an
4657      lvalue, and the `struct gcpro' local variable contains a pointer to
4658      this lvalue.  This is why things will mess up badly if you don't
4659      pair up the `GCPRO's and `UNGCPRO's--you will end up with
4660      `gcprolist's containing pointers to `struct gcpro's or local
4661      `Lisp_Object' variables in no-longer-active stack frames.
4662
4663   4. It is actually possible for a single `struct gcpro' to protect a
4664      contiguous array of any number of values, rather than just a
4665      single lvalue.  To effect this, call `GCPRON' as usual on the
4666      first object in the array and then set `gcproN.nvars'.
4667
4668   5. *Strings are relocated.*  What this means in practice is that the
4669      pointer obtained using `XSTRING_DATA()' is liable to change at any
4670      time, and you should never keep it around past any function call,
4671      or pass it as an argument to any function that might cause a
4672      garbage collection.  This is why a number of functions accept
4673      either a "non-relocatable" `char *' pointer or a relocatable Lisp
4674      string, and only access the Lisp string's data at the very last
4675      minute.  In some cases, you may end up having to `alloca()' some
4676      space and copy the string's data into it.
4677
4678   6. By convention, if you have to nest `GCPRO''s, use `NGCPRON' (along
4679      with `struct gcpro ngcpro1, ngcpro2', etc.), `NNGCPRON', etc.
4680      This avoids compiler warnings about shadowed locals.
4681
4682   7. It is _always_ better to err on the side of extra `GCPRO's rather
4683      than too few.  The extra cycles spent on this are almost never
4684      going to make a whit of difference in the speed of anything.
4685
4686   8. The general rule to follow is that caller, not callee, `GCPRO's.
4687      That is, you should not have to explicitly `GCPRO' any Lisp objects
4688      that are passed in as parameters.
4689
4690      One exception from this rule is if you ever plan to change the
4691      parameter value, and store a new object in it.  In that case, you
4692      _must_ `GCPRO' the parameter, because otherwise the new object
4693      will not be protected.
4694
4695      So, if you create any Lisp objects (remember, this happens in all
4696      sorts of circumstances, e.g. with `Fcons()', etc.), you are
4697      responsible for `GCPRO'ing them, unless you are _absolutely sure_
4698      that there's no possibility that a garbage-collection can occur
4699      while you need to use the object.  Even then, consider `GCPRO'ing.
4700
4701   9. A garbage collection can occur whenever anything calls `Feval', or
4702      whenever a QUIT can occur where execution can continue past this.
4703      (Remember, this is almost anywhere.)
4704
4705  10. If you have the _least smidgeon of doubt_ about whether you need
4706      to `GCPRO', you should `GCPRO'.
4707
4708  11. Beware of `GCPRO'ing something that is uninitialized.  If you have
4709      any shade of doubt about this, initialize all your variables to
4710      `Qnil'.
4711
4712  12. Be careful of traps, like calling `Fcons()' in the argument to
4713      another function.  By the "caller protects" law, you should be
4714      `GCPRO'ing the newly-created cons, but you aren't.  A certain
4715      number of functions that are commonly called on freshly created
4716      stuff (e.g. `nconc2()', `Fsignal()'), break the "caller protects"
4717      law and go ahead and `GCPRO' their arguments so as to simplify
4718      things, but make sure and check if it's OK whenever doing
4719      something like this.
4720
4721  13. Once again, remember to `GCPRO'!  Bugs resulting from insufficient
4722      `GCPRO'ing are intermittent and extremely difficult to track down,
4723      often showing up in crashes inside of `garbage-collect' or in
4724      weirdly corrupted objects or even in incorrect values in a totally
4725      different section of code.
4726
4727    If you don't understand whether to `GCPRO' in a particular instance,
4728 ask on the mailing lists.  A general hint is that `prog1' is the
4729 canonical example.
4730
4731    Given the extremely error-prone nature of the `GCPRO' scheme, and
4732 the difficulties in tracking down, it should be considered a deficiency
4733 in the XEmacs code.  A solution to this problem would involve
4734 implementing so-called "conservative" garbage collection for the C
4735 stack.  That involves looking through all of stack memory and treating
4736 anything that looks like a reference to an object as a reference.  This
4737 will result in a few objects not getting collected when they should, but
4738 it obviates the need for `GCPRO'ing, and allows garbage collection to
4739 happen at any point at all, such as during object allocation.
4740
4741 \1f
4742 File: internals.info,  Node: Garbage Collection - Step by Step,  Next: Integers and Characters,  Prev: GCPROing,  Up: Allocation of Objects in XEmacs Lisp
4743
4744 Garbage Collection - Step by Step
4745 =================================
4746
4747 * Menu:
4748
4749 * Invocation::
4750 * garbage_collect_1::
4751 * mark_object::
4752 * gc_sweep::
4753 * sweep_lcrecords_1::
4754 * compact_string_chars::
4755 * sweep_strings::
4756 * sweep_bit_vectors_1::
4757
4758 \1f
4759 File: internals.info,  Node: Invocation,  Next: garbage_collect_1,  Up: Garbage Collection - Step by Step
4760
4761 Invocation
4762 ----------
4763
4764 The first thing that anyone should know about garbage collection is:
4765 when and how the garbage collector is invoked. One might think that this
4766 could happen every time new memory is allocated, e.g. new objects are
4767 created, but this is _not_ the case. Instead, we have the following
4768 situation:
4769
4770    The entry point of any process of garbage collection is an invocation
4771 of the function `garbage_collect_1' in file `alloc.c'. The invocation
4772 can occur _explicitly_ by calling the function `Fgarbage_collect' (in
4773 addition this function provides information about the freed memory), or
4774 can occur _implicitly_ in four different situations:
4775   1. In function `main_1' in file `emacs.c'. This function is called at
4776      each startup of xemacs. The garbage collection is invoked after all
4777      initial creations are completed, but only if a special internal
4778      error checking-constant `ERROR_CHECK_GC' is defined.
4779
4780   2. In function `disksave_object_finalization' in file `alloc.c'. The
4781      only purpose of this function is to clear the objects from memory
4782      which need not be stored with xemacs when we dump out an
4783      executable. This is only done by `Fdump_emacs' or by
4784      `Fdump_emacs_data' respectively (both in `emacs.c'). The actual
4785      clearing is accomplished by making these objects unreachable and
4786      starting a garbage collection. The function is only used while
4787      building xemacs.
4788
4789   3. In function `Feval / eval' in file `eval.c'. Each time the well
4790      known and often used function eval is called to evaluate a form,
4791      one of the first things that could happen, is a potential call of
4792      `garbage_collect_1'. There exist three global variables,
4793      `consing_since_gc' (counts the created cons-cells since the last
4794      garbage collection), `gc_cons_threshold' (a specified threshold
4795      after which a garbage collection occurs) and `always_gc'. If
4796      `always_gc' is set or if the threshold is exceeded, the garbage
4797      collection will start.
4798
4799   4. In function `Ffuncall / funcall' in file `eval.c'. This function
4800      evaluates calls of elisp functions and works according to `Feval'.
4801
4802    The upshot is that garbage collection can basically occur everywhere
4803 `Feval', respectively `Ffuncall', is used - either directly or through
4804 another function. Since calls to these two functions are hidden in
4805 various other functions, many calls to `garbage_collect_1' are not
4806 obviously foreseeable, and therefore unexpected. Instances where they
4807 are used that are worth remembering are various elisp commands, as for
4808 example `or', `and', `if', `cond', `while', `setq', etc., miscellaneous
4809 `gui_item_...' functions, everything related to `eval' (`Feval_buffer',
4810 `call0', ...) and inside `Fsignal'. The latter is used to handle
4811 signals, as for example the ones raised by every `QUIT'-macro triggered
4812 after pressing Ctrl-g.
4813
4814 \1f
4815 File: internals.info,  Node: garbage_collect_1,  Next: mark_object,  Prev: Invocation,  Up: Garbage Collection - Step by Step
4816
4817 `garbage_collect_1'
4818 -------------------
4819
4820 We can now describe exactly what happens after the invocation takes
4821 place.
4822   1. There are several cases in which the garbage collector is left
4823      immediately: when we are already garbage collecting
4824      (`gc_in_progress'), when the garbage collection is somehow
4825      forbidden (`gc_currently_forbidden'), when we are currently
4826      displaying something (`in_display') or when we are preparing for
4827      the armageddon of the whole system (`preparing_for_armageddon').
4828
4829   2. Next the correct frame in which to put all the output occurring
4830      during garbage collecting is determined. In order to be able to
4831      restore the old display's state after displaying the message, some
4832      data about the current cursor position has to be saved. The
4833      variables `pre_gc_cursor' and `cursor_changed' take care of that.
4834
4835   3. The state of `gc_currently_forbidden' must be restored after the
4836      garbage collection, no matter what happens during the process. We
4837      accomplish this by `record_unwind_protect'ing the suitable function
4838      `restore_gc_inhibit' together with the current value of
4839      `gc_currently_forbidden'.
4840
4841   4. If we are concurrently running an interactive xemacs session, the
4842      next step is simply to show the garbage collector's cursor/message.
4843
4844   5. The following steps are the intrinsic steps of the garbage
4845      collector, therefore `gc_in_progress' is set.
4846
4847   6. For debugging purposes, it is possible to copy the current C stack
4848      frame. However, this seems to be a currently unused feature.
4849
4850   7. Before actually starting to go over all live objects, references to
4851      objects that are no longer used are pruned. We only have to do
4852      this for events (`clear_event_resource') and for specifiers
4853      (`cleanup_specifiers').
4854
4855   8. Now the mark phase begins and marks all accessible elements. In
4856      order to start from all slots that serve as roots of
4857      accessibility, the function `mark_object' is called for each root
4858      individually to go out from there to mark all reachable objects.
4859      All roots that are traversed are shown in their processed order:
4860         * all constant symbols and static variables that are registered
4861           via `staticpro' in the dynarr `staticpros'.  *Note Adding
4862           Global Lisp Variables::.
4863
4864         * all Lisp objects that are created in C functions and that
4865           must be protected from freeing them. They are registered in
4866           the global list `gcprolist'.  *Note GCPROing::.
4867
4868         * all local variables (i.e. their name fields `symbol' and old
4869           values `old_values') that are bound during the evaluation by
4870           the Lisp engine. They are stored in `specbinding' structs
4871           pushed on a stack called `specpdl'.  *Note Dynamic Binding;
4872           The specbinding Stack; Unwind-Protects::.
4873
4874         * all catch blocks that the Lisp engine encounters during the
4875           evaluation cause the creation of structs `catchtag' inserted
4876           in the list `catchlist'. Their tag (`tag') and value (`val'
4877           fields are freshly created objects and therefore have to be
4878           marked.  *Note Catch and Throw::.
4879
4880         * every function application pushes new structs `backtrace' on
4881           the call stack of the Lisp engine (`backtrace_list'). The
4882           unique parts that have to be marked are the fields for each
4883           function (`function') and all their arguments (`args').
4884           *Note Evaluation::.
4885
4886         * all objects that are used by the redisplay engine that must
4887           not be freed are marked by a special function called
4888           `mark_redisplay' (in `redisplay.c').
4889
4890         * all objects created for profiling purposes are allocated by C
4891           functions instead of using the lisp allocation mechanisms. In
4892           order to receive the right ones during the sweep phase, they
4893           also have to be marked manually. That is done by the function
4894           `mark_profiling_info'
4895
4896   9. Hash tables in XEmacs belong to a kind of special objects that
4897      make use of a concept often called 'weak pointers'.  To make a
4898      long story short, these kind of pointers are not followed during
4899      the estimation of the live objects during garbage collection.  Any
4900      object referenced only by weak pointers is collected anyway, and
4901      the reference to it is cleared. In hash tables there are different
4902      usage patterns of them, manifesting in different types of hash
4903      tables, namely 'non-weak', 'weak', 'key-weak' and 'value-weak'
4904      (internally also 'key-car-weak' and 'value-car-weak') hash tables,
4905      each clearing entries depending on different conditions. More
4906      information can be found in the documentation to the function
4907      `make-hash-table'.
4908
4909      Because there are complicated dependency rules about when and what
4910      to mark while processing weak hash tables, the standard `marker'
4911      method is only active if it is marking non-weak hash tables. As
4912      soon as a weak component is in the table, the hash table entries
4913      are ignored while marking. Instead their marking is done each
4914      separately by the function `finish_marking_weak_hash_tables'. This
4915      function iterates over each hash table entry `hentries' for each
4916      weak hash table in `Vall_weak_hash_tables'. Depending on the type
4917      of a table, the appropriate action is performed.  If a table is
4918      acting as `HASH_TABLE_KEY_WEAK', and a key already marked,
4919      everything reachable from the `value' component is marked. If it is
4920      acting as a `HASH_TABLE_VALUE_WEAK' and the value component is
4921      already marked, the marking starts beginning only from the `key'
4922      component.  If it is a `HASH_TABLE_KEY_CAR_WEAK' and the car of
4923      the key entry is already marked, we mark both the `key' and
4924      `value' components.  Finally, if the table is of the type
4925      `HASH_TABLE_VALUE_CAR_WEAK' and the car of the value components is
4926      already marked, again both the `key' and the `value' components
4927      get marked.
4928
4929      Again, there are lists with comparable properties called weak
4930      lists. There exist different peculiarities of their types called
4931      `simple', `assoc', `key-assoc' and `value-assoc'. You can find
4932      further details about them in the description to the function
4933      `make-weak-list'. The scheme of their marking is similar: all weak
4934      lists are listed in `Qall_weak_lists', therefore we iterate over
4935      them. The marking is advanced until we hit an already marked pair.
4936      Then we know that during a former run all the rest has been marked
4937      completely. Again, depending on the special type of the weak list,
4938      our jobs differ. If it is a `WEAK_LIST_SIMPLE' and the elem is
4939      marked, we mark the `cons' part. If it is a `WEAK_LIST_ASSOC' and
4940      not a pair or a pair with both marked car and cdr, we mark the
4941      `cons' and the `elem'. If it is a `WEAK_LIST_KEY_ASSOC' and not a
4942      pair or a pair with a marked car of the elem, we mark the `cons'
4943      and the `elem'. Finally, if it is a `WEAK_LIST_VALUE_ASSOC' and
4944      not a pair or a pair with a marked cdr of the elem, we mark both
4945      the `cons' and the `elem'.
4946
4947      Since, by marking objects in reach from weak hash tables and weak
4948      lists, other objects could get marked, this perhaps implies
4949      further marking of other weak objects, both finishing functions
4950      are redone as long as yet unmarked objects get freshly marked.
4951
4952  10. After completing the special marking for the weak hash tables and
4953      for the weak lists, all entries that point to objects that are
4954      going to be swept in the further process are useless, and
4955      therefore have to be removed from the table or the list.
4956
4957      The function `prune_weak_hash_tables' does the job for weak hash
4958      tables. Totally unmarked hash tables are removed from the list
4959      `Vall_weak_hash_tables'. The other ones are treated more carefully
4960      by scanning over all entries and removing one as soon as one of
4961      the components `key' and `value' is unmarked.
4962
4963      The same idea applies to the weak lists. It is accomplished by
4964      `prune_weak_lists': An unmarked list is pruned from
4965      `Vall_weak_lists' immediately. A marked list is treated more
4966      carefully by going over it and removing just the unmarked pairs.
4967
4968  11. The function `prune_specifiers' checks all listed specifiers held
4969      in `Vall_specifiers' and removes the ones from the lists that are
4970      unmarked.
4971
4972  12. All syntax tables are stored in a list called
4973      `Vall_syntax_tables'. The function `prune_syntax_tables' walks
4974      through it and unlinks the tables that are unmarked.
4975
4976  13. Next, we will attack the complete sweeping - the function
4977      `gc_sweep' which holds the predominance.
4978
4979  14. First, all the variables with respect to garbage collection are
4980      reset. `consing_since_gc' - the counter of the created cells since
4981      the last garbage collection - is set back to 0, and
4982      `gc_in_progress' is not `true' anymore.
4983
4984  15. In case the session is interactive, the displayed cursor and
4985      message are removed again.
4986
4987  16. The state of `gc_inhibit' is restored to the former value by
4988      unwinding the stack.
4989
4990  17. A small memory reserve is always held back that can be reached by
4991      `breathing_space'. If nothing more is left, we create a new reserve
4992      and exit.
4993
4994 \1f
4995 File: internals.info,  Node: mark_object,  Next: gc_sweep,  Prev: garbage_collect_1,  Up: Garbage Collection - Step by Step
4996
4997 `mark_object'
4998 -------------
4999
5000 The first thing that is checked while marking an object is whether the
5001 object is a real Lisp object `Lisp_Type_Record' or just an integer or a
5002 character. Integers and characters are the only two types that are
5003 stored directly - without another level of indirection, and therefore
5004 they don't have to be marked and collected.  *Note How Lisp Objects Are
5005 Represented in C::.
5006
5007    The second case is the one we have to handle. It is the one when we
5008 are dealing with a pointer to a Lisp object. But, there exist also three
5009 possibilities, that prevent us from doing anything while marking: The
5010 object is read only which prevents it from being garbage collected,
5011 i.e. marked (`C_READONLY_RECORD_HEADER'). The object in question is
5012 already marked, and need not be marked for the second time (checked by
5013 `MARKED_RECORD_HEADER_P'). If it is a special, unmarkable object
5014 (`UNMARKABLE_RECORD_HEADER_P', apparently, these are objects that sit
5015 in some const space, and can therefore not be marked, see
5016 `this_one_is_unmarkable' in `alloc.c').
5017
5018    Now, the actual marking is feasible. We do so by once using the macro
5019 `MARK_RECORD_HEADER' to mark the object itself (actually the special
5020 flag in the lrecord header), and calling its special marker "method"
5021 `marker' if available. The marker method marks every other object that
5022 is in reach from our current object. Note, that these marker methods
5023 should not call `mark_object' recursively, but instead should return
5024 the next object from where further marking has to be performed.
5025
5026    In case another object was returned, as mentioned before, we
5027 reiterate the whole `mark_object' process beginning with this next
5028 object.
5029
5030 \1f
5031 File: internals.info,  Node: gc_sweep,  Next: sweep_lcrecords_1,  Prev: mark_object,  Up: Garbage Collection - Step by Step
5032
5033 `gc_sweep'
5034 ----------
5035
5036 The job of this function is to free all unmarked records from memory. As
5037 we know, there are different types of objects implemented and managed,
5038 and consequently different ways to free them from memory.  *Note
5039 Introduction to Allocation::.
5040
5041    We start with all objects stored through `lcrecords'. All bulkier
5042 objects are allocated and handled using that scheme of `lcrecords'.
5043 Each object is `malloc'ed separately instead of placing it in one of
5044 the contiguous frob blocks. All types that are currently stored using
5045 `lcrecords''s  `alloc_lcrecord' and `make_lcrecord_list' are the types:
5046 vectors, buffers, char-table, char-table-entry, console, weak-list,
5047 database, device, ldap, hash-table, command-builder, extent-auxiliary,
5048 extent-info, face, coding-system, frame, image-instance, glyph,
5049 popup-data, gui-item, keymap, charset, color_instance, font_instance,
5050 opaque, opaque-list, process, range-table, specifier,
5051 symbol-value-buffer-local, symbol-value-lisp-magic,
5052 symbol-value-varalias, toolbar-button, tooltalk-message,
5053 tooltalk-pattern, window, and window-configuration. We take care of
5054 them in the fist place in order to be able to handle and to finalize
5055 items stored in them more easily. The function `sweep_lcrecords_1' as
5056 described below is doing the whole job for us.  For a description about
5057 the internals: *Note lrecords::.
5058
5059    Our next candidates are the other objects that behave quite
5060 differently than everything else: the strings. They consists of two
5061 parts, a fixed-size portion (`struct Lisp_String') holding the string's
5062 length, its property list and a pointer to the second part, and the
5063 actual string data, which is stored in string-chars blocks comparable to
5064 frob blocks. In this block, the data is not only freed, but also a
5065 compression of holes is made, i.e. all strings are relocated together.
5066 *Note String::. This compacting phase is performed by the function
5067 `compact_string_chars', the actual sweeping by the function
5068 `sweep_strings' is described below.
5069
5070    After that, the other types are swept step by step using functions
5071 `sweep_conses', `sweep_bit_vectors_1', `sweep_compiled_functions',
5072 `sweep_floats', `sweep_symbols', `sweep_extents', `sweep_markers' and
5073 `sweep_extents'.  They are the fixed-size types cons, floats,
5074 compiled-functions, symbol, marker, extent, and event stored in
5075 so-called "frob blocks", and therefore we can basically do the same on
5076 every type objects, using the same macros, especially defined only to
5077 handle everything with respect to fixed-size blocks. The only fixed-size
5078 type that is not handled here are the fixed-size portion of strings,
5079 because we took special care of them earlier.
5080
5081    The only big exceptions are bit vectors stored differently and
5082 therefore treated differently by the function `sweep_bit_vectors_1'
5083 described later.
5084
5085    At first, we need some brief information about how these fixed-size
5086 types are managed in general, in order to understand how the sweeping
5087 is done. They have all a fixed size, and are therefore stored in big
5088 blocks of memory - allocated at once - that can hold a certain amount
5089 of objects of one type. The macro `DECLARE_FIXED_TYPE_ALLOC' creates
5090 the suitable structures for every type. More precisely, we have the
5091 block struct (holding a pointer to the previous block `prev' and the
5092 objects in `block[]'), a pointer to current block
5093 (`current_..._block)') and its last index (`current_..._block_index'),
5094 and a pointer to the free list that will be created. Also a macro
5095 `FIXED_TYPE_FROM_BLOCK' plus some related macros exists that are used
5096 to obtain a new object, either from the free list
5097 `ALLOCATE_FIXED_TYPE_1' if there is an unused object of that type
5098 stored or by allocating a completely new block using
5099 `ALLOCATE_FIXED_TYPE_FROM_BLOCK'.
5100
5101    The rest works as follows: all of them define a macro `UNMARK_...'
5102 that is used to unmark the object. They define a macro
5103 `ADDITIONAL_FREE_...' that defines additional work that has to be done
5104 when converting an object from in use to not in use (so far, only
5105 markers use it in order to unchain them). Then, they all call the macro
5106 `SWEEP_FIXED_TYPE_BLOCK' instantiated with their type name and their
5107 struct name.
5108
5109    This call in particular does the following: we go over all blocks
5110 starting with the current moving towards the oldest.  For each block,
5111 we look at every object in it. If the object already freed (checked
5112 with `FREE_STRUCT_P' using the first pointer of the object), or if it is
5113 set to read only (`C_READONLY_RECORD_HEADER_P', nothing must be done.
5114 If it is unmarked (checked with `MARKED_RECORD_HEADER_P'), it is put in
5115 the free list and set free (using the macro `FREE_FIXED_TYPE',
5116 otherwise it stays in the block, but is unmarked (by `UNMARK_...').
5117 While going through one block, we note if the whole block is empty. If
5118 so, the whole block is freed (using `xfree') and the free list state is
5119 set to the state it had before handling this block.
5120
5121 \1f
5122 File: internals.info,  Node: sweep_lcrecords_1,  Next: compact_string_chars,  Prev: gc_sweep,  Up: Garbage Collection - Step by Step
5123
5124 `sweep_lcrecords_1'
5125 -------------------
5126
5127 After nullifying the complete lcrecord statistics, we go over all
5128 lcrecords two separate times. They are all chained together in a list
5129 with a head called `all_lcrecords'.
5130
5131    The first loop calls for each object its `finalizer' method, but only
5132 in the case that it is not read only (`C_READONLY_RECORD_HEADER_P)', it
5133 is not already marked (`MARKED_RECORD_HEADER_P'), it is not already in
5134 a free list (list of freed objects, field `free') and finally it owns a
5135 finalizer method.
5136
5137    The second loop actually frees the appropriate objects again by
5138 iterating through the whole list. In case an object is read only or
5139 marked, it has to persist, otherwise it is manually freed by calling
5140 `xfree'. During this loop, the lcrecord statistics are kept up to date
5141 by calling `tick_lcrecord_stats' with the right arguments,
5142
5143 \1f
5144 File: internals.info,  Node: compact_string_chars,  Next: sweep_strings,  Prev: sweep_lcrecords_1,  Up: Garbage Collection - Step by Step
5145
5146 `compact_string_chars'
5147 ----------------------
5148
5149 The purpose of this function is to compact all the data parts of the
5150 strings that are held in so-called `string_chars_block', i.e. the
5151 strings that do not exceed a certain maximal length.
5152
5153    The procedure with which this is done is as follows. We are keeping
5154 two positions in the `string_chars_block's using two pointer/integer
5155 pairs, namely `from_sb'/`from_pos' and `to_sb'/`to_pos'. They stand for
5156 the actual positions, from where to where, to copy the actually handled
5157 string.
5158
5159    While going over all chained `string_char_block's and their held
5160 strings, staring at `first_string_chars_block', both pointers are
5161 advanced and eventually a string is copied from `from_sb' to `to_sb',
5162 depending on the status of the pointed at strings.
5163
5164    More precisely, we can distinguish between the following actions.
5165    * The string at `from_sb''s position could be marked as free, which
5166      is indicated by an invalid pointer to the pointer that should
5167      point back to the fixed size string object, and which is checked by
5168      `FREE_STRUCT_P'. In this case, the `from_sb'/`from_pos' is
5169      advanced to the next string, and nothing has to be copied.
5170
5171    * Also, if a string object itself is unmarked, nothing has to be
5172      copied. We likewise advance the `from_sb'/`from_pos' pair as
5173      described above.
5174
5175    * In all other cases, we have a marked string at hand. The string
5176      data must be moved from the from-position to the to-position. In
5177      case there is not enough space in the actual `to_sb'-block, we
5178      advance this pointer to the beginning of the next block before
5179      copying. In case the from and to positions are different, we
5180      perform the actual copying using the library function `memmove'.
5181
5182    After compacting, the pointer to the current `string_chars_block',
5183 sitting in `current_string_chars_block', is reset on the last block to
5184 which we moved a string, i.e. `to_block', and all remaining blocks (we
5185 know that they just carry garbage) are explicitly `xfree'd.
5186
5187 \1f
5188 File: internals.info,  Node: sweep_strings,  Next: sweep_bit_vectors_1,  Prev: compact_string_chars,  Up: Garbage Collection - Step by Step
5189
5190 `sweep_strings'
5191 ---------------
5192
5193 The sweeping for the fixed sized string objects is essentially exactly
5194 the same as it is for all other fixed size types. As before, the freeing
5195 into the suitable free list is done by using the macro
5196 `SWEEP_FIXED_SIZE_BLOCK' after defining the right macros
5197 `UNMARK_string' and `ADDITIONAL_FREE_string'. These two definitions are
5198 a little bit special compared to the ones used for the other fixed size
5199 types.
5200
5201    `UNMARK_string' is defined the same way except some additional code
5202 used for updating the bookkeeping information.
5203
5204    For strings, `ADDITIONAL_FREE_string' has to do something in
5205 addition: in case, the string was not allocated in a
5206 `string_chars_block' because it exceeded the maximal length, and
5207 therefore it was `malloc'ed separately, we know also `xfree' it
5208 explicitly.
5209
5210 \1f
5211 File: internals.info,  Node: sweep_bit_vectors_1,  Prev: sweep_strings,  Up: Garbage Collection - Step by Step
5212
5213 `sweep_bit_vectors_1'
5214 ---------------------
5215
5216 Bit vectors are also one of the rare types that are `malloc'ed
5217 individually. Consequently, while sweeping, all further needless bit
5218 vectors must be freed by hand. This is done, as one might imagine, the
5219 expected way: since they are all registered in a list called
5220 `all_bit_vectors', all elements of that list are traversed, all
5221 unmarked bit vectors are unlinked by calling `xfree' and all of them
5222 become unmarked.  In addition, the bookkeeping information used for
5223 garbage collector's output purposes is updated.
5224
5225 \1f
5226 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
5227
5228 Integers and Characters
5229 =======================
5230
5231 Integer and character Lisp objects are created from integers using the
5232 macros `XSETINT()' and `XSETCHAR()' or the equivalent functions
5233 `make_int()' and `make_char()'. (These are actually macros on most
5234 systems.)  These functions basically just do some moving of bits
5235 around, since the integral value of the object is stored directly in
5236 the `Lisp_Object'.
5237
5238    `XSETINT()' and the like will truncate values given to them that are
5239 too big; i.e. you won't get the value you expected but the tag bits
5240 will at least be correct.
5241
5242 \1f
5243 File: internals.info,  Node: Allocation from Frob Blocks,  Next: lrecords,  Prev: Integers and Characters,  Up: Allocation of Objects in XEmacs Lisp
5244
5245 Allocation from Frob Blocks
5246 ===========================
5247
5248 The uninitialized memory required by a `Lisp_Object' of a particular
5249 type is allocated using `ALLOCATE_FIXED_TYPE()'.  This only occurs
5250 inside of the lowest-level object-creating functions in `alloc.c':
5251 `Fcons()', `make_float()', `Fmake_byte_code()', `Fmake_symbol()',
5252 `allocate_extent()', `allocate_event()', `Fmake_marker()', and
5253 `make_uninit_string()'.  The idea is that, for each type, there are a
5254 number of frob blocks (each 2K in size); each frob block is divided up
5255 into object-sized chunks.  Each frob block will have some of these
5256 chunks that are currently assigned to objects, and perhaps some that are
5257 free. (If a frob block has nothing but free chunks, it is freed at the
5258 end of the garbage collection cycle.)  The free chunks are stored in a
5259 free list, which is chained by storing a pointer in the first four bytes
5260 of the chunk. (Except for the free chunks at the end of the last frob
5261 block, which are handled using an index which points past the end of the
5262 last-allocated chunk in the last frob block.)  `ALLOCATE_FIXED_TYPE()'
5263 first tries to retrieve a chunk from the free list; if that fails, it
5264 calls `ALLOCATE_FIXED_TYPE_FROM_BLOCK()', which looks at the end of the
5265 last frob block for space, and creates a new frob block if there is
5266 none. (There are actually two versions of these macros, one of which is
5267 more defensive but less efficient and is used for error-checking.)
5268
5269 \1f
5270 File: internals.info,  Node: lrecords,  Next: Low-level allocation,  Prev: Allocation from Frob Blocks,  Up: Allocation of Objects in XEmacs Lisp
5271
5272 lrecords
5273 ========
5274
5275 [see `lrecord.h']
5276
5277    All lrecords have at the beginning of their structure a `struct
5278 lrecord_header'.  This just contains a type number and some flags,
5279 including the mark bit.  All builtin type numbers are defined as
5280 constants in `enum lrecord_type', to allow the compiler to generate
5281 more efficient code for `TYPEP'.  The type number, thru the
5282 `lrecord_implementation_table', gives access to a `struct
5283 lrecord_implementation', which is a structure containing method pointers
5284 and such.  There is one of these for each type, and it is a global,
5285 constant, statically-declared structure that is declared in the
5286 `DEFINE_LRECORD_IMPLEMENTATION()' macro.
5287
5288    Simple lrecords (of type (b) above) just have a `struct
5289 lrecord_header' at their beginning.  lcrecords, however, actually have a
5290 `struct lcrecord_header'.  This, in turn, has a `struct lrecord_header'
5291 at its beginning, so sanity is preserved; but it also has a pointer
5292 used to chain all lcrecords together, and a special ID field used to
5293 distinguish one lcrecord from another. (This field is used only for
5294 debugging and could be removed, but the space gain is not significant.)
5295
5296    Simple lrecords are created using `ALLOCATE_FIXED_TYPE()', just like
5297 for other frob blocks.  The only change is that the implementation
5298 pointer must be initialized correctly. (The implementation structure for
5299 an lrecord, or rather the pointer to it, is named `lrecord_float',
5300 `lrecord_extent', `lrecord_buffer', etc.)
5301
5302    lcrecords are created using `alloc_lcrecord()'.  This takes a size
5303 to allocate and an implementation pointer. (The size needs to be passed
5304 because some lcrecords, such as window configurations, are of variable
5305 size.) This basically just `malloc()'s the storage, initializes the
5306 `struct lcrecord_header', and chains the lcrecord onto the head of the
5307 list of all lcrecords, which is stored in the variable `all_lcrecords'.
5308 The calls to `alloc_lcrecord()' generally occur in the lowest-level
5309 allocation function for each lrecord type.
5310
5311    Whenever you create an lrecord, you need to call either
5312 `DEFINE_LRECORD_IMPLEMENTATION()' or
5313 `DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION()'.  This needs to be specified
5314 in a `.c' file, at the top level.  What this actually does is define
5315 and initialize the implementation structure for the lrecord. (And
5316 possibly declares a function `error_check_foo()' that implements the
5317 `XFOO()' macro when error-checking is enabled.)  The arguments to the
5318 macros are the actual type name (this is used to construct the C
5319 variable name of the lrecord implementation structure and related
5320 structures using the `##' macro concatenation operator), a string that
5321 names the type on the Lisp level (this may not be the same as the C
5322 type name; typically, the C type name has underscores, while the Lisp
5323 string has dashes), various method pointers, and the name of the C
5324 structure that contains the object.  The methods are used to
5325 encapsulate type-specific information about the object, such as how to
5326 print it or mark it for garbage collection, so that it's easy to add
5327 new object types without having to add a specific case for each new
5328 type in a bunch of different places.
5329
5330    The difference between `DEFINE_LRECORD_IMPLEMENTATION()' and
5331 `DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION()' is that the former is used
5332 for fixed-size object types and the latter is for variable-size object
5333 types.  Most object types are fixed-size; some complex types, however
5334 (e.g. window configurations), are variable-size.  Variable-size object
5335 types have an extra method, which is called to determine the actual
5336 size of a particular object of that type.  (Currently this is only used
5337 for keeping allocation statistics.)
5338
5339    For the purpose of keeping allocation statistics, the allocation
5340 engine keeps a list of all the different types that exist.  Note that,
5341 since `DEFINE_LRECORD_IMPLEMENTATION()' is a macro that is specified at
5342 top-level, there is no way for it to initialize the global data
5343 structures containing type information, like
5344 `lrecord_implementations_table'.  For this reason a call to
5345 `INIT_LRECORD_IMPLEMENTATION' must be added to the same source file
5346 containing `DEFINE_LRECORD_IMPLEMENTATION', but instead of to the top
5347 level, to one of the init functions, typically `syms_of_FOO.c'.
5348 `INIT_LRECORD_IMPLEMENTATION' must be called before an object of this
5349 type is used.
5350
5351    The type number is also used to index into an array holding the
5352 number of objects of each type and the total memory allocated for
5353 objects of that type.  The statistics in this array are computed during
5354 the sweep stage.  These statistics are returned by the call to
5355 `garbage-collect'.
5356
5357    Note that for every type defined with a `DEFINE_LRECORD_*()' macro,
5358 there needs to be a `DECLARE_LRECORD_IMPLEMENTATION()' somewhere in a
5359 `.h' file, and this `.h' file needs to be included by `inline.c'.
5360
5361    Furthermore, there should generally be a set of `XFOOBAR()',
5362 `FOOBARP()', etc. macros in a `.h' (or occasionally `.c') file.  To
5363 create one of these, copy an existing model and modify as necessary.
5364
5365    *Please note:* If you define an lrecord in an external
5366 dynamically-loaded module, you must use `DECLARE_EXTERNAL_LRECORD',
5367 `DEFINE_EXTERNAL_LRECORD_IMPLEMENTATION', and
5368 `DEFINE_EXTERNAL_LRECORD_SEQUENCE_IMPLEMENTATION' instead of the
5369 non-EXTERNAL forms. These macros will dynamically add new type numbers
5370 to the global enum that records them, whereas the non-EXTERNAL forms
5371 assume that the programmer has already inserted the correct type numbers
5372 into the enum's code at compile-time.
5373
5374    The various methods in the lrecord implementation structure are:
5375
5376   1. A "mark" method.  This is called during the marking stage and
5377      passed a function pointer (usually the `mark_object()' function),
5378      which is used to mark an object.  All Lisp objects that are
5379      contained within the object need to be marked by applying this
5380      function to them.  The mark method should also return a Lisp
5381      object, which should be either `nil' or an object to mark. (This
5382      can be used in lieu of calling `mark_object()' on the object, to
5383      reduce the recursion depth, and consequently should be the most
5384      heavily nested sub-object, such as a long list.)
5385
5386      *Please note:* When the mark method is called, garbage collection
5387      is in progress, and special precautions need to be taken when
5388      accessing objects; see section (B) above.
5389
5390      If your mark method does not need to do anything, it can be `NULL'.
5391
5392   2. A "print" method.  This is called to create a printed
5393      representation of the object, whenever `princ', `prin1', or the
5394      like is called.  It is passed the object, a stream to which the
5395      output is to be directed, and an `escapeflag' which indicates
5396      whether the object's printed representation should be "escaped" so
5397      that it is readable. (This corresponds to the difference between
5398      `princ' and `prin1'.) Basically, "escaped" means that strings will
5399      have quotes around them and confusing characters in the strings
5400      such as quotes, backslashes, and newlines will be backslashed; and
5401      that special care will be taken to make symbols print in a
5402      readable fashion (e.g. symbols that look like numbers will be
5403      backslashed).  Other readable objects should perhaps pass
5404      `escapeflag' on when sub-objects are printed, so that readability
5405      is preserved when necessary (or if not, always pass in a 1 for
5406      `escapeflag').  Non-readable objects should in general ignore
5407      `escapeflag', except that some use it as an indication that more
5408      verbose output should be given.
5409
5410      Sub-objects are printed using `print_internal()', which takes
5411      exactly the same arguments as are passed to the print method.
5412
5413      Literal C strings should be printed using `write_c_string()', or
5414      `write_string_1()' for non-null-terminated strings.
5415
5416      Functions that do not have a readable representation should check
5417      the `print_readably' flag and signal an error if it is set.
5418
5419      If you specify NULL for the print method, the
5420      `default_object_printer()' will be used.
5421
5422   3. A "finalize" method.  This is called at the beginning of the sweep
5423      stage on lcrecords that are about to be freed, and should be used
5424      to perform any extra object cleanup.  This typically involves
5425      freeing any extra `malloc()'ed memory associated with the object,
5426      releasing any operating-system and window-system resources
5427      associated with the object (e.g. pixmaps, fonts), etc.
5428
5429      The finalize method can be NULL if nothing needs to be done.
5430
5431      WARNING #1: The finalize method is also called at the end of the
5432      dump phase; this time with the for_disksave parameter set to
5433      non-zero.  The object is _not_ about to disappear, so you have to
5434      make sure to _not_ free any extra `malloc()'ed memory if you're
5435      going to need it later.  (Also, signal an error if there are any
5436      operating-system and window-system resources here, because they
5437      can't be dumped.)
5438
5439      Finalize methods should, as a rule, set to zero any pointers after
5440      they've been freed, and check to make sure pointers are not zero
5441      before freeing.  Although I'm pretty sure that finalize methods
5442      are not called twice on the same object (except for the
5443      `for_disksave' proviso), we've gotten nastily burned in some cases
5444      by not doing this.
5445
5446      WARNING #2: The finalize method is _only_ called for lcrecords,
5447      _not_ for simply lrecords.  If you need a finalize method for
5448      simple lrecords, you have to stick it in the
5449      `ADDITIONAL_FREE_foo()' macro in `alloc.c'.
5450
5451      WARNING #3: Things are in an _extremely_ bizarre state when
5452      `ADDITIONAL_FREE_foo()' is called, so you have to be incredibly
5453      careful when writing one of these functions.  See the comment in
5454      `gc_sweep()'.  If you ever have to add one of these, consider
5455      using an lcrecord or dealing with the problem in a different
5456      fashion.
5457
5458   4. An "equal" method.  This compares the two objects for similarity,
5459      when `equal' is called.  It should compare the contents of the
5460      objects in some reasonable fashion.  It is passed the two objects
5461      and a "depth" value, which is used to catch circular objects.  To
5462      compare sub-Lisp-objects, call `internal_equal()' and bump the
5463      depth value by one.  If this value gets too high, a
5464      `circular-object' error will be signaled.
5465
5466      If this is NULL, objects are `equal' only when they are `eq', i.e.
5467      identical.
5468
5469   5. A "hash" method.  This is used to hash objects when they are to be
5470      compared with `equal'.  The rule here is that if two objects are
5471      `equal', they _must_ hash to the same value; i.e. your hash
5472      function should use some subset of the sub-fields of the object
5473      that are compared in the "equal" method.  If you specify this
5474      method as `NULL', the object's pointer will be used as the hash,
5475      which will _fail_ if the object has an `equal' method, so don't do
5476      this.
5477
5478      To hash a sub-Lisp-object, call `internal_hash()'.  Bump the depth
5479      by one, just like in the "equal" method.
5480
5481      To convert a Lisp object directly into a hash value (using its
5482      pointer), use `LISP_HASH()'.  This is what happens when the hash
5483      method is NULL.
5484
5485      To hash two or more values together into a single value, use
5486      `HASH2()', `HASH3()', `HASH4()', etc.
5487
5488   6. "getprop", "putprop", "remprop", and "plist" methods.  These are
5489      used for object types that have properties.  I don't feel like
5490      documenting them here.  If you create one of these objects, you
5491      have to use different macros to define them, i.e.
5492      `DEFINE_LRECORD_IMPLEMENTATION_WITH_PROPS()' or
5493      `DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION_WITH_PROPS()'.
5494
5495   7. A "size_in_bytes" method, when the object is of variable-size.
5496      (i.e. declared with a `_SEQUENCE_IMPLEMENTATION' macro.)  This
5497      should simply return the object's size in bytes, exactly as you
5498      might expect.  For an example, see the methods for window
5499      configurations and opaques.
5500
5501 \1f
5502 File: internals.info,  Node: Low-level allocation,  Next: Cons,  Prev: lrecords,  Up: Allocation of Objects in XEmacs Lisp
5503
5504 Low-level allocation
5505 ====================
5506
5507 Memory that you want to allocate directly should be allocated using
5508 `xmalloc()' rather than `malloc()'.  This implements error-checking on
5509 the return value, and once upon a time did some more vital stuff (i.e.
5510 `BLOCK_INPUT', which is no longer necessary).  Free using `xfree()',
5511 and realloc using `xrealloc()'.  Note that `xmalloc()' will do a
5512 non-local exit if the memory can't be allocated. (Many functions,
5513 however, do not expect this, and thus XEmacs will likely crash if this
5514 happens.  *This is a bug.*  If you can, you should strive to make your
5515 function handle this OK.  However, it's difficult in the general
5516 circumstance, perhaps requiring extra unwind-protects and such.)
5517
5518    Note that XEmacs provides two separate replacements for the standard
5519 `malloc()' library function.  These are called "old GNU malloc"
5520 (`malloc.c') and "new GNU malloc" (`gmalloc.c'), respectively.  New GNU
5521 malloc is better in pretty much every way than old GNU malloc, and
5522 should be used if possible.  (It used to be that on some systems, the
5523 old one worked but the new one didn't.  I think this was due
5524 specifically to a bug in SunOS, which the new one now works around; so
5525 I don't think the old one ever has to be used any more.) The primary
5526 difference between both of these mallocs and the standard system malloc
5527 is that they are much faster, at the expense of increased space.  The
5528 basic idea is that memory is allocated in fixed chunks of powers of
5529 two.  This allows for basically constant malloc time, since the various
5530 chunks can just be kept on a number of free lists. (The standard system
5531 malloc typically allocates arbitrary-sized chunks and has to spend some
5532 time, sometimes a significant amount of time, walking the heap looking
5533 for a free block to use and cleaning things up.)  The new GNU malloc
5534 improves on things by allocating large objects in chunks of 4096 bytes
5535 rather than in ever larger powers of two, which results in ever larger
5536 wastage.  There is a slight speed loss here, but it's of doubtful
5537 significance.
5538
5539    NOTE: Apparently there is a third-generation GNU malloc that is
5540 significantly better than the new GNU malloc, and should probably be
5541 included in XEmacs.
5542
5543    There is also the relocating allocator, `ralloc.c'.  This actually
5544 moves blocks of memory around so that the `sbrk()' pointer shrunk and
5545 virtual memory released back to the system.  On some systems, this is a
5546 big win.  On all systems, it causes a noticeable (and sometimes huge)
5547 speed penalty, so I turn it off by default.  `ralloc.c' only works with
5548 the new GNU malloc in `gmalloc.c'.  There are also two versions of
5549 `ralloc.c', one that uses `mmap()' rather than block copies to move
5550 data around.  This purports to be faster, although that depends on the
5551 amount of data that would have had to be block copied and the
5552 system-call overhead for `mmap()'.  I don't know exactly how this
5553 works, except that the relocating-allocation routines are pretty much
5554 used only for the memory allocated for a buffer, which is the biggest
5555 consumer of space, esp. of space that may get freed later.
5556
5557    Note that the GNU mallocs have some "memory warning" facilities.
5558 XEmacs taps into them and issues a warning through the standard warning
5559 system, when memory gets to 75%, 85%, and 95% full.  (On some systems,
5560 the memory warnings are not functional.)
5561
5562    Allocated memory that is going to be used to make a Lisp object is
5563 created using `allocate_lisp_storage()'.  This just calls `xmalloc()'.
5564 It used to verify that the pointer to the memory can fit into a Lisp
5565 word, before the current Lisp object representation was introduced.
5566 `allocate_lisp_storage()' is called by `alloc_lcrecord()',
5567 `ALLOCATE_FIXED_TYPE()', and the vector and bit-vector creation
5568 routines.  These routines also call `INCREMENT_CONS_COUNTER()' at the
5569 appropriate times; this keeps statistics on how much memory is
5570 allocated, so that garbage-collection can be invoked when the threshold
5571 is reached.
5572
5573 \1f
5574 File: internals.info,  Node: Cons,  Next: Vector,  Prev: Low-level allocation,  Up: Allocation of Objects in XEmacs Lisp
5575
5576 Cons
5577 ====
5578
5579 Conses are allocated in standard frob blocks.  The only thing to note
5580 is that conses can be explicitly freed using `free_cons()' and
5581 associated functions `free_list()' and `free_alist()'.  This
5582 immediately puts the conses onto the cons free list, and decrements the
5583 statistics on memory allocation appropriately.  This is used to good
5584 effect by some extremely commonly-used code, to avoid generating extra
5585 objects and thereby triggering GC sooner.  However, you have to be
5586 _extremely_ careful when doing this.  If you mess this up, you will get
5587 BADLY BURNED, and it has happened before.
5588
5589 \1f
5590 File: internals.info,  Node: Vector,  Next: Bit Vector,  Prev: Cons,  Up: Allocation of Objects in XEmacs Lisp
5591
5592 Vector
5593 ======
5594
5595 As mentioned above, each vector is `malloc()'ed individually, and all
5596 are threaded through the variable `all_vectors'.  Vectors are marked
5597 strangely during garbage collection, by kludging the size field.  Note
5598 that the `struct Lisp_Vector' is declared with its `contents' field
5599 being a _stretchy_ array of one element.  It is actually `malloc()'ed
5600 with the right size, however, and access to any element through the
5601 `contents' array works fine.
5602
5603 \1f
5604 File: internals.info,  Node: Bit Vector,  Next: Symbol,  Prev: Vector,  Up: Allocation of Objects in XEmacs Lisp
5605
5606 Bit Vector
5607 ==========
5608
5609 Bit vectors work exactly like vectors, except for more complicated code
5610 to access an individual bit, and except for the fact that bit vectors
5611 are lrecords while vectors are not. (The only difference here is that
5612 there's an lrecord implementation pointer at the beginning and the tag
5613 field in bit vector Lisp words is "lrecord" rather than "vector".)
5614
5615 \1f
5616 File: internals.info,  Node: Symbol,  Next: Marker,  Prev: Bit Vector,  Up: Allocation of Objects in XEmacs Lisp
5617
5618 Symbol
5619 ======
5620
5621 Symbols are also allocated in frob blocks.  Symbols in the awful
5622 horrible obarray structure are chained through their `next' field.
5623
5624    Remember that `intern' looks up a symbol in an obarray, creating one
5625 if necessary.
5626
5627 \1f
5628 File: internals.info,  Node: Marker,  Next: String,  Prev: Symbol,  Up: Allocation of Objects in XEmacs Lisp
5629
5630 Marker
5631 ======
5632
5633 Markers are allocated in frob blocks, as usual.  They are kept in a
5634 buffer unordered, but in a doubly-linked list so that they can easily
5635 be removed. (Formerly this was a singly-linked list, but in some cases
5636 garbage collection took an extraordinarily long time due to the O(N^2)
5637 time required to remove lots of markers from a buffer.) Markers are
5638 removed from a buffer in the finalize stage, in
5639 `ADDITIONAL_FREE_marker()'.
5640
5641 \1f
5642 File: internals.info,  Node: String,  Next: Compiled Function,  Prev: Marker,  Up: Allocation of Objects in XEmacs Lisp
5643
5644 String
5645 ======
5646
5647 As mentioned above, strings are a special case.  A string is logically
5648 two parts, a fixed-size object (containing the length, property list,
5649 and a pointer to the actual data), and the actual data in the string.
5650 The fixed-size object is a `struct Lisp_String' and is allocated in
5651 frob blocks, as usual.  The actual data is stored in special
5652 "string-chars blocks", which are 8K blocks of memory.
5653 Currently-allocated strings are simply laid end to end in these
5654 string-chars blocks, with a pointer back to the `struct Lisp_String'
5655 stored before each string in the string-chars block.  When a new string
5656 needs to be allocated, the remaining space at the end of the last
5657 string-chars block is used if there's enough, and a new string-chars
5658 block is created otherwise.
5659
5660    There are never any holes in the string-chars blocks due to the
5661 string compaction and relocation that happens at the end of garbage
5662 collection.  During the sweep stage of garbage collection, when objects
5663 are reclaimed, the garbage collector goes through all string-chars
5664 blocks, looking for unused strings.  Each chunk of string data is
5665 preceded by a pointer to the corresponding `struct Lisp_String', which
5666 indicates both whether the string is used and how big the string is,
5667 i.e. how to get to the next chunk of string data.  Holes are compressed
5668 by block-copying the next string into the empty space and relocating the
5669 pointer stored in the corresponding `struct Lisp_String'.  *This means
5670 you have to be careful with strings in your code.* See the section
5671 above on `GCPRO'ing.
5672
5673    Note that there is one situation not handled: a string that is too
5674 big to fit into a string-chars block.  Such strings, called "big
5675 strings", are all `malloc()'ed as their own block. (#### Although it
5676 would make more sense for the threshold for big strings to be somewhat
5677 lower, e.g. 1/2 or 1/4 the size of a string-chars block.  It seems that
5678 this was indeed the case formerly--indeed, the threshold was set at
5679 1/8--but Mly forgot about this when rewriting things for 19.8.)
5680
5681    Note also that the string data in string-chars blocks is padded as
5682 necessary so that proper alignment constraints on the `struct
5683 Lisp_String' back pointers are maintained.
5684
5685    Finally, strings can be resized.  This happens in Mule when a
5686 character is substituted with a different-length character, or during
5687 modeline frobbing. (You could also export this to Lisp, but it's not
5688 done so currently.) Resizing a string is a potentially tricky process.
5689 If the change is small enough that the padding can absorb it, nothing
5690 other than a simple memory move needs to be done.  Keep in mind,
5691 however, that the string can't shrink too much because the offset to the
5692 next string in the string-chars block is computed by looking at the
5693 length and rounding to the nearest multiple of four or eight.  If the
5694 string would shrink or expand beyond the correct padding, new string
5695 data needs to be allocated at the end of the last string-chars block and
5696 the data moved appropriately.  This leaves some dead string data, which
5697 is marked by putting a special marker of 0xFFFFFFFF in the `struct
5698 Lisp_String' pointer before the data (there's no real `struct
5699 Lisp_String' to point to and relocate), and storing the size of the dead
5700 string data (which would normally be obtained from the now-non-existent
5701 `struct Lisp_String') at the beginning of the dead string data gap.
5702 The string compactor recognizes this special 0xFFFFFFFF marker and
5703 handles it correctly.
5704
5705 \1f
5706 File: internals.info,  Node: Compiled Function,  Prev: String,  Up: Allocation of Objects in XEmacs Lisp
5707
5708 Compiled Function
5709 =================
5710
5711 Not yet documented.
5712
5713 \1f
5714 File: internals.info,  Node: Dumping,  Next: Events and the Event Loop,  Prev: Allocation of Objects in XEmacs Lisp,  Up: Top
5715
5716 Dumping
5717 *******
5718
5719 What is dumping and its justification
5720 =====================================
5721
5722 The C code of XEmacs is just a Lisp engine with a lot of built-in
5723 primitives useful for writing an editor.  The editor itself is written
5724 mostly in Lisp, and represents around 100K lines of code.  Loading and
5725 executing the initialization of all this code takes a bit a time (five
5726 to ten times the usual startup time of current xemacs) and requires
5727 having all the lisp source files around.  Having to reload them each
5728 time the editor is started would not be acceptable.
5729
5730    The traditional solution to this problem is called dumping: the build
5731 process first creates the lisp engine under the name `temacs', then
5732 runs it until it has finished loading and initializing all the lisp
5733 code, and eventually creates a new executable called `xemacs' including
5734 both the object code in `temacs' and all the contents of the memory
5735 after the initialization.
5736
5737    This solution, while working, has a huge problem: the creation of the
5738 new executable from the actual contents of memory is an extremely
5739 system-specific process, quite error-prone, and which interferes with a
5740 lot of system libraries (like malloc).  It is even getting worse
5741 nowadays with libraries using constructors which are automatically
5742 called when the program is started (even before main()) which tend to
5743 crash when they are called multiple times, once before dumping and once
5744 after (IRIX 6.x libz.so pulls in some C++ image libraries thru
5745 dependencies which have this problem).  Writing the dumper is also one
5746 of the most difficult parts of porting XEmacs to a new operating system.
5747 Basically, `dumping' is an operation that is just not officially
5748 supported on many operating systems.
5749
5750    The aim of the portable dumper is to solve the same problem as the
5751 system-specific dumper, that is to be able to reload quickly, using only
5752 a small number of files, the fully initialized lisp part of the editor,
5753 without any system-specific hacks.
5754
5755 * Menu:
5756
5757 * Overview::
5758 * Data descriptions::
5759 * Dumping phase::
5760 * Reloading phase::
5761 * Remaining issues::
5762
5763 \1f
5764 File: internals.info,  Node: Overview,  Next: Data descriptions,  Up: Dumping
5765
5766 Overview
5767 ========
5768
5769 The portable dumping system has to:
5770
5771   1. At dump time, write all initialized, non-quickly-rebuildable data
5772      to a file [Note: currently named `xemacs.dmp', but the name will
5773      change], along with all informations needed for the reloading.
5774
5775   2. When starting xemacs, reload the dump file, relocate it to its new
5776      starting address if needed, and reinitialize all pointers to this
5777      data.  Also, rebuild all the quickly rebuildable data.
5778
5779 \1f
5780 File: internals.info,  Node: Data descriptions,  Next: Dumping phase,  Prev: Overview,  Up: Dumping
5781
5782 Data descriptions
5783 =================
5784
5785 The more complex task of the dumper is to be able to write lisp objects
5786 (lrecords) and C structs to disk and reload them at a different address,
5787 updating all the pointers they include in the process.  This is done by
5788 using external data descriptions that give information about the layout
5789 of the structures in memory.
5790
5791    The specification of these descriptions is in lrecord.h.  A
5792 description of an lrecord is an array of struct lrecord_description.
5793 Each of these structs include a type, an offset in the structure and
5794 some optional parameters depending on the type.  For instance, here is
5795 the string description:
5796
5797      static const struct lrecord_description string_description[] = {
5798        { XD_BYTECOUNT,         offsetof (Lisp_String, size) },
5799        { XD_OPAQUE_DATA_PTR,   offsetof (Lisp_String, data), XD_INDIRECT(0, 1) },
5800        { XD_LISP_OBJECT,       offsetof (Lisp_String, plist) },
5801        { XD_END }
5802      };
5803
5804    The first line indicates a member of type Bytecount, which is used by
5805 the next, indirect directive.  The second means "there is a pointer to
5806 some opaque data in the field `data'".  The length of said data is
5807 given by the expression `XD_INDIRECT(0, 1)', which means "the value in
5808 the 0th line of the description (welcome to C) plus one".  The third
5809 line means "there is a Lisp_Object member `plist' in the Lisp_String
5810 structure".  `XD_END' then ends the description.
5811
5812    This gives us all the information we need to move around what is
5813 pointed to by a structure (C or lrecord) and, by transitivity,
5814 everything that it points to.  The only missing information for dumping
5815 is the size of the structure.  For lrecords, this is part of the
5816 lrecord_implementation, so we don't need to duplicate it.  For C
5817 structures we use a struct struct_description, which includes a size
5818 field and a pointer to an associated array of lrecord_description.
5819
5820 \1f
5821 File: internals.info,  Node: Dumping phase,  Next: Reloading phase,  Prev: Data descriptions,  Up: Dumping
5822
5823 Dumping phase
5824 =============
5825
5826 Dumping is done by calling the function pdump() (in dumper.c) which is
5827 invoked from Fdump_emacs (in emacs.c).  This function performs a number
5828 of tasks.
5829
5830 * Menu:
5831
5832 * Object inventory::
5833 * Address allocation::
5834 * The header::
5835 * Data dumping::
5836 * Pointers dumping::
5837
5838 \1f
5839 File: internals.info,  Node: Object inventory,  Next: Address allocation,  Up: Dumping phase
5840
5841 Object inventory
5842 ----------------
5843
5844 The first task is to build the list of the objects to dump.  This
5845 includes:
5846
5847    * lisp objects
5848
5849    * C structures
5850
5851    We end up with one `pdump_entry_list_elmt' per object group (arrays
5852 of C structs are kept together) which includes a pointer to the first
5853 object of the group, the per-object size and the count of objects in the
5854 group, along with some other information which is initialized later.
5855
5856    These entries are linked together in `pdump_entry_list' structures
5857 and can be enumerated thru either:
5858
5859   1. the `pdump_object_table', an array of `pdump_entry_list', one per
5860      lrecord type, indexed by type number.
5861
5862   2. the `pdump_opaque_data_list', used for the opaque data which does
5863      not include pointers, and hence does not need descriptions.
5864
5865   3. the `pdump_struct_table', which is a vector of
5866      `struct_description'/`pdump_entry_list' pairs, used for non-opaque
5867      C structures.
5868
5869    This uses a marking strategy similar to the garbage collector.  Some
5870 differences though:
5871
5872   1. We do not use the mark bit (which does not exist for C structures
5873      anyway); we use a big hash table instead.
5874
5875   2. We do not use the mark function of lrecords but instead rely on the
5876      external descriptions.  This happens essentially because we need to
5877      follow pointers to C structures and opaque data in addition to
5878      Lisp_Object members.
5879
5880    This is done by `pdump_register_object()', which handles Lisp_Object
5881 variables, and `pdump_register_struct()' which handles C structures,
5882 which both delegate the description management to
5883 `pdump_register_sub()'.
5884
5885    The hash table doubles as a map object to pdump_entry_list_elmt (i.e.
5886 allows us to look up a pdump_entry_list_elmt with the object it points
5887 to).  Entries are added with `pdump_add_entry()' and looked up with
5888 `pdump_get_entry()'.  There is no need for entry removal.  The hash
5889 value is computed quite simply from the object pointer by
5890 `pdump_make_hash()'.
5891
5892    The roots for the marking are:
5893
5894   1. the `staticpro''ed variables (there is a special
5895      `staticpro_nodump()' call for protected variables we do not want
5896      to dump).
5897
5898   2. the variables registered via `dump_add_root_object' (`staticpro()'
5899      is equivalent to `staticpro_nodump()' + `dump_add_root_object()').
5900
5901   3. the variables registered via `dump_add_root_struct_ptr', each of
5902      which points to a C structure.
5903
5904    This does not include the GCPRO'ed variables, the specbinds, the
5905 catchtags, the backlist, the redisplay or the profiling info, since we
5906 do not want to rebuild the actual chain of lisp calls which end up to
5907 the dump-emacs call, only the global variables.
5908
5909    Weak lists and weak hash tables are dumped as if they were their
5910 non-weak equivalent (without changing their type, of course).  This has
5911 not yet been a problem.
5912
5913 \1f
5914 File: internals.info,  Node: Address allocation,  Next: The header,  Prev: Object inventory,  Up: Dumping phase
5915
5916 Address allocation
5917 ------------------
5918
5919 The next step is to allocate the offsets of each of the objects in the
5920 final dump file.  This is done by `pdump_allocate_offset()' which is
5921 called indirectly by `pdump_scan_by_alignment()'.
5922
5923    The strategy to deal with alignment problems uses these facts:
5924
5925   1. real world alignment requirements are powers of two.
5926
5927   2. the C compiler is required to adjust the size of a struct so that
5928      you can have an array of them next to each other.  This means you
5929      can have an upper bound of the alignment requirements of a given
5930      structure by looking at which power of two its size is a multiple.
5931
5932   3. the non-variant part of variable size lrecords has an alignment
5933      requirement of 4.
5934
5935    Hence, for each lrecord type, C struct type or opaque data block the
5936 alignment requirement is computed as a power of two, with a minimum of
5937 2^2 for lrecords.  `pdump_scan_by_alignment()' then scans all the
5938 `pdump_entry_list_elmt''s, the ones with the highest requirements
5939 first.  This ensures the best packing.
5940
5941    The maximum alignment requirement we take into account is 2^8.
5942
5943    `pdump_allocate_offset()' only has to do a linear allocation,
5944 starting at offset 256 (this leaves room for the header and keeps the
5945 alignments happy).
5946
5947 \1f
5948 File: internals.info,  Node: The header,  Next: Data dumping,  Prev: Address allocation,  Up: Dumping phase
5949
5950 The header
5951 ----------
5952
5953 The next step creates the file and writes a header with a signature and
5954 some random information in it.  The `reloc_address' field, which
5955 indicates at which address the file should be loaded if we want to avoid
5956 post-reload relocation, is set to 0.  It then seeks to offset 256 (base
5957 offset for the objects).
5958
5959 \1f
5960 File: internals.info,  Node: Data dumping,  Next: Pointers dumping,  Prev: The header,  Up: Dumping phase
5961
5962 Data dumping
5963 ------------
5964
5965 The data is dumped in the same order as the addresses were allocated by
5966 `pdump_dump_data()', called from `pdump_scan_by_alignment()'.  This
5967 function copies the data to a temporary buffer, relocates all pointers
5968 in the object to the addresses allocated in step Address Allocation,
5969 and writes it to the file.  Using the same order means that, if we are
5970 careful with lrecords whose size is not a multiple of 4, we are ensured
5971 that the object is always written at the offset in the file allocated
5972 in step Address Allocation.
5973
5974 \1f
5975 File: internals.info,  Node: Pointers dumping,  Prev: Data dumping,  Up: Dumping phase
5976
5977 Pointers dumping
5978 ----------------
5979
5980 A bunch of tables needed to reassign properly the global pointers are
5981 then written.  They are:
5982
5983   1. the pdump_root_struct_ptrs dynarr
5984
5985   2. the pdump_opaques dynarr
5986
5987   3. a vector of all the offsets to the objects in the file that
5988      include a description (for faster relocation at reload time)
5989
5990   4. the pdump_root_objects and pdump_weak_object_chains dynarrs.
5991
5992    For each of the dynarrs we write both the pointer to the variables
5993 and the relocated offset of the object they point to.  Since these
5994 variables are global, the pointers are still valid when restarting the
5995 program and are used to regenerate the global pointers.
5996
5997    The `pdump_weak_object_chains' dynarr is a special case.  The
5998 variables it points to are the head of weak linked lists of lisp objects
5999 of the same type.  Not all objects of this list are dumped so the
6000 relocated pointer we associate with them points to the first dumped
6001 object of the list, or Qnil if none is available.  This is also the
6002 reason why they are not used as roots for the purpose of object
6003 enumeration.
6004
6005    Some very important information like the `staticpros' and
6006 `lrecord_implementations_table' are handled indirectly using
6007 `dump_add_opaque' or `dump_add_root_struct_ptr'.
6008
6009    This is the end of the dumping part.
6010
6011 \1f
6012 File: internals.info,  Node: Reloading phase,  Next: Remaining issues,  Prev: Dumping phase,  Up: Dumping
6013
6014 Reloading phase
6015 ===============
6016
6017 File loading
6018 ------------
6019
6020 The file is mmap'ed in memory (which ensures a PAGESIZE alignment, at
6021 least 4096), or if mmap is unavailable or fails, a 256-bytes aligned
6022 malloc is done and the file is loaded.
6023
6024    Some variables are reinitialized from the values found in the header.
6025
6026    The difference between the actual loading address and the
6027 reloc_address is computed and will be used for all the relocations.
6028
6029 Putting back the pdump_opaques
6030 ------------------------------
6031
6032 The memory contents are restored in the obvious and trivial way.
6033
6034 Putting back the pdump_root_struct_ptrs
6035 ---------------------------------------
6036
6037 The variables pointed to by pdump_root_struct_ptrs in the dump phase are
6038 reset to the right relocated object addresses.
6039
6040 Object relocation
6041 -----------------
6042
6043 All the objects are relocated using their description and their offset
6044 by `pdump_reloc_one'.  This step is unnecessary if the reloc_address is
6045 equal to the file loading address.
6046
6047 Putting back the pdump_root_objects and pdump_weak_object_chains
6048 ----------------------------------------------------------------
6049
6050 Same as Putting back the pdump_root_struct_ptrs.
6051
6052 Reorganize the hash tables
6053 --------------------------
6054
6055 Since some of the hash values in the lisp hash tables are
6056 address-dependent, their layout is now wrong.  So we go through each of
6057 them and have them resorted by calling `pdump_reorganize_hash_table'.
6058
6059 \1f
6060 File: internals.info,  Node: Remaining issues,  Prev: Reloading phase,  Up: Dumping
6061
6062 Remaining issues
6063 ================
6064
6065 The build process will have to start a post-dump xemacs, ask it the
6066 loading address (which will, hopefully, be always the same between
6067 different xemacs invocations) and relocate the file to the new address.
6068 This way the object relocation phase will not have to be done, which
6069 means no writes in the objects and that, because of the use of mmap, the
6070 dumped data will be shared between all the xemacs running on the
6071 computer.
6072
6073    Some executable signature will be necessary to ensure that a given
6074 dump file is really associated with a given executable, or random
6075 crashes will occur.  Maybe a random number set at compile or configure
6076 time thru a define.  This will also allow for having
6077 differently-compiled xemacsen on the same system (mule and no-mule
6078 comes to mind).
6079
6080    The DOC file contents should probably end up in the dump file.
6081
6082 \1f
6083 File: internals.info,  Node: Events and the Event Loop,  Next: Evaluation; Stack Frames; Bindings,  Prev: Dumping,  Up: Top
6084
6085 Events and the Event Loop
6086 *************************
6087
6088 * Menu:
6089
6090 * Introduction to Events::
6091 * Main Loop::
6092 * Specifics of the Event Gathering Mechanism::
6093 * Specifics About the Emacs Event::
6094 * The Event Stream Callback Routines::
6095 * Other Event Loop Functions::
6096 * Converting Events::
6097 * Dispatching Events; The Command Builder::
6098
6099 \1f
6100 File: internals.info,  Node: Introduction to Events,  Next: Main Loop,  Up: Events and the Event Loop
6101
6102 Introduction to Events
6103 ======================
6104
6105 An event is an object that encapsulates information about an
6106 interesting occurrence in the operating system.  Events are generated
6107 either by user action, direct (e.g. typing on the keyboard or moving
6108 the mouse) or indirect (moving another window, thereby generating an
6109 expose event on an Emacs frame), or as a result of some other typically
6110 asynchronous action happening, such as output from a subprocess being
6111 ready or a timer expiring.  Events come into the system in an
6112 asynchronous fashion (typically through a callback being called) and
6113 are converted into a synchronous event queue (first-in, first-out) in a
6114 process that we will call "collection".
6115
6116    Note that each application has its own event queue. (It is
6117 immaterial whether the collection process directly puts the events in
6118 the proper application's queue, or puts them into a single system
6119 queue, which is later split up.)
6120
6121    The most basic level of event collection is done by the operating
6122 system or window system.  Typically, XEmacs does its own event
6123 collection as well.  Often there are multiple layers of collection in
6124 XEmacs, with events from various sources being collected into a queue,
6125 which is then combined with other sources to go into another queue
6126 (i.e. a second level of collection), with perhaps another level on top
6127 of this, etc.
6128
6129    XEmacs has its own types of events (called "Emacs events"), which
6130 provides an abstract layer on top of the system-dependent nature of the
6131 most basic events that are received.  Part of the complex nature of the
6132 XEmacs event collection process involves converting from the
6133 operating-system events into the proper Emacs events--there may not be
6134 a one-to-one correspondence.
6135
6136    Emacs events are documented in `events.h'; I'll discuss them later.
6137
6138 \1f
6139 File: internals.info,  Node: Main Loop,  Next: Specifics of the Event Gathering Mechanism,  Prev: Introduction to Events,  Up: Events and the Event Loop
6140
6141 Main Loop
6142 =========
6143
6144 The "command loop" is the top-level loop that the editor is always
6145 running.  It loops endlessly, calling `next-event' to retrieve an event
6146 and `dispatch-event' to execute it. `dispatch-event' does the
6147 appropriate thing with non-user events (process, timeout, magic, eval,
6148 mouse motion); this involves calling a Lisp handler function, redrawing
6149 a newly-exposed part of a frame, reading subprocess output, etc.  For
6150 user events, `dispatch-event' looks up the event in relevant keymaps or
6151 menubars; when a full key sequence or menubar selection is reached, the
6152 appropriate function is executed. `dispatch-event' may have to keep
6153 state across calls; this is done in the "command-builder" structure
6154 associated with each console (remember, there's usually only one
6155 console), and the engine that looks up keystrokes and constructs full
6156 key sequences is called the "command builder".  This is documented
6157 elsewhere.
6158
6159    The guts of the command loop are in `command_loop_1()'.  This
6160 function doesn't catch errors, though--that's the job of
6161 `command_loop_2()', which is a condition-case (i.e. error-trapping)
6162 wrapper around `command_loop_1()'.  `command_loop_1()' never returns,
6163 but may get thrown out of.
6164
6165    When an error occurs, `cmd_error()' is called, which usually invokes
6166 the Lisp error handler in `command-error'; however, a default error
6167 handler is provided if `command-error' is `nil' (e.g. during startup).
6168 The purpose of the error handler is simply to display the error message
6169 and do associated cleanup; it does not need to throw anywhere.  When
6170 the error handler finishes, the condition-case in `command_loop_2()'
6171 will finish and `command_loop_2()' will reinvoke `command_loop_1()'.
6172
6173    `command_loop_2()' is invoked from three places: from
6174 `initial_command_loop()' (called from `main()' at the end of internal
6175 initialization), from the Lisp function `recursive-edit', and from
6176 `call_command_loop()'.
6177
6178    `call_command_loop()' is called when a macro is started and when the
6179 minibuffer is entered; normal termination of the macro or minibuffer
6180 causes a throw out of the recursive command loop. (To
6181 `execute-kbd-macro' for macros and `exit' for minibuffers.  Note also
6182 that the low-level minibuffer-entering function,
6183 `read-minibuffer-internal', provides its own error handling and does
6184 not need `command_loop_2()''s error encapsulation; so it tells
6185 `call_command_loop()' to invoke `command_loop_1()' directly.)
6186
6187    Note that both read-minibuffer-internal and recursive-edit set up a
6188 catch for `exit'; this is why `abort-recursive-edit', which throws to
6189 this catch, exits out of either one.
6190
6191    `initial_command_loop()', called from `main()', sets up a catch for
6192 `top-level' when invoking `command_loop_2()', allowing functions to
6193 throw all the way to the top level if they really need to.  Before
6194 invoking `command_loop_2()', `initial_command_loop()' calls
6195 `top_level_1()', which handles all of the startup stuff (creating the
6196 initial frame, handling the command-line options, loading the user's
6197 `.emacs' file, etc.).  The function that actually does this is in Lisp
6198 and is pointed to by the variable `top-level'; normally this function is
6199 `normal-top-level'.  `top_level_1()' is just an error-handling wrapper
6200 similar to `command_loop_2()'.  Note also that `initial_command_loop()'
6201 sets up a catch for `top-level' when invoking `top_level_1()', just
6202 like when it invokes `command_loop_2()'.
6203
6204 \1f
6205 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
6206
6207 Specifics of the Event Gathering Mechanism
6208 ==========================================
6209
6210 Here is an approximate diagram of the collection processes at work in
6211 XEmacs, under TTY's (TTY's are simpler than X so we'll look at this
6212 first):
6213
6214       asynch.      asynch.    asynch.   asynch.             [Collectors in
6215      kbd events  kbd events   process   process                the OS]
6216            |         |         output    output
6217            |         |           |         |
6218            |         |           |         |      SIGINT,   [signal handlers
6219            |         |           |         |      SIGQUIT,     in XEmacs]
6220            V         V           V         V      SIGWINCH,
6221           file      file        file      file    SIGALRM
6222           desc.     desc.       desc.     desc.     |
6223           (TTY)     (TTY)       (pipe)    (pipe)    |
6224            |          |          |         |      fake    timeouts
6225            |          |          |         |      file        |
6226            |          |          |         |      desc.       |
6227            |          |          |         |      (pipe)      |
6228            |          |          |         |        |         |
6229            |          |          |         |        |         |
6230            |          |          |         |        |         |
6231            V          V          V         V        V         V
6232            ------>-----------<----------------<----------------
6233                        |
6234                        |
6235                        | [collected using select() in emacs_tty_next_event()
6236                        |  and converted to the appropriate Emacs event]
6237                        |
6238                        |
6239                        V          (above this line is TTY-specific)
6240                      Emacs -----------------------------------------------
6241                      event (below this line is the generic event mechanism)
6242                        |
6243                        |
6244      was there     if not, call
6245      a SIGINT?  emacs_tty_next_event()
6246          |             |
6247          |             |
6248          |             |
6249          V             V
6250          --->------<----
6251                 |
6252                 |     [collected in event_stream_next_event();
6253                 |      SIGINT is converted using maybe_read_quit_event()]
6254                 V
6255               Emacs
6256               event
6257                 |
6258                 \---->------>----- maybe_kbd_translate() ---->---\
6259                                                                  |
6260                                                                  |
6261                                                                  |
6262           command event queue                                    |
6263                                                     if not from command
6264        (contains events that were                   event queue, call
6265        read earlier but not processed,              event_stream_next_event()
6266        typically when waiting in a                               |
6267        sit-for, sleep-for, etc. for                              |
6268       a particular event to be received)                         |
6269                     |                                            |
6270                     |                                            |
6271                     V                                            V
6272                     ---->------------------------------------<----
6273                                                     |
6274                                                     | [collected in
6275                                                     |  next_event_internal()]
6276                                                     |
6277       unread-     unread-       event from          |
6278       command-    command-       keyboard       else, call
6279       events      event           macro      next_event_internal()
6280         |           |               |               |
6281         |           |               |               |
6282         |           |               |               |
6283         V           V               V               V
6284         --------->----------------------<------------
6285                           |
6286                           |      [collected in `next-event', which may loop
6287                           |       more than once if the event it gets is on
6288                           |       a dead frame, device, etc.]
6289                           |
6290                           |
6291                           V
6292                  feed into top-level event loop,
6293                  which repeatedly calls `next-event'
6294                  and then dispatches the event
6295                  using `dispatch-event'
6296
6297    Notice the separation between TTY-specific and generic event
6298 mechanism.  When using the Xt-based event loop, the TTY-specific stuff
6299 is replaced but the rest stays the same.
6300
6301    It's also important to realize that only one different kind of
6302 system-specific event loop can be operating at a time, and must be able
6303 to receive all kinds of events simultaneously.  For the two existing
6304 event loops (implemented in `event-tty.c' and `event-Xt.c',
6305 respectively), the TTY event loop _only_ handles TTY consoles, while
6306 the Xt event loop handles _both_ TTY and X consoles.  This situation is
6307 different from all of the output handlers, where you simply have one
6308 per console type.
6309
6310    Here's the Xt Event Loop Diagram (notice that below a certain point,
6311 it's the same as the above diagram):
6312
6313      asynch. asynch. asynch. asynch.                 [Collectors in
6314       kbd     kbd    process process                    the OS]
6315      events  events  output  output
6316        |       |       |       |
6317        |       |       |       |     asynch. asynch. [Collectors in the
6318        |       |       |       |       X        X     OS and X Window System]
6319        |       |       |       |     events  events
6320        |       |       |       |       |        |
6321        |       |       |       |       |        |
6322        |       |       |       |       |        |    SIGINT, [signal handlers
6323        |       |       |       |       |        |    SIGQUIT,   in XEmacs]
6324        |       |       |       |       |        |    SIGWINCH,
6325        |       |       |       |       |        |    SIGALRM
6326        |       |       |       |       |        |       |
6327        |       |       |       |       |        |       |
6328        |       |       |       |       |        |       |      timeouts
6329        |       |       |       |       |        |       |          |
6330        |       |       |       |       |        |       |          |
6331        |       |       |       |       |        |       V          |
6332        V       V       V       V       V        V      fake        |
6333       file    file    file    file    file     file    file        |
6334       desc.   desc.   desc.   desc.   desc.    desc.   desc.       |
6335       (TTY)   (TTY)   (pipe)  (pipe) (socket) (socket) (pipe)      |
6336        |       |       |       |       |        |       |          |
6337        |       |       |       |       |        |       |          |
6338        |       |       |       |       |        |       |          |
6339        V       V       V       V       V        V       V          V
6340        --->----------------------------------------<---------<------
6341             |              |               |
6342             |              |               |[collected using select() in
6343             |              |               | _XtWaitForSomething(), called
6344             |              |               | from XtAppProcessEvent(), called
6345             |              |               | in emacs_Xt_next_event();
6346             |              |               | dispatched to various callbacks]
6347             |              |               |
6348             |              |               |
6349        emacs_Xt_        p_s_callback(),    | [popup_selection_callback]
6350        event_handler()  x_u_v_s_callback(),| [x_update_vertical_scrollbar_
6351             |           x_u_h_s_callback(),|  callback]
6352             |           search_callback()  | [x_update_horizontal_scrollbar_
6353             |              |               |  callback]
6354             |              |               |
6355             |              |               |
6356        enqueue_Xt_       signal_special_   |
6357        dispatch_event()  Xt_user_event()   |
6358        [maybe multiple     |               |
6359         times, maybe 0     |               |
6360         times]             |               |
6361             |            enqueue_Xt_       |
6362             |            dispatch_event()  |
6363             |              |               |
6364             |              |               |
6365             V              V               |
6366             -->----------<--               |
6367                    |                       |
6368                    |                       |
6369                 dispatch             Xt_what_callback()
6370                 event                  sets flags
6371                 queue                      |
6372                    |                       |
6373                    |                       |
6374                    |                       |
6375                    |                       |
6376                    ---->-----------<--------
6377                         |
6378                         |
6379                         |     [collected and converted as appropriate in
6380                         |            emacs_Xt_next_event()]
6381                         |
6382                         |
6383                         V          (above this line is Xt-specific)
6384                       Emacs ------------------------------------------------
6385                       event (below this line is the generic event mechanism)
6386                         |
6387                         |
6388      was there      if not, call
6389      a SIGINT?   emacs_Xt_next_event()
6390          |              |
6391          |              |
6392          |              |
6393          V              V
6394          --->-------<----
6395                 |
6396                 |        [collected in event_stream_next_event();
6397                 |         SIGINT is converted using maybe_read_quit_event()]
6398                 V
6399               Emacs
6400               event
6401                 |
6402                 \---->------>----- maybe_kbd_translate() -->-----\
6403                                                                  |
6404                                                                  |
6405                                                                  |
6406           command event queue                                    |
6407                                                    if not from command
6408        (contains events that were                  event queue, call
6409        read earlier but not processed,             event_stream_next_event()
6410        typically when waiting in a                               |
6411        sit-for, sleep-for, etc. for                              |
6412       a particular event to be received)                         |
6413                     |                                            |
6414                     |                                            |
6415                     V                                            V
6416                     ---->----------------------------------<------
6417                                                     |
6418                                                     | [collected in
6419                                                     |  next_event_internal()]
6420                                                     |
6421       unread-     unread-       event from          |
6422       command-    command-       keyboard       else, call
6423       events      event           macro      next_event_internal()
6424         |           |               |               |
6425         |           |               |               |
6426         |           |               |               |
6427         V           V               V               V
6428         --------->----------------------<------------
6429                           |
6430                           |      [collected in `next-event', which may loop
6431                           |       more than once if the event it gets is on
6432                           |       a dead frame, device, etc.]
6433                           |
6434                           |
6435                           V
6436                  feed into top-level event loop,
6437                  which repeatedly calls `next-event'
6438                  and then dispatches the event
6439                  using `dispatch-event'
6440
6441 \1f
6442 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
6443
6444 Specifics About the Emacs Event
6445 ===============================
6446
6447 \1f
6448 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
6449
6450 The Event Stream Callback Routines
6451 ==================================
6452
6453 \1f
6454 File: internals.info,  Node: Other Event Loop Functions,  Next: Converting Events,  Prev: The Event Stream Callback Routines,  Up: Events and the Event Loop
6455
6456 Other Event Loop Functions
6457 ==========================
6458
6459 `detect_input_pending()' and `input-pending-p' look for input by
6460 calling `event_stream->event_pending_p' and looking in
6461 `[V]unread-command-event' and the `command_event_queue' (they do not
6462 check for an executing keyboard macro, though).
6463
6464    `discard-input' cancels any command events pending (and any keyboard
6465 macros currently executing), and puts the others onto the
6466 `command_event_queue'.  There is a comment about a "race condition",
6467 which is not a good sign.
6468
6469    `next-command-event' and `read-char' are higher-level interfaces to
6470 `next-event'.  `next-command-event' gets the next "command" event (i.e.
6471 keypress, mouse event, menu selection, or scrollbar action), calling
6472 `dispatch-event' on any others.  `read-char' calls `next-command-event'
6473 and uses `event_to_character()' to return the character equivalent.
6474 With the right kind of input method support, it is possible for
6475 (read-char) to return a Kanji character.
6476
6477 \1f
6478 File: internals.info,  Node: Converting Events,  Next: Dispatching Events; The Command Builder,  Prev: Other Event Loop Functions,  Up: Events and the Event Loop
6479
6480 Converting Events
6481 =================
6482
6483 `character_to_event()', `event_to_character()', `event-to-character',
6484 and `character-to-event' convert between characters and keypress events
6485 corresponding to the characters.  If the event was not a keypress,
6486 `event_to_character()' returns -1 and `event-to-character' returns
6487 `nil'.  These functions convert between character representation and
6488 the split-up event representation (keysym plus mod keys).
6489
6490 \1f
6491 File: internals.info,  Node: Dispatching Events; The Command Builder,  Prev: Converting Events,  Up: Events and the Event Loop
6492
6493 Dispatching Events; The Command Builder
6494 =======================================
6495
6496 Not yet documented.
6497
6498 \1f
6499 File: internals.info,  Node: Evaluation; Stack Frames; Bindings,  Next: Symbols and Variables,  Prev: Events and the Event Loop,  Up: Top
6500
6501 Evaluation; Stack Frames; Bindings
6502 **********************************
6503
6504 * Menu:
6505
6506 * Evaluation::
6507 * Dynamic Binding; The specbinding Stack; Unwind-Protects::
6508 * Simple Special Forms::
6509 * Catch and Throw::
6510
6511 \1f
6512 File: internals.info,  Node: Evaluation,  Next: Dynamic Binding; The specbinding Stack; Unwind-Protects,  Up: Evaluation; Stack Frames; Bindings
6513
6514 Evaluation
6515 ==========
6516
6517 `Feval()' evaluates the form (a Lisp object) that is passed to it.
6518 Note that evaluation is only non-trivial for two types of objects:
6519 symbols and conses.  A symbol is evaluated simply by calling
6520 `symbol-value' on it and returning the value.
6521
6522    Evaluating a cons means calling a function.  First, `eval' checks to
6523 see if garbage-collection is necessary, and calls `garbage_collect_1()'
6524 if so.  It then increases the evaluation depth by 1 (`lisp_eval_depth',
6525 which is always less than `max_lisp_eval_depth') and adds an element to
6526 the linked list of `struct backtrace''s (`backtrace_list').  Each such
6527 structure contains a pointer to the function being called plus a list
6528 of the function's arguments.  Originally these values are stored
6529 unevalled, and as they are evaluated, the backtrace structure is
6530 updated.  Garbage collection pays attention to the objects pointed to
6531 in the backtrace structures (garbage collection might happen while a
6532 function is being called or while an argument is being evaluated, and
6533 there could easily be no other references to the arguments in the
6534 argument list; once an argument is evaluated, however, the unevalled
6535 version is not needed by eval, and so the backtrace structure is
6536 changed).
6537
6538    At this point, the function to be called is determined by looking at
6539 the car of the cons (if this is a symbol, its function definition is
6540 retrieved and the process repeated).  The function should then consist
6541 of either a `Lisp_Subr' (built-in function written in C), a
6542 `Lisp_Compiled_Function' object, or a cons whose car is one of the
6543 symbols `autoload', `macro' or `lambda'.
6544
6545    If the function is a `Lisp_Subr', the lisp object points to a
6546 `struct Lisp_Subr' (created by `DEFUN()'), which contains a pointer to
6547 the C function, a minimum and maximum number of arguments (or possibly
6548 the special constants `MANY' or `UNEVALLED'), a pointer to the symbol
6549 referring to that subr, and a couple of other things.  If the subr
6550 wants its arguments `UNEVALLED', they are passed raw as a list.
6551 Otherwise, an array of evaluated arguments is created and put into the
6552 backtrace structure, and either passed whole (`MANY') or each argument
6553 is passed as a C argument.
6554
6555    If the function is a `Lisp_Compiled_Function',
6556 `funcall_compiled_function()' is called.  If the function is a lambda
6557 list, `funcall_lambda()' is called.  If the function is a macro, [.....
6558 fill in] is done.  If the function is an autoload, `do_autoload()' is
6559 called to load the definition and then eval starts over [explain this
6560 more].
6561
6562    When `Feval()' exits, the evaluation depth is reduced by one, the
6563 debugger is called if appropriate, and the current backtrace structure
6564 is removed from the list.
6565
6566    Both `funcall_compiled_function()' and `funcall_lambda()' need to go
6567 through the list of formal parameters to the function and bind them to
6568 the actual arguments, checking for `&rest' and `&optional' symbols in
6569 the formal parameters and making sure the number of actual arguments is
6570 correct.  `funcall_compiled_function()' can do this a little more
6571 efficiently, since the formal parameter list can be checked for sanity
6572 when the compiled function object is created.
6573
6574    `funcall_lambda()' simply calls `Fprogn' to execute the code in the
6575 lambda list.
6576
6577    `funcall_compiled_function()' calls the real byte-code interpreter
6578 `execute_optimized_program()' on the byte-code instructions, which are
6579 converted into an internal form for faster execution.
6580
6581    When a compiled function is executed for the first time by
6582 `funcall_compiled_function()', or during the dump phase of building
6583 XEmacs, the byte-code instructions are converted from a `Lisp_String'
6584 (which is inefficient to access, especially in the presence of MULE)
6585 into a `Lisp_Opaque' object containing an array of unsigned char, which
6586 can be directly executed by the byte-code interpreter.  At this time
6587 the byte code is also analyzed for validity and transformed into a more
6588 optimized form, so that `execute_optimized_program()' can really fly.
6589
6590    Here are some of the optimizations performed by the internal
6591 byte-code transformer:
6592   1. References to the `constants' array are checked for out-of-range
6593      indices, so that the byte interpreter doesn't have to.
6594
6595   2. References to the `constants' array that will be used as a Lisp
6596      variable are checked for being correct non-constant (i.e. not `t',
6597      `nil', or `keywordp') symbols, so that the byte interpreter
6598      doesn't have to.
6599
6600   3. The maximum number of variable bindings in the byte-code is
6601      pre-computed, so that space on the `specpdl' stack can be
6602      pre-reserved once for the whole function execution.
6603
6604   4. All byte-code jumps are relative to the current program counter
6605      instead of the start of the program, thereby saving a register.
6606
6607   5. One-byte relative jumps are converted from the byte-code form of
6608      unsigned chars offset by 127 to machine-friendly signed chars.
6609
6610    Of course, this transformation of the `instructions' should not be
6611 visible to the user, so `Fcompiled_function_instructions()' needs to
6612 know how to convert the optimized opaque object back into a Lisp string
6613 that is identical to the original string from the `.elc' file.
6614 (Actually, the resulting string may (rarely) contain slightly
6615 different, yet equivalent, byte code.)
6616
6617    `Ffuncall()' implements Lisp `funcall'.  `(funcall fun x1 x2 x3
6618 ...)' is equivalent to `(eval (list fun (quote x1) (quote x2) (quote
6619 x3) ...))'.  `Ffuncall()' contains its own code to do the evaluation,
6620 however, and is very similar to `Feval()'.
6621
6622    From the performance point of view, it is worth knowing that most of
6623 the time in Lisp evaluation is spent executing `Lisp_Subr' and
6624 `Lisp_Compiled_Function' objects via `Ffuncall()' (not `Feval()').
6625
6626    `Fapply()' implements Lisp `apply', which is very similar to
6627 `funcall' except that if the last argument is a list, the result is the
6628 same as if each of the arguments in the list had been passed separately.
6629 `Fapply()' does some business to expand the last argument if it's a
6630 list, then calls `Ffuncall()' to do the work.
6631
6632    `apply1()', `call0()', `call1()', `call2()', and `call3()' call a
6633 function, passing it the argument(s) given (the arguments are given as
6634 separate C arguments rather than being passed as an array).  `apply1()'
6635 uses `Fapply()' while the others use `Ffuncall()' to do the real work.
6636
6637 \1f
6638 File: internals.info,  Node: Dynamic Binding; The specbinding Stack; Unwind-Protects,  Next: Simple Special Forms,  Prev: Evaluation,  Up: Evaluation; Stack Frames; Bindings
6639
6640 Dynamic Binding; The specbinding Stack; Unwind-Protects
6641 =======================================================
6642
6643      struct specbinding
6644      {
6645        Lisp_Object symbol;
6646        Lisp_Object old_value;
6647        Lisp_Object (*func) (Lisp_Object); /* for unwind-protect */
6648      };
6649
6650    `struct specbinding' is used for local-variable bindings and
6651 unwind-protects.  `specpdl' holds an array of `struct specbinding''s,
6652 `specpdl_ptr' points to the beginning of the free bindings in the
6653 array, `specpdl_size' specifies the total number of binding slots in
6654 the array, and `max_specpdl_size' specifies the maximum number of
6655 bindings the array can be expanded to hold.  `grow_specpdl()' increases
6656 the size of the `specpdl' array, multiplying its size by 2 but never
6657 exceeding `max_specpdl_size' (except that if this number is less than
6658 400, it is first set to 400).
6659
6660    `specbind()' binds a symbol to a value and is used for local
6661 variables and `let' forms.  The symbol and its old value (which might
6662 be `Qunbound', indicating no prior value) are recorded in the specpdl
6663 array, and `specpdl_size' is increased by 1.
6664
6665    `record_unwind_protect()' implements an "unwind-protect", which,
6666 when placed around a section of code, ensures that some specified
6667 cleanup routine will be executed even if the code exits abnormally
6668 (e.g. through a `throw' or quit).  `record_unwind_protect()' simply
6669 adds a new specbinding to the `specpdl' array and stores the
6670 appropriate information in it.  The cleanup routine can either be a C
6671 function, which is stored in the `func' field, or a `progn' form, which
6672 is stored in the `old_value' field.
6673
6674    `unbind_to()' removes specbindings from the `specpdl' array until
6675 the specified position is reached.  Each specbinding can be one of
6676 three types:
6677
6678   1. an unwind-protect with a C cleanup function (`func' is not 0, and
6679      `old_value' holds an argument to be passed to the function);
6680
6681   2. an unwind-protect with a Lisp form (`func' is 0, `symbol' is
6682      `nil', and `old_value' holds the form to be executed with
6683      `Fprogn()'); or
6684
6685   3. a local-variable binding (`func' is 0, `symbol' is not `nil', and
6686      `old_value' holds the old value, which is stored as the symbol's
6687      value).
6688
6689 \1f
6690 File: internals.info,  Node: Simple Special Forms,  Next: Catch and Throw,  Prev: Dynamic Binding; The specbinding Stack; Unwind-Protects,  Up: Evaluation; Stack Frames; Bindings
6691
6692 Simple Special Forms
6693 ====================
6694
6695 `or', `and', `if', `cond', `progn', `prog1', `prog2', `setq', `quote',
6696 `function', `let*', `let', `while'
6697
6698    All of these are very simple and work as expected, calling `Feval()'
6699 or `Fprogn()' as necessary and (in the case of `let' and `let*') using
6700 `specbind()' to create bindings and `unbind_to()' to undo the bindings
6701 when finished.
6702
6703    Note that, with the exception of `Fprogn', these functions are
6704 typically called in real life only in interpreted code, since the byte
6705 compiler knows how to convert calls to these functions directly into
6706 byte code.
6707
6708 \1f
6709 File: internals.info,  Node: Catch and Throw,  Prev: Simple Special Forms,  Up: Evaluation; Stack Frames; Bindings
6710
6711 Catch and Throw
6712 ===============
6713
6714      struct catchtag
6715      {
6716        Lisp_Object tag;
6717        Lisp_Object val;
6718        struct catchtag *next;
6719        struct gcpro *gcpro;
6720        jmp_buf jmp;
6721        struct backtrace *backlist;
6722        int lisp_eval_depth;
6723        int pdlcount;
6724      };
6725
6726    `catch' is a Lisp function that places a catch around a body of
6727 code.  A catch is a means of non-local exit from the code.  When a catch
6728 is created, a tag is specified, and executing a `throw' to this tag
6729 will exit from the body of code caught with this tag, and its value will
6730 be the value given in the call to `throw'.  If there is no such call,
6731 the code will be executed normally.
6732
6733    Information pertaining to a catch is held in a `struct catchtag',
6734 which is placed at the head of a linked list pointed to by `catchlist'.
6735 `internal_catch()' is passed a C function to call (`Fprogn()' when
6736 Lisp `catch' is called) and arguments to give it, and places a catch
6737 around the function.  Each `struct catchtag' is held in the stack frame
6738 of the `internal_catch()' instance that created the catch.
6739
6740    `internal_catch()' is fairly straightforward.  It stores into the
6741 `struct catchtag' the tag name and the current values of
6742 `backtrace_list', `lisp_eval_depth', `gcprolist', and the offset into
6743 the `specpdl' array, sets a jump point with `_setjmp()' (storing the
6744 jump point into the `struct catchtag'), and calls the function.
6745 Control will return to `internal_catch()' either when the function
6746 exits normally or through a `_longjmp()' to this jump point.  In the
6747 latter case, `throw' will store the value to be returned into the
6748 `struct catchtag' before jumping.  When it's done, `internal_catch()'
6749 removes the `struct catchtag' from the catchlist and returns the proper
6750 value.
6751
6752    `Fthrow()' goes up through the catchlist until it finds one with a
6753 matching tag.  It then calls `unbind_catch()' to restore everything to
6754 what it was when the appropriate catch was set, stores the return value
6755 in the `struct catchtag', and jumps (with `_longjmp()') to its jump
6756 point.
6757
6758    `unbind_catch()' removes all catches from the catchlist until it
6759 finds the correct one.  Some of the catches might have been placed for
6760 error-trapping, and if so, the appropriate entries on the handlerlist
6761 must be removed (see "errors").  `unbind_catch()' also restores the
6762 values of `gcprolist', `backtrace_list', and `lisp_eval', and calls
6763 `unbind_to()' to undo any specbindings created since the catch.
6764
6765 \1f
6766 File: internals.info,  Node: Symbols and Variables,  Next: Buffers and Textual Representation,  Prev: Evaluation; Stack Frames; Bindings,  Up: Top
6767
6768 Symbols and Variables
6769 *********************
6770
6771 * Menu:
6772
6773 * Introduction to Symbols::
6774 * Obarrays::
6775 * Symbol Values::
6776