XEmacs 21.2-b2
[chise/xemacs-chise.git.1] / man / internals / internals.texi
1 \input texinfo  @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename ../../info/internals.info
4 @settitle XEmacs Internals Manual
5 @c %**end of header
6
7 @ifinfo
8
9 Copyright @copyright{} 1992 - 1996 Ben Wing.
10 Copyright @copyright{} 1996, 1997 Sun Microsystems.
11 Copyright @copyright{} 1994, 1995 Free Software Foundation.
12 Copyright @copyright{} 1994, 1995 Board of Trustees, University of Illinois.
13
14
15 Permission is granted to make and distribute verbatim copies of this
16 manual provided the copyright notice and this permission notice are
17 preserved on all copies.
18
19 @ignore
20 Permission is granted to process this file through TeX and print the
21 results, provided the printed document carries copying permission notice
22 identical to this one except for the removal of this paragraph (this
23 paragraph not being relevant to the printed manual).
24
25 @end ignore
26 Permission is granted to copy and distribute modified versions of this
27 manual under the conditions for verbatim copying, provided that the
28 entire resulting derived work is distributed under the terms of a
29 permission notice identical to this one.
30
31 Permission is granted to copy and distribute translations of this manual
32 into another language, under the above conditions for modified versions,
33 except that this permission notice may be stated in a translation
34 approved by the Foundation.
35
36 Permission is granted to copy and distribute modified versions of this
37 manual under the conditions for verbatim copying, provided also that the
38 section entitled ``GNU General Public License'' is included exactly as
39 in the original, and provided that the entire resulting derived work is
40 distributed under the terms of a permission notice identical to this
41 one.
42
43 Permission is granted to copy and distribute translations of this manual
44 into another language, under the above conditions for modified versions,
45 except that the section entitled ``GNU General Public License'' may be
46 included in a translation approved by the Free Software Foundation
47 instead of in the original English.
48 @end ifinfo
49
50 @c Combine indices.
51 @synindex cp fn
52 @syncodeindex vr fn
53 @syncodeindex ky fn
54 @syncodeindex pg fn
55 @syncodeindex tp fn
56
57 @setchapternewpage odd
58 @finalout
59
60 @titlepage
61 @title XEmacs Internals Manual
62 @subtitle Version 1.1, March 1997
63
64 @author Ben Wing
65 @author Martin Buchholz
66 @page
67 @vskip 0pt plus 1fill
68
69 @noindent
70 Copyright @copyright{} 1992 - 1996 Ben Wing. @*
71 Copyright @copyright{} 1996 Sun Microsystems, Inc. @*
72 Copyright @copyright{} 1994 Free Software Foundation. @*
73 Copyright @copyright{} 1994, 1995 Board of Trustees, University of Illinois.
74
75 @sp 2
76 Version 1.1 @*
77 March, 1997.@*
78
79 Permission is granted to make and distribute verbatim copies of this
80 manual provided the copyright notice and this permission notice are
81 preserved on all copies.
82
83 Permission is granted to copy and distribute modified versions of this
84 manual under the conditions for verbatim copying, provided also that the
85 section entitled ``GNU General Public License'' is included
86 exactly as in the original, and provided that the entire resulting
87 derived work is distributed under the terms of a permission notice
88 identical to this one.
89
90 Permission is granted to copy and distribute translations of this manual
91 into another language, under the above conditions for modified versions,
92 except that the section entitled ``GNU General Public License'' may be
93 included in a translation approved by the Free Software Foundation
94 instead of in the original English.
95 @end titlepage
96 @page
97
98 @node Top, A History of Emacs, (dir), (dir)
99
100 @ifinfo
101 This Info file contains v1.0 of the XEmacs Internals Manual.
102 @end ifinfo
103
104 @menu
105 * A History of Emacs::          Times, dates, important events.
106 * XEmacs From the Outside::     A broad conceptual overview.
107 * The Lisp Language::           An overview.
108 * XEmacs From the Perspective of Building::
109 * XEmacs From the Inside::
110 * The XEmacs Object System (Abstractly Speaking)::
111 * How Lisp Objects Are Represented in C::
112 * Rules When Writing New C Code::
113 * A Summary of the Various XEmacs Modules::
114 * Allocation of Objects in XEmacs Lisp::
115 * Events and the Event Loop::
116 * Evaluation; Stack Frames; Bindings::
117 * Symbols and Variables::
118 * Buffers and Textual Representation::
119 * MULE Character Sets and Encodings::
120 * The Lisp Reader and Compiler::
121 * Lstreams::
122 * Consoles; Devices; Frames; Windows::
123 * The Redisplay Mechanism::
124 * Extents::
125 * Faces and Glyphs::
126 * Specifiers::
127 * Menus::
128 * Subprocesses::
129 * Interface to X Windows::
130 * Index::                   Index including concepts, functions, variables,
131                               and other terms.
132
133       --- The Detailed Node Listing ---
134
135 Here are other nodes that are inferiors of those already listed,
136 mentioned here so you can get to them in one step:
137
138 A History of Emacs
139
140 * Through Version 18::          Unification prevails.
141 * Lucid Emacs::                 One version 19 Emacs.
142 * GNU Emacs 19::                The other version 19 Emacs.
143 * XEmacs::                      The continuation of Lucid Emacs.
144
145 Rules When Writing New C Code
146
147 * General Coding Rules::
148 * Writing Lisp Primitives::
149 * Adding Global Lisp Variables::
150 * Techniques for XEmacs Developers::
151
152 A Summary of the Various XEmacs Modules
153
154 * Low-Level Modules::
155 * Basic Lisp Modules::
156 * Modules for Standard Editing Operations::
157 * Editor-Level Control Flow Modules::
158 * Modules for the Basic Displayable Lisp Objects::
159 * Modules for other Display-Related Lisp Objects::
160 * Modules for the Redisplay Mechanism::
161 * Modules for Interfacing with the File System::
162 * Modules for Other Aspects of the Lisp Interpreter and Object System::
163 * Modules for Interfacing with the Operating System::
164 * Modules for Interfacing with X Windows::
165 * Modules for Internationalization::
166
167 Allocation of Objects in XEmacs Lisp
168
169 * Introduction to Allocation::
170 * Garbage Collection::
171 * GCPROing::
172 * Integers and Characters::
173 * Allocation from Frob Blocks::
174 * lrecords::
175 * Low-level allocation::
176 * Pure Space::
177 * Cons::
178 * Vector::
179 * Bit Vector::
180 * Symbol::
181 * Marker::
182 * String::
183 * Bytecode::
184
185 Events and the Event Loop
186
187 * Introduction to Events::
188 * Main Loop::
189 * Specifics of the Event Gathering Mechanism::
190 * Specifics About the Emacs Event::
191 * The Event Stream Callback Routines::
192 * Other Event Loop Functions::
193 * Converting Events::
194 * Dispatching Events; The Command Builder::
195
196 Evaluation; Stack Frames; Bindings
197
198 * Evaluation::
199 * Dynamic Binding; The specbinding Stack; Unwind-Protects::
200 * Simple Special Forms::
201 * Catch and Throw::
202
203 Symbols and Variables
204
205 * Introduction to Symbols::
206 * Obarrays::
207 * Symbol Values::
208
209 Buffers and Textual Representation
210
211 * Introduction to Buffers::     A buffer holds a block of text such as a file.
212 * The Text in a Buffer::        Representation of the text in a buffer.
213 * Buffer Lists::                Keeping track of all buffers.
214 * Markers and Extents::         Tagging locations within a buffer.
215 * Bufbytes and Emchars::        Representation of individual characters.
216 * The Buffer Object::           The Lisp object corresponding to a buffer.
217
218 MULE Character Sets and Encodings
219
220 * Character Sets::
221 * Encodings::
222 * Internal Mule Encodings::
223
224 Encodings
225
226 * Japanese EUC (Extended Unix Code)::
227 * JIS7::
228
229 Internal Mule Encodings
230
231 * Internal String Encoding::
232 * Internal Character Encoding::
233
234 The Lisp Reader and Compiler
235
236 Lstreams
237
238 Consoles; Devices; Frames; Windows
239
240 * Introduction to Consoles; Devices; Frames; Windows::
241 * Point::
242 * Window Hierarchy::
243
244 The Redisplay Mechanism
245
246 * Critical Redisplay Sections::
247 * Line Start Cache::
248
249 Extents
250
251 * Introduction to Extents::     Extents are ranges over text, with properties.
252 * Extent Ordering::             How extents are ordered internally.
253 * Format of the Extent Info::   The extent information in a buffer or string.
254 * Zero-Length Extents::         A weird special case.
255 * Mathematics of Extent Ordering::      A rigorous foundation.
256 * Extent Fragments::            Cached information useful for redisplay.
257
258 Faces and Glyphs
259
260 Specifiers
261
262 Menus
263
264 Subprocesses
265
266 Interface to X Windows
267
268 @end menu
269
270 @node A History of Emacs, XEmacs From the Outside, Top, Top
271 @chapter A History of Emacs
272 @cindex history of Emacs
273 @cindex Hackers (Steven Levy)
274 @cindex Levy, Steven
275 @cindex ITS (Incompatible Timesharing System)
276 @cindex Stallman, Richard
277 @cindex RMS
278 @cindex MIT
279 @cindex TECO
280 @cindex FSF
281 @cindex Free Software Foundation
282
283   XEmacs is a powerful, customizable text editor and development
284 environment.  It began as Lucid Emacs, which was in turn derived from
285 GNU Emacs, a program written by Richard Stallman of the Free Software
286 Foundation.  GNU Emacs dates back to the 1970's, and was modelled
287 after a package called ``Emacs'', written in 1976, that was a set of
288 macros on top of TECO, an old, old text editor written at MIT on the
289 DEC PDP 10 under one of the earliest time-sharing operating systems,
290 ITS (Incompatible Timesharing System). (ITS dates back well before
291 Unix.) ITS, TECO, and Emacs were products of a group of people at MIT
292 who called themselves ``hackers'', who shared an idealistic belief
293 system about the free exchange of information and were fanatical in
294 their devotion to and time spent with computers. (The hacker
295 subculture dates back to the late 1950's at MIT and is described in
296 detail in Steven Levy's book @cite{Hackers}.  This book also includes
297 a lot of information about Stallman himself and the development of
298 Lisp, a programming language developed at MIT that underlies Emacs.)
299
300 @menu
301 * Through Version 18::          Unification prevails.
302 * Lucid Emacs::                 One version 19 Emacs.
303 * GNU Emacs 19::                The other version 19 Emacs.
304 * GNU Emacs 20::                The other version 20 Emacs.
305 * XEmacs::                      The continuation of Lucid Emacs.
306 @end menu
307
308 @node Through Version 18
309 @section Through Version 18
310 @cindex Gosling, James
311 @cindex Great Usenet Renaming
312
313   Although the history of the early versions of GNU Emacs is unclear,
314 the history is well-known from the middle of 1985.  A time line is:
315
316 @itemize @bullet
317 @item
318 GNU Emacs version 15 (15.34) was released sometime in 1984 or 1985 and
319 shared some code with a version of Emacs written by James Gosling (the
320 same James Gosling who later created the Java language).
321 @item
322 GNU Emacs version 16 (first released version was 16.56) was released on
323 July 15, 1985.  All Gosling code was removed due to potential copyright
324 problems with the code.
325 @item
326 version 16.57: released on September 16, 1985.
327 @item
328 versions 16.58, 16.59: released on September 17, 1985.
329 @item
330 version 16.60: released on September 19, 1985.  These later version 16's
331 incorporated patches from the net, esp. for getting Emacs to work under
332 System V.
333 @item
334 version 17.36 (first official v17 release) released on December 20,
335 1985.  Included a TeX-able user manual.  First official unpatched
336 version that worked on vanilla System V machines.
337 @item
338 version 17.43 (second official v17 release) released on January 25,
339 1986.
340 @item
341 version 17.45 released on January 30, 1986.
342 @item
343 version 17.46 released on February 4, 1986.
344 @item
345 version 17.48 released on February 10, 1986.
346 @item
347 version 17.49 released on February 12, 1986.
348 @item
349 version 17.55 released on March 18, 1986.
350 @item
351 version 17.57 released on March 27, 1986.
352 @item
353 version 17.58 released on April 4, 1986.
354 @item
355 version 17.61 released on April 12, 1986.
356 @item
357 version 17.63 released on May 7, 1986.
358 @item
359 version 17.64 released on May 12, 1986.
360 @item
361 version 18.24 (a beta version) released on October 2, 1986.
362 @item
363 version 18.30 (a beta version) released on November 15, 1986.
364 @item
365 version 18.31 (a beta version) released on November 23, 1986.
366 @item
367 version 18.32 (a beta version) released on December 7, 1986.
368 @item
369 version 18.33 (a beta version) released on December 12, 1986.
370 @item
371 version 18.35 (a beta version) released on January 5, 1987.
372 @item
373 version 18.36 (a beta version) released on January 21, 1987.
374 @item
375 January 27, 1987: The Great Usenet Renaming.  net.emacs is now
376 comp.emacs.
377 @item
378 version 18.37 (a beta version) released on February 12, 1987.
379 @item
380 version 18.38 (a beta version) released on March 3, 1987.
381 @item
382 version 18.39 (a beta version) released on March 14, 1987.
383 @item
384 version 18.40 (a beta version) released on March 18, 1987.
385 @item
386 version 18.41 (the first ``official'' release) released on March 22,
387 1987.
388 @item
389 version 18.45 released on June 2, 1987.
390 @item
391 version 18.46 released on June 9, 1987.
392 @item
393 version 18.47 released on June 18, 1987.
394 @item
395 version 18.48 released on September 3, 1987.
396 @item
397 version 18.49 released on September 18, 1987.
398 @item
399 version 18.50 released on February 13, 1988.
400 @item
401 version 18.51 released on May 7, 1988.
402 @item
403 version 18.52 released on September 1, 1988.
404 @item
405 version 18.53 released on February 24, 1989.
406 @item
407 version 18.54 released on April 26, 1989.
408 @item
409 version 18.55 released on August 23, 1989.  This is the earliest version
410 that is still available by FTP.
411 @item
412 version 18.56 released on January 17, 1991.
413 @item
414 version 18.57 released late January, 1991.
415 @item
416 version 18.58 released ?????.
417 @item
418 version 18.59 released October 31, 1992.
419 @end itemize
420
421 @node Lucid Emacs
422 @section Lucid Emacs
423 @cindex Lucid Emacs
424 @cindex Lucid Inc.
425 @cindex Energize
426 @cindex Epoch
427
428   Lucid Emacs was developed by the (now-defunct) Lucid Inc., a maker of
429 C++ and Lisp development environments.  It began when Lucid decided they
430 wanted to use Emacs as the editor and cornerstone of their C++
431 development environment (called ``Energize'').  They needed many features
432 that were not available in the existing version of GNU Emacs (version
433 18.5something), in particular good and integrated support for GUI
434 elements such as mouse support, multiple fonts, multiple window-system
435 windows, etc.  A branch of GNU Emacs called Epoch, written at the
436 University of Illinois, existed that supplied many of these features;
437 however, Lucid needed more than what existed in Epoch.  At the time, the
438 Free Software Foundation was working on version 19 of Emacs (this was
439 sometime around 1991), which was planned to have similar features, and
440 so Lucid decided to work with the Free Software Foundation.  Their plan
441 was to add features that they needed, and coordinate with the FSF so
442 that the features would get included back into Emacs version 19.
443
444   Delays in the release of version 19 occurred, however (resulting in it
445 finally being released more than a year after what was initially
446 planned), and Lucid encountered unexpected technical resistance in
447 getting their changes merged back into version 19, so they decided to
448 release their own version of Emacs, which became Lucid Emacs 19.0.
449
450 @cindex Zawinski, Jamie
451 @cindex Sexton, Harlan
452 @cindex Benson, Eric
453 @cindex Devin, Matthieu
454   The initial authors of Lucid Emacs were Matthieu Devin, Harlan Sexton,
455 and Eric Benson, and the work was later taken over by Jamie Zawinski,
456 who became ``Mr. Lucid Emacs'' for many releases.
457
458   A time line for Lucid Emacs/XEmacs is
459
460 @itemize @bullet
461 @item
462 version 19.0 shipped with Energize 1.0, April 1992.
463 @item
464 version 19.1 released June 4, 1992.
465 @item
466 version 19.2 released June 19, 1992.
467 @item
468 version 19.3 released September 9, 1992.
469 @item
470 version 19.4 released January 21, 1993.
471 @item
472 version 19.5 was a repackaging of 19.4 with a few bug fixes and
473 shipped with Energize 2.0.  Never released to the net.
474 @item
475 version 19.6 released April 9, 1993.
476 @item
477 version 19.7 was a repackaging of 19.6 with a few bug fixes and
478 shipped with Energize 2.1.  Never released to the net.
479 @item
480 version 19.8 released September 6, 1993.
481 @item
482 version 19.9 released January 12, 1994.
483 @item
484 version 19.10 released May 27, 1994.
485 @item
486 version 19.11 (first XEmacs) released September 13, 1994.
487 @item
488 version 19.12 released June 23, 1995.
489 @item
490 version 19.13 released September 1, 1995.
491 @item
492 version 19.14 released June 23, 1996.
493 @item
494 version 20.0 released February 9, 1997.
495 @item
496 version 19.15 released March 28, 1997.
497 @item
498 version 20.1 (not released to the net) April 15, 1997.
499 @item
500 version 20.2 released May 16, 1997.
501 @item
502 version 19.16 released October 31, 1997.
503 @item
504 version 20.3 (the first stable version of XEmacs 20.x) released November 30,
505 1997.
506 version 20.4 released February 28, 1998.
507 @end itemize
508
509 @node GNU Emacs 19
510 @section GNU Emacs 19
511 @cindex GNU Emacs 19
512 @cindex FSF Emacs
513
514   About a year after the initial release of Lucid Emacs, the FSF
515 released a beta of their version of Emacs 19 (referred to here as ``GNU
516 Emacs'').  By this time, the current version of Lucid Emacs was
517 19.6. (Strangely, the first released beta from the FSF was GNU Emacs
518 19.7.) A time line for GNU Emacs version 19 is
519
520 @itemize @bullet
521 @item
522 version 19.8 (beta) released May 27, 1993.
523 @item
524 version 19.9 (beta) released May 27, 1993.
525 @item
526 version 19.10 (beta) released May 30, 1993.
527 @item
528 version 19.11 (beta) released June 1, 1993.
529 @item
530 version 19.12 (beta) released June 2, 1993.
531 @item
532 version 19.13 (beta) released June 8, 1993.
533 @item
534 version 19.14 (beta) released June 17, 1993.
535 @item
536 version 19.15 (beta) released June 19, 1993.
537 @item
538 version 19.16 (beta) released July 6, 1993.
539 @item
540 version 19.17 (beta) released late July, 1993.
541 @item
542 version 19.18 (beta) released August 9, 1993.
543 @item
544 version 19.19 (beta) released August 15, 1993.
545 @item
546 version 19.20 (beta) released November 17, 1993.
547 @item
548 version 19.21 (beta) released November 17, 1993.
549 @item
550 version 19.22 (beta) released November 28, 1993.
551 @item
552 version 19.23 (beta) released May 17, 1994.
553 @item
554 version 19.24 (beta) released May 16, 1994.
555 @item
556 version 19.25 (beta) released June 3, 1994.
557 @item
558 version 19.26 (beta) released September 11, 1994.
559 @item
560 version 19.27 (beta) released September 14, 1994.
561 @item
562 version 19.28 (first ``official'' release) released November 1, 1994.
563 @item
564 version 19.29 released June 21, 1995.
565 @item
566 version 19.30 released November 24, 1995.
567 @item
568 version 19.31 released May 25, 1996.
569 @item
570 version 19.32 released July 31, 1996.
571 @item
572 version 19.33 released August 11, 1996.
573 @item
574 version 19.34 released August 21, 1996.
575 @item
576 version 19.34b released September 6, 1996.
577 @end itemize
578
579 @cindex Mlynarik, Richard
580   In some ways, GNU Emacs 19 was better than Lucid Emacs; in some ways,
581 worse.  Lucid soon began incorporating features from GNU Emacs 19 into
582 Lucid Emacs; the work was mostly done by Richard Mlynarik, who had been
583 working on and using GNU Emacs for a long time (back as far as version
584 16 or 17).
585
586 @node GNU Emacs 20
587 @section GNU Emacs 20
588 @cindex GNU Emacs 20
589 @cindex FSF Emacs
590
591 On February 2, 1997 work began on GNU Emacs to integrate Mule.  The first
592 release was made in September of that year.
593
594 A timeline for Emacs 20 is
595
596 @itemize @bullet
597 @item
598 version 20.1 released September 17, 1997.
599 @item
600 version 20.2 released September 20, 1997.
601 @item
602 version 20.3 released August 19, 1998.
603 @end itemize
604
605 @node XEmacs
606 @section XEmacs
607 @cindex XEmacs
608
609 @cindex Sun Microsystems
610 @cindex University of Illinois
611 @cindex Illinois, University of
612 @cindex SPARCWorks
613 @cindex Andreessen, Marc
614 @cindex Baur, Steve
615 @cindex Buchholz, Martin
616 @cindex Kaplan, Simon
617 @cindex Wing, Ben
618 @cindex Thompson, Chuck
619 @cindex Win-Emacs
620 @cindex Epoch
621 @cindex Amdahl Corporation
622   Around the time that Lucid was developing Energize, Sun Microsystems
623 was developing their own development environment (called ``SPARCWorks'')
624 and also decided to use Emacs.  They joined forces with the Epoch team
625 at the University of Illinois and later with Lucid.  The maintainer of
626 the last-released version of Epoch was Marc Andreessen, but he dropped
627 out and the Epoch project, headed by Simon Kaplan, lured Chuck Thompson
628 away from a system administration job to become the primary Lucid Emacs
629 author for Epoch and Sun.  Chuck's area of specialty became the
630 redisplay engine (he replaced the old Lucid Emacs redisplay engine with
631 a ported version from Epoch and then later rewrote it from scratch).
632 Sun also hired Ben Wing (the author of Win-Emacs, a port of Lucid Emacs
633 to Microsoft Windows 3.1) in 1993, for what was initially a one-month
634 contract to fix some event problems but later became a many-year
635 involvement, punctuated by a six-month contract with Amdahl Corporation.
636
637 @cindex rename to XEmacs
638   In 1994, Sun and Lucid agreed to rename Lucid Emacs to XEmacs (a name
639 not favorable to either company); the first release called XEmacs was
640 version 19.11.  In June 1994, Lucid folded and Jamie quit to work for
641 the newly formed Mosaic Communications Corp., later Netscape
642 Communications Corp. (co-founded by the same Marc Andreessen, who had
643 quit his Epoch job to work on a graphical browser for the World Wide
644 Web).  Chuck then become the primary maintainer of XEmacs, and put out
645 versions 19.11 through 19.14 in conjunction with Ben.  For 19.12 and
646 19.13, Chuck added the new redisplay and many other display improvements
647 and Ben added MULE support (support for Asian and other languages) and
648 redesigned most of the internal Lisp subsystems to better support the
649 MULE work and the various other features being added to XEmacs.  After
650 19.14 Chuck retired as primary maintainer and Steve Baur stepped in.
651
652 @cindex MULE merged XEmacs appears
653   Soon after 19.13 was released, work began in earnest on the MULE
654 internationalization code and the source tree was divided into two
655 development paths.  The MULE version was initially called 19.20, but was
656 soon renamed to 20.0.  In 1996 Martin Buchholz of Sun Microsystems took
657 over the care and feeding of it and worked on it in parallel with the
658 19.14 development that was occurring at the same time.  After much work
659 by Martin, it was decided to release 20.0 ahead of 19.15 in February
660 1997.  The source tree remained divided until 20.2 when the version 19
661 source was finally retired at version 19.16.
662
663 @cindex Baur, Steve
664 @cindex Buchholz, Martin
665 @cindex Jones, Kyle
666 @cindex Niksic, Hrvoje
667 @cindex XEmacs goes it alone
668   In 1997, Sun finally dropped all pretense of support for XEmacs and
669 Martin Buchholz left the company in November.  Since then, and mostly
670 for the previous year, because Steve Baur was never paid to work on
671 XEmacs, XEmacs has existed solely on the contributions of volunteers
672 from the Free Software Community.  Starting from 1997, Hrvoje Niksic and
673 Kyle Jones have figured prominently in XEmacs development.
674
675 @cindex merging attempts
676   Many attempts have been made to merge XEmacs and GNU Emacs, but they
677 have consistently failed.
678
679   A more detailed history is contained in the XEmacs About page.
680
681 @node XEmacs From the Outside, The Lisp Language, A History of Emacs, Top
682 @chapter XEmacs From the Outside
683 @cindex read-eval-print
684
685   XEmacs appears to the outside world as an editor, but it is really a
686 Lisp environment.  At its heart is a Lisp interpreter; it also
687 ``happens'' to contain many specialized object types (e.g. buffers,
688 windows, frames, events) that are useful for implementing an editor.
689 Some of these objects (in particular windows and frames) have
690 displayable representations, and XEmacs provides a function
691 @code{redisplay()} that ensures that the display of all such objects
692 matches their internal state.  Most of the time, a standard Lisp
693 environment is in a @dfn{read-eval-print} loop -- i.e. ``read some Lisp
694 code, execute it, and print the results''.  XEmacs has a similar loop:
695
696 @itemize @bullet
697 @item
698 read an event
699 @item
700 dispatch the event (i.e. ``do it'')
701 @item
702 redisplay
703 @end itemize
704
705   Reading an event is done using the Lisp function @code{next-event},
706 which waits for something to happen (typically, the user presses a key
707 or moves the mouse) and returns an event object describing this.
708 Dispatching an event is done using the Lisp function
709 @code{dispatch-event}, which looks up the event in a keymap object (a
710 particular kind of object that associates an event with a Lisp function)
711 and calls that function.  The function ``does'' what the user has
712 requested by changing the state of particular frame objects, buffer
713 objects, etc.  Finally, @code{redisplay()} is called, which updates the
714 display to reflect those changes just made.  Thus is an ``editor'' born.
715
716 @cindex bridge, playing
717 @cindex taxes, doing
718 @cindex pi, calculating
719   Note that you do not have to use XEmacs as an editor; you could just
720 as well make it do your taxes, compute pi, play bridge, etc.  You'd just
721 have to write functions to do those operations in Lisp.
722
723 @node The Lisp Language, XEmacs From the Perspective of Building, XEmacs From the Outside, Top
724 @chapter The Lisp Language
725 @cindex Lisp vs. C
726 @cindex C vs. Lisp
727 @cindex Lisp vs. Java
728 @cindex Java vs. Lisp
729 @cindex dynamic scoping
730 @cindex scoping, dynamic
731 @cindex dynamic types
732 @cindex types, dynamic
733 @cindex Java
734 @cindex Common Lisp
735 @cindex Gosling, James
736
737   Lisp is a general-purpose language that is higher-level than C and in
738 many ways more powerful than C.  Powerful dialects of Lisp such as
739 Common Lisp are probably much better languages for writing very large
740 applications than is C. (Unfortunately, for many non-technical
741 reasons C and its successor C++ have become the dominant languages for
742 application development.  These languages are both inadequate for
743 extremely large applications, which is evidenced by the fact that newer,
744 larger programs are becoming ever harder to write and are requiring ever
745 more programmers despite great increases in C development environments;
746 and by the fact that, although hardware speeds and reliability have been
747 growing at an exponential rate, most software is still generally
748 considered to be slow and buggy.)
749
750   The new Java language holds promise as a better general-purpose
751 development language than C.  Java has many features in common with
752 Lisp that are not shared by C (this is not a coincidence, since
753 Java was designed by James Gosling, a former Lisp hacker).  This
754 will be discussed more later.
755
756 For those used to C, here is a summary of the basic differences between
757 C and Lisp:
758
759 @enumerate
760 @item
761 Lisp has an extremely regular syntax.  Every function, expression,
762 and control statement is written in the form
763
764 @example
765    (@var{func} @var{arg1} @var{arg2} ...)
766 @end example
767
768 This is as opposed to C, which writes functions as
769
770 @example
771    func(@var{arg1}, @var{arg2}, ...)
772 @end example
773
774 but writes expressions involving operators as (e.g.)
775
776 @example
777    @var{arg1} + @var{arg2}
778 @end example
779
780 and writes control statements as (e.g.)
781
782 @example
783    while (@var{expr}) @{ @var{statement1}; @var{statement2}; ... @}
784 @end example
785
786 Lisp equivalents of the latter two would be
787
788 @example
789    (+ @var{arg1} @var{arg2} ...)
790 @end example
791
792 and
793
794 @example
795    (while @var{expr} @var{statement1} @var{statement2} ...)
796 @end example
797
798 @item
799 Lisp is a safe language.  Assuming there are no bugs in the Lisp
800 interpreter/compiler, it is impossible to write a program that ``core
801 dumps'' or otherwise causes the machine to execute an illegal
802 instruction.  This is very different from C, where perhaps the most
803 common outcome of a bug is exactly such a crash.  A corollary of this is that
804 the C operation of casting a pointer is impossible (and unnecessary) in
805 Lisp, and that it is impossible to access memory outside the bounds of
806 an array.
807
808 @item
809 Programs and data are written in the same form.  The
810 parenthesis-enclosing form described above for statements is the same
811 form used for the most common data type in Lisp, the list.  Thus, it is
812 possible to represent any Lisp program using Lisp data types, and for
813 one program to construct Lisp statements and then dynamically
814 @dfn{evaluate} them, or cause them to execute.
815
816 @item
817 All objects are @dfn{dynamically typed}.  This means that part of every
818 object is an indication of what type it is.  A Lisp program can
819 manipulate an object without knowing what type it is, and can query an
820 object to determine its type.  This means that, correspondingly,
821 variables and function parameters can hold objects of any type and are
822 not normally declared as being of any particular type.  This is opposed
823 to the @dfn{static typing} of C, where variables can hold exactly one
824 type of object and must be declared as such, and objects do not contain
825 an indication of their type because it's implicit in the variables they
826 are stored in.  It is possible in C to have a variable hold different
827 types of objects (e.g. through the use of @code{void *} pointers or
828 variable-argument functions), but the type information must then be
829 passed explicitly in some other fashion, leading to additional program
830 complexity.
831
832 @item
833 Allocated memory is automatically reclaimed when it is no longer in use.
834 This operation is called @dfn{garbage collection} and involves looking
835 through all variables to see what memory is being pointed to, and
836 reclaiming any memory that is not pointed to and is thus
837 ``inaccessible'' and out of use.  This is as opposed to C, in which
838 allocated memory must be explicitly reclaimed using @code{free()}.  If
839 you simply drop all pointers to memory without freeing it, it becomes
840 ``leaked'' memory that still takes up space.  Over a long period of
841 time, this can cause your program to grow and grow until it runs out of
842 memory.
843
844 @item
845 Lisp has built-in facilities for handling errors and exceptions.  In C,
846 when an error occurs, usually either the program exits entirely or the
847 routine in which the error occurs returns a value indicating this.  If
848 an error occurs in a deeply-nested routine, then every routine currently
849 called must unwind itself normally and return an error value back up to
850 the next routine.  This means that every routine must explicitly check
851 for an error in all the routines it calls; if it does not do so,
852 unexpected and often random behavior results.  This is an extremely
853 common source of bugs in C programs.  An alternative would be to do a
854 non-local exit using @code{longjmp()}, but that is often very dangerous
855 because the routines that were exited past had no opportunity to clean
856 up after themselves and may leave things in an inconsistent state,
857 causing a crash shortly afterwards.
858
859 Lisp provides mechanisms to make such non-local exits safe.  When an
860 error occurs, a routine simply signals that an error of a particular
861 class has occurred, and a non-local exit takes place.  Any routine can
862 trap errors occurring in routines it calls by registering an error
863 handler for some or all classes of errors. (If no handler is registered,
864 a default handler, generally installed by the top-level event loop, is
865 executed; this prints out the error and continues.) Routines can also
866 specify cleanup code (called an @dfn{unwind-protect}) that will be
867 called when control exits from a block of code, no matter how that exit
868 occurs -- i.e. even if a function deeply nested below it causes a
869 non-local exit back to the top level.
870
871 Note that this facility has appeared in some recent vintages of C, in
872 particular Visual C++ and other PC compilers written for the Microsoft
873 Win32 API.
874
875 @item
876 In Emacs Lisp, local variables are @dfn{dynamically scoped}.  This means
877 that if you declare a local variable in a particular function, and then
878 call another function, that subfunction can ``see'' the local variable
879 you declared.  This is actually considered a bug in Emacs Lisp and in
880 all other early dialects of Lisp, and was corrected in Common Lisp. (In
881 Common Lisp, you can still declare dynamically scoped variables if you
882 want to -- they are sometimes useful -- but variables by default are
883 @dfn{lexically scoped} as in C.)
884 @end enumerate
885
886 For those familiar with Lisp, Emacs Lisp is modelled after MacLisp, an
887 early dialect of Lisp developed at MIT (no relation to the Macintosh
888 computer).  There is a Common Lisp compatibility package available for
889 Emacs that provides many of the features of Common Lisp.
890
891 The Java language is derived in many ways from C, and shares a similar
892 syntax, but has the following features in common with Lisp (and different
893 from C):
894
895 @enumerate
896 @item
897 Java is a safe language, like Lisp.
898 @item
899 Java provides garbage collection, like Lisp.
900 @item
901 Java has built-in facilities for handling errors and exceptions, like
902 Lisp.
903 @item
904 Java has a type system that combines the best advantages of both static
905 and dynamic typing.  Objects (except very simple types) are explicitly
906 marked with their type, as in dynamic typing; but there is a hierarchy
907 of types and functions are declared to accept only certain types, thus
908 providing the increased compile-time error-checking of static typing.
909 @end enumerate
910
911 @node XEmacs From the Perspective of Building, XEmacs From the Inside, The Lisp Language, Top
912 @chapter XEmacs From the Perspective of Building
913
914   The heart of XEmacs is the Lisp environment, which is written in C.
915 This is contained in the @file{src/} subdirectory.  Underneath
916 @file{src/} are two subdirectories of header files: @file{s/} (header
917 files for particular operating systems) and @file{m/} (header files for
918 particular machine types).  In practice the distinction between the two
919 types of header files is blurred.  These header files define or undefine
920 certain preprocessor constants and macros to indicate particular
921 characteristics of the associated machine or operating system.  As part
922 of the configure process, one @file{s/} file and one @file{m/} file is
923 identified for the particular environment in which XEmacs is being
924 built.
925
926   XEmacs also contains a great deal of Lisp code.  This implements the
927 operations that make XEmacs useful as an editor as well as just a
928 Lisp environment, and also contains many add-on packages that allow
929 XEmacs to browse directories, act as a mail and Usenet news reader,
930 compile Lisp code, etc.  There is actually more Lisp code than
931 C code associated with XEmacs, but much of the Lisp code is
932 peripheral to the actual operation of the editor.  The Lisp code
933 all lies in subdirectories underneath the @file{lisp/} directory.
934
935   The @file{lwlib/} directory contains C code that implements a
936 generalized interface onto different X widget toolkits and also
937 implements some widgets of its own that behave like Motif widgets but
938 are faster, free, and in some cases more powerful.  The code in this
939 directory compiles into a library and is mostly independent from XEmacs.
940
941   The @file{etc/} directory contains various data files associated with
942 XEmacs.  Some of them are actually read by XEmacs at startup; others
943 merely contain useful information of various sorts.
944
945   The @file{lib-src/} directory contains C code for various auxiliary
946 programs that are used in connection with XEmacs.  Some of them are used
947 during the build process; others are used to perform certain functions
948 that cannot conveniently be placed in the XEmacs executable (e.g. the
949 @file{movemail} program for fetching mail out of @file{/var/spool/mail},
950 which must be setgid to @file{mail} on many systems; and the
951 @file{gnuclient} program, which allows an external script to communicate
952 with a running XEmacs process).
953
954   The @file{man/} directory contains the sources for the XEmacs
955 documentation.  It is mostly in a form called Texinfo, which can be
956 converted into either a printed document (by passing it through @TeX{})
957 or into on-line documentation called @dfn{info files}.
958
959   The @file{info/} directory contains the results of formatting the
960 XEmacs documentation as @dfn{info files}, for on-line use.  These files
961 are used when you enter the Info system using @kbd{C-h i} or through the
962 Help menu.
963
964   The @file{dynodump/} directory contains auxiliary code used to build
965 XEmacs on Solaris platforms.
966
967   The other directories contain various miscellaneous code and
968 information that is not normally used or needed.
969
970   The first step of building involves running the @file{configure}
971 program and passing it various parameters to specify any optional
972 features you want and compiler arguments and such, as described in the
973 @file{INSTALL} file.  This determines what the build environment is,
974 chooses the appropriate @file{s/} and @file{m/} file, and runs a series
975 of tests to determine many details about your environment, such as which
976 library functions are available and exactly how they work. (The
977 @file{s/} and @file{m/} files only contain information that cannot be
978 conveniently detected in this fashion.) The reason for running these
979 tests is that it allows XEmacs to be compiled on a much wider variety of
980 platforms than those that the XEmacs developers happen to be familiar
981 with, including various sorts of hybrid platforms.  This is especially
982 important now that many operating systems give you a great deal of
983 control over exactly what features you want installed, and allow for
984 easy upgrading of parts of a system without upgrading the rest.  It
985 would be impossible to pre-determine and pre-specify the information for
986 all possible configurations.
987
988   When configure is done running, it generates @file{Makefile}s and the
989 file @file{src/config.h} (which describes the features of your system)
990 from template files.  You then run @file{make}, which compiles the
991 auxiliary code and programs in @file{lib-src/} and @file{lwlib/} and the
992 main XEmacs executable in @file{src/}.  The result of compiling and
993 linking is an executable called @file{temacs}, which is @emph{not} the
994 final XEmacs executable.  @file{temacs} by itself is not intended to
995 function as an editor or even display any windows on the screen, and if
996 you simply run it, it will exit immediately.  The @file{Makefile} runs
997 @file{temacs} with certain options that cause it to initialize itself,
998 read in a number of basic Lisp files, and then dump itself out into a
999 new executable called @file{xemacs}.  This new executable has been
1000 pre-initialized and contains pre-digested Lisp code that is necessary
1001 for the editor to function (this includes most basic Lisp functions,
1002 e.g. @code{not}, that can be defined in terms of other Lisp primitives;
1003 some initialization code that is called when certain objects, such as
1004 frames, are created; and all of the standard keybindings and code for
1005 the actions they result in).  This executable, @file{xemacs}, is the
1006 executable that you run to use the XEmacs editor.
1007
1008 Although @file{temacs} is not intended to be run as an editor, it can,
1009 by using the incantation @code{temacs -batch -l loadup.el run-temacs}.
1010 This is useful when the dumping procedure described above is broken, or
1011 when using certain program debugging tools such as Purify.  These tools
1012 get mighty confused by the tricks played by the XEmacs build process,
1013 such as allocation memory in one process, and freeing it in the next.
1014
1015 @node XEmacs From the Inside, The XEmacs Object System (Abstractly Speaking), XEmacs From the Perspective of Building, Top
1016 @chapter XEmacs From the Inside
1017
1018   Internally, XEmacs is quite complex, and can be very confusing.  To
1019 simplify things, it can be useful to think of XEmacs as containing an
1020 event loop that ``drives'' everything, and a number of other subsystems,
1021 such as a Lisp engine and a redisplay mechanism.  Each of these other
1022 subsystems exists simultaneously in XEmacs, and each has a certain
1023 state.  The flow of control continually passes in and out of these
1024 different subsystems in the course of normal operation of the editor.
1025
1026   It is important to keep in mind that, most of the time, the editor is
1027 ``driven'' by the event loop.  Except during initialization and batch
1028 mode, all subsystems are entered directly or indirectly through the
1029 event loop, and ultimately, control exits out of all subsystems back up
1030 to the event loop.  This cycle of entering a subsystem, exiting back out
1031 to the event loop, and starting another iteration of the event loop
1032 occurs once each keystroke, mouse motion, etc.
1033
1034   If you're trying to understand a particular subsystem (other than the
1035 event loop), think of it as a ``daemon'' process or ``servant'' that is
1036 responsible for one particular aspect of a larger system, and
1037 periodically receives commands or environment changes that cause it to
1038 do something.  Ultimately, these commands and environment changes are
1039 always triggered by the event loop.  For example:
1040
1041 @itemize @bullet
1042 @item
1043 The window and frame mechanism is responsible for keeping track of what
1044 windows and frames exist, what buffers are in them, etc.  It is
1045 periodically given commands (usually from the user) to make a change to
1046 the current window/frame state: i.e. create a new frame, delete a
1047 window, etc.
1048
1049 @item
1050 The buffer mechanism is responsible for keeping track of what buffers
1051 exist and what text is in them.  It is periodically given commands
1052 (usually from the user) to insert or delete text, create a buffer, etc.
1053 When it receives a text-change command, it notifies the redisplay
1054 mechanism.
1055
1056 @item
1057 The redisplay mechanism is responsible for making sure that windows and
1058 frames are displayed correctly.  It is periodically told (by the event
1059 loop) to actually ``do its job'', i.e. snoop around and see what the
1060 current state of the environment (mostly of the currently-existing
1061 windows, frames, and buffers) is, and make sure that that state matches
1062 what's actually displayed.  It keeps lots and lots of information around
1063 (such as what is actually being displayed currently, and what the
1064 environment was last time it checked) so that it can minimize the work
1065 it has to do.  It is also helped along in that whenever a relevant
1066 change to the environment occurs, the redisplay mechanism is told about
1067 this, so it has a pretty good idea of where it has to look to find
1068 possible changes and doesn't have to look everywhere.
1069
1070 @item
1071 The Lisp engine is responsible for executing the Lisp code in which most
1072 user commands are written.  It is entered through a call to @code{eval}
1073 or @code{funcall}, which occurs as a result of dispatching an event from
1074 the event loop.  The functions it calls issue commands to the buffer
1075 mechanism, the window/frame subsystem, etc.
1076
1077 @item
1078 The Lisp allocation subsystem is responsible for keeping track of Lisp
1079 objects.  It is given commands from the Lisp engine to allocate objects,
1080 garbage collect, etc.
1081 @end itemize
1082
1083 etc.
1084
1085   The important idea here is that there are a number of independent
1086 subsystems each with its own responsibility and persistent state, just
1087 like different employees in a company, and each subsystem is
1088 periodically given commands from other subsystems.  Commands can flow
1089 from any one subsystem to any other, but there is usually some sort of
1090 hierarchy, with all commands originating from the event subsystem.
1091
1092   XEmacs is entered in @code{main()}, which is in @file{emacs.c}.  When
1093 this is called the first time (in a properly-invoked @file{temacs}), it
1094 does the following:
1095
1096 @enumerate
1097 @item
1098 It does some very basic environment initializations, such as determining
1099 where it and its directories (e.g. @file{lisp/} and @file{etc/}) reside
1100 and setting up signal handlers.
1101 @item
1102 It initializes the entire Lisp interpreter.
1103 @item
1104 It sets the initial values of many built-in variables (including many
1105 variables that are visible to Lisp programs), such as the global keymap
1106 object and the built-in faces (a face is an object that describes the
1107 display characteristics of text).  This involves creating Lisp objects
1108 and thus is dependent on step (2).
1109 @item
1110 It performs various other initializations that are relevant to the
1111 particular environment it is running in, such as retrieving environment
1112 variables, determining the current date and the user who is running the
1113 program, examining its standard input, creating any necessary file
1114 descriptors, etc.
1115 @item
1116 At this point, the C initialization is complete.  A Lisp program that
1117 was specified on the command line (usually @file{loadup.el}) is called
1118 (temacs is normally invoked as @code{temacs -batch -l loadup.el dump}).
1119 @file{loadup.el} loads all of the other Lisp files that are needed for
1120 the operation of the editor, calls the @code{dump-emacs} function to
1121 write out @file{xemacs}, and then kills the temacs process.
1122 @end enumerate
1123
1124   When @file{xemacs} is then run, it only redoes steps (1) and (4)
1125 above; all variables already contain the values they were set to when
1126 the executable was dumped, and all memory that was allocated with
1127 @code{malloc()} is still around. (XEmacs knows whether it is being run
1128 as @file{xemacs} or @file{temacs} because it sets the global variable
1129 @code{initialized} to 1 after step (4) above.) At this point,
1130 @file{xemacs} calls a Lisp function to do any further initialization,
1131 which includes parsing the command-line (the C code can only do limited
1132 command-line parsing, which includes looking for the @samp{-batch} and
1133 @samp{-l} flags and a few other flags that it needs to know about before
1134 initialization is complete), creating the first frame (or @dfn{window}
1135 in standard window-system parlance), running the user's init file
1136 (usually the file @file{.emacs} in the user's home directory), etc.  The
1137 function to do this is usually called @code{normal-top-level};
1138 @file{loadup.el} tells the C code about this function by setting its
1139 name as the value of the Lisp variable @code{top-level}.
1140
1141   When the Lisp initialization code is done, the C code enters the event
1142 loop, and stays there for the duration of the XEmacs process.  The code
1143 for the event loop is contained in @file{keyboard.c}, and is called
1144 @code{Fcommand_loop_1()}.  Note that this event loop could very well be
1145 written in Lisp, and in fact a Lisp version exists; but apparently,
1146 doing this makes XEmacs run noticeably slower.
1147
1148   Notice how much of the initialization is done in Lisp, not in C.
1149 In general, XEmacs tries to move as much code as is possible
1150 into Lisp.  Code that remains in C is code that implements the
1151 Lisp interpreter itself, or code that needs to be very fast, or
1152 code that needs to do system calls or other such stuff that
1153 needs to be done in C, or code that needs to have access to
1154 ``forbidden'' structures. (One conscious aspect of the design of
1155 Lisp under XEmacs is a clean separation between the external
1156 interface to a Lisp object's functionality and its internal
1157 implementation.  Part of this design is that Lisp programs
1158 are forbidden from accessing the contents of the object other
1159 than through using a standard API.  In this respect, XEmacs Lisp
1160 is similar to modern Lisp dialects but differs from GNU Emacs,
1161 which tends to expose the implementation and allow Lisp
1162 programs to look at it directly.  The major advantage of
1163 hiding the implementation is that it allows the implementation
1164 to be redesigned without affecting any Lisp programs, including
1165 those that might want to be ``clever'' by looking directly at
1166 the object's contents and possibly manipulating them.)
1167
1168   Moving code into Lisp makes the code easier to debug and maintain and
1169 makes it much easier for people who are not XEmacs developers to
1170 customize XEmacs, because they can make a change with much less chance
1171 of obscure and unwanted interactions occurring than if they were to
1172 change the C code.
1173
1174 @node The XEmacs Object System (Abstractly Speaking), How Lisp Objects Are Represented in C, XEmacs From the Inside, Top
1175 @chapter The XEmacs Object System (Abstractly Speaking)
1176
1177   At the heart of the Lisp interpreter is its management of objects.
1178 XEmacs Lisp contains many built-in objects, some of which are
1179 simple and others of which can be very complex; and some of which
1180 are very common, and others of which are rarely used or are only
1181 used internally. (Since the Lisp allocation system, with its
1182 automatic reclamation of unused storage, is so much more convenient
1183 than @code{malloc()} and @code{free()}, the C code makes extensive use of it
1184 in its internal operations.)
1185
1186   The basic Lisp objects are
1187
1188 @table @code
1189 @item integer
1190 28 bits of precision, or 60 bits on 64-bit machines; the reason for this
1191 is described below when the internal Lisp object representation is
1192 described.
1193 @item float
1194 Same precision as a double in C.
1195 @item cons
1196 A simple container for two Lisp objects, used to implement lists and
1197 most other data structures in Lisp.
1198 @item char
1199 An object representing a single character of text; chars behave like
1200 integers in many ways but are logically considered text rather than
1201 numbers and have a different read syntax. (the read syntax for a char
1202 contains the char itself or some textual encoding of it -- for example,
1203 a Japanese Kanji character might be encoded as @samp{^[$(B#&^[(B} using the
1204 ISO-2022 encoding standard -- rather than the numerical representation
1205 of the char; this way, if the mapping between chars and integers
1206 changes, which is quite possible for Kanji characters and other extended
1207 characters, the same character will still be created.  Note that some
1208 primitives confuse chars and integers.  The worst culprit is @code{eq},
1209 which makes a special exception and considers a char to be @code{eq} to
1210 its integer equivalent, even though in no other case are objects of two
1211 different types @code{eq}.  The reason for this monstrosity is
1212 compatibility with existing code; the separation of char from integer
1213 came fairly recently.)
1214 @item symbol
1215 An object that contains Lisp objects and is referred to by name;
1216 symbols are used to implement variables and named functions
1217 and to provide the equivalent of preprocessor constants in C.
1218 @item vector
1219 A one-dimensional array of Lisp objects providing constant-time access
1220 to any of the objects; access to an arbitrary object in a vector is
1221 faster than for lists, but the operations that can be done on a vector
1222 are more limited.
1223 @item string
1224 Self-explanatory; behaves much like a vector of chars
1225 but has a different read syntax and is stored and manipulated
1226 more compactly and efficiently.
1227 @item bit-vector
1228 A vector of bits; similar to a string in spirit.
1229 @item compiled-function
1230 An object describing compiled Lisp code, known as @dfn{byte code}.
1231 @item subr
1232 An object describing a Lisp primitive.
1233 @end table
1234
1235 @cindex closure
1236   Note that there is no basic ``function'' type, as in more powerful
1237 versions of Lisp (where it's called a @dfn{closure}).  XEmacs Lisp does
1238 not provide the closure semantics implemented by Common Lisp and Scheme.
1239 The guts of a function in XEmacs Lisp are represented in one of four
1240 ways: a symbol specifying another function (when one function is an
1241 alias for another), a list containing the function's source code, a
1242 bytecode object, or a subr object. (In other words, given a symbol
1243 specifying the name of a function, calling @code{symbol-function} to
1244 retrieve the contents of the symbol's function cell will return one of
1245 these types of objects.)
1246
1247   XEmacs Lisp also contains numerous specialized objects used to
1248 implement the editor:
1249
1250 @table @code
1251 @item buffer
1252 Stores text like a string, but is optimized for insertion and deletion
1253 and has certain other properties that can be set.
1254 @item frame
1255 An object with various properties whose displayable representation is a
1256 @dfn{window} in window-system parlance.
1257 @item window
1258 A section of a frame that displays the contents of a buffer;
1259 often called a @dfn{pane} in window-system parlance.
1260 @item window-configuration
1261 An object that represents a saved configuration of windows in a frame.
1262 @item device
1263 An object representing a screen on which frames can be displayed;
1264 equivalent to a @dfn{display} in the X Window System and a @dfn{TTY} in
1265 character mode.
1266 @item face
1267 An object specifying the appearance of text or graphics; it contains
1268 characteristics such as font, foreground color, and background color.
1269 @item marker
1270 An object that refers to a particular position in a buffer and moves
1271 around as text is inserted and deleted to stay in the same relative
1272 position to the text around it.
1273 @item extent
1274 Similar to a marker but covers a range of text in a buffer; can also
1275 specify properties of the text, such as a face in which the text is to
1276 be displayed, whether the text is invisible or unmodifiable, etc.
1277 @item event
1278 Generated by calling @code{next-event} and contains information
1279 describing a particular event happening in the system, such as the user
1280 pressing a key or a process terminating.
1281 @item keymap
1282 An object that maps from events (described using lists, vectors, and
1283 symbols rather than with an event object because the mapping is for
1284 classes of events, rather than individual events) to functions to
1285 execute or other events to recursively look up; the functions are
1286 described by name, using a symbol, or using lists to specify the
1287 function's code.
1288 @item glyph
1289 An object that describes the appearance of an image (e.g.  pixmap) on
1290 the screen; glyphs can be attached to the beginning or end of extents
1291 and in some future version of XEmacs will be able to be inserted
1292 directly into a buffer.
1293 @item process
1294 An object that describes a connection to an externally-running process.
1295 @end table
1296
1297   There are some other, less-commonly-encountered general objects:
1298
1299 @table @code
1300 @item hashtable
1301 An object that maps from an arbitrary Lisp object to another arbitrary
1302 Lisp object, using hashing for fast lookup.
1303 @item obarray
1304 A limited form of hashtable that maps from strings to symbols; obarrays
1305 are used to look up a symbol given its name and are not actually their
1306 own object type but are kludgily represented using vectors with hidden
1307 fields (this representation derives from GNU Emacs).
1308 @item specifier
1309 A complex object used to specify the value of a display property; a
1310 default value is given and different values can be specified for
1311 particular frames, buffers, windows, devices, or classes of device.
1312 @item char-table
1313 An object that maps from chars or classes of chars to arbitrary Lisp
1314 objects; internally char tables use a complex nested-vector
1315 representation that is optimized to the way characters are represented
1316 as integers.
1317 @item range-table
1318 An object that maps from ranges of integers to arbitrary Lisp objects.
1319 @end table
1320
1321   And some strange special-purpose objects:
1322
1323 @table @code
1324 @item charset
1325 @itemx coding-system
1326 Objects used when MULE, or multi-lingual/Asian-language, support is
1327 enabled.
1328 @item color-instance
1329 @itemx font-instance
1330 @itemx image-instance
1331 An object that encapsulates a window-system resource; instances are
1332 mostly used internally but are exposed on the Lisp level for cleanness
1333 of the specifier model and because it's occasionally useful for Lisp
1334 program to create or query the properties of instances.
1335 @item subwindow
1336 An object that encapsulate a @dfn{subwindow} resource, i.e. a
1337 window-system child window that is drawn into by an external process;
1338 this object should be integrated into the glyph system but isn't yet,
1339 and may change form when this is done.
1340 @item tooltalk-message
1341 @itemx tooltalk-pattern
1342 Objects that represent resources used in the ToolTalk interprocess
1343 communication protocol.
1344 @item toolbar-button
1345 An object used in conjunction with the toolbar.
1346 @item x-resource
1347 An object that encapsulates certain miscellaneous resources in the X
1348 window system, used only when Epoch support is enabled.
1349 @end table
1350
1351   And objects that are only used internally:
1352
1353 @table @asis
1354 @item opaque
1355 A generic object for encapsulating arbitrary memory; this allows you the
1356 generality of @code{malloc()} and the convenience of the Lisp object
1357 system.
1358 @item lstream
1359 A buffering I/O stream, used to provide a unified interface to anything
1360 that can accept output or provide input, such as a file descriptor, a
1361 stdio stream, a chunk of memory, a Lisp buffer, a Lisp string, etc.;
1362 it's a Lisp object to make its memory management more convenient.
1363 @item char-table-entry
1364 Subsidiary objects in the internal char-table representation.
1365 @item extent-auxiliary
1366 @itemx menubar-data
1367 @itemx toolbar-data
1368 Various special-purpose objects that are basically just used to
1369 encapsulate memory for particular subsystems, similar to the more
1370 general ``opaque'' object.
1371 @item symbol-value-forward
1372 @itemx symbol-value-buffer-local
1373 @itemx symbol-value-varalias
1374 @itemx symbol-value-lisp-magic
1375 Special internal-only objects that are placed in the value cell of a
1376 symbol to indicate that there is something special with this variable --
1377 e.g. it has no value, it mirrors another variable, or it mirrors some C
1378 variable; there is really only one kind of object, called a
1379 @dfn{symbol-value-magic}, but it is sort-of halfway kludged into
1380 semi-different object types.
1381 @end table
1382
1383 @cindex permanent objects
1384 @cindex temporary objects
1385   Some types of objects are @dfn{permanent}, meaning that once created,
1386 they do not disappear until explicitly destroyed, using a function such
1387 as @code{delete-buffer}, @code{delete-window}, @code{delete-frame}, etc.
1388 Others will disappear once they are not longer used, through the garbage
1389 collection mechanism.  Buffers, frames, windows, devices, and processes
1390 are among the objects that are permanent.  Note that some objects can go
1391 both ways: Faces can be created either way; extents are normally
1392 permanent, but detached extents (extents not referring to any text, as
1393 happens to some extents when the text they are referring to is deleted)
1394 are temporary.  Note that some permanent objects, such as faces and
1395 coding systems, cannot be deleted.  Note also that windows are unique in
1396 that they can be @emph{undeleted} after having previously been
1397 deleted. (This happens as a result of restoring a window configuration.)
1398
1399 @cindex read syntax
1400   Note that many types of objects have a @dfn{read syntax}, i.e. a way of
1401 specifying an object of that type in Lisp code.  When you load a Lisp
1402 file, or type in code to be evaluated, what really happens is that the
1403 function @code{read} is called, which reads some text and creates an object
1404 based on the syntax of that text; then @code{eval} is called, which
1405 possibly does something special; then this loop repeats until there's
1406 no more text to read. (@code{eval} only actually does something special
1407 with symbols, which causes the symbol's value to be returned,
1408 similar to referencing a variable; and with conses [i.e. lists],
1409 which cause a function invocation.  All other values are returned
1410 unchanged.)
1411
1412   The read syntax
1413
1414 @example
1415 17297
1416 @end example
1417
1418 converts to an integer whose value is 17297.
1419
1420 @example
1421 1.983e-4
1422 @end example
1423
1424 converts to a float whose value is 1983.23e-4, or .0001983.
1425
1426 @example
1427 ?b
1428 @end example
1429
1430 converts to a char that represents the lowercase letter b.
1431
1432 @example
1433 ?^[$(B#&^[(B
1434 @end example
1435
1436 (where @samp{^[} actually is an @samp{ESC} character) converts to a
1437 particular Kanji character when using an ISO2022-based coding system for
1438 input. (To decode this gook: @samp{ESC} begins an escape sequence;
1439 @samp{ESC $ (} is a class of escape sequences meaning ``switch to a
1440 94x94 character set''; @samp{ESC $ ( B} means ``switch to Japanese
1441 Kanji''; @samp{#} and @samp{&} collectively index into a 94-by-94 array
1442 of characters [subtract 33 from the ASCII value of each character to get
1443 the corresponding index]; @samp{ESC (} is a class of escape sequences
1444 meaning ``switch to a 94 character set''; @samp{ESC (B} means ``switch
1445 to US ASCII''.  It is a coincidence that the letter @samp{B} is used to
1446 denote both Japanese Kanji and US ASCII.  If the first @samp{B} were
1447 replaced with an @samp{A}, you'd be requesting a Chinese Hanzi character
1448 from the GB2312 character set.)
1449
1450 @example
1451 "foobar"
1452 @end example
1453
1454 converts to a string.
1455
1456 @example
1457 foobar
1458 @end example
1459
1460 converts to a symbol whose name is @code{"foobar"}.  This is done by
1461 looking up the string equivalent in the global variable
1462 @code{obarray}, whose contents should be an obarray.  If no symbol
1463 is found, a new symbol with the name @code{"foobar"} is automatically
1464 created and added to @code{obarray}; this process is called
1465 @dfn{interning} the symbol. 
1466 @cindex interning
1467
1468 @example
1469 (foo . bar)
1470 @end example
1471
1472 converts to a cons cell containing the symbols @code{foo} and @code{bar}.
1473
1474 @example
1475 (1 a 2.5)
1476 @end example
1477
1478 converts to a three-element list containing the specified objects
1479 (note that a list is actually a set of nested conses; see the
1480 XEmacs Lisp Reference).
1481
1482 @example
1483 [1 a 2.5]
1484 @end example
1485
1486 converts to a three-element vector containing the specified objects.
1487
1488 @example
1489 #[... ... ... ...]
1490 @end example
1491
1492 converts to a compiled-function object (the actual contents are not
1493 shown since they are not relevant here; look at a file that ends with
1494 @file{.elc} for examples).
1495
1496 @example
1497 #*01110110
1498 @end example
1499
1500 converts to a bit-vector.
1501
1502 @example
1503 #s(range-table ... ...)
1504 @end example
1505
1506 converts to a range table (the actual contents are not shown).
1507
1508 @example
1509 #s(char-table ... ...)
1510 @end example
1511
1512 converts to a char table (the actual contents are not shown).
1513 (Note that the #s syntax is the general syntax for structures,
1514 which are not really implemented in XEmacs Lisp but should be.)
1515
1516   When an object is printed out (using @code{print} or a related
1517 function), the read syntax is used, so that the same object can be read
1518 in again.
1519
1520   The other objects do not have read syntaxes, usually because it does
1521 not really make sense to create them in this fashion (i.e.  processes,
1522 where it doesn't make sense to have a subprocess created as a side
1523 effect of reading some Lisp code), or because they can't be created at
1524 all (e.g. subrs).  Permanent objects, as a rule, do not have a read
1525 syntax; nor do most complex objects, which contain too much state to be
1526 easily initialized through a read syntax.
1527
1528 @node How Lisp Objects Are Represented in C, Rules When Writing New C Code, The XEmacs Object System (Abstractly Speaking), Top
1529 @chapter How Lisp Objects Are Represented in C
1530
1531   Lisp objects are represented in C using a 32- or 64-bit machine word
1532 (depending on the processor; i.e. DEC Alphas use 64-bit Lisp objects and
1533 most other processors use 32-bit Lisp objects).  The representation
1534 stuffs a pointer together with a tag, as follows:
1535
1536 @example
1537  [ 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 ]
1538  [ 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 ]
1539
1540    ^ <---> <------------------------------------------------------>
1541    |  tag         a pointer to a structure, or an integer
1542    |
1543    `---> mark bit
1544 @end example
1545
1546   The tag describes the type of the Lisp object.  For integers and
1547 chars, the lower 28 bits contain the value of the integer or char; for
1548 all others, the lower 28 bits contain a pointer.  The mark bit is used
1549 during garbage-collection, and is always 0 when garbage collection is
1550 not happening.  Many macros that extract out parts of a Lisp object
1551 expect that the mark bit is 0, and will produce incorrect results if
1552 it's not. (The way that garbage collection works, basically, is that it
1553 loops over all places where Lisp objects could exist -- this includes
1554 all global variables in C that contain Lisp objects [including
1555 @code{Vobarray}, the C equivalent of @code{obarray}; through this, all
1556 Lisp variables will get marked], plus various other places -- and
1557 recursively scans through the Lisp objects, marking each object it finds
1558 by setting the mark bit.  Then it goes through the lists of all objects
1559 allocated, freeing the ones that are not marked and turning off the
1560 mark bit of the ones that are marked.)
1561
1562   Lisp objects use the typedef @code{Lisp_Object}, but the actual C type
1563 used for the Lisp object can vary.  It can be either a simple type
1564 (@code{long} on the DEC Alpha, @code{int} on other machines) or a
1565 structure whose fields are bit fields that line up properly (actually, a
1566 union of structures that's used).  Generally the simple integral type is
1567 preferable because it ensures that the compiler will actually use a
1568 machine word to represent the object (some compilers will use more
1569 general and less efficient code for unions and structs even if they can
1570 fit in a machine word).  The union type, however, has the advantage of
1571 stricter type checking (if you accidentally pass an integer where a Lisp
1572 object is desired, you get a compile error), and it makes it easier to
1573 decode Lisp objects when debugging.  The choice of which type to use is
1574 determined by the presence or absence of the preprocessor constant
1575 @code{USE_UNION_TYPE}.
1576
1577 @cindex record type
1578   Note that there are only eight types that the tag can represent,
1579 but many more actual types than this.  This is handled by having
1580 one of the tag types specify a meta-type called a @dfn{record};
1581 for all such objects, the first four bytes of the pointed-to
1582 structure indicate what the actual type is.
1583
1584   Note also that having 28 bits for pointers and integers restricts a
1585 lot of things to 256 megabytes of memory. (Basically, enough pointers
1586 and indices and whatnot get stuffed into Lisp objects that the total
1587 amount of memory used by XEmacs can't grow above 256 megabytes.  In
1588 older versions of XEmacs and GNU Emacs, the tag was 5 bits wide,
1589 allowing for 32 types, which was more than the actual number of types
1590 that existed at the time, and no ``record'' type was necessary.
1591 However, this limited the editor to 64 megabytes total, which some users
1592 who edited large files might conceivably exceed.)
1593
1594   Also, note that there is an implicit assumption here that all pointers
1595 are low enough that the top bits are all zero and can just be chopped
1596 off.  On standard machines that allocate memory from the bottom up (and
1597 give each process its own address space), this works fine.  Some
1598 machines, however, put the data space somewhere else in memory
1599 (e.g. beginning at 0x80000000).  Those machines cope by defining
1600 @code{DATA_SEG_BITS} in the corresponding @file{m/} or @file{s/} file to
1601 the proper mask.  Then, pointers retrieved from Lisp objects are
1602 automatically OR'ed with this value prior to being used.
1603
1604   A corollary of the previous paragraph is that @strong{(pointers to)
1605 stack-allocated structures cannot be put into Lisp objects}.  The stack
1606 is generally located near the top of memory; if you put such a pointer
1607 into a Lisp object, it will get its top bits chopped off, and you will
1608 lose.
1609
1610   Various macros are used to construct Lisp objects and extract the
1611 components.  Macros of the form @code{XINT()}, @code{XCHAR()},
1612 @code{XSTRING()}, @code{XSYMBOL()}, etc. mask out the pointer/integer
1613 field and cast it to the appropriate type.  All of the macros that
1614 construct pointers will @code{OR} with @code{DATA_SEG_BITS} if
1615 necessary.  @code{XINT()} needs to be a bit tricky so that negative
1616 numbers are properly sign-extended: Usually it does this by shifting the
1617 number four bits to the left and then four bits to the right.  This
1618 assumes that the right-shift operator does an arithmetic shift (i.e. it
1619 leaves the most-significant bit as-is rather than shifting in a zero, so
1620 that it mimics a divide-by-two even for negative numbers).  Not all
1621 machines/compilers do this, and on the ones that don't, a more
1622 complicated definition is selected by defining
1623 @code{EXPLICIT_SIGN_EXTEND}.
1624
1625   Note that when @code{ERROR_CHECK_TYPECHECK} is defined, the extractor
1626 macros become more complicated -- they check the tag bits and/or the
1627 type field in the first four bytes of a record type to ensure that the
1628 object is really of the correct type.  This is great for catching places
1629 where an incorrect type is being dereferenced -- this typically results
1630 in a pointer being dereferenced as the wrong type of structure, with
1631 unpredictable (and sometimes not easily traceable) results.
1632
1633   There are similar @code{XSET@var{TYPE}()} macros that construct a Lisp object.
1634 These macros are of the form @code{XSET@var{TYPE} (@var{lvalue}, @var{result})},
1635 i.e. they have to be a statement rather than just used in an expression.
1636 The reason for this is that standard C doesn't let you ``construct'' a
1637 structure (but GCC does).  Granted, this sometimes isn't too convenient;
1638 for the case of integers, at least, you can use the function
1639 @code{make_int()}, which constructs and @emph{returns} an integer
1640 Lisp object.  Note that the @code{XSET@var{TYPE}()} macros are also
1641 affected by @code{ERROR_CHECK_TYPECHECK} and make sure that the
1642 structure is of the right type in the case of record types, where the
1643 type is contained in the structure.
1644
1645 @node Rules When Writing New C Code, A Summary of the Various XEmacs Modules, How Lisp Objects Are Represented in C, Top
1646 @chapter Rules When Writing New C Code
1647
1648   The XEmacs C Code is extremely complex and intricate, and there are
1649 many rules that are more or less consistently followed throughout the code.
1650 Many of these rules are not obvious, so they are explained here.  It is
1651 of the utmost importance that you follow them.  If you don't, you may get
1652 something that appears to work, but which will crash in odd situations,
1653 often in code far away from where the actual breakage is.
1654
1655 @menu
1656 * General Coding Rules::
1657 * Writing Lisp Primitives::
1658 * Adding Global Lisp Variables::
1659 * Coding for Mule::
1660 * Techniques for XEmacs Developers::
1661 @end menu
1662
1663 @node General Coding Rules
1664 @section General Coding Rules
1665
1666   Almost every module contains a @code{syms_of_*()} function and a
1667 @code{vars_of_*()} function.  The former declares any Lisp primitives
1668 you have defined and defines any symbols you will be using.  The latter
1669 declares any global Lisp variables you have added and initializes global
1670 C variables in the module.  For each such function, declare it in
1671 @file{symsinit.h} and make sure it's called in the appropriate place in
1672 @file{emacs.c}.  @strong{Important}: There are stringent requirements on
1673 exactly what can go into these functions.  See the comment in
1674 @file{emacs.c}.  The reason for this is to avoid obscure unwanted
1675 interactions during initialization.  If you don't follow these rules,
1676 you'll be sorry!  If you want to do anything that isn't allowed, create
1677 a @code{complex_vars_of_*()} function for it.  Doing this is tricky,
1678 though: You have to make sure your function is called at the right time
1679 so that all the initialization dependencies work out.
1680
1681   Every module includes @file{<config.h>} (angle brackets so that
1682 @samp{--srcdir} works correctly; @file{config.h} may or may not be in
1683 the same directory as the C sources) and @file{lisp.h}.  @file{config.h}
1684 should always be included before any other header files (including
1685 system header files) to ensure that certain tricks played by various
1686 @file{s/} and @file{m/} files work out correctly.
1687
1688   @strong{All global and static variables that are to be modifiable must
1689 be declared uninitialized.}  This means that you may not use the ``declare
1690 with initializer'' form for these variables, such as @code{int
1691 some_variable = 0;}.  The reason for this has to do with some kludges
1692 done during the dumping process: If possible, the initialized data
1693 segment is re-mapped so that it becomes part of the (unmodifiable) code
1694 segment in the dumped executable.  This allows this memory to be shared
1695 among multiple running XEmacs processes.  XEmacs is careful to place as
1696 much constant data as possible into initialized variables (in
1697 particular, into what's called the @dfn{pure space} -- see below) during
1698 the @file{temacs} phase.
1699
1700 @cindex copy-on-write
1701   @strong{Please note:} This kludge only works on a few systems
1702 nowadays, and is rapidly becoming irrelevant because most modern
1703 operating systems provide @dfn{copy-on-write} semantics.  All data is
1704 initially shared between processes, and a private copy is automatically
1705 made (on a page-by-page basis) when a process first attempts to write to
1706 a page of memory.
1707
1708   Formerly, there was a requirement that static variables not be
1709 declared inside of functions.  This had to do with another hack along
1710 the same vein as what was just described: old USG systems put
1711 statically-declared variables in the initialized data space, so those
1712 header files had a @code{#define static} declaration. (That way, the
1713 data-segment remapping described above could still work.) This fails
1714 badly on static variables inside of functions, which suddenly become
1715 automatic variables; therefore, you weren't supposed to have any of
1716 them.  This awful kludge has been removed in XEmacs because
1717
1718 @enumerate
1719 @item
1720 almost all of the systems that used this kludge ended up having
1721 to disable the data-segment remapping anyway;
1722 @item
1723 the only systems that didn't were extremely outdated ones;
1724 @item
1725 this hack completely messed up inline functions.
1726 @end enumerate
1727
1728 @node Writing Lisp Primitives
1729 @section Writing Lisp Primitives
1730
1731   Lisp primitives are Lisp functions implemented in C.  The details of
1732 interfacing the C function so that Lisp can call it are handled by a few
1733 C macros.  The only way to really understand how to write new C code is
1734 to read the source, but we can explain some things here.
1735
1736   An example of a special form is the definition of @code{or}, from
1737 @file{eval.c}.  (An ordinary function would have the same general
1738 appearance.)
1739
1740 @cindex garbage collection protection
1741 @smallexample
1742 @group
1743 DEFUN ("or", For, 0, UNEVALLED, 0, /*
1744 Eval args until one of them yields non-nil, then return that value.
1745 The remaining args are not evalled at all.
1746 If all args return nil, return nil.
1747 */
1748        (args))
1749 @{
1750   /* This function can GC */
1751   Lisp_Object val = Qnil;
1752   struct gcpro gcpro1;
1753
1754   GCPRO1 (args);
1755
1756   while (!NILP (args))
1757     @{
1758       val = Feval (XCAR (args));
1759       if (!NILP (val))
1760         break;
1761       args = XCDR (args);
1762     @}
1763
1764   UNGCPRO;
1765   return val;
1766 @}
1767 @end group
1768 @end smallexample
1769
1770   Let's start with a precise explanation of the arguments to the
1771 @code{DEFUN} macro.  Here is a template for them:
1772
1773 @example
1774 DEFUN (@var{lname}, @var{fname}, @var{min}, @var{max}, @var{interactive}, /* 
1775 @var{docstring} 
1776 */  
1777    (@var{arglist}) )
1778 @end example
1779
1780 @table @var
1781 @item lname
1782 This string is the name of the Lisp symbol to define as the function
1783 name; in the example above, it is @code{"or"}.
1784
1785 @item fname
1786 This is the C function name for this function.  This is the name that is
1787 used in C code for calling the function.  The name is, by convention,
1788 @samp{F} prepended to the Lisp name, with all dashes (@samp{-}) in the
1789 Lisp name changed to underscores.  Thus, to call this function from C
1790 code, call @code{For}.  Remember that the arguments are of type
1791 @code{Lisp_Object}; various macros and functions for creating values of
1792 type @code{Lisp_Object} are declared in the file @file{lisp.h}.
1793
1794 Primitives whose names are special characters (e.g. @code{+} or
1795 @code{<}) are named by spelling out, in some fashion, the special
1796 character: e.g. @code{Fplus()} or @code{Flss()}.  Primitives whose names
1797 begin with normal alphanumeric characters but also contain special
1798 characters are spelled out in some creative way, e.g. @code{let*}
1799 becomes @code{FletX()}.
1800
1801 Each function also has an associated structure that holds the data for
1802 the subr object that represents the function in Lisp.  This structure
1803 conveys the Lisp symbol name to the initialization routine that will
1804 create the symbol and store the subr object as its definition.  The C
1805 variable name of this structure is always @samp{S} prepended to the
1806 @var{fname}.  You hardly ever need to be aware of the existence of this
1807 structure.
1808
1809 @item min
1810 This is the minimum number of arguments that the function requires.  The
1811 function @code{or} allows a minimum of zero arguments.
1812
1813 @item max
1814 This is the maximum number of arguments that the function accepts, if
1815 there is a fixed maximum.  Alternatively, it can be @code{UNEVALLED},
1816 indicating a special form that receives unevaluated arguments, or
1817 @code{MANY}, indicating an unlimited number of evaluated arguments (the
1818 equivalent of @code{&rest}).  Both @code{UNEVALLED} and @code{MANY} are
1819 macros.  If @var{max} is a number, it may not be less than @var{min} and
1820 it may not be greater than 8. (If you need to add a function with
1821 more than 8 arguments, either use the @code{MANY} form or edit the
1822 definition of @code{DEFUN} in @file{lisp.h}.  If you do the latter,
1823 make sure to also add another clause to the switch statement in
1824 @code{primitive_funcall().})
1825
1826 @item interactive
1827 This is an interactive specification, a string such as might be used as
1828 the argument of @code{interactive} in a Lisp function.  In the case of
1829 @code{or}, it is 0 (a null pointer), indicating that @code{or} cannot be
1830 called interactively.  A value of @code{""} indicates a function that
1831 should receive no arguments when called interactively.
1832
1833 @item docstring
1834 This is the documentation string.  It is written just like a
1835 documentation string for a function defined in Lisp; in particular, the
1836 first line should be a single sentence.  Note how the documentation
1837 string is enclosed in a comment, none of the documentation is placed on
1838 the same lines as the comment-start and comment-end characters, and the
1839 comment-start characters are on the same line as the interactive
1840 specification.  @file{make-docfile}, which scans the C files for
1841 documentation strings, is very particular about what it looks for, and
1842 will not properly extract the doc string if it's not in this exact format.
1843
1844 You are free to put the various arguments to @code{DEFUN} on separate
1845 lines to avoid overly long lines.  However, make sure to put the
1846 comment-start characters for the doc string on the same line as the
1847 interactive specification, and put a newline directly after them (and
1848 before the comment-end characters).
1849
1850 @item arglist
1851 This is the comma-separated list of arguments to the C function.  For a
1852 function with a fixed maximum number of arguments, provide a C argument
1853 for each Lisp argument.  In this case, unlike regular C functions, the
1854 types of the arguments are not declared; they are simply always of type
1855 @code{Lisp_Object}.  
1856
1857 The names of the C arguments will be used as the names of the arguments
1858 to the Lisp primitive as displayed in its documentation, modulo the same
1859 concerns described above for @code{F...} names (in particular,
1860 underscores in the C arguments become dashes in the Lisp arguments).
1861
1862 There is one additional kludge: A trailing `_' on the C argument is
1863 discarded when forming the Lisp argument.  This allows C language
1864 reserved words (like @code{default}) or global symbols (like
1865 @code{dirname}) to be used as argument names without compiler warnings
1866 or errors.
1867
1868 A Lisp function with @w{@var{max} = @code{UNEVALLED}} is a
1869 @w{@dfn{special form}}; its arguments are not evaluated.  Instead it
1870 receives one argument of type @code{Lisp_Object}, a (Lisp) list of the
1871 unevaluated arguments, conventionally named @code{(args)}.
1872
1873 When a Lisp function has no upper limit on the number of arguments,
1874 specify @w{@var{max} = @code{MANY}}.  In this case its implementation in
1875 C actually receives exactly two arguments: the number of Lisp arguments
1876 (an @code{int}) and the address of a block containing their values (a
1877 @w{@code{Lisp_Object *}}).  In this case only are the C types specified
1878 in the @var{arglist}: @w{@code{(int nargs, Lisp_Object *args)}}.
1879
1880 @end table
1881
1882   Within the function @code{For} itself, note the use of the macros
1883 @code{GCPRO1} and @code{UNGCPRO}.  @code{GCPRO1} is used to ``protect''
1884 a variable from garbage collection---to inform the garbage collector
1885 that it must look in that variable and regard its contents as an
1886 accessible object.  This is necessary whenever you call @code{Feval} or
1887 anything that can directly or indirectly call @code{Feval} (this
1888 includes the @code{QUIT} macro!).  At such a time, any Lisp object that
1889 you intend to refer to again must be protected somehow.  @code{UNGCPRO}
1890 cancels the protection of the variables that are protected in the
1891 current function.  It is necessary to do this explicitly.
1892
1893   The macro @code{GCPRO1} protects just one local variable.  If you want
1894 to protect two, use @code{GCPRO2} instead; repeating @code{GCPRO1} will
1895 not work.  Macros @code{GCPRO3} and @code{GCPRO4} also exist.
1896
1897   These macros implicitly use local variables such as @code{gcpro1}; you
1898 must declare these explicitly, with type @code{struct gcpro}.  Thus, if
1899 you use @code{GCPRO2}, you must declare @code{gcpro1} and @code{gcpro2}.
1900
1901 @cindex caller-protects (@code{GCPRO} rule)
1902   Note also that the general rule is @dfn{caller-protects}; i.e. you
1903 are only responsible for protecting those Lisp objects that you create.
1904 Any objects passed to you as parameters should have been protected
1905 by whoever created them, so you don't in general have to protect them.
1906 @code{For} is an exception; it protects its parameters to provide
1907 extra assurance against Lisp primitives elsewhere that are incorrectly
1908 written, and against malicious self-modifying code.  There are a few
1909 other standard functions that also do this.
1910
1911 @code{GCPRO}ing is perhaps the trickiest and most error-prone part
1912 of XEmacs coding.  It is @strong{extremely} important that you get this
1913 right and use a great deal of discipline when writing this code.
1914 @xref{GCPROing, ,@code{GCPRO}ing}, for full details on how to do this.
1915
1916   What @code{DEFUN} actually does is declare a global structure of
1917 type @code{Lisp_Subr} whose name begins with capital @samp{SF} and
1918 which contains information about the primitive (e.g. a pointer to the
1919 function, its minimum and maximum allowed arguments, a string describing
1920 its Lisp name); @code{DEFUN} then begins a normal C function
1921 declaration using the @code{F...} name.  The Lisp subr object that is
1922 the function definition of a primitive (i.e. the object in the function
1923 slot of the symbol that names the primitive) actually points to this
1924 @samp{SF} structure; when @code{Feval} encounters a subr, it looks in the
1925 structure to find out how to call the C function.
1926
1927   Defining the C function is not enough to make a Lisp primitive
1928 available; you must also create the Lisp symbol for the primitive (the
1929 symbol is @dfn{interned}; @pxref{Obarrays}) and store a suitable subr
1930 object in its function cell. (If you don't do this, the primitive won't
1931 be seen by Lisp code.) The code looks like this:
1932
1933 @example
1934 DEFSUBR (@var{fname});
1935 @end example
1936
1937 @noindent 
1938 Here @var{fname} is the name you used as the second argument to
1939 @code{DEFUN}.
1940
1941   This call to @code{DEFSUBR} should go in the @code{syms_of_*()}
1942 function at the end of the module.  If no such function exists, create
1943 it and make sure to also declare it in @file{symsinit.h} and call it
1944 from the appropriate spot in @code{main()}.  @xref{General Coding
1945 Rules}.
1946
1947   Note that C code cannot call functions by name unless they are defined
1948 in C.  The way to call a function written in Lisp from C is to use
1949 @code{Ffuncall}, which embodies the Lisp function @code{funcall}.  Since
1950 the Lisp function @code{funcall} accepts an unlimited number of
1951 arguments, in C it takes two: the number of Lisp-level arguments, and a
1952 one-dimensional array containing their values.  The first Lisp-level
1953 argument is the Lisp function to call, and the rest are the arguments to
1954 pass to it.  Since @code{Ffuncall} can call the evaluator, you must
1955 protect pointers from garbage collection around the call to
1956 @code{Ffuncall}. (However, @code{Ffuncall} explicitly protects all of
1957 its parameters, so you don't have to protect any pointers passed
1958 as parameters to it.)
1959
1960   The C functions @code{call0}, @code{call1}, @code{call2}, and so on,
1961 provide handy ways to call a Lisp function conveniently with a fixed
1962 number of arguments.  They work by calling @code{Ffuncall}.
1963
1964   @file{eval.c} is a very good file to look through for examples;
1965 @file{lisp.h} contains the definitions for some important macros and
1966 functions.
1967
1968 @node Adding Global Lisp Variables
1969 @section Adding Global Lisp Variables
1970
1971   Global variables whose names begin with @samp{Q} are constants whose
1972 value is a symbol of a particular name.  The name of the variable should
1973 be derived from the name of the symbol using the same rules as for Lisp
1974 primitives.  These variables are initialized using a call to
1975 @code{defsymbol()} in the @code{syms_of_*()} function. (This call
1976 interns a symbol, sets the C variable to the resulting Lisp object, and
1977 calls @code{staticpro()} on the C variable to tell the
1978 garbage-collection mechanism about this variable.  What
1979 @code{staticpro()} does is add a pointer to the variable to a large
1980 global array; when garbage-collection happens, all pointers listed in
1981 the array are used as starting points for marking Lisp objects.  This is
1982 important because it's quite possible that the only current reference to
1983 the object is the C variable.  In the case of symbols, the
1984 @code{staticpro()} doesn't matter all that much because the symbol is
1985 contained in @code{obarray}, which is itself @code{staticpro()}ed.
1986 However, it's possible that a naughty user could do something like
1987 uninterning the symbol out of @code{obarray} or even setting
1988 @code{obarray} to a different value [although this is likely to make
1989 XEmacs crash!].)
1990
1991   @strong{Please note:} It is potentially deadly if you declare a
1992 @samp{Q...}  variable in two different modules.  The two calls to
1993 @code{defsymbol()} are no problem, but some linkers will complain about
1994 multiply-defined symbols.  The most insidious aspect of this is that
1995 often the link will succeed anyway, but then the resulting executable
1996 will sometimes crash in obscure ways during certain operations!  To
1997 avoid this problem, declare any symbols with common names (such as
1998 @code{text}) that are not obviously associated with this particular
1999 module in the module @file{general.c}.
2000
2001   Global variables whose names begin with @samp{V} are variables that
2002 contain Lisp objects.  The convention here is that all global variables
2003 of type @code{Lisp_Object} begin with @samp{V}, and all others don't
2004 (including integer and boolean variables that have Lisp
2005 equivalents). Most of the time, these variables have equivalents in
2006 Lisp, but some don't.  Those that do are declared this way by a call to
2007 @code{DEFVAR_LISP()} in the @code{vars_of_*()} initializer for the
2008 module.  What this does is create a special @dfn{symbol-value-forward}
2009 Lisp object that contains a pointer to the C variable, intern a symbol
2010 whose name is as specified in the call to @code{DEFVAR_LISP()}, and set
2011 its value to the symbol-value-forward Lisp object; it also calls
2012 @code{staticpro()} on the C variable to tell the garbage-collection
2013 mechanism about the variable.  When @code{eval} (or actually
2014 @code{symbol-value}) encounters this special object in the process of
2015 retrieving a variable's value, it follows the indirection to the C
2016 variable and gets its value.  @code{setq} does similar things so that
2017 the C variable gets changed.
2018
2019   Whether or not you @code{DEFVAR_LISP()} a variable, you need to
2020 initialize it in the @code{vars_of_*()} function; otherwise it will end
2021 up as all zeroes, which is the integer 0 (@emph{not} @code{nil}), and
2022 this is probably not what you want.  Also, if the variable is not
2023 @code{DEFVAR_LISP()}ed, @strong{you must call} @code{staticpro()} on the
2024 C variable in the @code{vars_of_*()} function.  Otherwise, the
2025 garbage-collection mechanism won't know that the object in this variable
2026 is in use, and will happily collect it and reuse its storage for another
2027 Lisp object, and you will be the one who's unhappy when you can't figure
2028 out how your variable got overwritten.
2029
2030 @node Coding for Mule
2031 @section Coding for Mule
2032 @cindex Coding for Mule
2033
2034 Although Mule support is not compiled by default in XEmacs, many people
2035 are using it, and we consider it crucial that new code works correctly
2036 with multibyte characters.  This is not hard; it is only a matter of
2037 following several simple user-interface guidelines.  Even if you never
2038 compile with Mule, with a little practice you will find it quite easy
2039 to code Mule-correctly.
2040
2041 Note that these guidelines are not necessarily tied to the current Mule
2042 implementation; they are also a good idea to follow on the grounds of
2043 code generalization for future I18N work.
2044
2045 @menu
2046 * Character-Related Data Types::
2047 * Working With Character and Byte Positions::
2048 * Conversion of External Data::
2049 * General Guidelines for Writing Mule-Aware Code::
2050 * An Example of Mule-Aware Code::
2051 @end menu
2052
2053 @node Character-Related Data Types
2054 @subsection Character-Related Data Types
2055
2056 First, we will list the basic character-related datatypes used by
2057 XEmacs.  Note that the separate @code{typedef}s are not required for the 
2058 code to work (all of them boil down to @code{unsigned char} or
2059 @code{int}), but they improve clarity of code a great deal, because one
2060 glance at the declaration can tell the intended use of the variable.
2061
2062 @table @code
2063 @item Emchar
2064 @cindex Emchar
2065 An @code{Emchar} holds a single Emacs character.
2066
2067 Obviously, the equality between characters and bytes is lost in the Mule
2068 world.  Characters can be represented by one or more bytes in the
2069 buffer, and @code{Emchar} is the C type large enough to hold any
2070 character.
2071
2072 Without Mule support, an @code{Emchar} is equivalent to an
2073 @code{unsigned char}.
2074
2075 @item Bufbyte
2076 @cindex Bufbyte
2077 The data representing the text in a buffer or string is logically a set
2078 of @code{Bufbyte}s.
2079
2080 XEmacs does not work with character formats all the time; when reading
2081 characters from the outside, it decodes them to an internal format, and
2082 likewise encodes them when writing.  @code{Bufbyte} (in fact
2083 @code{unsigned char}) is the basic unit of XEmacs internal buffers and
2084 strings format.
2085
2086 One character can correspond to one or more @code{Bufbyte}s.  In the
2087 current implementation, an ASCII character is represented by the same
2088 @code{Bufbyte}, and extended characters are represented by a sequence of
2089 @code{Bufbyte}s.
2090
2091 Without Mule support, a @code{Bufbyte} is equivalent to an
2092 @code{Emchar}.
2093
2094 @item Bufpos
2095 @itemx Charcount
2096 A @code{Bufpos} represents a character position in a buffer or string.
2097 A @code{Charcount} represents a number (count) of characters.
2098 Logically, subtracting two @code{Bufpos} values yields a
2099 @code{Charcount} value.  Although all of these are @code{typedef}ed to
2100 @code{int}, we use them in preference to @code{int} to make it clear
2101 what sort of position is being used.
2102
2103 @code{Bufpos} and @code{Charcount} values are the only ones that are
2104 ever visible to Lisp.
2105
2106 @item Bytind
2107 @itemx Bytecount
2108 A @code{Bytind} represents a byte position in a buffer or string.  A
2109 @code{Bytecount} represents the distance between two positions in bytes.
2110 The relationship between @code{Bytind} and @code{Bytecount} is the same
2111 as the relationship between @code{Bufpos} and @code{Charcount}.
2112
2113 @item Extbyte
2114 @itemx Extcount
2115 When dealing with the outside world, XEmacs works with @code{Extbyte}s,
2116 which are equivalent to @code{unsigned char}.  Obviously, an
2117 @code{Extcount} is the distance between two @code{Extbyte}s.  Extbytes
2118 and Extcounts are not all that frequent in XEmacs code.
2119 @end table
2120
2121 @node Working With Character and Byte Positions
2122 @subsection Working With Character and Byte Positions
2123
2124 Now that we have defined the basic character-related types, we can look
2125 at the macros and functions designed for work with them and for
2126 conversion between them.  Most of these macros are defined in
2127 @file{buffer.h}, and we don't discuss all of them here, but only the
2128 most important ones.  Examining the existing code is the best way to
2129 learn about them.
2130
2131 @table @code
2132 @item MAX_EMCHAR_LEN
2133 This preprocessor constant is the maximum number of buffer bytes per
2134 Emacs character, i.e. the byte length of an @code{Emchar}.  It is useful
2135 when allocating temporary strings to keep a known number of characters.
2136 For instance:
2137
2138 @example
2139 @group
2140 @{
2141   Charcount cclen;
2142   ...
2143   @{
2144     /* Allocate place for @var{cclen} characters. */
2145     Bufbyte *tmp_buf = (Bufbyte *)alloca (cclen * MAX_EMCHAR_LEN);
2146 ...
2147 @end group
2148 @end example
2149
2150 If you followed the previous section, you can guess that, logically,
2151 multiplying a @code{Charcount} value with @code{MAX_EMCHAR_LEN} produces 
2152 a @code{Bytecount} value.
2153
2154 In the current Mule implementation, @code{MAX_EMCHAR_LEN} equals 4.
2155 Without Mule, it is 1.
2156
2157 @item charptr_emchar
2158 @item set_charptr_emchar
2159 @code{charptr_emchar} macro takes a @code{Bufbyte} pointer and returns
2160 the underlying @code{Emchar}.  If it were a function, its prototype
2161 would be:
2162
2163 @example
2164 Emchar charptr_emchar (Bufbyte *p);
2165 @end example
2166
2167 @code{set_charptr_emchar} stores an @code{Emchar} to the specified byte
2168 position.  It returns the number of bytes stored:
2169
2170 @example
2171 Bytecount set_charptr_emchar (Bufbyte *p, Emchar c);
2172 @end example
2173
2174 It is important to note that @code{set_charptr_emchar} is safe only for
2175 appending a character at the end of a buffer, not for overwriting a
2176 character in the middle.  This is because the width of characters
2177 varies, and @code{set_charptr_emchar} cannot resize the string if it
2178 writes, say, a two-byte character where a single-byte character used to
2179 reside.
2180
2181 A typical use of @code{set_charptr_emchar} can be demonstrated by this
2182 example, which copies characters from buffer @var{buf} to a temporary
2183 string of Bufbytes.
2184
2185 @example
2186 @group
2187 @{
2188   Bufpos pos;
2189   for (pos = beg; pos < end; pos++)
2190     @{
2191       Emchar c = BUF_FETCH_CHAR (buf, pos);
2192       p += set_charptr_emchar (buf, c);
2193     @}
2194 @}
2195 @end group
2196 @end example
2197
2198 Note how @code{set_charptr_emchar} is used to store the @code{Emchar}
2199 and increment the counter, at the same time.
2200
2201 @item INC_CHARPTR
2202 @itemx DEC_CHARPTR
2203 These two macros increment and decrement a @code{Bufbyte} pointer,
2204 respectively.  The pointer needs to be correctly positioned at the
2205 beginning of a valid character position.
2206
2207 Without Mule support, @code{INC_CHARPTR (p)} and @code{DEC_CHARPTR (p)}
2208 simply expand to @code{p++} and @code{p--}, respectively.
2209
2210 @item bytecount_to_charcount
2211 Given a pointer to a text string and a length in bytes, return the
2212 equivalent length in characters.
2213
2214 @example
2215 Charcount bytecount_to_charcount (Bufbyte *p, Bytecount bc);
2216 @end example
2217
2218 @item charcount_to_bytecount
2219 Given a pointer to a text string and a length in characters, return the
2220 equivalent length in bytes.
2221
2222 @example
2223 Bytecount charcount_to_bytecount (Bufbyte *p, Charcount cc);
2224 @end example
2225
2226 @item charptr_n_addr
2227 Return a pointer to the beginning of the character offset @var{cc} (in
2228 characters) from @var{p}.
2229
2230 @example
2231 Bufbyte *charptr_n_addr (Bufbyte *p, Charcount cc);
2232 @end example
2233 @end table
2234
2235 @node Conversion of External Data
2236 @subsection Conversion of External Data
2237
2238 When an external function, such as a C library function, returns a
2239 @code{char} pointer, you should never treat it as @code{Bufbyte}.  This
2240 is because these returned strings may contain 8bit characters which can
2241 be misinterpreted by XEmacs, and cause a crash.  Instead, you should use
2242 a conversion macro.  Many different conversion macros are defined in
2243 @file{buffer.h}, so I will try to order them logically, by direction and
2244 by format.
2245
2246 Thus the basic conversion macros are @code{GET_CHARPTR_INT_DATA_ALLOCA}
2247 and @code{GET_CHARPTR_EXT_DATA_ALLOCA}.  The former is used to convert
2248 external data to internal format, and the latter is used to convert the
2249 other way around.  The arguments each of these receives are @var{ptr}
2250 (pointer to the text in external format), @var{len} (length of texts in
2251 bytes), @var{fmt} (format of the external text), @var{ptr_out} (lvalue
2252 to which new text should be copied), and @var{len_out} (lvalue which
2253 will be assigned the length of the internal text in bytes).  The
2254 resulting text is stored to a stack-allocated buffer.  If the text
2255 doesn't need changing, these macros will do nothing, except for setting
2256 @var{len_out}.
2257
2258 Currently meaningful formats are @code{FORMAT_BINARY},
2259 @code{FORMAT_FILENAME}, @code{FORMAT_OS}, and @code{FORMAT_CTEXT}.
2260
2261 The two macros above take many arguments which makes them unwieldy.  For
2262 this reason, several convenience macros are defined with obvious
2263 functionality, but accepting less arguments:
2264
2265 @table @code
2266 @item GET_C_CHARPTR_EXT_DATA_ALLOCA
2267 @itemx GET_C_CHARPTR_INT_DATA_ALLOCA
2268 These two macros work on ``C char pointers'', which are zero-terminated, 
2269 and thus do not need @var{len} or @var{len_out} parameters.
2270
2271 @item GET_STRING_EXT_DATA_ALLOCA
2272 @itemx GET_C_STRING_EXT_DATA_ALLOCA
2273 These two macros work on Lisp strings, thus also not needing a @var{len}
2274 parameter.  However, @code{GET_STRING_EXT_DATA_ALLOCA} still provides a
2275 @var{len_out} parameter.  Note that for Lisp strings only one conversion
2276 direction makes sense.
2277
2278 @item GET_C_CHARPTR_EXT_BINARY_DATA_ALLOCA
2279 @itemx GET_C_CHARPTR_EXT_FILENAME_DATA_ALLOCA
2280 @itemx GET_C_CHARPTR_EXT_CTEXT_DATA_ALLOCA
2281 @itemx ...
2282 These macros are a combination of the above, but with the @var{fmt}
2283 argument encoded into the name of the macro.
2284 @end table
2285
2286 @node General Guidelines for Writing Mule-Aware Code
2287 @subsection General Guidelines for Writing Mule-Aware Code
2288
2289 This section contains some general guidance on how to write Mule-aware
2290 code, as well as some pitfalls you should avoid.
2291
2292 @table @emph
2293 @item Never use @code{char} and @code{char *}.
2294 In XEmacs, the use of @code{char} and @code{char *} is almost always a
2295 mistake.  If you want to manipulate an Emacs character from ``C'', use
2296 @code{Emchar}.  If you want to examine a specific octet in the internal
2297 format, use @code{Bufbyte}.  If you want a Lisp-visible character, use a
2298 @code{Lisp_Object} and @code{make_char}.  If you want a pointer to move
2299 through the internal text, use @code{Bufbyte *}.  Also note that you
2300 almost certainly do not need @code{Emchar *}.
2301
2302 @item Be careful not to confuse @code{Charcount}, @code{Bytecount}, and @code{Bufpos}.
2303 The whole point of using different types is to avoid confusion about the 
2304 use of certain variables.  Lest this effect be nullified, you need to be 
2305 careful about using the right types.
2306
2307 @item Always convert external data
2308 It is extremely important to always convert external data, because
2309 XEmacs can crash if unexpected 8bit sequences are copied to its internal 
2310 buffers literally.
2311
2312 This means that when a system function, such as @code{readdir}, returns
2313 a string, you need to convert it using one of the conversion macros
2314 described in the previous chapter, before passing it further to Lisp.
2315 In the case of @code{readdir}, you would use the
2316 @code{GET_C_CHARPTR_INT_FILENAME_DATA_ALLOCA} macro.
2317
2318 Also note that many internal functions, such as @code{make_string},
2319 accept Bufbytes, which removes the need for them to convert the data
2320 they receive.  This increases efficiency because that way external data
2321 needs to be decoded only once, when it is read.  After that, it is
2322 passed around in internal format.
2323 @end table
2324
2325 @node An Example of Mule-Aware Code
2326 @subsection An Example of Mule-Aware Code
2327
2328 As an example of Mule-aware code, we shall will analyze the
2329 @code{string} function, which conses up a Lisp string from the character
2330 arguments it receives.  Here is the definition, pasted from
2331 @code{alloc.c}:
2332
2333 @example
2334 @group
2335 DEFUN ("string", Fstring, 0, MANY, 0, /*
2336 Concatenate all the argument characters and make the result a string.
2337 */
2338        (int nargs, Lisp_Object *args))
2339 @{
2340   Bufbyte *storage = alloca_array (Bufbyte, nargs * MAX_EMCHAR_LEN);
2341   Bufbyte *p = storage;
2342
2343   for (; nargs; nargs--, args++)
2344     @{
2345       Lisp_Object lisp_char = *args;
2346       CHECK_CHAR_COERCE_INT (lisp_char);
2347       p += set_charptr_emchar (p, XCHAR (lisp_char));
2348     @}
2349   return make_string (storage, p - storage);
2350 @}
2351 @end group
2352 @end example
2353
2354 Now we can analyze the source line by line.
2355
2356 Obviously, string will be as long as there are arguments to the
2357 function.  This is why we allocate @code{MAX_EMCHAR_LEN} * @var{nargs}
2358 bytes on the stack, i.e. the worst-case number of bytes for @var{nargs}
2359 @code{Emchar}s to fit in the string.
2360
2361 Then, the loop checks that each element is a character, converting
2362 integers in the process.  Like many other functions in XEmacs, this
2363 function silently accepts integers where characters are expected, for
2364 historical and compatibility reasons.  Unless you know what you are
2365 doing, @code{CHECK_CHAR} will also suffice.  @code{XCHAR (lisp_char)}
2366 extracts the @code{Emchar} from the @code{Lisp_Object}, and
2367 @code{set_charptr_emchar} stores it to storage, increasing @code{p} in
2368 the process.
2369
2370 Other instructing examples of correct coding under Mule can be found all
2371 over XEmacs code.  For starters, I recommend
2372 @code{Fnormalize_menu_item_name} in @file{menubar.c}.  After you have
2373 understood this section of the manual and studied the examples, you can
2374 proceed writing new Mule-aware code.
2375
2376 @node Techniques for XEmacs Developers
2377 @section Techniques for XEmacs Developers
2378
2379 To make a quantified XEmacs, do: @code{make quantmacs}.
2380
2381 You simply can't dump Quantified and Purified images.  Run the image
2382 like so:  @code{quantmacs -batch -l loadup.el run-temacs -q}.
2383
2384 Before you go through the trouble, are you compiling with all
2385 debugging and error-checking off?  If not try that first.  Be warned
2386 that while Quantify is directly responsible for quite a few
2387 optimizations which have been made to XEmacs, doing a run which
2388 generates results which can be acted upon is not necessarily a trivial
2389 task.
2390
2391 Also, if you're still willing to do some runs make sure you configure
2392 with the @samp{--quantify} flag.  That will keep Quantify from starting
2393 to record data until after the loadup is completed and will shut off
2394 recording right before it shuts down (which generates enough bogus data
2395 to throw most results off).  It also enables three additional elisp
2396 commands: @code{quantify-start-recording-data},
2397 @code{quantify-stop-recording-data} and @code{quantify-clear-data}.
2398
2399 To get started debugging XEmacs, take a look at the @file{gdbinit} and
2400 @file{dbxrc} files in the @file{src} directory.  
2401 @xref{Q2.1.15 - How to Debug an XEmacs problem with a debugger,,, 
2402 xemacs-faq, XEmacs FAQ}.
2403
2404
2405 Here are things to know when you create a new source file:
2406
2407 @itemize @bullet
2408 @item
2409 All .c files should @code{#include <config.h>} first.  Almost all .c
2410 files should @code{#include "lisp.h"} second.
2411
2412 @item
2413 Generated header files should be included using the @code{<>} syntax,
2414 not the @code{""} syntax.  The generated headers are:
2415
2416 config.h puresize-adjust.h sheap-adjust.h paths.h Emacs.ad.h
2417
2418 The basic rule is that you should assume builds using @code{--srcdir}
2419 and the @code{<>} syntax needs to be used when the to-be-included
2420 generated file is in a potentially different directory 
2421 @emph{at compile time}.
2422
2423 @item 
2424 Header files should not include <config.h> and "lisp.h".   It is the
2425 responsibility of the .c files that use it to do so.
2426
2427 @item 
2428 If the header uses INLINE, either directly or though DECLARE_LRECORD,
2429 then it must be added to inline.c's includes.
2430
2431 @item
2432 Try compiling at least once with 
2433
2434 @example
2435 gcc --with-mule --with-union-type --error-checking=all
2436 @end example
2437 @end itemize
2438
2439 @node A Summary of the Various XEmacs Modules, Allocation of Objects in XEmacs Lisp, Rules When Writing New C Code, Top
2440 @chapter A Summary of the Various XEmacs Modules
2441
2442   This is accurate as of XEmacs 20.0.
2443
2444 @menu
2445 * Low-Level Modules::
2446 * Basic Lisp Modules::
2447 * Modules for Standard Editing Operations::
2448 * Editor-Level Control Flow Modules::
2449 * Modules for the Basic Displayable Lisp Objects::
2450 * Modules for other Display-Related Lisp Objects::
2451 * Modules for the Redisplay Mechanism::
2452 * Modules for Interfacing with the File System::
2453 * Modules for Other Aspects of the Lisp Interpreter and Object System::
2454 * Modules for Interfacing with the Operating System::
2455 * Modules for Interfacing with X Windows::
2456 * Modules for Internationalization::
2457 @end menu
2458
2459 @node Low-Level Modules
2460 @section Low-Level Modules
2461
2462 @example
2463    size  name
2464 -------  ---------------------
2465   18150  config.h
2466 @end example
2467
2468 This is automatically generated from @file{config.h.in} based on the
2469 results of configure tests and user-selected optional features and
2470 contains preprocessor definitions specifying the nature of the
2471 environment in which XEmacs is being compiled.
2472
2473
2474
2475 @example
2476    2347  paths.h
2477 @end example
2478
2479 This is automatically generated from @file{paths.h.in} based on supplied
2480 configure values, and allows for non-standard installed configurations
2481 of the XEmacs directories.  It's currently broken, though.
2482
2483
2484
2485 @example
2486   47878  emacs.c
2487   20239  signal.c
2488 @end example
2489
2490 @file{emacs.c} contains @code{main()} and other code that performs the most
2491 basic environment initializations and handles shutting down the XEmacs
2492 process (this includes @code{kill-emacs}, the normal way that XEmacs is
2493 exited; @code{dump-emacs}, which is used during the build process to
2494 write out the XEmacs executable; @code{run-emacs-from-temacs}, which can
2495 be used to start XEmacs directly when temacs has finished loading all
2496 the Lisp code; and emergency code to handle crashes [XEmacs tries to
2497 auto-save all files before it crashes]).
2498
2499 Low-level code that directly interacts with the Unix signal mechanism,
2500 however, is in @file{signal.c}.  Note that this code does not handle system
2501 dependencies in interfacing to signals; that is handled using the
2502 @file{syssignal.h} header file, described in section J below.
2503
2504
2505
2506 @example
2507   23458  unexaix.c
2508    9893  unexalpha.c
2509   11302  unexapollo.c
2510   16544  unexconvex.c
2511   31967  unexec.c
2512   30959  unexelf.c
2513   35791  unexelfsgi.c
2514    3207  unexencap.c
2515    7276  unexenix.c
2516   20539  unexfreebsd.c
2517    1153  unexfx2800.c
2518   13432  unexhp9k3.c
2519   11049  unexhp9k800.c
2520    9165  unexmips.c
2521    8981  unexnext.c
2522    1673  unexsol2.c
2523   19261  unexsunos4.c
2524 @end example
2525
2526 These modules contain code dumping out the XEmacs executable on various
2527 different systems. (This process is highly machine-specific and
2528 requires intimate knowledge of the executable format and the memory map
2529 of the process.) Only one of these modules is actually used; this is
2530 chosen by @file{configure}.
2531
2532
2533
2534 @example
2535   15715  crt0.c
2536    1484  lastfile.c
2537    1115  pre-crt0.c
2538 @end example
2539
2540 These modules are used in conjunction with the dump mechanism.  On some
2541 systems, an alternative version of the C startup code (the actual code
2542 that receives control from the operating system when the process is
2543 started, and which calls @code{main()}) is required so that the dumping
2544 process works properly; @file{crt0.c} provides this.
2545
2546 @file{pre-crt0.c} and @file{lastfile.c} should be the very first and
2547 very last file linked, respectively. (Actually, this is not really true.
2548 @file{lastfile.c} should be after all Emacs modules whose initialized
2549 data should be made constant, and before all other Emacs files and all
2550 libraries.  In particular, the allocation modules @file{gmalloc.c},
2551 @file{alloca.c}, etc. are normally placed past @file{lastfile.c}, and
2552 all of the files that implement Xt widget classes @emph{must} be placed
2553 after @file{lastfile.c} because they contain various structures that
2554 must be statically initialized and into which Xt writes at various
2555 times.) @file{pre-crt0.c} and @file{lastfile.c} contain exported symbols
2556 that are used to determine the start and end of XEmacs' initialized
2557 data space when dumping.
2558
2559
2560
2561 @example
2562   14786  alloca.c
2563   16678  free-hook.c
2564    1692  getpagesize.h
2565   41936  gmalloc.c
2566   25141  malloc.c
2567    3802  mem-limits.h
2568   39011  ralloc.c
2569    3436  vm-limit.c
2570 @end example
2571
2572 These handle basic C allocation of memory.  @file{alloca.c} is an emulation of
2573 the stack allocation function @code{alloca()} on machines that lack
2574 this. (XEmacs makes extensive use of @code{alloca()} in its code.)
2575
2576 @file{gmalloc.c} and @file{malloc.c} are two implementations of the standard C
2577 functions @code{malloc()}, @code{realloc()} and @code{free()}.  They are
2578 often used in place of the standard system-provided @code{malloc()}
2579 because they usually provide a much faster implementation, at the
2580 expense of additional memory use.  @file{gmalloc.c} is a newer implementation
2581 that is much more memory-efficient for large allocations than @file{malloc.c},
2582 and should always be preferred if it works. (At one point, @file{gmalloc.c}
2583 didn't work on some systems where @file{malloc.c} worked; but this should be
2584 fixed now.)
2585
2586 @cindex relocating allocator
2587 @file{ralloc.c} is the @dfn{relocating allocator}.  It provides functions
2588 similar to @code{malloc()}, @code{realloc()} and @code{free()} that allocate
2589 memory that can be dynamically relocated in memory.  The advantage of
2590 this is that allocated memory can be shuffled around to place all the
2591 free memory at the end of the heap, and the heap can then be shrunk,
2592 releasing the memory back to the operating system.  The use of this can
2593 be controlled with the configure option @code{--rel-alloc}; if enabled, memory allocated for
2594 buffers will be relocatable, so that if a very large file is visited and
2595 the buffer is later killed, the memory can be released to the operating
2596 system.  (The disadvantage of this mechanism is that it can be very
2597 slow.  On systems with the @code{mmap()} system call, the XEmacs version
2598 of @file{ralloc.c} uses this to move memory around without actually having to
2599 block-copy it, which can speed things up; but it can still cause
2600 noticeable performance degradation.)
2601
2602 @file{free-hook.c} contains some debugging functions for checking for invalid
2603 arguments to @code{free()}.
2604
2605 @file{vm-limit.c} contains some functions that warn the user when memory is
2606 getting low.  These are callback functions that are called by @file{gmalloc.c}
2607 and @file{malloc.c} at appropriate times.
2608
2609 @file{getpagesize.h} provides a uniform interface for retrieving the size of a
2610 page in virtual memory.  @file{mem-limits.h} provides a uniform interface for
2611 retrieving the total amount of available virtual memory.  Both are
2612 similar in spirit to the @file{sys*.h} files described in section J, below.
2613
2614
2615
2616 @example
2617    2659  blocktype.c
2618    1410  blocktype.h
2619    7194  dynarr.c
2620    2671  dynarr.h
2621 @end example
2622
2623 These implement a couple of basic C data types to facilitate memory
2624 allocation.  The @code{Blocktype} type efficiently manages the
2625 allocation of fixed-size blocks by minimizing the number of times that
2626 @code{malloc()} and @code{free()} are called.  It allocates memory in
2627 large chunks, subdivides the chunks into blocks of the proper size, and
2628 returns the blocks as requested.  When blocks are freed, they are placed
2629 onto a linked list, so they can be efficiently reused.  This data type
2630 is not much used in XEmacs currently, because it's a fairly new
2631 addition.
2632
2633 @cindex dynamic array
2634 The @code{Dynarr} type implements a @dfn{dynamic array}, which is
2635 similar to a standard C array but has no fixed limit on the number of
2636 elements it can contain.  Dynamic arrays can hold elements of any type,
2637 and when you add a new element, the array automatically resizes itself
2638 if it isn't big enough.  Dynarrs are extensively used in the redisplay
2639 mechanism.
2640
2641
2642
2643 @example
2644    2058  inline.c
2645 @end example
2646
2647 This module is used in connection with inline functions (available in
2648 some compilers).  Often, inline functions need to have a corresponding
2649 non-inline function that does the same thing.  This module is where they
2650 reside.  It contains no actual code, but defines some special flags that
2651 cause inline functions defined in header files to be rendered as actual
2652 functions.  It then includes all header files that contain any inline
2653 function definitions, so that each one gets a real function equivalent.
2654
2655
2656
2657 @example
2658    6489  debug.c
2659    2267  debug.h
2660 @end example
2661
2662 These functions provide a system for doing internal consistency checks
2663 during code development.  This system is not currently used; instead the
2664 simpler @code{assert()} macro is used along with the various checks
2665 provided by the @samp{--error-check-*} configuration options.
2666
2667
2668
2669 @example
2670    1643  prefix-args.c
2671 @end example
2672
2673 This is actually the source for a small, self-contained program
2674 used during building.
2675
2676
2677 @example
2678     904  universe.h
2679 @end example
2680
2681 This is not currently used.
2682
2683
2684
2685 @node Basic Lisp Modules
2686 @section Basic Lisp Modules
2687
2688 @example
2689    size  name
2690 -------  ---------------------
2691   70167  emacsfns.h
2692    6305  lisp-disunion.h
2693    7086  lisp-union.h
2694   54929  lisp.h
2695   14235  lrecord.h
2696   10728  symsinit.h
2697 @end example
2698
2699 These are the basic header files for all XEmacs modules.  Each module
2700 includes @file{lisp.h}, which brings the other header files in.
2701 @file{lisp.h} contains the definitions of the structures and extractor
2702 and constructor macros for the basic Lisp objects and various other
2703 basic definitions for the Lisp environment, as well as some
2704 general-purpose definitions (e.g. @code{min()} and @code{max()}).
2705 @file{lisp.h} includes either @file{lisp-disunion.h} or
2706 @file{lisp-union.h}, depending on whether @code{USE_UNION_TYPE} is
2707 defined.  These files define the typedef of the Lisp object itself (as
2708 described above) and the low-level macros that hide the actual
2709 implementation of the Lisp object.  All extractor and constructor macros
2710 for particular types of Lisp objects are defined in terms of these
2711 low-level macros.
2712
2713 As a general rule, all typedefs should go into the typedefs section of
2714 @file{lisp.h} rather than into a module-specific header file even if the
2715 structure is defined elsewhere.  This allows function prototypes that
2716 use the typedef to be placed into @file{emacsfns.h}.  Forward structure
2717 declarations (i.e. a simple declaration like @code{struct foo;} where
2718 the structure itself is defined elsewhere) should be placed into the
2719 typedefs section as necessary.
2720
2721 @file{lrecord.h} contains the basic structures and macros that implement
2722 all record-type Lisp objects -- i.e. all objects whose type is a field
2723 in their C structure, which includes all objects except the few most
2724 basic ones.
2725
2726 @file{emacsfns.h} contains prototypes for most of the exported functions
2727 in the various modules. (In particular, prototypes for Lisp primitives
2728 should always go into this header file.  Prototypes for other functions
2729 can either go here or in a module-specific header file, depending on how
2730 general-purpose the function is and whether it has special-purpose
2731 argument types requiring definitions not in @file{lisp.h}.)  All
2732 initialization functions are prototyped in @file{symsinit.h}.
2733
2734
2735
2736 @example
2737  120478  alloc.c
2738    1029  pure.c
2739    2506  puresize.h
2740 @end example
2741
2742 The large module @file{alloc.c} implements all of the basic allocation and
2743 garbage collection for Lisp objects.  The most commonly used Lisp
2744 objects are allocated in chunks, similar to the Blocktype data type
2745 described above; others are allocated in individually @code{malloc()}ed
2746 blocks.  This module provides the foundation on which all other aspects
2747 of the Lisp environment sit, and is the first module initialized at
2748 startup.
2749
2750 Note that @file{alloc.c} provides a series of generic functions that are
2751 not dependent on any particular object type, and interfaces to
2752 particular types of objects using a standardized interface of
2753 type-specific methods.  This scheme is a fundamental principle of
2754 object-oriented programming and is heavily used throughout XEmacs.  The
2755 great advantage of this is that it allows for a clean separation of
2756 functionality into different modules -- new classes of Lisp objects, new
2757 event interfaces, new device types, new stream interfaces, etc. can be
2758 added transparently without affecting code anywhere else in XEmacs.
2759 Because the different subsystems are divided into general and specific
2760 code, adding a new subtype within a subsystem will in general not
2761 require changes to the generic subsystem code or affect any of the other
2762 subtypes in the subsystem; this provides a great deal of robustness to
2763 the XEmacs code.
2764
2765 @cindex pure space
2766 @file{pure.c} contains the declaration of the @dfn{purespace} array.
2767 Pure space is a hack used to place some constant Lisp data into the code
2768 segment of the XEmacs executable, even though the data needs to be
2769 initialized through function calls.  (See above in section VIII for more
2770 info about this.)  During startup, certain sorts of data is
2771 automatically copied into pure space, and other data is copied manually
2772 in some of the basic Lisp files by calling the function @code{purecopy},
2773 which copies the object if possible (this only works in temacs, of
2774 course) and returns the new object.  In particular, while temacs is
2775 executing, the Lisp reader automatically copies all compiled-function
2776 objects that it reads into pure space.  Since compiled-function objects
2777 are large, are never modified, and typically comprise the majority of
2778 the contents of a compiled-Lisp file, this works well.  While XEmacs is
2779 running, any attempt to modify an object that resides in pure space
2780 causes an error.  Objects in pure space are never garbage collected --
2781 almost all of the time, they're intended to be permanent, and in any
2782 case you can't write into pure space to set the mark bits.
2783
2784 @file{puresize.h} contains the declaration of the size of the pure space
2785 array.  This depends on the optional features that are compiled in, any
2786 extra purespace requested by the user at compile time, and certain other
2787 factors (e.g. 64-bit machines need more pure space because their Lisp
2788 objects are larger).  The smallest size that suffices should be used, so
2789 that there's no wasted space.  If there's not enough pure space, you
2790 will get an error during the build process, specifying how much more
2791 pure space is needed.
2792
2793
2794
2795 @example
2796  122243  eval.c
2797    2305  backtrace.h
2798 @end example
2799
2800 This module contains all of the functions to handle the flow of control.
2801 This includes the mechanisms of defining functions, calling functions,
2802 traversing stack frames, and binding variables; the control primitives
2803 and other special forms such as @code{while}, @code{if}, @code{eval},
2804 @code{let}, @code{and}, @code{or}, @code{progn}, etc.; handling of
2805 non-local exits, unwind-protects, and exception handlers; entering the
2806 debugger; methods for the subr Lisp object type; etc.  It does
2807 @emph{not} include the @code{read} function, the @code{print} function,
2808 or the handling of symbols and obarrays.
2809
2810 @file{backtrace.h} contains some structures related to stack frames and the
2811 flow of control.
2812
2813
2814
2815 @example
2816   64949  lread.c
2817 @end example
2818
2819 This module implements the Lisp reader and the @code{read} function,
2820 which converts text into Lisp objects, according to the read syntax of
2821 the objects, as described above.  This is similar to the parser that is
2822 a part of all compilers.
2823
2824
2825
2826 @example
2827   40900  print.c
2828 @end example
2829
2830 This module implements the Lisp print mechanism and the @code{print}
2831 function and related functions.  This is the inverse of the Lisp reader
2832 -- it converts Lisp objects to a printed, textual representation.
2833 (Hopefully something that can be read back in using @code{read} to get
2834 an equivalent object.)
2835
2836
2837
2838 @example
2839    4518  general.c
2840   60220  symbols.c
2841    9966  symeval.h
2842 @end example
2843
2844 @file{symbols.c} implements the handling of symbols, obarrays, and
2845 retrieving the values of symbols.  Much of the code is devoted to
2846 handling the special @dfn{symbol-value-magic} objects that define
2847 special types of variables -- this includes buffer-local variables,
2848 variable aliases, variables that forward into C variables, etc.  This
2849 module is initialized extremely early (right after @file{alloc.c}),
2850 because it is here that the basic symbols @code{t} and @code{nil} are
2851 created, and those symbols are used everywhere throughout XEmacs.
2852
2853 @file{symeval.h} contains the definitions of symbol structures and the
2854 @code{DEFVAR_LISP()} and related macros for declaring variables.
2855
2856
2857
2858 @example
2859   48973  data.c
2860   25694  floatfns.c
2861   71049  fns.c
2862 @end example
2863
2864 These modules implement the methods and standard Lisp primitives for all
2865 the basic Lisp object types other than symbols (which are described
2866 above).  @file{data.c} contains all the predicates (primitives that return
2867 whether an object is of a particular type); the integer arithmetic
2868 functions; and the basic accessor and mutator primitives for the various
2869 object types.  @file{fns.c} contains all the standard predicates for working
2870 with sequences (where, abstractly speaking, a sequence is an ordered set
2871 of objects, and can be represented by a list, string, vector, or
2872 bit-vector); it also contains @code{equal}, perhaps on the grounds that
2873 bulk of the operation of @code{equal} is comparing sequences.
2874 @file{floatfns.c} contains methods and primitives for floats and floating-point
2875 arithmetic.
2876
2877
2878
2879 @example
2880   23555  bytecode.c
2881    3358  bytecode.h
2882 @end example
2883
2884 @file{bytecode.c} implements the byte-code interpreter, and @file{bytecode.h} contains
2885 associated structures.  Note that the byte-code @emph{compiler} is
2886 written in Lisp.
2887
2888
2889
2890
2891 @node Modules for Standard Editing Operations
2892 @section Modules for Standard Editing Operations
2893
2894 @example
2895    size  name
2896 -------  ---------------------
2897   82900  buffer.c
2898   60964  buffer.h
2899    6059  bufslots.h
2900 @end example
2901
2902 @file{buffer.c} implements the @dfn{buffer} Lisp object type.  This
2903 includes functions that create and destroy buffers; retrieve buffers by
2904 name or by other properties; manipulate lists of buffers (remember that
2905 buffers are permanent objects and stored in various ordered lists);
2906 retrieve or change buffer properties; etc.  It also contains the
2907 definitions of all the built-in buffer-local variables (which can be
2908 viewed as buffer properties).  It does @emph{not} contain code to
2909 manipulate buffer-local variables (that's in @file{symbols.c}, described
2910 above); or code to manipulate the text in a buffer.
2911
2912 @file{buffer.h} defines the structures associated with a buffer and the various
2913 macros for retrieving text from a buffer and special buffer positions
2914 (e.g. @code{point}, the default location for text insertion).  It also
2915 contains macros for working with buffer positions and converting between
2916 their representations as character offsets and as byte offsets (under
2917 MULE, they are different, because characters can be multi-byte).  It is
2918 one of the largest header files.
2919
2920 @file{bufslots.h} defines the fields in the buffer structure that correspond to
2921 the built-in buffer-local variables.  It is its own header file because
2922 it is included many times in @file{buffer.c}, as a way of iterating over all
2923 the built-in buffer-local variables.
2924
2925
2926
2927 @example
2928   79888  insdel.c
2929    6103  insdel.h
2930 @end example
2931
2932 @file{insdel.c} contains low-level functions for inserting and deleting text in
2933 a buffer, keeping track of changed regions for use by redisplay, and
2934 calling any before-change and after-change functions that may have been
2935 registered for the buffer.  It also contains the actual functions that
2936 convert between byte offsets and character offsets.
2937
2938 @file{insdel.h} contains associated headers.
2939
2940
2941
2942 @example
2943   10975  marker.c
2944 @end example
2945
2946 This module implements the @dfn{marker} Lisp object type, which
2947 conceptually is a pointer to a text position in a buffer that moves
2948 around as text is inserted and deleted, so as to remain in the same
2949 relative position.  This module doesn't actually move the markers around
2950 -- that's handled in @file{insdel.c}.  This module just creates them and
2951 implements the primitives for working with them.  As markers are simple
2952 objects, this does not entail much.
2953
2954 Note that the standard arithmetic primitives (e.g. @code{+}) accept
2955 markers in place of integers and automatically substitute the value of
2956 @code{marker-position} for the marker, i.e. an integer describing the
2957 current buffer position of the marker.
2958
2959
2960
2961 @example
2962  193714  extents.c
2963   15686  extents.h
2964 @end example
2965
2966 This module implements the @dfn{extent} Lisp object type, which is like
2967 a marker that works over a range of text rather than a single position.
2968 Extents are also much more complex and powerful than markers and have a
2969 more efficient (and more algorithmically complex) implementation.  The
2970 implementation is described in detail in comments in @file{extents.c}.
2971
2972 The code in @file{extents.c} works closely with @file{insdel.c} so that
2973 extents are properly moved around as text is inserted and deleted.
2974 There is also code in @file{extents.c} that provides information needed
2975 by the redisplay mechanism for efficient operation. (Remember that
2976 extents can have display properties that affect [sometimes drastically,
2977 as in the @code{invisible} property] the display of the text they
2978 cover.)
2979
2980
2981
2982 @example
2983   60155  editfns.c
2984 @end example
2985
2986 @file{editfns.c} contains the standard Lisp primitives for working with
2987 a buffer's text, and calls the low-level functions in @file{insdel.c}.
2988 It also contains primitives for working with @code{point} (the default
2989 buffer insertion location).
2990
2991 @file{editfns.c} also contains functions for retrieving various
2992 characteristics from the external environment: the current time, the
2993 process ID of the running XEmacs process, the name of the user who ran
2994 this XEmacs process, etc.  It's not clear why this code is in
2995 @file{editfns.c}.
2996
2997
2998
2999 @example
3000   26081  callint.c
3001   12577  cmds.c
3002    2749  commands.h
3003 @end example
3004
3005 @cindex interactive
3006 These modules implement the basic @dfn{interactive} commands,
3007 i.e. user-callable functions.  Commands, as opposed to other functions,
3008 have special ways of getting their parameters interactively (by querying
3009 the user), as opposed to having them passed in a normal function
3010 invocation.  Many commands are not really meant to be called from other
3011 Lisp functions, because they modify global state in a way that's often
3012 undesired as part of other Lisp functions.
3013
3014 @file{callint.c} implements the mechanism for querying the user for
3015 parameters and calling interactive commands.  The bulk of this module is
3016 code that parses the interactive spec that is supplied with an
3017 interactive command.
3018
3019 @file{cmds.c} implements the basic, most commonly used editing commands:
3020 commands to move around the current buffer and insert and delete
3021 characters.  These commands are implemented using the Lisp primitives
3022 defined in @file{editfns.c}.
3023
3024 @file{commands.h} contains associated structure definitions and prototypes.
3025
3026
3027
3028 @example
3029  194863  regex.c
3030   18968  regex.h
3031   79800  search.c
3032 @end example
3033
3034 @file{search.c} implements the Lisp primitives for searching for text in
3035 a buffer, and some of the low-level algorithms for doing this.  In
3036 particular, the fast fixed-string Boyer-Moore search algorithm is
3037 implemented in @file{search.c}.  The low-level algorithms for doing
3038 regular-expression searching, however, are implemented in @file{regex.c}
3039 and @file{regex.h}.  These two modules are largely independent of
3040 XEmacs, and are similar to (and based upon) the regular-expression
3041 routines used in @file{grep} and other GNU utilities.
3042
3043
3044
3045 @example
3046   20476  doprnt.c
3047 @end example
3048
3049 @file{doprnt.c} implements formatted-string processing, similar to
3050 @code{printf()} command in C.
3051
3052
3053
3054 @example
3055   15372  undo.c
3056 @end example
3057
3058 This module implements the undo mechanism for tracking buffer changes.
3059 Most of this could be implemented in Lisp.
3060
3061
3062
3063 @node Editor-Level Control Flow Modules
3064 @section Editor-Level Control Flow Modules
3065
3066 @example
3067    size  name
3068 -------  ---------------------
3069   84546  event-Xt.c
3070  121483  event-stream.c
3071    6658  event-tty.c
3072   49271  events.c
3073   14459  events.h
3074 @end example
3075
3076 These implement the handling of events (user input and other system
3077 notifications).
3078
3079 @file{events.c} and @file{events.h} define the @dfn{event} Lisp object
3080 type and primitives for manipulating it.
3081
3082 @file{event-stream.c} implements the basic functions for working with
3083 event queues, dispatching an event by looking it up in relevant keymaps
3084 and such, and handling timeouts; this includes the primitives
3085 @code{next-event} and @code{dispatch-event}, as well as related
3086 primitives such as @code{sit-for}, @code{sleep-for}, and
3087 @code{accept-process-output}. (@file{event-stream.c} is one of the
3088 hairiest and trickiest modules in XEmacs.  Beware!  You can easily mess
3089 things up here.)
3090
3091 @file{event-Xt.c} and @file{event-tty.c} implement the low-level
3092 interfaces onto retrieving events from Xt (the X toolkit) and from TTY's
3093 (using @code{read()} and @code{select()}), respectively.  The event
3094 interface enforces a clean separation between the specific code for
3095 interfacing with the operating system and the generic code for working
3096 with events, by defining an API of basic, low-level event methods;
3097 @file{event-Xt.c} and @file{event-tty.c} are two different
3098 implementations of this API.  To add support for a new operating system
3099 (e.g. NeXTstep), one merely needs to provide another implementation of
3100 those API functions.
3101
3102 Note that the choice of whether to use @file{event-Xt.c} or
3103 @file{event-tty.c} is made at compile time!  Or at the very latest, it
3104 is made at startup time.  @file{event-Xt.c} handles events for
3105 @emph{both} X and TTY frames; @file{event-tty.c} is only used when X
3106 support is not compiled into XEmacs.  The reason for this is that there
3107 is only one event loop in XEmacs: thus, it needs to be able to receive
3108 events from all different kinds of frames.
3109
3110
3111
3112 @example
3113  129583  keymap.c
3114    2621  keymap.h
3115 @end example
3116
3117 @file{keymap.c} and @file{keymap.h} define the @dfn{keymap} Lisp object
3118 type and associated methods and primitives. (Remember that keymaps are
3119 objects that associate event descriptions with functions to be called to
3120 ``execute'' those events; @code{dispatch-event} looks up events in the
3121 relevant keymaps.)
3122
3123
3124
3125 @example
3126   25212  keyboard.c
3127 @end example
3128
3129 @file{keyboard.c} contains functions that implement the actual editor
3130 command loop -- i.e. the event loop that cyclically retrieves and
3131 dispatches events.  This code is also rather tricky, just like
3132 @file{event-stream.c}.
3133
3134
3135
3136 @example
3137    9973  macros.c
3138    1397  macros.h
3139 @end example
3140
3141 These two modules contain the basic code for defining keyboard macros.
3142 These functions don't actually do much; most of the code that handles keyboard
3143 macros is mixed in with the event-handling code in @file{event-stream.c}.
3144
3145
3146
3147 @example
3148   23234  minibuf.c
3149 @end example
3150
3151 This contains some miscellaneous code related to the minibuffer (most of
3152 the minibuffer code was moved into Lisp by Richard Mlynarik).  This
3153 includes the primitives for completion (although filename completion is
3154 in @file{dired.c}), the lowest-level interface to the minibuffer (if the
3155 command loop were cleaned up, this too could be in Lisp), and code for
3156 dealing with the echo area (this, too, was mostly moved into Lisp, and
3157 the only code remaining is code to call out to Lisp or provide simple
3158 bootstrapping implementations early in temacs, before the echo-area Lisp
3159 code is loaded).
3160
3161
3162
3163 @node Modules for the Basic Displayable Lisp Objects
3164 @section Modules for the Basic Displayable Lisp Objects
3165
3166 @example
3167    size  name
3168 -------  ---------------------
3169     985  device-ns.h
3170    6454  device-stream.c
3171    1196  device-stream.h
3172    9526  device-tty.c
3173    8660  device-tty.h
3174   43798  device-x.c
3175   11667  device-x.h
3176   26056  device.c
3177   22993  device.h
3178 @end example
3179
3180 These modules implement the @dfn{device} Lisp object type.  This
3181 abstracts a particular screen or connection on which frames are
3182 displayed.  As with Lisp objects, event interfaces, and other
3183 subsystems, the device code is separated into a generic component that
3184 contains a standardized interface (in the form of a set of methods) onto
3185 particular device types.
3186
3187 The device subsystem defines all the methods and provides method
3188 services for not only device operations but also for the frame, window,
3189 menubar, scrollbar, toolbar, and other displayable-object subsystems.
3190 The reason for this is that all of these subsystems have the same
3191 subtypes (X, TTY, NeXTstep, Microsoft Windows, etc.) as devices do.
3192
3193
3194
3195 @example
3196     934  frame-ns.h
3197    2303  frame-tty.c
3198   69205  frame-x.c
3199    5976  frame-x.h
3200   68175  frame.c
3201   15080  frame.h
3202 @end example
3203
3204 Each device contains one or more frames in which objects (e.g. text) are
3205 displayed.  A frame corresponds to a window in the window system;
3206 usually this is a top-level window but it could potentially be one of a
3207 number of overlapping child windows within a top-level window, using the
3208 MDI (Multiple Document Interface) protocol in Microsoft Windows or a
3209 similar scheme.
3210
3211 The @file{frame-*} files implement the @dfn{frame} Lisp object type and
3212 provide the generic and device-type-specific operations on frames
3213 (e.g. raising, lowering, resizing, moving, etc.).
3214
3215
3216
3217 @example
3218  160783  window.c
3219   15974  window.h
3220 @end example
3221
3222 @cindex window (in Emacs)
3223 @cindex pane
3224 Each frame consists of one or more non-overlapping @dfn{windows} (better
3225 known as @dfn{panes} in standard window-system terminology) in which a
3226 buffer's text can be displayed.  Windows can also have scrollbars
3227 displayed around their edges.
3228
3229 @file{window.c} and @file{window.h} implement the @dfn{window} Lisp
3230 object type and provide code to manage windows.  Since windows have no
3231 associated resources in the window system (the window system knows only
3232 about the frame; no child windows or anything are used for XEmacs
3233 windows), there is no device-type-specific code here; all of that code
3234 is part of the redisplay mechanism or the code for particular object
3235 types such as scrollbars.
3236
3237
3238
3239 @node Modules for other Display-Related Lisp Objects
3240 @section Modules for other Display-Related Lisp Objects
3241
3242 @example
3243    size  name
3244 -------  ---------------------
3245   54397  faces.c
3246   15173  faces.h
3247 @end example
3248
3249
3250
3251 @example
3252    4961  bitmaps.h
3253     954  glyphs-ns.h
3254  105345  glyphs-x.c
3255    4288  glyphs-x.h
3256   72102  glyphs.c
3257   16356  glyphs.h
3258 @end example
3259
3260
3261
3262 @example
3263     952  objects-ns.h
3264    9971  objects-tty.c
3265    1465  objects-tty.h
3266   32326  objects-x.c
3267    2806  objects-x.h
3268   31944  objects.c
3269    6809  objects.h
3270 @end example
3271
3272
3273
3274 @example
3275   57511  menubar-x.c
3276   11243  menubar.c
3277 @end example
3278
3279
3280
3281 @example
3282   25012  scrollbar-x.c
3283    2554  scrollbar-x.h
3284   26954  scrollbar.c
3285    2778  scrollbar.h
3286 @end example
3287
3288
3289
3290 @example
3291   23117  toolbar-x.c
3292   43456  toolbar.c
3293    4280  toolbar.h
3294 @end example
3295
3296
3297
3298 @example
3299   25070  font-lock.c
3300 @end example
3301
3302 This file provides C support for syntax highlighting -- i.e.
3303 highlighting different syntactic constructs of a source file in
3304 different colors, for easy reading.  The C support is provided so that
3305 this is fast.
3306
3307
3308
3309 @example
3310   32180  dgif_lib.c
3311    3999  gif_err.c
3312   10697  gif_lib.h
3313    9371  gifalloc.c
3314 @end example
3315
3316 These modules decode GIF-format image files, for use with glyphs.
3317
3318
3319
3320 @node Modules for the Redisplay Mechanism
3321 @section Modules for the Redisplay Mechanism
3322
3323 @example
3324    size  name
3325 -------  ---------------------
3326   38692  redisplay-output.c
3327   40835  redisplay-tty.c
3328   65069  redisplay-x.c
3329  234142  redisplay.c
3330   17026  redisplay.h
3331 @end example
3332
3333 These files provide the redisplay mechanism.  As with many other
3334 subsystems in XEmacs, there is a clean separation between the general
3335 and device-specific support.
3336
3337 @file{redisplay.c} contains the bulk of the redisplay engine.  These
3338 functions update the redisplay structures (which describe how the screen
3339 is to appear) to reflect any changes made to the state of any
3340 displayable objects (buffer, frame, window, etc.) since the last time
3341 that redisplay was called.  These functions are highly optimized to
3342 avoid doing more work than necessary (since redisplay is called
3343 extremely often and is potentially a huge time sink), and depend heavily
3344 on notifications from the objects themselves that changes have occurred,
3345 so that redisplay doesn't explicitly have to check each possible object.
3346 The redisplay mechanism also contains a great deal of caching to further
3347 speed things up; some of this caching is contained within the various
3348 displayable objects.
3349
3350 @file{redisplay-output.c} goes through the redisplay structures and converts
3351 them into calls to device-specific methods to actually output the screen
3352 changes.
3353
3354 @file{redisplay-x.c} and @file{redisplay-tty.c} are two implementations
3355 of these redisplay output methods, for X frames and TTY frames,
3356 respectively.
3357
3358
3359
3360 @example
3361   14129  indent.c
3362 @end example
3363
3364 This module contains various functions and Lisp primitives for
3365 converting between buffer positions and screen positions.  These
3366 functions call the redisplay mechanism to do most of the work, and then
3367 examine the redisplay structures to get the necessary information.  This
3368 module needs work.
3369
3370
3371
3372 @example
3373   14754  termcap.c
3374    2141  terminfo.c
3375    7253  tparam.c
3376 @end example
3377
3378 These files contain functions for working with the termcap (BSD-style)
3379 and terminfo (System V style) databases of terminal capabilities and
3380 escape sequences, used when XEmacs is displaying in a TTY.
3381
3382
3383
3384 @example
3385   10869  cm.c
3386    5876  cm.h
3387 @end example
3388
3389 These files provide some miscellaneous TTY-output functions and should
3390 probably be merged into @file{redisplay-tty.c}.
3391
3392
3393
3394 @node Modules for Interfacing with the File System
3395 @section Modules for Interfacing with the File System
3396
3397 @example
3398    size  name
3399 -------  ---------------------
3400   43362  lstream.c
3401   14240  lstream.h
3402 @end example
3403
3404 These modules implement the @dfn{stream} Lisp object type.  This is an
3405 internal-only Lisp object that implements a generic buffering stream.
3406 The idea is to provide a uniform interface onto all sources and sinks of
3407 data, including file descriptors, stdio streams, chunks of memory, Lisp
3408 buffers, Lisp strings, etc.  That way, I/O functions can be written to
3409 the stream interface and can transparently handle all possible sources
3410 and sinks.  (For example, the @code{read} function can read data from a
3411 file, a string, a buffer, or even a function that is called repeatedly
3412 to return data, without worrying about where the data is coming from or
3413 what-size chunks it is returned in.)
3414
3415 @cindex lstream
3416 Note that in the C code, streams are called @dfn{lstreams} (for ``Lisp
3417 streams'') to distinguish them from other kinds of streams, e.g. stdio
3418 streams and C++ I/O streams.
3419
3420 Similar to other subsystems in XEmacs, lstreams are separated into
3421 generic functions and a set of methods for the different types of
3422 lstreams.  @file{lstream.c} provides implementations of many different
3423 types of streams; others are provided, e.g., in @file{mule-coding.c}.
3424
3425
3426
3427 @example
3428  126926  fileio.c
3429 @end example
3430
3431 This implements the basic primitives for interfacing with the file
3432 system.  This includes primitives for reading files into buffers,
3433 writing buffers into files, checking for the presence or accessibility
3434 of files, canonicalizing file names, etc.  Note that these primitives
3435 are usually not invoked directly by the user: There is a great deal of
3436 higher-level Lisp code that implements the user commands such as
3437 @code{find-file} and @code{save-buffer}.  This is similar to the
3438 distinction between the lower-level primitives in @file{editfns.c} and
3439 the higher-level user commands in @file{commands.c} and
3440 @file{simple.el}.
3441
3442
3443
3444 @example
3445   10960  filelock.c
3446 @end example
3447
3448 This file provides functions for detecting clashes between different
3449 processes (e.g. XEmacs and some external process, or two different
3450 XEmacs processes) modifying the same file.  (XEmacs can optionally use
3451 the @file{lock/} subdirectory to provide a form of ``locking'' between
3452 different XEmacs processes.)  This module is also used by the low-level
3453 functions in @file{insdel.c} to ensure that, if the first modification
3454 is being made to a buffer whose corresponding file has been externally
3455 modified, the user is made aware of this so that the buffer can be
3456 synched up with the external changes if necessary.
3457
3458
3459 @example
3460    4527  filemode.c
3461 @end example
3462
3463 This file provides some miscellaneous functions that construct a
3464 @samp{rwxr-xr-x}-type permissions string (as might appear in an
3465 @file{ls}-style directory listing) given the information returned by the
3466 @code{stat()} system call.
3467
3468
3469
3470 @example
3471   22855  dired.c
3472    2094  ndir.h
3473 @end example
3474
3475 These files implement the XEmacs interface to directory searching.  This
3476 includes a number of primitives for determining the files in a directory
3477 and for doing filename completion. (Remember that generic completion is
3478 handled by a different mechanism, in @file{minibuf.c}.)
3479
3480 @file{ndir.h} is a header file used for the directory-searching
3481 emulation functions provided in @file{sysdep.c} (see section J below),
3482 for systems that don't provide any directory-searching functions. (On
3483 those systems, directories can be read directly as files, and parsed.)
3484
3485
3486
3487 @example
3488    4311  realpath.c
3489 @end example
3490
3491 This file provides an implementation of the @code{realpath()} function
3492 for expanding symbolic links, on systems that don't implement it or have
3493 a broken implementation.
3494
3495
3496
3497 @node Modules for Other Aspects of the Lisp Interpreter and Object System
3498 @section Modules for Other Aspects of the Lisp Interpreter and Object System
3499
3500 @example
3501    size  name
3502 -------  ---------------------
3503   22290  elhash.c
3504    2454  elhash.h
3505   12169  hash.c
3506    3369  hash.h
3507 @end example
3508
3509 These files implement the @dfn{hashtable} Lisp object type.
3510 @file{hash.c} and @file{hash.h} provide a generic C implementation of
3511 hash tables (which can stand independently of XEmacs), and
3512 @file{elhash.c} and @file{elhash.h} provide a Lisp interface onto the C
3513 hash tables using the hashtable Lisp object type.
3514
3515
3516
3517 @example
3518   95691  specifier.c
3519   11167  specifier.h
3520 @end example
3521
3522 This module implements the @dfn{specifier} Lisp object type.  This is
3523 primarily used for displayable properties, and allows for values that
3524 are specific to a particular buffer, window, frame, device, or device
3525 class, as well as a default value existing.  This is used, for example,
3526 to control the height of the horizontal scrollbar or the appearance of
3527 the @code{default}, @code{bold}, or other faces.  The specifier object
3528 consists of a number of specifications, each of which maps from a
3529 buffer, window, etc. to a value.  The function @code{specifier-instance}
3530 looks up a value given a window (from which a buffer, frame, and device
3531 can be derived).
3532
3533
3534 @example
3535   43058  chartab.c
3536    6503  chartab.h
3537    9918  casetab.c
3538 @end example
3539
3540 @file{chartab.c} and @file{chartab.h} implement the @dfn{char table}
3541 Lisp object type, which maps from characters or certain sorts of
3542 character ranges to Lisp objects.  The implementation of this object
3543 type is optimized for the internal representation of characters.  Char
3544 tables come in different types, which affect the allowed object types to
3545 which a character can be mapped and also dictate certain other
3546 properties of the char table.
3547
3548 @cindex case table
3549 @file{casetab.c} implements one sort of char table, the @dfn{case
3550 table}, which maps characters to other characters of possibly different
3551 case.  These are used by XEmacs to implement case-changing primitives
3552 and to do case-insensitive searching.
3553
3554
3555
3556 @example
3557   49593  syntax.c
3558   10200  syntax.h
3559 @end example
3560
3561 @cindex scanner
3562 This module implements @dfn{syntax tables}, another sort of char table
3563 that maps characters into syntax classes that define the syntax of these
3564 characters (e.g. a parenthesis belongs to a class of @samp{open}
3565 characters that have corresponding @samp{close} characters and can be
3566 nested).  This module also implements the Lisp @dfn{scanner}, a set of
3567 primitives for scanning over text based on syntax tables.  This is used,
3568 for example, to find the matching parenthesis in a command such as
3569 @code{forward-sexp}, and by @file{font-lock.c} to locate quoted strings,
3570 comments, etc.
3571
3572
3573
3574 @example
3575   10438  casefiddle.c
3576 @end example
3577
3578 This module implements various Lisp primitives for upcasing, downcasing
3579 and capitalizing strings or regions of buffers.
3580
3581
3582
3583 @example
3584   20234  rangetab.c
3585 @end example
3586
3587 This module implements the @dfn{range table} Lisp object type, which
3588 provides for a mapping from ranges of integers to arbitrary Lisp
3589 objects.
3590
3591
3592
3593 @example
3594    3201  opaque.c
3595    2206  opaque.h
3596 @end example
3597
3598 This module implements the @dfn{opaque} Lisp object type, an
3599 internal-only Lisp object that encapsulates an arbitrary block of memory
3600 so that it can be managed by the Lisp allocation system.  To create an
3601 opaque object, you call @code{make_opaque()}, passing a pointer to a
3602 block of memory.  An object is created that is big enough to hold the
3603 memory, which is copied into the object's storage.  The object will then
3604 stick around as long as you keep pointers to it, after which it will be
3605 automatically reclaimed.
3606
3607 @cindex mark method
3608 Opaque objects can also have an arbitrary @dfn{mark method} associated
3609 with them, in case the block of memory contains other Lisp objects that
3610 need to be marked for garbage-collection purposes. (If you need other
3611 object methods, such as a finalize method, you should just go ahead and
3612 create a new Lisp object type -- it's not hard.)
3613
3614
3615
3616 @example
3617    8783  abbrev.c
3618 @end example
3619
3620 This function provides a few primitives for doing dynamic abbreviation
3621 expansion.  In XEmacs, most of the code for this has been moved into
3622 Lisp.  Some C code remains for speed and because the primitive
3623 @code{self-insert-command} (which is executed for all self-inserting
3624 characters) hooks into the abbrev mechanism. (@code{self-insert-command}
3625 is itself in C only for speed.)
3626
3627
3628
3629 @example
3630   21934  doc.c
3631 @end example
3632
3633 This function provides primitives for retrieving the documentation
3634 strings of functions and variables.  These documentation strings contain
3635 certain special markers that get dynamically expanded (e.g. a
3636 reverse-lookup is performed on some named functions to retrieve their
3637 current key bindings).  Some documentation strings (in particular, for
3638 the built-in primitives and pre-loaded Lisp functions) are stored
3639 externally in a file @file{DOC} in the @file{lib-src/} directory and
3640 need to be fetched from that file. (Part of the build stage involves
3641 building this file, and another part involves constructing an index for
3642 this file and embedding it into the executable, so that the functions in
3643 @file{doc.c} do not have to search the entire @file{DOC} file to find
3644 the appropriate documentation string.)
3645
3646
3647
3648 @example
3649   13197  md5.c
3650 @end example
3651
3652 This function provides a Lisp primitive that implements the MD5 secure
3653 hashing scheme, used to create a large hash value of a string of data such that
3654 the data cannot be derived from the hash value.  This is used for
3655 various security applications on the Internet.
3656
3657
3658
3659
3660 @node Modules for Interfacing with the Operating System
3661 @section Modules for Interfacing with the Operating System
3662
3663 @example
3664    size  name
3665 -------  ---------------------
3666   33533  callproc.c
3667   89697  process.c
3668    4663  process.h
3669 @end example
3670
3671 These modules allow XEmacs to spawn and communicate with subprocesses
3672 and network connections.
3673
3674 @cindex synchronous subprocesses
3675 @cindex subprocesses, synchronous
3676   @file{callproc.c} implements (through the @code{call-process}
3677 primitive) what are called @dfn{synchronous subprocesses}.  This means
3678 that XEmacs runs a program, waits till it's done, and retrieves its
3679 output.  A typical example might be calling the @file{ls} program to get
3680 a directory listing.
3681
3682 @cindex asynchronous subprocesses
3683 @cindex subprocesses, asynchronous
3684   @file{process.c} and @file{process.h} implement @dfn{asynchronous
3685 subprocesses}.  This means that XEmacs starts a program and then
3686 continues normally, not waiting for the process to finish.  Data can be
3687 sent to the process or retrieved from it as it's running.  This is used
3688 for the @code{shell} command (which provides a front end onto a shell
3689 program such as @file{csh}), the mail and news readers implemented in
3690 XEmacs, etc.  The result of calling @code{start-process} to start a
3691 subprocess is a process object, a particular kind of object used to
3692 communicate with the subprocess.  You can send data to the process by
3693 passing the process object and the data to @code{send-process}, and you
3694 can specify what happens to data retrieved from the process by setting
3695 properties of the process object. (When the process sends data, XEmacs
3696 receives a process event, which says that there is data ready.  When
3697 @code{dispatch-event} is called on this event, it reads the data from
3698 the process and does something with it, as specified by the process
3699 object's properties.  Typically, this means inserting the data into a
3700 buffer or calling a function.) Another property of the process object is
3701 called the @dfn{sentinel}, which is a function that is called when the
3702 process terminates.
3703
3704 @cindex network connections
3705   Process objects are also used for network connections (connections to a
3706 process running on another machine).  Network connections are started
3707 with @code{open-network-stream} but otherwise work just like
3708 subprocesses.
3709
3710
3711
3712 @example
3713  136029  sysdep.c
3714    5986  sysdep.h
3715 @end example
3716
3717   These modules implement most of the low-level, messy operating-system
3718 interface code.  This includes various device control (ioctl) operations
3719 for file descriptors, TTY's, pseudo-terminals, etc. (usually this stuff
3720 is fairly system-dependent; thus the name of this module), and emulation
3721 of standard library functions and system calls on systems that don't
3722 provide them or have broken versions.
3723
3724
3725
3726 @example
3727    3605  sysdir.h
3728    6708  sysfile.h
3729    2027  sysfloat.h
3730    2918  sysproc.h
3731     745  syspwd.h
3732    7643  syssignal.h
3733    6892  systime.h
3734   12477  systty.h
3735    3487  syswait.h
3736 @end example
3737
3738 These header files provide consistent interfaces onto system-dependent
3739 header files and system calls.  The idea is that, instead of including a
3740 standard header file like @file{<sys/param.h>} (which may or may not
3741 exist on various systems) or having to worry about whether all system
3742 provide a particular preprocessor constant, or having to deal with the
3743 four different paradigms for manipulating signals, you just include the
3744 appropriate @file{sys*.h} header file, which includes all the right
3745 system header files, defines and missing preprocessor constants,
3746 provides a uniform interface onto system calls, etc.
3747
3748 @file{sysdir.h} provides a uniform interface onto directory-querying
3749 functions. (In some cases, this is in conjunction with emulation
3750 functions in @file{sysdep.c}.)
3751
3752 @file{sysfile.h} includes all the necessary header files for standard
3753 system calls (e.g. @code{read()}), ensures that all necessary
3754 @code{open()} and @code{stat()} preprocessor constants are defined, and
3755 possibly (usually) substitutes sugared versions of @code{read()},
3756 @code{write()}, etc. that automatically restart interrupted I/O
3757 operations.
3758
3759 @file{sysfloat.h} includes the necessary header files for floating-point
3760 operations.
3761
3762 @file{sysproc.h} includes the necessary header files for calling
3763 @code{select()}, @code{fork()}, @code{execve()}, socket operations, and
3764 the like, and ensures that the @code{FD_*()} macros for descriptor-set
3765 manipulations are available.
3766
3767 @file{syspwd.h} includes the necessary header files for obtaining
3768 information from @file{/etc/passwd} (the functions are emulated under
3769 VMS).
3770
3771 @file{syssignal.h} includes the necessary header files for
3772 signal-handling and provides a uniform interface onto the different
3773 signal-handling and signal-blocking paradigms.
3774
3775 @file{systime.h} includes the necessary header files and provides
3776 uniform interfaces for retrieving the time of day, setting file
3777 access/modification times, getting the amount of time used by the XEmacs
3778 process, etc.
3779
3780 @file{systty.h} buffers against the infinitude of different ways of
3781 controlling TTY's.
3782
3783 @file{syswait.h} provides a uniform way of retrieving the exit status
3784 from a @code{wait()}ed-on process (some systems use a union, others use
3785 an int).
3786
3787
3788
3789 @example
3790    7940  hpplay.c
3791   10920  libsst.c
3792    1480  libsst.h
3793    3260  libst.h
3794   15355  linuxplay.c
3795   15849  nas.c
3796   19133  sgiplay.c
3797   15411  sound.c
3798    7358  sunplay.c
3799 @end example
3800
3801 These files implement the ability to play various sounds on some types
3802 of computers.  You have to configure your XEmacs with sound support in
3803 order to get this capability.
3804
3805 @file{sound.c} provides the generic interface.  It implements various
3806 Lisp primitives and variables that let you specify which sounds should
3807 be played in certain conditions. (The conditions are identified by
3808 symbols, which are passed to @code{ding} to make a sound.  Various
3809 standard functions call this function at certain times; if sound support
3810 does not exist, a simple beep results.
3811
3812 @cindex native sound
3813 @cindex sound, native
3814 @file{sgiplay.c}, @file{sunplay.c}, @file{hpplay.c}, and
3815 @file{linuxplay.c} interface to the machine's speaker for various
3816 different kind of machines.  This is called @dfn{native} sound.
3817
3818 @cindex sound, network
3819 @cindex network sound
3820 @cindex NAS
3821 @file{nas.c} interfaces to a computer somewhere else on the network
3822 using the NAS (Network Audio Server) protocol, playing sounds on that
3823 machine.  This allows you to run XEmacs on a remote machine, with its
3824 display set to your local machine, and have the sounds be made on your
3825 local machine, provided that you have a NAS server running on your local
3826 machine.
3827
3828 @file{libsst.c}, @file{libsst.h}, and @file{libst.h} provide some
3829 additional functions for playing sound on a Sun SPARC but are not
3830 currently in use.
3831
3832
3833
3834 @example
3835   44368  tooltalk.c
3836    2137  tooltalk.h
3837 @end example
3838
3839 These two modules implement an interface to the ToolTalk protocol, which
3840 is an interprocess communication protocol implemented on some versions
3841 of Unix.  ToolTalk is a high-level protocol that allows processes to
3842 register themselves as providers of particular services; other processes
3843 can then request a service without knowing or caring exactly who is
3844 providing the service.  It is similar in spirit to the DDE protocol
3845 provided under Microsoft Windows.  ToolTalk is a part of the new CDE
3846 (Common Desktop Environment) specification and is used to connect the
3847 parts of the SPARCWorks development environment.
3848
3849
3850
3851 @example
3852   22695  getloadavg.c
3853 @end example
3854
3855 This module provides the ability to retrieve the system's current load
3856 average. (The way to do this is highly system-specific, unfortunately,
3857 and requires a lot of special-case code.)
3858
3859
3860
3861 @example
3862  148520  energize.c
3863    6896  energize.h
3864 @end example
3865
3866 This module provides code to interface to an Energize server (when
3867 XEmacs is used as part of Lucid's Energize development environment) and
3868 provides some other Energize-specific functions.  Much of the code in
3869 this module should be made more general-purpose and moved elsewhere, but
3870 is no longer very relevant now that Lucid is defunct.  It also hasn't
3871 worked since version 19.12, since nobody has been maintaining it.
3872
3873
3874
3875 @example
3876    2861  sunpro.c
3877 @end example
3878
3879 This module provides a small amount of code used internally at Sun to
3880 keep statistics on the usage of XEmacs.
3881
3882
3883
3884 @example
3885    5548  broken-sun.h
3886    3468  strcmp.c
3887    2179  strcpy.c
3888    1650  sunOS-fix.c
3889 @end example
3890
3891 These files provide replacement functions and prototypes to fix numerous
3892 bugs in early releases of SunOS 4.1.
3893
3894
3895
3896 @example
3897   11669  hftctl.c
3898 @end example
3899
3900 This module provides some terminal-control code necessary on versions of
3901 AIX prior to 4.1.
3902
3903
3904
3905 @example
3906    1776  acldef.h
3907    1602  chpdef.h
3908    9032  uaf.h
3909     105  vlimit.h
3910    7145  vms-pp.c
3911    1158  vms-pwd.h
3912   26532  vmsfns.c
3913    6038  vmsmap.c
3914     695  vmspaths.h
3915   17482  vmsproc.c
3916     469  vmsproc.h
3917 @end example
3918
3919 All of these files are used for VMS support, which has never worked in
3920 XEmacs.
3921
3922
3923
3924 @example
3925   28316  msdos.c
3926    1472  msdos.h
3927 @end example
3928
3929 These modules are used for MS-DOS support, which does not work in
3930 XEmacs.
3931
3932
3933
3934 @node Modules for Interfacing with X Windows
3935 @section Modules for Interfacing with X Windows
3936
3937 @example
3938    size  name
3939 -------  ---------------------
3940    3196  Emacs.ad.h
3941 @end example
3942
3943 A file generated from @file{Emacs.ad}, which contains XEmacs-supplied
3944 fallback resources (so that XEmacs has pretty defaults).
3945
3946
3947
3948 @example
3949   24242  EmacsFrame.c
3950    6979  EmacsFrame.h
3951    3351  EmacsFrameP.h
3952 @end example
3953
3954 These modules implement an Xt widget class that encapsulates a frame.
3955 This is for ease in integrating with Xt.  The EmacsFrame widget covers
3956 the entire X window except for the menubar; the scrollbars are
3957 positioned on top of the EmacsFrame widget.
3958
3959 @strong{Warning:} Abandon hope, all ye who enter here.  This code took
3960 an ungodly amount of time to get right, and is likely to fall apart
3961 mercilessly at the slightest change.  Such is life under Xt.
3962
3963
3964
3965 @example
3966    8178  EmacsManager.c
3967    1967  EmacsManager.h
3968    1895  EmacsManagerP.h
3969 @end example
3970
3971 These modules implement a simple Xt manager (i.e. composite) widget
3972 class that simply lets its children set whatever geometry they want.
3973 It's amazing that Xt doesn't provide this standardly, but on second
3974 thought, it makes sense, considering how amazingly broken Xt is.
3975
3976
3977 @example
3978   13188  EmacsShell-sub.c
3979    4588  EmacsShell.c
3980    2180  EmacsShell.h
3981    3133  EmacsShellP.h
3982 @end example
3983
3984 These modules implement two Xt widget classes that are subclasses of
3985 the TopLevelShell and TransientShell classes.  This is necessary to deal
3986 with more brokenness that Xt has sadistically thrust onto the backs of
3987 developers.
3988
3989
3990
3991 @example
3992    9673  xgccache.c
3993    1111  xgccache.h
3994 @end example
3995
3996 These modules provide functions for maintenance and caching of GC's
3997 (graphics contexts) under the X Window System.  This code is junky and
3998 needs to be rewritten.
3999
4000
4001
4002 @example
4003   69181  xselect.c
4004 @end example
4005
4006 @cindex selections
4007   This module provides an interface to the X Window System's concept of
4008 @dfn{selections}, the standard way for X applications to communicate
4009 with each other.
4010
4011
4012
4013 @example
4014     929  xintrinsic.h
4015    1038  xintrinsicp.h
4016    1579  xmmanagerp.h
4017    1585  xmprimitivep.h
4018 @end example
4019
4020 These header files are similar in spirit to the @file{sys*.h} files and buffer
4021 against different implementations of Xt and Motif.
4022
4023 @itemize @bullet
4024 @item
4025 @file{xintrinsic.h} should be included in place of @file{<Intrinsic.h>}.
4026 @item
4027 @file{xintrinsicp.h} should be included in place of @file{<IntrinsicP.h>}.
4028 @item
4029 @file{xmmanagerp.h} should be included in place of @file{<XmManagerP.h>}.
4030 @item
4031 @file{xmprimitivep.h} should be included in place of @file{<XmPrimitiveP.h>}.
4032 @end itemize
4033
4034
4035
4036 @example
4037   16930  xmu.c
4038     936  xmu.h
4039 @end example
4040
4041 These files provide an emulation of the Xmu library for those systems
4042 (i.e. HPUX) that don't provide it as a standard part of X.
4043
4044
4045
4046 @example
4047    4201  ExternalClient-Xlib.c
4048   18083  ExternalClient.c
4049    2035  ExternalClient.h
4050    2104  ExternalClientP.h
4051   22684  ExternalShell.c
4052    1709  ExternalShell.h
4053    1971  ExternalShellP.h
4054    2478  extw-Xlib.c
4055    1481  extw-Xlib.h
4056    6565  extw-Xt.c
4057    1430  extw-Xt.h
4058 @end example
4059
4060 @cindex external widget
4061   These files provide the @dfn{external widget} interface, which allows an
4062 XEmacs frame to appear as a widget in another application.  To do this,
4063 you have to configure with @samp{--external-widget}.
4064
4065 @file{ExternalShell*} provides the server (XEmacs) side of the
4066 connection.
4067
4068 @file{ExternalClient*} provides the client (other application) side of
4069 the connection.  These files are not compiled into XEmacs but are
4070 compiled into libraries that are then linked into your application.
4071
4072 @file{extw-*} is common code that is used for both the client and server.
4073
4074 Don't touch this code; something is liable to break if you do.
4075
4076
4077
4078 @example
4079   31014  epoch.c
4080 @end example
4081
4082 This file provides some additional, Epoch-compatible, functionality for
4083 interfacing to the X Window System.
4084
4085
4086
4087 @node Modules for Internationalization
4088 @section Modules for Internationalization
4089
4090 @example
4091    size  name
4092 -------  ---------------------
4093   42836  mule-canna.c
4094   16737  mule-ccl.c
4095   41080  mule-charset.c
4096   30176  mule-charset.h
4097  146844  mule-coding.c
4098   16588  mule-coding.h
4099    6996  mule-mcpath.c
4100    2899  mule-mcpath.h
4101   57158  mule-wnnfns.c
4102    3351  mule.c
4103 @end example
4104
4105 These files implement the MULE (Asian-language) support.  Note that MULE
4106 actually provides a general interface for all sorts of languages, not
4107 just Asian languages (although they are generally the most complicated
4108 to support).  This code is still in beta.
4109
4110 @file{mule-charset.*} and @file{mule-coding.*} provide the heart of the
4111 XEmacs MULE support.  @file{mule-charset.*} implements the @dfn{charset}
4112 Lisp object type, which encapsulates a character set (an ordered one- or
4113 two-dimensional set of characters, such as US ASCII or JISX0208 Japanese
4114 Kanji).  
4115
4116 @file{mule-coding.*} implements the @dfn{coding-system} Lisp object
4117 type, which encapsulates a method of converting between different
4118 encodings.  An encoding is a representation of a stream of characters,
4119 possibly from multiple character sets, using a stream of bytes or words,
4120 and defines (e.g.) which escape sequences are used to specify particular
4121 character sets, how the indices for a character are converted into bytes
4122 (sometimes this involves setting the high bit; sometimes complicated
4123 rearranging of the values takes place, as in the Shift-JIS encoding),
4124 etc.
4125
4126 @file{mule-ccl.c} provides the CCL (Code Conversion Language)
4127 interpreter.  CCL is similar in spirit to Lisp byte code and is used to
4128 implement converters for custom encodings.
4129
4130 @file{mule-canna.c} and @file{mule-wnnfns.c} implement interfaces to
4131 external programs used to implement the Canna and WNN input methods,
4132 respectively.  This is currently in beta.
4133
4134 @file{mule-mcpath.c} provides some functions to allow for pathnames
4135 containing extended characters.  This code is fragmentary, obsolete, and
4136 completely non-working.  Instead, @var{pathname-coding-system} is used
4137 to specify conversions of names of files and directories.  The standard
4138 C I/O functions like @samp{open()} are wrapped so that conversion occurs
4139 automatically.
4140
4141 @file{mule.c} provides a few miscellaneous things that should probably
4142 be elsewhere.
4143
4144
4145
4146 @example
4147    9400  intl.c
4148 @end example
4149
4150 This provides some miscellaneous internationalization code for
4151 implementing message translation and interfacing to the Ximp input
4152 method.  None of this code is currently working.
4153
4154
4155
4156 @example
4157    1764  iso-wide.h
4158 @end example
4159
4160 This contains leftover code from an earlier implementation of
4161 Asian-language support, and is not currently used.
4162
4163
4164
4165
4166 @node Allocation of Objects in XEmacs Lisp, Events and the Event Loop, A Summary of the Various XEmacs Modules, Top
4167 @chapter Allocation of Objects in XEmacs Lisp
4168
4169 @menu
4170 * Introduction to Allocation::
4171 * Garbage Collection::
4172 * GCPROing::
4173 * Integers and Characters::
4174 * Allocation from Frob Blocks::
4175 * lrecords::
4176 * Low-level allocation::
4177 * Pure Space::
4178 * Cons::
4179 * Vector::
4180 * Bit Vector::
4181 * Symbol::
4182 * Marker::
4183 * String::
4184 * Bytecode::
4185 @end menu
4186
4187 @node Introduction to Allocation
4188 @section Introduction to Allocation
4189
4190   Emacs Lisp, like all Lisps, has garbage collection.  This means that
4191 the programmer never has to explicitly free (destroy) an object; it
4192 happens automatically when the object becomes inaccessible.  Most
4193 experts agree that garbage collection is a necessity in a modern,
4194 high-level language.  Its omission from C stems from the fact that C was
4195 originally designed to be a nice abstract layer on top of assembly
4196 language, for writing kernels and basic system utilities rather than
4197 large applications.
4198
4199   Lisp objects can be created by any of a number of Lisp primitives.
4200 Most object types have one or a small number of basic primitives
4201 for creating objects.  For conses, the basic primitive is @code{cons};
4202 for vectors, the primitives are @code{make-vector} and @code{vector}; for
4203 symbols, the primitives are @code{make-symbol} and @code{intern}; etc.
4204 Some Lisp objects, especially those that are primarily used internally,
4205 have no corresponding Lisp primitives.  Every Lisp object, though,
4206 has at least one C primitive for creating it.
4207
4208   Recall from section (VII) that a Lisp object, as stored in a 32-bit
4209 or 64-bit word, has a mark bit, a few tag bits, and a ``value'' that
4210 occupies the remainder of the bits.  We can separate the different
4211 Lisp object types into four broad categories:
4212
4213 @itemize @bullet
4214 @item
4215 (a) Those for whom the value directly represents the contents of the
4216 Lisp object.  Only two types are in this category: integers and
4217 characters.  No special allocation or garbage collection is necessary
4218 for such objects.  Lisp objects of these types do not need to be 
4219 @code{GCPRO}ed.
4220 @end itemize
4221
4222   In the remaining three categories, the value is a pointer to a
4223 structure.
4224
4225 @itemize @bullet
4226 @item
4227 @cindex frob block
4228 (b) Those for whom the tag directly specifies the type.  Recall that
4229 there are only three tag bits; this means that at most five types can be
4230 specified this way.  The most commonly-used types are stored in this
4231 format; this includes conses, strings, vectors, and sometimes symbols.
4232 With the exception of vectors, objects in this category are allocated in
4233 @dfn{frob blocks}, i.e. large blocks of memory that are subdivided into
4234 individual objects.  This saves a lot on malloc overhead, since there
4235 are typically quite a lot of these objects around, and the objects are
4236 small.  (A cons, for example, occupies 8 bytes on 32-bit machines -- 4
4237 bytes for each of the two objects it contains.) Vectors are individually
4238 @code{malloc()}ed since they are of variable size.  (It would be
4239 possible, and desirable, to allocate vectors of certain small sizes out
4240 of frob blocks, but it isn't currently done.) Strings are handled
4241 specially: Each string is allocated in two parts, a fixed size structure
4242 containing a length and a data pointer, and the actual data of the
4243 string.  The former structure is allocated in frob blocks as usual, and
4244 the latter data is stored in @dfn{string chars blocks} and is relocated
4245 during garbage collection to eliminate holes.
4246 @end itemize
4247
4248   In the remaining two categories, the type is stored in the object
4249 itself.  The tag for all such objects is the generic @dfn{lrecord}
4250 (Lisp_Record) tag.  The first four bytes (or eight, for 64-bit machines)
4251 of the object's structure are a pointer to a structure that describes
4252 the object's type, which includes method pointers and a pointer to a
4253 string naming the type.  Note that it's possible to save some space by
4254 using a one- or two-byte tag, rather than a four- or eight-byte pointer
4255 to store the type, but it's not clear it's worth making the change.
4256
4257 @itemize @bullet
4258 @item
4259 (c) Those lrecords that are allocated in frob blocks (see above).  This
4260 includes the objects that are most common and relatively small, and
4261 includes floats, bytecodes, symbols (when not in category (b)), extents,
4262 events, and markers.  With the cleanup of frob blocks done in 19.12,
4263 it's not terribly hard to add more objects to this category, but it's a
4264 bit trickier than adding an object type to type (d) (esp. if the object
4265 needs a finalization method), and is not likely to save much space
4266 unless the object is small and there are many of them. (In fact, if
4267 there are very few of them, it might actually waste space.)
4268 @item
4269 (d) Those lrecords that are individually @code{malloc()}ed.  These are
4270 called @dfn{lcrecords}.  All other types are in this category.  Adding a
4271 new type to this category is comparatively easy, and all types added
4272 since 19.8 (when the current allocation scheme was devised, by Richard
4273 Mlynarik), with the exception of the character type, have been in this
4274 category.
4275 @end itemize
4276
4277   Note that bit vectors are a bit of a special case.  They are
4278 simple lrecords as in category (c), but are individually @code{malloc()}ed
4279 like vectors.  You can basically view them as exactly like vectors
4280 except that their type is stored in lrecord fashion rather than
4281 in directly-tagged fashion.
4282
4283   Note that FSF Emacs redesigned their object system in 19.29 to follow
4284 a similar scheme.  However, given RMS's expressed dislike for data
4285 abstraction, the FSF scheme is not nearly as clean or as easy to
4286 extend. (FSF calls items of type (c) @code{Lisp_Misc} and items of type
4287 (d) @code{Lisp_Vectorlike}, with separate tags for each, although
4288 @code{Lisp_Vectorlike} is also used for vectors.)
4289
4290 @node Garbage Collection
4291 @section Garbage Collection
4292 @cindex garbage collection
4293
4294 @cindex mark and sweep
4295   Garbage collection is simple in theory but tricky to implement.
4296 Emacs Lisp uses the oldest garbage collection method, called
4297 @dfn{mark and sweep}.  Garbage collection begins by starting with
4298 all accessible locations (i.e. all variables and other slots where
4299 Lisp objects might occur) and recursively traversing all objects
4300 accessible from those slots, marking each one that is found.
4301 We then go through all of memory and free each object that is
4302 not marked, and unmarking each object that is marked.  Note
4303 that ``all of memory'' means all currently allocated objects.
4304 Traversing all these objects means traversing all frob blocks,
4305 all vectors (which are chained in one big list), and all
4306 lcrecords (which are likewise chained).
4307
4308   Note that, when an object is marked, the mark has to occur
4309 inside of the object's structure, rather than in the 32-bit
4310 @code{Lisp_Object} holding the object's pointer; i.e. you can't just
4311 set the pointer's mark bit.  This is because there may be many
4312 pointers to the same object.  This means that the method of
4313 marking an object can differ depending on the type.  The
4314 different marking methods are approximately as follows:
4315
4316 @enumerate
4317 @item
4318 For conses, the mark bit of the car is set.
4319 @item
4320 For strings, the mark bit of the string's plist is set.
4321 @item
4322 For symbols when not lrecords, the mark bit of the
4323 symbol's plist is set.
4324 @item
4325 For vectors, the length is negated after adding 1.
4326 @item
4327 For lrecords, the pointer to the structure describing
4328 the type is changed (see below).
4329 @item
4330 Integers and characters do not need to be marked, since
4331 no allocation occurs for them.
4332 @end enumerate
4333
4334   The details of this are in the @code{mark_object()} function.
4335
4336   Note that any code that operates during garbage collection has
4337 to be especially careful because of the fact that some objects
4338 may be marked and as such may not look like they normally do.
4339 In particular:
4340
4341 @itemize @bullet
4342 Some object pointers may have their mark bit set.  This will make
4343 @code{FOOBARP()} predicates fail.  Use @code{GC_FOOBARP()} to deal with
4344 this.
4345 @item
4346 Even if you clear the mark bit, @code{FOOBARP()} will still fail
4347 for lrecords because the implementation pointer has been
4348 changed (see below).  @code{GC_FOOBARP()} will correctly deal with
4349 this.
4350 @item
4351 Vectors have their size field munged, so anything that
4352 looks at this field will fail.
4353 @item
4354 Note that @code{XFOOBAR()} macros @emph{will} work correctly on object
4355 pointers with their mark bit set, because the logical shift operations
4356 that remove the tag also remove the mark bit.
4357 @end itemize
4358
4359   Finally, note that garbage collection can be invoked explicitly
4360 by calling @code{garbage-collect} but is also called automatically
4361 by @code{eval}, once a certain amount of memory has been allocated
4362 since the last garbage collection (according to @code{gc-cons-threshold}).
4363
4364 @node GCPROing
4365 @section @code{GCPRO}ing
4366
4367 @code{GCPRO}ing is one of the ugliest and trickiest parts of Emacs
4368 internals.  The basic idea is that whenever garbage collection
4369 occurs, all in-use objects must be reachable somehow or
4370 other from one of the roots of accessibility.  The roots
4371 of accessibility are:
4372
4373 @enumerate
4374 @item
4375 All objects that have been @code{staticpro()}d.  This is used for
4376 any global C variables that hold Lisp objects.  A call to
4377 @code{staticpro()} happens implicitly as a result of any symbols
4378 declared with @code{defsymbol()} and any variables declared with
4379 @code{DEFVAR_FOO()}.  You need to explicitly call @code{staticpro()}
4380 (in the @code{vars_of_foo()} method of a module) for other global
4381 C variables holding Lisp objects. (This typically includes
4382 internal lists and such things.)
4383
4384 Note that @code{obarray} is one of the @code{staticpro()}d things.
4385 Therefore, all functions and variables get marked through this.
4386 @item
4387 Any shadowed bindings that are sitting on the @code{specpdl} stack.
4388 @item
4389 Any objects sitting in currently active (Lisp) stack frames,
4390 catches, and condition cases.
4391 @item
4392 A couple of special-case places where active objects are
4393 located.
4394 @item
4395 Anything currently marked with @code{GCPRO}.
4396 @end enumerate
4397
4398   Marking with @code{GCPRO} is necessary because some C functions (quite
4399 a lot, in fact), allocate objects during their operation.  Quite
4400 frequently, there will be no other pointer to the object while the
4401 function is running, and if a garbage collection occurs and the object
4402 needs to be referenced again, bad things will happen.  The solution is
4403 to mark those objects with @code{GCPRO}.  Unfortunately this is easy to
4404 forget, and there is basically no way around this problem.  Here are
4405 some rules, though:
4406
4407 @enumerate
4408 @item
4409 For every @code{GCPRO@var{n}}, there have to be declarations of
4410 @code{struct gcpro gcpro1, gcpro2}, etc.
4411
4412 @item
4413 You @emph{must} @code{UNGCPRO} anything that's @code{GCPRO}ed, and you
4414 @emph{must not} @code{UNGCPRO} if you haven't @code{GCPRO}ed.  Getting
4415 either of these wrong will lead to crashes, often in completely random
4416 places unrelated to where the problem lies.
4417
4418 @item
4419 The way this actually works is that all currently active @code{GCPRO}s
4420 are chained through the @code{struct gcpro} local variables, with the
4421 variable @samp{gcprolist} pointing to the head of the list and the nth
4422 local @code{gcpro} variable pointing to the first @code{gcpro} variable
4423 in the next enclosing stack frame.  Each @code{GCPRO}ed thing is an
4424 lvalue, and the @code{struct gcpro} local variable contains a pointer to
4425 this lvalue.  This is why things will mess up badly if you don't pair up
4426 the @code{GCPRO}s and @code{UNGCPRO}s -- you will end up with
4427 @code{gcprolist}s containing pointers to @code{struct gcpro}s or local
4428 @code{Lisp_Object} variables in no-longer-active stack frames.
4429
4430 @item
4431 It is actually possible for a single @code{struct gcpro} to
4432 protect a contiguous array of any number of values, rather than
4433 just a single lvalue.  To effect this, call @code{GCPRO@var{n}} as usual on
4434 the first object in the array and then set @code{gcpro@var{n}.nvars}.
4435
4436 @item
4437 @strong{Strings are relocated.}  What this means in practice is that the
4438 pointer obtained using @code{XSTRING_DATA()} is liable to change at any
4439 time, and you should never keep it around past any function call, or
4440 pass it as an argument to any function that might cause a garbage
4441 collection.  This is why a number of functions accept either a
4442 ``non-relocatable'' @code{char *} pointer or a relocatable Lisp string,
4443 and only access the Lisp string's data at the very last minute.  In some
4444 cases, you may end up having to @code{alloca()} some space and copy the
4445 string's data into it.
4446
4447 @item
4448 By convention, if you have to nest @code{GCPRO}'s, use @code{NGCPRO@var{n}}
4449 (along with @code{struct gcpro ngcpro1, ngcpro2}, etc.), @code{NNGCPRO@var{n}},
4450 etc.  This avoids compiler warnings about shadowed locals.
4451
4452 @item
4453 It is @emph{always} better to err on the side of extra @code{GCPRO}s
4454 rather than too few.  The extra cycles spent on this are
4455 almost never going to make a whit of difference in the
4456 speed of anything.
4457
4458 @item
4459 The general rule to follow is that caller, not callee, @code{GCPRO}s.
4460 That is, you should not have to explicitly @code{GCPRO} any Lisp objects
4461 that are passed in as parameters.
4462
4463 One exception from this rule is if you ever plan to change the parameter
4464 value, and store a new object in it.  In that case, you @emph{must}
4465 @code{GCPRO} the parameter, because otherwise the new object will not be
4466 protected.
4467
4468 So, if you create any Lisp objects (remember, this happens in all sorts
4469 of circumstances, e.g. with @code{Fcons()}, etc.), you are responsible
4470 for @code{GCPRO}ing them, unless you are @emph{absolutely sure} that
4471 there's no possibility that a garbage-collection can occur while you
4472 need to use the object.  Even then, consider @code{GCPRO}ing.
4473
4474 @item
4475 A garbage collection can occur whenever anything calls @code{Feval}, or
4476 whenever a QUIT can occur where execution can continue past
4477 this. (Remember, this is almost anywhere.)
4478
4479 @item
4480 If you have the @emph{least smidgeon of doubt} about whether
4481 you need to @code{GCPRO}, you should @code{GCPRO}.
4482
4483 @item
4484 Beware of @code{GCPRO}ing something that is uninitialized.  If you have
4485 any shade of doubt about this, initialize all your variables to @code{Qnil}.
4486
4487 @item
4488 Be careful of traps, like calling @code{Fcons()} in the argument to
4489 another function.  By the ``caller protects'' law, you should be
4490 @code{GCPRO}ing the newly-created cons, but you aren't.  A certain
4491 number of functions that are commonly called on freshly created stuff
4492 (e.g. @code{nconc2()}, @code{Fsignal()}), break the ``caller protects''
4493 law and go ahead and @code{GCPRO} their arguments so as to simplify
4494 things, but make sure and check if it's OK whenever doing something like
4495 this.
4496
4497 @item
4498 Once again, remember to @code{GCPRO}!  Bugs resulting from insufficient
4499 @code{GCPRO}ing are intermittent and extremely difficult to track down,
4500 often showing up in crashes inside of @code{garbage-collect} or in
4501 weirdly corrupted objects or even in incorrect values in a totally
4502 different section of code.
4503 @end enumerate
4504
4505 @cindex garbage collection, conservative
4506 @cindex conservative garbage collection
4507   Given the extremely error-prone nature of the @code{GCPRO} scheme, and
4508 the difficulties in tracking down, it should be considered a deficiency
4509 in the XEmacs code.  A solution to this problem would involve
4510 implementing so-called @dfn{conservative} garbage collection for the C
4511 stack.  That involves looking through all of stack memory and treating
4512 anything that looks like a reference to an object as a reference.  This
4513 will result in a few objects not getting collected when they should, but
4514 it obviates the need for @code{GCPRO}ing, and allows garbage collection
4515 to happen at any point at all, such as during object allocation.
4516
4517 @node Integers and Characters
4518 @section Integers and Characters
4519
4520   Integer and character Lisp objects are created from integers using the
4521 macros @code{XSETINT()} and @code{XSETCHAR()} or the equivalent
4522 functions @code{make_int()} and @code{make_char()}. (These are actually
4523 macros on most systems.)  These functions basically just do some moving
4524 of bits around, since the integral value of the object is stored
4525 directly in the @code{Lisp_Object}.
4526
4527   @code{XSETINT()} and the like will truncate values given to them that
4528 are too big; i.e. you won't get the value you expected but the tag bits
4529 will at least be correct.
4530
4531 @node Allocation from Frob Blocks
4532 @section Allocation from Frob Blocks
4533
4534 The uninitialized memory required by a @code{Lisp_Object} of a particular type
4535 is allocated using
4536 @code{ALLOCATE_FIXED_TYPE()}.  This only occurs inside of the
4537 lowest-level object-creating functions in @file{alloc.c}:
4538 @code{Fcons()}, @code{make_float()}, @code{Fmake_byte_code()},
4539 @code{Fmake_symbol()}, @code{allocate_extent()},
4540 @code{allocate_event()}, @code{Fmake_marker()}, and
4541 @code{make_uninit_string()}.  The idea is that, for each type, there are
4542 a number of frob blocks (each 2K in size); each frob block is divided up
4543 into object-sized chunks.  Each frob block will have some of these
4544 chunks that are currently assigned to objects, and perhaps some that are
4545 free. (If a frob block has nothing but free chunks, it is freed at the
4546 end of the garbage collection cycle.)  The free chunks are stored in a
4547 free list, which is chained by storing a pointer in the first four bytes
4548 of the chunk. (Except for the free chunks at the end of the last frob
4549 block, which are handled using an index which points past the end of the
4550 last-allocated chunk in the last frob block.)
4551 @code{ALLOCATE_FIXED_TYPE()} first tries to retrieve a chunk from the
4552 free list; if that fails, it calls
4553 @code{ALLOCATE_FIXED_TYPE_FROM_BLOCK()}, which looks at the end of the
4554 last frob block for space, and creates a new frob block if there is
4555 none. (There are actually two versions of these macros, one of which is
4556 more defensive but less efficient and is used for error-checking.)
4557
4558 @node lrecords
4559 @section lrecords
4560
4561   [see @file{lrecord.h}]
4562
4563   All lrecords have at the beginning of their structure a @code{struct
4564 lrecord_header}.  This just contains a pointer to a @code{struct
4565 lrecord_implementation}, which is a structure containing method pointers
4566 and such.  There is one of these for each type, and it is a global,
4567 constant, statically-declared structure that is declared in the
4568 @code{DEFINE_LRECORD_IMPLEMENTATION()} macro. (This macro actually
4569 declares an array of two @code{struct lrecord_implementation}
4570 structures.  The first one contains all the standard method pointers,
4571 and is used in all normal circumstances.  During garbage collection,
4572 however, the lrecord is @dfn{marked} by bumping its implementation
4573 pointer by one, so that it points to the second structure in the array.
4574 This structure contains a special indication in it that it's a
4575 @dfn{marked-object} structure: the finalize method is the special
4576 function @code{this_marks_a_marked_record()}, and all other methods are
4577 null pointers.  At the end of garbage collection, all lrecords will
4578 either be reclaimed or unmarked by decrementing their implementation
4579 pointers, so this second structure pointer will never remain past
4580 garbage collection.
4581
4582   Simple lrecords (of type (c) above) just have a @code{struct
4583 lrecord_header} at their beginning.  lcrecords, however, actually have a
4584 @code{struct lcrecord_header}.  This, in turn, has a @code{struct
4585 lrecord_header} at its beginning, so sanity is preserved; but it also
4586 has a pointer used to chain all lcrecords together, and a special ID
4587 field used to distinguish one lcrecord from another. (This field is used
4588 only for debugging and could be removed, but the space gain is not
4589 significant.)
4590
4591   Simple lrecords are created using @code{ALLOCATE_FIXED_TYPE()}, just
4592 like for other frob blocks.  The only change is that the implementation
4593 pointer must be initialized correctly. (The implementation structure for
4594 an lrecord, or rather the pointer to it, is named @code{lrecord_float},
4595 @code{lrecord_extent}, @code{lrecord_buffer}, etc.)
4596
4597   lcrecords are created using @code{alloc_lcrecord()}.  This takes a
4598 size to allocate and an implementation pointer. (The size needs to be
4599 passed because some lcrecords, such as window configurations, are of
4600 variable size.) This basically just @code{malloc()}s the storage,
4601 initializes the @code{struct lcrecord_header}, and chains the lcrecord
4602 onto the head of the list of all lcrecords, which is stored in the
4603 variable @code{all_lcrecords}.  The calls to @code{alloc_lcrecord()}
4604 generally occur in the lowest-level allocation function for each lrecord
4605 type.
4606
4607 Whenever you create an lrecord, you need to call either
4608 @code{DEFINE_LRECORD_IMPLEMENTATION()} or
4609 @code{DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION()}.  This needs to be
4610 specified in a C file, at the top level.  What this actually does is
4611 define and initialize the implementation structure for the lrecord. (And
4612 possibly declares a function @code{error_check_foo()} that implements
4613 the @code{XFOO()} macro when error-checking is enabled.)  The arguments
4614 to the macros are the actual type name (this is used to construct the C
4615 variable name of the lrecord implementation structure and related
4616 structures using the @samp{##} macro concatenation operator), a string
4617 that names the type on the Lisp level (this may not be the same as the C
4618 type name; typically, the C type name has underscores, while the Lisp
4619 string has dashes), various method pointers, and the name of the C
4620 structure that contains the object.  The methods are used to encapsulate
4621 type-specific information about the object, such as how to print it or
4622 mark it for garbage collection, so that it's easy to add new object
4623 types without having to add a specific case for each new type in a bunch
4624 of different places.
4625
4626   The difference between @code{DEFINE_LRECORD_IMPLEMENTATION()} and
4627 @code{DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION()} is that the former is
4628 used for fixed-size object types and the latter is for variable-size
4629 object types.  Most object types are fixed-size; some complex
4630 types, however (e.g. window configurations), are variable-size.
4631 Variable-size object types have an extra method, which is called
4632 to determine the actual size of a particular object of that type.
4633 (Currently this is only used for keeping allocation statistics.)
4634
4635   For the purpose of keeping allocation statistics, the allocation
4636 engine keeps a list of all the different types that exist.  Note that,
4637 since @code{DEFINE_LRECORD_IMPLEMENTATION()} is a macro that is
4638 specified at top-level, there is no way for it to add to the list of all
4639 existing types.  What happens instead is that each implementation
4640 structure contains in it a dynamically assigned number that is
4641 particular to that type. (Or rather, it contains a pointer to another
4642 structure that contains this number.  This evasiveness is done so that
4643 the implementation structure can be declared const.) In the sweep stage
4644 of garbage collection, each lrecord is examined to see if its
4645 implementation structure has its dynamically-assigned number set.  If
4646 not, it must be a new type, and it is added to the list of known types
4647 and a new number assigned.  The number is used to index into an array
4648 holding the number of objects of each type and the total memory
4649 allocated for objects of that type.  The statistics in this array are
4650 also computed during the sweep stage.  These statistics are returned by
4651 the call to @code{garbage-collect} and are printed out at the end of the
4652 loadup phase.
4653
4654   Note that for every type defined with a @code{DEFINE_LRECORD_*()}
4655 macro, there needs to be a @code{DECLARE_LRECORD_IMPLEMENTATION()}
4656 somewhere in a @file{.h} file, and this @file{.h} file needs to be
4657 included by @file{inline.c}.
4658
4659   Furthermore, there should generally be a set of @code{XFOOBAR()},
4660 @code{FOOBARP()}, etc. macros in a @file{.h} (or occasionally @file{.c})
4661 file.  To create one of these, copy an existing model and modify as
4662 necessary.
4663
4664   The various methods in the lrecord implementation structure are:
4665
4666 @enumerate
4667 @item
4668 @cindex mark method
4669 A @dfn{mark} method.  This is called during the marking stage and passed
4670 a function pointer (usually the @code{mark_object()} function), which is
4671 used to mark an object.  All Lisp objects that are contained within the
4672 object need to be marked by applying this function to them.  The mark
4673 method should also return a Lisp object, which should be either nil or
4674 an object to mark. (This can be used in lieu of calling
4675 @code{mark_object()} on the object, to reduce the recursion depth, and
4676 consequently should be the most heavily nested sub-object, such as a
4677 long list.)
4678
4679 @strong{Please note:} When the mark method is called, garbage collection
4680 is in progress, and special precautions need to be taken when accessing
4681 objects; see section (B) above.
4682
4683 If your mark method does not need to do anything, it can be
4684 @code{NULL}.
4685
4686 @item
4687 A @dfn{print} method.  This is called to create a printed representation
4688 of the object, whenever @code{princ}, @code{prin1}, or the like is
4689 called.  It is passed the object, a stream to which the output is to be
4690 directed, and an @code{escapeflag} which indicates whether the object's
4691 printed representation should be @dfn{escaped} so that it is
4692 readable. (This corresponds to the difference between @code{princ} and
4693 @code{prin1}.) Basically, @dfn{escaped} means that strings will have
4694 quotes around them and confusing characters in the strings such as
4695 quotes, backslashes, and newlines will be backslashed; and that special
4696 care will be taken to make symbols print in a readable fashion
4697 (e.g. symbols that look like numbers will be backslashed).  Other
4698 readable objects should perhaps pass @code{escapeflag} on when
4699 sub-objects are printed, so that readability is preserved when necessary
4700 (or if not, always pass in a 1 for @code{escapeflag}).  Non-readable
4701 objects should in general ignore @code{escapeflag}, except that some use
4702 it as an indication that more verbose output should be given.
4703
4704 Sub-objects are printed using @code{print_internal()}, which takes
4705 exactly the same arguments as are passed to the print method.
4706
4707 Literal C strings should be printed using @code{write_c_string()},
4708 or @code{write_string_1()} for non-null-terminated strings.
4709
4710 Functions that do not have a readable representation should check the
4711 @code{print_readably} flag and signal an error if it is set.
4712
4713 If you specify NULL for the print method, the
4714 @code{default_object_printer()} will be used.
4715
4716 @item
4717 A @dfn{finalize} method.  This is called at the beginning of the sweep
4718 stage on lcrecords that are about to be freed, and should be used to
4719 perform any extra object cleanup.  This typically involves freeing any
4720 extra @code{malloc()}ed memory associated with the object, releasing any
4721 operating-system and window-system resources associated with the object
4722 (e.g. pixmaps, fonts), etc.
4723
4724 The finalize method can be NULL if nothing needs to be done.
4725
4726 WARNING #1: The finalize method is also called at the end of the dump
4727 phase; this time with the for_disksave parameter set to non-zero.  The
4728 object is @emph{not} about to disappear, so you have to make sure to
4729 @emph{not} free any extra @code{malloc()}ed memory if you're going to
4730 need it later.  (Also, signal an error if there are any operating-system
4731 and window-system resources here, because they can't be dumped.)
4732
4733 Finalize methods should, as a rule, set to zero any pointers after
4734 they've been freed, and check to make sure pointers are not zero before
4735 freeing.  Although I'm pretty sure that finalize methods are not called
4736 twice on the same object (except for the @code{for_disksave} proviso),
4737 we've gotten nastily burned in some cases by not doing this.
4738
4739 WARNING #2: The finalize method is @emph{only} called for
4740 lcrecords, @emph{not} for simply lrecords.  If you need a
4741 finalize method for simple lrecords, you have to stick
4742 it in the @code{ADDITIONAL_FREE_foo()} macro in @file{alloc.c}.
4743
4744 WARNING #3: Things are in an @emph{extremely} bizarre state
4745 when @code{ADDITIONAL_FREE_foo()} is called, so you have to
4746 be incredibly careful when writing one of these functions.
4747 See the comment in @code{gc_sweep()}.  If you ever have to add
4748 one of these, consider using an lcrecord or dealing with
4749 the problem in a different fashion.
4750
4751 @item
4752 An @dfn{equal} method.  This compares the two objects for similarity,
4753 when @code{equal} is called.  It should compare the contents of the
4754 objects in some reasonable fashion.  It is passed the two objects and a
4755 @dfn{depth} value, which is used to catch circular objects.  To compare
4756 sub-Lisp-objects, call @code{internal_equal()} and bump the depth value
4757 by one.  If this value gets too high, a @code{circular-object} error
4758 will be signaled.
4759
4760 If this is NULL, objects are @code{equal} only when they are @code{eq},
4761 i.e. identical.
4762
4763 @item
4764 A @dfn{hash} method.  This is used to hash objects when they are to be
4765 compared with @code{equal}.  The rule here is that if two objects are
4766 @code{equal}, they @emph{must} hash to the same value; i.e. your hash
4767 function should use some subset of the sub-fields of the object that are
4768 compared in the ``equal'' method.  If you specify this method as
4769 @code{NULL}, the object's pointer will be used as the hash, which will
4770 @emph{fail} if the object has an @code{equal} method, so don't do this.
4771
4772 To hash a sub-Lisp-object, call @code{internal_hash()}.  Bump the
4773 depth by one, just like in the ``equal'' method.
4774
4775 To convert a Lisp object directly into a hash value (using
4776 its pointer), use @code{LISP_HASH()}.  This is what happens when
4777 the hash method is NULL.
4778
4779 To hash two or more values together into a single value, use
4780 @code{HASH2()}, @code{HASH3()}, @code{HASH4()}, etc.
4781
4782 @item
4783 @dfn{getprop}, @dfn{putprop}, @dfn{remprop}, and @dfn{plist} methods.
4784 These are used for object types that have properties.  I don't feel like
4785 documenting them here.  If you create one of these objects, you have to
4786 use different macros to define them,
4787 i.e. @code{DEFINE_LRECORD_IMPLEMENTATION_WITH_PROPS()} or
4788 @code{DEFINE_LRECORD_SEQUENCE_IMPLEMENTATION_WITH_PROPS()}.
4789
4790 @item
4791 A @dfn{size_in_bytes} method, when the object is of variable-size.
4792 (i.e. declared with a @code{_SEQUENCE_IMPLEMENTATION} macro.)  This should
4793 simply return the object's size in bytes, exactly as you might expect.
4794 For an example, see the methods for window configurations and opaques.
4795 @end enumerate
4796
4797 @node Low-level allocation
4798 @section Low-level allocation
4799
4800   Memory that you want to allocate directly should be allocated using
4801 @code{xmalloc()} rather than @code{malloc()}.  This implements
4802 error-checking on the return value, and once upon a time did some more
4803 vital stuff (i.e. @code{BLOCK_INPUT}, which is no longer necessary).
4804 Free using @code{xfree()}, and realloc using @code{xrealloc()}.  Note
4805 that @code{xmalloc()} will do a non-local exit if the memory can't be
4806 allocated. (Many functions, however, do not expect this, and thus XEmacs
4807 will likely crash if this happens.  @strong{This is a bug.}  If you can,
4808 you should strive to make your function handle this OK.  However, it's
4809 difficult in the general circumstance, perhaps requiring extra
4810 unwind-protects and such.)
4811
4812   Note that XEmacs provides two separate replacements for the standard
4813 @code{malloc()} library function.  These are called @dfn{old GNU malloc}
4814 (@file{malloc.c}) and @dfn{new GNU malloc} (@file{gmalloc.c}),
4815 respectively.  New GNU malloc is better in pretty much every way than
4816 old GNU malloc, and should be used if possible.  (It used to be that on
4817 some systems, the old one worked but the new one didn't.  I think this
4818 was due specifically to a bug in SunOS, which the new one now works
4819 around; so I don't think the old one ever has to be used any more.) The
4820 primary difference between both of these mallocs and the standard system
4821 malloc is that they are much faster, at the expense of increased space.
4822 The basic idea is that memory is allocated in fixed chunks of powers of
4823 two.  This allows for basically constant malloc time, since the various
4824 chunks can just be kept on a number of free lists. (The standard system
4825 malloc typically allocates arbitrary-sized chunks and has to spend some
4826 time, sometimes a significant amount of time, walking the heap looking
4827 for a free block to use and cleaning things up.)  The new GNU malloc
4828 improves on things by allocating large objects in chunks of 4096 bytes
4829 rather than in ever larger powers of two, which results in ever larger
4830 wastage.  There is a slight speed loss here, but it's of doubtful
4831 significance.
4832
4833   NOTE: Apparently there is a third-generation GNU malloc that is
4834 significantly better than the new GNU malloc, and should probably
4835 be included in XEmacs.
4836
4837   There is also the relocating allocator, @file{ralloc.c}.  This actually
4838 moves blocks of memory around so that the @code{sbrk()} pointer shrunk
4839 and virtual memory released back to the system.  On some systems,
4840 this is a big win.  On all systems, it causes a noticeable (and
4841 sometimes huge) speed penalty, so I turn it off by default.
4842 @file{ralloc.c} only works with the new GNU malloc in @file{gmalloc.c}.
4843 There are also two versions of @file{ralloc.c}, one that uses @code{mmap()}
4844 rather than block copies to move data around.  This purports to
4845 be faster, although that depends on the amount of data that would
4846 have had to be block copied and the system-call overhead for
4847 @code{mmap()}.  I don't know exactly how this works, except that the
4848 relocating-allocation routines are pretty much used only for
4849 the memory allocated for a buffer, which is the biggest consumer
4850 of space, esp. of space that may get freed later.
4851
4852   Note that the GNU mallocs have some ``memory warning'' facilities.
4853 XEmacs taps into them and issues a warning through the standard
4854 warning system, when memory gets to 75%, 85%, and 95% full.
4855 (On some systems, the memory warnings are not functional.)
4856
4857   Allocated memory that is going to be used to make a Lisp object
4858 is created using @code{allocate_lisp_storage()}.  This calls @code{xmalloc()}
4859 but also verifies that the pointer to the memory can fit into
4860 a Lisp word (remember that some bits are taken away for a type
4861 tag and a mark bit).  If not, an error is issued through @code{memory_full()}.
4862 @code{allocate_lisp_storage()} is called by @code{alloc_lcrecord()},
4863 @code{ALLOCATE_FIXED_TYPE()}, and the vector and bit-vector creation
4864 routines.  These routines also call @code{INCREMENT_CONS_COUNTER()} at the
4865 appropriate times; this keeps statistics on how much memory is
4866 allocated, so that garbage-collection can be invoked when the
4867 threshold is reached.
4868
4869 @node Pure Space
4870 @section Pure Space
4871
4872   Not yet documented.
4873
4874 @node Cons
4875 @section Cons
4876
4877   Conses are allocated in standard frob blocks.  The only thing to
4878 note is that conses can be explicitly freed using @code{free_cons()}
4879 and associated functions @code{free_list()} and @code{free_alist()}.  This
4880 immediately puts the conses onto the cons free list, and decrements
4881 the statistics on memory allocation appropriately.  This is used
4882 to good effect by some extremely commonly-used code, to avoid
4883 generating extra objects and thereby triggering GC sooner.
4884 However, you have to be @emph{extremely} careful when doing this.
4885 If you mess this up, you will get BADLY BURNED, and it has happened
4886 before.
4887
4888 @node Vector
4889 @section Vector
4890
4891   As mentioned above, each vector is @code{malloc()}ed individually, and
4892 all are threaded through the variable @code{all_vectors}.  Vectors are
4893 marked strangely during garbage collection, by kludging the size field.
4894 Note that the @code{struct Lisp_Vector} is declared with its
4895 @code{contents} field being a @emph{stretchy} array of one element.  It
4896 is actually @code{malloc()}ed with the right size, however, and access
4897 to any element through the @code{contents} array works fine.
4898
4899 @node Bit Vector
4900 @section Bit Vector
4901
4902   Bit vectors work exactly like vectors, except for more complicated
4903 code to access an individual bit, and except for the fact that bit
4904 vectors are lrecords while vectors are not. (The only difference here is
4905 that there's an lrecord implementation pointer at the beginning and the
4906 tag field in bit vector Lisp words is ``lrecord'' rather than
4907 ``vector''.)
4908
4909 @node Symbol
4910 @section Symbol
4911
4912   Symbols are also allocated in frob blocks.  Note that the code
4913 exists for symbols to be either lrecords (category (c) above)
4914 or simple types (category (b) above), and are lrecords by
4915 default (I think), although there is no good reason for this.
4916
4917   Note that symbols in the awful horrible obarray structure are
4918 chained through their @code{next} field.
4919
4920 Remember that @code{intern} looks up a symbol in an obarray, creating
4921 one if necessary.
4922
4923 @node Marker
4924 @section Marker
4925
4926   Markers are allocated in frob blocks, as usual.  They are kept
4927 in a buffer unordered, but in a doubly-linked list so that they
4928 can easily be removed. (Formerly this was a singly-linked list,
4929 but in some cases garbage collection took an extraordinarily
4930 long time due to the O(N^2) time required to remove lots of
4931 markers from a buffer.) Markers are removed from a buffer in
4932 the finalize stage, in @code{ADDITIONAL_FREE_marker()}.
4933
4934 @node String
4935 @section String
4936
4937   As mentioned above, strings are a special case.  A string is logically
4938 two parts, a fixed-size object (containing the length, property list,
4939 and a pointer to the actual data), and the actual data in the string.
4940 The fixed-size object is a @code{struct Lisp_String} and is allocated in
4941 frob blocks, as usual.  The actual data is stored in special
4942 @dfn{string-chars blocks}, which are 8K blocks of memory.
4943 Currently-allocated strings are simply laid end to end in these
4944 string-chars blocks, with a pointer back to the @code{struct Lisp_String}
4945 stored before each string in the string-chars block.  When a new string
4946 needs to be allocated, the remaining space at the end of the last
4947 string-chars block is used if there's enough, and a new string-chars
4948 block is created otherwise.
4949
4950   There are never any holes in the string-chars blocks due to the string
4951 compaction and relocation that happens at the end of garbage collection.
4952 During the sweep stage of garbage collection, when objects are
4953 reclaimed, the garbage collector goes through all string-chars blocks,
4954 looking for unused strings.  Each chunk of string data is preceded by a
4955 pointer to the corresponding @code{struct Lisp_String}, which indicates
4956 both whether the string is used and how big the string is, i.e. how to
4957 get to the next chunk of string data.  Holes are compressed by
4958 block-copying the next string into the empty space and relocating the
4959 pointer stored in the corresponding @code{struct Lisp_String}.
4960 @strong{This means you have to be careful with strings in your code.}
4961 See the section above on @code{GCPRO}ing.
4962
4963   Note that there is one situation not handled: a string that is too big
4964 to fit into a string-chars block.  Such strings, called @dfn{big
4965 strings}, are all @code{malloc()}ed as their own block. (#### Although it
4966 would make more sense for the threshold for big strings to be somewhat
4967 lower, e.g. 1/2 or 1/4 the size of a string-chars block.  It seems that
4968 this was indeed the case formerly -- indeed, the threshold was set at
4969 1/8 -- but Mly forgot about this when rewriting things for 19.8.)
4970
4971 Note also that the string data in string-chars blocks is padded as
4972 necessary so that proper alignment constraints on the @code{struct
4973 Lisp_String} back pointers are maintained.
4974
4975   Finally, strings can be resized.  This happens in Mule when a
4976 character is substituted with a different-length character, or during
4977 modeline frobbing. (You could also export this to Lisp, but it's not
4978 done so currently.) Resizing a string is a potentially tricky process.
4979 If the change is small enough that the padding can absorb it, nothing
4980 other than a simple memory move needs to be done.  Keep in mind,
4981 however, that the string can't shrink too much because the offset to the
4982 next string in the string-chars block is computed by looking at the
4983 length and rounding to the nearest multiple of four or eight.  If the
4984 string would shrink or expand beyond the correct padding, new string
4985 data needs to be allocated at the end of the last string-chars block and
4986 the data moved appropriately.  This leaves some dead string data, which
4987 is marked by putting a special marker of 0xFFFFFFFF in the @code{struct
4988 Lisp_String} pointer before the data (there's no real @code{struct
4989 Lisp_String} to point to and relocate), and storing the size of the dead
4990 string data (which would normally be obtained from the now-non-existent
4991 @code{struct Lisp_String}) at the beginning of the dead string data gap.
4992 The string compactor recognizes this special 0xFFFFFFFF marker and
4993 handles it correctly.
4994
4995 @node Bytecode
4996 @section Bytecode
4997
4998   Not yet documented.
4999
5000 @node Events and the Event Loop, Evaluation; Stack Frames; Bindings, Allocation of Objects in XEmacs Lisp, Top
5001 @chapter Events and the Event Loop
5002
5003 @menu
5004 * Introduction to Events::
5005 * Main Loop::
5006 * Specifics of the Event Gathering Mechanism::
5007 * Specifics About the Emacs Event::
5008 * The Event Stream Callback Routines::
5009 * Other Event Loop Functions::
5010 * Converting Events::
5011 * Dispatching Events; The Command Builder::
5012 @end menu
5013
5014 @node Introduction to Events
5015 @section Introduction to Events
5016
5017   An event is an object that encapsulates information about an
5018 interesting occurrence in the operating system.  Events are
5019 generated either by user action, direct (e.g. typing on the
5020 keyboard or moving the mouse) or indirect (moving another
5021 window, thereby generating an expose event on an Emacs frame),
5022 or as a result of some other typically asynchronous action happening,
5023 such as output from a subprocess being ready or a timer expiring.
5024 Events come into the system in an asynchronous fashion (typically
5025 through a callback being called) and are converted into a
5026 synchronous event queue (first-in, first-out) in a process that
5027 we will call @dfn{collection}.
5028
5029   Note that each application has its own event queue. (It is
5030 immaterial whether the collection process directly puts the
5031 events in the proper application's queue, or puts them into
5032 a single system queue, which is later split up.)
5033
5034   The most basic level of event collection is done by the
5035 operating system or window system.  Typically, XEmacs does
5036 its own event collection as well.  Often there are multiple
5037 layers of collection in XEmacs, with events from various
5038 sources being collected into a queue, which is then combined
5039 with other sources to go into another queue (i.e. a second
5040 level of collection), with perhaps another level on top of
5041 this, etc.
5042
5043   XEmacs has its own types of events (called @dfn{Emacs events}),
5044 which provides an abstract layer on top of the system-dependent
5045 nature of the most basic events that are received.  Part of the
5046 complex nature of the XEmacs event collection process involves
5047 converting from the operating-system events into the proper
5048 Emacs events -- there may not be a one-to-one correspondence.
5049
5050   Emacs events are documented in @file{events.h}; I'll discuss them
5051 later.
5052
5053 @node Main Loop
5054 @section Main Loop
5055
5056   The @dfn{command loop} is the top-level loop that the editor is always
5057 running.  It loops endlessly, calling @code{next-event} to retrieve an
5058 event and @code{dispatch-event} to execute it. @code{dispatch-event} does
5059 the appropriate thing with non-user events (process, timeout,
5060 magic, eval, mouse motion); this involves calling a Lisp handler
5061 function, redrawing a newly-exposed part of a frame, reading
5062 subprocess output, etc.  For user events, @code{dispatch-event}
5063 looks up the event in relevant keymaps or menubars; when a
5064 full key sequence or menubar selection is reached, the appropriate
5065 function is executed. @code{dispatch-event} may have to keep state
5066 across calls; this is done in the ``command-builder'' structure
5067 associated with each console (remember, there's usually only
5068 one console), and the engine that looks up keystrokes and
5069 constructs full key sequences is called the @dfn{command builder}.
5070 This is documented elsewhere.
5071
5072   The guts of the command loop are in @code{command_loop_1()}.  This
5073 function doesn't catch errors, though -- that's the job of
5074 @code{command_loop_2()}, which is a condition-case (i.e. error-trapping)
5075 wrapper around @code{command_loop_1()}.  @code{command_loop_1()} never
5076 returns, but may get thrown out of.
5077
5078   When an error occurs, @code{cmd_error()} is called, which usually
5079 invokes the Lisp error handler in @code{command-error}; however, a
5080 default error handler is provided if @code{command-error} is @code{nil}
5081 (e.g. during startup).  The purpose of the error handler is simply to
5082 display the error message and do associated cleanup; it does not need to
5083 throw anywhere.  When the error handler finishes, the condition-case in
5084 @code{command_loop_2()} will finish and @code{command_loop_2()} will
5085 reinvoke @code{command_loop_1()}.
5086
5087   @code{command_loop_2()} is invoked from three places: from
5088 @code{initial_command_loop()} (called from @code{main()} at the end of
5089 internal initialization), from the Lisp function @code{recursive-edit},
5090 and from @code{call_command_loop()}.
5091
5092   @code{call_command_loop()} is called when a macro is started and when
5093 the minibuffer is entered; normal termination of the macro or minibuffer
5094 causes a throw out of the recursive command loop. (To
5095 @code{execute-kbd-macro} for macros and @code{exit} for minibuffers.
5096 Note also that the low-level minibuffer-entering function,
5097 @code{read-minibuffer-internal}, provides its own error handling and
5098 does not need @code{command_loop_2()}'s error encapsulation; so it tells
5099 @code{call_command_loop()} to invoke @code{command_loop_1()} directly.)
5100
5101   Note that both read-minibuffer-internal and recursive-edit set up a
5102 catch for @code{exit}; this is why @code{abort-recursive-edit}, which
5103 throws to this catch, exits out of either one.
5104
5105   @code{initial_command_loop()}, called from @code{main()}, sets up a
5106 catch for @code{top-level} when invoking @code{command_loop_2()},
5107 allowing functions to throw all the way to the top level if they really
5108 need to.  Before invoking @code{command_loop_2()},
5109 @code{initial_command_loop()} calls @code{top_level_1()}, which handles
5110 all of the startup stuff (creating the initial frame, handling the
5111 command-line options, loading the user's @file{.emacs} file, etc.).  The
5112 function that actually does this is in Lisp and is pointed to by the
5113 variable @code{top-level}; normally this function is
5114 @code{normal-top-level}.  @code{top_level_1()} is just an error-handling
5115 wrapper similar to @code{command_loop_2()}.  Note also that
5116 @code{initial_command_loop()} sets up a catch for @code{top-level} when
5117 invoking @code{top_level_1()}, just like when it invokes
5118 @code{command_loop_2()}.
5119
5120 @node Specifics of the Event Gathering Mechanism
5121 @section Specifics of the Event Gathering Mechanism
5122
5123   Here is an approximate diagram of the collection processes
5124 at work in XEmacs, under TTY's (TTY's are simpler than X
5125 so we'll look at this first):
5126
5127 @noindent
5128 @example
5129  asynch.      asynch.    asynch.   asynch.                [Collectors in
5130 kbd events  kbd events   process   process                   the OS]
5131       |         |         output    output                 
5132       |         |           |         |                    
5133       |         |           |         |      SIGINT,      [signal handlers
5134       |         |           |         |      SIGQUIT,        in XEmacs]
5135       V         V           V         V      SIGWINCH,
5136      file      file        file      file    SIGALRM
5137      desc.     desc.       desc.     desc.     |
5138      (TTY)     (TTY)       (pipe)    (pipe)    |
5139       |          |          |         |      fake    timeouts
5140       |          |          |         |      file        |
5141       |          |          |         |      desc.       |
5142       |          |          |         |      (pipe)      |
5143       |          |          |         |        |         |
5144       |          |          |         |        |         |
5145       |          |          |         |        |         |
5146       V          V          V         V        V         V
5147       ------>-----------<----------------<----------------
5148                    |                
5149                    |
5150                    |   [collected using select() in emacs_tty_next_event()
5151                    |    and converted to the appropriate Emacs event]
5152                    | 
5153                    | 
5154                    V              (above this line is TTY-specific)
5155                  Emacs    ------------------------------------------------
5156                  event    (below this line is the generic event mechanism)
5157                    |
5158                    |
5159 was there      if not, call
5160 a SIGINT?   emacs_tty_next_event()
5161     |              |
5162     |              |
5163     |              |
5164     V              V
5165     --->-------<----
5166            |
5167            |        [collected in event_stream_next_event();
5168            |         SIGINT is converted using maybe_read_quit_event()]
5169            V
5170          Emacs
5171          event
5172            |
5173            \---->------>----- maybe_kbd_translate() ---->---\
5174                                                             |
5175                                                             |
5176                                                             |
5177      command event queue                                    |
5178                                                  if not from command
5179   (contains events that were                     event queue, call
5180   read earlier but not processed,                event_stream_next_event()
5181   typically when waiting in a                               |
5182   sit-for, sleep-for, etc. for                              |
5183  a particular event to be received)                         |
5184                |                                            |
5185                |                                            |
5186                V                                            V
5187                ---->------------------------------------<----
5188                                                |
5189                                                |   [collected in
5190                                                |    next_event_internal()]
5191                                                |
5192  unread-     unread-       event from          |
5193  command-    command-       keyboard       else, call
5194  events      event           macro      next_event_internal()
5195    |           |               |               |
5196    |           |               |               |
5197    |           |               |               |
5198    V           V               V               V
5199    --------->----------------------<------------
5200                      |
5201                      |      [collected in `next-event', which may loop
5202                      |       more than once if the event it gets is on
5203                      |       a dead frame, device, etc.]
5204                      |
5205                      |
5206                      V
5207             feed into top-level event loop,
5208             which repeatedly calls `next-event'
5209             and then dispatches the event
5210             using `dispatch-event'
5211 @end example
5212
5213 Notice the separation between TTY-specific and generic event mechanism.
5214 When using the Xt-based event loop, the TTY-specific stuff is replaced
5215 but the rest stays the same.
5216
5217 It's also important to realize that only one different kind of
5218 system-specific event loop can be operating at a time, and must be able
5219 to receive all kinds of events simultaneously.  For the two existing
5220 event loops (implemented in @file{event-tty.c} and @file{event-Xt.c},
5221 respectively), the TTY event loop @emph{only} handles TTY consoles,
5222 while the Xt event loop handles @emph{both} TTY and X consoles.  This
5223 situation is different from all of the output handlers, where you simply
5224 have one per console type.
5225
5226   Here's the Xt Event Loop Diagram (notice that below a certain point,
5227 it's the same as the above diagram):
5228
5229 @example
5230 asynch. asynch. asynch. asynch.                 [Collectors in
5231  kbd     kbd    process process                    the OS]
5232 events  events  output  output                 
5233   |       |       |       |                    
5234   |       |       |       |     asynch. asynch.   [Collectors in the
5235   |       |       |       |       X        X       OS and X Window System]
5236   |       |       |       |     events  events 
5237   |       |       |       |       |        |
5238   |       |       |       |       |        |
5239   |       |       |       |       |        |    SIGINT,   [signal handlers   
5240   |       |       |       |       |        |    SIGQUIT,     in XEmacs]      
5241   |       |       |       |       |        |    SIGWINCH,                      
5242   |       |       |       |       |        |    SIGALRM                        
5243   |       |       |       |       |        |       |                           
5244   |       |       |       |       |        |       |                        
5245   |       |       |       |       |        |       |      timeouts             
5246   |       |       |       |       |        |       |          |
5247   |       |       |       |       |        |       |          |
5248   |       |       |       |       |        |       V          |
5249   V       V       V       V       V        V      fake        |          
5250  file    file    file    file    file     file    file        |   
5251  desc.   desc.   desc.   desc.   desc.    desc.   desc.       |   
5252  (TTY)   (TTY)   (pipe)  (pipe) (socket) (socket) (pipe)      |   
5253   |       |       |       |       |        |       |          |
5254   |       |       |       |       |        |       |          |
5255   |       |       |       |       |        |       |          |
5256   V       V       V       V       V        V       V          V          
5257   --->----------------------------------------<---------<------
5258        |              |               |
5259        |              |               |   [collected using select() in
5260        |              |               |   _XtWaitForSomething(), called
5261        |              |               |   from XtAppProcessEvent(), called
5262        |              |               |   in emacs_Xt_next_event();
5263        |              |               |   dispatched to various callbacks]
5264        |              |               |
5265        |              |               |
5266   emacs_Xt_        p_s_callback(),    |   [popup_selection_callback]
5267   event_handler()  x_u_v_s_callback(),|   [x_update_vertical_scrollbar_
5268        |           x_u_h_s_callback(),|    callback]
5269        |           search_callback()  |   [x_update_horizontal_scrollbar_ 
5270        |              |               |    callback]
5271        |              |               |
5272        |              |               |
5273   enqueue_Xt_       signal_special_   |
5274   dispatch_event()  Xt_user_event()   |
5275   [maybe multiple     |               |
5276    times, maybe 0     |               |
5277    times]             |               |
5278        |            enqueue_Xt_       |
5279        |            dispatch_event()  |
5280        |              |               |
5281        |              |               |
5282        V              V               |
5283        -->----------<--               |
5284               |                       |
5285               |                       |
5286            dispatch             Xt_what_callback()      
5287            event                  sets flags
5288            queue                      |
5289               |                       |
5290               |                       |
5291               |                       |
5292               |                       |
5293               ---->-----------<--------
5294                    |                
5295                    |
5296                    |     [collected and converted as appropriate in
5297                    |            emacs_Xt_next_event()]
5298                    | 
5299                    | 
5300                    V              (above this line is Xt-specific)
5301                  Emacs    ------------------------------------------------
5302                  event    (below this line is the generic event mechanism)
5303                    |
5304                    |
5305 was there      if not, call
5306 a SIGINT?   emacs_Xt_next_event()
5307     |              |
5308     |              |
5309     |              |
5310     V              V
5311     --->-------<----
5312            |
5313            |        [collected in event_stream_next_event();
5314            |         SIGINT is converted using maybe_read_quit_event()]
5315            V
5316          Emacs
5317          event
5318            |
5319            \---->------>----- maybe_kbd_translate() -->-----\
5320                                                             |
5321                                                             |
5322                                                             |
5323      command event queue                                    |
5324                                                  if not from command
5325   (contains events that were                     event queue, call
5326   read earlier but not processed,                event_stream_next_event()
5327   typically when waiting in a                               |
5328   sit-for, sleep-for, etc. for                              |
5329  a particular event to be received)                         |
5330                |                                            |
5331                |                                            |
5332                V                                            V
5333                ---->----------------------------------<------
5334                                                |
5335                                                |   [collected in
5336                                                |    next_event_internal()]
5337                                                |
5338  unread-     unread-       event from          |
5339  command-    command-       keyboard       else, call
5340  events      event           macro      next_event_internal()
5341    |           |               |               |
5342    |           |               |               |
5343    |           |               |               |
5344    V           V               V               V
5345    --------->----------------------<------------
5346                      |
5347                      |      [collected in `next-event', which may loop
5348                      |       more than once if the event it gets is on
5349                      |       a dead frame, device, etc.]
5350                      |
5351                      |
5352                      V
5353             feed into top-level event loop,
5354             which repeatedly calls `next-event'
5355             and then dispatches the event
5356             using `dispatch-event'
5357 @end example
5358
5359 @node Specifics About the Emacs Event
5360 @section Specifics About the Emacs Event
5361
5362 @node The Event Stream Callback Routines
5363 @section The Event Stream Callback Routines
5364
5365 @node Other Event Loop Functions
5366 @section Other Event Loop Functions
5367
5368   @code{detect_input_pending()} and @code{input-pending-p} look for
5369 input by calling @code{event_stream->event_pending_p} and looking in
5370 @code{[V]unread-command-event} and the @code{command_event_queue} (they
5371 do not check for an executing keyboard macro, though).
5372
5373   @code{discard-input} cancels any command events pending (and any
5374 keyboard macros currently executing), and puts the others onto the
5375 @code{command_event_queue}.  There is a comment about a ``race
5376 condition'', which is not a good sign.
5377
5378   @code{next-command-event} and @code{read-char} are higher-level
5379 interfaces to @code{next-event}.  @code{next-command-event} gets the
5380 next @dfn{command} event (i.e.  keypress, mouse event, menu selection,
5381 or scrollbar action), calling @code{dispatch-event} on any others.
5382 @code{read-char} calls @code{next-command-event} and uses
5383 @code{event_to_character()} to return the character equivalent.  With
5384 the right kind of input method support, it is possible for (read-char)
5385 to return a Kanji character.
5386
5387 @node Converting Events
5388 @section Converting Events
5389
5390   @code{character_to_event()}, @code{event_to_character()},
5391 @code{event-to-character}, and @code{character-to-event} convert between
5392 characters and keypress events corresponding to the characters.  If the
5393 event was not a keypress, @code{event_to_character()} returns -1 and
5394 @code{event-to-character} returns @code{nil}.  These functions convert
5395 between character representation and the split-up event representation
5396 (keysym plus mod keys).
5397
5398 @node Dispatching Events; The Command Builder
5399 @section Dispatching Events; The Command Builder
5400
5401 Not yet documented.
5402
5403 @node Evaluation; Stack Frames; Bindings, Symbols and Variables, Events and the Event Loop, Top
5404 @chapter Evaluation; Stack Frames; Bindings
5405
5406 @menu
5407 * Evaluation::
5408 * Dynamic Binding; The specbinding Stack; Unwind-Protects::
5409 * Simple Special Forms::
5410 * Catch and Throw::
5411 @end menu
5412
5413 @node Evaluation
5414 @section Evaluation
5415
5416   @code{Feval()} evaluates the form (a Lisp object) that is passed to
5417 it.  Note that evaluation is only non-trivial for two types of objects:
5418 symbols and conses.  A symbol is evaluated simply by calling
5419 symbol-value on it and returning the value.
5420
5421   Evaluating a cons means calling a function.  First, @code{eval} checks
5422 to see if garbage-collection is necessary, and calls
5423 @code{Fgarbage_collect()} if so.  It then increases the evaluation depth
5424 by 1 (@code{lisp_eval_depth}, which is always less than @code{max_lisp_eval_depth}) and adds an
5425 element to the linked list of @code{struct backtrace}'s
5426 (@code{backtrace_list}).  Each such structure contains a pointer to the
5427 function being called plus a list of the function's arguments.
5428 Originally these values are stored unevalled, and as they are evaluated,
5429 the backtrace structure is updated.  Garbage collection pays attention
5430 to the objects pointed to in the backtrace structures (garbage
5431 collection might happen while a function is being called or while an
5432 argument is being evaluated, and there could easily be no other
5433 references to the arguments in the argument list; once an argument is
5434 evaluated, however, the unevalled version is not needed by eval, and so
5435 the backtrace structure is changed).
5436
5437   At this point, the function to be called is determined by looking at
5438 the car of the cons (if this is a symbol, its function definition is
5439 retrieved and the process repeated).  The function should then consist
5440 of either a @code{Lisp_Subr} (built-in function), a
5441 @code{Lisp_Compiled_Function} object, or a cons whose car is the symbol
5442 @code{autoload}, @code{macro} or @code{lambda}.
5443
5444 If the function is a @code{Lisp_Subr}, the lisp object points to a
5445 @code{struct Lisp_Subr} (created by @code{DEFUN()}), which contains a
5446 pointer to the C function, a minimum and maximum number of arguments
5447 (possibly the special constants @code{MANY} or @code{UNEVALLED}), a
5448 pointer to the symbol referring to that subr, and a couple of other
5449 things.  If the subr wants its arguments @code{UNEVALLED}, they are
5450 passed raw as a list.  Otherwise, an array of evaluated arguments is
5451 created and put into the backtrace structure, and either passed whole
5452 (@code{MANY}) or each argument is passed as a C argument.
5453
5454   If the function is a @code{Lisp_Compiled_Function} object or a lambda,
5455 @code{apply_lambda()} is called.  If the function is a macro,
5456 [..... fill in] is done.  If the function is an autoload,
5457 @code{do_autoload()} is called to load the definition and then eval
5458 starts over [explain this more].
5459
5460   When @code{Feval} exits, the evaluation depth is reduced by one, the
5461 debugger is called if appropriate, and the current backtrace structure
5462 is removed from the list.
5463
5464   @code{apply_lambda()} is passed a function, a list of arguments, and a
5465 flag indicating whether to evaluate the arguments.  It creates an array
5466 of (possibly) evaluated arguments and fixes up the backtrace structure,
5467 just like eval does.  Then it calls @code{funcall_lambda()}.
5468
5469   @code{funcall_lambda()} goes through the formal arguments to the
5470 function and binds them to the actual arguments, checking for
5471 @code{&rest} and @code{&optional} symbols in the formal arguments and
5472 making sure the number of actual arguments is correct.  Then either
5473 @code{progn} or @code{byte-code} is called to actually execute the body
5474 and return a value.
5475
5476   @code{Ffuncall()} implements Lisp @code{funcall}.  @code{(funcall fun
5477 x1 x2 x3 ...)} is equivalent to @code{(eval (list fun (quote x1) (quote
5478 x2) (quote x3) ...))}.  @code{Ffuncall()} contains its own code to do
5479 the evaluation, however, and is almost identical to eval.
5480
5481   @code{Fapply()} implements Lisp @code{apply}, which is very similar to
5482 @code{funcall} except that if the last argument is a list, the result is the
5483 same as if each of the arguments in the list had been passed separately.
5484 @code{Fapply()} does some business to expand the last argument if it's a
5485 list, then calls @code{Ffuncall()} to do the work.
5486
5487   @code{apply1()}, @code{call0()}, @code{call1()}, @code{call2()}, and
5488 @code{call3()} call a function, passing it the argument(s) given (the
5489 arguments are given as separate C arguments rather than being passed as
5490 an array).  @code{apply1()} uses @code{apply} while the others use
5491 @code{funcall}.
5492
5493 @node Dynamic Binding; The specbinding Stack; Unwind-Protects
5494 @section Dynamic Binding; The specbinding Stack; Unwind-Protects
5495
5496 @example
5497 struct specbinding
5498 @{
5499   Lisp_Object symbol, old_value;
5500   Lisp_Object (*func) (Lisp_Object); /* for unwind-protect */
5501 @};
5502 @end example
5503
5504   @code{struct specbinding} is used for local-variable bindings and
5505 unwind-protects.  @code{specpdl} holds an array of @code{struct specbinding}'s,
5506 @code{specpdl_ptr} points to the beginning of the free bindings in the
5507 array, @code{specpdl_size} specifies the total number of binding slots
5508 in the array, and @code{max_specpdl_size} specifies the maximum number
5509 of bindings the array can be expanded to hold.  @code{grow_specpdl()}
5510 increases the size of the @code{specpdl} array, multiplying its size by
5511 2 but never exceeding @code{max_specpdl_size} (except that if this
5512 number is less than 400, it is first set to 400).
5513
5514   @code{specbind()} binds a symbol to a value and is used for local
5515 variables and @code{let} forms.  The symbol and its old value (which
5516 might be @code{Qunbound}, indicating no prior value) are recorded in the
5517 specpdl array, and @code{specpdl_size} is increased by 1.
5518
5519   @code{record_unwind_protect()} implements an @dfn{unwind-protect},
5520 which, when placed around a section of code, ensures that some specified
5521 cleanup routine will be executed even if the code exits abnormally
5522 (e.g. through a @code{throw} or quit).  @code{record_unwind_protect()}
5523 simply adds a new specbinding to the @code{specpdl} array and stores the
5524 appropriate information in it.  The cleanup routine can either be a C
5525 function, which is stored in the @code{func} field, or a @code{progn}
5526 form, which is stored in the @code{old_value} field.
5527
5528   @code{unbind_to()} removes specbindings from the @code{specpdl} array
5529 until the specified position is reached.  Each specbinding can be one of
5530 three types:
5531
5532 @enumerate
5533 @item
5534 an unwind-protect with a C cleanup function (@code{func} is not 0, and
5535 @code{old_value} holds an argument to be passed to the function);
5536 @item
5537 an unwind-protect with a Lisp form (@code{func} is 0, @code{symbol}
5538 is @code{nil}, and @code{old_value} holds the form to be executed with
5539 @code{Fprogn()}); or
5540 @item
5541 a local-variable binding (@code{func} is 0, @code{symbol} is not
5542 @code{nil}, and @code{old_value} holds the old value, which is stored as
5543 the symbol's value).
5544 @end enumerate
5545
5546 @node Simple Special Forms
5547 @section Simple Special Forms
5548
5549 @code{or}, @code{and}, @code{if}, @code{cond}, @code{progn},
5550 @code{prog1}, @code{prog2}, @code{setq}, @code{quote}, @code{function},
5551 @code{let*}, @code{let}, @code{while}
5552
5553   All of these are very simple and work as expected, calling
5554 @code{Feval()} or @code{Fprogn()} as necessary and (in the case of
5555 @code{let} and @code{let*}) using @code{specbind()} to create bindings
5556 and @code{unbind_to()} to undo the bindings when finished.  Note that
5557 these functions do a lot of @code{GCPRO}ing to protect their arguments
5558 from garbage collection because they call @code{Feval()} (@pxref{Garbage
5559 Collection}).
5560
5561 @node Catch and Throw
5562 @section Catch and Throw
5563
5564 @example
5565 struct catchtag
5566 @{
5567   Lisp_Object tag;
5568   Lisp_Object val;
5569   struct catchtag *next;
5570   struct gcpro *gcpro;
5571   jmp_buf jmp;
5572   struct backtrace *backlist;
5573   int lisp_eval_depth;
5574   int pdlcount;
5575 @};
5576 @end example
5577
5578   @code{catch} is a Lisp function that places a catch around a body of
5579 code.  A catch is a means of non-local exit from the code.  When a catch
5580 is created, a tag is specified, and executing a @code{throw} to this tag
5581 will exit from the body of code caught with this tag, and its value will
5582 be the value given in the call to @code{throw}.  If there is no such
5583 call, the code will be executed normally.
5584
5585   Information pertaining to a catch is held in a @code{struct catchtag},
5586 which is placed at the head of a linked list pointed to by
5587 @code{catchlist}.  @code{internal_catch()} is passed a C function to
5588 call (@code{Fprogn()} when Lisp @code{catch} is called) and arguments to
5589 give it, and places a catch around the function.  Each @code{struct
5590 catchtag} is held in the stack frame of the @code{internal_catch()}
5591 instance that created the catch.
5592
5593   @code{internal_catch()} is fairly straightforward.  It stores into the
5594 @code{struct catchtag} the tag name and the current values of
5595 @code{backtrace_list}, @code{lisp_eval_depth}, @code{gcprolist}, and the
5596 offset into the @code{specpdl} array, sets a jump point with @code{_setjmp()}
5597 (storing the jump point into the @code{struct catchtag}), and calls the
5598 function.  Control will return to @code{internal_catch()} either when
5599 the function exits normally or through a @code{_longjmp()} to this jump
5600 point.  In the latter case, @code{throw} will store the value to be
5601 returned into the @code{struct catchtag} before jumping.  When it's
5602 done, @code{internal_catch()} removes the @code{struct catchtag} from
5603 the catchlist and returns the proper value.
5604
5605   @code{Fthrow()} goes up through the catchlist until it finds one with
5606 a matching tag.  It then calls @code{unbind_catch()} to restore
5607 everything to what it was when the appropriate catch was set, stores the
5608 return value in the @code{struct catchtag}, and jumps (with
5609 @code{_longjmp()}) to its jump point.
5610
5611   @code{unbind_catch()} removes all catches from the catchlist until it
5612 finds the correct one.  Some of the catches might have been placed for
5613 error-trapping, and if so, the appropriate entries on the handlerlist
5614 must be removed (see ``errors'').  @code{unbind_catch()} also restores
5615 the values of @code{gcprolist}, @code{backtrace_list}, and
5616 @code{lisp_eval}, and calls @code{unbind_to()} to undo any specbindings
5617 created since the catch.
5618
5619
5620 @node Symbols and Variables, Buffers and Textual Representation, Evaluation; Stack Frames; Bindings, Top
5621 @chapter Symbols and Variables
5622
5623 @menu
5624 * Introduction to Symbols::
5625 * Obarrays::
5626 * Symbol Values::
5627 @end menu
5628
5629 @node Introduction to Symbols
5630 @section Introduction to Symbols
5631
5632   A symbol is basically just an object with four fields: a name (a
5633 string), a value (some Lisp object), a function (some Lisp object), and
5634 a property list (usually a list of alternating keyword/value pairs).
5635 What makes symbols special is that there is usually only one symbol with
5636 a given name, and the symbol is referred to by name.  This makes a
5637 symbol a convenient way of calling up data by name, i.e. of implementing
5638 variables. (The variable's value is stored in the @dfn{value slot}.)
5639 Similarly, functions are referenced by name, and the definition of the
5640 function is stored in a symbol's @dfn{function slot}.  This means that
5641 there can be a distinct function and variable with the same name.  The
5642 property list is used as a more general mechanism of associating
5643 additional values with particular names, and once again the namespace is
5644 independent of the function and variable namespaces.
5645
5646 @node Obarrays
5647 @section Obarrays
5648
5649   The identity of symbols with their names is accomplished through a
5650 structure called an obarray, which is just a poorly-implemented hash
5651 table mapping from strings to symbols whose name is that string. (I say
5652 ``poorly implemented'' because an obarray appears in Lisp as a vector
5653 with some hidden fields rather than as its own opaque type.  This is an
5654 Emacs Lisp artifact that should be fixed.)
5655
5656   Obarrays are implemented as a vector of some fixed size (which should
5657 be a prime for best results), where each ``bucket'' of the vector
5658 contains one or more symbols, threaded through a hidden @code{next}
5659 field in the symbol.  Lookup of a symbol in an obarray, and adding a
5660 symbol to an obarray, is accomplished through standard hash-table
5661 techniques.
5662
5663   The standard Lisp function for working with symbols and obarrays is
5664 @code{intern}.  This looks up a symbol in an obarray given its name; if
5665 it's not found, a new symbol is automatically created with the specified
5666 name, added to the obarray, and returned.  This is what happens when the
5667 Lisp reader encounters a symbol (or more precisely, encounters the name
5668 of a symbol) in some text that it is reading.  There is a standard
5669 obarray called @code{obarray} that is used for this purpose, although
5670 the Lisp programmer is free to create his own obarrays and @code{intern}
5671 symbols in them.
5672
5673   Note that, once a symbol is in an obarray, it stays there until
5674 something is done about it, and the standard obarray @code{obarray}
5675 always stays around, so once you use any particular variable name, a
5676 corresponding symbol will stay around in @code{obarray} until you exit
5677 XEmacs.
5678
5679   Note that @code{obarray} itself is a variable, and as such there is a
5680 symbol in @code{obarray} whose name is @code{"obarray"} and which
5681 contains @code{obarray} as its value.
5682
5683   Note also that this call to @code{intern} occurs only when in the Lisp
5684 reader, not when the code is executed (at which point the symbol is
5685 already around, stored as such in the definition of the function).
5686
5687   You can create your own obarray using @code{make-vector} (this is
5688 horrible but is an artifact) and intern symbols into that obarray.
5689 Doing that will result in two or more symbols with the same name.
5690 However, at most one of these symbols is in the standard @code{obarray}:
5691 You cannot have two symbols of the same name in any particular obarray.
5692 Note that you cannot add a symbol to an obarray in any fashion other
5693 than using @code{intern}: i.e. you can't take an existing symbol and put
5694 it in an existing obarray.  Nor can you change the name of an existing
5695 symbol. (Since obarrays are vectors, you can violate the consistency of
5696 things by storing directly into the vector, but let's ignore that
5697 possibility.)
5698
5699   Usually symbols are created by @code{intern}, but if you really want,
5700 you can explicitly create a symbol using @code{make-symbol}, giving it
5701 some name.  The resulting symbol is not in any obarray (i.e. it is
5702 @dfn{uninterned}), and you can't add it to any obarray.  Therefore its
5703 primary purpose is as a symbol to use in macros to avoid namespace
5704 pollution.  It can also be used as a carrier of information, but cons
5705 cells could probably be used just as well.
5706
5707   You can also use @code{intern-soft} to look up a symbol but not create
5708 a new one, and @code{unintern} to remove a symbol from an obarray.  This
5709 returns the removed symbol. (Remember: You can't put the symbol back
5710 into any obarray.) Finally, @code{mapatoms} maps over all of the symbols
5711 in an obarray.
5712
5713 @node Symbol Values
5714 @section Symbol Values
5715
5716   The value field of a symbol normally contains a Lisp object.  However,
5717 a symbol can be @dfn{unbound}, meaning that it logically has no value.
5718 This is internally indicated by storing a special Lisp object, called
5719 @dfn{the unbound marker} and stored in the global variable
5720 @code{Qunbound}.  The unbound marker is of a special Lisp object type
5721 called @dfn{symbol-value-magic}.  It is impossible for the Lisp
5722 programmer to directly create or access any object of this type.
5723
5724   @strong{You must not let any ``symbol-value-magic'' object escape to
5725 the Lisp level.}  Printing any of these objects will cause the message
5726 @samp{INTERNAL EMACS BUG} to appear as part of the print representation.
5727 (You may see this normally when you call @code{debug_print()} from the
5728 debugger on a Lisp object.) If you let one of these objects escape to
5729 the Lisp level, you will violate a number of assumptions contained in
5730 the C code and make the unbound marker not function right.
5731
5732   When a symbol is created, its value field (and function field) are set
5733 to @code{Qunbound}.  The Lisp programmer can restore these conditions
5734 later using @code{makunbound} or @code{fmakunbound}, and can query to
5735 see whether the value of function fields are @dfn{bound} (i.e. have a
5736 value other than @code{Qunbound}) using @code{boundp} and
5737 @code{fboundp}.  The fields are set to a normal Lisp object using
5738 @code{set} (or @code{setq}) and @code{fset}.
5739
5740   Other symbol-value-magic objects are used as special markers to
5741 indicate variables that have non-normal properties.  This includes any
5742 variables that are tied into C variables (setting the variable magically
5743 sets some global variable in the C code, and likewise for retrieving the
5744 variable's value), variables that magically tie into slots in the
5745 current buffer, variables that are buffer-local, etc.  The
5746 symbol-value-magic object is stored in the value cell in place of
5747 a normal object, and the code to retrieve a symbol's value
5748 (i.e. @code{symbol-value}) knows how to do special things with them.
5749 This means that you should not just fetch the value cell directly if you
5750 want a symbol's value.
5751
5752   The exact workings of this are rather complex and involved and are
5753 well-documented in comments in @file{buffer.c}, @file{symbols.c}, and
5754 @file{lisp.h}.
5755
5756 @node Buffers and Textual Representation, MULE Character Sets and Encodings, Symbols and Variables, Top
5757 @chapter Buffers and Textual Representation
5758
5759 @menu
5760 * Introduction to Buffers::     A buffer holds a block of text such as a file.
5761 * The Text in a Buffer::        Representation of the text in a buffer.
5762 * Buffer Lists::                Keeping track of all buffers.
5763 * Markers and Extents::         Tagging locations within a buffer.
5764 * Bufbytes and Emchars::        Representation of individual characters.
5765 * The Buffer Object::           The Lisp object corresponding to a buffer.
5766 @end menu
5767
5768 @node Introduction to Buffers
5769 @section Introduction to Buffers
5770
5771   A buffer is logically just a Lisp object that holds some text.
5772 In this, it is like a string, but a buffer is optimized for
5773 frequent insertion and deletion, while a string is not.  Furthermore:
5774
5775 @enumerate
5776 @item
5777 Buffers are @dfn{permanent} objects, i.e. once you create them, they
5778 remain around, and need to be explicitly deleted before they go away.
5779 @item
5780 Each buffer has a unique name, which is a string.  Buffers are
5781 normally referred to by name.  In this respect, they are like
5782 symbols.
5783 @item
5784 Buffers have a default insertion position, called @dfn{point}.
5785 Inserting text (unless you explicitly give a position) goes at point,
5786 and moves point forward past the text.  This is what is going on when
5787 you type text into Emacs.
5788 @item
5789 Buffers have lots of extra properties associated with them.
5790 @item
5791 Buffers can be @dfn{displayed}.  What this means is that there
5792 exist a number of @dfn{windows}, which are objects that correspond
5793 to some visible section of your display, and each window has
5794 an associated buffer, and the current contents of the buffer
5795 are shown in that section of the display.  The redisplay mechanism
5796 (which takes care of doing this) knows how to look at the
5797 text of a buffer and come up with some reasonable way of displaying
5798 this.  Many of the properties of a buffer control how the
5799 buffer's text is displayed.
5800 @item
5801 One buffer is distinguished and called the @dfn{current buffer}.  It is
5802 stored in the variable @code{current_buffer}.  Buffer operations operate
5803 on this buffer by default.  When you are typing text into a buffer, the
5804 buffer you are typing into is always @code{current_buffer}.  Switching
5805 to a different window changes the current buffer.  Note that Lisp code
5806 can temporarily change the current buffer using @code{set-buffer} (often
5807 enclosed in a @code{save-excursion} so that the former current buffer
5808 gets restored when the code is finished).  However, calling
5809 @code{set-buffer} will NOT cause a permanent change in the current
5810 buffer.  The reason for this is that the top-level event loop sets
5811 @code{current_buffer} to the buffer of the selected window, each time 
5812 it finishes executing a user command.
5813 @end enumerate
5814
5815   Make sure you understand the distinction between @dfn{current buffer}
5816 and @dfn{buffer of the selected window}, and the distinction between
5817 @dfn{point} of the current buffer and @dfn{window-point} of the selected
5818 window. (This latter distinction is explained in detail in the section
5819 on windows.)
5820
5821 @node The Text in a Buffer
5822 @section The Text in a Buffer
5823
5824   The text in a buffer consists of a sequence of zero or more
5825 characters.  A @dfn{character} is an integer that logically represents
5826 a letter, number, space, or other unit of text.  Most of the characters
5827 that you will typically encounter belong to the ASCII set of characters,
5828 but there are also characters for various sorts of accented letters,
5829 special symbols, Chinese and Japanese ideograms (i.e. Kanji, Katakana,
5830 etc.), Cyrillic and Greek letters, etc.  The actual number of possible
5831 characters is quite large.
5832
5833   For now, we can view a character as some non-negative integer that
5834 has some shape that defines how it typically appears (e.g. as an
5835 uppercase A). (The exact way in which a character appears depends on the
5836 font used to display the character.) The internal type of characters in
5837 the C code is an @code{Emchar}; this is just an @code{int}, but using a
5838 symbolic type makes the code clearer.
5839
5840   Between every character in a buffer is a @dfn{buffer position} or
5841 @dfn{character position}.  We can speak of the character before or after
5842 a particular buffer position, and when you insert a character at a
5843 particular position, all characters after that position end up at new
5844 positions.  When we speak of the character @dfn{at} a position, we
5845 really mean the character after the position.  (This schizophrenia
5846 between a buffer position being ``between'' a character and ``on'' a
5847 character is rampant in Emacs.)
5848
5849   Buffer positions are numbered starting at 1.  This means that
5850 position 1 is before the first character, and position 0 is not
5851 valid.  If there are N characters in a buffer, then buffer
5852 position N+1 is after the last one, and position N+2 is not valid.
5853
5854   The internal makeup of the Emchar integer varies depending on whether
5855 we have compiled with MULE support.  If not, the Emchar integer is an
5856 8-bit integer with possible values from 0 - 255.  0 - 127 are the
5857 standard ASCII characters, while 128 - 255 are the characters from the
5858 ISO-8859-1 character set.  If we have compiled with MULE support, an
5859 Emchar is a 19-bit integer, with the various bits having meanings
5860 according to a complex scheme that will be detailed later.  The
5861 characters numbered 0 - 255 still have the same meanings as for the
5862 non-MULE case, though.
5863
5864   Internally, the text in a buffer is represented in a fairly simple
5865 fashion: as a contiguous array of bytes, with a @dfn{gap} of some size
5866 in the middle.  Although the gap is of some substantial size in bytes,
5867 there is no text contained within it: From the perspective of the text
5868 in the buffer, it does not exist.  The gap logically sits at some buffer
5869 position, between two characters (or possibly at the beginning or end of
5870 the buffer).  Insertion of text in a buffer at a particular position is
5871 always accomplished by first moving the gap to that position
5872 (i.e. through some block moving of text), then writing the text into the
5873 beginning of the gap, thereby shrinking the gap.  If the gap shrinks
5874 down to nothing, a new gap is created. (What actually happens is that a
5875 new gap is ``created'' at the end of the buffer's text, which requires
5876 nothing more than changing a couple of indices; then the gap is
5877 ``moved'' to the position where the insertion needs to take place by
5878 moving up in memory all the text after that position.)  Similarly,
5879 deletion occurs by moving the gap to the place where the text is to be
5880 deleted, and then simply expanding the gap to include the deleted text.
5881 (@dfn{Expanding} and @dfn{shrinking} the gap as just described means
5882 just that the internal indices that keep track of where the gap is
5883 located are changed.)
5884
5885   Note that the total amount of memory allocated for a buffer text never
5886 decreases while the buffer is live.  Therefore, if you load up a
5887 20-megabyte file and then delete all but one character, there will be a
5888 20-megabyte gap, which won't get any smaller (except by inserting
5889 characters back again).  Once the buffer is killed, the memory allocated
5890 for the buffer text will be freed, but it will still be sitting on the
5891 heap, taking up virtual memory, and will not be released back to the
5892 operating system. (However, if you have compiled XEmacs with rel-alloc,
5893 the situation is different.  In this case, the space @emph{will} be
5894 released back to the operating system.  However, this tends to result in a
5895 noticeable speed penalty.)
5896
5897   Astute readers may notice that the text in a buffer is represented as
5898 an array of @emph{bytes}, while (at least in the MULE case) an Emchar is
5899 a 19-bit integer, which clearly cannot fit in a byte.  This means (of
5900 course) that the text in a buffer uses a different representation from
5901 an Emchar: specifically, the 19-bit Emchar becomes a series of one to
5902 four bytes.  The conversion between these two representations is complex
5903 and will be described later.
5904
5905   In the non-MULE case, everything is very simple: An Emchar
5906 is an 8-bit value, which fits neatly into one byte.
5907
5908   If we are given a buffer position and want to retrieve the
5909 character at that position, we need to follow these steps:
5910
5911 @enumerate
5912 @item
5913 Pretend there's no gap, and convert the buffer position into a @dfn{byte
5914 index} that indexes to the appropriate byte in the buffer's stream of
5915 textual bytes.  By convention, byte indices begin at 1, just like buffer
5916 positions.  In the non-MULE case, byte indices and buffer positions are
5917 identical, since one character equals one byte.
5918 @item
5919 Convert the byte index into a @dfn{memory index}, which takes the gap
5920 into account.  The memory index is a direct index into the block of
5921 memory that stores the text of a buffer.  This basically just involves
5922 checking to see if the byte index is past the gap, and if so, adding the
5923 size of the gap to it.  By convention, memory indices begin at 1, just
5924 like buffer positions and byte indices, and when referring to the
5925 position that is @dfn{at} the gap, we always use the memory position at
5926 the @emph{beginning}, not at the end, of the gap.
5927 @item
5928 Fetch the appropriate bytes at the determined memory position.
5929 @item
5930 Convert these bytes into an Emchar.
5931 @end enumerate
5932
5933   In the non-Mule case, (3) and (4) boil down to a simple one-byte
5934 memory access.
5935
5936   Note that we have defined three types of positions in a buffer:
5937
5938 @enumerate
5939 @item
5940 @dfn{buffer positions} or @dfn{character positions}, typedef @code{Bufpos}
5941 @item
5942 @dfn{byte indices}, typedef @code{Bytind}
5943 @item
5944 @dfn{memory indices}, typedef @code{Memind}
5945 @end enumerate
5946
5947   All three typedefs are just @code{int}s, but defining them this way makes
5948 things a lot clearer.
5949
5950   Most code works with buffer positions.  In particular, all Lisp code
5951 that refers to text in a buffer uses buffer positions.  Lisp code does
5952 not know that byte indices or memory indices exist.
5953
5954   Finally, we have a typedef for the bytes in a buffer.  This is a
5955 @code{Bufbyte}, which is an unsigned char.  Referring to them as
5956 Bufbytes underscores the fact that we are working with a string of bytes
5957 in the internal Emacs buffer representation rather than in one of a
5958 number of possible alternative representations (e.g. EUC-encoded text,
5959 etc.).
5960
5961 @node Buffer Lists
5962 @section Buffer Lists
5963
5964   Recall earlier that buffers are @dfn{permanent} objects, i.e.  that
5965 they remain around until explicitly deleted.  This entails that there is
5966 a list of all the buffers in existence.  This list is actually an
5967 assoc-list (mapping from the buffer's name to the buffer) and is stored
5968 in the global variable @code{Vbuffer_alist}.
5969
5970   The order of the buffers in the list is important: the buffers are
5971 ordered approximately from most-recently-used to least-recently-used.
5972 Switching to a buffer using @code{switch-to-buffer},
5973 @code{pop-to-buffer}, etc. and switching windows using
5974 @code{other-window}, etc.  usually brings the new current buffer to the
5975 front of the list.  @code{switch-to-buffer}, @code{other-buffer},
5976 etc. look at the beginning of the list to find an alternative buffer to
5977 suggest.  You can also explicitly move a buffer to the end of the list
5978 using @code{bury-buffer}.
5979
5980   In addition to the global ordering in @code{Vbuffer_alist}, each frame
5981 has its own ordering of the list.  These lists always contain the same
5982 elements as in @code{Vbuffer_alist} although possibly in a different
5983 order.  @code{buffer-list} normally returns the list for the selected
5984 frame.  This allows you to work in separate frames without things
5985 interfering with each other.
5986
5987   The standard way to look up a buffer given a name is
5988 @code{get-buffer}, and the standard way to create a new buffer is
5989 @code{get-buffer-create}, which looks up a buffer with a given name,
5990 creating a new one if necessary.  These operations correspond exactly
5991 with the symbol operations @code{intern-soft} and @code{intern},
5992 respectively.  You can also force a new buffer to be created using
5993 @code{generate-new-buffer}, which takes a name and (if necessary) makes
5994 a unique name from this by appending a number, and then creates the
5995 buffer.  This is basically like the symbol operation @code{gensym}.
5996
5997 @node Markers and Extents
5998 @section Markers and Extents
5999
6000   Among the things associated with a buffer are things that are
6001 logically attached to certain buffer positions.  This can be used to
6002 keep track of a buffer position when text is inserted and deleted, so
6003 that it remains at the same spot relative to the text around it; to
6004 assign properties to particular sections of text; etc.  There are two
6005 such objects that are useful in this regard: they are @dfn{markers} and
6006 @dfn{extents}.
6007
6008   A @dfn{marker} is simply a flag placed at a particular buffer
6009 position, which is moved around as text is inserted and deleted.
6010 Markers are used for all sorts of purposes, such as the @code{mark} that
6011 is the other end of textual regions to be cut, copied, etc.
6012
6013   An @dfn{extent} is similar to two markers plus some associated
6014 properties, and is used to keep track of regions in a buffer as text is
6015 inserted and deleted, and to add properties (e.g. fonts) to particular
6016 regions of text.  The external interface of extents is explained
6017 elsewhere.
6018
6019   The important thing here is that markers and extents simply contain
6020 buffer positions in them as integers, and every time text is inserted or
6021 deleted, these positions must be updated.  In order to minimize the
6022 amount of shuffling that needs to be done, the positions in markers and
6023 extents (there's one per marker, two per extent) and stored in Meminds.
6024 This means that they only need to be moved when the text is physically
6025 moved in memory; since the gap structure tries to minimize this, it also
6026 minimizes the number of marker and extent indices that need to be
6027 adjusted.  Look in @file{insdel.c} for the details of how this works.
6028
6029   One other important distinction is that markers are @dfn{temporary}
6030 while extents are @dfn{permanent}.  This means that markers disappear as
6031 soon as there are no more pointers to them, and correspondingly, there
6032 is no way to determine what markers are in a buffer if you are just
6033 given the buffer.  Extents remain in a buffer until they are detached
6034 (which could happen as a result of text being deleted) or the buffer is
6035 deleted, and primitives do exist to enumerate the extents in a buffer.
6036
6037 @node Bufbytes and Emchars
6038 @section Bufbytes and Emchars
6039
6040   Not yet documented.
6041
6042 @node The Buffer Object
6043 @section The Buffer Object
6044
6045   Buffers contain fields not directly accessible by the Lisp programmer.
6046 We describe them here, naming them by the names used in the C code.
6047 Many are accessible indirectly in Lisp programs via Lisp primitives.
6048
6049 @table @code
6050 @item name
6051 The buffer name is a string that names the buffer.  It is guaranteed to
6052 be unique.  @xref{Buffer Names,,, lispref, XEmacs Lisp Programmer's
6053 Manual}.
6054
6055 @item save_modified
6056 This field contains the time when the buffer was last saved, as an
6057 integer.  @xref{Buffer Modification,,, lispref, XEmacs Lisp Programmer's
6058 Manual}.
6059
6060 @item modtime
6061 This field contains the modification time of the visited file.  It is
6062 set when the file is written or read.  Every time the buffer is written
6063 to the file, this field is compared to the modification time of the
6064 file.  @xref{Buffer Modification,,, lispref, XEmacs Lisp Programmer's
6065 Manual}.
6066
6067 @item auto_save_modified
6068 This field contains the time when the buffer was last auto-saved.
6069
6070 @item last_window_start
6071 This field contains the @code{window-start} position in the buffer as of
6072 the last time the buffer was displayed in a window.
6073
6074 @item undo_list
6075 This field points to the buffer's undo list.  @xref{Undo,,, lispref,
6076 XEmacs Lisp Programmer's Manual}.
6077
6078 @item syntax_table_v
6079 This field contains the syntax table for the buffer.  @xref{Syntax
6080 Tables,,, lispref, XEmacs Lisp Programmer's Manual}.
6081
6082 @item downcase_table
6083 This field contains the conversion table for converting text to lower
6084 case.  @xref{Case Tables,,, lispref, XEmacs Lisp Programmer's Manual}.
6085
6086 @item upcase_table
6087 This field contains the conversion table for converting text to upper
6088 case.  @xref{Case Tables,,, lispref, XEmacs Lisp Programmer's Manual}.
6089
6090 @item case_canon_table
6091 This field contains the conversion table for canonicalizing text for
6092 case-folding search.  @xref{Case Tables,,, lispref, XEmacs Lisp
6093 Programmer's Manual}.
6094
6095 @item case_eqv_table
6096 This field contains the equivalence table for case-folding search.
6097 @xref{Case Tables,,, lispref, XEmacs Lisp Programmer's Manual}.
6098
6099 @item display_table
6100 This field contains the buffer's display table, or @code{nil} if it
6101 doesn't have one.  @xref{Display Tables,,, lispref, XEmacs Lisp
6102 Programmer's Manual}.
6103
6104 @item markers
6105 This field contains the chain of all markers that currently point into
6106 the buffer.  Deletion of text in the buffer, and motion of the buffer's
6107 gap, must check each of these markers and perhaps update it.
6108 @xref{Markers,,, lispref, XEmacs Lisp Programmer's Manual}.
6109
6110 @item backed_up
6111 This field is a flag that tells whether a backup file has been made for
6112 the visited file of this buffer.
6113
6114 @item mark
6115 This field contains the mark for the buffer.  The mark is a marker,
6116 hence it is also included on the list @code{markers}.  @xref{The Mark,,,
6117 lispref, XEmacs Lisp Programmer's Manual}.
6118
6119 @item mark_active
6120 This field is non-@code{nil} if the buffer's mark is active.
6121
6122 @item local_var_alist
6123 This field contains the association list describing the variables local
6124 in this buffer, and their values, with the exception of local variables
6125 that have special slots in the buffer object.  (Those slots are omitted
6126 from this table.)  @xref{Buffer-Local Variables,,, lispref, XEmacs Lisp
6127 Programmer's Manual}.
6128
6129 @item modeline_format
6130 This field contains a Lisp object which controls how to display the mode
6131 line for this buffer.  @xref{Modeline Format,,, lispref, XEmacs Lisp
6132 Programmer's Manual}.
6133
6134 @item base_buffer
6135 This field holds the buffer's base buffer (if it is an indirect buffer),
6136 or @code{nil}.
6137 @end table
6138
6139 @node MULE Character Sets and Encodings, The Lisp Reader and Compiler, Buffers and Textual Representation, Top
6140 @chapter MULE Character Sets and Encodings
6141
6142   Recall that there are two primary ways that text is represented in
6143 XEmacs.  The @dfn{buffer} representation sees the text as a series of
6144 bytes (Bufbytes), with a variable number of bytes used per character.
6145 The @dfn{character} representation sees the text as a series of integers
6146 (Emchars), one per character.  The character representation is a cleaner
6147 representation from a theoretical standpoint, and is thus used in many
6148 cases when lots of manipulations on a string need to be done.  However,
6149 the buffer representation is the standard representation used in both
6150 Lisp strings and buffers, and because of this, it is the ``default''
6151 representation that text comes in.  The reason for using this
6152 representation is that it's compact and is compatible with ASCII.
6153
6154 @menu
6155 * Character Sets::
6156 * Encodings::
6157 * Internal Mule Encodings::
6158 * CCL::
6159 @end menu
6160
6161 @node Character Sets
6162 @section Character Sets
6163
6164   A character set (or @dfn{charset}) is an ordered set of characters.  A
6165 particular character in a charset is indexed using one or more
6166 @dfn{position codes}, which are non-negative integers.  The number of
6167 position codes needed to identify a particular character in a charset is
6168 called the @dfn{dimension} of the charset.  In XEmacs/Mule, all charsets
6169 have dimension 1 or 2, and the size of all charsets (except for a few
6170 special cases) is either 94, 96, 94 by 94, or 96 by 96.  The range of
6171 position codes used to index characters from any of these types of
6172 character sets is as follows:
6173
6174 @example
6175 Charset type            Position code 1         Position code 2
6176 ------------------------------------------------------------
6177 94                      33 - 126                N/A
6178 96                      32 - 127                N/A
6179 94x94                   33 - 126                33 - 126
6180 96x96                   32 - 127                32 - 127
6181 @end example
6182
6183   Note that in the above cases position codes do not start at an
6184 expected value such as 0 or 1.  The reason for this will become clear
6185 later.
6186
6187   For example, Latin-1 is a 96-character charset, and JISX0208 (the
6188 Japanese national character set) is a 94x94-character charset.
6189
6190   [Note that, although the ranges above define the @emph{valid} position
6191 codes for a charset, some of the slots in a particular charset may in
6192 fact be empty.  This is the case for JISX0208, for example, where (e.g.)
6193 all the slots whose first position code is in the range 118 - 127 are
6194 empty.]
6195
6196   There are three charsets that do not follow the above rules.  All of
6197 them have one dimension, and have ranges of position codes as follows:
6198
6199 @example
6200 Charset name            Position code 1
6201 ------------------------------------
6202 ASCII                   0 - 127
6203 Control-1               0 - 31
6204 Composite               0 - some large number
6205 @end example
6206
6207   (The upper bound of the position code for composite characters has not
6208 yet been determined, but it will probably be at least 16,383).
6209
6210   ASCII is the union of two subsidiary character sets: Printing-ASCII
6211 (the printing ASCII character set, consisting of position codes 33 -
6212 126, like for a standard 94-character charset) and Control-ASCII (the
6213 non-printing characters that would appear in a binary file with codes 0
6214 - 32 and 127).
6215
6216   Control-1 contains the non-printing characters that would appear in a
6217 binary file with codes 128 - 159.
6218
6219   Composite contains characters that are generated by overstriking one
6220 or more characters from other charsets.
6221
6222   Note that some characters in ASCII, and all characters in Control-1,
6223 are @dfn{control} (non-printing) characters.  These have no printed
6224 representation but instead control some other function of the printing
6225 (e.g. TAB or 8 moves the current character position to the next tab
6226 stop).  All other characters in all charsets are @dfn{graphic}
6227 (printing) characters.
6228
6229   When a binary file is read in, the bytes in the file are assigned to
6230 character sets as follows:
6231
6232 @example
6233 Bytes           Character set           Range
6234 --------------------------------------------------
6235 0 - 127         ASCII                   0 - 127
6236 128 - 159       Control-1               0 - 31
6237 160 - 255       Latin-1                 32 - 127
6238 @end example
6239
6240   This is a bit ad-hoc but gets the job done.
6241
6242 @node Encodings
6243 @section Encodings
6244
6245   An @dfn{encoding} is a way of numerically representing characters from
6246 one or more character sets.  If an encoding only encompasses one
6247 character set, then the position codes for the characters in that
6248 character set could be used directly.  This is not possible, however, if
6249 more than one character set is to be used in the encoding.
6250
6251   For example, the conversion detailed above between bytes in a binary
6252 file and characters is effectively an encoding that encompasses the
6253 three character sets ASCII, Control-1, and Latin-1 in a stream of 8-bit
6254 bytes.
6255
6256   Thus, an encoding can be viewed as a way of encoding characters from a
6257 specified group of character sets using a stream of bytes, each of which
6258 contains a fixed number of bits (but not necessarily 8, as in the common
6259 usage of ``byte'').
6260
6261   Here are descriptions of a couple of common
6262 encodings:
6263
6264 @menu
6265 * Japanese EUC (Extended Unix Code)::
6266 * JIS7::
6267 @end menu
6268
6269 @node Japanese EUC (Extended Unix Code)
6270 @subsection Japanese EUC (Extended Unix Code)
6271
6272 This encompasses the character sets Printing-ASCII, Japanese-JISSX0201,
6273 and Japanese-JISX0208-Kana (half-width katakana, the right half of
6274 JISX0201).  It uses 8-bit bytes.
6275
6276 Note that Printing-ASCII and Japanese-JISX0201-Kana are 94-character
6277 charsets, while Japanese-JISX0208 is a 94x94-character charset.
6278
6279 The encoding is as follows:
6280
6281 @example
6282 Character set            Representation (PC=position-code)
6283 -------------            --------------
6284 Printing-ASCII           PC1
6285 Japanese-JISX0201-Kana   0x8E       | PC1 + 0x80
6286 Japanese-JISX0208        PC1 + 0x80 | PC2 + 0x80
6287 Japanese-JISX0212        PC1 + 0x80 | PC2 + 0x80
6288 @end example
6289
6290
6291 @node JIS7
6292 @subsection JIS7
6293
6294 This encompasses the character sets Printing-ASCII,
6295 Japanese-JISX0201-Roman (the left half of JISX0201; this character set
6296 is very similar to Printing-ASCII and is a 94-character charset),
6297 Japanese-JISX0208, and Japanese-JISX0201-Kana.  It uses 7-bit bytes.
6298
6299 Unlike Japanese EUC, this is a @dfn{modal} encoding, which
6300 means that there are multiple states that the encoding can
6301 be in, which affect how the bytes are to be interpreted.
6302 Special sequences of bytes (called @dfn{escape sequences})
6303 are used to change states.
6304
6305   The encoding is as follows:
6306
6307 @example
6308 Character set              Representation (PC=position-code)
6309 -------------              --------------
6310 Printing-ASCII             PC1
6311 Japanese-JISX0201-Roman    PC1
6312 Japanese-JISX0201-Kana     PC1
6313 Japanese-JISX0208          PC1 PC2
6314
6315
6316 Escape sequence   ASCII equivalent   Meaning
6317 ---------------   ----------------   -------
6318 0x1B 0x28 0x4A    ESC ( J            invoke Japanese-JISX0201-Roman
6319 0x1B 0x28 0x49    ESC ( I            invoke Japanese-JISX0201-Kana
6320 0x1B 0x24 0x42    ESC $ B            invoke Japanese-JISX0208
6321 0x1B 0x28 0x42    ESC ( B            invoke Printing-ASCII
6322 @end example
6323
6324   Initially, Printing-ASCII is invoked.
6325
6326 @node Internal Mule Encodings
6327 @section Internal Mule Encodings
6328
6329 In XEmacs/Mule, each character set is assigned a unique number, called a
6330 @dfn{leading byte}.  This is used in the encodings of a character.
6331 Leading bytes are in the range 0x80 - 0xFF (except for ASCII, which has
6332 a leading byte of 0), although some leading bytes are reserved.
6333
6334 Charsets whose leading byte is in the range 0x80 - 0x9F are called
6335 @dfn{official} and are used for built-in charsets.  Other charsets are
6336 called @dfn{private} and have leading bytes in the range 0xA0 - 0xFF;
6337 these are user-defined charsets.
6338
6339   More specifically:
6340
6341 @example
6342 Character set           Leading byte
6343 -------------           ------------
6344 ASCII                   0
6345 Composite               0x80
6346 Dimension-1 Official    0x81 - 0x8D
6347                           (0x8E is free)
6348 Control-1               0x8F
6349 Dimension-2 Official    0x90 - 0x99
6350                           (0x9A - 0x9D are free;
6351                            0x9E and 0x9F are reserved)
6352 Dimension-1 Private     0xA0 - 0xEF
6353 Dimension-2 Private     0xF0 - 0xFF
6354 @end example
6355
6356 There are two internal encodings for characters in XEmacs/Mule.  One is
6357 called @dfn{string encoding} and is an 8-bit encoding that is used for
6358 representing characters in a buffer or string.  It uses 1 to 4 bytes per
6359 character.  The other is called @dfn{character encoding} and is a 19-bit
6360 encoding that is used for representing characters individually in a
6361 variable.
6362
6363 (In the following descriptions, we'll ignore composite characters for
6364 the moment.  We also give a general (structural) overview first,
6365 followed later by the exact details.)
6366
6367 @menu
6368 * Internal String Encoding::
6369 * Internal Character Encoding::
6370 @end menu
6371
6372 @node Internal String Encoding
6373 @subsection Internal String Encoding
6374
6375 ASCII characters are encoded using their position code directly.  Other
6376 characters are encoded using their leading byte followed by their
6377 position code(s) with the high bit set.  Characters in private character
6378 sets have their leading byte prefixed with a @dfn{leading byte prefix},
6379 which is either 0x9E or 0x9F. (No character sets are ever assigned these
6380 leading bytes.) Specifically:
6381
6382 @example
6383 Character set           Encoding (PC=position-code, LB=leading-byte)
6384 -------------           --------
6385 ASCII                   PC-1 |
6386 Control-1               LB   |  PC1 + 0xA0 |
6387 Dimension-1 official    LB   |  PC1 + 0x80 |
6388 Dimension-1 private     0x9E |  LB         | PC1 + 0x80 |
6389 Dimension-2 official    LB   |  PC1 + 0x80 | PC2 + 0x80 |
6390 Dimension-2 private     0x9F |  LB         | PC1 + 0x80 | PC2 + 0x80
6391 @end example
6392
6393   The basic characteristic of this encoding is that the first byte
6394 of all characters is in the range 0x00 - 0x9F, and the second and
6395 following bytes of all characters is in the range 0xA0 - 0xFF.
6396 This means that it is impossible to get out of sync, or more
6397 specifically:
6398
6399 @enumerate
6400 @item
6401 Given any byte position, the beginning of the character it is
6402 within can be determined in constant time.
6403 @item
6404 Given any byte position at the beginning of a character, the
6405 beginning of the next character can be determined in constant
6406 time.
6407 @item
6408 Given any byte position at the beginning of a character, the
6409 beginning of the previous character can be determined in constant
6410 time.
6411 @item
6412 Textual searches can simply treat encoded strings as if they
6413 were encoded in a one-byte-per-character fashion rather than
6414 the actual multi-byte encoding.
6415 @end enumerate
6416
6417   None of the standard non-modal encodings meet all of these
6418 conditions.  For example, EUC satisfies only (2) and (3), while
6419 Shift-JIS and Big5 (not yet described) satisfy only (2). (All
6420 non-modal encodings must satisfy (2), in order to be unambiguous.)
6421
6422 @node Internal Character Encoding
6423 @subsection Internal Character Encoding
6424
6425   One 19-bit word represents a single character.  The word is
6426 separated into three fields:
6427
6428 @example
6429 Bit number:     18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01 00
6430                 <------------> <------------------> <------------------>
6431 Field:                1                  2                    3
6432 @end example
6433
6434   Note that fields 2 and 3 hold 7 bits each, while field 1 holds 5 bits.
6435
6436 @example
6437 Character set           Field 1         Field 2         Field 3
6438 -------------           -------         -------         -------
6439 ASCII                      0               0              PC1
6440    range:                                                   (00 - 7F)
6441 Control-1                  0               1              PC1
6442    range:                                                   (00 - 1F)
6443 Dimension-1 official       0            LB - 0x80         PC1
6444    range:                                    (01 - 0D)      (20 - 7F)
6445 Dimension-1 private        0            LB - 0x80         PC1
6446    range:                                    (20 - 6F)      (20 - 7F)
6447 Dimension-2 official    LB - 0x8F         PC1             PC2
6448    range:                    (01 - 0A)       (20 - 7F)      (20 - 7F)
6449 Dimension-2 private     LB - 0xE1         PC1             PC2
6450    range:                    (0F - 1E)       (20 - 7F)      (20 - 7F)
6451 Composite                 0x1F             ?               ?
6452 @end example
6453
6454   Note that character codes 0 - 255 are the same as the ``binary encoding''
6455 described above.
6456
6457 @node CCL
6458 @section CCL
6459
6460 @example
6461 CCL PROGRAM SYNTAX:
6462         CCL_PROGRAM := (CCL_MAIN_BLOCK
6463                         [ CCL_EOF_BLOCK ])
6464
6465         CCL_MAIN_BLOCK := CCL_BLOCK
6466         CCL_EOF_BLOCK := CCL_BLOCK
6467
6468         CCL_BLOCK := STATEMENT | (STATEMENT [STATEMENT ...])
6469         STATEMENT :=
6470                 SET | IF | BRANCH | LOOP | REPEAT | BREAK
6471                 | READ | WRITE
6472
6473         SET := (REG = EXPRESSION) | (REG SELF_OP EXPRESSION)
6474                | INT-OR-CHAR
6475
6476         EXPRESSION := ARG | (EXPRESSION OP ARG)
6477
6478         IF := (if EXPRESSION CCL_BLOCK CCL_BLOCK)
6479         BRANCH := (branch EXPRESSION CCL_BLOCK [CCL_BLOCK ...])
6480         LOOP := (loop STATEMENT [STATEMENT ...])
6481         BREAK := (break)
6482         REPEAT := (repeat)
6483                 | (write-repeat [REG | INT-OR-CHAR | string])
6484                 | (write-read-repeat REG [INT-OR-CHAR | string | ARRAY]?)
6485         READ := (read REG) | (read REG REG)
6486                 | (read-if REG ARITH_OP ARG CCL_BLOCK CCL_BLOCK)
6487                 | (read-branch REG CCL_BLOCK [CCL_BLOCK ...])
6488         WRITE := (write REG) | (write REG REG)
6489                 | (write INT-OR-CHAR) | (write STRING) | STRING
6490                 | (write REG ARRAY)
6491         END := (end)
6492
6493         REG := r0 | r1 | r2 | r3 | r4 | r5 | r6 | r7
6494         ARG := REG | INT-OR-CHAR
6495         OP :=   + | - | * | / | % | & | '|' | ^ | << | >> | <8 | >8 | //
6496                 | < | > | == | <= | >= | !=
6497         SELF_OP :=
6498                 += | -= | *= | /= | %= | &= | '|=' | ^= | <<= | >>=
6499         ARRAY := '[' INT-OR-CHAR ... ']'
6500         INT-OR-CHAR := INT | CHAR
6501
6502 MACHINE CODE:
6503
6504 The machine code consists of a vector of 32-bit words.
6505 The first such word specifies the start of the EOF section of the code;
6506 this is the code executed to handle any stuff that needs to be done
6507 (e.g. designating back to ASCII and left-to-right mode) after all
6508 other encoded/decoded data has been written out.  This is not used for
6509 charset CCL programs.
6510
6511 REGISTER: 0..7  -- refered by RRR or rrr
6512
6513 OPERATOR BIT FIELD (27-bit): XXXXXXXXXXXXXXX RRR TTTTT
6514         TTTTT (5-bit): operator type
6515         RRR (3-bit): register number
6516         XXXXXXXXXXXXXXXX (15-bit):
6517                 CCCCCCCCCCCCCCC: constant or address
6518                 000000000000rrr: register number
6519
6520 AAAA:   00000 + 
6521         00001 - 
6522         00010 * 
6523         00011 / 
6524         00100 % 
6525         00101 & 
6526         00110 | 
6527         00111 ~
6528
6529         01000 <<
6530         01001 >>
6531         01010 <8
6532         01011 >8
6533         01100 //
6534         01101 not used
6535         01110 not used
6536         01111 not used
6537
6538         10000 < 
6539         10001 > 
6540         10010 ==
6541         10011 <=
6542         10100 >=
6543         10101 !=
6544
6545 OPERATORS:      TTTTT RRR XX..
6546
6547 SetCS:          00000 RRR C...C         RRR = C...C
6548 SetCL:          00001 RRR .....         RRR = c...c
6549                 c.............c
6550 SetR:           00010 RRR ..rrr         RRR = rrr
6551 SetA:           00011 RRR ..rrr         RRR = array[rrr]
6552                 C.............C         size of array = C...C
6553                 c.............c         contents = c...c
6554
6555 Jump:           00100 000 c...c         jump to c...c
6556 JumpCond:       00101 RRR c...c         if (!RRR) jump to c...c
6557 WriteJump:      00110 RRR c...c         Write1 RRR, jump to c...c
6558 WriteReadJump:  00111 RRR c...c         Write1, Read1 RRR, jump to c...c
6559 WriteCJump:     01000 000 c...c         Write1 C...C, jump to c...c
6560                 C...C
6561 WriteCReadJump: 01001 RRR c...c         Write1 C...C, Read1 RRR,
6562                 C.............C         and jump to c...c
6563 WriteSJump:     01010 000 c...c         WriteS, jump to c...c
6564                 C.............C
6565                 S.............S
6566                 ...
6567 WriteSReadJump: 01011 RRR c...c         WriteS, Read1 RRR, jump to c...c
6568                 C.............C
6569                 S.............S
6570                 ...
6571 WriteAReadJump: 01100 RRR c...c         WriteA, Read1 RRR, jump to c...c
6572                 C.............C         size of array = C...C
6573                 c.............c         contents = c...c
6574                 ...
6575 Branch:         01101 RRR C...C         if (RRR >= 0 && RRR < C..)
6576                 c.............c         branch to (RRR+1)th address
6577 Read1:          01110 RRR ...           read 1-byte to RRR
6578 Read2:          01111 RRR ..rrr         read 2-byte to RRR and rrr
6579 ReadBranch:     10000 RRR C...C         Read1 and Branch
6580                 c.............c
6581                 ...
6582 Write1:         10001 RRR .....         write 1-byte RRR
6583 Write2:         10010 RRR ..rrr         write 2-byte RRR and rrr
6584 WriteC:         10011 000 .....         write 1-char C...CC
6585                 C.............C
6586 WriteS:         10100 000 .....         write C..-byte of string
6587                 C.............C
6588                 S.............S
6589                 ...
6590 WriteA:         10101 RRR .....         write array[RRR]
6591                 C.............C         size of array = C...C
6592                 c.............c         contents = c...c
6593                 ...
6594 End:            10110 000 .....         terminate the execution
6595
6596 SetSelfCS:      10111 RRR C...C         RRR AAAAA= C...C
6597                 ..........AAAAA
6598 SetSelfCL:      11000 RRR .....         RRR AAAAA= c...c
6599                 c.............c
6600                 ..........AAAAA
6601 SetSelfR:       11001 RRR ..Rrr         RRR AAAAA= rrr
6602                 ..........AAAAA
6603 SetExprCL:      11010 RRR ..Rrr         RRR = rrr AAAAA c...c
6604                 c.............c
6605                 ..........AAAAA
6606 SetExprR:       11011 RRR ..rrr         RRR = rrr AAAAA Rrr
6607                 ............Rrr
6608                 ..........AAAAA
6609 JumpCondC:      11100 RRR c...c         if !(RRR AAAAA C..) jump to c...c
6610                 C.............C
6611                 ..........AAAAA
6612 JumpCondR:      11101 RRR c...c         if !(RRR AAAAA rrr) jump to c...c
6613                 ............rrr
6614                 ..........AAAAA
6615 ReadJumpCondC:  11110 RRR c...c         Read1 and JumpCondC
6616                 C.............C
6617                 ..........AAAAA
6618 ReadJumpCondR:  11111 RRR c...c         Read1 and JumpCondR
6619                 ............rrr
6620                 ..........AAAAA
6621 @end example
6622
6623 @node The Lisp Reader and Compiler, Lstreams, MULE Character Sets and Encodings, Top
6624 @chapter The Lisp Reader and Compiler
6625
6626 Not yet documented.
6627
6628 @node Lstreams, Consoles; Devices; Frames; Windows, The Lisp Reader and Compiler, Top
6629 @chapter Lstreams
6630
6631   An @dfn{lstream} is an internal Lisp object that provides a generic
6632 buffering stream implementation.  Conceptually, you send data to the
6633 stream or read data from the stream, not caring what's on the other end
6634 of the stream.  The other end could be another stream, a file
6635 descriptor, a stdio stream, a fixed block of memory, a reallocating
6636 block of memory, etc.  The main purpose of the stream is to provide a
6637 standard interface and to do buffering.  Macros are defined to read or
6638 write characters, so the calling functions do not have to worry about
6639 blocking data together in order to achieve efficiency.
6640
6641 @menu
6642 * Creating an Lstream::         Creating an lstream object.
6643 * Lstream Types::               Different sorts of things that are streamed.
6644 * Lstream Functions::           Functions for working with lstreams.
6645 * Lstream Methods::             Creating new lstream types.
6646 @end menu
6647
6648 @node Creating an Lstream
6649 @section Creating an Lstream
6650
6651 Lstreams come in different types, depending on what is being interfaced
6652 to.  Although the primitive for creating new lstreams is
6653 @code{Lstream_new()}, generally you do not call this directly.  Instead,
6654 you call some type-specific creation function, which creates the lstream
6655 and initializes it as appropriate for the particular type.
6656
6657 All lstream creation functions take a @var{mode} argument, specifying
6658 what mode the lstream should be opened as.  This controls whether the
6659 lstream is for input and output, and optionally whether data should be
6660 blocked up in units of MULE characters.  Note that some types of
6661 lstreams can only be opened for input; others only for output; and
6662 others can be opened either way.  #### Richard Mlynarik thinks that
6663 there should be a strict separation between input and output streams,
6664 and he's probably right.
6665
6666   @var{mode} is a string, one of
6667
6668 @table @code
6669 @item "r"
6670   Open for reading.
6671 @item "w"
6672   Open for writing.
6673 @item "rc"
6674   Open for reading, but ``read'' never returns partial MULE characters.
6675 @item "wc"
6676   Open for writing, but never writes partial MULE characters.
6677 @end table
6678
6679 @node Lstream Types
6680 @section Lstream Types
6681
6682 @table @asis
6683 @item stdio
6684
6685 @item filedesc
6686
6687 @item lisp-string
6688
6689 @item fixed-buffer
6690
6691 @item resizing-buffer
6692
6693 @item dynarr
6694
6695 @item lisp-buffer
6696
6697 @item print
6698
6699 @item decoding
6700
6701 @item encoding
6702 @end table
6703
6704 @node Lstream Functions
6705 @section Lstream Functions
6706
6707 @deftypefun {Lstream *} Lstream_new (Lstream_implementation *@var{imp}, CONST char *@var{mode})
6708 Allocate and return a new Lstream.  This function is not really meant to
6709 be called directly; rather, each stream type should provide its own
6710 stream creation function, which creates the stream and does any other
6711 necessary creation stuff (e.g. opening a file).
6712 @end deftypefun
6713
6714 @deftypefun void Lstream_set_buffering (Lstream *@var{lstr}, Lstream_buffering @var{buffering}, int @var{buffering_size})
6715 Change the buffering of a stream.  See @file{lstream.h}.  By default the
6716 buffering is @code{STREAM_BLOCK_BUFFERED}.
6717 @end deftypefun
6718
6719 @deftypefun int Lstream_flush (Lstream *@var{lstr})
6720 Flush out any pending unwritten data in the stream.  Clear any buffered
6721 input data.  Returns 0 on success, -1 on error.
6722 @end deftypefun
6723
6724 @deftypefn Macro int Lstream_putc (Lstream *@var{stream}, int @var{c})
6725 Write out one byte to the stream.  This is a macro and so it is very
6726 efficient.  The @var{c} argument is only evaluated once but the @var{stream}
6727 argument is evaluated more than once.  Returns 0 on success, -1 on
6728 error.
6729 @end deftypefn
6730
6731 @deftypefn Macro int Lstream_getc (Lstream *@var{stream})
6732 Read one byte from the stream.  This is a macro and so it is very
6733 efficient.  The @var{stream} argument is evaluated more than once.  Return
6734 value is -1 for EOF or error.
6735 @end deftypefn
6736
6737 @deftypefn Macro void Lstream_ungetc (Lstream *@var{stream}, int @var{c})
6738 Push one byte back onto the input queue.  This will be the next byte
6739 read from the stream.  Any number of bytes can be pushed back and will
6740 be read in the reverse order they were pushed back -- most recent
6741 first. (This is necessary for consistency -- if there are a number of
6742 bytes that have been unread and I read and unread a byte, it needs to be
6743 the first to be read again.) This is a macro and so it is very
6744 efficient.  The @var{c} argument is only evaluated once but the @var{stream}
6745 argument is evaluated more than once.
6746 @end deftypefn
6747
6748 @deftypefun int Lstream_fputc (Lstream *@var{stream}, int @var{c})
6749 @deftypefunx int Lstream_fgetc (Lstream *@var{stream})
6750 @deftypefunx void Lstream_fungetc (Lstream *@var{stream}, int @var{c})
6751 Function equivalents of the above macros.
6752 @end deftypefun
6753
6754 @deftypefun int Lstream_read (Lstream *@var{stream}, void *@var{data}, int @var{size})
6755 Read @var{size} bytes of @var{data} from the stream.  Return the number
6756 of bytes read.  0 means EOF. -1 means an error occurred and no bytes
6757 were read.
6758 @end deftypefun
6759
6760 @deftypefun int Lstream_write (Lstream *@var{stream}, void *@var{data}, int @var{size})
6761 Write @var{size} bytes of @var{data} to the stream.  Return the number
6762 of bytes written.  -1 means an error occurred and no bytes were written.
6763 @end deftypefun
6764
6765 @deftypefun void Lstream_unread (Lstream *@var{stream}, void *@var{data}, int @var{size})
6766 Push back @var{size} bytes of @var{data} onto the input queue.  The next
6767 call to @code{Lstream_read()} with the same size will read the same
6768 bytes back.  Note that this will be the case even if there is other
6769 pending unread data.
6770 @end deftypefun
6771
6772 @deftypefun int Lstream_close (Lstream *@var{stream})
6773 Close the stream.  All data will be flushed out.
6774 @end deftypefun
6775
6776 @deftypefun void Lstream_reopen (Lstream *@var{stream})
6777 Reopen a closed stream.  This enables I/O on it again.  This is not
6778 meant to be called except from a wrapper routine that reinitializes
6779 variables and such -- the close routine may well have freed some
6780 necessary storage structures, for example.
6781 @end deftypefun
6782
6783 @deftypefun void Lstream_rewind (Lstream *@var{stream})
6784 Rewind the stream to the beginning.
6785 @end deftypefun
6786
6787 @node Lstream Methods
6788 @section Lstream Methods
6789
6790 @deftypefn {Lstream Method} int reader (Lstream *@var{stream}, unsigned char *@var{data}, int @var{size})
6791 Read some data from the stream's end and store it into @var{data}, which
6792 can hold @var{size} bytes.  Return the number of bytes read.  A return
6793 value of 0 means no bytes can be read at this time.  This may be because
6794 of an EOF, or because there is a granularity greater than one byte that
6795 the stream imposes on the returned data, and @var{size} is less than
6796 this granularity. (This will happen frequently for streams that need to
6797 return whole characters, because @code{Lstream_read()} calls the reader
6798 function repeatedly until it has the number of bytes it wants or until 0
6799 is returned.)  The lstream functions do not treat a 0 return as EOF or
6800 do anything special; however, the calling function will interpret any 0
6801 it gets back as EOF.  This will normally not happen unless the caller
6802 calls @code{Lstream_read()} with a very small size.
6803
6804 This function can be @code{NULL} if the stream is output-only.
6805 @end deftypefn
6806
6807 @deftypefn {Lstream Method} int writer (Lstream *@var{stream}, CONST unsigned char *@var{data}, int @var{size})
6808 Send some data to the stream's end.  Data to be sent is in @var{data}
6809 and is @var{size} bytes.  Return the number of bytes sent.  This
6810 function can send and return fewer bytes than is passed in; in that
6811 case, the function will just be called again until there is no data left
6812 or 0 is returned.  A return value of 0 means that no more data can be
6813 currently stored, but there is no error; the data will be squirreled
6814 away until the writer can accept data. (This is useful, e.g., if you're
6815 dealing with a non-blocking file descriptor and are getting
6816 @code{EWOULDBLOCK} errors.)  This function can be @code{NULL} if the
6817 stream is input-only.
6818 @end deftypefn
6819
6820 @deftypefn {Lstream Method} int rewinder (Lstream *@var{stream})
6821 Rewind the stream.  If this is @code{NULL}, the stream is not seekable.
6822 @end deftypefn
6823
6824 @deftypefn {Lstream Method} int seekable_p (Lstream *@var{stream})
6825 Indicate whether this stream is seekable -- i.e. it can be rewound.
6826 This method is ignored if the stream does not have a rewind method.  If
6827 this method is not present, the result is determined by whether a rewind
6828 method is present.
6829 @end deftypefn
6830
6831 @deftypefn {Lstream Method} int flusher (Lstream *@var{stream})
6832 Perform any additional operations necessary to flush the data in this
6833 stream.
6834 @end deftypefn
6835
6836 @deftypefn {Lstream Method} int pseudo_closer (Lstream *@var{stream})
6837 @end deftypefn
6838
6839 @deftypefn {Lstream Method} int closer (Lstream *@var{stream})
6840 Perform any additional operations necessary to close this stream down.
6841 May be @code{NULL}.  This function is called when @code{Lstream_close()}
6842 is called or when the stream is garbage-collected.  When this function
6843 is called, all pending data in the stream will already have been written
6844 out.
6845 @end deftypefn
6846
6847 @deftypefn {Lstream Method} Lisp_Object marker (Lisp_Object @var{lstream}, void (*@var{markfun}) (Lisp_Object))
6848 Mark this object for garbage collection.  Same semantics as a standard
6849 @code{Lisp_Object} marker.  This function can be @code{NULL}.
6850 @end deftypefn
6851
6852 @node Consoles; Devices; Frames; Windows, The Redisplay Mechanism, Lstreams, Top
6853 @chapter Consoles; Devices; Frames; Windows
6854
6855 @menu
6856 * Introduction to Consoles; Devices; Frames; Windows::
6857 * Point::
6858 * Window Hierarchy::
6859 * The Window Object::
6860 @end menu
6861
6862 @node Introduction to Consoles; Devices; Frames; Windows
6863 @section Introduction to Consoles; Devices; Frames; Windows
6864
6865 A window-system window that you see on the screen is called a
6866 @dfn{frame} in Emacs terminology.  Each frame is subdivided into one or
6867 more non-overlapping panes, called (confusingly) @dfn{windows}.  Each
6868 window displays the text of a buffer in it. (See above on Buffers.) Note
6869 that buffers and windows are independent entities: Two or more windows
6870 can be displaying the same buffer (potentially in different locations),
6871 and a buffer can be displayed in no windows.
6872
6873   A single display screen that contains one or more frames is called
6874 a @dfn{display}.  Under most circumstances, there is only one display.
6875 However, more than one display can exist, for example if you have
6876 a @dfn{multi-headed} console, i.e. one with a single keyboard but
6877 multiple displays. (Typically in such a situation, the various
6878 displays act like one large display, in that the mouse is only
6879 in one of them at a time, and moving the mouse off of one moves
6880 it into another.) In some cases, the different displays will
6881 have different characteristics, e.g. one color and one mono.
6882
6883   XEmacs can display frames on multiple displays.  It can even deal
6884 simultaneously with frames on multiple keyboards (called @dfn{consoles} in
6885 XEmacs terminology).  Here is one case where this might be useful: You
6886 are using XEmacs on your workstation at work, and leave it running.
6887 Then you go home and dial in on a TTY line, and you can use the
6888 already-running XEmacs process to display another frame on your local
6889 TTY.
6890
6891   Thus, there is a hierarchy console -> display -> frame -> window.
6892 There is a separate Lisp object type for each of these four concepts.
6893 Furthermore, there is logically a @dfn{selected console}, 
6894 @dfn{selected display}, @dfn{selected frame}, and @dfn{selected window}.
6895 Each of these objects is distinguished in various ways, such as being the
6896 default object for various functions that act on objects of that type.
6897 Note that every containing object rememembers the ``selected'' object
6898 among the objects that it contains: e.g. not only is there a selected
6899 window, but every frame remembers the last window in it that was
6900 selected, and changing the selected frame causes the remembered window
6901 within it to become the selected window.  Similar relationships apply
6902 for consoles to devices and devices to frames.
6903
6904 @node Point
6905 @section Point
6906
6907   Recall that every buffer has a current insertion position, called
6908 @dfn{point}.  Now, two or more windows may be displaying the same buffer,
6909 and the text cursor in the two windows (i.e. @code{point}) can be in
6910 two different places.  You may ask, how can that be, since each
6911 buffer has only one value of @code{point}?  The answer is that each window
6912 also has a value of @code{point} that is squirreled away in it.  There
6913 is only one selected window, and the value of ``point'' in that buffer
6914 corresponds to that window.  When the selected window is changed
6915 from one window to another displaying the same buffer, the old
6916 value of @code{point} is stored into the old window's ``point'' and the
6917 value of @code{point} from the new window is retrieved and made the
6918 value of @code{point} in the buffer.  This means that @code{window-point}
6919 for the selected window is potentially inaccurate, and if you
6920 want to retrieve the correct value of @code{point} for a window,
6921 you must special-case on the selected window and retrieve the
6922 buffer's point instead.  This is related to why @code{save-window-excursion}
6923 does not save the selected window's value of @code{point}.
6924
6925 @node Window Hierarchy
6926 @section Window Hierarchy
6927 @cindex window hierarchy
6928 @cindex hierarchy of windows
6929
6930   If a frame contains multiple windows (panes), they are always created
6931 by splitting an existing window along the horizontal or vertical axis.
6932 Terminology is a bit confusing here: to @dfn{split a window
6933 horizontally} means to create two side-by-side windows, i.e. to make a
6934 @emph{vertical} cut in a window.  Likewise, to @dfn{split a window
6935 vertically} means to create two windows, one above the other, by making
6936 a @emph{horizontal} cut.
6937
6938   If you split a window and then split again along the same axis, you
6939 will end up with a number of panes all arranged along the same axis.
6940 The precise way in which the splits were made should not be important,
6941 and this is reflected internally.  Internally, all windows are arranged
6942 in a tree, consisting of two types of windows, @dfn{combination} windows
6943 (which have children, and are covered completely by those children) and
6944 @dfn{leaf} windows, which have no children and are visible.  Every
6945 combination window has two or more children, all arranged along the same
6946 axis.  There are (logically) two subtypes of windows, depending on
6947 whether their children are horizontally or vertically arrayed.  There is
6948 always one root window, which is either a leaf window (if the frame
6949 contains only one window) or a combination window (if the frame contains
6950 more than one window).  In the latter case, the root window will have
6951 two or more children, either horizontally or vertically arrayed, and
6952 each of those children will be either a leaf window or another
6953 combination window.
6954
6955   Here are some rules:
6956
6957 @enumerate
6958 @item
6959 Horizontal combination windows can never have children that are
6960 horizontal combination windows; same for vertical.
6961
6962 @item
6963 Only leaf windows can be split (obviously) and this splitting does one
6964 of two things: (a) turns the leaf window into a combination window and
6965 creates two new leaf children, or (b) turns the leaf window into one of
6966 the two new leaves and creates the other leaf.  Rule (1) dictates which
6967 of these two outcomes happens.
6968
6969 @item
6970 Every combination window must have at least two children.
6971
6972 @item
6973 Leaf windows can never become combination windows.  They can be deleted,
6974 however.  If this results in a violation of (3), the parent combination
6975 window also gets deleted.
6976
6977 @item
6978 All functions that accept windows must be prepared to accept combination
6979 windows, and do something sane (e.g. signal an error if so).
6980 Combination windows @emph{do} escape to the Lisp level.
6981
6982 @item
6983 All windows have three fields governing their contents:
6984 these are @dfn{hchild} (a list of horizontally-arrayed children),
6985 @dfn{vchild} (a list of vertically-arrayed children), and @dfn{buffer}
6986 (the buffer contained in a leaf window).  Exactly one of
6987 these will be non-nil.  Remember that @dfn{horizontally-arrayed}
6988 means ``side-by-side'' and @dfn{vertically-arrayed} means
6989 @dfn{one above the other}.
6990
6991 @item
6992 Leaf windows also have markers in their @code{start} (the
6993 first buffer position displayed in the window) and @code{pointm}
6994 (the window's stashed value of @code{point} -- see above) fields,
6995 while combination windows have nil in these fields.
6996
6997 @item
6998 The list of children for a window is threaded through the
6999 @code{next} and @code{prev} fields of each child window.
7000
7001 @item
7002 @strong{Deleted windows can be undeleted}.  This happens as a result of
7003 restoring a window configuration, and is unlike frames, displays, and
7004 consoles, which, once deleted, can never be restored.  Deleting a window
7005 does nothing except set a special @code{dead} bit to 1 and clear out the
7006 @code{next}, @code{prev}, @code{hchild}, and @code{vchild} fields, for
7007 GC purposes.
7008
7009 @item
7010 Most frames actually have two top-level windows -- one for the
7011 minibuffer and one (the @dfn{root}) for everything else.  The modeline
7012 (if present) separates these two.  The @code{next} field of the root
7013 points to the minibuffer, and the @code{prev} field of the minibuffer
7014 points to the root.  The other @code{next} and @code{prev} fields are
7015 @code{nil}, and the frame points to both of these windows.
7016 Minibuffer-less frames have no minibuffer window, and the @code{next}
7017 and @code{prev} of the root window are @code{nil}.  Minibuffer-only
7018 frames have no root window, and the @code{next} of the minibuffer window
7019 is @code{nil} but the @code{prev} points to itself. (#### This is an
7020 artifact that should be fixed.)
7021 @end enumerate
7022
7023 @node The Window Object
7024 @section The Window Object
7025
7026   Windows have the following accessible fields:
7027
7028 @table @code
7029 @item frame
7030 The frame that this window is on.
7031
7032 @item mini_p
7033 Non-@code{nil} if this window is a minibuffer window.
7034
7035 @item buffer
7036 The buffer that the window is displaying.  This may change often during
7037 the life of the window.
7038
7039 @item dedicated
7040 Non-@code{nil} if this window is dedicated to its buffer.
7041
7042 @item pointm
7043 @cindex window point internals
7044 This is the value of point in the current buffer when this window is
7045 selected; when it is not selected, it retains its previous value.
7046
7047 @item start
7048 The position in the buffer that is the first character to be displayed
7049 in the window.
7050
7051 @item force_start
7052 If this flag is non-@code{nil}, it says that the window has been
7053 scrolled explicitly by the Lisp program.  This affects what the next
7054 redisplay does if point is off the screen: instead of scrolling the
7055 window to show the text around point, it moves point to a location that
7056 is on the screen.
7057
7058 @item last_modified
7059 The @code{modified} field of the window's buffer, as of the last time
7060 a redisplay completed in this window.
7061
7062 @item last_point
7063 The buffer's value of point, as of the last time
7064 a redisplay completed in this window.
7065
7066 @item left
7067 This is the left-hand edge of the window, measured in columns.  (The
7068 leftmost column on the screen is @w{column 0}.)
7069
7070 @item top
7071 This is the top edge of the window, measured in lines.  (The top line on
7072 the screen is @w{line 0}.)
7073
7074 @item height
7075 The height of the window, measured in lines.
7076
7077 @item width
7078 The width of the window, measured in columns.
7079
7080 @item next
7081 This is the window that is the next in the chain of siblings.  It is
7082 @code{nil} in a window that is the rightmost or bottommost of a group of
7083 siblings.
7084
7085 @item prev
7086 This is the window that is the previous in the chain of siblings.  It is
7087 @code{nil} in a window that is the leftmost or topmost of a group of
7088 siblings.
7089
7090 @item parent
7091 Internally, XEmacs arranges windows in a tree; each group of siblings has
7092 a parent window whose area includes all the siblings.  This field points
7093 to a window's parent.
7094
7095 Parent windows do not display buffers, and play little role in display
7096 except to shape their child windows.  Emacs Lisp programs usually have
7097 no access to the parent windows; they operate on the windows at the
7098 leaves of the tree, which actually display buffers.
7099
7100 @item hscroll
7101 This is the number of columns that the display in the window is scrolled
7102 horizontally to the left.  Normally, this is 0.
7103
7104 @item use_time
7105 This is the last time that the window was selected.  The function
7106 @code{get-lru-window} uses this field.
7107
7108 @item display_table
7109 The window's display table, or @code{nil} if none is specified for it.
7110
7111 @item update_mode_line
7112 Non-@code{nil} means this window's mode line needs to be updated.
7113
7114 @item base_line_number
7115 The line number of a certain position in the buffer, or @code{nil}.
7116 This is used for displaying the line number of point in the mode line.
7117
7118 @item base_line_pos
7119 The position in the buffer for which the line number is known, or
7120 @code{nil} meaning none is known.
7121
7122 @item region_showing
7123 If the region (or part of it) is highlighted in this window, this field
7124 holds the mark position that made one end of that region.  Otherwise,
7125 this field is @code{nil}.
7126 @end table
7127
7128 @node The Redisplay Mechanism, Extents, Consoles; Devices; Frames; Windows, Top
7129 @chapter The Redisplay Mechanism
7130
7131   The redisplay mechanism is one of the most complicated sections of
7132 XEmacs, especially from a conceptual standpoint.  This is doubly so
7133 because, unlike for the basic aspects of the Lisp interpreter, the
7134 computer science theories of how to efficiently handle redisplay are not
7135 well-developed.
7136
7137   When working with the redisplay mechanism, remember the Golden Rules
7138 of Redisplay:
7139
7140 @enumerate
7141 @item
7142 It Is Better To Be Correct Than Fast.
7143 @item
7144 Thou Shalt Not Run Elisp From Within Redisplay.
7145 @item
7146 It Is Better To Be Fast Than Not To Be.
7147 @end enumerate
7148
7149 @menu
7150 * Critical Redisplay Sections::
7151 * Line Start Cache::
7152 @end menu
7153
7154 @node Critical Redisplay Sections
7155 @section Critical Redisplay Sections
7156 @cindex critical redisplay sections
7157
7158 Within this section, we are defenseless and assume that the
7159 following cannot happen:
7160
7161 @enumerate
7162 @item
7163 garbage collection
7164 @item
7165 Lisp code evaluation
7166 @item
7167 frame size changes
7168 @end enumerate
7169
7170 We ensure (3) by calling @code{hold_frame_size_changes()}, which
7171 will cause any pending frame size changes to get put on hold
7172 till after the end of the critical section.  (1) follows
7173 automatically if (2) is met.  #### Unfortunately, there are
7174 some places where Lisp code can be called within this section.
7175 We need to remove them.
7176
7177 If @code{Fsignal()} is called during this critical section, we
7178 will @code{abort()}.
7179
7180 If garbage collection is called during this critical section,
7181 we simply return. #### We should abort instead.
7182
7183 #### If a frame-size change does occur we should probably
7184 actually be preempting redisplay.
7185
7186 @node Line Start Cache
7187 @section Line Start Cache
7188 @cindex line start cache
7189
7190   The traditional scrolling code in Emacs breaks in a variable height
7191 world.  It depends on the key assumption that the number of lines that
7192 can be displayed at any given time is fixed.  This led to a complete
7193 separation of the scrolling code from the redisplay code.  In order to
7194 fully support variable height lines, the scrolling code must actually be
7195 tightly integrated with redisplay.  Only redisplay can determine how
7196 many lines will be displayed on a screen for any given starting point.
7197
7198   What is ideally wanted is a complete list of the starting buffer
7199 position for every possible display line of a buffer along with the
7200 height of that display line.  Maintaining such a full list would be very
7201 expensive.  We settle for having it include information for all areas
7202 which we happen to generate anyhow (i.e. the region currently being
7203 displayed) and for those areas we need to work with.
7204
7205   In order to ensure that the cache accurately represents what redisplay
7206 would actually show, it is necessary to invalidate it in many
7207 situations.  If the buffer changes, the starting positions may no longer
7208 be correct.  If a face or an extent has changed then the line heights
7209 may have altered.  These events happen frequently enough that the cache
7210 can end up being constantly disabled.  With this potentially constant
7211 invalidation when is the cache ever useful?
7212
7213   Even if the cache is invalidated before every single usage, it is
7214 necessary.  Scrolling often requires knowledge about display lines which
7215 are actually above or below the visible region.  The cache provides a
7216 convenient light-weight method of storing this information for multiple
7217 display regions.  This knowledge is necessary for the scrolling code to
7218 always obey the First Golden Rule of Redisplay.
7219
7220   If the cache already contains all of the information that the scrolling
7221 routines happen to need so that it doesn't have to go generate it, then
7222 we are able to obey the Third Golden Rule of Redisplay.  The first thing
7223 we do to help out the cache is to always add the displayed region.  This
7224 region had to be generated anyway, so the cache ends up getting the
7225 information basically for free.  In those cases where a user is simply
7226 scrolling around viewing a buffer there is a high probability that this
7227 is sufficient to always provide the needed information.  The second
7228 thing we can do is be smart about invalidating the cache.
7229
7230   TODO -- Be smart about invalidating the cache.  Potential places:
7231
7232 @itemize @bullet
7233 @item
7234 Insertions at end-of-line which don't cause line-wraps do not alter the
7235 starting positions of any display lines.  These types of buffer
7236 modifications should not invalidate the cache.  This is actually a large
7237 optimization for redisplay speed as well.
7238 @item
7239 Buffer modifications frequently only affect the display of lines at and
7240 below where they occur.  In these situations we should only invalidate
7241 the part of the cache starting at where the modification occurs.
7242 @end itemize
7243
7244   In case you're wondering, the Second Golden Rule of Redisplay is not
7245 applicable.
7246
7247 @node Extents, Faces and Glyphs, The Redisplay Mechanism, Top
7248 @chapter Extents
7249
7250 @menu
7251 * Introduction to Extents::     Extents are ranges over text, with properties.
7252 * Extent Ordering::             How extents are ordered internally.
7253 * Format of the Extent Info::   The extent information in a buffer or string.
7254 * Zero-Length Extents::         A weird special case.
7255 * Mathematics of Extent Ordering::      A rigorous foundation.
7256 * Extent Fragments::            Cached information useful for redisplay.
7257 @end menu
7258
7259 @node Introduction to Extents
7260 @section Introduction to Extents
7261
7262   Extents are regions over a buffer, with a start and an end position
7263 denoting the region of the buffer included in the extent.  In
7264 addition, either end can be closed or open, meaning that the endpoint
7265 is or is not logically included in the extent.  Insertion of a character
7266 at a closed endpoint causes the character to go inside the extent;
7267 insertion at an open endpoint causes the character to go outside.
7268
7269   Extent endpoints are stored using memory indices (see @file{insdel.c}),
7270 to minimize the amount of adjusting that needs to be done when
7271 characters are inserted or deleted.
7272
7273   (Formerly, extent endpoints at the gap could be either before or
7274 after the gap, depending on the open/closedness of the endpoint.
7275 The intent of this was to make it so that insertions would
7276 automatically go inside or out of extents as necessary with no
7277 further work needing to be done.  It didn't work out that way,
7278 however, and just ended up complexifying and buggifying all the
7279 rest of the code.)
7280
7281 @node Extent Ordering
7282 @section Extent Ordering
7283
7284   Extents are compared using memory indices.  There are two orderings
7285 for extents and both orders are kept current at all times.  The normal
7286 or @dfn{display} order is as follows:
7287
7288 @example
7289 Extent A is ``less than'' extent B, that is, earlier in the display order,
7290 if:    A-start < B-start,
7291 or if: A-start = B-start, and A-end > B-end
7292 @end example
7293
7294   So if two extents begin at the same position, the larger of them is the
7295 earlier one in the display order (@code{EXTENT_LESS} is true).
7296
7297   For the e-order, the same thing holds:
7298
7299 @example
7300 Extent A is ``less than'' extent B in e-order, that is, later in the buffer,
7301 if:    A-end < B-end,
7302 or if: A-end = B-end, and A-start > B-start
7303 @end example
7304
7305   So if two extents end at the same position, the smaller of them is the
7306 earlier one in the e-order (@code{EXTENT_E_LESS} is true).
7307
7308   The display order and the e-order are complementary orders: any
7309 theorem about the display order also applies to the e-order if you swap
7310 all occurrences of ``display order'' and ``e-order'', ``less than'' and
7311 ``greater than'', and ``extent start'' and ``extent end''.
7312
7313 @node Format of the Extent Info
7314 @section Format of the Extent Info
7315
7316   An extent-info structure consists of a list of the buffer or string's
7317 extents and a @dfn{stack of extents} that lists all of the extents over
7318 a particular position.  The stack-of-extents info is used for
7319 optimization purposes -- it basically caches some info that might
7320 be expensive to compute.  Certain otherwise hard computations are easy
7321 given the stack of extents over a particular position, and if the
7322 stack of extents over a nearby position is known (because it was
7323 calculated at some prior point in time), it's easy to move the stack
7324 of extents to the proper position.
7325
7326   Given that the stack of extents is an optimization, and given that
7327 it requires memory, a string's stack of extents is wiped out each
7328 time a garbage collection occurs.  Therefore, any time you retrieve
7329 the stack of extents, it might not be there.  If you need it to
7330 be there, use the @code{_force} version.
7331
7332   Similarly, a string may or may not have an extent_info structure.
7333 (Generally it won't if there haven't been any extents added to the
7334 string.) So use the @code{_force} version if you need the extent_info
7335 structure to be there.
7336
7337   A list of extents is maintained as a double gap array: one gap array
7338 is ordered by start index (the @dfn{display order}) and the other is
7339 ordered by end index (the @dfn{e-order}).  Note that positions in an
7340 extent list should logically be conceived of as referring @emph{to} a
7341 particular extent (as is the norm in programs) rather than sitting
7342 between two extents.  Note also that callers of these functions should
7343 not be aware of the fact that the extent list is implemented as an
7344 array, except for the fact that positions are integers (this should be
7345 generalized to handle integers and linked list equally well).
7346
7347 @node Zero-Length Extents
7348 @section Zero-Length Extents
7349
7350   Extents can be zero-length, and will end up that way if their endpoints
7351 are explicitly set that way or if their detachable property is nil
7352 and all the text in the extent is deleted. (The exception is open-open
7353 zero-length extents, which are barred from existing because there is
7354 no sensible way to define their properties.  Deletion of the text in
7355 an open-open extent causes it to be converted into a closed-open
7356 extent.)  Zero-length extents are primarily used to represent
7357 annotations, and behave as follows:
7358
7359 @enumerate
7360 @item
7361 Insertion at the position of a zero-length extent expands the extent
7362 if both endpoints are closed; goes after the extent if it is closed-open;
7363 and goes before the extent if it is open-closed.
7364
7365 @item
7366 Deletion of a character on a side of a zero-length extent whose
7367 corresponding endpoint is closed causes the extent to be detached if
7368 it is detachable; if the extent is not detachable or the corresponding
7369 endpoint is open, the extent remains in the buffer, moving as necessary.
7370 @end enumerate
7371
7372   Note that closed-open, non-detachable zero-length extents behave
7373 exactly like markers and that open-closed, non-detachable zero-length
7374 extents behave like the ``point-type'' marker in Mule.
7375
7376 @node Mathematics of Extent Ordering
7377 @section Mathematics of Extent Ordering
7378 @cindex extent mathematics
7379 @cindex mathematics of extents
7380 @cindex extent ordering
7381
7382 @cindex display order of extents
7383 @cindex extents, display order
7384   The extents in a buffer are ordered by ``display order'' because that
7385 is that order that the redisplay mechanism needs to process them in.
7386 The e-order is an auxiliary ordering used to facilitate operations
7387 over extents.  The operations that can be performed on the ordered
7388 list of extents in a buffer are
7389
7390 @enumerate
7391 @item
7392 Locate where an extent would go if inserted into the list.
7393 @item
7394 Insert an extent into the list.
7395 @item
7396 Remove an extent from the list.
7397 @item
7398 Map over all the extents that overlap a range.
7399 @end enumerate
7400
7401   (4) requires being able to determine the first and last extents
7402 that overlap a range.
7403
7404   NOTE: @dfn{overlap} is used as follows:
7405
7406 @itemize @bullet
7407 @item
7408 two ranges overlap if they have at least one point in common.
7409 Whether the endpoints are open or closed makes a difference here.
7410 @item
7411 a point overlaps a range if the point is contained within the
7412 range; this is equivalent to treating a point @math{P} as the range
7413 @math{[P, P]}.
7414 @item
7415 In the case of an @emph{extent} overlapping a point or range, the extent
7416 is normally treated as having closed endpoints.  This applies
7417 consistently in the discussion of stacks of extents and such below.
7418 Note that this definition of overlap is not necessarily consistent with
7419 the extents that @code{map-extents} maps over, since @code{map-extents}
7420 sometimes pays attention to whether the endpoints of an extents are open
7421 or closed.  But for our purposes, it greatly simplifies things to treat
7422 all extents as having closed endpoints.
7423 @end itemize
7424
7425 First, define @math{>}, @math{<}, @math{<=}, etc. as applied to extents
7426 to mean comparison according to the display order.  Comparison between
7427 an extent @math{E} and an index @math{I} means comparison between
7428 @math{E} and the range @math{[I, I]}.
7429
7430 Also define @math{e>}, @math{e<}, @math{e<=}, etc. to mean comparison
7431 according to the e-order.
7432
7433 For any range @math{R}, define @math{R(0)} to be the starting index of
7434 the range and @math{R(1)} to be the ending index of the range.
7435
7436 For any extent @math{E}, define @math{E(next)} to be the extent directly
7437 following @math{E}, and @math{E(prev)} to be the extent directly
7438 preceding @math{E}.  Assume @math{E(next)} and @math{E(prev)} can be
7439 determined from @math{E} in constant time.  (This is because we store
7440 the extent list as a doubly linked list.)
7441
7442 Similarly, define @math{E(e-next)} and @math{E(e-prev)} to be the
7443 extents directly following and preceding @math{E} in the e-order.
7444
7445 Now:
7446
7447 Let @math{R} be a range.
7448 Let @math{F} be the first extent overlapping @math{R}.
7449 Let @math{L} be the last extent overlapping @math{R}.
7450
7451 Theorem 1: @math{R(1)} lies between @math{L} and @math{L(next)},
7452 i.e. @math{L <= R(1) < L(next)}.
7453
7454   This follows easily from the definition of display order.  The
7455 basic reason that this theorem applies is that the display order
7456 sorts by increasing starting index.
7457
7458   Therefore, we can determine @math{L} just by looking at where we would
7459 insert @math{R(1)} into the list, and if we know @math{F} and are moving
7460 forward over extents, we can easily determine when we've hit @math{L} by
7461 comparing the extent we're at to @math{R(1)}.
7462
7463 @example
7464 Theorem 2: @math{F(e-prev) e< [1, R(0)] e<= F}.
7465 @end example
7466
7467   This is the analog of Theorem 1, and applies because the e-order
7468 sorts by increasing ending index.
7469
7470   Therefore, @math{F} can be found in the same amount of time as
7471 operation (1), i.e. the time that it takes to locate where an extent
7472 would go if inserted into the e-order list.
7473
7474   If the lists were stored as balanced binary trees, then operation (1)
7475 would take logarithmic time, which is usually quite fast.  However,
7476 currently they're stored as simple doubly-linked lists, and instead we
7477 do some caching to try to speed things up.
7478
7479   Define a @dfn{stack of extents} (or @dfn{SOE}) as the set of extents
7480 (ordered in the display order) that overlap an index @math{I}, together
7481 with the SOE's @dfn{previous} extent, which is an extent that precedes
7482 @math{I} in the e-order. (Hopefully there will not be very many extents
7483 between @math{I} and the previous extent.)
7484
7485 Now:
7486
7487 Let @math{I} be an index, let @math{S} be the stack of extents on
7488 @math{I}, let @math{F} be the first extent in @math{S}, and let @math{P}
7489 be @math{S}'s previous extent.
7490
7491 Theorem 3: The first extent in @math{S} is the first extent that overlaps
7492 any range @math{[I, J]}.
7493
7494 Proof: Any extent that overlaps @math{[I, J]} but does not include
7495 @math{I} must have a start index @math{> I}, and thus be greater than
7496 any extent in @math{S}.
7497
7498 Therefore, finding the first extent that overlaps a range @math{R} is
7499 the same as finding the first extent that overlaps @math{R(0)}.
7500
7501 Theorem 4: Let @math{I2} be an index such that @math{I2 > I}, and let
7502 @math{F2} be the first extent that overlaps @math{I2}.  Then, either
7503 @math{F2} is in @math{S} or @math{F2} is greater than any extent in
7504 @math{S}.
7505
7506 Proof: If @math{F2} does not include @math{I} then its start index is
7507 greater than @math{I} and thus it is greater than any extent in
7508 @math{S}, including @math{F}.  Otherwise, @math{F2} includes @math{I}
7509 and thus is in @math{S}, and thus @math{F2 >= F}.
7510
7511 @node Extent Fragments
7512 @section Extent Fragments
7513 @cindex extent fragment
7514
7515   Imagine that the buffer is divided up into contiguous, non-overlapping
7516 @dfn{runs} of text such that no extent starts or ends within a run
7517 (extents that abut the run don't count).
7518
7519   An extent fragment is a structure that holds data about the run that
7520 contains a particular buffer position (if the buffer position is at the
7521 junction of two runs, the run after the position is used) -- the
7522 beginning and end of the run, a list of all of the extents in that run,
7523 the @dfn{merged face} that results from merging all of the faces
7524 corresponding to those extents, the begin and end glyphs at the
7525 beginning of the run, etc.  This is the information that redisplay needs
7526 in order to display this run.
7527
7528   Extent fragments have to be very quick to update to a new buffer
7529 position when moving linearly through the buffer.  They rely on the
7530 stack-of-extents code, which does the heavy-duty algorithmic work of
7531 determining which extents overly a particular position.
7532
7533 @node Faces and Glyphs, Specifiers, Extents, Top
7534 @chapter Faces and Glyphs
7535
7536 Not yet documented.
7537
7538 @node Specifiers, Menus, Faces and Glyphs, Top
7539 @chapter Specifiers
7540
7541 Not yet documented.
7542
7543 @node Menus, Subprocesses, Specifiers, Top
7544 @chapter Menus
7545
7546   A menu is set by setting the value of the variable
7547 @code{current-menubar} (which may be buffer-local) and then calling
7548 @code{set-menubar-dirty-flag} to signal a change.  This will cause the
7549 menu to be redrawn at the next redisplay.  The format of the data in
7550 @code{current-menubar} is described in @file{menubar.c}.
7551
7552   Internally the data in current-menubar is parsed into a tree of
7553 @code{widget_value's} (defined in @file{lwlib.h}); this is accomplished
7554 by the recursive function @code{menu_item_descriptor_to_widget_value()},
7555 called by @code{compute_menubar_data()}.  Such a tree is deallocated
7556 using @code{free_widget_value()}.
7557
7558   @code{update_screen_menubars()} is one of the external entry points.
7559 This checks to see, for each screen, if that screen's menubar needs to
7560 be updated.  This is the case if
7561
7562 @enumerate
7563 @item
7564 @code{set-menubar-dirty-flag} was called since the last redisplay.  (This
7565 function sets the C variable menubar_has_changed.)
7566 @item
7567 The buffer displayed in the screen has changed.
7568 @item
7569 The screen has no menubar currently displayed.
7570 @end enumerate
7571
7572   @code{set_screen_menubar()} is called for each such screen.  This
7573 function calls @code{compute_menubar_data()} to create the tree of
7574 widget_value's, then calls @code{lw_create_widget()},
7575 @code{lw_modify_all_widgets()}, and/or @code{lw_destroy_all_widgets()}
7576 to create the X-Toolkit widget associated with the menu.
7577
7578   @code{update_psheets()}, the other external entry point, actually
7579 changes the menus being displayed.  It uses the widgets fixed by
7580 @code{update_screen_menubars()} and calls various X functions to ensure
7581 that the menus are displayed properly.
7582
7583   The menubar widget is set up so that @code{pre_activate_callback()} is
7584 called when the menu is first selected (i.e. mouse button goes down),
7585 and @code{menubar_selection_callback()} is called when an item is
7586 selected.  @code{pre_activate_callback()} calls the function in
7587 activate-menubar-hook, which can change the menubar (this is described
7588 in @file{menubar.c}).  If the menubar is changed,
7589 @code{set_screen_menubars()} is called.
7590 @code{menubar_selection_callback()} enqueues a menu event, putting in it
7591 a function to call (either @code{eval} or @code{call-interactively}) and
7592 its argument, which is the callback function or form given in the menu's
7593 description.
7594
7595 @node Subprocesses, Interface to X Windows, Menus, Top
7596 @chapter Subprocesses
7597
7598   The fields of a process are:
7599
7600 @table @code
7601 @item name
7602 A string, the name of the process.
7603
7604 @item command
7605 A list containing the command arguments that were used to start this
7606 process.
7607
7608 @item filter
7609 A function used to accept output from the process instead of a buffer,
7610 or @code{nil}.
7611
7612 @item sentinel
7613 A function called whenever the process receives a signal, or @code{nil}.
7614
7615 @item buffer
7616 The associated buffer of the process.
7617
7618 @item pid
7619 An integer, the Unix process @sc{id}.
7620
7621 @item childp
7622 A flag, non-@code{nil} if this is really a child process.
7623 It is @code{nil} for a network connection.
7624
7625 @item mark
7626 A marker indicating the position of the end of the last output from this
7627 process inserted into the buffer.  This is often but not always the end
7628 of the buffer.
7629
7630 @item kill_without_query
7631 If this is non-@code{nil}, killing XEmacs while this process is still
7632 running does not ask for confirmation about killing the process.
7633
7634 @item raw_status_low
7635 @itemx raw_status_high
7636 These two fields record 16 bits each of the process status returned by
7637 the @code{wait} system call.
7638
7639 @item status
7640 The process status, as @code{process-status} should return it.
7641
7642 @item tick
7643 @itemx update_tick
7644 If these two fields are not equal, a change in the status of the process
7645 needs to be reported, either by running the sentinel or by inserting a
7646 message in the process buffer.
7647
7648 @item pty_flag
7649 Non-@code{nil} if communication with the subprocess uses a @sc{pty};
7650 @code{nil} if it uses a pipe.
7651
7652 @item infd
7653 The file descriptor for input from the process.
7654
7655 @item outfd
7656 The file descriptor for output to the process.
7657
7658 @item subtty
7659 The file descriptor for the terminal that the subprocess is using.  (On
7660 some systems, there is no need to record this, so the value is
7661 @code{-1}.)
7662
7663 @item tty_name
7664 The name of the terminal that the subprocess is using,
7665 or @code{nil} if it is using pipes.
7666 @end table
7667
7668 @node Interface to X Windows, Index, Subprocesses, Top
7669 @chapter Interface to X Windows
7670
7671 Not yet documented.
7672
7673 @include index.texi
7674
7675 @c Print the tables of contents
7676 @summarycontents
7677 @contents
7678 @c That's all
7679
7680 @bye
7681