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