This is ../info/internals.info, produced by makeinfo version 4.7 from
internals/internals.texi.

INFO-DIR-SECTION XEmacs Editor
START-INFO-DIR-ENTRY
* Internals: (internals).       XEmacs Internals Manual.
END-INFO-DIR-ENTRY

   Edition History:

   Created November 1995 (?) by Ben Wing.  XEmacs Internals Manual
Version 1.0, March, 1996.  XEmacs Internals Manual Version 1.1, March,
1997.  XEmacs Internals Manual Version 1.4, March, 2001.  XEmacs
Internals Manual Version 21.5, October, 2004.

   Copyright (C) 1992 - 2004 Ben Wing.  Copyright (C) 1996, 1997 Sun
Microsystems.  Copyright (C) 1994 - 1998, 2002, 2003 Free Software
Foundation.  Copyright (C) 1994, 1995 Board of Trustees, University of
Illinois.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided that the
entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a
translation approved by the Foundation.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided also
that the section entitled "GNU General Public License" is included
exactly as in the original, and provided that the entire resulting
derived work is distributed under the terms of a permission notice
identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that the section entitled "GNU General Public License"
may be included in a translation approved by the Free Software
Foundation instead of in the original English.


File: internals.info,  Node: Top,  Next: Introduction,  Prev: (dir),  Up: (dir)

   This Info file contains v21.5 of the XEmacs Internals Manual,
October 2004.

* Menu:

* Introduction::                Overview of this manual.
* Authorship of XEmacs::
* A History of Emacs::          Times, dates, important events.
* The XEmacs Split::
* XEmacs from the Outside::     A broad conceptual overview.
* The Lisp Language::           An overview.
* XEmacs from the Perspective of Building::
* Build-Time Dependencies::
* The Modules of XEmacs::
* The Build Configuration System::
* Rules When Writing New C Code::
* Regression Testing XEmacs::
* CVS Techniques::
* XEmacs from the Inside::
* Basic Types::
* Low-Level Allocation::
* The XEmacs Object System (Abstractly Speaking)::
* How Lisp Objects Are Represented in C::
* Allocation of Objects in XEmacs Lisp::
* The Lisp Reader and Compiler::
* Evaluation; Stack Frames; Bindings::
* Symbols and Variables::
* Buffers::
* Text::
* Multilingual Support::
* Consoles; Devices; Frames; Windows::
* The Redisplay Mechanism::
* Extents::
* Faces::
* Glyphs::
* Specifiers::
* Menus::
* Events and the Event Loop::
* Asynchronous Events; Quit Checking::
* Lstreams::
* Subprocesses::
* Interface to MS Windows::
* Interface to the X Window System::
* Dumping::
* Future Work::
* Future Work Discussion::
* Old Future Work::
* Index::

 --- The Detailed Node Listing ---

A History of Emacs

* Through Version 18::          Unification prevails.
* Epoch::                       An early graphical split of GNU Emacs.
* Lucid Emacs::                 One version 19 Emacs.
* GNU Emacs 19::                The other version 19 Emacs.
* GNU Emacs 20::                The other version 20 Emacs.
* XEmacs::                      The continuation of Lucid Emacs.

The Modules of XEmacs

* A Summary of the Various XEmacs Modules::
* Low-Level Modules::
* Basic Lisp Modules::
* Modules for Standard Editing Operations::
* Modules for Interfacing with the File System::
* Modules for Other Aspects of the Lisp Interpreter and Object System::
* Modules for Interfacing with the Operating System::

Rules When Writing New C Code

* Introduction to Writing C Code::
* Writing New Modules::
* Working with Lisp Objects::
* Writing Lisp Primitives::
* Writing Good Comments::
* Adding Global Lisp Variables::
* Writing Macros::
* Proper Use of Unsigned Types::
* Major Textual Changes::
* Debugging and Testing::

Major Textual Changes

* Great Integral Type Renaming::
* Text/Char Type Renaming::

Regression Testing XEmacs

* How to Regression-Test::
* Modules for Regression Testing::

CVS Techniques

* Merging a Branch into the Trunk::

Low-Level Allocation

* Basic Heap Allocation::
* Stack Allocation::
* Dynamic Arrays::
* Allocation by Blocks::
* Modules for Allocation::

Allocation of Objects in XEmacs Lisp

* Introduction to Allocation::
* Garbage Collection::
* GCPROing::
* Garbage Collection - Step by Step::
* Integers and Characters::
* Allocation from Frob Blocks::
* lrecords::
* Low-level allocation::
* Cons::
* Vector::
* Bit Vector::
* Symbol::
* Marker::
* String::
* Compiled Function::

Garbage Collection - Step by Step

* Invocation::
* garbage_collect_1::
* mark_object::
* gc_sweep::
* sweep_lcrecords_1::
* compact_string_chars::
* sweep_strings::
* sweep_bit_vectors_1::

Evaluation; Stack Frames; Bindings

* Evaluation::
* Dynamic Binding; The specbinding Stack; Unwind-Protects::
* Simple Special Forms::
* Catch and Throw::
* Error Trapping::

Symbols and Variables

* Introduction to Symbols::
* Obarrays::
* Symbol Values::

Buffers

* Introduction to Buffers::     A buffer holds a block of text such as a file.
* Buffer Lists::                Keeping track of all buffers.
* Markers and Extents::         Tagging locations within a buffer.
* The Buffer Object::           The Lisp object corresponding to a buffer.

Text

* The Text in a Buffer::        Representation of the text in a buffer.
* Ibytes and Ichars::           Representation of individual characters.
* Byte-Char Position Conversion::
* Searching and Matching::      Higher-level algorithms.

Multilingual Support

* Introduction to Multilingual Issues #1::
* Introduction to Multilingual Issues #2::
* Introduction to Multilingual Issues #3::
* Introduction to Multilingual Issues #4::
* Character Sets::
* Encodings::
* Internal Mule Encodings::
* Byte/Character Types; Buffer Positions; Other Typedefs::
* Internal Text API's::
* Coding for Mule::
* CCL::
* Microsoft Windows-Related Multilingual Issues::
* Modules for Internationalization::

Encodings

* Japanese EUC (Extended Unix Code)::
* JIS7::

Internal Mule Encodings

* Internal String Encoding::
* Internal Character Encoding::

Byte/Character Types; Buffer Positions; Other Typedefs

* Byte Types::
* Different Ways of Seeing Internal Text::
* Buffer Positions::
* Other Typedefs::
* Usage of the Various Representations::
* Working With the Various Representations::

Internal Text API's

* Basic internal-format API's::
* The DFC API::
* The Eistring API::

Coding for Mule

* Character-Related Data Types::
* Working With Character and Byte Positions::
* Conversion to and from External Data::
* General Guidelines for Writing Mule-Aware Code::
* An Example of Mule-Aware Code::
* Mule-izing Code::

Microsoft Windows-Related Multilingual Issues

* Microsoft Documentation::
* Locales::
* More about code pages::
* More about locales::
* Unicode support under Windows::
* The golden rules of writing Unicode-safe code::
* The format of the locale in setlocale()::
* Random other Windows I18N docs::

Consoles; Devices; Frames; Windows

* Introduction to Consoles; Devices; Frames; Windows::
* Point::
* Window Hierarchy::
* The Window Object::
* Modules for the Basic Displayable Lisp Objects::

The Redisplay Mechanism

* Critical Redisplay Sections::
* Line Start Cache::
* Redisplay Piece by Piece::
* Modules for the Redisplay Mechanism::
* Modules for other Display-Related Lisp Objects::

Extents

* Introduction to Extents::     Extents are ranges over text, with properties.
* Extent Ordering::             How extents are ordered internally.
* Format of the Extent Info::   The extent information in a buffer or string.
* Zero-Length Extents::         A weird special case.
* Mathematics of Extent Ordering::  A rigorous foundation.
* Extent Fragments::            Cached information useful for redisplay.

Events and the Event Loop

* Introduction to Events::
* Main Loop::
* Specifics of the Event Gathering Mechanism::
* Specifics About the Emacs Event::
* Event Queues::
* Event Stream Callback Routines::
* Other Event Loop Functions::
* Stream Pairs::
* Converting Events::
* Dispatching Events; The Command Builder::
* Focus Handling::
* Editor-Level Control Flow Modules::

Asynchronous Events; Quit Checking

* Signal Handling::
* Control-G (Quit) Checking::
* Profiling::
* Asynchronous Timeouts::
* Exiting::

Lstreams

* Creating an Lstream::         Creating an lstream object.
* Lstream Types::               Different sorts of things that are streamed.
* Lstream Functions::           Functions for working with lstreams.
* Lstream Methods::             Creating new lstream types.

Interface to MS Windows

* Different kinds of Windows environments::
* Windows Build Flags::
* Windows I18N Introduction::
* Modules for Interfacing with MS Windows::

Interface to the X Window System

* Lucid Widget Library::        An interface to various widget sets.
* Modules for Interfacing with X Windows::

Lucid Widget Library

* Generic Widget Interface::    The lwlib generic widget interface.
* Scrollbars::
* Menubars::
* Checkboxes and Radio Buttons::
* Progress Bars::
* Tab Controls::

Dumping

* Dumping Justification::
* Overview::
* Data descriptions::
* Dumping phase::
* Reloading phase::
* Remaining issues::

Dumping phase

* Object inventory::
* Address allocation::
* The header::
* Data dumping::
* Pointers dumping::

Future Work

* Future Work -- General Suggestions::
* Future Work -- Elisp Compatibility Package::
* Future Work -- Drag-n-Drop::
* Future Work -- Standard Interface for Enabling Extensions::
* Future Work -- Better Initialization File Scheme::
* Future Work -- Keyword Parameters::
* Future Work -- Property Interface Changes::
* Future Work -- Toolbars::
* Future Work -- Menu API Changes::
* Future Work -- Removal of Misc-User Event Type::
* Future Work -- Mouse Pointer::
* Future Work -- Extents::
* Future Work -- Version Number and Development Tree Organization::
* Future Work -- Improvements to the `xemacs.org' Website::
* Future Work -- Keybindings::
* Future Work -- Byte Code Snippets::
* Future Work -- Lisp Stream API::
* Future Work -- Multiple Values::
* Future Work -- Macros::
* Future Work -- Specifiers::
* Future Work -- Display Tables::
* Future Work -- Making Elisp Function Calls Faster::
* Future Work -- Lisp Engine Replacement::
* Future Work -- Better Rendering Support::

Future Work -- Toolbars

* Future Work -- Easier Toolbar Customization::
* Future Work -- Toolbar Interface Changes::

Future Work -- Mouse Pointer

* Future Work -- Abstracted Mouse Pointer Interface::
* Future Work -- Busy Pointer::

Future Work -- Extents

* Future Work -- Everything should obey duplicable extents::

Future Work -- Keybindings

* Future Work -- Keybinding Schemes::
* Future Work -- Better Support for Windows Style Key Bindings::
* Future Work -- Misc Key Binding Ideas::

Future Work -- Byte Code Snippets

* Future Work -- Autodetection::
* Future Work -- Conversion Error Detection::
* Future Work -- Unicode::
* Future Work -- BIDI Support::
* Future Work -- Localized Text/Messages::

Future Work -- Lisp Engine Replacement

* Future Work -- Lisp Engine Discussion::
* Future Work -- Lisp Engine Replacement -- Implementation::
* Future Work -- Startup File Modification by Packages::

Future Work Discussion

* Discussion -- Garbage Collection::
* Discussion -- Glyphs::
* Discussion -- Dialog Boxes::
* Discussion -- Multilingual Issues::
* Discussion -- Instantiators and Generic Property Accessors::
* Discussion -- Switching to C++::
* Discussion -- Windows External Widget::
* Discussion -- Packages::
* Discussion -- Distribution Layout::

Discussion -- Garbage Collection

* Discussion -- Pure Space::
* Discussion -- Hashtable-Based Marking and Cleanup::
* Discussion -- The Anti-Cons::

Old Future Work

* Old Future Work -- A Portable Unexec Replacement::
* Old Future Work -- Indirect Buffers::
* Old Future Work -- Improvements in support for non-ASCII (European) keysyms under X::
* Old Future Work -- RTF Clipboard Support::
* Old Future Work -- xemacs.org Mailing Address Changes::
* Old Future Work -- Lisp callbacks from critical areas of the C code::


File: internals.info,  Node: Introduction,  Next: Authorship of XEmacs,  Prev: Top,  Up: Top

1 Introduction
**************

This manual documents the internals of XEmacs.  It presumes knowledge of
how to use XEmacs (*note Top: (xemacs)Top.), and especially, knowledge
of XEmacs Lisp (*note Top: (lispref)Top.).  Information in either of
these manuals will not be repeated here, and some information in the
Lisp Reference Manual in particular is more relevant to a person
working on the internals than the average XEmacs Lisp programmer. (In
such cases, a cross-reference is usually made to the Lisp Reference
Manual.)

   Ideally, this manual would be complete and up-to-date.
Unfortunately, in reality it is neither, due to the limited resources
of the maintainers of XEmacs. (That said, it is much better than the
internal documentation of most programs.) Also, much information about
the internals is documented only in the code itself, in the form of
comments.  Furthermore, since the maintainers are more likely to be
working on the code than on this manual, information contained in
comments may be more up-to-date than information in this manual.  Do not
assume that all information in this manual is necessarily accurate as of
the snapshot of the code you are looking at, and in the case of
contradictions between the code comments and the manual, *always*
assume that the code comments are correct. (Because of the proximity of
the comments to the code, comments will rarely be out-of-date.)

   The manual is organized in chapters which are broadly grouped into
major divisions:

  1. First is the introduction, including this chapter and chapters on
     the history and authorship of XEmacs.

  2. Next, starting with *Note XEmacs from the Outside::, are a couple
     of chapters giving a broad overview of the internal workings of
     XEmacs.

  3. Afterwards, starting with *Note XEmacs from the Perspective of
     Building::, are some chapters documenting important information
     relevant to those working on the code.

  4. The remaining divisions document the nitty-gritty details of the
     internal workings.  First, starting with *Note XEmacs from the
     Inside::, is a division on the low-level types and allocation
     routines and the workings of the Lisp interpreter that drives
     XEmacs.

  5. Next, starting with *Note Buffers::, is a division on the parts of
     the code specifically devoted to text processing, including
     multilingual support (Mule).

  6. Afterwards, starting with *Note Consoles; Devices; Frames;
     Windows::, is a division covering the display mechanism and the
     objects and modules relevant to this.

  7. Then, starting with *Note Events and the Event Loop::, is a
     division covering the interface between XEmacs and the outside
     world, including user interactions, subprocesses, file I/O,
     interfaces to particular windowing systems, and dumping.

  8. Finally, starting with *Note Future Work::, is a division
     containing proposals and discussion relating to future work on
     XEmacs.

   This manual was primarily written by Ben Wing.  Certain sections were
written by others, including those mentioned on the title page as well
as other coders.  Some sections were lifted directly from comments in
the code, and in those cases we may not completely be aware of the
authorship.  In addition, due to the collaborative nature of XEmacs,
many people have made small changes and emendations as they have
discovered problems.

   The following is a (necessarily incomplete) list of the work that was
_not_ done by Ben Wing (for more complete information, take a look at
the ChangeLog for the `man' directory and the CVS records of actual
changes):

Stephen Turnbull
     Various cleanup work, mostly post-2000.  Object-Oriented
     Techniques in XEmacs.  A Reader's Guide to XEmacs Coding
     Conventions.  Searching and Matching.  Regression Testing XEmacs.
     Modules for Regression Testing.  Lucid Widget Library.  A number
     of sections in the Future Work chapter.

Martin Buchholz
     Various cleanup work, mostly pre-2001.  Docs on inline functions.
     Docs on dfc conversion functions (Conversion to and from External
     Data).  Improvements in support for non-ASCII (European) keysyms
     under X.  A section or two in the Future Work chapter.

Hrvoje Niksic
     Coding for Mule.

Matthias Neubauer
     Garbage Collection - Step by Step.

Olivier Galibert
     Portable dumper documentation.

Andy Piper
     Redisplay Piece by Piece.  Glyphs.

Chuck Thompson
     Line Start Cache.

Kenichi Handa
     CCL.

Jamie Zawinski
     A couple of sections in the Future Work chapter.


File: internals.info,  Node: Authorship of XEmacs,  Next: A History of Emacs,  Prev: Introduction,  Up: Top

2 Authorship of XEmacs
**********************

XEmacs is the result of the time and effort of many people, and the
active developers have changed over time.  There are two major
components of the XEmacs effort - writing the code itself and providing
all the support work (testing the code, releasing beta and final
versions, handling patches, reading bug reports, maintaining the web
site, managing the mailing lists, etc. etc.).  Neither component would
work without the other.

CODING
------

The primary code contributor over the years has been Ben Wing (active
since late 1992).  Between 1991 and 1995, large amounts of coding was
contributed by Jamie Zawinski and Chuck Thompson.  Many other people
have authored major subsystems or otherwise contributed large amounts of
code, including Andy Piper, Hrvoje Niksic, Jerry James, Jonathan Harris,
Kyle Jones, Martin Buchholz, Michael Sperber, Olivier Galibert, Richard
Mlynarik, Stig, William Perry and plenty of others.

   Primary XEmacs-specific subsystems and their authors:

Objects
        - Conversion from 26-bit to 28-bit pointers and integers,
          lrecords, lcrecords: Richard Mlynarik, 1994

        - Conversion to 32-bit pointers and 31-bit integers: Kyle
          Jones, Martin Buchholz

        - Portable dumper, object descriptions: Olivier Galibert

        - KKCC (new garbage collector), ephemerons, weak boxes: Michael
          Sperber and students

        - Random object work (object equal and hash methods, weak
          lists, lcrecord lists, bit vectors, dynarr, blocktype,
          opaque, string resizing): Ben Wing

        - Profiling: Ben Wing

        - Some byte-compilation and hash-table improvements: Martin
          Buchholz

        - Bignum: Jerry James

Internationalization/Mule
        - mostly Ben Wing; many ideas for future work, Stephen Turnbull

I/O
        - Basic event/event-stream implementation: Jamie Zawinski

        - Most event work since 1994: Ben Wing

        - Asynchronous stuff (async timeouts, signals, quit-checking):
          Ben Wing

        - Process method abstraction, Windows process work: Kirill
          Katsnelson

        - Misc-user events, async timeouts, most quit-checking and
          signal code, most other work since 1994: Ben Wing

        - Lstreams: Ben Wing

Display
        - Redisplay mechanism: implementation, Chuck Thompson;
          additional work, lots of people

        - Glyphs: mostly Ben Wing

        - Specifiers: Ben Wing

        - Extents: initial implementation, someone at Lucid; rewrite,
          1994, Ben Wing

        - Widgets: Andy Piper

        - JPEG/PNG/TIFF image converters: Ben Wing, William Perry,
          Jareth Hein, others (see comment in `glyphs-eimage.c')

        - Menus: Jamie Zawinski, someone at Lucid (Lucid menus)

        - Scrollbars: Chuck Thompson, ??? (Lucid scrollbar)

        - Multi-device/device-independence work (console/device/etc
          methods): Ben Wing, prototype by chuck thompson

        - Faces: first implementation, Jamie Zawinski; second, chuck;
          third, Ben Wing

        - Fonts/colors: first implementation, Jamie Zawinski; further
          work, Ben Wing

        - Toolbars: implementation, chuck, much interface work, Ben Wing

        - Gutters, tabs: andy piper

Device subsystems
        - X Windows: Jamie Zawinksi, Ben Wing, others

        - GTK: William Perry, Malcolm Purvis

        - MS Windows: initial implementation, Jonathan Harris; some
          more work, Andy Piper, Ben Wing

        - TTY: Chuck Thompson, Ben Wing

        - Cygwin: Andy Piper

Misc
        - Configure: initial porting from fsf, Chuck Thompson;
          conversion to autoconf 2, much rewriting, Martin Buchholz

        - Most initialization-related code: Ben Wing

        - Internals manual, much of Lisp manual: Ben Wing

        - FSF synching: initial sync with FSF 19, Richard Mlynarik,
          further work, Ben Wing

SUPPORT
-------

Currently, support duties are handled by many different people.

   Release managers have been

   - Stephen Turnbull (April 2001 - January 2003, March 2004 - present,
     21.2.47 - 21.4.12, 21.5.2 - 21.5.7, 21.5.17 - present)

   - Vin Shelton (May 2003 - present, 21.4.13 - present)

   - Steve Youngs (July 2002 - September 2003, 21.5.8 - 21.5.16)

   - Martin Buchholz (December 1998, November 1999 - May 2001, 21.2.7 -
     21.2.8, 21.2.21 - 21.2.46, 21.5.0 - 21.5.1)

   - Steve Baur (early 1997 - December 1998, February 1999 - November
     1999, 19.15 - 21.2.5, 21.2.9 - 21.2.20)

   - Andy Piper (December 1998, 21.2.6)

   - Chuck Thompson (June 1994 - September 1996, 19.11 - 19.14)

   - Jamie Zawinski (April 1991 - June 1994, 19.0 - 19.10)

   The recent overlapping dates are intentional, since two or three
trees are maintained simultaneously at any point.

   Other major support work:

   - Adrian Aichner wrote and maintains the web site.

   - Stephen Turnbull has produced many of the beta and semi-stable
     releases and has attempted to be the "face" of XEmacs on the
     newsgroups and mailing lists.

   - Steve Youngs, Ville Skytta, and now Norbert Koch have taken turns
     maintaining the packages.

   - Vin Shelton maintains the stable releases.

   - Testing - #### Norbert, Adrian, ???


File: internals.info,  Node: A History of Emacs,  Next: The XEmacs Split,  Prev: Authorship of XEmacs,  Up: Top

3 A History of Emacs
********************

XEmacs is a powerful, customizable text editor and development
environment.  It began in 1991 as Lucid Emacs, which was in turn
derived from GNU Emacs, a program written by Richard Stallman of the
Free Software Foundation.  GNU Emacs dates back to 1985 and was
modelled after Unipress Emacs, an editor written by James Gosling in
1981 and based on a series of other "Emacs"-like editors, including
EINE (EINE Is Not EMACS), c. 1976, by Dan Weinreb, which run on the MIT
Lisp Machine and was the first Emacs written in Lisp; ZWEI (ZWEI Was
EINE Initially), c. 1978, by Dan Weinreb and Mike McMahon; Multics
Emacs, c. 1978, by Bernie Greenberg, which was written in MacLisp and
also used Lisp as its extension language; and ZMACS, c. 1980, a direct
descendant of ZWEI that on ran the Symbolics LM-2, LMI LispM, and
later, TI Explorer (1983-1989).  These in turn were inspired by the
first Emacs, a package called EMACS, written in 1976 by Richard
Stallman, Guy Steele, and Dave Moon.  This was a merger of TECMAC and
TMACS, a pair of "TECO-macro realtime editors" written by Guy Steele,
Dave Moon, Richard Greenblatt, Charles Frankston, et al., and added a
dynamic loader and Meta-key cmds.  It ran under ITS (the Incompatible
Timesharing System) on a DEC PDP 10 and under TWENEX on a Tops-20 and
was written in TECO and PDP 10 assembly.  ITS was one of the first
time-sharing operating systems and dates back well before Unix.  ITS,
TECO, and Emacs were products of a group of people at MIT who called
themselves "hackers", who shared an idealistic belief system about the
free exchange of information and were fanatical in their devotion to
and time spent with computers. (The hacker subculture dates back to the
late 1950's at MIT and is described in detail in Steven Levy's book
`Hackers'.  This book also includes a lot of information about Stallman
himself and the development of Lisp, a programming language developed
at MIT that underlies Emacs.)

* Menu:

* Through Version 18::          Unification prevails.
* Epoch::                       An early graphical split of GNU Emacs.
* Lucid Emacs::                 One version 19 Emacs.
* GNU Emacs 19::                The other version 19 Emacs.
* GNU Emacs 20::                The other version 20 Emacs.
* XEmacs::                      The continuation of Lucid Emacs.


File: internals.info,  Node: Through Version 18,  Next: Epoch,  Prev: A History of Emacs,  Up: A History of Emacs

3.1 Through Version 18
======================

As described above, Emacs began life in the mid-1970's as a series of
editor macros for TECO, an early editor on the PDP-10.  In the early
1980's it was rewritten in C as a collaboration between Richard M.
Stallman (RMS) and James Gosling (the creator of Java); its extension
language was known as "Mocklisp".  This version of Emacs-in-C formed
the basis for the early versions of GNU Emacs and also for Gosling's
Unipress Emacs, a commercial product.  Because of bad blood between the
two over the issue of commercialism, RMS pretty much disowned this
collaboration, referring to it as "Gosling Emacs".

   At this point we pick up with a time line of events. (A broader
timeline is available at "Emacs Timeline"
(http://http://www.jwz.org/doc/emacs-timeline.html).)

   *NOTE*: Sometimes there are two release dates listed below.  In this
case, the first one is the date listed in the source code, and the
second one is when the official announcement was made on Usenet.
(Sometimes, one or the other of the dates is missing, and then the date
below reflects the only existing one.)

   * Unipress Emacs, a $395 commercial product, was released on May 6,
     1983.  This was an outgrowth of the Emacs-in-C collaboration
     written by Gosling and RMS.

   * The first entry on `net.emacs' available on Google is dated August
     20, 1984:

          From: B.BURGER (btb@hogpc.UUCP)
          Subject: Arrow Key Problems
          Newsgroups: net.emacs
          Date: 1984-08-20 11:15:46 PST

          I would greatly appreciate some help getting my arrow keys to work
          with EMACS 4.5 on an AT&T 3B20.  My terminal is an AT&T PC6300
          (IBM-compatible) using an AT&T 4410 terminal emulator.  While this
          may not yet be a common configuration, I believe the same problem
          has come up using an hp2621 emulator or a real live vt100.

          The problem is that, when I press an arrow key, it isn't
          transmitted/read by emacs (one or the other) correctly.
          The 4410 terminal description that I'm using defines up=M-[A
          (it appears as ^[[A, with the initial ^[ as one character).
          Pressting cntrl-Q up_arrow while in emacs shows me the same thing.
          On the vt100 the same thing happens but the terminal file says up=M-A
          (it appears as ^[A).  I've tried every other imaginable up= but get
          the same results.  I've also been unsuccessful writing a macro that
          understands what my keyboard is saying.

          Any ideas on how I can get the arrow keys to do somethingt?
          Anything?  Thanks in advance.

          --Bruce Burger     AT&T-Information Systems     Freehold, NJ
            {...ihnp4!}hogpc!btb    (201) 577-5230

   * GNU Emacs versions 1.0 through 1.12 were apparently released in
     early 1985.  The next version after this was 13.0; there were no
     GNU Emacs versions 2 through 12.

   * GNU Emacs version 13.0? 1.0? was released on March 20, 1985.  This
     appears to be the initial public release.  This was also based on
     this same Emacs-in-C collaboration.

     Here is the release notice:

          From: Chuck Wegrzyn (wegrzyn@encore.UUCP)
          Subject: Public Domain EMACS available from GNU Project
          Newsgroups: net.emacs, net.general, net.unix, net.unix-wizards
          Date: 1985-03-20 08:03:20 PST

           The GNU project has released its first major subsystem,
           the EMACS editor. This editor is a sophisticated screen
           editor that is compatible and comparable with the EMACS
           editors being sold by UniPress and CCA. It comes with
           Mock Lisp ( did you know that UniPress trademarked MLISP??),
           and all the little bells and features most of us expect
           with EMACS.

           The GNU version of EMACS, written by Richard Stallman, is
           available for distribution. The distribution includes all
           source code for EMACS and a source code level debugger.
           Furthermore, under the GNU project banner, the EMACS system
           can be distributed (in source code form) by one and all.

           I was thinking of sending out the source code over the net,
           but resisted : it is over 1Mbyte of code. If there is
           enough demand, I will add a UUCP dial-in to our system, or
           send out tapes, or ... ?

           Is anyone interested in EMACS? If so, please tell me how
           you think I should distribute it?

             Chuck Wegrzyn
            {allegra,decvax,ihnp4,princeton}!encore!wegrzyn

   * GNU Emacs version 15.10 was released on April 11, 1985.

   * GNU Emacs version 15.34 was released on May 7, 1985.  This appears
     to be the last release of version 15.

   * GNU Emacs version 16 (first released version was 16.56) was
     released on July 15, 1985.  All Gosling code was removed due to
     potential copyright problems with the code.

   * Version 16.57: released on September 16, 1985.

   * Versions 16.58, 16.59: released on September 17, 1985.

   * Version 16.60: released on September 19, 1985.  These later
     version 16's incorporated patches from the net, esp. for getting
     Emacs to work under System V.

   * Version 17.36 (first official v17 release) released on December 20,
     1985.  Included a TeX-able user manual.  First official unpatched
     version that worked on vanilla System V machines.

   * Version 17.43 (second official v17 release) released on January 25,
     1986.

   * Version 17.45 released on January 30, 1986.

   * Version 17.46 released on February 4, 1986.

   * Version 17.48 released on February 10, 1986 (February 9 on
     net.emacs).

   * Version 17.49 released on February 12, 1986.

   * Version 17.55 released on March 18, 1986.

   * Version 17.57 released on March 27, 1986.

   * Version 17.58 released on April 4, 1986.

   * Version 17.61 released on April 12 (?), 1986 (April 22 on
     net.emacs).

   * Version 17.63 released on May 7, 1986.

   * Version 17.64 released on May 12, 1986.

   * Version 18.24 (a beta version) released on October 2, 1986.

   * Version 18.30 (a beta version) released on November 15, 1986.

   * Version 18.31 (a beta version) released on November 23, 1986.

   * Version 18.32 (a beta version) released on December 6 or 7, 1986.

   * Version 18.33 (a beta version) released on December 12, 1986.

   * Version 18.35 (a beta version) released on January 5, 1987.

   * Version 18.36 (a beta version) released on January 21, 1987.

   * January 27, 1987: The Great Usenet Renaming.  net.emacs is now
     comp.emacs.

   * Version 18.37 (a beta version) released on February 9 or 12, 1987.

   * Version 18.38 (a beta version) released on March 2 or 3, 1987.

   * Version 18.39 (a beta version) released on March 14, 1987.

   * Version 18.40 (a beta version) released on March 18, 1987.

   * Version 18.41 (the first "official" release) released on March 22,
     1987.

   * Version 18.45 released on June 2, 1987.

   * Version 18.46 released on June 8 or 9, 1987.

   * Version 18.47 released on June 10 or 18, 1987.

   * Version 18.48 released on August 30 or September 3, 1987.

   * Version 18.49 released on September 16 or 18, 1987.

   * Version 18.50 released on February 11 or 13, 1988.

   * Version 18.51 released on May 6 or 7, 1988.

   * Version 18.52 released on September 1, 1988.

   * Version 18.53 released on February 23 or 24, 1989.

   * Version 18.54 released on April 26, 1989.

   * Version 18.55 released on August 18 or 23, 1989.  This is the
     earliest version that is still available by FTP. (Verified in
     November 2004.)

   * Version 18.56 released on January 16 or 17, 1991.

   * Version 18.57 released on January 25, 1991.

   * Version 18.58 released on February 18, 1991.

   * Version 18.59 released on October 30 or 31, 1992.


File: internals.info,  Node: Epoch,  Next: Lucid Emacs,  Prev: Through Version 18,  Up: A History of Emacs

3.2 Epoch
=========

#### Document Epoch

   A time line for Epoch is

   * Epoch 1.0 released December 14, 1989. (by Simon Kaplan, Chris
     Love, et al.)

   * Epoch 2.0 released December 23, 1989.

   * Epoch 3.1 released February 6, 1990.

   * Epoch 3.2 released December[????] 11, 1990.

   * Epoch 4.0 released August 27, 1990.


File: internals.info,  Node: Lucid Emacs,  Next: GNU Emacs 19,  Prev: Epoch,  Up: A History of Emacs

3.3 Lucid Emacs
===============

Lucid Emacs was developed by the (now-defunct) Lucid Inc., a maker of
C++ and Lisp development environments.  It began when Lucid decided they
wanted to use Emacs as the editor and cornerstone of their C++
development environment (called "Energize").  They needed many features
that were not available in the existing version of GNU Emacs (version
18.5something), in particular good and integrated support for GUI
elements such as mouse support, multiple fonts, multiple window-system
windows, etc.  A branch of GNU Emacs called Epoch, written at the
University of Illinois, existed that supplied many of these features;
however, Lucid needed more than what existed in Epoch.  At the time, the
Free Software Foundation was working on version 19 of Emacs (this was
sometime around 1991), which was planned to have similar features, and
so Lucid decided to work with the Free Software Foundation.  Their plan
was to add features that they needed, and coordinate with the FSF so
that the features would get included back into Emacs version 19.

   Delays in the release of version 19 occurred, however (resulting in
it finally being released more than a year after what was initially
planned), and Lucid encountered unexpected technical resistance in
getting their changes merged back into version 19, so they decided to
release their own version of Emacs, which became Lucid Emacs 19.0.

   The initial authors of Lucid Emacs were Matthieu Devin, Harlan
Sexton, and Eric Benson, and the work was later taken over by Jamie
Zawinski, who became "Mr. Lucid Emacs" for many releases.

   A time line for Lucid Emacs is

   * Version 19.0 shipped with Energize 1.0, April 1992.

   * Version 19.1 released June 4, 1992.

   * Version 19.2 released June 19, 1992.

   * Version 19.3 released September 9, 1992.

   * Version 19.4 released January 21, 1993.

   * Version 19.5 released February 5, 1993.  This was a repackaging of
     19.4 with a few bug fixes and shipped with Energize 2.0.  It was a
     trade-show giveaway and never released to the net.

   * Version 19.6 released April 9, 1993.

   * Version 19.7 was a repackaging of 19.6 with a few bug fixes and
     shipped with Energize 2.1.  Never released to the net.

   * Version 19.8 released September 6, 1993. (Epoch 4.0 merger of
     redisplay code, preliminary I18N support, code merged from GNU
     Emacs 19.8 beta)

   * Version 19.9 released January 12, 1994. (Scrollbars, Athena.)

   * Version 19.10 released May 27, 1994. (Uses `configure'; code merged
     from GNU Emacs 19.23 beta and further merging with Epoch 4.0)
     Known as "Lucid Emacs" when shipped by Lucid, and as "XEmacs" when
     shipped by Sun; but Lucid went out of business a few days later
     and it's unclear very many copies of 19.10 were released by Lucid.
     (Last release by Jamie Zawinski.)


File: internals.info,  Node: GNU Emacs 19,  Next: GNU Emacs 20,  Prev: Lucid Emacs,  Up: A History of Emacs

3.4 GNU Emacs 19
================

About a year after the initial release of Lucid Emacs, the FSF released
a beta of their version of Emacs 19 (referred to here as "GNU Emacs").
By this time, the current version of Lucid Emacs was 19.6. (Strangely,
the first released beta from the FSF was GNU Emacs 19.7.) A time line
for GNU Emacs version 19 is

   * Version 19.7 beta released May 22, 1993.  First public beta v19
     release.

   * Version 19.8 beta released May 25 or 27, 1993.

   * Version 19.9 beta released May 27, 1993.

   * Version 19.10 beta released May 30, 1993.

   * Version 19.11 beta released June 1, 1993.

   * Version 19.12 beta released June 1 or 2, 1993.

   * Version 19.13 beta released June 8, 1993.

   * Version 19.14 beta released June 17, 1993.

   * Version 19.15 beta released June 19, 1993.

   * Version 19.16 beta released July 6, 1993.

   * Version 19.17 beta released July 17, 1993.

   * Version 19.18 beta released August 8 or 9, 1993.

   * Version 19.19 beta released August 14 or 15, 1993.

   * Version 19.20 beta released November 11 or 17, 1993.

   * Version 19.21 beta released November 16 or 17, 1993.

   * Version 19.22 beta released November 27 or 28, 1993.

   * Version 19.23 beta released May 17, 1994.

   * Version 19.24 beta released May 23 or 16 (?), 1994.

   * Version 19.25 beta released May 30 or June 3, 1994.

   * Version 19.26 beta released September 7 or 11, 1994.

   * Version 19.27 beta released September 11 or 14, 1994.

   * Version 19.28 (first "official" release) released November 1, 1994.

   * Version 19.29 released June 19 or 21, 1995.

   * Version 19.30 released November 24, 1995.

   * Version 19.31 released May 25, 1996.

   * Version 19.32 released July 31, 1996.

   * Version 19.33 released August 11, 1996.

   * Version 19.34 released August 21, 1996.

   * Version 19.34b released September 6, 1996.

   In some ways, GNU Emacs 19 was better than Lucid Emacs; in some ways,
worse.  Lucid soon began incorporating features from GNU Emacs 19 into
Lucid Emacs; for the first year, the work was mostly done by Richard
Mlynarik, who had been working on and using GNU Emacs for a long time
(back as far as version 16 or 17).  After that, Lucid folded and Sun
continued with XEmacs; further merging work has continued up through
the present, done mostly by Ben Wing but a good deal of synching was
done by Steve Baur in 1996 with GNU Emacs 19.34.


File: internals.info,  Node: GNU Emacs 20,  Next: XEmacs,  Prev: GNU Emacs 19,  Up: A History of Emacs

3.5 GNU Emacs 20
================

On February 2, 1997 work began on GNU Emacs to integrate Mule.  The
first release was made in September of that year.

   A timeline for GNU Emacs 20 is

   * Version 20.1 released September 15 or 17, 1997.

   * Version 20.2 released September 19 or 20, 1997.

   * Version 20.3 released August 19, 1998.

   * version 20.4 released July 12, 1999; on comp.emacs, July 27.

   * version 20.5 released December 4, 1999.

   * version 20.6 released February 26, 2000.

   * version 20.7 released June 13, 2000.

   A timeline for GNU Emacs 21 is

   * version 21.1 released October 20, 2001.

   * Version 21.2 released March 16, 2002.

   * Version 21.3 released March 19, 2003.


File: internals.info,  Node: XEmacs,  Prev: GNU Emacs 20,  Up: A History of Emacs

3.6 XEmacs
==========

Around the time that Lucid was developing Energize, Sun Microsystems
was developing their own development environment (called "SPARCWorks")
and also decided to use Emacs.  They joined forces with the Epoch team
at the University of Illinois and later with Lucid.  The maintainer of
the last-released version of Epoch was Marc Andreessen, but he dropped
out and the Epoch project, headed by Simon Kaplan, lured Chuck Thompson
away from a system administration job to become the primary Lucid Emacs
author for Epoch and Sun.  Chuck's area of specialty became the
redisplay engine (he replaced the old Lucid Emacs redisplay engine with
a ported version from Epoch and then later rewrote it from scratch).
Sun also hired Ben Wing (the author of Win-Emacs, a port of Lucid Emacs
to Microsoft Windows 3.1) in 1993, for what was initially a one-month
contract to fix some event problems but later became a many-year
involvement, punctuated by a six-month contract with Amdahl Corporation.

   In 1994, Sun and Lucid agreed to rename Lucid Emacs to XEmacs (a name
not favorable to either company); the first release called XEmacs was
version 19.11.  In June 1994, Lucid folded and Jamie quit to work for
the newly formed Mosaic Communications Corp., later Netscape
Communications Corp. (co-founded by the same Marc Andreessen, who had
quit his Epoch job to work on a graphical browser for the World Wide
Web).  Chuck and Ben then become the primary authors and maintainers of
XEmacs, with Chuck putting out versions 19.11 through 19.14 in
conjunction with Ben.  For 19.12 through 19.14, Chuck added the new
redisplay and various other display improvements and Ben added MULE
support (support for Asian and other languages), multi-device support,
glyphs, specifiers, and GIF/JPG/PNG support, and redesigned most of the
internal Lisp subsystems to better support the MULE work, display work
and the various other features being added to XEmacs.  After 19.14
Chuck retired from XEmacs and Steve Baur stepped in as release
engineer.  Ben Wing continued on as the primary author and architect of
XEmacs and has remained, sometimes on-and-off, with XEmacs until the
present day (late 2004), being responsible for perhaps 75% of all the
non-FSF code in the core (i.e. not the packages) of XEmacs.

   Soon after 19.13 was released, work began in earnest on the MULE
internationalization code and the source tree was divided into two
development paths.  The MULE version was initially called 19.20, but was
soon renamed to 20.0.  In 1996 Martin Buchholz of Sun Microsystems took
over the care and feeding of it and worked on it in parallel with the
19.14 development that was occurring at the same time.  After much work
by Martin, it was decided to release 20.0 ahead of 19.15 in February
1997.  The source tree remained divided until 20.2 when the version 19
source was finally retired at version 19.16.

   In 1997, Sun finally dropped all pretense of support for XEmacs and
Martin Buchholz left the company in November.  Since then, and mostly
for the previous year, because Steve Baur was never paid to work on
XEmacs, XEmacs has existed solely on the contributions of volunteers
from the Free Software Community.

   Between 1997 and 2000, MS-Windows support was added and stabilized by
Jonathan Harris, Andy Piper, Ben Wing and Kirill Katsnelson.  Hrvoje
Niksic and Kyle Jones figured prominently in XEmacs development during
these same years.  Steve Baur added the package system in 1997 (?), and
Olivier Galibert also added the portable dumper support around 2000.
Martin Buchholz took over from Steve Baur as release manager in late
1998 (?), and continued in this position through to eary 2000 (?), when
Stephen Turnbull took it over.  XEmacs has also been split into stable
and experimental branches since early 1999, and Vin Shelton has been
the release manager of the stable branches since the beginning.  Ben
Wing suffered severe pain problems throughout much of this time, making
him unable to use his hands, but he contributed when he could,
especially in the form of dictated design documents.

   Starting around 2000, Kyle, Hrvoje, Martin and Kirill became less
active.  Jonathan Harris had dropped out of the project around 1998,
and Andy Piper became mostly inactive by the year 2001 or 2002.  New
faces appeared, however, and others continued strong:

   * Michael Sperber, who had been in the background as a beta tester
     for a fair amount of time, began to assume a more active role.  He
     revamped the path-searching code at initialization time, did some
     major work on the CVS repositories, and is in the process of a
     major project to replace the garbage collector, which he is
     overseeing with some of his students (e.g. Marcus Crestani).

   * Steve Youngs stepped in as package maintainer in late 1998 (?).

   * Stephen Turnbull has contained to produce the experimental beta
     releases, write code when he can, produce many design documents,
     and generally oversee the managerial aspects of the project.

   * Jerry James appeared on the scene in early 2002 and has
     contributed a large amount of code, including the module
     subsystem, bignums, and lots of other code cleanup.

   * Bill Perry, who had been active on and off in XEmacs since the
     early 1990's (e.g. he did a fair amount of work on the JPG and PNG
     interface and added the TIFF interface, in addition to writing the
     Emacs/W3 browser), added GTK support for XEmacs, a major project
     for which he received a multi-month contract through BeOpen (?).
     He has since disappeared but Malcolm Purvis has taken up the GTK
     project again and is keeping it going when he has time.

   * Adrian Aichner is continuing to create and update the web site on
     XEmacs Web Site (www.xemacs.org), and is a particularly active
     beta tester.

   * Ben Wing has recovered somewhat from the bad years of 1997 - 1999
     and has resumed his position as Architect of XEmacs and chief code
     contributor to the project.  He added Mule on Windows support,
     Unicode support, the Internals manual (originally written by him
     during his last days at Sun) and many other projects, and is now
     working on a new behaviors system and cleanups of various other
     subsystems.

   * Vin Shelton continues to put out stable releases of XEmacs.

   Many attempts have been made to merge XEmacs and GNU Emacs, but they
have consistently failed.

   A more detailed history is contained in the XEmacs About page.

   For more detailed information about the features added to each
version, see the files `NEWS', `ONEWS', and `OONEWS' in the `etc/'
directory.

   A time line for XEmacs is

   * version 19.11 (first XEmacs) released September 13, 1994.

   * Initial work on Mule support begins September 1994 by both Ben
     Wing and Stig.  Both projects got bogged down in other issues.

   * version 19.12 released June 23, 1995. (The Release Times 10.
     Included rewritten redisplay, TTY support, multi-device support,
     device and console objects, specifiers, glyphs, toolbars,
     horizontal scrollbars, Lucid scrollbar widget, 3-d modeline,
     stay-up Lucid menus, resizable minibuffer, echo area is a true
     buffer, MD5 hashing support, expanded menubar, redone menu
     specification format (including menu filters), rewritten extents,
     renamed "screen" to "frame", misc-user events, rewritten face
     code, rewritten mouse code, warnings system, CL backquote syntax,
     critical C-g, code merging with GNU Emacs 19.28.  New packages
     Hyperbole, OOBR, hm-html-menus, viper, lazy-lock, ksh-mode,
     rsz-minibuf.)

   * Mule work done in earnest from May through November, 1995 by Ben
     Wing.  Early on, much of the work involved Mule-izing and was
     incorporated into 19.12 and 19.13.  After the release of 19.13,
     further work was forked onto a new development branch, which
     eventually became 20.0.

   * version 19.13 released September 1, 1995. (Bug-fix release.
     Message logging, background pixmaps, sticky modifiers, Linux audio
     support, new Elisp manual, keyboard-translate-table.  New packages
     ada-mode, arc-mode, auto-show-mode, completion, dabbrev, easymenu,
     live-icon, mailcrypt 3.2, two-column.)

   * xemacs.org created, date ??? - early 1996?.

   * version 19.14 released June 23, 1996. (TTY colors, mousable/color
     modeline, GIF/JPEG/PNG support, file dialog box, blinking cursor,
     gnuattach, auto scrolling horizontally to keep point in view, major
     code merging with GNU Emacs 19.30, key bindings from GNU Emacs
     19.30, surrogate minibuffers, function-key-map,
     key-translation-map.  New packages PSGML, Java/VRML modes, GNUS
     5.2.)

   * version 20.0 released February 9, 1997.

   * version 19.15 released March 28, 1997. (Custom, widget, new logo
     and background color, introduction of `compatible' variables,
     major code merging with GNU Emacs 19.30.  New packages EFS, TM,
     AUC Tex, redo, igrep, uniquify, many others.)

   * version 20.1 (not released to the net) April 15, 1997.

   * version 20.2 released May 16, 1997.

   * version 19.16 released October 31, 1997. (Bug-fix release.  Faster
     font-locking.  Not much else.)

   * version 20.3 (the first stable version of XEmacs 20.x) released
     November 30, 1997.

   * version 20.4 released February 28, 1998.

   * version 21.0.60 released December 10, 1998. (The version naming
     scheme was changed at this point: [a] the second version number is
     odd for stable versions, even for beta versions; [b] a third
     version number is added, replacing the "beta xxx" ending for beta
     versions and allowing for periodic maintenance releases for stable
     versions.  Therefore, 21.0 was never "officially" released;
     similarly for 21.2, etc.)

   * version 21.0.61 released January 4, 1999.

   * version 21.0.63 released February 3, 1999.

   * version 21.0.64 released March 1, 1999.

   * version 21.0.65 released March 5, 1999.

   * version 21.0.66 released March 12, 1999.

   * version 21.0.67 released March 25, 1999.

   * version 21.1.2 released May 14, 1999. (This is the followup to
     21.0.67.  The second version number was bumped to indicate the
     beginning of the "stable" series.)

   * version 21.1.3 released June 26, 1999.

   * version 21.1.4 released July 8, 1999.

   * version 21.1.6 released August 14, 1999. (There was no 21.1.5.)

   * version 21.1.7 released September 26, 1999.

   * version 21.1.8 released November 2, 1999.

   * version 21.1.9 released February 13, 2000.

   * version 21.1.10 released May 7, 2000.

   * version 21.1.10a released June 24, 2000.

   * version 21.1.11 released July 18, 2000.

   * version 21.1.12 released August 5, 2000.

   * version 21.1.13 released January 7, 2001.

   * version 21.1.14 released January 27, 2001.

   * version 21.2.9 released February 3, 1999.

   * version 21.2.10 released February 5, 1999.

   * version 21.2.11 released March 1, 1999.

   * version 21.2.12 released March 5, 1999.

   * version 21.2.13 released March 12, 1999.

   * version 21.2.14 released May 14, 1999.

   * version 21.2.15 released June 4, 1999.

   * version 21.2.16 released June 11, 1999.

   * version 21.2.17 released June 22, 1999.

   * version 21.2.18 released July 14, 1999.

   * version 21.2.19 released July 30, 1999.

   * version 21.2.20 released November 10, 1999.

   * version 21.2.21 released November 28, 1999.

   * version 21.2.22 released November 29, 1999.

   * version 21.2.23 released December 7, 1999.

   * version 21.2.24 released December 14, 1999.

   * version 21.2.25 released December 24, 1999.

   * version 21.2.26 released December 31, 1999.

   * version 21.2.27 released January 18, 2000.

   * version 21.2.28 released February 7, 2000.

   * version 21.2.29 released February 16, 2000.

   * version 21.2.30 released February 21, 2000.

   * version 21.2.31 released February 23, 2000.

   * version 21.2.32 released March 20, 2000.

   * version 21.2.33 released May 1, 2000.

   * version 21.2.34 released May 28, 2000.

   * version 21.2.35 released July 19, 2000.

   * version 21.2.36 released October 4, 2000.

   * version 21.2.37 released November 14, 2000.

   * version 21.2.38 released December 5, 2000.

   * version 21.2.39 released December 31, 2000.

   * version 21.2.40 released January 8, 2001.

   * version 21.2.41 "Polyhymnia" released January 17, 2001.

   * version 21.2.42 "Poseidon" released January 20, 2001.

   * version 21.2.43 "Terspichore" released January 26, 2001.

   * version 21.2.44 "Thalia" released February 8, 2001.

   * version 21.2.45 "Thelxepeia" released February 23, 2001.

   * version 21.2.46 "Urania" released March 21, 2001.

   * version 21.2.47 "Zephir" released April 14, 2001.

   * XEmacs 21.4.0 "Solid Vapor" released April 16, 2001.

   * XEmacs 21.4.1 "Copyleft" released April 19, 2001.

   * XEmacs 21.4.2 "Developer-Friendly Unix APIs" released May 10, 2001.

   * XEmacs 21.4.3 "Academic Rigor" released May 17, 2001.

   * XEmacs 21.4.4 "Artificial Intelligence" released July 28, 2001.

   * XEmacs 21.4.5 "Civil Service" released October 23, 2001.

   * XEmacs 21.4.6 "Common Lisp" released December 17, 2001.

   * XEmacs 21.4.7 "Economic Science" released May 4, 2002.

   * XEmacs 21.4.8 "Honest Recruiter" released May 9, 2002.

   * XEmacs 21.4.9 "Informed Management" released August 23, 2002.

   * XEmacs 21.4.10 "Military Intelligence" released November 2, 2002.

   * XEmacs 21.4.11 "Native Windows TTY Support" released January 3,
     2003.

   * XEmacs 21.4.12 "Portable Code" released January 15, 2003.

   * XEmacs 21.4.13 "Rational FORTRAN" released May 25, 2003.

   * XEmacs 21.4.14 "Reasonable Discussion" released September 3, 2003.

   * XEmacs 21.4.15 "Security Through Obscurity" released February 2,
     2004.

   * XEmacs 21.4.16 "Successful IPO" released December 5, 2004.

   * version 21.5.0 "alfalfa" released April 18, 2001.

   * version 21.5.1 "anise" released May 9, 2001.

   * version 21.5.2 "artichoke" released July 28, 2001.

   * version 21.5.3 "asparagus" released September 7, 2001.

   * version 21.5.4 "bamboo" released January 8, 2002.

   * version 21.5.5 "beets" released March 5, 2002.

   * version 21.5.6 "bok choi" released April 5, 2002.

   * version 21.5.7 "broccoflower" released July 2, 2002.

   * version 21.5.8 "broccoli" released July 27, 2002.

   * version 21.5.9 "brussels sprouts" released August 30, 2002.

   * version 21.5.10 "burdock" released January 4, 2003.

   * version 21.5.11 "cabbage" released February 16, 2003.

   * version 21.5.12 "carrot" released April 24, 2003.

   * version 21.5.13 "cauliflower" released May 10, 2003.

   * version 21.5.14 "cassava" released June 1, 2003.

   * version 21.5.15 "celery" released September 3, 2003.

   * version 21.5.16 "celeriac" released September 26, 2003.

   * version 21.5.17 "chayote" released March 22, 2004.

   * version 21.5.18 "chestnut" released October 22, 2004.


File: internals.info,  Node: The XEmacs Split,  Next: XEmacs from the Outside,  Prev: A History of Emacs,  Up: Top

4 The XEmacs Split
******************

Author: Ben Wing (mailto:ben@xemacs.org)

Ben Wing's attempts
-------------------

*Nota bene:* The following is a *highly* opinionated piece written by
one of the main authors of XEmacs.  This reflects his opinions, and his
only!  It is included here because it may help to clarify some of the
issues that are keeping the two versions of Emacs separate.

   Many people look at the split between GNU Emacs and XEmacs and are
convinced that the XEmacs team is being needlessly divisive and just
needs to cooperate a bit with RMS, and the two versions of Emacs will
merge. In fact there have been six to seven major attempts at merging,
each running hundreds of messages long and all of them coming from the
XEmacs side. All have failed because they have eventually come to the
same conclusion, which is that RMS has no real interest in cooperation
at all. If you work with him, you have to do it his way - "my way or
the highway".  Specifically:

  1.  RMS insists on having legal papers signed for every bit of code
     that goes into GNU Emacs. RMS's lawyers have told him that every
     contribution over ten lines long requires legal papers. These
     papers cannot be filled out over to the web but must be done so in
     person and mailed to the FSF.  Obviously this by itself has a
     tendency to inhibit contributions because of the hassle factor.
     Furthermore, many people (and especially organizations) are either
     hesitant to or refuse to sign legal papers, for reasons mentioned
     below.  Because of these reasons, XEmacs has never enforced legal
     signed papers for the code in it. Such papers are not a part of
     the GPL and are not required by any projects other than those of
     the FSF (for example, Linux does not require such papers). Since
     we do not know exactly who is the author of every bit of code that
     has been contributed to XEmacs in the last nine years, we would
     essentially have to rewrite large sections of the code. The
     situation however, is worse than that because many of the large
     copyright holders of XEmacs (for example Sun Microsystems) refuse
     to sign legal papers. Although they have not stated their reasons,
     there are quite a number of reasons not to sign legal papers:

        * By doing so you essentially give up all control over your
          code.  You can no longer release your code under a different
          license.  If you want to use your code that you've
          contributed to the FSF in a project of your own, and that
          project is not released under the GPL, you are not allowed to
          do this.  (This is supposed to be avoided by the standard
          assignment contract used by the FSF, which either
          automatically relicenses the code to the author for any
          purpose under any license, or promises to do so, depending on
          the version - stephen.)  Obviously, large companies tend to
          want to reuse their code in many different projects and as a
          result feel very uncomfortable about signing legal papers.

        * One of the dangers of assigning copyright to the FSF is that
          if the FSF happens to be taken over by some evil corporate
          identity or anyone with different ideas than RMS, they will
          own all copyright-assigned code, and can revoke the GPL and
          enforce any license they please.  (This is false, according
          to RMS; the FSF's covenants and the assignment contracts
          require that it or any successors may release the code only
          under copyleft.  Thus, the only real loophole is if the FSF
          goes bankrupt, somehow leaving the code in the public domain
          - stephen.)  If the code has many different copyright
          holders, this is much less likely of a scenario.

  2. RMS does not like abstract data structures. Abstract data
     structures are the foundation of XEmacs and most other modern
     programming projects. In my opinion, is difficult to impossible to
     write maintainable and expandable code without using abstract data
     structures. In merging talks with RMS he has said we can have any
     abstract data structures we want in a merged version but must
     allow direct access to the implementation as well, which defeats
     the primary purpose of having abstract data structures.

  3. RMS is very unwilling to compromise when it comes to divergent
     implementations of the same functionality, which is very common
     between XEmacs and GNU Emacs. Rather than taking the better
     interface on technical grounds, RMS insists that both interfaces
     must be implemented in C at the same level (rather than
     implementing one in C and the other on top if it), so that code
     that uses either interface is just as fast. This means that the
     resulting merged Emacs would be filled with a lot of very
     complicated code to simultaneously support two divergent
     interfaces, and would be difficult to maintain in this state.

  4. RMS's idea of compromise and cooperation is almost purely political
     rather than technical. The XEmacs maintainers would like to have
     issues resolved by examining them technically and deciding what
     makes the most sense from a technical prospective. RMS however,
     wants to proceed on a tit for tat kind of basis, which is to say,
     “If we support this feature of yours, we also get to support this
     other feature of mine.” The result of such a process is typically
     a big mess, because there is no overarching design but instead a
     great deal of incompatible things hodgepodged together.

   If only some of the above differences were firmly held by RMS, and
if he were willing to compromise effectively on the others and to
demonstrate willingness to work with us on the issues that he is less
willing to compromise on, we might go ahead with the merge despite
misgivings. However RMS has shown no real interest at all in
compromising. He has never stated how all of the redundant work that
would be required to support his preconditions would get done. It's
unlikely that he would do it all and it's certainly not clear that the
XEmacs project would be willing to do it all, given that it is a
tremendous amount of extra work and the XEmacs project is already
strapped for coding resources. (Not to mention the inherent difficulty
in convincing people to redo existing work for primarily political
reasons.) In general the free software community is quite strapped as a
whole for coding resources; duplicative efforts amount to very little
positively and have a lot of negative effects in that they take away
what few resources we do have from projects that would actually be
useful.

   RMS however, does not seem to be bothered by this. He is more
interested in sticking firm to his principles, though the heavens may
fall down, than in working forward to create genuinely useful software.
It is abundantly clear that RMS has no real interest in unity except if
it happens to be on his own terms and allows him ultimate control over
the result. He would rather see nothing happen at all than something
that is not exactly according to his principles.  The fact that few if
any people share his principles is meaningless to him.

Jamie Zawinski's attempts
-------------------------

In 1991, I was working at Lucid Inc., and our newest product, Energize,
was an integrated development environment for C and C++ on Unix. The
design of this development environment involved very tight integration
between the various tools: compilers, linkers, debuggers, graphers, and
editors. So of course we needed a powerful editor to tie the whole
thing together, and it was obvious to all of us that there was only one
editor that would do: Emacs.

   At the time, the current version of GNU Emacs from the FSF was Emacs
18. There was another version of GNU Emacs called Epoch, that had been
developed at NCSA, which was a set of patches to Emacs 18 that gave it
much better GUI support (Emacs 18 was very much a tty program, with GUI
support crudely grafted on as an afterthought.)

   For the last few years, Emacs 19 had been due to be released "real
soon now," and was expected to integrate the various features of Epoch
in a cleaner way. The Epoch maintainers themselves saw Epoch as an
interim measure, awaiting the release of Emacs 19.

   So, at Lucid we didn't want to tie ourselves to Emacs 18 or on Epoch,
because those code bases were considered obsolete by their maintainers.
We wanted to use Emacs 19 with our product: the idea was that our
product would operate with the off-the-shelf version of Emacs 19, which
most people would already have pre-installed on their system anyway.
That way, Energize would make use, to some extent, of tools you already
had and were already using.

   The only problem was, Emacs 19 wasn't done yet. So, we decided we
could help solve that problem, by providing money and resources to get
Emacs 19 finished.

   Even though Energize was a proprietary, commercial product, all of
our work on Emacs (and on GCC and GDB) was released under the GPL. We
even assigned the copyright on all of our work back to the FSF, because
we had no proprietary interest in Emacs per se: it was just a tool that
we wanted to use, and we wanted it to work well, and that was best
achieved by making our modifications to it be as freely available as
possible. (This was one of the earliest, if not the earliest, example
of a commercial product being built to a significant extent out of open
source software.)

   Well, our attempts to help the FSF complete their Emacs 19 project
were pretty much a disaster, and we reached the point where we just
couldn't wait any longer: we needed to ship our product to customers,
and our product needed to have an editor in it. So we bundled up our
work on GNU Emacs 19, called it Lucid Emacs, and released it to the
world.

   This incident has become famous as one of the most significant
"forks" in a free software code base.

   When Lucid went out of business in 1994, and I came to Netscape, I
passed the torch for the maintenance of Lucid Emacs to Chuck Thompson
(at NCSA) and Ben Wing (at Sun), who renamed it from "Lucid Emacs" to
"XEmacs."

   To this day, XEmacs is as popular as FSFmacs, because it still
provides features and a design that many people find superior to the
FSF's version.

   I attribute Lucid Emacs's success to two things, primarily:

   First, that my focus was on user interface, and an attempt to both
make Emacs be a good citizen of modern GUI desktops, and to make it as
easy for new users to pick up Emacs as any other GUI editor;

   Second, that I ran the Lucid Emacs project in a much more open,
inclusive way than RMS ran his project. I was not just willing, but
eager, to delegate significant and critical pieces of the project to
other hackers once they had shown that they knew what they were doing.
RMS was basically never willing to do this with anybody. Other things
that helped Lucid Emacs's success, but were probably less important
than the above:

   We gave the users what they wanted first. People had been
anticipating Emacs 19 for years, and we stopped dragging our feet and
finished it. So this got us a lot of users up front. However, XEmacs's
current popularity can't be attributed to this, not since 1993, anyway.

   Lucid Emacs was technically superior in many ways. This won us the
mindshare of many good developers, who preferred working with Lucid
Emacs to FSF Emacs. It would be nice if technical superiority was all
that mattered, but realistically, the other factors were probably more
important than this one, as far as number of users is concerned. The
following messages, from the Lucid Emacs mailing lists in 1992 and
1993, comprise the bulk (if not the entirety) of the public discussions
between the Lucid and FSF camps on why the split happened and why a
merger never did.  The Lucid Emacs Split
(http://www.jwz.org/doc/lemacs.html).

   The current XEmacs maintainers have a much more pusillanimous summary
of this history on their XEmacs versus GNU Emacs page
(http://www.xemacs.org/About/XEmacsVsGNUemacs.html).

   - jwz, 11-Feb-2000.


File: internals.info,  Node: XEmacs from the Outside,  Next: The Lisp Language,  Prev: The XEmacs Split,  Up: Top

5 XEmacs from the Outside
*************************

XEmacs appears to the outside world as an editor, but it is really a
Lisp environment.  At its heart is a Lisp interpreter; it also
"happens" to contain many specialized object types (e.g. buffers,
windows, frames, events) that are useful for implementing an editor.
Some of these objects (in particular windows and frames) have
displayable representations, and XEmacs provides a function
`redisplay()' that ensures that the display of all such objects matches
their internal state.  Most of the time, a standard Lisp environment is
in a "read-eval-print" loop--i.e. "read some Lisp code, execute it, and
print the results".  XEmacs has a similar loop:

   * read an event

   * dispatch the event (i.e. "do it")

   * redisplay

   Reading an event is done using the Lisp function `next-event', which
waits for something to happen (typically, the user presses a key or
moves the mouse) and returns an event object describing this.
Dispatching an event is done using the Lisp function `dispatch-event',
which looks up the event in a keymap object (a particular kind of
object that associates an event with a Lisp function) and calls that
function.  The function "does" what the user has requested by changing
the state of particular frame objects, buffer objects, etc.  Finally,
`redisplay()' is called, which updates the display to reflect those
changes just made.  Thus is an "editor" born.

   Note that you do not have to use XEmacs as an editor; you could just
as well make it do your taxes, compute pi, play bridge, etc.  You'd just
have to write functions to do those operations in Lisp.


File: internals.info,  Node: The Lisp Language,  Next: XEmacs from the Perspective of Building,  Prev: XEmacs from the Outside,  Up: Top

6 The Lisp Language
*******************

Lisp is a general-purpose language that is higher-level than C and in
many ways more powerful than C.  Powerful dialects of Lisp such as
Common Lisp are probably much better languages for writing very large
applications than is C. (Unfortunately, for many non-technical reasons
C and its successor C++ have become the dominant languages for
application development.  These languages are both inadequate for
extremely large applications, which is evidenced by the fact that newer,
larger programs are becoming ever harder to write and are requiring ever
more programmers despite great increases in C development environments;
and by the fact that, although hardware speeds and reliability have been
growing at an exponential rate, most software is still generally
considered to be slow and buggy.)

   The new Java language holds promise as a better general-purpose
development language than C.  Java has many features in common with
Lisp that are not shared by C (this is not a coincidence, since Java
was designed by James Gosling, a former Lisp hacker).  This will be
discussed more later.

   For those used to C, here is a summary of the basic differences
between C and Lisp:

  1. Lisp has an extremely regular syntax.  Every function, expression,
     and control statement is written in the form

             (FUNC ARG1 ARG2 ...)

     This is as opposed to C, which writes functions as

             func(ARG1, ARG2, ...)

     but writes expressions involving operators as (e.g.)

             ARG1 + ARG2

     and writes control statements as (e.g.)

             while (EXPR) { STATEMENT1; STATEMENT2; ... }

     Lisp equivalents of the latter two would be

             (+ ARG1 ARG2 ...)

     and

             (while EXPR STATEMENT1 STATEMENT2 ...)

  2. Lisp is a safe language.  Assuming there are no bugs in the Lisp
     interpreter/compiler, it is impossible to write a program that
     "core dumps" or otherwise causes the machine to execute an illegal
     instruction.  This is very different from C, where perhaps the most
     common outcome of a bug is exactly such a crash.  A corollary of
     this is that the C operation of casting a pointer is impossible
     (and unnecessary) in Lisp, and that it is impossible to access
     memory outside the bounds of an array.

  3. Programs and data are written in the same form.  The
     parenthesis-enclosing form described above for statements is the
     same form used for the most common data type in Lisp, the list.
     Thus, it is possible to represent any Lisp program using Lisp data
     types, and for one program to construct Lisp statements and then
     dynamically "evaluate" them, or cause them to execute.

  4. All objects are "dynamically typed".  This means that part of every
     object is an indication of what type it is.  A Lisp program can
     manipulate an object without knowing what type it is, and can
     query an object to determine its type.  This means that,
     correspondingly, variables and function parameters can hold
     objects of any type and are not normally declared as being of any
     particular type.  This is opposed to the "static typing" of C,
     where variables can hold exactly one type of object and must be
     declared as such, and objects do not contain an indication of
     their type because it's implicit in the variables they are stored
     in.  It is possible in C to have a variable hold different types
     of objects (e.g. through the use of `void *' pointers or
     variable-argument functions), but the type information must then be
     passed explicitly in some other fashion, leading to additional
     program complexity.

  5. Allocated memory is automatically reclaimed when it is no longer
     in use.  This operation is called "garbage collection" and
     involves looking through all variables to see what memory is being
     pointed to, and reclaiming any memory that is not pointed to and
     is thus "inaccessible" and out of use.  This is as opposed to C,
     in which allocated memory must be explicitly reclaimed using
     `free()'.  If you simply drop all pointers to memory without
     freeing it, it becomes "leaked" memory that still takes up space.
     Over a long period of time, this can cause your program to grow
     and grow until it runs out of memory.

  6. Lisp has built-in facilities for handling errors and exceptions.
     In C, when an error occurs, usually either the program exits
     entirely or the routine in which the error occurs returns a value
     indicating this.  If an error occurs in a deeply-nested routine,
     then every routine currently called must unwind itself normally
     and return an error value back up to the next routine.  This means
     that every routine must explicitly check for an error in all the
     routines it calls; if it does not do so, unexpected and often
     random behavior results.  This is an extremely common source of
     bugs in C programs.  An alternative would be to do a non-local
     exit using `longjmp()', but that is often very dangerous because
     the routines that were exited past had no opportunity to clean up
     after themselves and may leave things in an inconsistent state,
     causing a crash shortly afterwards.

     Lisp provides mechanisms to make such non-local exits safe.  When
     an error occurs, a routine simply signals that an error of a
     particular class has occurred, and a non-local exit takes place.
     Any routine can trap errors occurring in routines it calls by
     registering an error handler for some or all classes of errors.
     (If no handler is registered, a default handler, generally
     installed by the top-level event loop, is executed; this prints
     out the error and continues.) Routines can also specify cleanup
     code (called an "unwind-protect") that will be called when control
     exits from a block of code, no matter how that exit occurs--i.e.
     even if a function deeply nested below it causes a non-local exit
     back to the top level.

     Note that this facility has appeared in some recent vintages of C,
     in particular Visual C++ and other PC compilers written for the
     Microsoft Win32 API.

  7. In Emacs Lisp, local variables are "dynamically scoped".  This
     means that if you declare a local variable in a particular
     function, and then call another function, that subfunction can
     "see" the local variable you declared.  This is actually
     considered a bug in Emacs Lisp and in all other early dialects of
     Lisp, and was corrected in Common Lisp. (In Common Lisp, you can
     still declare dynamically scoped variables if you want to--they
     are sometimes useful--but variables by default are "lexically
     scoped" as in C.)

   For those familiar with Lisp, Emacs Lisp is modelled after MacLisp,
an early dialect of Lisp developed at MIT (no relation to the Macintosh
computer).  There is a Common Lisp compatibility package available for
Emacs that provides many of the features of Common Lisp.

   The Java language is derived in many ways from C, and shares a
similar syntax, but has the following features in common with Lisp (and
different from C):

  1. Java is a safe language, like Lisp.

  2. Java provides garbage collection, like Lisp.

  3. Java has built-in facilities for handling errors and exceptions,
     like Lisp.

  4. Java has a type system that combines the best advantages of both
     static and dynamic typing.  Objects (except very simple types) are
     explicitly marked with their type, as in dynamic typing; but there
     is a hierarchy of types and functions are declared to accept only
     certain types, thus providing the increased compile-time
     error-checking of static typing.

   The Java language also has some negative attributes:

  1. Java uses the edit/compile/run model of software development.  This
     makes it hard to use interactively.  For example, to use Java like
     `bc' it is necessary to write a special purpose, albeit tiny,
     application.  In Emacs Lisp, a calculator comes built-in without
     any effort - one can always just type an expression in the
     `*scratch*' buffer.

  2. Java tries too hard to enforce, not merely enable, portability,
     making ordinary access to standard OS facilities painful.  Java
     has an "agenda".  I think this is why `chdir' is not part of
     standard Java, which is inexcusable.

   Unfortunately, there is no perfect language.  Static typing allows a
compiler to catch programmer errors and produce more efficient code, but
makes programming more tedious and less fun.  For the foreseeable
future, an Ideal Editing and Programming Environment (and that is what
XEmacs aspires to) will be programmable in multiple languages: high
level ones like Lisp for user customization and prototyping, and lower
level ones for infrastructure and industrial strength applications.  If
I had my way, XEmacs would be friendly towards the Python, Scheme, C++,
ML, etc... communities.  But there are serious technical difficulties to
achieving that goal.

   The word "application" in the previous paragraph was used
intentionally.  XEmacs implements an API for programs written in Lisp
that makes it a full-fledged application platform, very much like an OS
inside the real OS.


File: internals.info,  Node: XEmacs from the Perspective of Building,  Next: Build-Time Dependencies,  Prev: The Lisp Language,  Up: Top

7 XEmacs from the Perspective of Building
*****************************************

The heart of XEmacs is the Lisp environment, which is written in C.
This is contained in the `src/' subdirectory.  Underneath `src/' are
two subdirectories of header files: `s/' (header files for particular
operating systems) and `m/' (header files for particular machine
types).  In practice the distinction between the two types of header
files is blurred.  These header files define or undefine certain
preprocessor constants and macros to indicate particular
characteristics of the associated machine or operating system.  As part
of the configure process, one `s/' file and one `m/' file is identified
for the particular environment in which XEmacs is being built.

   XEmacs also contains a great deal of Lisp code.  This implements the
operations that make XEmacs useful as an editor as well as just a Lisp
environment, and also contains many add-on packages that allow XEmacs to
browse directories, act as a mail and Usenet news reader, compile Lisp
code, etc.  There is actually more Lisp code than C code associated with
XEmacs, but much of the Lisp code is peripheral to the actual operation
of the editor.  The Lisp code all lies in subdirectories underneath the
`lisp/' directory.

   The `lwlib/' directory contains C code that implements a generalized
interface onto different X widget toolkits and also implements some
widgets of its own that behave like Motif widgets but are faster, free,
and in some cases more powerful.  The code in this directory compiles
into a library and is mostly independent from XEmacs.

   The `etc/' directory contains various data files associated with
XEmacs.  Some of them are actually read by XEmacs at startup; others
merely contain useful information of various sorts.

   The `lib-src/' directory contains C code for various auxiliary
programs that are used in connection with XEmacs.  Some of them are used
during the build process; others are used to perform certain functions
that cannot conveniently be placed in the XEmacs executable (e.g. the
`movemail' program for fetching mail out of `/var/spool/mail', which
must be setgid to `mail' on many systems; and the `gnuclient' program,
which allows an external script to communicate with a running XEmacs
process).

   The `man/' directory contains the sources for the XEmacs
documentation.  It is mostly in a form called Texinfo, which can be
converted into either a printed document (by passing it through TeX) or
into on-line documentation called "info files".

   The `info/' directory contains the results of formatting the XEmacs
documentation as "info files", for on-line use.  These files are used
when you enter the Info system using `C-h i' or through the Help menu.

   The `dynodump/' directory contains auxiliary code used to build
XEmacs on Solaris platforms.

   The other directories contain various miscellaneous code and
information that is not normally used or needed.

   The first step of building involves running the `configure' program
and passing it various parameters to specify any optional features you
want and compiler arguments and such, as described in the `INSTALL'
file.  (You may optionally run `autoconf' first to update the
`configure' script.  *Note Modules for Build Configuration::.)  This
determines what the build environment is, chooses the appropriate `s/'
and `m/' file, and runs a series of tests to determine many details
about your environment, such as which library functions are available
and exactly how they work.  Running these tests allows XEmacs to be
compiled on a much wider variety of platforms than those that the
XEmacs developers happen to be familiar with, including various sorts
of hybrid platforms.  This is especially important now that many
operating systems give you a great deal of control over exactly what
features you want installed, and allow for easy upgrading of parts of a
system without upgrading the rest.  It would be impossible to
pre-determine and pre-specify the information for all possible
configurations.

   Thus, the `s/' and `m/' files are basically _evil_, since they
contain platform-specific hard-coded information.  XEmacs is moving in
the direction of having all system-specific information be determined
dynamically by `configure'.  Perhaps someday we can `rm -rf src/s
src/m'.

   `configure' also parses the version information from `version.sh'
and adds it to `config.h' as C preprocessor macros.  These macros in
turn are used to initialize some Lisp variables, such as
`emacs-version'.  *Note The version.sh Script::.

   When configure is done running, it generates `Makefile's and
`GNUmakefile's and the file `src/config.h' (which describes the
features of your system) from template files.  You then run `make',
which compiles the auxiliary code and programs in `lib-src/' and
`lwlib/' and the main XEmacs executable in `src/'.  The result of
compiling and linking is an executable called `temacs', which is _not_
the final XEmacs executable.  `temacs' by itself is not intended to
function as an editor or even display any windows on the screen, and if
you simply run it, it will exit immediately.  The `Makefile' runs
`temacs' with certain options that cause it to initialize itself, read
in a number of basic Lisp files, and then dump itself out into a new
executable called `xemacs'.  This new executable has been
pre-initialized and contains pre-digested Lisp code that is necessary
for the editor to function (this includes most basic editing functions,
e.g. `kill-line', that can be defined in terms of other Lisp
primitives; some initialization code that is called when certain
objects, such as frames, are created; and all of the standard
keybindings and code for the actions they result in).  This executable,
`xemacs', is the executable that you run to use the XEmacs editor.

   Although `temacs' is not intended to be run as an editor, it can, by
using the incantation `temacs -batch -l loadup.el run-temacs'.  This is
useful when the dumping procedure described above is broken, or when
using certain program debugging tools such as Purify.  These tools get
mighty confused by the tricks played by the XEmacs build process, such
as allocating memory in one process, and freeing it in the next.


File: internals.info,  Node: Build-Time Dependencies,  Next: The Modules of XEmacs,  Prev: XEmacs from the Perspective of Building,  Up: Top

8 Build-Time Dependencies
*************************

This is a collection of random notes on build-time dependencies as of
about XEmacs 21.5.11.  Of course we use `make' to manage most
dependencies, especially for the C code.  The main thing here is for the
Release Engineer to run the `src/make-src-depend' script every so
often, at least at every release.

   However, since most of XEmacs is written in Lisp, and we compile and
preload the Lisp for efficiency, managing Lisp compilation using `make'
would imply running XEmacs hundreds of times.  This would make the
build process unbearably long.  Thus those processes that require
running the same Lisp programs on many files are managed using Lisp
driver functions rather than `make'.  The situation is further
complicated by the fact that documentation strings are kept in an
external database, and referenced in the dumped XEmacs by file offset.
Finally, the Lisp files are processed to collect autoloaded function
information and customize dependencies, which are then written into
generated Lisp files.

   About this, Ben sez:

       1. Redumping depends on up-to-date dumped `.elc' files and `DOC'
          but not directly on auto-autoloads.

       2. Rebuilding dumped `.elc' files depends on auto-autoloads being
          up-to-date.

       3. Building the `DOC' file depends on up-to-date dumped `.elc'
          files but not directly on auto-autoloads.

       4. Recompiling anything depends on `bytecomp.elc' and
          `byte-optimize.elc' being up-to-date.

     Put these together and you'll see it's perfectly acceptable to
     build auto-autoloads *after* dumping if no `.elc' files are
     out-of-date.

   These Lisp driver programs typically run from temacs, not a dumped
XEmacs.  The simplest (but time-consuming) way to achieve a sane
environment for running Lisp is to load `loadup.el' or `loadup-el.el'.
(The latter is used to avoid loading possibly out-of-date compiled Lisp
files.)  If this is not done, you have to construct the environment
yourself.  See `dumped-lisp.el' to see how it is done in the dumped
XEmacs.

   One potential gotcha is that very early customizations are now
handled by adding the definitions to the special variable
`custom-declare-variable-list', defined in `subr.el'.  If you use any
higher-level functionality that might load `custom.el', but you do not
need `subr.el', you should `defvar' `custom-declare-variable-list' to
prevent the `void-variable' error.  (Currently this is only needed for
`make-docfile.el'.)


File: internals.info,  Node: The Modules of XEmacs,  Next: The Build Configuration System,  Prev: Build-Time Dependencies,  Up: Top

9 The Modules of XEmacs
***********************

* Menu:

* A Summary of the Various XEmacs Modules::
* Modules for Building XEmacs::
* Low-Level Modules::
* Basic Lisp Modules::
* Modules for Standard Editing Operations::
* Modules for Interfacing with the File System::
* Modules for Other Aspects of the Lisp Interpreter and Object System::
* Modules for Interfacing with the Operating System::


File: internals.info,  Node: A Summary of the Various XEmacs Modules,  Next: Modules for Building XEmacs,  Prev: The Modules of XEmacs,  Up: The Modules of XEmacs

9.1 A Summary of the Various XEmacs Modules
===========================================

The following is a list of the sections describing the various modules
(i.e. files) that implement XEmacs.  Some of them are in this chapter;
some of them are attached to the chapters describing the modules in
question.

   * *Note Modules for Build Configuration::.

   * *Note Modules for Compiling XEmacs::.

   * *Note Modules for Preloading Lisp::.

   * *Note Low-Level Modules::.

   * *Note Basic Lisp Modules::.

   * *Note Modules for Standard Editing Operations::.

   * *Note Editor-Level Control Flow Modules::.

   * *Note Modules for the Basic Displayable Lisp Objects::.

   * *Note Modules for other Display-Related Lisp Objects::.

   * *Note Modules for the Redisplay Mechanism::.

   * *Note Modules for Interfacing with the File System::.

   * *Note Modules for Other Aspects of the Lisp Interpreter and Object
     System::.

   * *Note Modules for Interfacing with the Operating System::.

   * *Note Modules for Interfacing with MS Windows::.

   * *Note Modules for Interfacing with X Windows::.

   * *Note Modules for Internationalization::.

   * *Note Modules for Regression Testing::.

   The following table contains cross-references from each module in
XEmacs 21.5 to the section (if any) describing it.

`Emacs.ad.h'                *Note Modules for Interfacing with X Windows::.
`EmacsFrame.c'              *Note Modules for Interfacing with X Windows::.
`EmacsFrame.h'              *Note Modules for Interfacing with X Windows::.
`EmacsFrameP.h'             *Note Modules for Interfacing with X Windows::.
`EmacsManager.c'            *Note Modules for Interfacing with X Windows::.
`EmacsManager.h'            *Note Modules for Interfacing with X Windows::.
`EmacsManagerP.h'           *Note Modules for Interfacing with X Windows::.
`EmacsShell-sub.c'          *Note Modules for Interfacing with X Windows::.
`EmacsShell.c'              *Note Modules for Interfacing with X Windows::.
`EmacsShell.h'              *Note Modules for Interfacing with X Windows::.
`EmacsShellP.h'             *Note Modules for Interfacing with X Windows::.
`ExternalClient-Xlib.c'     *Note Modules for Interfacing with X Windows::.
`ExternalClient.c'          *Note Modules for Interfacing with X Windows::.
`ExternalClient.h'          *Note Modules for Interfacing with X Windows::.
`ExternalClientP.h'         *Note Modules for Interfacing with X Windows::.
`ExternalShell.c'           *Note Modules for Interfacing with X Windows::.
`ExternalShell.h'           *Note Modules for Interfacing with X Windows::.
`ExternalShellP.h'          *Note Modules for Interfacing with X Windows::.
`Makefile.in.in'            
`abbrev.c'                  *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`alloc.c'                   *Note Basic Lisp Modules::.
`alloca.c'                  *Note Low-Level Modules::.
`alloca.s'                  
`backtrace.h'               *Note Basic Lisp Modules::.
`balloon-x.c'               
`balloon_help.c'            
`balloon_help.h'            
`base64-tests.el'           *Note Modules for Regression Testing::.
`bitmaps.h'                 *Note Modules for other Display-Related Lisp Objects::.
`blocktype.c'               *Note Low-Level Modules::.
`blocktype.h'               *Note Low-Level Modules::.
`broken-sun.h'              *Note Modules for Interfacing with the Operating System::.
`buffer.c'                  *Note Modules for Standard Editing Operations::.
`buffer.h'                  *Note Modules for Standard Editing Operations::.
`bufslots.h'                *Note Modules for Standard Editing Operations::.
`byte-compiler-tests.el'    *Note Modules for Regression Testing::.
`bytecode.c'                *Note Basic Lisp Modules::.
`bytecode.h'                *Note Basic Lisp Modules::.
`c-tests.el'                *Note Modules for Regression Testing::.
`callint.c'                 *Note Modules for Standard Editing Operations::.
`case-tests.el'             *Note Modules for Regression Testing::.
`casefiddle.c'              *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`casetab.c'                 *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`casetab.h'                 
`ccl-tests.el'              *Note Modules for Regression Testing::.
`charset.h'                 
`chartab.c'                 *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`chartab.h'                 *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`cm.c'                      *Note Modules for the Redisplay Mechanism::.
`cm.h'                      *Note Modules for the Redisplay Mechanism::.
`cmdloop.c'                 *Note Editor-Level Control Flow Modules::.
`cmds.c'                    *Note Modules for Standard Editing Operations::.
`coding-system-slots.h'     
`commands.h'                *Note Modules for Standard Editing Operations::.
`compiler.h'                
`config.h.in'               
`config.h'                  *Note Low-Level Modules::.
`conslots.h'                
`console-gtk-impl.h'        
`console-gtk.c'             
`console-gtk.h'             
`console-impl.h'            
`console-msw-impl.h'        
`console-msw.c'             *Note Modules for the Basic Displayable Lisp Objects::.
`console-msw.h'             *Note Modules for the Basic Displayable Lisp Objects::.
`console-stream-impl.h'     
`console-stream.c'          *Note Modules for the Basic Displayable Lisp Objects::.
`console-stream.h'          *Note Modules for the Basic Displayable Lisp Objects::.
`console-tty-impl.h'        
`console-tty.c'             *Note Modules for the Basic Displayable Lisp Objects::.
`console-tty.h'             *Note Modules for the Basic Displayable Lisp Objects::.
`console-x-impl.h'          
`console-x.c'               *Note Modules for the Basic Displayable Lisp Objects::.
`console-x.h'               *Note Modules for the Basic Displayable Lisp Objects::.
`console.c'                 *Note Modules for the Basic Displayable Lisp Objects::.
`console.h'                 *Note Modules for the Basic Displayable Lisp Objects::.
`data.c'                    *Note Basic Lisp Modules::.
`database-tests.el'         *Note Modules for Regression Testing::.
`database.c'                
`database.h'                
`debug.c'                   *Note Low-Level Modules::.
`debug.h'                   *Note Low-Level Modules::.
`depend'                    
`device-gtk.c'              
`device-impl.h'             
`device-msw.c'              *Note Modules for the Basic Displayable Lisp Objects::.
`device-tty.c'              *Note Modules for the Basic Displayable Lisp Objects::.
`device-x.c'                *Note Modules for the Basic Displayable Lisp Objects::.
`device.c'                  *Note Modules for the Basic Displayable Lisp Objects::.
`device.h'                  *Note Modules for the Basic Displayable Lisp Objects::.
`devslots.h'                
`dgif_lib.c'                *Note Modules for other Display-Related Lisp Objects::.
`dialog-gtk.c'              
`dialog-msw.c'              
`dialog-x.c'                
`dialog.c'                  
`dired-msw.c'               
`dired.c'                   *Note Modules for Interfacing with the File System::.
`doc.c'                     *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`doprnt.c'                  *Note Modules for Standard Editing Operations::.
`dragdrop.c'                
`dragdrop.h'                
`dump-data.c'               
`dump-data.h'               
`dump-id.c'                 
`dumper.c'                  
`dumper.h'                  
`dynarr.c'                  *Note Low-Level Modules::.
`ecrt0.c'                   *Note Low-Level Modules::.
`editfns.c'                 *Note Modules for Standard Editing Operations::.
`elhash.c'                  *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`elhash.h'                  *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`emacs-marshals.c'          
`emacs-new.c.old'           
`emacs-widget-accessors.c'  
`emacs.c'                   *Note Low-Level Modules::.
`emodules.c'                
`emodules.h'                
`esd.c'                     
`eval.c'                    *Note Basic Lisp Modules::.
`event-Xt.c'                *Note Editor-Level Control Flow Modules::.
`event-gtk.c'               
`event-gtk.h'               
`event-msw.c'               *Note Editor-Level Control Flow Modules::.
`event-stream.c'            *Note Editor-Level Control Flow Modules::.
`event-tty.c'               *Note Editor-Level Control Flow Modules::.
`event-unixoid.c'           
`event-xlike-inc.c'         
`events-mod.h'              *Note Editor-Level Control Flow Modules::.
`events.c'                  *Note Editor-Level Control Flow Modules::.
`events.h'                  *Note Editor-Level Control Flow Modules::.
`extent-tests.el'           *Note Modules for Regression Testing::.
`extents-impl.h'            
`extents.c'                 *Note Modules for Standard Editing Operations::.
`extents.h'                 *Note Modules for Standard Editing Operations::.
`extw-Xlib.c'               *Note Modules for Interfacing with X Windows::.
`extw-Xlib.h'               *Note Modules for Interfacing with X Windows::.
`extw-Xt.c'                 *Note Modules for Interfacing with X Windows::.
`extw-Xt.h'                 *Note Modules for Interfacing with X Windows::.
`faces.c'                   *Note Modules for other Display-Related Lisp Objects::.
`faces.h'                   *Note Modules for other Display-Related Lisp Objects::.
`file-coding.c'             *Note Modules for Internationalization::.
`file-coding.h'             *Note Modules for Internationalization::.
`fileio.c'                  *Note Modules for Interfacing with the File System::.
`filelock.c'                *Note Modules for Interfacing with the File System::.
`filemode.c'                *Note Modules for Interfacing with the File System::.
`floatfns.c'                *Note Basic Lisp Modules::.
`fns.c'                     *Note Basic Lisp Modules::.
`font-lock.c'               *Note Modules for other Display-Related Lisp Objects::.
`frame-gtk.c'               
`frame-impl.h'              
`frame-msw.c'               *Note Modules for the Basic Displayable Lisp Objects::.
`frame-tty.c'               *Note Modules for the Basic Displayable Lisp Objects::.
`frame-x.c'                 *Note Modules for the Basic Displayable Lisp Objects::.
`frame.c'                   *Note Modules for the Basic Displayable Lisp Objects::.
`frame.diff'                
`frame.h'                   *Note Modules for the Basic Displayable Lisp Objects::.
`frameslots.h'              
`free-hook.c'               *Note Low-Level Modules::.
`gccache-gtk.c'             
`gccache-gtk.h'             
`general-slots.h'           
`general.c'                 *Note Basic Lisp Modules::.
`getloadavg.c'              *Note Modules for Interfacing with the Operating System::.
`getpagesize.h'             *Note Low-Level Modules::.
`gif_err.c'                 *Note Modules for other Display-Related Lisp Objects::.
`gif_io.c'                  
`gif_lib.h'                 *Note Modules for other Display-Related Lisp Objects::.
`gifalloc.c'                *Note Modules for other Display-Related Lisp Objects::.
`gifrlib.h'                 
`glade.c'                   
`glyphs-eimage.c'           *Note Modules for other Display-Related Lisp Objects::.
`glyphs-gtk.c'              
`glyphs-gtk.h'              
`glyphs-msw.c'              *Note Modules for other Display-Related Lisp Objects::.
`glyphs-msw.h'              *Note Modules for other Display-Related Lisp Objects::.
`glyphs-shared.c'           
`glyphs-widget.c'           *Note Modules for other Display-Related Lisp Objects::.
`glyphs-x.c'                *Note Modules for other Display-Related Lisp Objects::.
`glyphs-x.h'                *Note Modules for other Display-Related Lisp Objects::.
`glyphs.c'                  *Note Modules for other Display-Related Lisp Objects::.
`glyphs.h'                  *Note Modules for other Display-Related Lisp Objects::.
`gmalloc.c'                 *Note Low-Level Modules::.
`gpmevent.c'                *Note Editor-Level Control Flow Modules::.
`gpmevent.h'                *Note Editor-Level Control Flow Modules::.
`gtk-glue.c'                
`gtk-xemacs.c'              
`gtk-xemacs.h'              
`gui-gtk.c'                 
`gui-msw.c'                 
`gui-x.c'                   
`gui.c'                     
`gui.h'                     
`gutter.c'                  
`gutter.h'                  
`hash-table-tests.el'       *Note Modules for Regression Testing::.
`hash.c'                    *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`hash.h'                    *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`hftctl.c'                  *Note Modules for Interfacing with the Operating System::.
`hpplay.c'                  *Note Modules for Interfacing with the Operating System::.
`imgproc.c'                 
`imgproc.h'                 
`indent.c'                  *Note Modules for the Redisplay Mechanism::.
`inline.c'                  *Note Low-Level Modules::.
`input-method-motif.c'      
`input-method-xlib.c'       
`insdel.c'                  *Note Modules for Standard Editing Operations::.
`insdel.h'                  *Note Modules for Standard Editing Operations::.
`intl-auto-encap-win32.c'   
`intl-auto-encap-win32.h'   
`intl-encap-win32.c'        
`intl-win32.c'              
`intl-x.c'                  
`intl.c'                    *Note Modules for Internationalization::.
`iso-wide.h'                *Note Modules for Internationalization::.
`keymap.c'                  *Note Editor-Level Control Flow Modules::.
`keymap.h'                  *Note Editor-Level Control Flow Modules::.
`lastfile.c'                *Note Low-Level Modules::.
`libinterface.c'            
`libinterface.h'            
`libsst.c'                  *Note Modules for Interfacing with the Operating System::.
`libsst.h'                  *Note Modules for Interfacing with the Operating System::.
`libst.h'                   *Note Modules for Interfacing with the Operating System::.
`line-number.c'             
`line-number.h'             
`linuxplay.c'               *Note Modules for Interfacing with the Operating System::.
`lisp-disunion.h'           *Note Basic Lisp Modules::.
`lisp-tests.el'             *Note Modules for Regression Testing::.
`lisp-union.h'              *Note Basic Lisp Modules::.
`lisp.h'                    *Note Basic Lisp Modules::.
`lread.c'                   *Note Basic Lisp Modules::.
`lrecord.h'                 *Note Basic Lisp Modules::.
`lstream.c'                 *Note Modules for Interfacing with the File System::.
`lstream.h'                 *Note Modules for Interfacing with the File System::.
`macros.c'                  *Note Editor-Level Control Flow Modules::.
`macros.h'                  *Note Editor-Level Control Flow Modules::.
`make-src-depend'           
`malloc.c'                  *Note Low-Level Modules::.
`marker.c'                  *Note Modules for Standard Editing Operations::.
`md5-tests.el'              *Note Modules for Regression Testing::.
`md5.c'                     *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`mem-limits.h'              *Note Low-Level Modules::.
`menubar-gtk.c'             
`menubar-msw.c'             *Note Modules for other Display-Related Lisp Objects::.
`menubar-msw.h'             *Note Modules for other Display-Related Lisp Objects::.
`menubar-x.c'               *Note Modules for other Display-Related Lisp Objects::.
`menubar.c'                 *Note Modules for other Display-Related Lisp Objects::.
`menubar.h'                 *Note Modules for other Display-Related Lisp Objects::.
`minibuf.c'                 *Note Editor-Level Control Flow Modules::.
`miscplay.c'                
`miscplay.h'                
`mule-canna.c'              *Note Modules for Internationalization::.
`mule-ccl.c'                *Note Modules for Internationalization::.
`mule-ccl.h'                
`mule-charset.c'            *Note Modules for Internationalization::.
`mule-charset.h'            *Note Modules for Internationalization::.
`mule-coding.c'             *Note Modules for Internationalization::.
`mule-mcpath.c'             *Note Modules for Internationalization::.
`mule-mcpath.h'             *Note Modules for Internationalization::.
`mule-tests.el'             *Note Modules for Regression Testing::.
`mule-wnnfns.c'             *Note Modules for Internationalization::.
`mule.c'                    *Note Modules for Internationalization::.
`nas.c'                     *Note Modules for Interfacing with the Operating System::.
`native-gtk-toolbar.c'      
`ndir.h'                    *Note Modules for Interfacing with the File System::.
`nsselect.m'                
`nt.c'                      
`ntheap.c'                  
`ntplay.c'                  
`number-gmp.c'              
`number-gmp.h'              
`number-mp.c'               
`number-mp.h'               
`number.c'                  
`number.h'                  
`objects-gtk-impl.h'        
`objects-gtk.c'             
`objects-gtk.h'             
`objects-impl.h'            
`objects-msw-impl.h'        
`objects-msw.c'             *Note Modules for other Display-Related Lisp Objects::.
`objects-msw.h'             *Note Modules for other Display-Related Lisp Objects::.
`objects-tty-impl.h'        
`objects-tty.c'             *Note Modules for other Display-Related Lisp Objects::.
`objects-tty.h'             *Note Modules for other Display-Related Lisp Objects::.
`objects-x-impl.h'          
`objects-x.c'               *Note Modules for other Display-Related Lisp Objects::.
`objects-x.h'               *Note Modules for other Display-Related Lisp Objects::.
`objects.c'                 *Note Modules for other Display-Related Lisp Objects::.
`objects.h'                 *Note Modules for other Display-Related Lisp Objects::.
`offix-cursors.h'           
`offix-types.h'             
`offix.c'                   
`offix.h'                   
`opaque.c'                  *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`opaque.h'                  *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`paths.h.in'                
`paths.h'                   *Note Low-Level Modules::.
`ppc.ldscript'              
`pre-crt0.c'                *Note Low-Level Modules::.
`print.c'                   *Note Basic Lisp Modules::.
`process-nt.c'              
`process-slots.h'           
`process-unix.c'            
`process.c'                 *Note Modules for Interfacing with the Operating System::.
`process.el'                *Note Modules for Interfacing with the Operating System::.
`process.h'                 *Note Modules for Interfacing with the Operating System::.
`procimpl.h'                
`profile.c.orig'            
`profile.c.rej'             
`profile.c'                 
`profile.h'                 
`ralloc.c'                  *Note Low-Level Modules::.
`rangetab.c'                *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`rangetab.h'                
`realpath.c'                *Note Modules for Interfacing with the File System::.
`redisplay-gtk.c'           
`redisplay-msw.c'           *Note Modules for the Redisplay Mechanism::.
`redisplay-output.c'        *Note Modules for the Redisplay Mechanism::.
`redisplay-tty.c'           *Note Modules for the Redisplay Mechanism::.
`redisplay-x.c'             *Note Modules for the Redisplay Mechanism::.
`redisplay.c'               *Note Modules for the Redisplay Mechanism::.
`redisplay.h'               *Note Modules for the Redisplay Mechanism::.
`regex.c'                   *Note Modules for Standard Editing Operations::.
`regex.h'                   *Note Modules for Standard Editing Operations::.
`regexp-tests.el'           *Note Modules for Regression Testing::.
`scrollbar-gtk.c'           
`scrollbar-gtk.h'           
`scrollbar-msw.c'           *Note Modules for other Display-Related Lisp Objects::.
`scrollbar-msw.h'           *Note Modules for other Display-Related Lisp Objects::.
`scrollbar-x.c'             *Note Modules for other Display-Related Lisp Objects::.
`scrollbar-x.h'             *Note Modules for other Display-Related Lisp Objects::.
`scrollbar.c'               *Note Modules for other Display-Related Lisp Objects::.
`scrollbar.h'               *Note Modules for other Display-Related Lisp Objects::.
`search.c'                  *Note Modules for Standard Editing Operations::.
`select-common.h'           
`select-gtk.c'              
`select-msw.c'              *Note Modules for Interfacing with X Windows::.
`select-x.c'                *Note Modules for Interfacing with X Windows::.
`select.c'                  *Note Modules for Interfacing with X Windows::.
`select.h'                  *Note Modules for Interfacing with X Windows::.
`sgiplay.c'                 *Note Modules for Interfacing with the Operating System::.
`sheap.c'                   
`signal.c'                  *Note Low-Level Modules::.
`sound.c'                   *Note Modules for Interfacing with the Operating System::.
`sound.h'                   
`specifier.c'               *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`specifier.h'               *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`src-headers'               
`strcat.c'                  
`strcmp.c'                  *Note Modules for Interfacing with the Operating System::.
`strcpy.c'                  *Note Modules for Interfacing with the Operating System::.
`strftime.c'                
`sunOS-fix.c'               *Note Modules for Interfacing with the Operating System::.
`sunplay.c'                 *Note Modules for Interfacing with the Operating System::.
`sunpro.c'                  *Note Modules for Interfacing with the Operating System::.
`symbol-tests.el'           *Note Modules for Regression Testing::.
`symbols.c'                 *Note Basic Lisp Modules::.
`symeval.h'                 *Note Basic Lisp Modules::.
`symsinit.h'                *Note Basic Lisp Modules::.
`syntax-tests.el'           *Note Modules for Regression Testing::.
`syntax.c'                  *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`syntax.h'                  *Note Modules for Other Aspects of the Lisp Interpreter and Object System::.
`sysdep.c'                  *Note Modules for Interfacing with the Operating System::.
`sysdep.h'                  *Note Modules for Interfacing with the Operating System::.
`sysdir.h'                  *Note Modules for Interfacing with the Operating System::.
`sysdll.c'                  
`sysdll.h'                  
`sysfile.h'                 *Note Modules for Interfacing with the Operating System::.
`sysfloat.h'                *Note Modules for Interfacing with the Operating System::.
`sysproc.h'                 *Note Modules for Interfacing with the Operating System::.
`syspwd.h'                  *Note Modules for Interfacing with the Operating System::.
`syssignal.h'               *Note Modules for Interfacing with the Operating System::.
`systime.h'                 *Note Modules for Interfacing with the Operating System::.
`systty.h'                  *Note Modules for Interfacing with the Operating System::.
`syswait.h'                 *Note Modules for Interfacing with the Operating System::.
`syswindows.h'              
`tag-tests.el'              *Note Modules for Regression Testing::.
`termcap.c'                 *Note Modules for the Redisplay Mechanism::.
`terminfo.c'                *Note Modules for the Redisplay Mechanism::.
`test-harness.el'           *Note Modules for Regression Testing::.
`tests.c'                   
`text.c'                    
`text.h'                    
`toolbar-common.c'          
`toolbar-common.h'          
`toolbar-gtk.c'             
`toolbar-msw.c'             *Note Modules for other Display-Related Lisp Objects::.
`toolbar-x.c'               *Note Modules for other Display-Related Lisp Objects::.
`toolbar.c'                 *Note Modules for other Display-Related Lisp Objects::.
`toolbar.h'                 *Note Modules for other Display-Related Lisp Objects::.
`tooltalk.c'                *Note Modules for Interfacing with the Operating System::.
`tooltalk.h'                *Note Modules for Interfacing with the Operating System::.
`tparam.c'                  *Note Modules for the Redisplay Mechanism::.
`ui-byhand.c'               
`ui-gtk.c'                  
`ui-gtk.h'                  
`undo.c'                    *Note Modules for Standard Editing Operations::.
`unexaix.c'                 *Note Low-Level Modules::.
`unexalpha.c'               *Note Low-Level Modules::.
`unexapollo.c'              *Note Low-Level Modules::.
`unexconvex.c'              *Note Low-Level Modules::.
`unexcw.c'                  
`unexec.c'                  *Note Low-Level Modules::.
`unexelf.c'                 *Note Low-Level Modules::.
`unexelfsgi.c'              *Note Low-Level Modules::.
`unexencap.c'               *Note Low-Level Modules::.
`unexenix.c'                *Note Low-Level Modules::.
`unexfreebsd.c'             *Note Low-Level Modules::.
`unexfx2800.c'              *Note Low-Level Modules::.
`unexhp9k3.c'               *Note Low-Level Modules::.
`unexhp9k800.c'             *Note Low-Level Modules::.
`unexmips.c'                *Note Low-Level Modules::.
`unexnext.c'                *Note Low-Level Modules::.
`unexnt.c'                  
`unexsni.c'                 
`unexsol2-6.c'              
`unexsol2.c'                *Note Low-Level Modules::.
`unexsunos4.c'              *Note Low-Level Modules::.
`unicode.c'                 
`universe.h'                *Note Low-Level Modules::.
`vm-limit.c'                *Note Low-Level Modules::.
`weak-tests.el'             *Note Modules for Regression Testing::.
`widget.c'                  
`win32.c'                   
`window-impl.h'             
`window.c'                  *Note Modules for the Basic Displayable Lisp Objects::.
`window.h'                  *Note Modules for the Basic Displayable Lisp Objects::.
`winslots.h'                
`xemacs.def.in.in'          
`xgccache.c'                *Note Modules for Interfacing with X Windows::.
`xgccache.h'                *Note Modules for Interfacing with X Windows::.
`xintrinsic.h'              *Note Modules for Interfacing with X Windows::.
`xintrinsicp.h'             *Note Modules for Interfacing with X Windows::.
`xmmanagerp.h'              *Note Modules for Interfacing with X Windows::.
`xmotif.h'                  
`xmprimitivep.h'            *Note Modules for Interfacing with X Windows::.
`xmu.c'                     *Note Modules for Interfacing with X Windows::.
`xmu.h'                     *Note Modules for Interfacing with X Windows::.


File: internals.info,  Node: Modules for Building XEmacs,  Next: Low-Level Modules,  Prev: A Summary of the Various XEmacs Modules,  Up: The Modules of XEmacs

9.2 Modules for Building XEmacs
===============================

* Menu:

* Modules for Build Configuration::
* Modules for Compiling XEmacs::
* Modules for Preloading Lisp::


File: internals.info,  Node: Modules for Build Configuration,  Next: Modules for Compiling XEmacs,  Prev: Modules for Building XEmacs,  Up: Modules for Building XEmacs

9.2.1 Modules for Build Configuration
-------------------------------------

     `configure'
     `config.h.in'
     `Makefile.in.in'
     `version.sh'

     `configure.ac'
     `configure.in'

   *Note The version.sh Script::.  *Note The configure Script::.


File: internals.info,  Node: Modules for Compiling XEmacs,  Next: Modules for Preloading Lisp,  Prev: Modules for Build Configuration,  Up: Modules for Building XEmacs

9.2.2 Modules for Compiling XEmacs
----------------------------------

*Please write this node!*  This node should contain descriptions of
files like the various Makefiles, and I guess cross-references to ellcc
etc.


File: internals.info,  Node: Modules for Preloading Lisp,  Prev: Modules for Compiling XEmacs,  Up: Modules for Building XEmacs

9.2.3 Modules for Preloading Lisp
---------------------------------

*Please write this node!*  This node should contain descriptions of
files like dumped-lisp.el (maybe that goes in Modules for Build
Configuration supra?), update-elcs.el, and so on.


File: internals.info,  Node: Low-Level Modules,  Next: Basic Lisp Modules,  Prev: Modules for Building XEmacs,  Up: The Modules of XEmacs

9.3 Low-Level Modules
=====================

     `version.sh'

   This is a Bourne shell script which sets version-related variables.
It is updated in the release process by the maintainer of each series or
branch, and may also be automatically updated.  *Note The version.sh
Script::.

     `config.h'

   This is automatically generated from `config.h.in' based on the
results of configure tests and user-selected optional features and
contains preprocessor definitions specifying the nature of the
environment in which XEmacs is being compiled.

     `paths.h'

   This is automatically generated from `paths.h.in' based on supplied
configure values, and allows for non-standard installed configurations
of the XEmacs directories.  It's currently broken, though.

     `emacs.c'
     `signal.c'

   `emacs.c' contains `main()' and other code that performs the most
basic environment initializations and handles shutting down the XEmacs
process (this includes `kill-emacs', the normal way that XEmacs is
exited; `dump-emacs', which is used during the build process to write
out the XEmacs executable; `run-emacs-from-temacs', which can be used
to start XEmacs directly when temacs has finished loading all the Lisp
code; and emergency code to handle crashes [XEmacs tries to auto-save
all files before it crashes]).

   Low-level code that directly interacts with the Unix signal
mechanism, however, is in `signal.c'.  Note that this code does not
handle system dependencies in interfacing to signals; that is handled
using the `syssignal.h' header file, described in section J below.

     `unexaix.c'
     `unexalpha.c'
     `unexapollo.c'
     `unexconvex.c'
     `unexec.c'
     `unexelf.c'
     `unexelfsgi.c'
     `unexencap.c'
     `unexenix.c'
     `unexfreebsd.c'
     `unexfx2800.c'
     `unexhp9k3.c'
     `unexhp9k800.c'
     `unexmips.c'
     `unexnext.c'
     `unexsol2.c'
     `unexsunos4.c'

   These modules contain code dumping out the XEmacs executable on
various different systems. (This process is highly machine-specific and
requires intimate knowledge of the executable format and the memory map
of the process.) Only one of these modules is actually used; this is
chosen by `configure'.

     `ecrt0.c'
     `lastfile.c'
     `pre-crt0.c'

   These modules are used in conjunction with the dump mechanism.  On
some systems, an alternative version of the C startup code (the actual
code that receives control from the operating system when the process is
started, and which calls `main()') is required so that the dumping
process works properly; `crt0.c' provides this.

   `pre-crt0.c' and `lastfile.c' should be the very first and very last
file linked, respectively. (Actually, this is not really true.
`lastfile.c' should be after all Emacs modules whose initialized data
should be made constant, and before all other Emacs files and all
libraries.  In particular, the allocation modules `gmalloc.c',
`alloca.c', etc. are normally placed past `lastfile.c', and all of the
files that implement Xt widget classes _must_ be placed after
`lastfile.c' because they contain various structures that must be
statically initialized and into which Xt writes at various times.)
`pre-crt0.c' and `lastfile.c' contain exported symbols that are used to
determine the start and end of XEmacs' initialized data space when
dumping.

     `inline.c'

   This module is used in connection with inline functions (available in
some compilers).  Often, inline functions need to have a corresponding
non-inline function that does the same thing.  This module is where they
reside.  It contains no actual code, but defines some special flags that
cause inline functions defined in header files to be rendered as actual
functions.  It then includes all header files that contain any inline
function definitions, so that each one gets a real function equivalent.

     `debug.c'
     `debug.h'

   These functions provide a system for doing internal consistency
checks during code development.  This system is not currently used;
instead the simpler `assert()' macro is used along with the various
checks provided by the `--error-check-*' configuration options.

     `universe.h'

   This is not currently used.


File: internals.info,  Node: Basic Lisp Modules,  Next: Modules for Standard Editing Operations,  Prev: Low-Level Modules,  Up: The Modules of XEmacs

9.4 Basic Lisp Modules
======================

     `lisp-disunion.h'
     `lisp-union.h'
     `lisp.h'
     `lrecord.h'
     `symsinit.h'

   These are the basic header files for all XEmacs modules.  Each module
includes `lisp.h', which brings the other header files in.  `lisp.h'
contains the definitions of the structures and extractor and
constructor macros for the basic Lisp objects and various other basic
definitions for the Lisp environment, as well as some general-purpose
definitions (e.g. `min()' and `max()').  `lisp.h' includes either
`lisp-disunion.h' or `lisp-union.h', depending on whether
`USE_UNION_TYPE' is defined.  These files define the typedef of the
Lisp object itself (as described above) and the low-level macros that
hide the actual implementation of the Lisp object.  All extractor and
constructor macros for particular types of Lisp objects are defined in
terms of these low-level macros.

   As a general rule, all typedefs should go into the typedefs section
of `lisp.h' rather than into a module-specific header file even if the
structure is defined elsewhere.  This allows function prototypes that
use the typedef to be placed into other header files.  Forward structure
declarations (i.e. a simple declaration like `struct foo;' where the
structure itself is defined elsewhere) should be placed into the
typedefs section as necessary.

   `lrecord.h' contains the basic structures and macros that implement
all record-type Lisp objects--i.e. all objects whose type is a field in
their C structure, which includes all objects except the few most basic
ones.

   `lisp.h' contains prototypes for most of the exported functions in
the various modules.  Lisp primitives defined using `DEFUN' that need
to be called by C code should be declared using `EXFUN'.  Other
function prototypes should be placed either into the appropriate
section of `lisp.h', or into a module-specific header file, depending
on how general-purpose the function is and whether it has
special-purpose argument types requiring definitions not in `lisp.h'.)
All initialization functions are prototyped in `symsinit.h'.

     `alloc.c'

   The large module `alloc.c' implements all of the basic allocation and
garbage collection for Lisp objects.  The most commonly used Lisp
objects are allocated in chunks, similar to the Blocktype data type
described above; others are allocated in individually `malloc()'ed
blocks.  This module provides the foundation on which all other aspects
of the Lisp environment sit, and is the first module initialized at
startup.

   Note that `alloc.c' provides a series of generic functions that are
not dependent on any particular object type, and interfaces to
particular types of objects using a standardized interface of
type-specific methods.  This scheme is a fundamental principle of
object-oriented programming and is heavily used throughout XEmacs.  The
great advantage of this is that it allows for a clean separation of
functionality into different modules--new classes of Lisp objects, new
event interfaces, new device types, new stream interfaces, etc. can be
added transparently without affecting code anywhere else in XEmacs.
Because the different subsystems are divided into general and specific
code, adding a new subtype within a subsystem will in general not
require changes to the generic subsystem code or affect any of the other
subtypes in the subsystem; this provides a great deal of robustness to
the XEmacs code.

     `eval.c'
     `backtrace.h'

   This module contains all of the functions to handle the flow of
control.  This includes the mechanisms of defining functions, calling
functions, traversing stack frames, and binding variables; the control
primitives and other special forms such as `while', `if', `eval',
`let', `and', `or', `progn', etc.; handling of non-local exits,
unwind-protects, and exception handlers; entering the debugger; methods
for the subr Lisp object type; etc.  It does _not_ include the `read'
function, the `print' function, or the handling of symbols and obarrays.

   `backtrace.h' contains some structures related to stack frames and
the flow of control.

     `lread.c'

   This module implements the Lisp reader and the `read' function,
which converts text into Lisp objects, according to the read syntax of
the objects, as described above.  This is similar to the parser that is
a part of all compilers.

     `print.c'

   This module implements the Lisp print mechanism and the `print'
function and related functions.  This is the inverse of the Lisp reader
- it converts Lisp objects to a printed, textual representation.
(Hopefully something that can be read back in using `read' to get an
equivalent object.)

     `general.c'
     `symbols.c'
     `symeval.h'

   `symbols.c' implements the handling of symbols, obarrays, and
retrieving the values of symbols.  Much of the code is devoted to
handling the special "symbol-value-magic" objects that define special
types of variables--this includes buffer-local variables, variable
aliases, variables that forward into C variables, etc.  This module is
initialized extremely early (right after `alloc.c'), because it is here
that the basic symbols `t' and `nil' are created, and those symbols are
used everywhere throughout XEmacs.

   `symeval.h' contains the definitions of symbol structures and the
`DEFVAR_LISP()' and related macros for declaring variables.

     `data.c'
     `floatfns.c'
     `fns.c'

   These modules implement the methods and standard Lisp primitives for
all the basic Lisp object types other than symbols (which are described
above).  `data.c' contains all the predicates (primitives that return
whether an object is of a particular type); the integer arithmetic
functions; and the basic accessor and mutator primitives for the various
object types.  `fns.c' contains all the standard predicates for working
with sequences (where, abstractly speaking, a sequence is an ordered set
of objects, and can be represented by a list, string, vector, or
bit-vector); it also contains `equal', perhaps on the grounds that bulk
of the operation of `equal' is comparing sequences.  `floatfns.c'
contains methods and primitives for floats and floating-point
arithmetic.

     `bytecode.c'
     `bytecode.h'

   `bytecode.c' implements the byte-code interpreter and
compiled-function objects, and `bytecode.h' contains associated
structures.  Note that the byte-code _compiler_ is written in Lisp.


File: internals.info,  Node: Modules for Standard Editing Operations,  Next: Modules for Interfacing with the File System,  Prev: Basic Lisp Modules,  Up: The Modules of XEmacs

9.5 Modules for Standard Editing Operations
===========================================

     `buffer.c'
     `buffer.h'
     `bufslots.h'

   `buffer.c' implements the "buffer" Lisp object type.  This includes
functions that create and destroy buffers; retrieve buffers by name or
by other properties; manipulate lists of buffers (remember that buffers
are permanent objects and stored in various ordered lists); retrieve or
change buffer properties; etc.  It also contains the definitions of all
the built-in buffer-local variables (which can be viewed as buffer
properties).  It does _not_ contain code to manipulate buffer-local
variables (that's in `symbols.c', described above); or code to
manipulate the text in a buffer.

   `buffer.h' defines the structures associated with a buffer and the
various macros for retrieving text from a buffer and special buffer
positions (e.g. `point', the default location for text insertion).  It
also contains macros for working with buffer positions and converting
between their representations as character offsets and as byte offsets
(under MULE, they are different, because characters can be multi-byte).
It is one of the largest header files.

   `bufslots.h' defines the fields in the buffer structure that
correspond to the built-in buffer-local variables.  It is its own
header file because it is included many times in `buffer.c', as a way
of iterating over all the built-in buffer-local variables.

     `insdel.c'
     `insdel.h'

   `insdel.c' contains low-level functions for inserting and deleting
text in a buffer, keeping track of changed regions for use by
redisplay, and calling any before-change and after-change functions
that may have been registered for the buffer.  It also contains the
actual functions that convert between byte offsets and character
offsets.

   `insdel.h' contains associated headers.

     `marker.c'

   This module implements the "marker" Lisp object type, which
conceptually is a pointer to a text position in a buffer that moves
around as text is inserted and deleted, so as to remain in the same
relative position.  This module doesn't actually move the markers around
- that's handled in `insdel.c'.  This module just creates them and
implements the primitives for working with them.  As markers are simple
objects, this does not entail much.

   Note that the standard arithmetic primitives (e.g. `+') accept
markers in place of integers and automatically substitute the value of
`marker-position' for the marker, i.e. an integer describing the
current buffer position of the marker.

     `extents.c'
     `extents.h'

   This module implements the "extent" Lisp object type, which is like
a marker that works over a range of text rather than a single position.
Extents are also much more complex and powerful than markers and have a
more efficient (and more algorithmically complex) implementation.  The
implementation is described in detail in comments in `extents.c'.

   The code in `extents.c' works closely with `insdel.c' so that
extents are properly moved around as text is inserted and deleted.
There is also code in `extents.c' that provides information needed by
the redisplay mechanism for efficient operation. (Remember that extents
can have display properties that affect [sometimes drastically, as in
the `invisible' property] the display of the text they cover.)

     `editfns.c'

   `editfns.c' contains the standard Lisp primitives for working with a
buffer's text, and calls the low-level functions in `insdel.c'.  It
also contains primitives for working with `point' (the default buffer
insertion location).

   `editfns.c' also contains functions for retrieving various
characteristics from the external environment: the current time, the
process ID of the running XEmacs process, the name of the user who ran
this XEmacs process, etc.  It's not clear why this code is in
`editfns.c'.

     `callint.c'
     `cmds.c'
     `commands.h'

   These modules implement the basic "interactive" commands, i.e.
user-callable functions.  Commands, as opposed to other functions, have
special ways of getting their parameters interactively (by querying the
user), as opposed to having them passed in a normal function
invocation.  Many commands are not really meant to be called from other
Lisp functions, because they modify global state in a way that's often
undesired as part of other Lisp functions.

   `callint.c' implements the mechanism for querying the user for
parameters and calling interactive commands.  The bulk of this module is
code that parses the interactive spec that is supplied with an
interactive command.

   `cmds.c' implements the basic, most commonly used editing commands:
commands to move around the current buffer and insert and delete
characters.  These commands are implemented using the Lisp primitives
defined in `editfns.c'.

   `commands.h' contains associated structure definitions and
prototypes.

     `regex.c'
     `regex.h'
     `search.c'

   `search.c' implements the Lisp primitives for searching for text in
a buffer, and some of the low-level algorithms for doing this.  In
particular, the fast fixed-string Boyer-Moore search algorithm is
implemented in `search.c'.  The low-level algorithms for doing
regular-expression searching, however, are implemented in `regex.c' and
`regex.h'.  These two modules are largely independent of XEmacs, and
are similar to (and based upon) the regular-expression routines used in
`grep' and other GNU utilities.

     `doprnt.c'

   `doprnt.c' implements formatted-string processing, similar to
`printf()' command in C.

     `undo.c'

   This module implements the undo mechanism for tracking buffer
changes.  Most of this could be implemented in Lisp.


File: internals.info,  Node: Modules for Interfacing with the File System,  Next: Modules for Other Aspects of the Lisp Interpreter and Object System,  Prev: Modules for Standard Editing Operations,  Up: The Modules of XEmacs

9.6 Modules for Interfacing with the File System
================================================

     `lstream.c'
     `lstream.h'

   These modules implement the "stream" Lisp object type.  This is an
internal-only Lisp object that implements a generic buffering stream.
The idea is to provide a uniform interface onto all sources and sinks of
data, including file descriptors, stdio streams, chunks of memory, Lisp
buffers, Lisp strings, etc.  That way, I/O functions can be written to
the stream interface and can transparently handle all possible sources
and sinks.  (For example, the `read' function can read data from a
file, a string, a buffer, or even a function that is called repeatedly
to return data, without worrying about where the data is coming from or
what-size chunks it is returned in.)

   Note that in the C code, streams are called "lstreams" (for "Lisp
streams") to distinguish them from other kinds of streams, e.g. stdio
streams and C++ I/O streams.

   Similar to other subsystems in XEmacs, lstreams are separated into
generic functions and a set of methods for the different types of
lstreams.  `lstream.c' provides implementations of many different types
of streams; others are provided, e.g., in `file-coding.c'.

     `fileio.c'

   This implements the basic primitives for interfacing with the file
system.  This includes primitives for reading files into buffers,
writing buffers into files, checking for the presence or accessibility
of files, canonicalizing file names, etc.  Note that these primitives
are usually not invoked directly by the user: There is a great deal of
higher-level Lisp code that implements the user commands such as
`find-file' and `save-buffer'.  This is similar to the distinction
between the lower-level primitives in `editfns.c' and the higher-level
user commands in `commands.c' and `simple.el'.

     `filelock.c'

   This file provides functions for detecting clashes between different
processes (e.g. XEmacs and some external process, or two different
XEmacs processes) modifying the same file.  (XEmacs can optionally use
the `lock/' subdirectory to provide a form of "locking" between
different XEmacs processes.)  This module is also used by the low-level
functions in `insdel.c' to ensure that, if the first modification is
being made to a buffer whose corresponding file has been externally
modified, the user is made aware of this so that the buffer can be
synched up with the external changes if necessary.

     `filemode.c'

   This file provides some miscellaneous functions that construct a
`rwxr-xr-x'-type permissions string (as might appear in an `ls'-style
directory listing) given the information returned by the `stat()'
system call.

     `dired.c'
     `ndir.h'

   These files implement the XEmacs interface to directory searching.
This includes a number of primitives for determining the files in a
directory and for doing filename completion. (Remember that generic
completion is handled by a different mechanism, in `minibuf.c'.)

   `ndir.h' is a header file used for the directory-searching emulation
functions provided in `sysdep.c' (see section J below), for systems
that don't provide any directory-searching functions. (On those
systems, directories can be read directly as files, and parsed.)

     `realpath.c'

   This file provides an implementation of the `realpath()' function
for expanding symbolic links, on systems that don't implement it or have
a broken implementation.


File: internals.info,  Node: Modules for Other Aspects of the Lisp Interpreter and Object System,  Next: Modules for Interfacing with the Operating System,  Prev: Modules for Interfacing with the File System,  Up: The Modules of XEmacs

9.7 Modules for Other Aspects of the Lisp Interpreter and Object System
=======================================================================

     `elhash.c'
     `elhash.h'
     `hash.c'
     `hash.h'

   These files provide two implementations of hash tables.  Files
`hash.c' and `hash.h' provide a generic C implementation of hash tables
which can stand independently of XEmacs.  Files `elhash.c' and
`elhash.h' provide a separate implementation of hash tables that can
store only Lisp objects, and knows about Lispy things like garbage
collection, and implement the "hash-table" Lisp object type.

     `specifier.c'
     `specifier.h'

   This module implements the "specifier" Lisp object type.  This is
primarily used for displayable properties, and allows for values that
are specific to a particular buffer, window, frame, device, or device
class, as well as a default value existing.  This is used, for example,
to control the height of the horizontal scrollbar or the appearance of
the `default', `bold', or other faces.  The specifier object consists
of a number of specifications, each of which maps from a buffer,
window, etc. to a value.  The function `specifier-instance' looks up a
value given a window (from which a buffer, frame, and device can be
derived).

     `chartab.c'
     `chartab.h'
     `casetab.c'

   `chartab.c' and `chartab.h' implement the "char table" Lisp object
type, which maps from characters or certain sorts of character ranges
to Lisp objects.  The implementation of this object type is optimized
for the internal representation of characters.  Char tables come in
different types, which affect the allowed object types to which a
character can be mapped and also dictate certain other properties of
the char table.

   `casetab.c' implements one sort of char table, the "case table",
which maps characters to other characters of possibly different case.
These are used by XEmacs to implement case-changing primitives and to
do case-insensitive searching.

     `syntax.c'
     `syntax.h'

   This module implements "syntax tables", another sort of char table
that maps characters into syntax classes that define the syntax of these
characters (e.g. a parenthesis belongs to a class of `open' characters
that have corresponding `close' characters and can be nested).  This
module also implements the Lisp "scanner", a set of primitives for
scanning over text based on syntax tables.  This is used, for example,
to find the matching parenthesis in a command such as `forward-sexp',
and by `font-lock.c' to locate quoted strings, comments, etc.

   Syntax codes are implemented as bitfields in an int.  Bits 0-6
contain the syntax code itself, bit 7 is a special prefix flag used for
Lisp, and bits 16-23 contain comment syntax flags.  From the Lisp
programmer's point of view, there are 11 flags: 2 styles X 2 characters
X {start, end} flags for two-character comment delimiters, 2 style
flags for one-character comment delimiters, and the prefix flag.

   Internally, however, the characters used in multi-character
delimiters will have non-comment-character syntax classes (_e.g._, the
`/' in C's `/*' comment-start delimiter has "punctuation" (here meaning
"operator-like") class in C modes).  Thus in a mixed comment style,
such as C++'s `//' to end of line, is represented by giving `/' the
"punctuation" class and the "style b first character of start sequence"
and "style b second character of start sequence" flags.  The fact that
class is _not_ punctuation allows the syntax scanner to recognize that
this is a multi-character delimiter.  The `newline' character is given
(single-character) "comment-end" _class_ and the "style b first
character of end sequence" _flag_.  The "comment-end" class allows the
scanner to determine that no second character is needed to terminate
the comment.

   There used to be a syntax class `Sextword'.  A character of
`Sextword' class is a word-constituent but a word boundary may exist
between two such characters.  Ken'ichi HANDA <handa@etl.go.jp> explains
the purpose of the Sextword syntax category:

     Japanese words are not separated by spaces, which makes finding
     word boundaries very difficult.  Theoretically it's impossible
     without using natural language processing techniques.  But, by
     defining pseudo-words as below (much simplified for letting you
     understand it easily) for Japanese, we can have a convenient
     forward-word function for Japanese.

          A Japanese word is a sequence of characters that consists of
          zero or more Kanji characters followed by zero or more
          Hiragana characters.

     Then, the problem is that now we can't say that a sequence of
     word-constituents makes up a word.  For instance, both Hiragana "A"
     and Kanji "KAN" are word-constituents but the sequence of these two
     letters can't be a single word.

     So, we introduced Sextword for Japanese letters.

   There seems to have been some controversy about this category, as it
has been removed, readded, and removed again.  Currently neither GNU
Emacs (21.3.99) nor XEmacs (21.5.17) seems to use it.

     `casefiddle.c'

   This module implements various Lisp primitives for upcasing,
downcasing and capitalizing strings or regions of buffers.

     `rangetab.c'

   This module implements the "range table" Lisp object type, which
provides for a mapping from ranges of integers to arbitrary Lisp
objects.

     `opaque.c'
     `opaque.h'

   This module implements the "opaque" Lisp object type, an
internal-only Lisp object that encapsulates an arbitrary block of memory
so that it can be managed by the Lisp allocation system.  To create an
opaque object, you call `make_opaque()', passing a pointer to a block
of memory.  An object is created that is big enough to hold the memory,
which is copied into the object's storage.  The object will then stick
around as long as you keep pointers to it, after which it will be
automatically reclaimed.

   Opaque objects can also have an arbitrary "mark method" associated
with them, in case the block of memory contains other Lisp objects that
need to be marked for garbage-collection purposes. (If you need other
object methods, such as a finalize method, you should just go ahead and
create a new Lisp object type--it's not hard.)

     `abbrev.c'

   This function provides a few primitives for doing dynamic
abbreviation expansion.  In XEmacs, most of the code for this has been
moved into Lisp.  Some C code remains for speed and because the
primitive `self-insert-command' (which is executed for all
self-inserting characters) hooks into the abbrev mechanism.
(`self-insert-command' is itself in C only for speed.)

     `doc.c'

   This function provides primitives for retrieving the documentation
strings of functions and variables.  These documentation strings contain
certain special markers that get dynamically expanded (e.g. a
reverse-lookup is performed on some named functions to retrieve their
current key bindings).  Some documentation strings (in particular, for
the built-in primitives and pre-loaded Lisp functions) are stored
externally in a file `DOC' in the `lib-src/' directory and need to be
fetched from that file. (Part of the build stage involves building this
file, and another part involves constructing an index for this file and
embedding it into the executable, so that the functions in `doc.c' do
not have to search the entire `DOC' file to find the appropriate
documentation string.)

     `md5.c'

   This function provides a Lisp primitive that implements the MD5
secure hashing scheme, used to create a large hash value of a string of
data such that the data cannot be derived from the hash value.  This is
used for various security applications on the Internet.


File: internals.info,  Node: Modules for Interfacing with the Operating System,  Prev: Modules for Other Aspects of the Lisp Interpreter and Object System,  Up: The Modules of XEmacs

9.8 Modules for Interfacing with the Operating System
=====================================================

     `process.el'
     `process.c'
     `process.h'

   These modules allow XEmacs to spawn and communicate with subprocesses
and network connections.

   `process.el' implements (through the `call-process' primitive) what
are called "synchronous subprocesses".  This means that XEmacs runs a
program, waits till it's done, and retrieves its output.  A typical
example might be calling the `ls' program to get a directory listing.

   `process.c' and `process.h' implement "asynchronous subprocesses".
This means that XEmacs starts a program and then continues normally,
not waiting for the process to finish.  Data can be sent to the process
or retrieved from it as it's running.  This is used for the `shell'
command (which provides a front end onto a shell program such as
`csh'), the mail and news readers implemented in XEmacs, etc.  The
result of calling `start-process' to start a subprocess is a process
object, a particular kind of object used to communicate with the
subprocess.  You can send data to the process by passing the process
object and the data to `send-process', and you can specify what happens
to data retrieved from the process by setting properties of the process
object. (When the process sends data, XEmacs receives a process event,
which says that there is data ready.  When `dispatch-event' is called
on this event, it reads the data from the process and does something
with it, as specified by the process object's properties.  Typically,
this means inserting the data into a buffer or calling a function.)
Another property of the process object is called the "sentinel", which
is a function that is called when the process terminates.

   Process objects are also used for network connections (connections
to a process running on another machine).  Network connections are
started with `open-network-stream' but otherwise work just like
subprocesses.

     `sysdep.c'
     `sysdep.h'

   These modules implement most of the low-level, messy operating-system
interface code.  This includes various device control (ioctl) operations
for file descriptors, TTY's, pseudo-terminals, etc. (usually this stuff
is fairly system-dependent; thus the name of this module), and emulation
of standard library functions and system calls on systems that don't
provide them or have broken versions.

     `sysdir.h'
     `sysfile.h'
     `sysfloat.h'
     `sysproc.h'
     `syspwd.h'
     `syssignal.h'
     `systime.h'
     `systty.h'
     `syswait.h'

   These header files provide consistent interfaces onto
system-dependent header files and system calls.  The idea is that,
instead of including a standard header file like `<sys/param.h>' (which
may or may not exist on various systems) or having to worry about
whether all system provide a particular preprocessor constant, or
having to deal with the four different paradigms for manipulating
signals, you just include the appropriate `sys*.h' header file, which
includes all the right system header files, defines and missing
preprocessor constants, provides a uniform interface onto system calls,
etc.

   `sysdir.h' provides a uniform interface onto directory-querying
functions. (In some cases, this is in conjunction with emulation
functions in `sysdep.c'.)

   `sysfile.h' includes all the necessary header files for standard
system calls (e.g. `read()'), ensures that all necessary `open()' and
`stat()' preprocessor constants are defined, and possibly (usually)
substitutes sugared versions of `read()', `write()', etc. that
automatically restart interrupted I/O operations.

   `sysfloat.h' includes the necessary header files for floating-point
operations.

   `sysproc.h' includes the necessary header files for calling
`select()', `fork()', `execve()', socket operations, and the like, and
ensures that the `FD_*()' macros for descriptor-set manipulations are
available.

   `syspwd.h' includes the necessary header files for obtaining
information from `/etc/passwd' (the functions are emulated under VMS).

   `syssignal.h' includes the necessary header files for
signal-handling and provides a uniform interface onto the different
signal-handling and signal-blocking paradigms.

   `systime.h' includes the necessary header files and provides uniform
interfaces for retrieving the time of day, setting file
access/modification times, getting the amount of time used by the XEmacs
process, etc.

   `systty.h' buffers against the infinitude of different ways of
controlling TTY's.

   `syswait.h' provides a uniform way of retrieving the exit status
from a `wait()'ed-on process (some systems use a union, others use an
int).

     `hpplay.c'
     `libsst.c'
     `libsst.h'
     `libst.h'
     `linuxplay.c'
     `nas.c'
     `sgiplay.c'
     `sound.c'
     `sunplay.c'

   These files implement the ability to play various sounds on some
types of computers.  You have to configure your XEmacs with sound
support in order to get this capability.

   `sound.c' provides the generic interface.  It implements various
Lisp primitives and variables that let you specify which sounds should
be played in certain conditions. (The conditions are identified by
symbols, which are passed to `ding' to make a sound.  Various standard
functions call this function at certain times; if sound support does
not exist, a simple beep results.

   `sgiplay.c', `sunplay.c', `hpplay.c', and `linuxplay.c' interface to
the machine's speaker for various different kind of machines.  This is
called "native" sound.

   `nas.c' interfaces to a computer somewhere else on the network using
the NAS (Network Audio Server) protocol, playing sounds on that
machine.  This allows you to run XEmacs on a remote machine, with its
display set to your local machine, and have the sounds be made on your
local machine, provided that you have a NAS server running on your local
machine.

   `libsst.c', `libsst.h', and `libst.h' provide some additional
functions for playing sound on a Sun SPARC but are not currently in use.

     `tooltalk.c'
     `tooltalk.h'

   These two modules implement an interface to the ToolTalk protocol,
which is an interprocess communication protocol implemented on some
versions of Unix.  ToolTalk is a high-level protocol that allows
processes to register themselves as providers of particular services;
other processes can then request a service without knowing or caring
exactly who is providing the service.  It is similar in spirit to the
DDE protocol provided under Microsoft Windows.  ToolTalk is a part of
the new CDE (Common Desktop Environment) specification and is used to
connect the parts of the SPARCWorks development environment.

     `getloadavg.c'

   This module provides the ability to retrieve the system's current
load average. (The way to do this is highly system-specific,
unfortunately, and requires a lot of special-case code.)

     `sunpro.c'

   This module provides a small amount of code used internally at Sun to
keep statistics on the usage of XEmacs.

     `broken-sun.h'
     `strcmp.c'
     `strcpy.c'
     `sunOS-fix.c'

   These files provide replacement functions and prototypes to fix
numerous bugs in early releases of SunOS 4.1.

     `hftctl.c'

   This module provides some terminal-control code necessary on
versions of AIX prior to 4.1.


File: internals.info,  Node: The Build Configuration System,  Next: Rules When Writing New C Code,  Prev: The Modules of XEmacs,  Up: Top

10 The Build Configuration System
*********************************

XEmacs makes extensive use of the external features provided by the
system it is running on.  Determining which features are present and
where they are located is the responsibility of the build configuration
system.

* Menu:

* The version.sh Script::
* Adding Configurable Features::
* The configure Script::
* The Makefile Precursors::


File: internals.info,  Node: The version.sh Script,  Next: Adding Configurable Features,  Prev: The Build Configuration System,  Up: The Build Configuration System

10.1 The version.sh Script
==========================

The `version.sh' script is a snippet of Bourne shell script which sets
version variables.  By convention, these variables are given
descriptive names, all in lower case ASCII letters, with words separated
by underscores (`_', ASCII 0x5F).  They are converted to C preprocessor
macro definitions and added to `src/config.h' by `configure'.  Thus
each must have a corresponding `#undef' in `src/config.h.in'.  Each
macro's name is the same as the shell variable's, converted to all
uppercase.  Finally, the macros are used to initialize Lisp variables
defined in `src/emacs.c'.  These Lisp variables have the same name as
the shell variables and preprocessor macros, except that they obey the
Lisp conventions that Lisp variable names are all lowercase with words
separated by hyphens (`-', ASCII 0x2D), while the C implementations are
the same as the shell variable with the letter `V' (ASCII 0x56)
prepended.

   The file is updated by various release engineers and their scripts.
Other developers should have no need to edit this file.  The main
exception would be to add a branch tag and possibly other information to
`xemacs_extra_name' to describe informal releases from a private
branch.  In particular, `xemacs_release_date' and the `emacs_*_version'
variables should refer to the most recent release in the parent branch,
so "private branch" maintainers should not update them.  If the branch
is significant and long-lasting, you might enjoy assigning your own
codenames.  (Of course, if you have no intent of merging your changes
to the mainline, you can do what you want with any of the variables.
But in that case you should change the name of the program, as well, in
version strings and the like.)

   Regarding the syntax of the file, it is simply a sequence of shell
variable assignments.  So the only thing that you can rely on is that
the shebang (the shell's interpreter comment, `#!/bin/sh') will occupy
the first line of the file.  You should not count on order or other
comments being preserved.  On the other hand, some maintainers' tools
do depend on the order, so as much as possible your tools should
preserve the order of assignments.

   Here is a table of the currently defined variables and their
meanings (as of February 2005):

`#!/bin/sh'
     The shebang, making this an executable script on Unix.

`emacs_is_beta'
     Set to `t' when the release is a beta test release, otherwise null.

`emacs_major_version'
`emacs_minor_version'
`emacs_beta_version'
     Strings containing decimal numbers representing the components of
     the version of the source tree.  The name `emacs_beta_version' is a
     relic of the time when XEmacs had a two component version for
     public releases.  Since XEmacs 21.1, both the beta series and the
     stable series have three-component version numbers, and
     `emacs_beta_version' holds the lowest-order component of the
     stable series as well as the beta series.

`xemacs_codename'
     An optional string containing a codename for the release.  Recent
     maintainers have chosen humorous themes for their codenames, and
     typically the names are used in alphabetical order.

`emacs_kit_version'
     An optional string used for special branches.  (This should be
     deprecated in favor of xemacs_extra_name.)

`infodock_major_version'
`infodock_minor_version'
`infodock_build_version'
     Strings containing decimal numbers representing the components of
     the version of the Infodock applied to the source tree.  (The
     Infodock project has been in hibernation since XEmacs 21.1.9 or
     so; these variables are unused in current XEmacsen.)

`xemacs_extra_name'
     A string containing arbitrary additional information.  If length is
     positive, it is automatically added to the version string after the
     codename.

`xemacs_release_date'
     A string containing the date of the latest release in the series
     in ISO 8601 format.  The time zone should not be present, it is
     defined to be UTC.  Time is optional.  Not currently used in the
     version string.


File: internals.info,  Node: Adding Configurable Features,  Next: The configure Script,  Prev: The version.sh Script,  Up: The Build Configuration System

10.2 Adding Configurable Features
=================================

Adding a configurable feature requires at the very least adding an
option to the `configure' script and a macro definition to
`src/config.h.in' (*note The configure Script::), and often changes to
Makefile precursors (*note The Makefile Precursors::).

   Be prepared for the feature to be absent (even if you think that is
always present for a particular OS release) and work with
`--with-site-prefixes' to handle libraries and headers that are in
unusual locations.  There is no end to the strange ways in which systems
can be configured and XEmacs is expected to cope with anything thrown at
it.


File: internals.info,  Node: The configure Script,  Next: The Makefile Precursors,  Prev: Adding Configurable Features,  Up: The Build Configuration System

10.3 The configure Script
=========================

At the heart of the XEmacs build configuration system is the
`configure' script.  This beast is maintained using the Autoconf
system, which is a truly terrifying monstrosity based on a fundamentally
flawed programming model (extensive use of macros), with an unpleasant
implementation (GNU `m4'), used to string together a large set of _ad
hoc_ tests, to implement a configuration language with conventions that
are unimportant in simple cases and counterintuitive when things get
complicated.  If that doesn't scare you off, Welcome! I think you're
ready to become a configure hacker!  (But be prepared for things to go
downhill from here.)

   Unless you plan to develop autoconf macros, much of this complexity
can be removed by following the following rule:

     Always quote (ie surround with `[]') every argument to every
     macro.  This includes macros that appear in the argument list of
     other macros.

   If this rule is followed and the macro produces incorrect results
then the macro is buggy.

   `configure' is, of course, is written in POSIX shell language, and
autogenerated from a precursor.  As of March 2005 on the mainline the
precursor is called `configure.ac' and it is built using `autoconf'
2.59.  Prior to that, and with XEmacs 21.4 and earlier it was called
`configure.in' and build using `autoconf' 2.13.  `autoconf' 2.5X is not
completely backward compatible with `autoconf' 2.13 so the XEmacs
Project chose to stick with the devil it knew for the stable line of
XEmacs 21.4 releases.

   One reason for worrying about the level of compatibility is the fact
that XEmacs uses a lot of homebrew code, including `m4' macros, to
implement special features in its `configure' script.  Here are some of
the important features:

   * Selectively enabling debugging, error checking, and tracing.

   * Complex options, which are set-valued (i.e., unordered; ordered
     lists of options, for example "take the first available from the
     list," are neither used currently nor given special support).

   Where these are implemented as `m4' macros, the prefix `XE_' is used
to identify them as XEmacs features in the `configure' precursor code.
Here is a list of prototypes of the convenience macros provided for
performing common operations:

`USAGE_ERROR(string)'
     Prints a usage error and dies.

`PRINT_VAR(var var ...)'
     Prints the name and value of the list of shell variables.

`XE_ADD_OBJS(foo.o)'
     Appends the argument to the variable `extra_objs'.  This variable
     goes to make up part of the link command line.  If the command line
     argument `--verbose' is supplied a message is printed out.

`XE_APPEND(value, varname)'
     Append the value (separated by a space) to the shell variable
     VARNAME.  VARNAME should not be prefixed with a `$'.  If the
     command line argument `--verbose' is supplied a message is printed
     out.

`XE_PREPEND(value, varname)'
     Prepend the value (separated by a space) to the shell variable
     VARNAME.  VARNAME should not be prefixed with a `$'.  If the
     command line argument `--verbose' is supplied a message is printed
     out.

`XE_DIE(message)'
     Used for situations that can't lead to a successful build, such as
     missing include files or conflicts between requested features.

`XE_CHECK_FEATURE_DEPENDENCY(feature1, feature2)'
     `--with-FEATURE1' requires that `--with-FEATURE2' be also set and
     will die if the latter is not specified.

`XE_STRIP_4TH_COMPONENT(var)'
     Converts the four part system name (eg `i986-pc-linux-gnu') in VAR
     to a three part names (eg `i986-pc-linux').

`CANONICALIZE_PATH(varname)'
     Strips automount brokenness from the path in VARNAME.

`XE_PROTECT_LINKER_FLAGS(shell_var)'
     Wrap the command line arguments in SHELL_VAR with suitable
     incantations to ensure that the compiler front end passes them to
     the linker.  Currently the magic is added only for gcc.

`COLON_TO_SPACE(path)'
     Converts a colon separated list of paths into a space separated
     list of paths.

`XE_ADD_RUNPATH_DIR(directory)'
     Internal function used by `XE_COMPUTE_RUNPATH'.

`XE_COMPUTE_RUNPATH()'
     Calculate the appropriate dynamic library run path for XEmacs and
     the value to the shell variable `ld_switch_run'.

`XE_SPACE(var, words)'
     Append to `var' a space separated list of `words'.

`XE_SHLIB_STUFF'
     Generate the appropriate shared library support black magic. This
     is implemented in the file `aclocal.m4'.

XEmacs keyword option support
=============================

A "keyword" option is one that accepts one of a number of pre-defined
values (if support for sets of values is needed, x1see "complex
options" below).  For example, `--with-mail-locking=flock'.

   Keyword options are defined with expanded forms of
`AC_ARG_[WITH|ENABLE]' called `XE_KEYWORD_ARG_[WITH|ENABLE]', both
taking 5 parameters.  The first 4 parameters of these macros are the
same as original macros with the exception that all four parameters are
*required*.  The ACTION-IF-TRUE code is run after the argument list has
been parsed.

   The 5th parameter is a list of supported keywords.  The whole list
must be quoted but the individual keywords should not.  Here is how the
`mail-locking' flag is defined:

     XE_KEYWORD_ARG_WITH([mail-locking],
     	AC_HELP_STRING([--with-mail-locking],[Specify the locking to be
                             used by movemail to prevent concurrent updates
                             of mail spool files. Valid types are `lockf',
                             `flock', `dot', `locking' or `mmdf'.]),
             [],
             [],
             [lockf,flock,file,locking,mmdf,pop])

   (Note that the help string will be reformatted by `autoconf' so that
all whitespace is first compressed to a single space, then folded to
appear in the right-hand column as above.  Thus the help string may
appear differently when `./configure --help' is invoked.)

   If the option value is a not a valid keyword then an error message is
generated, otherwise the value is left untouched.

   This support is implemented via the following `GNU m4' macros.
Macros labeled "internal" are not expected to be used by `configure.ac'
programmers; they are part of the implementation of higher-level
features.

`XE_KEYWORD_ARG_WITH(package, help-string, action-if-true, action-if-false, [keyword1, keyword2, ....])'
     Expanded version of `AC_ARG_WITH' for keyword options.  All the
     parameters are required.  The last argument is a comma-separated
     list of supported keywords, `m4'-quoted with `[]'.

`XE_KEYWORD_ARG_ENABLE(feature, help-string, action-if-true, action-if-false, [keyword1, keyword2, ....])'
     Expanded version of `AC_ARG_ENABLE' for keyword options.  All the
     parameters are required.  The last argument is a comma-separated
     list of supported keywords, `m4'-quoted with `[]'.

`XE_PARSE_KEYWORD_OPTION(prefix, cmdline-flag)'
     Internal macro to parse the option values.  If an undeclared
     option is found then an error is generated.

`XE_KEYWORD(keyword)'
     Internal macro to convert the keyword list into the various forms
     needed by `XE_PARSE_KEYWORD_OPTION'.


XEmacs complex option support
=============================

A "complex option" is one that takes a number of related values, as a
set.  For example, we might use `--with-sound=native,nas' to play
sounds using the native libraries and via NAS.

   Complex options are defined with expanded forms of
`AC_ARG_[WITH|ENABLE]' called `XE_COMPLEX_ARG_[WITH|ENABLE]', both
taking 5 parameters.  The first 4 parameters of these macros are the
same as original macros with the exception that all four parameters are
*required*.  The ACTION-IF-TRUE code is run after the argument list has
been parsed.

   The 5th parameter is a list of `XE_COMPLEX_OPTION' macro calls that
define the valid components and their default values.  The list must be
quoted but the individual macro calls should not.  Here is how the
`sound' flag is defined:

     XE_COMPLEX_ARG_ENABLE([sound],
     	AC_HELP_STRING([--enable-sound],[Compile with sound support.
                             Valid types are `native', `nas' and `esd'.
                             Prefix a type with 'no' to disable.
                             The first type can be `none' or `all'.  `none' means
                             `nonative,nonas,noesd'.  `all' means `native,nas,esd'.
                             Later options override earlier ones for the same TYPE.
                             The default is to autodetect all sound support except
                             for ESD which defaults to off.]),
     	[],
     	[enable_sound_nas=""],
     	[XE_COMPLEX_OPTION([native],[""]),
     	 XE_COMPLEX_OPTION([nas],[""]),
     	 XE_COMPLEX_OPTION([esd],[no])])

   Each option is interpreted as a separate feature to be enabled or
disabled.  As usual, the distinction between "with" and "enable" is
that "with" features require specific support from the system, usually
one or more optional libraries, and "enable" features are supported
entirely by code in XEmacs, but the user might want to switch it off for
some reason.  Option values are stored in the variables
`with_PACKAGE_COMPONENT' or `enable_FEATURE_COMPONENT' (e.g.
`enable_sound_native').

   The user of `configure' specifies the configuration by providing a
list of components.  The special components `all' and `none' may occur
first in the list, setting the defaults for all components to `yes' or
`no' respectively.

   In `configure.ac', default values of option values may be `yes'
which means that the option must be used and an error must occur if
there is a configuration problems (such as a missing library) or `no'
which means that the option must not be used.  The default value can
also be the null string `""', usually meaning that `configure' will
attempt to find support for the feature on the system, and will enable
the configuration if it is available.  Sometimes the null string means
that `configure''s default is system-dependent.  (This usage is not
consistent, and depends on the implementation of the feature detector
rather than the argument parser.)  Users cannot specify the null string
for an individual component from the command line.

   There are two possible uses in XEmacs for this kind of facility.
One is exemplified by sound: there are alternative protocols (native,
ESD, NAS) and each is supported by a corresponding library.  The other
is a single library which may or may not be supported by multiple
components of XEmacs, as exemplified by Xft.  This latter usage may be
more common during development of a feature.  Perhaps specialized APIs
should be provided, see comment on `XE_COMPLEX_OPTION_HELP_STRING'
below.

`XE_COMPLEX_OPTION(option, yesno)'
     Declare a complex option and its default value.  The value *must*
     be either `yes' or `no' or the null string `""'.  The null string
     means "maybe", whose semantics are determined by the
     implementation of the option, not by the parser.  Typical
     semantics are "use the library if found in the usual places" or
     "default is platform-dependent".

`XE_COMPLEX_OPTION_HELP_STRING(flag, long, short, components, libraries)'
     Format a boilerplate help string for complex options.

     This was originally written for the Xft option, and doesn't read
     so well for options based on alternative libraries like sound.
     Hackers beware: the API may be enhanced to deal with this in the
     future.

`XE_COMPLEX_ARG_WITH(PACKAGE, HELP-STRING, ACTION-IF-TRUE, ACTION-IF-FALSE, [XE_COMPLEX_OPTION(a,yes), ....])'
     Extended version of `AC_ARG_WITH' for complex options.  All the
     parameters are required.

`XE_COMPLEX_ARG_ENABLE(FEATURE, HELP-STRING, ACTION-IF-TRUE, ACTION-IF-FALSE, [XE_COMPLEX_OPTION(a,yes), ....])'
     Expanded version of `AC_ARG_ENABLE' for complex options.  All the
     parameters are required.

`XE_EXPAND_COMPLEX_OPTION(prefix, component, yesno)'
     Internal macro create the option's shell variable containing the
     default value and to note the values in an option list.

`XE_EXPAND_COMPLEX_OPTIONS(prefix, option_list)'
     Internal macro which recursively expands an option list.

`XE_INIT_COMPLEX_OPTION(prefix, option_list)'
     Internal macro to initialise the complex option shell variables.

     Variables of the form `PREFIX_OPTION' contain the default value
     for that option.  `PREFIX_types' contains a space-separated list
     of all the options and `PREFIX_default' contains a comma-separated
     list of all the default values.

`XE_PARSE_COMPLEX_OPTION(prefix, cmdline-flag)'
     Internal macro to parse the option values.  If an undeclared
     option is found then an error is generated.



File: internals.info,  Node: The Makefile Precursors,  Prev: The configure Script,  Up: The Build Configuration System

10.4 The Makefile Precursors
============================

As with other `autoconf' based programs, XEmacs's Makefiles are not
written, they are generated.  The `configure' program uses Makefile
precursors, or templates, to generate the actual Makefiles.  Unlike
other programs this is a multistage process.  The developer changes the
file `Makefile.in.in', then `configure' first generates an intermediate
file `Makefile.in', and finally produces a portable Makefile called
`Makefile', and a Makefile optimized for `GNU make' called
`GNUmakefile'.

   `Makefile.in.in' is run through the C preprocessor as part of this
process. This means that common files can be included and conditional
construction of the Makefile can occur.  When `GNUmakefile' is being
produced `USE_GNU_MAKE' is defined.

   Comments in `Makefile.in.in' must start with `##' to avoid confusing
the preprocessor.


File: internals.info,  Node: Rules When Writing New C Code,  Next: Regression Testing XEmacs,  Prev: The Build Configuration System,  Up: Top

11 Rules When Writing New C Code
********************************

The XEmacs C Code is extremely complex and intricate, and there are many
rules that are more or less consistently followed throughout the code.
Many of these rules are not obvious, so they are explained here.  It is
of the utmost importance that you follow them.  If you don't, you may
get something that appears to work, but which will crash in odd
situations, often in code far away from where the actual breakage is.

* Menu:

* Introduction to Writing C Code::
* Writing New Modules::
* Working with Lisp Objects::
* Writing Lisp Primitives::
* Writing Good Comments::
* Adding Global Lisp Variables::
* Writing Macros::
* Proper Use of Unsigned Types::
* Major Textual Changes::
* Debugging and Testing::

   See also *Note Coding for Mule::.


File: internals.info,  Node: Introduction to Writing C Code,  Next: Writing New Modules,  Prev: Rules When Writing New C Code,  Up: Rules When Writing New C Code

11.1 Introduction to Writing C Code
===================================

The C code is actually written in a dialect of C called "Clean C",
meaning that it can be compiled, warning-free, with either a C or C++
compiler.  Coding in Clean C has several advantages over plain C.  C++
compilers are more nit-picking, and a number of coding errors have been
found by compiling with C++.  The ability to use both C and C++ tools
means that a greater variety of development tools are available to the
developer.  In addition, the ability to overload operators in C++ means
it is possible, for error-checking purposes, to redefine certain simple
types (normally defined as aliases for simple built-in types such as
`unsigned char' or `long') as classes, strictly limiting the
permissible operations and catching illegal implicit casts and such.

   XEmacs follows the GNU coding standards, which are documented
separately in *Note top: (standards)top.  This section mainly documents
standards that are not included in that document; typically this
consists of standards that are specifically relevant to the XEmacs code
itself.

   First, a recap of the GNU standards:

   * Put a space after every comma.

   * Put a space before the parenthesis that begins a function call,
     macro call, function declaration or definition, or control
     statement (if, while, switch, for). (DO NOT do this for macro
     definitions; this is invalid preprocessor syntax.)

   * The brace that begins a control statement (if, while, for, switch,
     do) or a function definition should go on a line by itself.

   * In function definitions, put the return type and all other
     qualifiers on a line before the function name.  Thus, the function
     name is always at the beginning of a line.

   * Indentation level is two spaces.  (However, the first and following
     statements of a while/for/if/etc. block are indented four spaces
     from the while/for/if keyword.  The opening and closing braces are
     indented two spaces.)

   * Variable and function names should be all lowercase, with
     underscores separating words, except for a prefixing tag, which
     may be in uppercase.  Do not use the mixed-case convention (e.g.
     SetVariableToValue ()) and *especially* do not use Microsoft
     Hungarian notation (char **rgszRedundantTag).

   * preprocessor and enum constants should be all uppercase, and should
     be prefixed with a tag that groups related constants together.

   Now, the XEmacs coding standards:

Specially-prefixed functions/variables:
---------------------------------------

   * All global C variables whose value is constant and is a symbol
     begin with a capital Q, e.g. Qkey_press_event. (The type will
     always be Lisp_Object.)

   * All other global C variables whose value is a Lisp_Object (this
     includes variables that forward into Lisp variables plus others
     like Vselected_console) begin with a capital V.

   * No C variables whose value is other than a Lisp_Object should begin
     with a capital V. (This includes C variables that forward into
     integer or boolean Lisp variables.)

   * All global C variables whose value is a struct Lisp_Subr begin
     with a capital S. (This only occurs in connection with DEFUN ()).

   * All C functions that are Lisp primitives begin with a capital F,
     and no others should begin this way.

Functions for manipulating Lisp types:
--------------------------------------

   * Any function that creates an empty or mostly empty Lisp object
     should begin allocate_(). (*Not* make_().) (Except, of course, for
     Lisp primitives, which usually begin Fmake_()).

   * Any function that converts a pointer into an equivalent Lisp_Object
     should begin make_().

   * Any function that converts a Lisp_Object into its equivalent
     pointer and checks the type and validity of the object (e.g.
     making sure it's not dead) should begin decode_().

   * Any function that looks up a Lisp object (e.g. buffer, face) given
     a symbol or string should begin get_(). (Except, of course, for
     Lisp primitives, which usually begin Fget_()).

Other:
------

   * Any header-file declarations of the sort

     struct foobar;

     go into the "types" section of lisp.h.


File: internals.info,  Node: Writing New Modules,  Next: Working with Lisp Objects,  Prev: Introduction to Writing C Code,  Up: Rules When Writing New C Code

11.2 Writing New Modules
========================

Every module includes `<config.h>' (angle brackets so that `--srcdir'
works correctly; `config.h' may or may not be in the same directory as
the C sources) and `lisp.h'.  `config.h' must always be included before
any other header files (including system header files) to ensure that
certain tricks played by various `s/' and `m/' files work out correctly.

   When including header files, always use angle brackets, not double
quotes, except when the file to be included is always in the same
directory as the including file.  If either file is a generated file,
then that is not likely to be the case.  In order to understand why we
have this rule, imagine what happens when you do a build in the source
directory using `./configure' and another build in another directory
using `../work/configure'.  There will be two different `config.h'
files.  Which one will be used if you `#include "config.h"'?

   Almost every module contains a `syms_of_*()' function and a
`vars_of_*()' function.  The former declares any Lisp primitives you
have defined and defines any symbols you will be using.  The latter
declares any global Lisp variables you have added and initializes global
C variables in the module.  *Important*: There are stringent
requirements on exactly what can go into these functions.  See the
comment in `emacs.c'.  The reason for this is to avoid obscure unwanted
interactions during initialization.  If you don't follow these rules,
you'll be sorry!  If you want to do anything that isn't allowed, create
a `complex_vars_of_*()' function for it.  Doing this is tricky, though:
you have to make sure your function is called at the right time so that
all the initialization dependencies work out.

   Declare each function of these kinds in `symsinit.h'.  Make sure
it's called in the appropriate place in `emacs.c'.  You never need to
include `symsinit.h' directly, because it is included by `lisp.h'.

   *All global and static variables that are to be modifiable must be
declared uninitialized.*  This means that you may not use the "declare
with initializer" form for these variables, such as `int some_variable
= 0;'.  The reason for this has to do with some kludges done during the
dumping process: If possible, the initialized data segment is re-mapped
so that it becomes part of the (unmodifiable) code segment in the
dumped executable.  This allows this memory to be shared among multiple
running XEmacs processes.  XEmacs is careful to place as much constant
data as possible into initialized variables during the `temacs' phase.

   *Please note:* This kludge only works on a few systems nowadays, and
is rapidly becoming irrelevant because most modern operating systems
provide "copy-on-write" semantics.  All data is initially shared
between processes, and a private copy is automatically made (on a
page-by-page basis) when a process first attempts to write to a page of
memory.

   Formerly, there was a requirement that static variables not be
declared inside of functions.  This had to do with another hack along
the same vein as what was just described: old USG systems put
statically-declared variables in the initialized data space, so those
header files had a `#define static' declaration. (That way, the
data-segment remapping described above could still work.) This fails
badly on static variables inside of functions, which suddenly become
automatic variables; therefore, you weren't supposed to have any of
them.  This awful kludge has been removed in XEmacs because

  1. almost all of the systems that used this kludge ended up having to
     disable the data-segment remapping anyway;

  2. the only systems that didn't were extremely outdated ones;

  3. this hack completely messed up inline functions.

   Here are things to know when you create a new source file:

   * All `.c' files should `#include <config.h>' first.  Almost all
     `.c' files should `#include "lisp.h"' second.

   * Generated header files should be included using the `#include
     <...>' syntax, not the `#include "..."' syntax.  The generated
     headers are:

     `config.h sheap-adjust.h paths.h Emacs.ad.h'

     The basic rule is that you should assume builds using `--srcdir'
     and the `#include <...>' syntax needs to be used when the
     to-be-included generated file is in a potentially different
     directory _at compile time_.  The non-obvious C rule is that
     `#include "..."' means to search for the included file in the same
     directory as the including file, _not_ in the current directory.
     Normally this is not a problem but when building with `--srcdir',
     `make' will search the `VPATH' for you, while the C compiler knows
     nothing about it.

   * Header files should _not_ include `<config.h>' and `"lisp.h"'.  It
     is the responsibility of the `.c' files that use it to do so.



File: internals.info,  Node: Working with Lisp Objects,  Next: Writing Lisp Primitives,  Prev: Writing New Modules,  Up: Rules When Writing New C Code

11.3 Working with Lisp Objects
==============================

Conventions involving Lisp objects
----------------------------------

Of course the low-level implementation language of XEmacs is C, but much
of that uses the Lisp engine to do its work.  However, because the code
is "inside" of the protective containment shell around the "reactor
core," you'll see lots of complex "plumbing" needed to do the work and
"safety mechanisms," whose failure results in a meltdown.  This section
provides a quick overview (or review) of the various components of the
implementation of Lisp objects.

   Two typographic conventions help to identify C objects that implement
Lisp objects.  The first is that capitalized identifiers, especially
beginning with the letters `Q', `V', `F', and `S', for C variables and
functions, and C macros with beginning with the letter `X', are used to
implement Lisp.  The second is that where Lisp uses the hyphen `-' in
symbol names, the corresponding C identifiers use the underscore `_'.
Of course, since XEmacs Lisp contains interfaces to many external
libraries, those external names will follow the coding conventions
their authors chose, and may overlap the "XEmacs name space."  However
these cases are usually pretty obvious.

   All Lisp objects are handled indirectly.  The `Lisp_Object' type is
usually a pointer to a structure, except for a very small number of
types with immediate representations (currently characters and
integers).  However, these types cannot be directly operated on in C
code, either, so they can also be considered indirect.  Types that do
not have an immediate representation always have a C typedef
`Lisp_TYPE' for a corresponding structure.

   In older code, it was common practice to pass around pointers to
`Lisp_TYPE', but this is now deprecated in favor of using `Lisp_Object'
for all function arguments and return values that are Lisp objects.
The `XTYPE' macro is used to extract the pointer and cast it to
`(Lisp_TYPE *)' for the desired type.

   *Convention*: macros whose names begin with `X' operate on
`Lisp_Object's and do no type-checking.  Many such macros are type
extractors, but others implement Lisp operations in C (_e.g._, `XCAR'
implements the Lisp `car' function).  These are unsafe, and must only
be used where types of all data have already been checked.  Such macros
are only applied to `Lisp_Object's.  In internal implementations where
the pointer has already been converted, the structure is operated on
directly using the C `->' member access operator.

   The `TYPEP', `CHECK_TYPE', and `CONCHECK_TYPE' macros are used to
test types.  The first returns a Boolean value, and the latter signal
errors.  (The `CONCHECK' variety allows execution to be CONtinued under
some circumstances, thus the name.)  Functions which expect to be
passed user data invariably call `CHECK' macros on arguments.

   There are many types of specialized Lisp objects implemented in C,
but the most pervasive type is the "symbol".  Symbols are used as
identifiers, variables, and functions.

   *Convention*: Global variables whose names begin with `Q' are
constants whose value is a symbol.  The name of the variable should be
derived from the name of the symbol using the same rules as for Lisp
primitives.  Such variables allow the C code to check whether a
particular `Lisp_Object' is equal to a given symbol.  Symbols are Lisp
objects, so these variables may be passed to Lisp primitives.  (An
alternative to the use of `Q...' variables is to call the `intern'
function at initialization in the `vars_of_MODULE' function, which is
hardly less efficient.)

   *Convention*: Global variables whose names begin with `V' are
variables that contain Lisp objects.  The convention here is that all
global variables of type `Lisp_Object' begin with `V', and no others do
(not even integer and boolean variables that have Lisp equivalents).
Most of the time, these variables have equivalents in Lisp, which are
defined via the `DEFVAR' family of macros, but some don't.  Since the
variable's value is a `Lisp_Object', it can be passed to Lisp
primitives.

   The implementation of Lisp primitives is more complex.
*Convention*: Global variables with names beginning with `S' contain a
structure that allows the Lisp engine to identify and call a C
function.  In modern versions of XEmacs, these identifiers are almost
always completely hidden in the `DEFUN' and `SUBR' macros, but you will
encounter them if you look at very old versions of XEmacs or at GNU
Emacs.  *Convention*: Functions with names beginning with `F' implement
Lisp primitives.  Of course all their arguments and their return values
must be Lisp_Objects.  (This is hidden in the `DEFUN' macro.)

Working with Lisp lists
-----------------------

Lisp lists are popular data structures in the C code as well as in
Elisp.  There are two sets of macros that iterate over lists.
`EXTERNAL_LIST_LOOP_N' should be used when the list has been supplied
by the user, and cannot be trusted to be acyclic and `nil'-terminated.
A `malformed-list' or `circular-list' error will be generated if the
list being iterated over is not entirely kosher.  `LIST_LOOP_N', on the
other hand, is faster and less safe, and can be used only on trusted
lists.

   Related macros are `GET_EXTERNAL_LIST_LENGTH' and `GET_LIST_LENGTH',
which calculate the length of a list, and in the case of
`GET_EXTERNAL_LIST_LENGTH', validating the properness of the list.  The
macros `EXTERNAL_LIST_LOOP_DELETE_IF' and `LIST_LOOP_DELETE_IF' delete
elements from a lisp list satisfying some predicate.

Implementation of Lisp objects
------------------------------

At the lowest levels, XEmacs makes heavy use of object-oriented
techniques to promote code-sharing and uniform interfaces for different
devices and platforms.  Commonly, but not always, such objects are
"wrapped" and exported to Lisp as Lisp objects.  Usually they use the
internal structures developed for Lisp objects (the `lrecord'
structure) in order to take advantage of Lisp memory management.
Unfortunately, XEmacs was originally written in C, so these techniques
are based on heavy use of C macros.

   A module defining a class is likely to use most of the following
declarations and macros.  In the following, the notation `<type>' will
stand for the full name of the class, and will be capitalized in the
way normal for its context.  The notation `<typ>' will stand for the
abbreviated form commonly used in macro names, while `ty' will be used
as the typical name for instances of the class.  (See the entry for
`MAYBE_<TY>METH' below for an example using all three notations.)

   In the interface (`.h' file), the following declarations are used
often.  Others may be used in for particular modules.  Since they're
quite short in most cases, the definitions are given as well.  The
generic macros used are defined in `lisp.h' or `lrecord.h'.

`typedef struct Lisp_<Type> Lisp_<Type>'
     This refers to the internal structure used by C code.  The XEmacs
     coding style now forbids passing pointers to `Lisp_<Type>'
     structures into or out of a function; instead, a `Lisp_Object'
     should be passed or returned (created using `wrap_<type>', if
     necessary).

`DECLARE_LRECORD (<type>, Lisp_<Type>)'
     Declares an `lrecord' for `<Type>', which is the unit of
     allocation.

`#define X<TYPE>(x) XRECORD (x, <type>, Lisp_<Type>)'
     Turns a `Lisp_Object' into a pointer to `struct Lisp_<Type>'.

`#define wrap_<type>(p) wrap_record (p, <type>)'
     Turns a pointer to `struct Lisp_<Type>' into a `Lisp_Object'.

`#define <TYPE>P(x) RECORDP (x, <type>)'
     Tests whether a given `Lisp_Object' is of type `Lisp_<Type>'.
     Returns a C int, not a Lisp Boolean value.

`#define CHECK_<TYPE>(x) CHECK_RECORD (x, <type>)'
`#define CONCHECK_<TYPE>(x) CONCHECK_RECORD (x, <type>)'
     Tests whether a given `Lisp_Object' is of type `Lisp_<Type>', and
     signals a Lisp error if not.  The `CHECK' version of the macro
     never returns if the type is wrong, while the `CONCHECK' version
     can return if the user catches it in the debugger and explicitly
     requests a return.

`#define RAW_<TYP>METH(ty, m) ((ty)->methods->m##_method)'
     Return a function pointer for the method for an object TY of class
     `Lisp_<Type>', or `NULL' if there is none for this type.

`#define HAS_<TYP>METH_P(ty, m) (!!RAW_<TYP>METH (ty, m))'
     Test whether the class that TY is an instance of has the method.

`#define <TYP>METH(ty, m, args) ((RAW_<TYP>METH (ty, m)) args)'
     Call the method on `args'.  `args' must be enclosed in parentheses
     in the call.  It is the programmer's responsibility to ensure that
     the method is available.  The standard convenience macro
     `MAYBE_<TYP>METH' is often provided for the common case where a
     void-returning method of `Type' is called.

`#define MAYBE_<TYP>METH(ty, m, args) do { ... } while (0)'
     Call a void-returning `<Type>' method, if it exists.  Note the use
     of the `do ... while (0)' idiom to give the macro call C statement
     semantics.  The full definition is equally idiomatic:

          #define MAYBE_<TYP>METH(ty, m, args) do {	\
            Lisp_<Type> *maybe_<typ>meth_ty = (ty);	\
            if (HAS_<TYP>METH_P (maybe_<typ>meth_ty, m))	\
              <TYP>METH (maybe_<typ>meth_ty, m, args);	\
          } while (0)

   The use of macros for invoking an object's methods makes life a bit
difficult for the student or maintainer when browsing the code.  In
particular, calls are of the form `<TYP>METH (ty, some_method, (x,
y))', but definitions typically are for `<subtype>_some_method'.  Thus,
when you are trying to find calls, you need to grep for `some_method',
but this will also catch calls and definitions of that method for
instances of other subtypes of `<Type>', and there may be a rather
large number of them.

   Here is a checklist of things to do when creating a new lisp object
type named FOO:

  1. create FOO.h

  2. create FOO.c

  3. add definitions of `syms_of_FOO', etc. to `FOO.c'

  4. add declarations of `syms_of_FOO', etc. to `symsinit.h'

  5. add calls to `syms_of_FOO', etc. to `emacs.c'

  6. add definitions of macros like `CHECK_FOO' and `FOOP' to `FOO.h'

  7. add the new type index to `enum lrecord_type'

  8. add a DEFINE_LRECORD_IMPLEMENTATION call to `FOO.c'

  9. add an INIT_LRECORD_IMPLEMENTATION call to `syms_of_FOO.c'


File: internals.info,  Node: Writing Lisp Primitives,  Next: Writing Good Comments,  Prev: Working with Lisp Objects,  Up: Rules When Writing New C Code

11.4 Writing Lisp Primitives
============================

Lisp primitives are Lisp functions implemented in C.  The details of
interfacing the C function so that Lisp can call it are handled by a few
C macros.  The only way to really understand how to write new C code is
to read the source, but we can explain some things here.

   An example of a special form is the definition of `prog1', from
`eval.c'.  (An ordinary function would have the same general
appearance.)

     DEFUN ("prog1", Fprog1, 1, UNEVALLED, 0, /*
     Similar to `progn', but the value of the first form is returned.
     \(prog1 FIRST BODY...): All the arguments are evaluated sequentially.
     The value of FIRST is saved during evaluation of the remaining args,
     whose values are discarded.
     */
            (args))
     {
       /* This function can GC */
       REGISTER Lisp_Object val, form, tail;
       struct gcpro gcpro1;

       val = Feval (XCAR (args));

       GCPRO1 (val);

       LIST_LOOP_3 (form, XCDR (args), tail)
         Feval (form);

       UNGCPRO;
       return val;
     }

   Let's start with a precise explanation of the arguments to the
`DEFUN' macro.  Here is a template for them:

     DEFUN (LNAME, FNAME, MIN_ARGS, MAX_ARGS, INTERACTIVE, /*
     DOCSTRING
     */
        (ARGLIST))

LNAME
     This string is the name of the Lisp symbol to define as the
     function name; in the example above, it is `"prog1"'.

FNAME
     This is the C function name for this function.  This is the name
     that is used in C code for calling the function.  The name is, by
     convention, `F' prepended to the Lisp name, with all dashes (`-')
     in the Lisp name changed to underscores.  Thus, to call this
     function from C code, call `Fprog1'.  Remember that the arguments
     are of type `Lisp_Object'; various macros and functions for
     creating values of type `Lisp_Object' are declared in the file
     `lisp.h'.

     Primitives whose names are special characters (e.g. `+' or `<')
     are named by spelling out, in some fashion, the special character:
     e.g. `Fplus()' or `Flss()'.  Primitives whose names begin with
     normal alphanumeric characters but also contain special characters
     are spelled out in some creative way, e.g. `let*' becomes
     `FletX()'.

     Each function also has an associated structure that holds the data
     for the subr object that represents the function in Lisp.  This
     structure conveys the Lisp symbol name to the initialization
     routine that will create the symbol and store the subr object as
     its definition.  The C variable name of this structure is always
     `S' prepended to the FNAME.  You hardly ever need to be aware of
     the existence of this structure, since `DEFUN' plus `DEFSUBR'
     takes care of all the details.

MIN_ARGS
     This is the minimum number of arguments that the function
     requires.  The function `prog1' allows a minimum of one argument.

MAX_ARGS
     This is the maximum number of arguments that the function accepts,
     if there is a fixed maximum.  Alternatively, it can be `UNEVALLED',
     indicating a special form that receives unevaluated arguments, or
     `MANY', indicating an unlimited number of evaluated arguments (the
     C equivalent of `&rest').  Both `UNEVALLED' and `MANY' are macros.
     If MAX_ARGS is a number, it may not be less than MIN_ARGS and it
     may not be greater than 8. (If you need to add a function with
     more than 8 arguments, use the `MANY' form.  Resist the urge to
     edit the definition of `DEFUN' in `lisp.h'.  If you do it anyways,
     make sure to also add another clause to the switch statement in
     `primitive_funcall().')

INTERACTIVE
     This is an interactive specification, a string such as might be
     used as the argument of `interactive' in a Lisp function.  In the
     case of `prog1', it is 0 (a null pointer), indicating that `prog1'
     cannot be called interactively.  A value of `""' indicates a
     function that should receive no arguments when called
     interactively.

DOCSTRING
     This is the documentation string.  It is written just like a
     documentation string for a function defined in Lisp; in
     particular, the first line should be a single sentence.  Note how
     the documentation string is enclosed in a comment, none of the
     documentation is placed on the same lines as the comment-start and
     comment-end characters, and the comment-start characters are on
     the same line as the interactive specification.  `make-docfile',
     which scans the C files for documentation strings, is very
     particular about what it looks for, and will not properly extract
     the doc string if it's not in this exact format.

     In order to make both `etags' and `make-docfile' happy, make sure
     that the `DEFUN' line contains the LNAME and FNAME, and that the
     comment-start characters for the doc string are on the same line
     as the interactive specification, and put a newline directly after
     them (and before the comment-end characters).

ARGLIST
     This is the comma-separated list of arguments to the C function.
     For a function with a fixed maximum number of arguments, provide a
     C argument for each Lisp argument.  In this case, unlike regular C
     functions, the types of the arguments are not declared; they are
     simply always of type `Lisp_Object'.

     The names of the C arguments will be used as the names of the
     arguments to the Lisp primitive as displayed in its documentation,
     modulo the same concerns described above for `F...' names (in
     particular, underscores in the C arguments become dashes in the
     Lisp arguments).

     There is one additional kludge: A trailing `_' on the C argument is
     discarded when forming the Lisp argument.  This allows C language
     reserved words (like `default') or global symbols (like `dirname')
     to be used as argument names without compiler warnings or errors.

     A Lisp function with MAX_ARGS = `UNEVALLED' is a "special form";
     its arguments are not evaluated.  Instead it receives one argument
     of type `Lisp_Object', a (Lisp) list of the unevaluated arguments,
     conventionally named `(args)'.

     When a Lisp function has no upper limit on the number of arguments,
     specify MAX_ARGS = `MANY'.  In this case its implementation in C
     actually receives exactly two arguments: the number of Lisp
     arguments (an `int') and the address of a block containing their
     values (a `Lisp_Object *').  In this case only are the C types
     specified in the ARGLIST: `(int nargs, Lisp_Object *args)'.


   Within the function `Fprog1' itself, note the use of the macros
`GCPRO1' and `UNGCPRO'.  `GCPRO1' is used to "protect" a variable from
garbage collection--to inform the garbage collector that it must look
in that variable and regard the object pointed at by its contents as an
accessible object.  This is necessary whenever you call `Feval' or
anything that can directly or indirectly call `Feval' (this includes
the `QUIT' macro!).  At such a time, any Lisp object that you intend to
refer to again must be protected somehow.  `UNGCPRO' cancels the
protection of the variables that are protected in the current function.
It is necessary to do this explicitly.

   The macro `GCPRO1' protects just one local variable.  If you want to
protect two, use `GCPRO2' instead; repeating `GCPRO1' will not work.
Macros `GCPRO3' and `GCPRO4' also exist.

   These macros implicitly use local variables such as `gcpro1'; you
must declare these explicitly, with type `struct gcpro'.  Thus, if you
use `GCPRO2', you must declare `gcpro1' and `gcpro2'.

   Note also that the general rule is "caller-protects"; i.e. you are
only responsible for protecting those Lisp objects that you create.  Any
objects passed to you as arguments should have been protected by whoever
created them, so you don't in general have to protect them.

   In particular, the arguments to any Lisp primitive are always
automatically `GCPRO'ed, when called "normally" from Lisp code or
bytecode.  So only a few Lisp primitives that are called frequently from
C code, such as `Fprogn' protect their arguments as a service to their
caller.  You don't need to protect your arguments when writing a new
`DEFUN'.

   `GCPRO'ing is perhaps the trickiest and most error-prone part of
XEmacs coding.  It is *extremely* important that you get this right and
use a great deal of discipline when writing this code.  *Note
`GCPRO'ing: GCPROing, for full details on how to do this.

   What `DEFUN' actually does is declare a global structure of type
`Lisp_Subr' whose name begins with capital `SF' and which contains
information about the primitive (e.g. a pointer to the function, its
minimum and maximum allowed arguments, a string describing its Lisp
name); `DEFUN' then begins a normal C function declaration using the
`F...' name.  The Lisp subr object that is the function definition of a
primitive (i.e. the object in the function slot of the symbol that
names the primitive) actually points to this `SF' structure; when
`Feval' encounters a subr, it looks in the structure to find out how to
call the C function.

   Defining the C function is not enough to make a Lisp primitive
available; you must also create the Lisp symbol for the primitive (the
symbol is "interned"; *note Obarrays::) and store a suitable subr
object in its function cell. (If you don't do this, the primitive won't
be seen by Lisp code.) The code looks like this:

     DEFSUBR (FNAME);

Here FNAME is the same name you used as the second argument to `DEFUN'.

   This call to `DEFSUBR' should go in the `syms_of_*()' function at
the end of the module.  If no such function exists, create it and make
sure to also declare it in `symsinit.h' and call it from the
appropriate spot in `main()'.  *Note Writing New Modules::.

   Note that C code cannot call functions by name unless they are
defined in C.  The way to call a function written in Lisp from C is to
use `Ffuncall', which embodies the Lisp function `funcall'.  Since the
Lisp function `funcall' accepts an unlimited number of arguments, in C
it takes two: the number of Lisp-level arguments, and a one-dimensional
array containing their values.  The first Lisp-level argument is the
Lisp function to call, and the rest are the arguments to pass to it.
Since `Ffuncall' can call the evaluator, you must protect pointers from
garbage collection around the call to `Ffuncall'. (However, `Ffuncall'
explicitly protects all of its parameters, so you don't have to protect
any pointers passed as parameters to it.)

   The C functions `call0', `call1', `call2', and so on, provide handy
ways to call a Lisp function conveniently with a fixed number of
arguments.  They work by calling `Ffuncall'.

   `eval.c' is a very good file to look through for examples; `lisp.h'
contains the definitions for important macros and functions.


File: internals.info,  Node: Writing Good Comments,  Next: Adding Global Lisp Variables,  Prev: Writing Lisp Primitives,  Up: Rules When Writing New C Code

11.5 Writing Good Comments
==========================

Comments are a lifeline for programmers trying to understand tricky
code.  In general, the less obvious it is what you are doing, the more
you need a comment, and the more detailed it needs to be.  You should
always be on guard when you're writing code for stuff that's tricky, and
should constantly be putting yourself in someone else's shoes and asking
if that person could figure out without much difficulty what's going
on. (Assume they are a competent programmer who understands the
essentials of how the XEmacs code is structured but doesn't know much
about the module you're working on or any algorithms you're using.) If
you're not sure whether they would be able to, add a comment.  Always
err on the side of more comments, rather than less.

   Generally, when making comments, there is no need to attribute them
with your name or initials.  This especially goes for small,
easy-to-understand, non-opinionated ones.  Also, comments indicating
where, when, and by whom a file was changed are _strongly_ discouraged,
and in general will be removed as they are discovered.  This is exactly
what `ChangeLogs' are there for.  However, it can occasionally be
useful to mark exactly where (but not when or by whom) changes are
made, particularly when making small changes to a file imported from
elsewhere.  These marks help when later on a newer version of the file
is imported and the changes need to be merged. (If everything were
always kept in CVS, there would be no need for this.  But in practice,
this often doesn't happen, or the CVS repository is later on lost or
unavailable to the person doing the update.)

   When putting in an explicit opinion in a comment, you should
_always_ attribute it with your name and the date.  This also goes for
long, complex comments explaining in detail the workings of something -
by putting your name there, you make it possible for someone who has
questions about how that thing works to determine who wrote the comment
so they can write to them.  Use your actual name or your alias at
xemacs.org, and not your initials or nickname, unless that is generally
recognized (e.g. `jwz').  Even then, please consider requesting a
virtual user at xemacs.org (forwarding address; we can't provide an
actual mailbox).  Otherwise, give first and last name.  If you're not a
regular contributor, you might consider putting your email address in -
it may be in the ChangeLog, but after awhile ChangeLogs have a tendency
of disappearing or getting muddled.  (E.g. your comment may get copied
somewhere else or even into another program, and tracking down the
proper ChangeLog may be very difficult.)

   If you come across an opinion that is not or is no longer valid, or
you come across any comment that no longer applies but you want to keep
it around, enclose it in `[[ ' and ` ]]' marks and add a comment
afterwards explaining why the preceding comment is no longer valid.  Put
your name on this comment, as explained above.

   Just as comments are a lifeline to programmers, incorrect comments
are death.  If you come across an incorrect comment, *immediately*
correct it or flag it as incorrect, as described in the previous
paragraph.  Whenever you work on a section of code, _always_ make sure
to update any comments to be correct - or, at the very least, flag them
as incorrect.

   To indicate a "todo" or other problem, use four pound signs - i.e.
`####'.


File: internals.info,  Node: Adding Global Lisp Variables,  Next: Writing Macros,  Prev: Writing Good Comments,  Up: Rules When Writing New C Code

11.6 Adding Global Lisp Variables
=================================

Global variables whose names begin with `Q' are constants whose value
is a symbol of a particular name.  The name of the variable should be
derived from the name of the symbol using the same rules as for Lisp
primitives.  These variables are initialized using a call to
`defsymbol()' in the `syms_of_*()' function. (This call interns a
symbol, sets the C variable to the resulting Lisp object, and calls
`staticpro()' on the C variable to tell the garbage-collection
mechanism about this variable.  What `staticpro()' does is add a
pointer to the variable to a large global array; when
garbage-collection happens, all pointers listed in the array are used
as starting points for marking Lisp objects.  This is important because
it's quite possible that the only current reference to the object is
the C variable.  In the case of symbols, the `staticpro()' doesn't
matter all that much because the symbol is contained in `obarray',
which is itself `staticpro()'ed.  However, it's possible that a naughty
user could do something like uninterning the symbol out of `obarray' or
even setting `obarray' to a different value [although this is likely to
make XEmacs crash!].)

   *Please note:* It is potentially deadly if you declare a `Q...'
variable in two different modules.  The two calls to `defsymbol()' are
no problem, but some linkers will complain about multiply-defined
symbols.  The most insidious aspect of this is that often the link will
succeed anyway, but then the resulting executable will sometimes crash
in obscure ways during certain operations!

   To avoid this problem, declare any symbols with common names (such as
`text') that are not obviously associated with this particular module
in the file `general-slots.h'.  The "-slots" suffix indicates that this
is a file that is included multiple times in `general.c'.  Redefinition
of preprocessor macros allows the effects to be different in each
context, so this is actually more convenient and less error-prone than
doing it in your module.

   Global variables whose names begin with `V' are variables that
contain Lisp objects.  The convention here is that all global variables
of type `Lisp_Object' begin with `V', and all others don't (including
integer and boolean variables that have Lisp equivalents). Most of the
time, these variables have equivalents in Lisp, but some don't.  Those
that do are declared this way by a call to `DEFVAR_LISP()' in the
`vars_of_*()' initializer for the module.  What this does is create a
special "symbol-value-forward" Lisp object that contains a pointer to
the C variable, intern a symbol whose name is as specified in the call
to `DEFVAR_LISP()', and set its value to the symbol-value-forward Lisp
object; it also calls `staticpro()' on the C variable to tell the
garbage-collection mechanism about the variable.  When `eval' (or
actually `symbol-value') encounters this special object in the process
of retrieving a variable's value, it follows the indirection to the C
variable and gets its value.  `setq' does similar things so that the C
variable gets changed.

   Whether or not you `DEFVAR_LISP()' a variable, you need to
initialize it in the `vars_of_*()' function; otherwise it will end up
as all zeroes, which is the integer 0 (_not_ `nil'), and this is
probably not what you want.  Also, if the variable is not
`DEFVAR_LISP()'ed, *you must call* `staticpro()' on the C variable in
the `vars_of_*()' function.  Otherwise, the garbage-collection
mechanism won't know that the object in this variable is in use, and
will happily collect it and reuse its storage for another Lisp object,
and you will be the one who's unhappy when you can't figure out how
your variable got overwritten.


File: internals.info,  Node: Writing Macros,  Next: Proper Use of Unsigned Types,  Prev: Adding Global Lisp Variables,  Up: Rules When Writing New C Code

11.7 Writing Macros
===================

Heavily used small code fragments need to be fast.  The traditional way
to implement such code fragments in C is with macros.  But macros in C
are known to be broken.

   Macro arguments that are repeatedly evaluated may suffer from
repeated side effects or suboptimal performance.

   Variable names used in macros may collide with caller's variables,
causing (at least) unwanted compiler warnings.

   In order to solve these problems, and maintain statement semantics,
one should use the `do { ... } while (0)' trick (which safely works
inside of if statements) while trying to reference macro arguments
exactly once using local variables.

   Let's take a look at this poor macro definition:

     #define MARK_OBJECT(obj) \
       if (!marked_p (obj)) mark_object (obj), did_mark = 1

   This macro evaluates its argument twice, and also fails if used like
this:
       if (flag) MARK_OBJECT (obj); else `do_something()';

   A much better definition is

     #define MARK_OBJECT(obj) do { \
       Lisp_Object mo_obj = (obj); \
       if (!marked_p (mo_obj))     \
         {                         \
           mark_object (mo_obj);   \
           did_mark = 1;           \
         }                         \
     } while (0)

   Notice the elimination of double evaluation by using the local
variable with the obscure name.  Writing safe and efficient macros
requires great care.  The one problem with macros that cannot be
portably worked around is, since a C block has no value, a macro used
as an expression rather than a statement cannot use the techniques just
described to avoid multiple evaluation.

   In most cases where a macro has function semantics, an inline
function is a better implementation technique.  Modern compiler
optimizers tend to inline functions even if they have no `inline'
keyword, and configure magic ensures that the `inline' keyword can be
safely used as an additional compiler hint.  Inline functions used in a
single .c files are easy.  The function must already be defined to be
`static'.  Just add another `inline' keyword to the definition.

     inline static int
     heavily_used_small_function (int arg)
     {
       ...
     }

   Inline functions in header files are trickier, because we would like
to make the following optimization if the function is _not_ inlined
(for example, because we're compiling for debugging).  We would like the
function to be defined externally exactly once, and each calling
translation unit would create an external reference to the function,
instead of including a definition of the inline function in the object
code of every translation unit that uses it.  This optimization is
currently only available for gcc.  But you don't have to worry about the
trickiness; just define your inline functions in header files using this
pattern:

     DECLARE_INLINE_HEADER (
     int
     i_used_to_be_a_crufty_macro_but_look_at_me_now (int arg)
     )
     {
       ...
     }

   We use `DECLARE_INLINE_HEADER' rather than just the modifier
`INLINE_HEADER' to prevent warnings when compiling with `gcc
-Wmissing-declarations'.  I consider issuing this warning for inline
functions a gcc bug, but the gcc maintainers disagree.

   Every header which contains inline functions, either directly by
using `DECLARE_INLINE_HEADER' or indirectly by using `DECLARE_LRECORD'
must be added to `inline.c''s includes to make the optimization
described above work.  (Optimization note: if all INLINE_HEADER
functions are in fact inlined in all translation units, then the linker
can just discard `inline.o', since it contains only unreferenced code).

   The three golden rules of macros:

  1. Anything that's an lvalue can be evaluated more than once.

  2. Macros where anything else can be evaluated more than once should
     have the word "unsafe" in their name (exceptions may be made for
     large sets of macros that evaluate arguments of certain types more
     than once, e.g. struct buffer * arguments, when clearly indicated
     in the macro documentation).  These macros are generally meant to
     be called only by other macros that have already stored the calling
     values in temporary variables.

  3. Nothing else can be evaluated more than once.  Use inline
     functions, if necessary, to prevent multiple evaluation.

   NOTE: The functions and macros below are given full prototypes in
their docs, even when the implementation is a macro.  In such cases,
passing an argument of a type other than expected will produce undefined
results.  Also, given that macros can do things functions can't (in
particular, directly modify arguments as if they were passed by
reference), the declaration syntax has been extended to include the
call-by-reference syntax from C++, where an & after a type indicates
that the argument is an lvalue and is passed by reference, i.e. the
function can modify its value. (This is equivalent in C to passing a
pointer to the argument, but without the need to explicitly worry about
pointers.)

   When to capitalize macros:

   * Capitalize macros doing stuff obviously impossible with (C)
     functions, e.g. directly modifying arguments as if they were
     passed by reference.

   * Capitalize macros that evaluate *any* argument more than once
     regardless of whether that's "allowed" (e.g. buffer arguments).

   * Capitalize macros that directly access a field in a Lisp_Object or
     its equivalent underlying structure.  In such cases, access
     through the Lisp_Object precedes the macro with an X, and access
     through the underlying structure doesn't.

   * Capitalize certain other basic macros relating to Lisp_Objects;
     e.g.  FRAMEP, CHECK_FRAME, etc.

   * Try to avoid capitalizing any other macros.


File: internals.info,  Node: Proper Use of Unsigned Types,  Next: Major Textual Changes,  Prev: Writing Macros,  Up: Rules When Writing New C Code

11.8 Proper Use of Unsigned Types
=================================

Avoid using `unsigned int' and `unsigned long' whenever possible.
Unsigned types are viral - any arithmetic or comparisons involving
mixed signed and unsigned types are automatically converted to
unsigned, which is almost certainly not what you want.  Many subtle and
hard-to-find bugs are created by careless use of unsigned types.  In
general, you should almost _never_ use an unsigned type to hold a
regular quantity of any sort.  The only exceptions are

  1. When there's a reasonable possibility you will actually need all
     32 or 64 bits to store the quantity.

  2. When calling existing API's that require unsigned types.  In this
     case, you should still do all manipulation using signed types, and
     do the conversion at the very threshold of the API call.

  3. In existing code that you don't want to modify because you don't
     maintain it.

  4. In bit-field structures.

   Other reasonable uses of `unsigned int' and `unsigned long' are
representing non-quantities - e.g. bit-oriented flags and such.


File: internals.info,  Node: Major Textual Changes,  Next: Debugging and Testing,  Prev: Proper Use of Unsigned Types,  Up: Rules When Writing New C Code

11.9 Major Textual Changes
==========================

Sometimes major textual changes are made to the source.  This means that
a search-and-replace is done to change type names and such.  Some people
disagree with such changes, and certainly if done without good reason
will just lead to headaches.  But it's important to keep the code clean
and understable, and consistent naming goes a long way towards this.

   An example of the right way to do this was the so-called "great
integral type renaming".

* Menu:

* Great Integral Type Renaming::
* Text/Char Type Renaming::


File: internals.info,  Node: Great Integral Type Renaming,  Next: Text/Char Type Renaming,  Prev: Major Textual Changes,  Up: Major Textual Changes

11.9.1 Great Integral Type Renaming
-----------------------------------

The purpose of this is to rationalize the names used for various
integral types, so that they match their intended uses and follow
consist conventions, and eliminate types that were not semantically
different from each other.

   The conventions are:

   * All integral types that measure quantities of anything are signed.
     Some people disagree vociferously with this, but their arguments
     are mostly theoretical, and are vastly outweighed by the practical
     headaches of mixing signed and unsigned values, and more
     importantly by the far increased likelihood of inadvertent bugs:
     Because of the broken "viral" nature of unsigned quantities in C
     (operations involving mixed signed/unsigned are done unsigned,
     when exactly the opposite is nearly always wanted), even a single
     error in declaring a quantity unsigned that should be signed, or
     even the even more subtle error of comparing signed and unsigned
     values and forgetting the necessary cast, can be catastrophic, as
     comparisons will yield wrong results.  -Wsign-compare is turned on
     specifically to catch this, but this tends to result in a great
     number of warnings when mixing signed and unsigned, and the casts
     are annoying.  More has been written on this elsewhere.

   * All such quantity types just mentioned boil down to EMACS_INT,
     which is 32 bits on 32-bit machines and 64 bits on 64-bit
     machines.  This is guaranteed to be the same size as Lisp objects
     of type `int', and (as far as I can tell) of size_t (unsigned!)
     and ssize_t.  The only type below that is not an EMACS_INT is
     Hashcode, which is an unsigned value of the same size as EMACS_INT.

   * Type names should be relatively short (no more than 10 characters
     or so), with the first letter capitalized and no underscores if
     they can at all be avoided.

   * "count" == a zero-based measurement of some quantity.  Includes
     sizes, offsets, and indexes.

   * "bpos" == a one-based measurement of a position in a buffer.
     "Charbpos" and "Bytebpos" count text in the buffer, rather than
     bytes in memory; thus Bytebpos does not directly correspond to the
     memory representation.  Use "Membpos" for this.

   * "Char" refers to internal-format characters, not to the C type
     "char", which is really a byte.

   For the actual name changes, see the script below.

   I ran the following script to do the conversion. (NOTE: This script
is idempotent.  You can safely run it multiple times and it will not
screw up previous results - in fact, it will do nothing if nothing has
changed.  Thus, it can be run repeatedly as necessary to handle patches
coming in from old workspaces, or old branches.)  There are two tags,
just before and just after the change: `pre-integral-type-rename' and
`post-integral-type-rename'.  When merging code from the main trunk
into a branch, the best thing to do is first merge up to
`pre-integral-type-rename', then apply the script and associated
changes, then merge from `post-integral-type-change' to the present.
(Alternatively, just do the merging in one operation; but you may then
have a lot of conflicts needing to be resolved by hand.)

   Script `fixtypes.sh' follows:

     ----------------------------------- cut ------------------------------------
     files="*.[ch] s/*.h m/*.h config.h.in ../configure.in Makefile.in.in ../lib-src/*.[ch] ../lwlib/*.[ch]"
     gr Memory_Count Bytecount $files
     gr Lstream_Data_Count Bytecount $files
     gr Element_Count Elemcount $files
     gr Hash_Code Hashcode $files
     gr extcount bytecount $files
     gr bufpos charbpos $files
     gr bytind bytebpos $files
     gr memind membpos $files
     gr bufbyte intbyte $files
     gr Extcount Bytecount $files
     gr Bufpos Charbpos $files
     gr Bytind Bytebpos $files
     gr Memind Membpos $files
     gr Bufbyte Intbyte $files
     gr EXTCOUNT BYTECOUNT $files
     gr BUFPOS CHARBPOS $files
     gr BYTIND BYTEBPOS $files
     gr MEMIND MEMBPOS $files
     gr BUFBYTE INTBYTE $files
     gr MEMORY_COUNT BYTECOUNT $files
     gr LSTREAM_DATA_COUNT BYTECOUNT $files
     gr ELEMENT_COUNT ELEMCOUNT $files
     gr HASH_CODE HASHCODE $files
     ----------------------------------- cut ------------------------------------

   The `gr' script, and the scripts it uses, are documented in
`README.global-renaming', because if placed in this file they would
need to have their @ characters doubled, meaning you couldn't easily
cut and paste from the source.

   In addition to those programs, I needed to fix up a few other
things, particularly relating to the duplicate definitions of types,
now that some types merged with others.  Specifically:

  1. in `lisp.h', removed duplicate declarations of Bytecount.  The
     changed code should now look like this: (In each code snippet
     below, the first and last lines are the same as the original, as
     are all lines outside of those lines.  That allows you to locate
     the section to be replaced, and replace the stuff in that section,
     verifying that there isn't anything new added that would need to
     be kept.)

          --------------------------------- snip -------------------------------------
          /* Counts of bytes or chars */
          typedef EMACS_INT Bytecount;
          typedef EMACS_INT Charcount;

          /* Counts of elements */
          typedef EMACS_INT Elemcount;

          /* Hash codes */
          typedef unsigned long Hashcode;

          /* ------------------------ dynamic arrays ------------------- */
          --------------------------------- snip -------------------------------------

  2. in `lstream.h', removed duplicate declaration of Bytecount.
     Rewrote the comment about this type.  The changed code should now
     look like this:

          --------------------------------- snip -------------------------------------
          #endif

          /* The have been some arguments over the what the type should be that
             specifies a count of bytes in a data block to be written out or read in,
             using `Lstream_read()', `Lstream_write()', and related functions.
             Originally it was long, which worked fine; Martin "corrected" these to
             size_t and ssize_t on the grounds that this is theoretically cleaner and
             is in keeping with the C standards.  Unfortunately, this practice is
             horribly error-prone due to design flaws in the way that mixed
             signed/unsigned arithmetic happens.  In fact, by doing this change,
             Martin introduced a subtle but fatal error that caused the operation of
             sending large mail messages to the SMTP server under Windows to fail.
             By putting all values back to be signed, avoiding any signed/unsigned
             mixing, the bug immediately went away.  The type then in use was
             Lstream_Data_Count, so that it be reverted cleanly if a vote came to
             that.  Now it is Bytecount.

             Some earlier comments about why the type must be signed: This MUST BE
             SIGNED, since it also is used in functions that return the number of
             bytes actually read to or written from in an operation, and these
             functions can return -1 to signal error.

             Note that the standard Unix `read()' and `write()' functions define the
             count going in as a size_t, which is UNSIGNED, and the count going
             out as an ssize_t, which is SIGNED.  This is a horrible design
             flaw.  Not only is it highly likely to lead to logic errors when a
             -1 gets interpreted as a large positive number, but operations are
             bound to fail in all sorts of horrible ways when a number in the
             upper-half of the size_t range is passed in -- this number is
             unrepresentable as an ssize_t, so code that checks to see how many
             bytes are actually written (which is mandatory if you are dealing
             with certain types of devices) will get completely screwed up.

             --ben
          */

          typedef enum lstream_buffering
          --------------------------------- snip -------------------------------------

  3. in `dumper.c', there are four places, all inside of `switch()'
     statements, where XD_BYTECOUNT appears twice as a case tag.  In
     each case, the two case blocks contain identical code, and you
     should *REMOVE THE SECOND* and leave the first.


File: internals.info,  Node: Text/Char Type Renaming,  Prev: Great Integral Type Renaming,  Up: Major Textual Changes

11.9.2 Text/Char Type Renaming
------------------------------

The purpose of this was

  1. To distinguish between "charptr" when it refers to operations on
     the pointer itself and when it refers to operations on text

  2. To use consistent naming for everything referring to internal
     format, i.e.

     	Itext == text in internal format
     	Ibyte == a byte in such text
     	Ichar == a char as represented in internal character format

   Thus e.g.

     	set_charptr_emchar -> set_itext_ichar

   This was done using a script like this:

     files="*.[ch] s/*.h m/*.h config.h.in ../configure.in Makefile.in.in ../lib-src/*.[ch] ../lwlib/*.[ch]"
     gr Intbyte Ibyte $files
     gr INTBYTE IBYTE $files
     gr intbyte ibyte $files
     gr EMCHAR ICHAR $files
     gr emchar ichar $files
     gr Emchar Ichar $files
     gr INC_CHARPTR INC_IBYTEPTR $files
     gr DEC_CHARPTR DEC_IBYTEPTR $files
     gr VALIDATE_CHARPTR VALIDATE_IBYTEPTR $files
     gr valid_charptr valid_ibyteptr $files
     gr CHARPTR ITEXT $files
     gr charptr itext $files
     gr Charptr Itext $files

   See above for the source to `gr'.

   As in the integral-types change, there are pre and post tags before
and after the change:

     	pre-internal-format-textual-renaming
     	post-internal-format-textual-renaming

   When merging a large branch, follow the same sort of procedure
documented above, using these tags - essentially sync up to the pre
tag, then apply the script yourself, then sync from the post tag to the
present.  You can probably do the same if you don't have a separate
workspace, but do have lots of outstanding changes and you'd rather not
just merge all the textual changes directly.  Use something like this:

   (WARNING: I'm not a CVS guru; before trying this, or any large
operation that might potentially mess things up, *DEFINITELY* make a
backup of your existing workspace.)

     cup -r pre-internal-format-textual-renaming
     <apply script>
     cup -A -j post-internal-format-textual-renaming -j HEAD

   This might also work:

     cup -j pre-internal-format-textual-renaming
     <apply script>
     cup -j post-internal-format-textual-renaming -j HEAD

   ben

   The following is a script to go in the opposite direction:

     files="*.[ch] s/*.h m/*.h config.h.in ../configure.in Makefile.in.in ../lib-src/*.[ch] ../lwlib/*.[ch]"

     # Evidently Perl considers _ to be a word char ala \b, even though XEmacs
     # doesn't.  We need to be careful here with ibyte/ichar because of words
     # like Richard, `eicharlen()', multibyte, HIBYTE, etc.

     gr Ibyte Intbyte $files
     gr '\bIBYTE' INTBYTE $files
     gr '\bibyte' intbyte $files
     gr '\bICHAR' EMCHAR $files
     gr '\bichar' emchar $files
     gr '\bIchar' Emchar $files
     gr '\bIBYTEPTR' CHARPTR $files
     gr '\bibyteptr' charptr $files
     gr '\bITEXT' CHARPTR $files
     gr '\bitext' charptr $files
     gr '\bItext' CHARPTR $files

     gr '_IBYTE' _INTBYTE $files
     gr '_ibyte' _intbyte $files
     gr '_ICHAR' _EMCHAR $files
     gr '_ichar' _emchar $files
     gr '_Ichar' _Emchar $files
     gr '_IBYTEPTR' _CHARPTR $files
     gr '_ibyteptr' _charptr $files
     gr '_ITEXT' _CHARPTR $files
     gr '_itext' _charptr $files
     gr '_Itext' _CHARPTR $files


File: internals.info,  Node: Debugging and Testing,  Prev: Major Textual Changes,  Up: Rules When Writing New C Code

11.10 Debugging and Testing
===========================

To make a purified XEmacs, do: `make puremacs'.  To make a quantified
XEmacs, do: `make quantmacs'.

   You simply can't dump Quantified and Purified images (unless using
the portable dumper).  Purify gets confused when xemacs frees memory in
one process that was allocated in a _different_ process on a different
machine!  Run it like so:
     temacs -batch -l loadup.el run-temacs XEMACS-ARGS...

   Before you go through the trouble, are you compiling with all
debugging and error-checking off?  If not, try that first.  Be warned
that while Quantify is directly responsible for quite a few
optimizations which have been made to XEmacs, doing a run which
generates results which can be acted upon is not necessarily a trivial
task.

   Also, if you're still willing to do some runs make sure you configure
with the `--quantify' flag.  That will keep Quantify from starting to
record data until after the loadup is completed and will shut off
recording right before it shuts down (which generates enough bogus data
to throw most results off).  It also enables three additional elisp
commands: `quantify-start-recording-data',
`quantify-stop-recording-data' and `quantify-clear-data'.

   If you want to make XEmacs faster, target your favorite slow
benchmark, run a profiler like Quantify, `gprof', or `tcov', and figure
out where the cycles are going.  In many cases you can localize the
problem (because a particular new feature or even a single patch
elicited it).  Don't hesitate to use brute force techniques like a
global counter incremented at strategic places, especially in
combination with other performance indications (_e.g._, degree of
buffer fragmentation into extents).

   Specific projects:

   * Make the garbage collector faster.  Figure out how to write an
     incremental garbage collector.

   * Write a compiler that takes bytecode and spits out C code.
     Unfortunately, you will then need a C compiler and a more fully
     developed module system.

   * Speed up redisplay.

   * Speed up syntax highlighting.  It was suggested that "maybe moving
     some of the syntax highlighting capabilities into C would make a
     difference."  Wrong idea, I think.  When processing one 400kB file
     a particular low-level routine was being called 40 _million_ times
     simply for _one_ call to `newline-and-indent'.  Syntax
     highlighting needs to be rewritten to use a reliable, fast parser,
     then to trust the pre-parsed structure, and only do
     re-highlighting locally to a text change.  Modern machines are
     fast enough to implement such parsers in Lisp; but no machine will
     ever be fast enough to deal with quadratic (or worse) algorithms!

   * Implement tail recursion in Emacs Lisp (hard!).

   Unfortunately, Emacs Lisp is slow, and is going to stay slow.
Function calls in elisp are especially expensive.  Iterating over a
long list is going to be 30 times faster implemented in C than in Elisp.

   To get started debugging XEmacs, take a look at the `.gdbinit' and
`.dbxrc' files in the `src' directory.  See the section in the XEmacs
FAQ on How to Debug an XEmacs problem with a debugger.

   After making source code changes, run `make check' to ensure that
you haven't introduced any regressions.  If you want to make xemacs more
reliable, please improve the test suite in `tests/automated'.

   Did you make sure you didn't introduce any new compiler warnings?

   Before submitting a patch, please try compiling at least once with

     configure --with-mule --use-union-type --error-checking=all


File: internals.info,  Node: Regression Testing XEmacs,  Next: CVS Techniques,  Prev: Rules When Writing New C Code,  Up: Top

12 Regression Testing XEmacs
****************************

* Menu:

* How to Regression-Test::
* Modules for Regression Testing::


File: internals.info,  Node: How to Regression-Test,  Next: Modules for Regression Testing,  Prev: Regression Testing XEmacs,  Up: Regression Testing XEmacs

12.1 How to Regression-Test
===========================

The source directory `tests/automated' contains XEmacs' automated test
suite.  The usual way of running all the tests is running `make check'
from the top-level build directory.

   The test suite is unfinished and it's still lacking some essential
features.  It is nevertheless recommended that you run the tests to
confirm that XEmacs behaves correctly.

   If you want to run a specific test case, you can do it from the
command-line like this:

     $ xemacs -batch -l test-harness.elc -f batch-test-emacs TEST-FILE

   If a test fails and you need more information, you can run the test
suite interactively by loading `test-harness.el' into a running XEmacs
and typing `M-x test-emacs-test-file RET <filename> RET'.  You will see
a log of passed and failed tests, which should allow you to investigate
the source of the error and ultimately fix the bug.  If you are not
capable of, or don't have time for, debugging it yourself, please do
report the failures using `M-x report-emacs-bug' or `M-x build-report'.

 -- Command: test-emacs-test-file file
     Runs the tests in FILE.  `test-harness.el' must be loaded.
     Defines all the macros described in this node, and undefines them
     when done.

   Adding a new test file is trivial: just create a new file here and it
will be run.  There is no need to byte-compile any of the files in this
directory--the test-harness will take care of any necessary
byte-compilation.

   Look at the existing test cases for the examples of coding test
cases.  It all boils down to your imagination and judicious use of the
macros `Assert', `Check-Error', `Check-Error-Message', and
`Check-Message'.  Note that all of these macros are defined only for
the duration of the test: they do not exist in the global environment.

 -- Macro: Assert expr
     Check that EXPR is non-nil at this point in the test.

 -- Macro: Check-Error expected-error body
     Check that execution of BODY causes EXPECTED-ERROR to be signaled.
     BODY is a `progn'-like body, and may contain several expressions.
     EXPECTED-ERROR is a symbol defined as an error by `define-error'.

 -- Macro: Check-Error-Message expected-error expected-error-regexp body
     Check that execution of BODY causes EXPECTED-ERROR to be signaled,
     and generate a message matching EXPECTED-ERROR-REGEXP.  BODY is a
     `progn'-like body, and may contain several expressions.
     EXPECTED-ERROR is a symbol defined as an error by `define-error'.

 -- Macro: Check-Message expected-message body
     Check that execution of BODY causes EXPECTED-MESSAGE to be
     generated (using `message' or a similar function).  BODY is a
     `progn'-like body, and may contain several expressions.

   Here's a simple example checking case-sensitive and case-insensitive
comparisons from `case-tests.el'.

     (with-temp-buffer
       (insert "Test Buffer")
       (let ((case-fold-search t))
         (goto-char (point-min))
         (Assert (eq (search-forward "test buffer" nil t) 12))
         (goto-char (point-min))
         (Assert (eq (search-forward "Test buffer" nil t) 12))
         (goto-char (point-min))
         (Assert (eq (search-forward "Test Buffer" nil t) 12))

         (setq case-fold-search nil)
         (goto-char (point-min))
         (Assert (not (search-forward "test buffer" nil t)))
         (goto-char (point-min))
         (Assert (not (search-forward "Test buffer" nil t)))
         (goto-char (point-min))
         (Assert (eq (search-forward "Test Buffer" nil t) 12))))

   This example could be saved in a file in `tests/automated', and it
would constitute a complete test, automatically executed when you run
`make check' after building XEmacs.  More complex tests may require
substantial temporary scaffolding to create the environment that elicits
the bugs, but the top-level `Makefile' and `test-harness.el' handle the
running and collection of results from the `Assert', `Check-Error',
`Check-Error-Message', and `Check-Message' macros.

   Don't suppress tests just because they're due to known bugs not yet
fixed--use the `Known-Bug-Expect-Failure' wrapper macro to mark them.

 -- Macro: Known-Bug-Expect-Failure body
     Arrange for failing tests in BODY to generate messages prefixed
     with "KNOWN BUG:" instead of "FAIL:".  BODY is a `progn'-like
     body, and may contain several tests.

   A lot of the tests we run push limits; suppress Ebola warning
messages with the `Ignore-Ebola' wrapper macro.

 -- Macro: Ignore-Ebola body
     Suppress Ebola warning messages while running tests in BODY.  BODY
     is a `progn'-like body, and may contain several tests.

   Both macros are defined temporarily within the test function.  Simple
examples:

     ;; Apparently Ignore-Ebola is a solution with no problem to address.
     ;; There are no examples in 21.5, anyway.

     ;; from regexp-tests.el
     (Known-Bug-Expect-Failure
      (Assert (not (string-match "\\b" "")))
      (Assert (not (string-match " \\b" " "))))

   In general, you should avoid using functionality from packages in
your tests, because you can't be sure that everyone will have the
required package.  However, if you've got a test that works, by all
means add it.  Simply wrap the test in an appropriate test, add a
notice that the test was skipped, and update the `skipped-test-reasons'
hashtable.  The wrapper macro `Skip-Test-Unless' is provided to handle
common cases.

 -- Variable: skipped-test-reasons
     Hash table counting the number of times a particular reason is
     given for skipping tests.  This is only defined within
     `test-emacs-test-file'.

 -- Macro: Skip-Test-Unless prerequisite reason description body
     PREREQUISITE is usually a feature test (`featurep', `boundp',
     `fboundp').  REASON is a string describing the prerequisite; it
     must be unique because it is used as a hash key in a table of
     reasons for skipping tests.  DESCRIPTION describes the tests being
     skipped, for the test result summary.  BODY is a `progn'-like
     body, and may contain several tests.

   `Skip-Test-Unless' is defined temporarily within the test function.
Here's an example of usage from `syntax-tests.el':

     ;; Test forward-comment at buffer boundaries
     (with-temp-buffer
       ;; try to use exactly what you need: featurep, boundp, fboundp
       (Skip-Test-Unless (fboundp 'c-mode)
                         "c-mode unavailable"
                         "comment and parse-partial-sexp tests"
         ;; and here's the test code
         (c-mode)
         (insert "// comment\n")
         (forward-comment -2)
         (Assert (eq (point) (point-min)))
         (let ((point (point)))
           (insert "/* comment */")
           (goto-char point)
           (forward-comment 2)
           (Assert (eq (point) (point-max)))
           (parse-partial-sexp point (point-max)))))

   `Skip-Test-Unless' is intended for use with features that are
normally present in typical configurations.  For truly optional
features, or tests that apply to one of several alternative
implementations (eg, to GTK widgets, but not Athena, Motif, MS Windows,
or Carbon), simply silently suppress the test if the feature is not
available.

   Here are a few general hints for writing tests.

  1. Include related successful cases.  Fixes often break something.

  2. Use the Known-Bug-Expect-Failure macro to mark the cases you know
     are going to fail.  We want to be able to distinguish between
     regressions and other unexpected failures, and cases that have
     been (partially) analyzed but not yet repaired.

  3. Mark the bug with the date of report.  An "Unfixed since
     yyyy-mm-dd" gloss for Known-Bug-Expect-Failure is planned to
     further increase developer embarrassment (== incentive to fix the
     bug), but until then at least put a comment about the date so we
     can easily see when it was first reported.

  4. It's a matter of your judgement, but you should often use generic
     tests (_e.g._, `eq') instead of more specific tests (`=' for
     numbers) even though you know that arguments "should" be of correct
     type.  That is, if the functions used can return generic objects
     (typically `nil'), as well as some more specific type that will be
     returned on success.  We don't want failures of those assertions
     reported as "other failures" (a wrong-type-arg signal, rather than
     a null return), we want them reported as "assertion failures."

     One example is a test that tests `(= (string-match this that) 0)',
     expecting a successful match.  Now suppose `string-match' is broken
     such that the match fails.  Then it will return `nil', and `='
     will signal "wrong-type-argument, number-char-or-marker-p, nil",
     generating an "other failure" in the report.  But this should be
     reported as an assertion failure (the test failed in a foreseeable
     way), rather than something else (we don't know what happened
     because XEmacs is broken in a way that we weren't trying to test!)


File: internals.info,  Node: Modules for Regression Testing,  Prev: How to Regression-Test,  Up: Regression Testing XEmacs

12.2 Modules for Regression Testing
===================================

     `test-harness.el'
     `base64-tests.el'
     `byte-compiler-tests.el'
     `case-tests.el'
     `ccl-tests.el'
     `c-tests.el'
     `database-tests.el'
     `extent-tests.el'
     `hash-table-tests.el'
     `lisp-tests.el'
     `md5-tests.el'
     `mule-tests.el'
     `regexp-tests.el'
     `symbol-tests.el'
     `syntax-tests.el'
     `tag-tests.el'
     `weak-tests.el'

   `test-harness.el' defines the macros `Assert', `Check-Error',
`Check-Error-Message', and `Check-Message'.  The other files are test
files, testing various XEmacs facilities.  *Note Regression Testing
XEmacs::.


File: internals.info,  Node: CVS Techniques,  Next: XEmacs from the Inside,  Prev: Regression Testing XEmacs,  Up: Top

13 CVS Techniques
*****************

* Menu:

* Merging a Branch into the Trunk::


File: internals.info,  Node: Merging a Branch into the Trunk,  Prev: CVS Techniques,  Up: CVS Techniques

13.1 Merging a Branch into the Trunk
====================================

  1. If you haven't already done a merge, you will be merging from the
     branch point; otherwise you'll be merging from the last merge
     point, which should be marked by a tag, e.g.
     `last-sync-ben-mule-21-5'.  In the former case, create the
     last-sync tag, e.g.

          crw rtag -r ben-mule-21-5-bp last-sync-ben-mule-21-5 xemacs

     (You did create a branch point tag when you created the branch,
     didn't you?)

  2. Check everything in on your branch.

  3. Tag your branch with a pre-sync tag, e.g.

          crw rtag -r ben-mule-21-5 ben-mule-21-5-pre-feb-20-2002-sync xemacs

     Note, you need to use rtag and specify a version with `-r' (use
     `-r HEAD' if necessary) so that removed files are handled correctly
     in some obscure cases.  See section 4.8 of the CVS manual.

  4. Tag the trunk so you have a stable place to merge up to in case
     people are asynchronously committing to the trunk, e.g.

          crw rtag -r HEAD main-branch-ben-mule-21-5-syncpoint-feb-20-2002 xemacs
          crw rtag -F -r main-branch-ben-mule-21-5-syncpoint-feb-20-2002 next-sync-ben-mule-21-5 xemacs

     Use -F in the second case because the name might already exist,
     e.g. if you've already done a merge.  We make two tags because one
     is a permanent mark indicating a syncpoint when merging, and the
     other is a symbolic tag to make other operations easier.

  5. Make a backup of your source tree (not totally necessary but
     useful for reference and peace of mind): Move one level up from
     the top directory of your branch and do, e.g.

          cp -a mule mule-backup-2-23-02

  6. Now, we're ready to merge!  Make sure you're in the top directory
     of your branch and do, e.g.

          cvs update -j last-sync-ben-mule-21-5 -j next-sync-ben-mule-21-5

  7. Fix all merge conflicts.  Get the sucker to compile and run.

  8. Tag your branch with a post-sync tag, e.g.

          crw rtag -r ben-mule-21-5 ben-mule-21-5-post-feb-20-2002-sync xemacs

  9. Update the last-sync tag, e.g.

          crw rtag -F -r next-sync-ben-mule-21-5 last-sync-ben-mule-21-5 xemacs


File: internals.info,  Node: XEmacs from the Inside,  Next: Basic Types,  Prev: CVS Techniques,  Up: Top

14 XEmacs from the Inside
*************************

Internally, XEmacs is quite complex, and can be very confusing.  To
simplify things, it can be useful to think of XEmacs as containing an
event loop that "drives" everything, and a number of other subsystems,
such as a Lisp engine and a redisplay mechanism.  Each of these other
subsystems exists simultaneously in XEmacs, and each has a certain
state.  The flow of control continually passes in and out of these
different subsystems in the course of normal operation of the editor.

   It is important to keep in mind that, most of the time, the editor is
"driven" by the event loop.  Except during initialization and batch
mode, all subsystems are entered directly or indirectly through the
event loop, and ultimately, control exits out of all subsystems back up
to the event loop.  This cycle of entering a subsystem, exiting back out
to the event loop, and starting another iteration of the event loop
occurs once each keystroke, mouse motion, etc.

   If you're trying to understand a particular subsystem (other than the
event loop), think of it as a "daemon" process or "servant" that is
responsible for one particular aspect of a larger system, and
periodically receives commands or environment changes that cause it to
do something.  Ultimately, these commands and environment changes are
always triggered by the event loop.  For example:

   * The window and frame mechanism is responsible for keeping track of
     what windows and frames exist, what buffers are in them, etc.  It
     is periodically given commands (usually from the user) to make a
     change to the current window/frame state: i.e. create a new frame,
     delete a window, etc.

   * The buffer mechanism is responsible for keeping track of what
     buffers exist and what text is in them.  It is periodically given
     commands (usually from the user) to insert or delete text, create
     a buffer, etc.  When it receives a text-change command, it
     notifies the redisplay mechanism.

   * The redisplay mechanism is responsible for making sure that
     windows and frames are displayed correctly.  It is periodically
     told (by the event loop) to actually "do its job", i.e. snoop
     around and see what the current state of the environment (mostly
     of the currently-existing windows, frames, and buffers) is, and
     make sure that state matches what's actually displayed.  It keeps
     lots and lots of information around (such as what is actually
     being displayed currently, and what the environment was last time
     it checked) so that it can minimize the work it has to do.  It is
     also helped along in that whenever a relevant change to the
     environment occurs, the redisplay mechanism is told about this, so
     it has a pretty good idea of where it has to look to find possible
     changes and doesn't have to look everywhere.

   * The Lisp engine is responsible for executing the Lisp code in
     which most user commands are written.  It is entered through a
     call to `eval' or `funcall', which occurs as a result of
     dispatching an event from the event loop.  The functions it calls
     issue commands to the buffer mechanism, the window/frame
     subsystem, etc.

   * The Lisp allocation subsystem is responsible for keeping track of
     Lisp objects.  It is given commands from the Lisp engine to
     allocate objects, garbage collect, etc.

   etc.

   The important idea here is that there are a number of independent
subsystems each with its own responsibility and persistent state, just
like different employees in a company, and each subsystem is
periodically given commands from other subsystems.  Commands can flow
from any one subsystem to any other, but there is usually some sort of
hierarchy, with all commands originating from the event subsystem.

   XEmacs is entered in `main()', which is in `emacs.c'.  When this is
called the first time (in a properly-invoked `temacs'), it does the
following:

  1. It does some very basic environment initializations, such as
     determining where it and its directories (e.g. `lisp/' and `etc/')
     reside and setting up signal handlers.

  2. It initializes the entire Lisp interpreter.

  3. It sets the initial values of many built-in variables (including
     many variables that are visible to Lisp programs), such as the
     global keymap object and the built-in faces (a face is an object
     that describes the display characteristics of text).  This
     involves creating Lisp objects and thus is dependent on step (2).

  4. It performs various other initializations that are relevant to the
     particular environment it is running in, such as retrieving
     environment variables, determining the current date and the user
     who is running the program, examining its standard input, creating
     any necessary file descriptors, etc.

  5. At this point, the C initialization is complete.  A Lisp program
     that was specified on the command line (usually `loadup.el') is
     called (temacs is normally invoked as `temacs -batch -l loadup.el
     dump').  `loadup.el' loads all of the other Lisp files that are
     needed for the operation of the editor, calls the `dump-emacs'
     function to write out `xemacs', and then kills the temacs process.

   When `xemacs' is then run, it only redoes steps (1) and (4) above;
all variables already contain the values they were set to when the
executable was dumped, and all memory that was allocated with
`malloc()' is still around. (XEmacs knows whether it is being run as
`xemacs' or `temacs' because it sets the global variable `initialized'
to 1 after step (4) above.) At this point, `xemacs' calls a Lisp
function to do any further initialization, which includes parsing the
command-line (the C code can only do limited command-line parsing,
which includes looking for the `-batch' and `-l' flags and a few other
flags that it needs to know about before initialization is complete),
creating the first frame (or "window" in standard window-system
parlance), running the user's init file (usually the file `.emacs' in
the user's home directory), etc.  The function to do this is usually
called `normal-top-level'; `loadup.el' tells the C code about this
function by setting its name as the value of the Lisp variable
`top-level'.

   When the Lisp initialization code is done, the C code enters the
event loop, and stays there for the duration of the XEmacs process.
The code for the event loop is contained in `cmdloop.c', and is called
`Fcommand_loop_1()'.  Note that this event loop could very well be
written in Lisp, and in fact a Lisp version exists; but apparently,
doing this makes XEmacs run noticeably slower.

   Notice how much of the initialization is done in Lisp, not in C.  In
general, XEmacs tries to move as much code as is possible into Lisp.
Code that remains in C is code that implements the Lisp interpreter
itself, or code that needs to be very fast, or code that needs to do
system calls or other such stuff that needs to be done in C, or code
that needs to have access to "forbidden" structures. (One conscious
aspect of the design of Lisp under XEmacs is a clean separation between
the external interface to a Lisp object's functionality and its
internal implementation.  Part of this design is that Lisp programs are
forbidden from accessing the contents of the object other than through
using a standard API.  In this respect, XEmacs Lisp is similar to
modern Lisp dialects but differs from GNU Emacs, which tends to expose
the implementation and allow Lisp programs to look at it directly.  The
major advantage of hiding the implementation is that it allows the
implementation to be redesigned without affecting any Lisp programs,
including those that might want to be "clever" by looking directly at
the object's contents and possibly manipulating them.)

   Moving code into Lisp makes the code easier to debug and maintain and
makes it much easier for people who are not XEmacs developers to
customize XEmacs, because they can make a change with much less chance
of obscure and unwanted interactions occurring than if they were to
change the C code.


File: internals.info,  Node: Basic Types,  Next: Low-Level Allocation,  Prev: XEmacs from the Inside,  Up: Top

15 Basic Types
**************

Not yet documented.


File: internals.info,  Node: Low-Level Allocation,  Next: The XEmacs Object System (Abstractly Speaking),  Prev: Basic Types,  Up: Top

16 Low-Level Allocation
***********************

* Menu:

* Basic Heap Allocation::
* Stack Allocation::
* Dynamic Arrays::
* Allocation by Blocks::
* Modules for Allocation::


File: internals.info,  Node: Basic Heap Allocation,  Next: Stack Allocation,  Prev: Low-Level Allocation,  Up: Low-Level Allocation

16.1 Basic Heap Allocation
==========================


File: internals.info,  Node: Stack Allocation,  Next: Dynamic Arrays,  Prev: Basic Heap Allocation,  Up: Low-Level Allocation

16.2 Stack Allocation
=====================


File: internals.info,  Node: Dynamic Arrays,  Next: Allocation by Blocks,  Prev: Stack Allocation,  Up: Low-Level Allocation

16.3 Dynamic Arrays
===================

The `Dynarr' type implements a "dynamic array", which is similar to a
standard C array but has no fixed limit on the number of elements it
can contain.  Dynamic arrays can hold elements of any type, and when
you add a new element, the array automatically resizes itself if it
isn't big enough.  Dynarrs are extensively used in the redisplay
mechanism.

   A "dynamic array" is a contiguous array of fixed-size elements where
there is no upper limit (except available memory) on the number of
elements in the array.  Because the elements are maintained
contiguously, space is used efficiently (no per-element pointers
necessary) and random access to a particular element is in constant
time.  At any one point, the block of memory that holds the array has
an upper limit; if this limit is exceeded, the memory is realloc()ed
into a new array that is twice as big.  Assuming that the time to grow
the array is on the order of the new size of the array block, this
scheme has a provably constant amortized time (i.e. average time over
all additions).

   When you add elements or retrieve elements, pointers are used.  Note
that the element itself (of whatever size it is), and not the pointer
to it, is stored in the array; thus you do not have to allocate any
heap memory on your own.  Also, returned pointers are only guaranteed
to be valid until the next operation that changes the length of the
array.

   This is a container object.  Declare a dynamic array of a specific
type as follows:

   typedef struct   {     Dynarr_declare (mytype);   } mytype_dynarr;

   Use the following functions/macros:

     void *Dynarr_new(type)
        [MACRO] Create a new dynamic-array object, with each element of the
        specified type.  The return value is cast to (type##_dynarr).
        This requires following the convention that types are declared in
        such a way that this type concatenation works.  In particular, TYPE
        must be a symbol, not an arbitrary C type.

     Dynarr_add(d, el)
        [MACRO] Add an element to the end of a dynamic array.  EL is a pointer
        to the element; the element itself is stored in the array, however.
        No function call is performed unless the array needs to be resized.

     Dynarr_add_many(d, base, len)
        [MACRO] Add LEN elements to the end of the dynamic array.  The elements
        should be contiguous in memory, starting at BASE.  If BASE if NULL,
        just make space for the elements; don't actually add them.

     Dynarr_insert_many_at_start(d, base, len)
        [MACRO] Append LEN elements to the beginning of the dynamic array.
        The elements should be contiguous in memory, starting at BASE.
        If BASE if NULL, just make space for the elements; don't actually
        add them.

     Dynarr_insert_many(d, base, len, start)
        Insert LEN elements to the dynamic array starting at position
        START.  The elements should be contiguous in memory, starting at BASE.
        If BASE if NULL, just make space for the elements; don't actually
        add them.

     Dynarr_delete(d, i)
        [MACRO] Delete an element from the dynamic array at position I.

     Dynarr_delete_many(d, start, len)
        Delete LEN elements from the dynamic array starting at position
        START.

     Dynarr_delete_by_pointer(d, p)
        [MACRO] Delete an element from the dynamic array at pointer P,
        which must point within the block of memory that stores the data.
        P should be obtained using Dynarr_atp().

     int Dynarr_length(d)
        [MACRO] Return the number of elements currently in a dynamic array.

     int Dynarr_largest(d)
        [MACRO] Return the maximum value that Dynarr_length(d) would
        ever have returned.

     type Dynarr_at(d, i)
        [MACRO] Return the element at the specified index (no bounds checking
        done on the index).  The element itself is returned, not a pointer
        to it.

     type *Dynarr_atp(d, i)
        [MACRO] Return a pointer to the element at the specified index (no
        bounds checking done on the index).  The pointer may not be valid
        after an element is added to or removed from the array.

     Dynarr_reset(d)
        [MACRO] Reset the length of a dynamic array to 0.

     Dynarr_free(d)
        Destroy a dynamic array and the memory allocated to it.

   Use the following global variable:

        Dynarr_min_size
           Minimum allowable size for a dynamic array when it is resized.


File: internals.info,  Node: Allocation by Blocks,  Next: Modules for Allocation,  Prev: Dynamic Arrays,  Up: Low-Level Allocation

16.4 Allocation by Blocks
=========================

The `Blocktype' type efficiently manages the allocation of fixed-size
blocks by minimizing the number of times that `malloc()' and `free()'
are called.  It allocates memory in large chunks, subdivides the chunks
into blocks of the proper size, and returns the blocks as requested.
When blocks are freed, they are placed onto a linked list, so they can
be efficiently reused.  This data type is not much used in XEmacs
currently, because it's a fairly new addition.

   A "block-type object" is used to efficiently allocate and free blocks
of a particular size.  Freed blocks are remembered in a free list and
are reused as necessary to allocate new blocks, so as to avoid as much
as possible making calls to malloc() and free().

   This is a container object.  Declare a block-type object of a
specific type as follows:

   struct mytype_blocktype {   Blocktype_declare (mytype); };

   Use the following functions/macros:

     structype *Blocktype_new(structype)
        [MACRO] Create a new block-type object of the specified type.
        The argument to this call should be the type of object to be
        created, e.g. foobar_blocktype.
     type *Blocktype_alloc(b)
        [MACRO] Allocate a block of the proper type for the specified
        block-type object and return a pointer to it.
     Blocktype_free(b, block)
        Free a block of the type corresponding to the specified block-type
        object.
     Blocktype_delete(b)
        Destroy a block-type object and the memory allocated to it.


File: internals.info,  Node: Modules for Allocation,  Prev: Allocation by Blocks,  Up: Low-Level Allocation

16.5 Modules for Allocation
===========================

     `alloca.c'
     `free-hook.c'
     `getpagesize.h'
     `gmalloc.c'
     `malloc.c'
     `mem-limits.h'
     `ralloc.c'
     `vm-limit.c'

   These handle basic C allocation of memory.  `alloca.c' is an
emulation of the stack allocation function `alloca()' on machines that
lack this. (XEmacs makes extensive use of `alloca()' in its code.)

   `gmalloc.c' and `malloc.c' are two implementations of the standard C
functions `malloc()', `realloc()' and `free()'.  They are often used in
place of the standard system-provided `malloc()' because they usually
provide a much faster implementation, at the expense of additional
memory use.  `gmalloc.c' is a newer implementation that is much more
memory-efficient for large allocations than `malloc.c', and should
always be preferred if it works. (At one point, `gmalloc.c' didn't work
on some systems where `malloc.c' worked; but this should be fixed now.)

   `ralloc.c' is the "relocating allocator".  It provides functions
similar to `malloc()', `realloc()' and `free()' that allocate memory
that can be dynamically relocated in memory.  The advantage of this is
that allocated memory can be shuffled around to place all the free
memory at the end of the heap, and the heap can then be shrunk,
releasing the memory back to the operating system.  The use of this can
be controlled with the configure option `--rel-alloc'; if enabled,
memory allocated for buffers will be relocatable, so that if a very
large file is visited and the buffer is later killed, the memory can be
released to the operating system.  (The disadvantage of this mechanism
is that it can be very slow.  On systems with the `mmap()' system call,
the XEmacs version of `ralloc.c' uses this to move memory around
without actually having to block-copy it, which can speed things up;
but it can still cause noticeable performance degradation.)

   On Linux systems using `glibc 2', these strategies are built in to
the so-called "Doug Lea malloc."  See, for example, Doug Lea's home
page, especially "A Memory Allocator"
(http://gee.cs.oswego.edu/dl/html/malloc.html).  The source file,
`malloc.c' (available at the same place) is copiously (and usefully!)
commented.  Wolfram Gloger's home page (http://www.malloc.de/) may also
be useful.

   `free-hook.c' contains some debugging functions for checking for
invalid arguments to `free()'.

   `vm-limit.c' contains some functions that warn the user when memory
is getting low.  These are callback functions that are called by
`gmalloc.c' and `malloc.c' at appropriate times.

   `getpagesize.h' provides a uniform interface for retrieving the size
of a page in virtual memory.  `mem-limits.h' provides a uniform
interface for retrieving the total amount of available virtual memory.
Both are similar in spirit to the `sys*.h' files described in section
J, below.

     `blocktype.c'
     `blocktype.h'
     `dynarr.c'

   These implement a couple of basic C data types to facilitate memory
allocation.


File: internals.info,  Node: The XEmacs Object System (Abstractly Speaking),  Next: How Lisp Objects Are Represented in C,  Prev: Low-Level Allocation,  Up: Top

17 The XEmacs Object System (Abstractly Speaking)
*************************************************

At the heart of the Lisp interpreter is its management of objects.
XEmacs Lisp contains many built-in objects, some of which are simple
and others of which can be very complex; and some of which are very
common, and others of which are rarely used or are only used
internally. (Since the Lisp allocation system, with its automatic
reclamation of unused storage, is so much more convenient than
`malloc()' and `free()', the C code makes extensive use of it in its
internal operations.)

   The basic Lisp objects are

`integer'
     31 bits of precision, or 63 bits on 64-bit machines; the reason
     for this is described below when the internal Lisp object
     representation is described.

`char'
     An object representing a single character of text; chars behave
     like integers in many ways but are logically considered text
     rather than numbers and have a different read syntax. (the read
     syntax for a char contains the char itself or some textual
     encoding of it--for example, a Japanese Kanji character might be
     encoded as `^[$(B#&^[(B' using the ISO-2022 encoding
     standard--rather than the numerical representation of the char;
     this way, if the mapping between chars and integers changes, which
     is quite possible for Kanji characters and other extended
     characters, the same character will still be created.  Note that
     some primitives confuse chars and integers.  The worst culprit is
     `eq', which makes a special exception and considers a char to be
     `eq' to its integer equivalent, even though in no other case are
     objects of two different types `eq'.  The reason for this
     monstrosity is compatibility with existing code; the separation of
     char from integer came fairly recently.)

`float'
     Same precision as a double in C.

`bignum'
`ratio'
`bigfloat'
     As build-time options, arbitrary-precision numbers are available.
     Bignums are integers, and when available they remove the
     restriction on buffer size.  Ratios are non-integral rational
     numbers.  Bigfloats are arbitrary-precision floating point
     numbers, with precision specified at runtime.

`symbol'
     An object that contains Lisp objects and is referred to by name;
     symbols are used to implement variables and named functions and to
     provide the equivalent of preprocessor constants in C.

`string'
     Self-explanatory; behaves much like a vector of chars but has a
     different read syntax and is stored and manipulated more compactly.

`bit-vector'
     A vector of bits; similar to a string in spirit.

`vector'
     A one-dimensional array of Lisp objects providing constant-time
     access to any of the objects; access to an arbitrary object in a
     vector is faster than for lists, but the operations that can be
     done on a vector are more limited.

`compiled-function'
     An object containing compiled Lisp code, known as "byte code".

`subr'
     A Lisp primitive, i.e. a Lisp-callable function implemented in C.

`cons'
     A simple container for two Lisp objects, used to implement lists
     and most other data structures in Lisp.

   Objects which are not conses are called atoms.

   Note that there is no basic "function" type, as in more powerful
versions of Lisp (where it's called a "closure").  XEmacs Lisp does not
provide the closure semantics implemented by Common Lisp and Scheme.
The guts of a function in XEmacs Lisp are represented in one of four
ways: a symbol specifying another function (when one function is an
alias for another), a list (whose first element must be the symbol
`lambda') containing the function's source code, a compiled-function
object, or a subr object. (In other words, given a symbol specifying
the name of a function, calling `symbol-function' to retrieve the
contents of the symbol's function cell will return one of these types
of objects.)

   XEmacs Lisp also contains numerous specialized objects used to
implement the editor:

`buffer'
     Stores text like a string, but is optimized for insertion and
     deletion and has certain other properties that can be set.

`frame'
     An object with various properties whose displayable representation
     is a "window" in window-system parlance.

`window'
     A section of a frame that displays the contents of a buffer; often
     called a "pane" in window-system parlance.

`window-configuration'
     An object that represents a saved configuration of windows in a
     frame.

`device'
     An object representing a screen on which frames can be displayed;
     equivalent to a "display" in the X Window System and a "TTY" in
     character mode.

`face'
     An object specifying the appearance of text or graphics; it has
     properties such as font, foreground color, and background color.

`marker'
     An object that refers to a particular position in a buffer and
     moves around as text is inserted and deleted to stay in the same
     relative position to the text around it.

`extent'
     Similar to a marker but covers a range of text in a buffer; can
     also specify properties of the text, such as a face in which the
     text is to be displayed, whether the text is invisible or
     unmodifiable, etc.

`event'
     Generated by calling `next-event' and contains information
     describing a particular event happening in the system, such as the
     user pressing a key or a process terminating.

`keymap'
     An object that maps from events (described using lists, vectors,
     and symbols rather than with an event object because the mapping
     is for classes of events, rather than individual events) to
     functions to execute or other events to recursively look up; the
     functions are described by name, using a symbol, or using lists to
     specify the function's code.

`glyph'
     An object that describes the appearance of an image (e.g.  pixmap)
     on the screen; glyphs can be attached to the beginning or end of
     extents and in some future version of XEmacs will be able to be
     inserted directly into a buffer.

`process'
     An object that describes a connection to an externally-running
     process.

   There are some other, less-commonly-encountered general objects:

`hash-table'
     An object that maps from an arbitrary Lisp object to another
     arbitrary Lisp object, using hashing for fast lookup.

`obarray'
     A limited form of hash-table that maps from strings to symbols;
     obarrays are used to look up a symbol given its name and are not
     actually their own object type but are kludgily represented using
     vectors with hidden fields (this representation derives from GNU
     Emacs).

`specifier'
     A complex object used to specify the value of a display property; a
     default value is given and different values can be specified for
     particular frames, buffers, windows, devices, or classes of device.

`char-table'
     An object that maps from chars or classes of chars to arbitrary
     Lisp objects; internally char tables use a complex nested-vector
     representation that is optimized to the way characters are
     represented as integers.

`range-table'
     An object that maps from ranges of integers to arbitrary Lisp
     objects.

   And some strange special-purpose objects:

`charset'
`coding-system'
     Objects used when MULE, or multi-lingual/Asian-language, support is
     enabled.

`color-instance'
`font-instance'
`image-instance'
     An object that encapsulates a window-system resource; instances are
     mostly used internally but are exposed on the Lisp level for
     cleanness of the specifier model and because it's occasionally
     useful for Lisp program to create or query the properties of
     instances.

`subwindow'
     An object that encapsulate a "subwindow" resource, i.e. a
     window-system child window that is drawn into by an external
     process; this object should be integrated into the glyph system
     but isn't yet, and may change form when this is done.

`tooltalk-message'
`tooltalk-pattern'
     Objects that represent resources used in the ToolTalk interprocess
     communication protocol.

`toolbar-button'
     An object used in conjunction with the toolbar.

   And objects that are only used internally:

`opaque'
     A generic object for encapsulating arbitrary memory; this allows
     you the generality of `malloc()' and the convenience of the Lisp
     object system.

`lstream'
     A buffering I/O stream, used to provide a unified interface to
     anything that can accept output or provide input, such as a file
     descriptor, a stdio stream, a chunk of memory, a Lisp buffer, a
     Lisp string, etc.; it's a Lisp object to make its memory
     management more convenient.

`char-table-entry'
     Subsidiary objects in the internal char-table representation.

`extent-auxiliary'
`menubar-data'
`toolbar-data'
     Various special-purpose objects that are basically just used to
     encapsulate memory for particular subsystems, similar to the more
     general "opaque" object.

`symbol-value-forward'
`symbol-value-buffer-local'
`symbol-value-varalias'
`symbol-value-lisp-magic'
     Special internal-only objects that are placed in the value cell of
     a symbol to indicate that there is something special with this
     variable - e.g. it has no value, it mirrors another variable, or
     it mirrors some C variable; there is really only one kind of
     object, called a "symbol-value-magic", but it is sort-of halfway
     kludged into semi-different object types.

   Some types of objects are "permanent", meaning that once created,
they do not disappear until explicitly destroyed, using a function such
as `delete-buffer', `delete-window', `delete-frame', etc.  Others will
disappear once they are not longer used, through the garbage collection
mechanism.  Buffers, frames, windows, devices, and processes are among
the objects that are permanent.  Note that some objects can go both
ways: Faces can be created either way; extents are normally permanent,
but detached extents (extents not referring to any text, as happens to
some extents when the text they are referring to is deleted) are
temporary.  Note that some permanent objects, such as faces and coding
systems, cannot be deleted.  Note also that windows are unique in that
they can be _undeleted_ after having previously been deleted. (This
happens as a result of restoring a window configuration.)

   Many types of objects have a "read syntax", i.e. a way of specifying
an object of that type in Lisp code.  When you load a Lisp file, or
type in code to be evaluated, what really happens is that the function
`read' is called, which reads some text and creates an object based on
the syntax of that text; then `eval' is called, which possibly does
something special; then this loop repeats until there's no more text to
read. (`eval' only actually does something special with symbols, which
causes the symbol's value to be returned, similar to referencing a
variable; and with conses [i.e. lists], which cause a function
invocation.  All other values are returned unchanged.)

   The read syntax

     17297

   converts to an integer whose value is 17297.

     355/113

   converts to a ratio commonly used to approximate _pi_ when ratios
are configured, and otherwise to a symbol whose name is "355/113" (for
backward compatibility).

     1.983e-4

   converts to a float whose value is 1.983e-4, or .0001983.

     ?b

   converts to a char that represents the lowercase letter b.

     ?^[$(B#&^[(B

   (where `^[' actually is an `ESC' character) converts to a particular
Kanji character when using an ISO2022-based coding system for input.
(To decode this goo: `ESC' begins an escape sequence; `ESC $ (' is a
class of escape sequences meaning "switch to a 94x94 character set";
`ESC $ ( B' means "switch to Japanese Kanji"; `#' and `&' collectively
index into a 94-by-94 array of characters [subtract 33 from the ASCII
value of each character to get the corresponding index]; `ESC (' is a
class of escape sequences meaning "switch to a 94 character set"; `ESC
(B' means "switch to US ASCII".  It is a coincidence that the letter
`B' is used to denote both Japanese Kanji and US ASCII.  If the first
`B' were replaced with an `A', you'd be requesting a Chinese Hanzi
character from the GB2312 character set.)

     "foobar"

   converts to a string.

     foobar

   converts to a symbol whose name is `"foobar"'.  This is done by
looking up the string equivalent in the global variable `obarray',
whose contents should be an obarray.  If no symbol is found, a new
symbol with the name `"foobar"' is automatically created and added to
`obarray'; this process is called "interning" the symbol.  

     (foo . bar)

   converts to a cons cell containing the symbols `foo' and `bar'.

     (1 a 2.5)

   converts to a three-element list containing the specified objects
(note that a list is actually a set of nested conses; see the XEmacs
Lisp Reference).

     [1 a 2.5]

   converts to a three-element vector containing the specified objects.

     #[... ... ... ...]

   converts to a compiled-function object (the actual contents are not
shown since they are not relevant here; look at a file that ends with
`.elc' for examples).

     #*01110110

   converts to a bit-vector.

     #s(hash-table ... ...)

   converts to a hash table (the actual contents are not shown).

     #s(range-table ... ...)

   converts to a range table (the actual contents are not shown).

     #s(char-table ... ...)

   converts to a char table (the actual contents are not shown).

   Note that the `#s()' syntax is the general syntax for structures,
which are not really implemented in XEmacs Lisp but should be.

   When an object is printed out (using `print' or a related function),
the read syntax is used, so that the same object can be read in again.

   The other objects do not have read syntaxes, usually because it does
not really make sense to create them in this fashion (i.e.  processes,
where it doesn't make sense to have a subprocess created as a side
effect of reading some Lisp code), or because they can't be created at
all (e.g. subrs).  Permanent objects, as a rule, do not have a read
syntax; nor do most complex objects, which contain too much state to be
easily initialized through a read syntax.


File: internals.info,  Node: How Lisp Objects Are Represented in C,  Next: Allocation of Objects in XEmacs Lisp,  Prev: The XEmacs Object System (Abstractly Speaking),  Up: Top

18 How Lisp Objects Are Represented in C
****************************************

Lisp objects are represented in C using a 32-bit or 64-bit machine word
(depending on the processor; i.e. DEC Alphas use 64-bit Lisp objects and
most other processors use 32-bit Lisp objects).  The representation
stuffs a pointer together with a tag, as follows:

      [ 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 ]
      [ 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 ]

        <---------------------------------------------------------> <->
                 a pointer to a structure, or an integer            tag

   A tag of 00 is used for all pointer object types, a tag of 10 is used
for characters, and the other two tags 01 and 11 are joined together to
form the integer object type.  This representation gives us 31 bit
integers and 30 bit characters, while pointers are represented directly
without any bit masking or shifting.  This representation, though,
assumes that pointers to structs are always aligned to multiples of 4,
so the lower 2 bits are always zero.

   Lisp objects use the typedef `Lisp_Object', but the actual C type
used for the Lisp object can vary.  It can be either a simple type
(`long' on the DEC Alpha, `int' on other machines) or a structure whose
fields are bit fields that line up properly (actually, a union of
structures is used).  Generally the simple integral type is preferable
because it ensures that the compiler will actually use a machine word
to represent the object (some compilers will use more general and less
efficient code for unions and structs even if they can fit in a machine
word).  The union type, however, has the advantage of stricter type
checking.  If you accidentally pass an integer where a Lisp object is
desired, you get a compile error.  The choice of which type to use is
determined by the preprocessor constant `USE_UNION_TYPE' which is
defined via the `--use-union-type' option to `configure'.

   Various macros are used to convert between Lisp_Objects and the
corresponding C type.  Macros of the form `XINT()', `XCHAR()',
`XSTRING()', `XSYMBOL()', do any required bit shifting and/or masking
and cast it to the appropriate type.  `XINT()' needs to be a bit tricky
so that negative numbers are properly sign-extended.  Since integers
are stored left-shifted, if the right-shift operator does an arithmetic
shift (i.e. it leaves the most-significant bit as-is rather than
shifting in a zero, so that it mimics a divide-by-two even for negative
numbers) the shift to remove the tag bit is enough.  This is the case
on all the systems we support.

   Note that when `ERROR_CHECK_TYPECHECK' is defined, the converter
macros become more complicated--they check the tag bits and/or the type
field in the first four bytes of a record type to ensure that the
object is really of the correct type.  This is great for catching places
where an incorrect type is being dereferenced--this typically results
in a pointer being dereferenced as the wrong type of structure, with
unpredictable (and sometimes not easily traceable) results.

   There are similar `XSETTYPE()' macros that construct a Lisp object.
These macros are of the form `XSETTYPE (LVALUE, RESULT)', i.e. they
have to be a statement rather than just used in an expression.  The
reason for this is that standard C doesn't let you "construct" a
structure (but GCC does).  Granted, this sometimes isn't too
convenient; for the case of integers, at least, you can use the
function `make_int()', which constructs and _returns_ an integer Lisp
object.  Note that the `XSETTYPE()' macros are also affected by
`ERROR_CHECK_TYPECHECK' and make sure that the structure is of the
right type in the case of record types, where the type is contained in
the structure.

   The C programmer is responsible for *guaranteeing* that a
Lisp_Object is the correct type before using the `XTYPE' macros.  This
is especially important in the case of lists.  Use `XCAR' and `XCDR' if
a Lisp_Object is certainly a cons cell, else use `Fcar()' and `Fcdr()'.
Trust other C code, but not Lisp code.  On the other hand, if XEmacs
has an internal logic error, it's better to crash immediately, so
sprinkle `assert()'s and "unreachable" `abort()'s liberally about the
source code.  Where performance is an issue, use `type_checking_assert',
`bufpos_checking_assert', and `gc_checking_assert', which do nothing
unless the corresponding configure error checking flag was specified.

   Note that in some cases `assert's will expand to nothing in a
context where that produces an empty statement.  Some compilers will
warn about this.


File: internals.info,  Node: Allocation of Objects in XEmacs Lisp,  Next: The Lisp Reader and Compiler,  Prev: How Lisp Objects Are Represented in C,  Up: Top

19 Allocation of Objects in XEmacs Lisp
***************************************

* Menu:

* Introduction to Allocation::
* Garbage Collection::
* GCPROing::
* Garbage Collection - Step by Step::
* Integers and Characters::
* Allocation from Frob Blocks::
* lrecords::
* Low-level allocation::
* Cons::
* Vector::
* Bit Vector::
* Symbol::
* Marker::
* String::
* Compiled Function::


File: internals.info,  Node: Introduction to Allocation,  Next: Garbage Collection,  Prev: Allocation of Objects in XEmacs Lisp,  Up: Allocation of Objects in XEmacs Lisp

19.1 Introduction to Allocation
===============================

Emacs Lisp, like all Lisps, has garbage collection.  This means that
the programmer never has to explicitly free (destroy) an object; it
happens automatically when the object becomes inaccessible.  Most
experts agree that garbage collection is a necessity in a modern,
high-level language.  Its omission from C stems from the fact that C was
originally designed to be a nice abstract layer on top of assembly
language, for writing kernels and basic system utilities rather than
large applications.

   Lisp objects can be created by any of a number of Lisp primitives.
Most object types have one or a small number of basic primitives for
creating objects.  For conses, the basic primitive is `cons'; for
vectors, the primitives are `make-vector' and `vector'; for symbols,
the primitives are `make-symbol' and `intern'; etc.  Some Lisp objects,
especially those that are primarily used internally, have no
corresponding Lisp primitives.  Every Lisp object, though, has at least
one C primitive for creating it.

   Recall from section (VII) that a Lisp object, as stored in a 32-bit
or 64-bit word, has a few tag bits, and a "value" that occupies the
remainder of the bits.  We can separate the different Lisp object types
into three broad categories:

   * (a) Those for whom the value directly represents the contents of
     the Lisp object.  Only two types are in this category: integers and
     characters.  No special allocation or garbage collection is
     necessary for such objects.  Lisp objects of these types do not
     need to be `GCPRO'ed.

   In the remaining two categories, the type is stored in the object
itself.  The tag for all such objects is the generic "lrecord"
(Lisp_Type_Record) tag.  The first bytes of the object's structure are
an integer (actually a char) characterising the object's type and some
flags, in particular the mark bit used for garbage collection.  A
structure describing the type is accessible thru the
lrecord_implementation_table indexed with said integer.  This structure
includes the method pointers and a pointer to a string naming the type.

   * (b) Those lrecords that are allocated in frob blocks (see above).
     This includes the objects that are most common and relatively
     small, and includes conses, strings, subrs, floats, compiled
     functions, symbols, extents, events, and markers.  With the
     cleanup of frob blocks done in 19.12, it's not terribly hard to
     add more objects to this category, but it's a bit trickier than
     adding an object type to type (c) (esp. if the object needs a
     finalization method), and is not likely to save much space unless
     the object is small and there are many of them. (In fact, if there
     are very few of them, it might actually waste space.)

   * (c) Those lrecords that are individually `malloc()'ed.  These are
     called "lcrecords".  All other types are in this category.  Adding
     a new type to this category is comparatively easy, and all types
     added since 19.8 (when the current allocation scheme was devised,
     by Richard Mlynarik), with the exception of the character type,
     have been in this category.

   Note that bit vectors are a bit of a special case.  They are simple
lrecords as in category (b), but are individually `malloc()'ed like
vectors.  You can basically view them as exactly like vectors except
that their type is stored in lrecord fashion rather than in
directly-tagged fashion.


File: internals.info,  Node: Garbage Collection,  Next: GCPROing,  Prev: Introduction to Allocation,  Up: Allocation of Objects in XEmacs Lisp

19.2 Garbage Collection
=======================

Garbage collection is simple in theory but tricky to implement.  Emacs
Lisp uses the oldest garbage collection method, called "mark and
sweep".  Garbage collection begins by starting with all accessible
locations (i.e. all variables and other slots where Lisp objects might
occur) and recursively traversing all objects accessible from those
slots, marking each one that is found.  We then go through all of
memory and free each object that is not marked, and unmarking each
object that is marked.  Note that "all of memory" means all currently
allocated objects.  Traversing all these objects means traversing all
frob blocks, all vectors (which are chained in one big list), and all
lcrecords (which are likewise chained).

   Garbage collection can be invoked explicitly by calling
`garbage-collect' but is also called automatically by `eval', once a
certain amount of memory has been allocated since the last garbage
collection (according to `gc-cons-threshold').


File: internals.info,  Node: GCPROing,  Next: Garbage Collection - Step by Step,  Prev: Garbage Collection,  Up: Allocation of Objects in XEmacs Lisp

19.3 `GCPRO'ing
===============

`GCPRO'ing is one of the ugliest and trickiest parts of Emacs
internals.  The basic idea is that whenever garbage collection occurs,
all in-use objects must be reachable somehow or other from one of the
roots of accessibility.  The roots of accessibility are:

  1. All objects that have been `staticpro()'d or
     `staticpro_nodump()'ed.  This is used for any global C variables
     that hold Lisp objects.  A call to `staticpro()' happens implicitly
     as a result of any symbols declared with `defsymbol()' and any
     variables declared with `DEFVAR_FOO()'.  You need to explicitly
     call `staticpro()' (in the `vars_of_foo()' method of a module) for
     other global C variables holding Lisp objects. (This typically
     includes internal lists and such things.).  Use
     `staticpro_nodump()' only in the rare cases when you do not want
     the pointed variable to be saved at dump time but rather recompute
     it at startup.

     Note that `obarray' is one of the `staticpro()'d things.
     Therefore, all functions and variables get marked through this.

  2. Any shadowed bindings that are sitting on the `specpdl' stack.

  3. Any objects sitting in currently active (Lisp) stack frames,
     catches, and condition cases.

  4. A couple of special-case places where active objects are located.

  5. Anything currently marked with `GCPRO'.

   Marking with `GCPRO' is necessary because some C functions (quite a
lot, in fact), allocate objects during their operation.  Quite
frequently, there will be no other pointer to the object while the
function is running, and if a garbage collection occurs and the object
needs to be referenced again, bad things will happen.  The solution is
to mark those references with `GCPRO'.  Note that it is a _reference_
that is marked with `GCPRO', not an object.  If you declare a
`Lisp_Object' variable, assign to it, `GCPRO' it, and then assign to it
again, the first object assigned _is not_ protected, while the second
object _is_ protected.  Unfortunately `GCPRO'ing is easy to forget, and
there is basically no way around this problem.  Here are some rules,
though:

  1. A garbage collection can occur whenever anything calls `Feval', or
     whenever a `QUIT' can occur where execution can continue past
     this. (Remember, this is almost anywhere.)  Note that `Fsignal' can
     GC, and it can return (even though it normally doesn't).  This
     means that you must `GCPRO' before calling most of the error
     functions, including the `CONCHECK' family of macros, if
     references occur after the call.

  2. You _must_ `UNGCPRO' anything that's `GCPRO'ed, and you _must not_
     `UNGCPRO' if you haven't `GCPRO'ed.  Getting either of these wrong
     will lead to crashes, often in completely random places unrelated
     to where the problem lies.  There are some functions (`Fsignal' is
     the canonical example) which may or may not return.  In these
     cases, the function is responsible for cleaning up the `GCPRO's if
     it doesn't return, so you should treat it as an ordinary function.

  3. For every `GCPRON', there have to be declarations of `struct gcpro
     gcpro1, gcpro2, ..., gcproN'.

  4. The way this actually works is that all currently active `GCPRO's
     are chained through the `struct gcpro' local variables, with the
     variable `gcprolist' pointing to the head of the list and the nth
     local `gcpro' variable pointing to the first `gcpro' variable in
     the next enclosing stack frame.  Each `GCPRO'ed thing is an
     lvalue, and the `struct gcpro' local variable contains a pointer to
     this lvalue.  This is why things will mess up badly if you don't
     pair up the `GCPRO's and `UNGCPRO's--you will end up with
     `gcprolist's containing pointers to `struct gcpro's or local
     `Lisp_Object' variables in no-longer-active stack frames.

  5. It is actually possible for a single `struct gcpro' to protect a
     contiguous array of any number of values, rather than just a
     single lvalue.  To effect this, call `GCPRON' as usual on the
     first object in the array and then set `gcproN.nvars'.

  6. *Strings are relocated.*  What this means in practice is that the
     pointer obtained using `XSTRING_DATA()' is liable to change at any
     time, and you should never keep it around past any function call,
     or pass it as an argument to any function that might cause a
     garbage collection.  This is why a number of functions accept
     either a "non-relocatable" `char *' pointer or a relocatable Lisp
     string, and only access the Lisp string's data at the very last
     minute.  In some cases, you may end up having to `alloca()' some
     space and copy the string's data into it.

  7. By convention, if you have to nest `GCPRO''s, use `NGCPRON' (along
     with `struct gcpro ngcpro1, ngcpro2', etc.), `NNGCPRON', etc.
     This avoids compiler warnings about shadowed locals.

  8. It is _always_ better to err on the side of extra `GCPRO's rather
     than too few.  The extra cycles spent on this are almost never
     going to make a whit of difference in the speed of anything.

  9. The general rule to follow is that caller, not callee, `GCPRO's.
     That is, you should not have to explicitly `GCPRO' any Lisp objects
     that are passed in as parameters.

     One exception from this rule is if you ever plan to change the
     parameter value, and store a new object in it.  In that case, you
     _must_ `GCPRO' the parameter, because otherwise the new object
     will not be protected.

     So, if you create any Lisp objects (remember, this happens in all
     sorts of circumstances, e.g. with `Fcons()', etc.), you are
     responsible for `GCPRO'ing them, unless you are _absolutely sure_
     that there's no possibility that a garbage-collection can occur
     while you need to use the object.  Even then, consider `GCPRO'ing.

 10. If you have the _least smidgeon of doubt_ about whether you need
     to `GCPRO', you should `GCPRO'.

 11. Beware of `GCPRO'ing something that is uninitialized.  If you have
     any shade of doubt about this, initialize all your variables to
     `Qnil'.

 12. Be careful of traps, like calling `Fcons()' in the argument to
     another function.  By the "caller protects" law, you should be
     `GCPRO'ing the newly-created cons, but you aren't.  A certain
     number of functions that are commonly called on freshly created
     stuff (e.g. `nconc2()', `Fsignal()'), break the "caller protects"
     law and go ahead and `GCPRO' their arguments so as to simplify
     things, but make sure and check if it's OK whenever doing
     something like this.

 13. Once again, remember to `GCPRO'!  Bugs resulting from insufficient
     `GCPRO'ing are intermittent and extremely difficult to track down,
     often showing up in crashes inside of `garbage-collect' or in
     weirdly corrupted objects or even in incorrect values in a totally
     different section of code.

   If you don't understand whether to `GCPRO' in a particular instance,
ask on the mailing lists.  A general hint is that `prog1' is the
canonical example.

   Given the extremely error-prone nature of the `GCPRO' scheme, and
the difficulties in tracking down, it should be considered a deficiency
in the XEmacs code.  A solution to this problem would involve
implementing so-called "conservative" garbage collection for the C
stack.  That involves looking through all of stack memory and treating
anything that looks like a reference to an object as a reference.  This
will result in a few objects not getting collected when they should, but
it obviates the need for `GCPRO'ing, and allows garbage collection to
happen at any point at all, such as during object allocation.

