Resorted; add missing Morohashi's Daikanwa characters; add missing
[chise/xemacs-chise.git-] / src / buffer.c
1 /* Buffer manipulation primitives for XEmacs.
2    Copyright (C) 1985-1989, 1992-1995 Free Software Foundation, Inc.
3    Copyright (C) 1995 Sun Microsystems, Inc.
4    Copyright (C) 1995, 1996 Ben Wing.
5
6 This file is part of XEmacs.
7
8 XEmacs is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12
13 XEmacs is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with XEmacs; see the file COPYING.  If not, write to
20 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA.  */
22
23 /* Synched up with: Mule 2.0, FSF 19.30. */
24
25 /* Authorship:
26
27    FSF: long ago.
28    JWZ: some changes for Lemacs, long ago. (e.g. separate buffer
29         list per frame.)
30    Mly: a few changes for buffer-local vars, 19.8 or 19.9.
31    Ben Wing: some changes and cleanups for Mule, 19.12.
32  */
33
34 /* This file contains functions that work with buffer objects.
35    Functions that manipulate a buffer's text, however, are not
36    in this file:
37
38    1) The low-level functions that actually know about the
39       implementation of a buffer's text are located in insdel.c.
40    2) The higher-level (mostly Lisp) functions that manipulate a
41       buffer's text are in editfns.c.
42    3) The highest-level Lisp commands are in cmds.c.
43
44    However:
45
46    -- Functions that know about syntax tables (forward-word,
47       scan-sexps, etc.) are in syntax.c, as are functions
48       that manipulate syntax tables.
49    -- Functions that know about case tables (upcase, downcase,
50       etc.) are in casefiddle.c.  Functions that manipulate
51       case tables (case-table-p, set-case-table, etc.) are
52       in casetab.c.
53    -- Functions that do searching and replacing are in
54       search.c.  The low-level functions that implement
55       regular expressions are in regex.c.
56
57    Also:
58
59    -- Some file and process functions (in fileio.c and process.c)
60       copy text from or insert text into a buffer; they call
61       low-level functions in insdel.c to do this.
62    -- insdel.c calls low-level functions in undo.c and extents.c
63       to record buffer modifications for undoing and to handle
64       extent adjustment and extent-data creation and insertion.
65
66 */
67
68 #include <config.h>
69 #include "lisp.h"
70
71 #include "buffer.h"
72 #include "chartab.h"
73 #include "commands.h"
74 #include "elhash.h"
75 #include "extents.h"
76 #include "faces.h"
77 #ifdef FILE_CODING
78 #include "file-coding.h"
79 #endif
80 #include "frame.h"
81 #include "insdel.h"
82 #include "lstream.h"
83 #include "process.h"            /* for kill_buffer_processes */
84 #ifdef REGION_CACHE_NEEDS_WORK
85 #include "region-cache.h"
86 #endif
87 #include "specifier.h"
88 #include "syntax.h"
89 #include "sysdep.h"     /* for getwd */
90 #include "window.h"
91
92 #include "sysfile.h"
93
94 struct buffer *current_buffer;  /* the current buffer */
95
96 /* This structure holds the default values of the buffer-local variables
97    defined with DEFVAR_BUFFER_LOCAL, that have special slots in each buffer.
98    The default value occupies the same slot in this structure
99    as an individual buffer's value occupies in that buffer.
100    Setting the default value also goes through the alist of buffers
101    and stores into each buffer that does not say it has a local value.  */
102 Lisp_Object Vbuffer_defaults;
103 static void *buffer_defaults_saved_slots;
104
105 /* This structure marks which slots in a buffer have corresponding
106    default values in Vbuffer_defaults.
107    Each such slot has a nonzero value in this structure.
108    The value has only one nonzero bit.
109
110    When a buffer has its own local value for a slot,
111    the bit for that slot (found in the same slot in this structure)
112    is turned on in the buffer's local_var_flags slot.
113
114    If a slot in this structure is 0, then there is a DEFVAR_BUFFER_LOCAL
115    for the slot, but there is no default value for it; the corresponding
116    slot in Vbuffer_defaults is not used except to initialize newly-created
117    buffers.
118
119    If a slot is -1, then there is a DEFVAR_BUFFER_LOCAL for it
120    as well as a default value which is used to initialize newly-created
121    buffers and as a reset-value when local-vars are killed.
122
123    If a slot is -2, there is no DEFVAR_BUFFER_LOCAL for it.
124    (The slot is always local, but there's no lisp variable for it.)
125    The default value is only used to initialize newly-creation buffers.
126
127    If a slot is -3, then there is no DEFVAR_BUFFER_LOCAL for it but
128    there is a default which is used to initialize newly-creation
129    buffers and as a reset-value when local-vars are killed.  */
130 struct buffer buffer_local_flags;
131
132 /* This is the initial (startup) directory, as used for the *scratch* buffer.
133    We're making this a global to make others aware of the startup directory.
134    `initial_directory' is stored in external format.
135  */
136 char initial_directory[MAXPATHLEN+1];
137
138 /* This structure holds the names of symbols whose values may be
139    buffer-local.  It is indexed and accessed in the same way as the above. */
140 static Lisp_Object Vbuffer_local_symbols;
141 static void *buffer_local_symbols_saved_slots;
142
143 /* Alist of all buffer names vs the buffers. */
144 /* This used to be a variable, but is no longer,
145    to prevent lossage due to user rplac'ing this alist or its elements.
146    Note that there is a per-frame copy of this as well; the frame slot
147    and the global variable contain the same data, but possibly in different
148    orders, so that the buffer ordering can be per-frame.
149   */
150 Lisp_Object Vbuffer_alist;
151
152 /* Functions to call before and after each text change. */
153 Lisp_Object Qbefore_change_functions;
154 Lisp_Object Qafter_change_functions;
155 Lisp_Object Vbefore_change_functions;
156 Lisp_Object Vafter_change_functions;
157
158 /* #### Obsolete, for compatibility */
159 Lisp_Object Qbefore_change_function;
160 Lisp_Object Qafter_change_function;
161 Lisp_Object Vbefore_change_function;
162 Lisp_Object Vafter_change_function;
163
164 #if 0 /* FSFmacs */
165 Lisp_Object Vtransient_mark_mode;
166 #endif
167
168 /* t means ignore all read-only text properties.
169    A list means ignore such a property if its value is a member of the list.
170    Any non-nil value means ignore buffer-read-only.  */
171 Lisp_Object Vinhibit_read_only;
172
173 /* List of functions to call that can query about killing a buffer.
174    If any of these functions returns nil, we don't kill it.  */
175 Lisp_Object Vkill_buffer_query_functions;
176
177 /* Non-nil means delete a buffer's auto-save file when the buffer is saved. */
178 int delete_auto_save_files;
179
180 Lisp_Object Qbuffer_live_p;
181 Lisp_Object Qbuffer_or_string_p;
182
183 /* List of functions to call before changing an unmodified buffer.  */
184 Lisp_Object Vfirst_change_hook;
185 Lisp_Object Qfirst_change_hook;
186
187 Lisp_Object Qfundamental_mode;
188 Lisp_Object Qmode_class;
189 Lisp_Object Qpermanent_local;
190
191 Lisp_Object Qprotected_field;
192
193 Lisp_Object QSFundamental;      /* A string "Fundamental" */
194 Lisp_Object QSscratch;          /* "*scratch*" */
195 Lisp_Object Qdefault_directory;
196
197 Lisp_Object Qkill_buffer_hook;
198
199 Lisp_Object Qrename_auto_save_file;
200
201 Lisp_Object Qget_file_buffer;
202 Lisp_Object Qchange_major_mode_hook, Vchange_major_mode_hook;
203
204 Lisp_Object Qfind_file_compare_truenames;
205
206 Lisp_Object Qswitch_to_buffer;
207
208 /* Two thresholds controlling how much undo information to keep.  */
209 int undo_threshold;
210 int undo_high_threshold;
211
212 int find_file_compare_truenames;
213 int find_file_use_truenames;
214
215 \f
216 static void reset_buffer_local_variables (struct buffer *, int first_time);
217 static void nuke_all_buffer_slots (struct buffer *b, Lisp_Object zap);
218
219 Lisp_Object
220 make_buffer (struct buffer *buf)
221 {
222   Lisp_Object obj;
223   XSETBUFFER (obj, buf);
224   return obj;
225 }
226
227 static Lisp_Object
228 mark_buffer (Lisp_Object obj)
229 {
230   struct buffer *buf = XBUFFER (obj);
231
232   /* Truncate undo information. */
233   buf->undo_list = truncate_undo_list (buf->undo_list,
234                                        undo_threshold,
235                                        undo_high_threshold);
236
237 #define MARKED_SLOT(x) mark_object (buf->x)
238 #include "bufslots.h"
239 #undef MARKED_SLOT
240
241   mark_object (buf->extent_info);
242   if (buf->text)
243     mark_object (buf->text->line_number_cache);
244
245   /* Don't mark normally through the children slot.
246      (Actually, in this case, it doesn't matter.)  */
247   if (! EQ (buf->indirect_children, Qnull_pointer))
248     mark_conses_in_list (buf->indirect_children);
249
250   return buf->base_buffer ? make_buffer (buf->base_buffer) : Qnil;
251 }
252
253 static void
254 print_buffer (Lisp_Object obj, Lisp_Object printcharfun, int escapeflag)
255 {
256   struct buffer *b = XBUFFER (obj);
257
258   if (print_readably)
259     {
260       if (!BUFFER_LIVE_P (b))
261         error ("printing unreadable object #<killed buffer>");
262       else
263         error ("printing unreadable object #<buffer %s>",
264                XSTRING_DATA (b->name));
265     }
266   else if (!BUFFER_LIVE_P (b))
267     write_c_string ("#<killed buffer>", printcharfun);
268   else if (escapeflag)
269     {
270       write_c_string ("#<buffer ", printcharfun);
271       print_internal (b->name, printcharfun, 1);
272       write_c_string (">", printcharfun);
273     }
274   else
275     {
276       print_internal (b->name, printcharfun, 0);
277     }
278 }
279
280 /* We do not need a finalize method to handle a buffer's children list
281    because all buffers have `kill-buffer' applied to them before
282    they disappear, and the children removal happens then. */
283 DEFINE_LRECORD_IMPLEMENTATION ("buffer", buffer,
284                                mark_buffer, print_buffer, 0, 0, 0, 0,
285                                struct buffer);
286 \f
287 DEFUN ("bufferp", Fbufferp, 1, 1, 0, /*
288 Return t if OBJECT is an editor buffer.
289 */
290        (object))
291 {
292   return BUFFERP (object) ? Qt : Qnil;
293 }
294
295 DEFUN ("buffer-live-p", Fbuffer_live_p, 1, 1, 0, /*
296 Return t if OBJECT is an editor buffer that has not been deleted.
297 */
298        (object))
299 {
300   return BUFFERP (object) && BUFFER_LIVE_P (XBUFFER (object)) ? Qt : Qnil;
301 }
302
303 static void
304 nsberror (Lisp_Object spec)
305 {
306   if (STRINGP (spec))
307     error ("No buffer named %s", XSTRING_DATA (spec));
308   signal_simple_error ("Invalid buffer argument", spec);
309 }
310
311 DEFUN ("buffer-list", Fbuffer_list, 0, 1, 0, /*
312 Return a list of all existing live buffers.
313 The order is specific to the selected frame; if the optional FRAME
314 argument is provided, the ordering for that frame is returned instead.
315 If the FRAME argument is t, then the global (non-frame) ordering is
316 returned instead.
317 */
318        (frame))
319 {
320   return Fmapcar (Qcdr,
321                   EQ (frame, Qt) ? Vbuffer_alist :
322                   decode_frame (frame)->buffer_alist);
323 }
324
325 Lisp_Object
326 get_buffer (Lisp_Object name, int error_if_deleted_or_does_not_exist)
327 {
328   if (BUFFERP (name))
329     {
330       if (!BUFFER_LIVE_P (XBUFFER (name)))
331         {
332           if (error_if_deleted_or_does_not_exist)
333             nsberror (name);
334           return Qnil;
335         }
336       return name;
337     }
338   else
339     {
340       Lisp_Object buf;
341       struct gcpro gcpro1;
342
343       CHECK_STRING (name);
344       name = LISP_GETTEXT (name); /* I18N3 */
345       GCPRO1 (name);
346       buf = Fcdr (Fassoc (name, Vbuffer_alist));
347       UNGCPRO;
348       if (NILP (buf) && error_if_deleted_or_does_not_exist)
349         nsberror (name);
350       return buf;
351     }
352 }
353
354 struct buffer *
355 decode_buffer (Lisp_Object buffer, int allow_string)
356 {
357   if (NILP (buffer))
358     return current_buffer;
359
360   if (allow_string && STRINGP (buffer))
361     return XBUFFER (get_buffer (buffer, 1));
362
363   CHECK_LIVE_BUFFER (buffer);
364   return XBUFFER (buffer);
365 }
366
367 DEFUN ("decode-buffer", Fdecode_buffer, 1, 1, 0, /*
368 Validate BUFFER or if BUFFER is nil, return the current buffer.
369 If BUFFER is a valid buffer or a string representing a valid buffer,
370 the corresponding buffer object will be returned.  Otherwise an error
371 will be signaled.
372 */
373        (buffer))
374 {
375   struct buffer *b = decode_buffer (buffer, 1);
376   XSETBUFFER (buffer, b);
377   return buffer;
378 }
379
380 #if 0 /* FSFmacs */
381 /* bleagh!!! */
382 /* Like Fassoc, but use Fstring_equal to compare
383    (which ignores text properties),
384    and don't ever QUIT.  */
385
386 static Lisp_Object
387 assoc_ignore_text_properties (REGISTER Lisp_Object key, Lisp_Object list)
388 {
389   REGISTER Lisp_Object tail;
390   for (tail = list; !NILP (tail); tail = Fcdr (tail))
391     {
392       REGISTER Lisp_Object elt, tem;
393       elt = Fcar (tail);
394       tem = Fstring_equal (Fcar (elt), key);
395       if (!NILP (tem))
396         return elt;
397     }
398   return Qnil;
399 }
400
401 #endif /* FSFmacs */
402
403 DEFUN ("get-buffer", Fget_buffer, 1, 1, 0, /*
404 Return the buffer named NAME (a string).
405 If there is no live buffer named NAME, return nil.
406 NAME may also be a buffer; if so, the value is that buffer.
407 */
408        (name))
409 {
410 #ifdef I18N3
411   /* #### Doc string should indicate that the buffer name will get
412      translated. */
413 #endif
414
415   /* #### This might return a dead buffer.  This is gross.  This is
416      called FSF compatibility. */
417   if (BUFFERP (name))
418     return name;
419   return get_buffer (name, 0);
420   /* FSFmacs 19.29 calls assoc_ignore_text_properties() here.
421      Bleagh!! */
422 }
423
424 \f
425 DEFUN ("get-file-buffer", Fget_file_buffer, 1, 1, 0, /*
426 Return the buffer visiting file FILENAME (a string).
427 The buffer's `buffer-file-name' must match exactly the expansion of FILENAME.
428 If there is no such live buffer, return nil.
429
430 Normally, the comparison is done by canonicalizing FILENAME (using
431 `expand-file-name') and comparing that to the value of `buffer-file-name'
432 for each existing buffer.  However,  If `find-file-compare-truenames' is
433 non-nil, FILENAME will be converted to its truename and the search will be
434 done on each buffer's value of `buffer-file-truename' instead of
435 `buffer-file-name'.  Otherwise, if `find-file-use-truenames' is non-nil,
436 FILENAME will be converted to its truename and used for searching, but
437 the search will still be done on `buffer-file-name'.
438 */
439        (filename))
440 {
441   /* This function can GC.  GC checked 1997.04.06. */
442   REGISTER Lisp_Object buf;
443   struct gcpro gcpro1;
444
445 #ifdef I18N3
446   /* DO NOT translate the filename. */
447 #endif
448   GCPRO1 (filename);
449   CHECK_STRING (filename);
450   filename = Fexpand_file_name (filename, Qnil);
451   {
452     /* If the file name has special constructs in it,
453        call the corresponding file handler.  */
454     Lisp_Object handler = Ffind_file_name_handler (filename, Qget_file_buffer);
455     if (!NILP (handler))
456       {
457         UNGCPRO;
458         return call2 (handler, Qget_file_buffer, filename);
459       }
460   }
461   UNGCPRO;
462
463   if (find_file_compare_truenames || find_file_use_truenames)
464     {
465       struct gcpro ngcpro1, ngcpro2, ngcpro3;
466       Lisp_Object fn = Qnil;
467       Lisp_Object dn = Qnil;
468
469       NGCPRO3 (fn, dn, filename);
470       fn = Ffile_truename (filename, Qnil);
471       if (NILP (fn))
472         {
473           dn = Ffile_name_directory (filename);
474           fn = Ffile_truename (dn, Qnil);
475           if (! NILP (fn)) dn = fn;
476           fn = Fexpand_file_name (Ffile_name_nondirectory (filename),
477                                   dn);
478         }
479       filename = fn;
480       NUNGCPRO;
481     }
482
483   {
484     Lisp_Object elt;
485     LIST_LOOP_2 (elt, Vbuffer_alist)
486       {
487         buf = Fcdr (elt);
488         if (!BUFFERP (buf)) continue;
489         if (!STRINGP (XBUFFER (buf)->filename)) continue;
490         if (!NILP (Fstring_equal (filename,
491                                   (find_file_compare_truenames
492                                    ? XBUFFER (buf)->file_truename
493                                    : XBUFFER (buf)->filename))))
494           return buf;
495       }
496   }
497   return Qnil;
498 }
499
500
501 static void
502 push_buffer_alist (Lisp_Object name, Lisp_Object buf)
503 {
504   Lisp_Object cons = Fcons (name, buf);
505   Lisp_Object frmcons, devcons, concons;
506
507   Vbuffer_alist = nconc2 (Vbuffer_alist, Fcons (cons, Qnil));
508   FRAME_LOOP_NO_BREAK (frmcons, devcons, concons)
509     {
510       struct frame *f;
511       f = XFRAME (XCAR (frmcons));
512       f->buffer_alist = nconc2 (f->buffer_alist, Fcons (cons, Qnil));
513     }
514 }
515
516 static void
517 delete_from_buffer_alist (Lisp_Object buf)
518 {
519   Lisp_Object cons = Frassq (buf, Vbuffer_alist);
520   Lisp_Object frmcons, devcons, concons;
521   if (NILP (cons))
522     return; /* abort() ? */
523   Vbuffer_alist = delq_no_quit (cons, Vbuffer_alist);
524
525   FRAME_LOOP_NO_BREAK (frmcons, devcons, concons)
526     {
527       struct frame *f;
528       f = XFRAME (XCAR (frmcons));
529       f->buffer_alist = delq_no_quit (cons, f->buffer_alist);
530     }
531 }
532
533 Lisp_Object
534 get_truename_buffer (REGISTER Lisp_Object filename)
535 {
536   /* FSFmacs has its own code here and doesn't call get-file-buffer.
537      That's because their equivalent of find-file-compare-truenames
538      (find-file-existing-other-name) isn't looked at in get-file-buffer.
539      This way is more correct. */
540   int count = specpdl_depth ();
541
542   specbind (Qfind_file_compare_truenames, Qt);
543   return unbind_to (count, Fget_file_buffer (filename));
544 }
545
546 static struct buffer *
547 allocate_buffer (void)
548 {
549   struct buffer *b = alloc_lcrecord_type (struct buffer, &lrecord_buffer);
550
551   copy_lcrecord (b, XBUFFER (Vbuffer_defaults));
552
553   return b;
554 }
555
556 static Lisp_Object
557 finish_init_buffer (struct buffer *b, Lisp_Object name)
558 {
559   Lisp_Object buf;
560
561   XSETBUFFER (buf, b);
562
563   name = Fcopy_sequence (name);
564   /* #### This really does not need to be called.  We already
565      initialized the buffer-local variables in allocate_buffer().
566      local_var_alist is set to Qnil at the same point, in
567      nuke_all_buffer_slots(). */
568   reset_buffer_local_variables (b, 1);
569   b->directory = current_buffer ? current_buffer->directory : Qnil;
570
571   b->last_window_start = 1;
572
573   b->name = name;
574   if (string_byte (XSTRING (name), 0) != ' ')
575     b->undo_list = Qnil;
576   else
577     b->undo_list = Qt;
578
579   /* initialize the extent list */
580   init_buffer_extents (b);
581
582   /* Put this in the alist of all live buffers.  */
583   push_buffer_alist (name, buf);
584
585   init_buffer_markers (b);
586
587   b->generated_modeline_string = Fmake_string (make_int (84), make_int (' '));
588   b->modeline_extent_table = make_lisp_hash_table (20, HASH_TABLE_KEY_WEAK,
589                                                    HASH_TABLE_EQ);
590
591   return buf;
592 }
593
594 DEFUN ("get-buffer-create", Fget_buffer_create, 1, 1, 0, /*
595 Return the buffer named NAME, or create such a buffer and return it.
596 A new buffer is created if there is no live buffer named NAME.
597 If NAME starts with a space, the new buffer does not keep undo information.
598 If NAME is a buffer instead of a string, then it is the value returned.
599 The value is never nil.
600 */
601        (name))
602 {
603   /* This function can GC */
604   Lisp_Object buf;
605   REGISTER struct buffer *b;
606
607 #ifdef I18N3
608   /* #### Doc string should indicate that the buffer name will get
609      translated. */
610 #endif
611
612   name = LISP_GETTEXT (name);
613   buf = Fget_buffer (name);
614   if (!NILP (buf))
615     return buf;
616
617   if (XSTRING_LENGTH (name) == 0)
618     error ("Empty string for buffer name is not allowed");
619
620   b = allocate_buffer ();
621
622   b->text = &b->own_text;
623   b->base_buffer = 0;
624   b->indirect_children = Qnil;
625   init_buffer_text (b);
626
627   return finish_init_buffer (b, name);
628 }
629
630 DEFUN ("make-indirect-buffer", Fmake_indirect_buffer, 2, 2,
631        "bMake indirect buffer (to buffer): \nBName of indirect buffer: ", /*
632 Create and return an indirect buffer for buffer BASE, named NAME.
633 BASE should be an existing buffer (or buffer name).
634 NAME should be a string which is not the name of an existing buffer.
635 If BASE is an indirect buffer itself, the base buffer for that buffer
636  is made the base buffer for the newly created buffer. (Thus, there will
637  never be indirect buffers whose base buffers are themselves indirect.)
638 */
639        (base_buffer, name))
640 {
641   /* This function can GC */
642
643   /* #### The above interactive specification is totally bogus,
644      because it offers an existing buffer as default answer to the
645      second question.  However, the second argument may not BE an
646      existing buffer!  */
647   struct buffer *b;
648
649   base_buffer = get_buffer (base_buffer, 1);
650
651 #ifdef I18N3
652   /* #### Doc string should indicate that the buffer name will get
653      translated. */
654 #endif
655   CHECK_STRING (name);
656   name = LISP_GETTEXT (name);
657   if (!NILP (Fget_buffer (name)))
658     signal_simple_error ("Buffer name already in use", name);
659   if (XSTRING_LENGTH (name) == 0)
660     error ("Empty string for buffer name is not allowed");
661
662   b = allocate_buffer ();
663
664   b->base_buffer = BUFFER_BASE_BUFFER (XBUFFER (base_buffer));
665
666   /* Use the base buffer's text object.  */
667   b->text = b->base_buffer->text;
668   b->indirect_children = Qnil;
669   b->base_buffer->indirect_children =
670     Fcons (make_buffer (b), b->base_buffer->indirect_children);
671   init_buffer_text (b);
672
673   return finish_init_buffer (b, name);
674 }
675
676
677 \f
678 static void
679 reset_buffer_local_variables (struct buffer *b, int first_time)
680 {
681   struct buffer *def = XBUFFER (Vbuffer_defaults);
682
683   b->local_var_flags = 0;
684   /* For each slot that has a default value,
685      copy that into the slot.  */
686 #define MARKED_SLOT(slot)                                               \
687   { int mask = XINT (buffer_local_flags.slot);                          \
688     if ((mask > 0 || mask == -1 || mask == -3)                          \
689         && (first_time                                                  \
690             || NILP (Fget (XBUFFER (Vbuffer_local_symbols)->slot,       \
691                            Qpermanent_local, Qnil))))                   \
692       b->slot = def->slot;                                              \
693   }
694 #include "bufslots.h"
695 #undef MARKED_SLOT
696 #if 0
697 #define STRING256_P(obj) \
698   (STRINGP (obj) && XSTRING_CHAR_LENGTH (obj) == 256)
699   /* If the standard case table has been altered and invalidated,
700      fix up its insides first.  */
701   if (!(STRING256_P(Vascii_upcase_table) &&
702         STRING256_P(Vascii_canon_table) &&
703         STRING256_P(Vascii_eqv_table)))
704     {
705       Fset_standard_case_table (Vascii_downcase_table);
706     }
707   b->downcase_table = Vascii_downcase_table;
708   b->upcase_table = Vascii_upcase_table;
709   b->case_canon_table = Vascii_canon_table;
710   b->case_eqv_table = Vascii_eqv_table;
711 #ifdef MULE
712   b->mirror_downcase_table = Vmirror_ascii_downcase_table;
713   b->mirror_upcase_table = Vmirror_ascii_upcase_table;
714   b->mirror_case_canon_table = Vmirror_ascii_canon_table;
715   b->mirror_case_eqv_table = Vmirror_ascii_eqv_table;
716 #endif
717 #endif
718 }
719
720 \f
721 /* We split this away from generate-new-buffer, because rename-buffer
722    and set-visited-file-name ought to be able to use this to really
723    rename the buffer properly.  */
724
725 DEFUN ("generate-new-buffer-name", Fgenerate_new_buffer_name, 1, 2, 0, /*
726 Return a string that is the name of no existing buffer based on NAME.
727 If there is no live buffer named NAME, then return NAME.
728 Otherwise modify name by appending `<NUMBER>', incrementing NUMBER
729 until an unused name is found, and then return that name.
730 Optional second argument IGNORE specifies a name that is okay to use
731 \(if it is in the sequence to be tried)
732 even if a buffer with that name exists.
733 */
734        (name, ignore))
735 {
736   REGISTER Lisp_Object gentemp, tem;
737   int count;
738   char number[10];
739
740   CHECK_STRING (name);
741
742   name = LISP_GETTEXT (name);
743 #ifdef I18N3
744   /* #### Doc string should indicate that the buffer name will get
745      translated. */
746 #endif
747
748   tem = Fget_buffer (name);
749   if (NILP (tem))
750     return name;
751
752   count = 1;
753   while (1)
754     {
755       sprintf (number, "<%d>", ++count);
756       gentemp = concat2 (name, build_string (number));
757       if (!NILP (ignore))
758         {
759           tem = Fstring_equal (gentemp, ignore);
760           if (!NILP (tem))
761             return gentemp;
762         }
763       tem = Fget_buffer (gentemp);
764       if (NILP (tem))
765         return gentemp;
766     }
767 }
768
769 \f
770 DEFUN ("buffer-name", Fbuffer_name, 0, 1, 0, /*
771 Return the name of BUFFER, as a string.
772 With no argument or nil as argument, return the name of the current buffer.
773 */
774        (buffer))
775 {
776   /* For compatibility, we allow a dead buffer here.
777      Earlier versions of Emacs didn't provide buffer-live-p. */
778   if (NILP (buffer))
779     return current_buffer->name;
780   CHECK_BUFFER (buffer);
781   return XBUFFER (buffer)->name;
782 }
783
784 DEFUN ("buffer-file-name", Fbuffer_file_name, 0, 1, 0, /*
785 Return name of file BUFFER is visiting, or nil if none.
786 No argument or nil as argument means use the current buffer.
787 */
788        (buffer))
789 {
790   /* For compatibility, we allow a dead buffer here.  Yuck! */
791   if (NILP (buffer))
792     return current_buffer->filename;
793   CHECK_BUFFER (buffer);
794   return XBUFFER (buffer)->filename;
795 }
796
797 DEFUN ("buffer-base-buffer", Fbuffer_base_buffer, 0, 1, 0, /*
798 Return the base buffer of indirect buffer BUFFER.
799 If BUFFER is not indirect, return nil.
800 */
801        (buffer))
802 {
803   struct buffer *buf = decode_buffer (buffer, 0);
804
805   return buf->base_buffer ? make_buffer (buf->base_buffer) : Qnil;
806 }
807
808 DEFUN ("buffer-indirect-children", Fbuffer_indirect_children, 0, 1, 0, /*
809 Return a list of all indirect buffers whose base buffer is BUFFER.
810 If BUFFER is indirect, the return value will always be nil; see
811 `make-indirect-buffer'.
812 */
813        (buffer))
814 {
815   struct buffer *buf = decode_buffer (buffer, 0);
816
817   return Fcopy_sequence (buf->indirect_children);
818 }
819
820 DEFUN ("buffer-local-variables", Fbuffer_local_variables, 0, 1, 0, /*
821 Return an alist of variables that are buffer-local in BUFFER.
822 Most elements look like (SYMBOL . VALUE), describing one variable.
823 For a symbol that is locally unbound, just the symbol appears in the value.
824 Note that storing new VALUEs in these elements doesn't change the variables.
825 No argument or nil as argument means use current buffer as BUFFER.
826 */
827        (buffer))
828 {
829   struct buffer *buf = decode_buffer (buffer, 0);
830   Lisp_Object result = Qnil;
831
832   {
833     Lisp_Object tail;
834     for (tail = buf->local_var_alist; CONSP (tail); tail = XCDR (tail))
835       {
836         Lisp_Object elt = XCAR (tail);
837         /* Reference each variable in the alist in buf.
838            If inquiring about the current buffer, this gets the current values,
839            so store them into the alist so the alist is up to date.
840            If inquiring about some other buffer, this swaps out any values
841            for that buffer, making the alist up to date automatically.  */
842         Lisp_Object val = find_symbol_value (XCAR (elt));
843         /* Use the current buffer value only if buf is the current buffer.  */
844         if (buf != current_buffer)
845           val = XCDR (elt);
846
847         /* If symbol is unbound, put just the symbol in the list.  */
848         if (UNBOUNDP (val))
849           result = Fcons (XCAR (elt), result);
850         /* Otherwise, put (symbol . value) in the list.  */
851         else
852           result = Fcons (Fcons (XCAR (elt), val), result);
853       }
854   }
855
856   /* Add on all the variables stored in special slots.  */
857   {
858     struct buffer *syms = XBUFFER (Vbuffer_local_symbols);
859 #define MARKED_SLOT(slot)                                       \
860     { int mask = XINT (buffer_local_flags.slot);                \
861       if (mask == 0 || mask == -1                               \
862           || ((mask > 0) && (buf->local_var_flags & mask)))     \
863         result = Fcons (Fcons (syms->slot, buf->slot), result); \
864     }
865 #include "bufslots.h"
866 #undef MARKED_SLOT
867   }
868   return result;
869 }
870
871 DEFUN ("buffer-dedicated-frame", Fbuffer_dedicated_frame, 0, 1, 0, /*
872 Return the frame dedicated to this BUFFER, or nil if there is none.
873 No argument or nil as argument means use current buffer as BUFFER.
874 */
875        (buffer))
876 {
877   struct buffer *buf = decode_buffer (buffer, 0);
878
879   /* XEmacs addition: if the frame is dead, silently make it go away. */
880   if (!NILP (buf->dedicated_frame) &&
881       !FRAME_LIVE_P (XFRAME (buf->dedicated_frame)))
882     buf->dedicated_frame = Qnil;
883
884   return buf->dedicated_frame;
885 }
886
887 DEFUN ("set-buffer-dedicated-frame", Fset_buffer_dedicated_frame, 2, 2, 0, /*
888 For this BUFFER, set the FRAME dedicated to it.
889 FRAME must be a frame or nil.
890 */
891        (buffer, frame))
892 {
893   struct buffer *buf = decode_buffer (buffer, 0);
894
895   if (!NILP (frame))
896     CHECK_LIVE_FRAME (frame); /* XEmacs change */
897
898   return buf->dedicated_frame = frame;
899 }
900
901
902 \f
903 DEFUN ("buffer-modified-p", Fbuffer_modified_p, 0, 1, 0, /*
904 Return t if BUFFER was modified since its file was last read or saved.
905 No argument or nil as argument means use current buffer as BUFFER.
906 */
907        (buffer))
908 {
909   struct buffer *buf = decode_buffer (buffer, 0);
910
911   return BUF_SAVE_MODIFF (buf) < BUF_MODIFF (buf) ? Qt : Qnil;
912 }
913
914 DEFUN ("set-buffer-modified-p", Fset_buffer_modified_p, 1, 2, 0, /*
915 Mark BUFFER as modified or unmodified according to FLAG.
916 A non-nil FLAG means mark the buffer modified.  No argument or nil
917 as BUFFER means use current buffer.
918 */
919        (flag, buffer))
920 {
921   /* This function can GC */
922   struct buffer *buf = decode_buffer (buffer, 0);
923
924 #ifdef CLASH_DETECTION
925   /* If buffer becoming modified, lock the file.
926      If buffer becoming unmodified, unlock the file.  */
927
928   Lisp_Object fn = buf->file_truename;
929   if (!NILP (fn))
930     {
931       int already = BUF_SAVE_MODIFF (buf) < BUF_MODIFF (buf);
932       if (already == NILP (flag))
933         {
934           int count = specpdl_depth ();
935           /* lock_file() and unlock_file() currently use current_buffer */
936           /* #### - dmoore, what if lock_file or unlock_file kill
937              the current buffer? */
938           record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
939           set_buffer_internal (buf);
940           if (!already && !NILP (flag))
941             lock_file (fn);
942           else if (already && NILP (flag))
943             unlock_file (fn);
944           unbind_to (count, Qnil);
945         }
946     }
947 #endif /* CLASH_DETECTION */
948
949   /* This is often called when the buffer contents are altered but we
950      don't want to treat the changes that way (e.g. selective
951      display).  We still need to make sure redisplay realizes that the
952      contents have potentially altered and it needs to do some
953      work. */
954   buf = decode_buffer(buffer, 0);
955   BUF_MODIFF (buf)++;
956   BUF_SAVE_MODIFF (buf) = NILP (flag) ? BUF_MODIFF (buf) : 0;
957   MARK_MODELINE_CHANGED;
958
959   return flag;
960 }
961
962 DEFUN ("buffer-modified-tick", Fbuffer_modified_tick, 0, 1, 0, /*
963 Return BUFFER's tick counter, incremented for each change in text.
964 Each buffer has a tick counter which is incremented each time the text in
965 that buffer is changed.  It wraps around occasionally.
966 No argument or nil as argument means use current buffer as BUFFER.
967 */
968        (buffer))
969 {
970   struct buffer *buf = decode_buffer (buffer, 0);
971
972   return make_int (BUF_MODIFF (buf));
973 }
974 \f
975 DEFUN ("rename-buffer", Frename_buffer, 1, 2,
976        "sRename buffer (to new name): \nP", /*
977 Change current buffer's name to NEWNAME (a string).
978 If second arg UNIQUE is nil or omitted, it is an error if a
979 buffer named NEWNAME already exists.
980 If UNIQUE is non-nil, come up with a new name using
981 `generate-new-buffer-name'.
982 Interactively, one can set UNIQUE with a prefix argument.
983 Returns the name we actually gave the buffer.
984 This does not change the name of the visited file (if any).
985 */
986        (newname, unique))
987 {
988   /* This function can GC */
989   Lisp_Object tem, buf;
990
991 #ifdef I18N3
992   /* #### Doc string should indicate that the buffer name will get
993      translated. */
994 #endif
995   CHECK_STRING (newname);
996   newname = LISP_GETTEXT (newname);
997
998   if (XSTRING_LENGTH (newname) == 0)
999     error ("Empty string is invalid as a buffer name");
1000
1001   tem = Fget_buffer (newname);
1002   /* Don't short-circuit if UNIQUE is t.  That is a useful way to rename
1003      the buffer automatically so you can create another with the original name.
1004      It makes UNIQUE equivalent to
1005      (rename-buffer (generate-new-buffer-name NEWNAME)).  */
1006   /* XEmacs change: added check for nil */
1007   if (NILP (unique) && !NILP (tem) && XBUFFER (tem) == current_buffer)
1008     return current_buffer->name;
1009   if (!NILP (tem))
1010     {
1011       if (!NILP (unique))
1012         newname = Fgenerate_new_buffer_name (newname, current_buffer->name);
1013       else
1014         error ("Buffer name \"%s\" is in use",
1015                XSTRING_DATA (newname));
1016     }
1017
1018   current_buffer->name = newname;
1019
1020   /* Catch redisplay's attention.  Unless we do this, the modelines for
1021      any windows displaying current_buffer will stay unchanged.  */
1022   MARK_MODELINE_CHANGED;
1023
1024   buf = Fcurrent_buffer ();
1025
1026   /* The aconses in the Vbuffer_alist are shared with frame->buffer_alist,
1027      so this will change it in the per-frame ordering as well. */
1028   Fsetcar (Frassq (buf, Vbuffer_alist), newname);
1029
1030   if (NILP (current_buffer->filename)
1031       && !NILP (current_buffer->auto_save_file_name))
1032     call0 (Qrename_auto_save_file);
1033   /* refetch since that last call may have done GC */
1034   /* (hypothetical relocating GC) */
1035   return current_buffer->name;
1036 }
1037
1038 DEFUN ("other-buffer", Fother_buffer, 0, 3, 0, /*
1039 Return most recently selected buffer other than BUFFER.
1040 Buffers not visible in windows are preferred to visible buffers,
1041 unless optional third argument VISIBLE-OK is non-nil.
1042 If no other buffer exists, the buffer `*scratch*' is returned.
1043 If BUFFER is omitted or nil, some interesting buffer is returned.
1044
1045 The ordering is for this frame; If second optional argument FRAME
1046 is provided, then the ordering is for that frame.  If the second arg
1047 is t, then the global ordering is returned.
1048
1049 Note: In FSF Emacs, this function takes two arguments: BUFFER and
1050 VISIBLE-OK.
1051 */
1052        (buffer, frame, visible_ok))
1053 {
1054   /* This function can GC */
1055   Lisp_Object tail, buf, notsogood, tem;
1056   Lisp_Object alist;
1057
1058   notsogood = Qnil;
1059
1060   if (EQ (frame, Qt))
1061     alist = Vbuffer_alist;
1062   else
1063     {
1064       struct frame *f = decode_frame (frame);
1065
1066       XSETFRAME (frame, f);
1067       alist = f->buffer_alist;
1068     }
1069
1070   for (tail = alist; !NILP (tail); tail = Fcdr (tail))
1071     {
1072       buf = Fcdr (Fcar (tail));
1073       if (EQ (buf, buffer))
1074         continue;
1075       if (string_byte (XSTRING (XBUFFER (buf)->name), 0) == ' ')
1076         continue;
1077       /* If FRAME has a buffer_predicate,
1078          disregard buffers that don't fit the predicate.  */
1079       if (FRAMEP (frame))
1080         {
1081           tem = XFRAME (frame)->buffer_predicate;
1082           if (!NILP (tem))
1083             {
1084               tem = call1 (tem, buf);
1085               if (NILP (tem))
1086                 continue;
1087             }
1088         }
1089
1090       if (NILP (visible_ok))
1091         {
1092           /* get-buffer-window will handle nil or t frame */
1093           tem = Fget_buffer_window (buf, frame, Qnil);
1094         }
1095       else
1096         tem = Qnil;
1097       if (NILP (tem))
1098         return buf;
1099       if (NILP (notsogood))
1100         notsogood = buf;
1101     }
1102   if (!NILP (notsogood))
1103     return notsogood;
1104   return Fget_buffer_create (QSscratch);
1105 }
1106 \f
1107 DEFUN ("buffer-disable-undo", Fbuffer_disable_undo, 0, 1, "", /*
1108 Make BUFFER stop keeping undo information.
1109 Any undo records it already has are discarded.
1110 No argument or nil as argument means do this for the current buffer.
1111 */
1112        (buffer))
1113 {
1114   /* Allowing nil is an RMSism */
1115   struct buffer *real_buf = decode_buffer (buffer, 1);
1116   real_buf->undo_list = Qt;
1117   return Qnil;
1118 }
1119
1120 DEFUN ("buffer-enable-undo", Fbuffer_enable_undo, 0, 1, "", /*
1121 Start keeping undo information for buffer BUFFER.
1122 No argument or nil as argument means do this for the current buffer.
1123 */
1124        (buffer))
1125 {
1126   /* Allowing nil is an RMSism */
1127   struct buffer *real_buf = decode_buffer (buffer, 1);
1128   if (EQ (real_buf->undo_list, Qt))
1129     real_buf->undo_list = Qnil;
1130
1131   return Qnil;
1132 }
1133
1134 DEFUN ("kill-buffer", Fkill_buffer, 1, 1, "bKill buffer: ", /*
1135 Kill the buffer BUFFER.
1136 The argument may be a buffer or may be the name of a buffer.
1137 An argument of nil means kill the current buffer.
1138
1139 Value is t if the buffer is actually killed, nil if user says no.
1140
1141 The value of `kill-buffer-hook' (which may be local to that buffer),
1142 if not void, is a list of functions to be called, with no arguments,
1143 before the buffer is actually killed.  The buffer to be killed is current
1144 when the hook functions are called.
1145
1146 Any processes that have this buffer as the `process-buffer' are killed
1147 with `delete-process'.
1148 */
1149        (buffer))
1150 {
1151   /* This function can call lisp */
1152   Lisp_Object buf;
1153   REGISTER struct buffer *b;
1154   struct gcpro gcpro1, gcpro2;
1155
1156   if (NILP (buffer))
1157     buf = Fcurrent_buffer ();
1158   else if (BUFFERP (buffer))
1159     buf = buffer;
1160   else
1161     {
1162       buf = get_buffer (buffer, 0);
1163       if (NILP (buf)) nsberror (buffer);
1164     }
1165
1166   b = XBUFFER (buf);
1167
1168   /* OK to delete an already-deleted buffer.  */
1169   if (!BUFFER_LIVE_P (b))
1170     return Qnil;
1171
1172   /* Don't kill the minibuffer now current.  */
1173   if (EQ (buf, Vminibuffer_zero))
1174     return Qnil;
1175
1176   /* Or the echo area.  */
1177   if (EQ (buf, Vecho_area_buffer))
1178     return Qnil;
1179
1180   /* Query if the buffer is still modified.  */
1181   if (INTERACTIVE && !NILP (b->filename)
1182       && BUF_MODIFF (b) > BUF_SAVE_MODIFF (b))
1183     {
1184       Lisp_Object killp;
1185       GCPRO1 (buf);
1186       killp = call1
1187         (Qyes_or_no_p,
1188          (emacs_doprnt_string_c
1189           ((const Bufbyte *) GETTEXT ("Buffer %s modified; kill anyway? "),
1190            Qnil, -1, XSTRING_DATA (b->name))));
1191       UNGCPRO;
1192       if (NILP (killp))
1193         return Qnil;
1194       b = XBUFFER (buf);        /* Hypothetical relocating GC. */
1195     }
1196
1197   /* Run hooks with the buffer to be killed temporarily selected,
1198      unless the buffer is already dead (could have been deleted
1199      in the question above).
1200    */
1201   if (BUFFER_LIVE_P (b))
1202     {
1203       int speccount = specpdl_depth ();
1204       Lisp_Object tail = Qnil;
1205
1206       GCPRO2 (buf, tail);
1207       record_unwind_protect (save_excursion_restore, save_excursion_save ());
1208       Fset_buffer (buf);
1209
1210       /* First run the query functions; if any query is answered no,
1211          don't kill the buffer.  */
1212       EXTERNAL_LIST_LOOP (tail, Vkill_buffer_query_functions)
1213         {
1214           if (NILP (call0 (Fcar (tail))))
1215             {
1216               UNGCPRO;
1217               return unbind_to (speccount, Qnil);
1218             }
1219         }
1220
1221       /* Then run the hooks.  */
1222       run_hook (Qkill_buffer_hook);
1223 #ifdef HAVE_X_WINDOWS
1224       /* If an X selection was in this buffer, disown it.
1225          We could have done this by simply adding this function to the
1226          kill-buffer-hook, but the user might mess that up.
1227          */
1228       if (EQ (Vwindow_system, Qx))
1229         call0 (intern ("xselect-kill-buffer-hook"));
1230       /* #### generalize me! */
1231 #endif /* HAVE_X_WINDOWS */
1232       unbind_to (speccount, Qnil);
1233       UNGCPRO;
1234       b = XBUFFER (buf);        /* Hypothetical relocating GC. */
1235   }
1236
1237   /* We have no more questions to ask.  Verify that it is valid
1238      to kill the buffer.  This must be done after the questions
1239      since anything can happen within yes-or-no-p.  */
1240
1241   /* Might have been deleted during the last question above */
1242   if (!BUFFER_LIVE_P (b))
1243     return Qnil;
1244
1245   /* Don't kill the minibuffer now current.  */
1246   if (EQ (buf, XWINDOW (minibuf_window)->buffer))
1247     return Qnil;
1248
1249   /* When we kill a base buffer, kill all its indirect buffers.
1250      We do it at this stage so nothing terrible happens if they
1251      ask questions or their hooks get errors.  */
1252   if (! b->base_buffer)
1253     {
1254       Lisp_Object rest;
1255
1256       GCPRO1 (buf);
1257
1258       LIST_LOOP (rest, b->indirect_children)
1259         {
1260           Fkill_buffer (XCAR (rest));
1261           /* Keep indirect_children updated in case a
1262              query-function/hook throws.  */
1263           b->indirect_children = XCDR (rest);
1264         }
1265
1266       UNGCPRO;
1267     }
1268
1269   /* Make this buffer not be current.
1270      In the process, notice if this is the sole visible buffer
1271      and give up if so.  */
1272   if (b == current_buffer)
1273     {
1274       Fset_buffer (Fother_buffer (buf, Qnil, Qnil));
1275       if (b == current_buffer)
1276         return Qnil;
1277     }
1278
1279   /* Now there is no question: we can kill the buffer.  */
1280
1281 #ifdef CLASH_DETECTION
1282   /* Unlock this buffer's file, if it is locked.  unlock_buffer
1283      can both GC and kill the current buffer, and wreak general
1284      havok by running lisp code. */
1285   GCPRO1 (buf);
1286   unlock_buffer (b);
1287   UNGCPRO;
1288   b = XBUFFER (buf);
1289
1290   if (!BUFFER_LIVE_P (b))
1291     return Qnil;
1292
1293   if (b == current_buffer)
1294     {
1295       Fset_buffer (Fother_buffer (buf, Qnil, Qnil));
1296       if (b == current_buffer)
1297         return Qnil;
1298     }
1299 #endif /* CLASH_DETECTION */
1300
1301   {
1302     int speccount = specpdl_depth ();
1303     specbind (Qinhibit_quit, Qt);
1304
1305     kill_buffer_processes (buf);
1306
1307     delete_from_buffer_alist (buf);
1308
1309     /* #### This is a problem if this buffer is in a dedicated window.
1310        Need to undedicate any windows of this buffer first (and delete them?)
1311        */
1312     Freplace_buffer_in_windows (buf);
1313
1314     font_lock_buffer_was_killed (b);
1315
1316     /* Delete any auto-save file, if we saved it in this session.  */
1317     if (STRINGP (b->auto_save_file_name)
1318         && b->auto_save_modified != 0
1319         && BUF_SAVE_MODIFF (b) < b->auto_save_modified)
1320       {
1321         if (delete_auto_save_files != 0)
1322           {
1323             /* deleting the auto save file might kill b! */
1324             /* #### dmoore - fix this crap, we do this same gcpro and
1325                buffer liveness check multiple times.  Let's get a
1326                macro or something for it. */
1327             GCPRO1 (buf);
1328             internal_delete_file (b->auto_save_file_name);
1329             UNGCPRO;
1330             b = XBUFFER (buf);
1331
1332             if (!BUFFER_LIVE_P (b))
1333               return Qnil;
1334
1335             if (b == current_buffer)
1336               {
1337                 Fset_buffer (Fother_buffer (buf, Qnil, Qnil));
1338                 if (b == current_buffer)
1339                   return Qnil;
1340               }
1341           }
1342       }
1343
1344     uninit_buffer_markers (b);
1345
1346     kill_buffer_local_variables (b);
1347
1348     b->name = Qnil;
1349     uninit_buffer_text (b);
1350     b->undo_list = Qnil;
1351     uninit_buffer_extents (b);
1352     if (b->base_buffer)
1353       {
1354 #ifdef ERROR_CHECK_BUFPOS
1355         assert (!NILP (memq_no_quit (buf, b->base_buffer->indirect_children)));
1356 #endif
1357         b->base_buffer->indirect_children =
1358           delq_no_quit (buf, b->base_buffer->indirect_children);
1359       }
1360
1361   /* Clear away all Lisp objects, so that they
1362      won't be protected from GC. */
1363     nuke_all_buffer_slots (b, Qnil);
1364
1365     unbind_to (speccount, Qnil);
1366   }
1367   return Qt;
1368 }
1369 \f
1370 DEFUN ("record-buffer", Frecord_buffer, 1, 1, 0, /*
1371 Place buffer BUFFER first in the buffer order.
1372 Call this function when a buffer is selected "visibly".
1373
1374 This function changes the global buffer order and the per-frame buffer
1375 order for the selected frame.  The buffer order keeps track of recency
1376 of selection so that `other-buffer' will return a recently selected
1377 buffer.  See `other-buffer' for more information.
1378 */
1379        (buffer))
1380 {
1381   REGISTER Lisp_Object lynk, prev;
1382   struct frame *f = selected_frame ();
1383
1384   prev = Qnil;
1385   for (lynk = Vbuffer_alist; CONSP (lynk); lynk = XCDR (lynk))
1386     {
1387       if (EQ (XCDR (XCAR (lynk)), buffer))
1388         break;
1389       prev = lynk;
1390     }
1391   /* Effectively do Vbuffer_alist = delq_no_quit (lynk, Vbuffer_alist) */
1392   if (NILP (prev))
1393     Vbuffer_alist = XCDR (Vbuffer_alist);
1394   else
1395     XCDR (prev) = XCDR (XCDR (prev));
1396   XCDR (lynk) = Vbuffer_alist;
1397   Vbuffer_alist = lynk;
1398
1399   /* That was the global one.  Now do the same thing for the
1400      per-frame buffer-alist. */
1401   prev = Qnil;
1402   for (lynk = f->buffer_alist; CONSP (lynk); lynk = XCDR (lynk))
1403     {
1404       if (EQ (XCDR (XCAR (lynk)), buffer))
1405         break;
1406       prev = lynk;
1407     }
1408   /* Effectively do f->buffer_alist = delq_no_quit (lynk, f->buffer_alist) */
1409   if (NILP (prev))
1410     f->buffer_alist = XCDR (f->buffer_alist);
1411   else
1412     XCDR (prev) = XCDR (XCDR (prev));
1413   XCDR (lynk) = f->buffer_alist;
1414   f->buffer_alist = lynk;
1415
1416   return Qnil;
1417 }
1418
1419 DEFUN ("set-buffer-major-mode", Fset_buffer_major_mode, 1, 1, 0, /*
1420 Set an appropriate major mode for BUFFER, according to `default-major-mode'.
1421 Use this function before selecting the buffer, since it may need to inspect
1422 the current buffer's major mode.
1423 */
1424        (buffer))
1425 {
1426   int speccount = specpdl_depth ();
1427   Lisp_Object function = XBUFFER (Vbuffer_defaults)->major_mode;
1428
1429   if (NILP (function))
1430     {
1431       Lisp_Object tem = Fget (current_buffer->major_mode, Qmode_class, Qnil);
1432       if (NILP (tem))
1433         function = current_buffer->major_mode;
1434     }
1435
1436   if (NILP (function) || EQ (function, Qfundamental_mode))
1437     return Qnil;
1438
1439   /* To select a nonfundamental mode,
1440      select the buffer temporarily and then call the mode function. */
1441
1442   record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
1443
1444   Fset_buffer (buffer);
1445   call0 (function);
1446
1447   return unbind_to (speccount, Qnil);
1448 }
1449
1450 void
1451 switch_to_buffer (Lisp_Object bufname, Lisp_Object norecord)
1452 {
1453   call2 (Qswitch_to_buffer, bufname, norecord);
1454 }
1455
1456
1457 DEFUN ("current-buffer", Fcurrent_buffer, 0, 0, 0, /*
1458 Return the current buffer as a Lisp object.
1459 */
1460        ())
1461 {
1462   Lisp_Object buffer;
1463   XSETBUFFER (buffer, current_buffer);
1464   return buffer;
1465 }
1466 \f
1467 /* Set the current buffer to B.  */
1468
1469 void
1470 set_buffer_internal (struct buffer *b)
1471 {
1472   REGISTER struct buffer *old_buf;
1473   REGISTER Lisp_Object tail;
1474
1475   if (current_buffer == b)
1476     return;
1477
1478   INVALIDATE_PIXEL_TO_GLYPH_CACHE;
1479
1480   old_buf = current_buffer;
1481   current_buffer = b;
1482   invalidate_current_column ();   /* invalidate indentation cache */
1483
1484 #ifdef HAVE_FEP
1485   if (!noninteractive && initialized)
1486     {
1487       extern Lisp_Object Ffep_force_on (), Ffep_force_off (), Ffep_get_mode ();
1488
1489       old_buf->fep_mode = Ffep_get_mode ();
1490
1491       if (!NILP (current_buffer->fep_mode))
1492         Ffep_force_on ();
1493       else
1494         Ffep_force_off ();
1495   }
1496 #endif /* HAVE_FEP */
1497
1498   if (old_buf)
1499     {
1500       /* Put the undo list back in the base buffer, so that it appears
1501          that an indirect buffer shares the undo list of its base.  */
1502       if (old_buf->base_buffer)
1503         old_buf->base_buffer->undo_list = old_buf->undo_list;
1504     }
1505
1506   /* Get the undo list from the base buffer, so that it appears
1507      that an indirect buffer shares the undo list of its base.  */
1508   if (b->base_buffer)
1509     b->undo_list = b->base_buffer->undo_list;
1510
1511   /* Look down buffer's list of local Lisp variables
1512      to find and update any that forward into C variables. */
1513
1514   LIST_LOOP (tail, b->local_var_alist)
1515     {
1516       Lisp_Object sym = XCAR (XCAR (tail));
1517       Lisp_Object valcontents = XSYMBOL (sym)->value;
1518       if (SYMBOL_VALUE_MAGIC_P (valcontents))
1519         {
1520           /* Just reference the variable
1521              to cause it to become set for this buffer.  */
1522           /* Use find_symbol_value_quickly to avoid an unnecessary O(n)
1523              lookup. */
1524           (void) find_symbol_value_quickly (XCAR (tail), 1);
1525         }
1526     }
1527
1528   /* Do the same with any others that were local to the previous buffer */
1529
1530   if (old_buf)
1531     {
1532       LIST_LOOP (tail, old_buf->local_var_alist)
1533         {
1534           Lisp_Object sym = XCAR (XCAR (tail));
1535           Lisp_Object valcontents = XSYMBOL (sym)->value;
1536
1537           if (SYMBOL_VALUE_MAGIC_P (valcontents))
1538             {
1539               /* Just reference the variable
1540                  to cause it to become set for this buffer.  */
1541               /* Use find_symbol_value_quickly with find_it_p as 0 to avoid an
1542                  unnecessary O(n) lookup which is guaranteed to be worst case.
1543                  Any symbols which are local are guaranteed to have been
1544                  handled in the previous loop, above. */
1545               (void) find_symbol_value_quickly (sym, 0);
1546             }
1547         }
1548     }
1549 }
1550
1551 DEFUN ("set-buffer", Fset_buffer, 1, 1, 0, /*
1552 Make the buffer BUFFER current for editing operations.
1553 BUFFER may be a buffer or the name of an existing buffer.
1554 See also `save-excursion' when you want to make a buffer current temporarily.
1555 This function does not display the buffer, so its effect ends
1556 when the current command terminates.
1557 Use `switch-to-buffer' or `pop-to-buffer' to switch buffers permanently.
1558 */
1559        (buffer))
1560 {
1561   buffer = get_buffer (buffer, 0);
1562   if (NILP (buffer))
1563     error ("Selecting deleted or non-existent buffer");
1564   set_buffer_internal (XBUFFER (buffer));
1565   return buffer;
1566 }
1567
1568 \f
1569 DEFUN ("barf-if-buffer-read-only", Fbarf_if_buffer_read_only, 0, 3, 0, /*
1570 Signal a `buffer-read-only' error if the buffer is read-only.
1571 Optional argument BUFFER defaults to the current buffer.
1572
1573 If optional argument START is non-nil, all extents in the buffer
1574 which overlap that part of the buffer are checked to ensure none has a
1575 `read-only' property. (Extents that lie completely within the range,
1576 however, are not checked.) END defaults to the value of START.
1577
1578 If START and END are equal, the range checked is [START, END] (i.e.
1579 closed on both ends); otherwise, the range checked is (START, END)
1580 \(open on both ends), except that extents that lie completely within
1581 [START, END] are not checked.  See `extent-in-region-p' for a fuller
1582 discussion.
1583 */
1584        (buffer, start, end))
1585 {
1586   struct buffer *b = decode_buffer (buffer, 0);
1587   Bufpos s, e;
1588
1589   if (NILP (start))
1590     s = e = -1;
1591   else
1592     {
1593       if (NILP (end))
1594         end = start;
1595       get_buffer_range_char (b, start, end, &s, &e, 0);
1596     }
1597   barf_if_buffer_read_only (b, s, e);
1598
1599   return Qnil;
1600 }
1601
1602 static void
1603 bury_buffer_1 (Lisp_Object buffer, Lisp_Object before,
1604                Lisp_Object *buffer_alist)
1605 {
1606   Lisp_Object aelt = rassq_no_quit (buffer, *buffer_alist);
1607   Lisp_Object lynk = memq_no_quit (aelt, *buffer_alist);
1608   Lisp_Object iter, before_before;
1609
1610   *buffer_alist = delq_no_quit (aelt, *buffer_alist);
1611   for (before_before = Qnil, iter = *buffer_alist;
1612        !NILP (iter) && !EQ (XCDR (XCAR (iter)), before);
1613        before_before = iter, iter = XCDR (iter))
1614     ;
1615   XCDR (lynk) = iter;
1616   if (!NILP (before_before))
1617     XCDR (before_before) = lynk;
1618   else
1619     *buffer_alist = lynk;
1620 }
1621
1622 DEFUN ("bury-buffer", Fbury_buffer, 0, 2, "", /*
1623 Put BUFFER at the end of the list of all buffers.
1624 There it is the least likely candidate for `other-buffer' to return;
1625 thus, the least likely buffer for \\[switch-to-buffer] to select by default.
1626 If BUFFER is nil or omitted, bury the current buffer.
1627 Also, if BUFFER is nil or omitted, remove the current buffer from the
1628 selected window if it is displayed there.
1629 Because of this, you may need to specify (current-buffer) as
1630 BUFFER when calling from minibuffer.
1631 If BEFORE is non-nil, it specifies a buffer before which BUFFER
1632 will be placed, instead of being placed at the end.
1633 */
1634        (buffer, before))
1635 {
1636   /* This function can GC */
1637   struct buffer *buf = decode_buffer (buffer, 1);
1638   /* If we're burying the current buffer, unshow it.  */
1639   /* Note that the behavior of (bury-buffer nil) and
1640      (bury-buffer (current-buffer)) is not the same.
1641      This is illogical but is historical.  Changing it
1642      breaks mh-e and TeX and such packages. */
1643   if (NILP (buffer))
1644     switch_to_buffer (Fother_buffer (Fcurrent_buffer (), Qnil, Qnil), Qnil);
1645   XSETBUFFER (buffer, buf);
1646
1647   if (!NILP (before))
1648     before = get_buffer (before, 1);
1649
1650   if (EQ (before, buffer))
1651     error ("Cannot place a buffer before itself");
1652
1653   bury_buffer_1 (buffer, before, &Vbuffer_alist);
1654   bury_buffer_1 (buffer, before, &selected_frame ()->buffer_alist);
1655
1656   return Qnil;
1657 }
1658
1659 \f
1660 DEFUN ("erase-buffer", Ferase_buffer, 0, 1, "*", /*
1661 Delete the entire contents of the BUFFER.
1662 Any clipping restriction in effect (see `narrow-to-region') is removed,
1663 so the buffer is truly empty after this.
1664 BUFFER defaults to the current buffer if omitted.
1665 */
1666        (buffer))
1667 {
1668   /* This function can GC */
1669   struct buffer *b = decode_buffer (buffer, 1);
1670   /* #### yuck yuck yuck.  This is gross.  The old echo-area code,
1671      however, was the only place that called erase_buffer() with a
1672      non-zero NO_CLIP argument.
1673
1674      Someone needs to fix up the redisplay code so it is smarter
1675      about this, so that the NO_CLIP junk isn't necessary. */
1676   int no_clip = (b == XBUFFER (Vecho_area_buffer));
1677
1678   INVALIDATE_PIXEL_TO_GLYPH_CACHE;
1679
1680   widen_buffer (b, no_clip);
1681   buffer_delete_range (b, BUF_BEG (b), BUF_Z (b), 0);
1682   b->last_window_start = 1;
1683
1684   /* Prevent warnings, or suspension of auto saving, that would happen
1685      if future size is less than past size.  Use of erase-buffer
1686      implies that the future text is not really related to the past text.  */
1687   b->saved_size = Qzero;
1688
1689   zmacs_region_stays = 0;
1690   return Qnil;
1691 }
1692
1693 \f
1694
1695 DEFUN ("kill-all-local-variables", Fkill_all_local_variables, 0, 0, 0, /*
1696 Switch to Fundamental mode by killing current buffer's local variables.
1697 Most local variable bindings are eliminated so that the default values
1698 become effective once more.  Also, the syntax table is set from
1699 `standard-syntax-table', the category table is set from
1700 `standard-category-table' (if support for Mule exists), local keymap is set
1701 to nil, the abbrev table is set from `fundamental-mode-abbrev-table',
1702 and all specifier specifications whose locale is the current buffer
1703 are removed.  This function also forces redisplay of the modeline.
1704
1705 Every function to select a new major mode starts by
1706 calling this function.
1707
1708 As a special exception, local variables whose names have
1709 a non-nil `permanent-local' property are not eliminated by this function.
1710
1711 The first thing this function does is run
1712 the normal hook `change-major-mode-hook'.
1713 */
1714        ())
1715 {
1716   /* This function can GC */
1717   run_hook (Qchange_major_mode_hook);
1718
1719   reset_buffer_local_variables (current_buffer, 0);
1720
1721   kill_buffer_local_variables (current_buffer);
1722
1723   kill_specifier_buffer_locals (Fcurrent_buffer ());
1724
1725   /* Force modeline redisplay.  Useful here because all major mode
1726      commands call this function.  */
1727   MARK_MODELINE_CHANGED;
1728
1729   return Qnil;
1730 }
1731
1732 #ifdef MEMORY_USAGE_STATS
1733
1734 struct buffer_stats
1735 {
1736   int text;
1737   int markers;
1738   int extents;
1739   int other;
1740 };
1741
1742 static size_t
1743 compute_buffer_text_usage (struct buffer *b, struct overhead_stats *ovstats)
1744 {
1745   int was_requested = b->text->z - 1;
1746   size_t gap = b->text->gap_size + b->text->end_gap_size;
1747   size_t malloc_use = malloced_storage_size (b->text->beg, was_requested + gap, 0);
1748
1749   ovstats->gap_overhead    += gap;
1750   ovstats->was_requested   += was_requested;
1751   ovstats->malloc_overhead += malloc_use - (was_requested + gap);
1752   return malloc_use;
1753 }
1754
1755 static void
1756 compute_buffer_usage (struct buffer *b, struct buffer_stats *stats,
1757                       struct overhead_stats *ovstats)
1758 {
1759   xzero (*stats);
1760   stats->other   += malloced_storage_size (b, sizeof (*b), ovstats);
1761   stats->text    += compute_buffer_text_usage   (b, ovstats);
1762   stats->markers += compute_buffer_marker_usage (b, ovstats);
1763   stats->extents += compute_buffer_extent_usage (b, ovstats);
1764 }
1765
1766 DEFUN ("buffer-memory-usage", Fbuffer_memory_usage, 1, 1, 0, /*
1767 Return stats about the memory usage of buffer BUFFER.
1768 The values returned are in the form of an alist of usage types and byte
1769 counts.  The byte counts attempt to encompass all the memory used
1770 by the buffer (separate from the memory logically associated with a
1771 buffer or frame), including internal structures and any malloc()
1772 overhead associated with them.  In practice, the byte counts are
1773 underestimated because certain memory usage is very hard to determine
1774 \(e.g. the amount of memory used inside the Xt library or inside the
1775 X server) and because there is other stuff that might logically
1776 be associated with a window, buffer, or frame (e.g. window configurations,
1777 glyphs) but should not obviously be included in the usage counts.
1778
1779 Multiple slices of the total memory usage may be returned, separated
1780 by a nil.  Each slice represents a particular view of the memory, a
1781 particular way of partitioning it into groups.  Within a slice, there
1782 is no overlap between the groups of memory, and each slice collectively
1783 represents all the memory concerned.
1784 */
1785        (buffer))
1786 {
1787   struct buffer_stats stats;
1788   struct overhead_stats ovstats;
1789   Lisp_Object val = Qnil;
1790
1791   CHECK_BUFFER (buffer); /* dead buffers should be allowed, no? */
1792   xzero (ovstats);
1793   compute_buffer_usage (XBUFFER (buffer), &stats, &ovstats);
1794
1795   val = acons (Qtext,    make_int (stats.text),    val);
1796   val = acons (Qmarkers, make_int (stats.markers), val);
1797   val = acons (Qextents, make_int (stats.extents), val);
1798   val = acons (Qother,   make_int (stats.other),   val);
1799   val = Fcons (Qnil, val);
1800   val = acons (Qactually_requested, make_int (ovstats.was_requested),   val);
1801   val = acons (Qmalloc_overhead,    make_int (ovstats.malloc_overhead), val);
1802   val = acons (Qgap_overhead,       make_int (ovstats.gap_overhead),    val);
1803   val = acons (Qdynarr_overhead,    make_int (ovstats.dynarr_overhead), val);
1804
1805   return Fnreverse (val);
1806 }
1807
1808 #endif /* MEMORY_USAGE_STATS */
1809
1810 \f
1811 /************************************************************************/
1812 /*           Implement TO_EXTERNAL_FORMAT, TO_INTERNAL_FORMAT           */
1813 /************************************************************************/
1814
1815 /* This implementation should probably be elsewhere, but it can't be
1816    in file-coding.c since that file is only available if FILE_CODING
1817    is defined. */
1818 #ifdef FILE_CODING
1819 static int
1820 coding_system_is_binary (Lisp_Object coding_system)
1821 {
1822   Lisp_Coding_System *cs = XCODING_SYSTEM (coding_system);
1823   return
1824     (CODING_SYSTEM_TYPE (cs) == CODESYS_NO_CONVERSION &&
1825      CODING_SYSTEM_EOL_TYPE (cs) == EOL_LF &&
1826      EQ (CODING_SYSTEM_POST_READ_CONVERSION (cs), Qnil) &&
1827      EQ (CODING_SYSTEM_PRE_WRITE_CONVERSION (cs), Qnil));
1828 }
1829 #else
1830 #define coding_system_is_binary(coding_system) 1
1831 #endif
1832
1833 typedef struct
1834 {
1835   Dynarr_declare (Bufbyte_dynarr *);
1836 } Bufbyte_dynarr_dynarr;
1837
1838 typedef struct
1839 {
1840   Dynarr_declare (Extbyte_dynarr *);
1841 } Extbyte_dynarr_dynarr;
1842
1843 static Extbyte_dynarr_dynarr *conversion_out_dynarr_list;
1844 static Bufbyte_dynarr_dynarr *conversion_in_dynarr_list;
1845
1846 static int dfc_convert_to_external_format_in_use;
1847 static int dfc_convert_to_internal_format_in_use;
1848
1849 static Lisp_Object
1850 dfc_convert_to_external_format_reset_in_use (Lisp_Object value)
1851 {
1852   dfc_convert_to_external_format_in_use = XINT (value);
1853   return Qnil;
1854 }
1855
1856 static Lisp_Object
1857 dfc_convert_to_internal_format_reset_in_use (Lisp_Object value)
1858 {
1859   dfc_convert_to_internal_format_in_use = XINT (value);
1860   return Qnil;
1861 }
1862
1863 void
1864 dfc_convert_to_external_format (dfc_conversion_type source_type,
1865                                 dfc_conversion_data *source,
1866 #ifdef FILE_CODING
1867                                 Lisp_Object coding_system,
1868 #endif
1869                                 dfc_conversion_type sink_type,
1870                                 dfc_conversion_data *sink)
1871 {
1872   int count = specpdl_depth ();
1873   Extbyte_dynarr *conversion_out_dynarr;
1874
1875   type_checking_assert
1876     (((source_type == DFC_TYPE_DATA) ||
1877       (source_type == DFC_TYPE_LISP_LSTREAM && LSTREAMP (source->lisp_object)) ||
1878       (source_type == DFC_TYPE_LISP_STRING && STRINGP (source->lisp_object)))
1879      &&
1880      ((sink_type == DFC_TYPE_DATA) ||
1881       (sink_type == DFC_TYPE_LISP_LSTREAM && LSTREAMP (source->lisp_object))));
1882
1883   record_unwind_protect (dfc_convert_to_external_format_reset_in_use,
1884                          make_int (dfc_convert_to_external_format_in_use));
1885   if (Dynarr_length (conversion_out_dynarr_list) <=
1886       dfc_convert_to_external_format_in_use)
1887     Dynarr_add (conversion_out_dynarr_list, Dynarr_new (Extbyte));
1888   conversion_out_dynarr = Dynarr_at (conversion_out_dynarr_list,
1889                                      dfc_convert_to_external_format_in_use);
1890   dfc_convert_to_external_format_in_use++;
1891   Dynarr_reset (conversion_out_dynarr);
1892
1893 #ifdef FILE_CODING
1894   coding_system = Fget_coding_system (coding_system);
1895 #endif
1896
1897   /* Here we optimize in the case where the coding system does no
1898      conversion. However, we don't want to optimize in case the source
1899      or sink is an lstream, since writing to an lstream can cause a
1900      garbage collection, and this could be problematic if the source
1901      is a lisp string. */
1902   if (source_type != DFC_TYPE_LISP_LSTREAM &&
1903       sink_type   != DFC_TYPE_LISP_LSTREAM &&
1904       coding_system_is_binary (coding_system))
1905     {
1906       const Bufbyte *ptr;
1907       Bytecount len;
1908
1909       if (source_type == DFC_TYPE_LISP_STRING)
1910         {
1911           ptr = XSTRING_DATA   (source->lisp_object);
1912           len = XSTRING_LENGTH (source->lisp_object);
1913         }
1914       else
1915         {
1916           ptr = (Bufbyte *) source->data.ptr;
1917           len = source->data.len;
1918         }
1919
1920 #ifdef MULE
1921       {
1922         const Bufbyte *end;
1923         for (end = ptr + len; ptr < end;)
1924           {
1925 #ifdef UTF2000
1926             Bufbyte c =
1927               (*ptr < 0xc0) ? *ptr :
1928               ((*ptr & 0x1f) << 6) | (*(ptr+1) & 0x3f);
1929 #else
1930             Bufbyte c =
1931               (BYTE_ASCII_P (*ptr))                ? *ptr :
1932               (*ptr == LEADING_BYTE_CONTROL_1)     ? (*(ptr+1) - 0x20) :
1933               (*ptr == LEADING_BYTE_LATIN_ISO8859_1) ? (*(ptr+1)) :
1934               '~';
1935 #endif
1936
1937             Dynarr_add (conversion_out_dynarr, (Extbyte) c);
1938             INC_CHARPTR (ptr);
1939           }
1940         bufpos_checking_assert (ptr == end);
1941       }
1942 #else
1943       Dynarr_add_many (conversion_out_dynarr, ptr, len);
1944 #endif
1945
1946     }
1947   else
1948     {
1949       Lisp_Object streams_to_delete[3];
1950       int delete_count = 0;
1951       Lisp_Object instream, outstream;
1952       Lstream *reader, *writer;
1953       struct gcpro gcpro1, gcpro2;
1954
1955       if (source_type == DFC_TYPE_LISP_LSTREAM)
1956         instream = source->lisp_object;
1957       else if (source_type == DFC_TYPE_DATA)
1958         streams_to_delete[delete_count++] = instream =
1959           make_fixed_buffer_input_stream (source->data.ptr, source->data.len);
1960       else
1961         {
1962           type_checking_assert (source_type == DFC_TYPE_LISP_STRING);
1963           streams_to_delete[delete_count++] = instream =
1964             make_lisp_string_input_stream (source->lisp_object, 0, -1);
1965         }
1966
1967       if (sink_type == DFC_TYPE_LISP_LSTREAM)
1968         outstream = sink->lisp_object;
1969       else
1970         {
1971           type_checking_assert (sink_type == DFC_TYPE_DATA);
1972           streams_to_delete[delete_count++] = outstream =
1973             make_dynarr_output_stream
1974             ((unsigned_char_dynarr *) conversion_out_dynarr);
1975         }
1976
1977 #ifdef FILE_CODING
1978       streams_to_delete[delete_count++] = outstream =
1979         make_encoding_output_stream (XLSTREAM (outstream), coding_system);
1980 #endif
1981
1982       reader = XLSTREAM (instream);
1983       writer = XLSTREAM (outstream);
1984       /* decoding_stream will gc-protect outstream */
1985       GCPRO2 (instream, outstream);
1986
1987       while (1)
1988         {
1989           ssize_t size_in_bytes;
1990           char tempbuf[1024]; /* some random amount */
1991
1992           size_in_bytes = Lstream_read (reader, tempbuf, sizeof (tempbuf));
1993
1994           if (size_in_bytes == 0)
1995             break;
1996           else if (size_in_bytes < 0)
1997             error ("Error converting to external format");
1998
1999           size_in_bytes = Lstream_write (writer, tempbuf, size_in_bytes);
2000
2001           if (size_in_bytes <= 0)
2002             error ("Error converting to external format");
2003         }
2004
2005       /* Closing writer will close any stream at the other end of writer. */
2006       Lstream_close (writer);
2007       Lstream_close (reader);
2008       UNGCPRO;
2009
2010       /* The idea is that this function will create no garbage. */
2011       while (delete_count)
2012         Lstream_delete (XLSTREAM (streams_to_delete [--delete_count]));
2013     }
2014
2015   unbind_to (count, Qnil);
2016
2017   if (sink_type != DFC_TYPE_LISP_LSTREAM)
2018     {
2019       sink->data.len = Dynarr_length (conversion_out_dynarr);
2020       Dynarr_add (conversion_out_dynarr, 0);
2021       sink->data.ptr = Dynarr_atp (conversion_out_dynarr, 0);
2022     }
2023 }
2024
2025 void
2026 dfc_convert_to_internal_format (dfc_conversion_type source_type,
2027                                 dfc_conversion_data *source,
2028 #ifdef FILE_CODING
2029                                 Lisp_Object coding_system,
2030 #endif
2031                                 dfc_conversion_type sink_type,
2032                                 dfc_conversion_data *sink)
2033 {
2034   int count = specpdl_depth ();
2035   Bufbyte_dynarr *conversion_in_dynarr;
2036
2037   type_checking_assert
2038     ((source_type == DFC_TYPE_DATA ||
2039       source_type == DFC_TYPE_LISP_LSTREAM)
2040     &&
2041     (sink_type   == DFC_TYPE_DATA ||
2042      sink_type   == DFC_TYPE_LISP_LSTREAM));
2043
2044   record_unwind_protect (dfc_convert_to_internal_format_reset_in_use,
2045                          make_int (dfc_convert_to_internal_format_in_use));
2046   if (Dynarr_length (conversion_in_dynarr_list) <=
2047       dfc_convert_to_internal_format_in_use)
2048     Dynarr_add (conversion_in_dynarr_list, Dynarr_new (Bufbyte));
2049   conversion_in_dynarr = Dynarr_at (conversion_in_dynarr_list,
2050                                     dfc_convert_to_internal_format_in_use);
2051   dfc_convert_to_internal_format_in_use++;
2052   Dynarr_reset (conversion_in_dynarr);
2053
2054 #ifdef FILE_CODING
2055   coding_system = Fget_coding_system (coding_system);
2056 #endif
2057
2058   if (source_type != DFC_TYPE_LISP_LSTREAM &&
2059       sink_type   != DFC_TYPE_LISP_LSTREAM &&
2060       coding_system_is_binary (coding_system))
2061     {
2062 #ifdef MULE
2063       const Bufbyte *ptr = (const Bufbyte *) source->data.ptr;
2064       Bytecount len = source->data.len;
2065       const Bufbyte *end = ptr + len;
2066
2067       for (; ptr < end; ptr++)
2068         {
2069           Extbyte c = *ptr;
2070
2071 #ifdef UTF2000
2072           if (BYTE_ASCII_P (c))
2073             Dynarr_add (conversion_in_dynarr, c);
2074           else
2075             {
2076               Dynarr_add (conversion_in_dynarr, (c >> 6) | 0xC0);
2077               Dynarr_add (conversion_in_dynarr, (c & 0x3F) | 0x80);
2078             }
2079 #else
2080           if (BYTE_ASCII_P (c))
2081             Dynarr_add (conversion_in_dynarr, c);
2082           else if (BYTE_C1_P (c))
2083             {
2084               Dynarr_add (conversion_in_dynarr, LEADING_BYTE_CONTROL_1);
2085               Dynarr_add (conversion_in_dynarr, c + 0x20);
2086             }
2087           else
2088             {
2089               Dynarr_add (conversion_in_dynarr, LEADING_BYTE_LATIN_ISO8859_1);
2090               Dynarr_add (conversion_in_dynarr, c);
2091             }
2092 #endif
2093         }
2094 #else
2095       Dynarr_add_many (conversion_in_dynarr, source->data.ptr, source->data.len);
2096 #endif
2097     }
2098   else
2099     {
2100       Lisp_Object streams_to_delete[3];
2101       int delete_count = 0;
2102       Lisp_Object instream, outstream;
2103       Lstream *reader, *writer;
2104       struct gcpro gcpro1, gcpro2;
2105
2106       if (source_type == DFC_TYPE_LISP_LSTREAM)
2107         instream = source->lisp_object;
2108       else
2109         {
2110           type_checking_assert (source_type == DFC_TYPE_DATA);
2111           streams_to_delete[delete_count++] = instream =
2112             make_fixed_buffer_input_stream (source->data.ptr, source->data.len);
2113         }
2114
2115       if (sink_type == DFC_TYPE_LISP_LSTREAM)
2116         outstream = sink->lisp_object;
2117       else
2118         {
2119           type_checking_assert (sink_type == DFC_TYPE_DATA);
2120           streams_to_delete[delete_count++] = outstream =
2121             make_dynarr_output_stream
2122             ((unsigned_char_dynarr *) conversion_in_dynarr);
2123         }
2124
2125 #ifdef FILE_CODING
2126       streams_to_delete[delete_count++] = outstream =
2127         make_decoding_output_stream (XLSTREAM (outstream), coding_system);
2128 #endif
2129
2130       reader = XLSTREAM (instream);
2131       writer = XLSTREAM (outstream);
2132       /* outstream will gc-protect its sink stream, if necessary */
2133       GCPRO2 (instream, outstream);
2134
2135       while (1)
2136         {
2137           ssize_t size_in_bytes;
2138           char tempbuf[1024]; /* some random amount */
2139
2140           size_in_bytes = Lstream_read (reader, tempbuf, sizeof (tempbuf));
2141
2142           if (size_in_bytes == 0)
2143             break;
2144           else if (size_in_bytes < 0)
2145             error ("Error converting to internal format");
2146
2147           size_in_bytes = Lstream_write (writer, tempbuf, size_in_bytes);
2148
2149           if (size_in_bytes <= 0)
2150             error ("Error converting to internal format");
2151         }
2152
2153       /* Closing writer will close any stream at the other end of writer. */
2154       Lstream_close (writer);
2155       Lstream_close (reader);
2156       UNGCPRO;
2157
2158       /* The idea is that this function will create no garbage. */
2159       while (delete_count)
2160         Lstream_delete (XLSTREAM (streams_to_delete [--delete_count]));
2161     }
2162
2163   unbind_to (count, Qnil);
2164
2165   if (sink_type != DFC_TYPE_LISP_LSTREAM)
2166     {
2167       sink->data.len = Dynarr_length (conversion_in_dynarr);
2168       Dynarr_add (conversion_in_dynarr, 0); /* remember to zero-terminate! */
2169       sink->data.ptr = Dynarr_atp (conversion_in_dynarr, 0);
2170     }
2171 }
2172 \f
2173
2174 void
2175 syms_of_buffer (void)
2176 {
2177   INIT_LRECORD_IMPLEMENTATION (buffer);
2178
2179   defsymbol (&Qbuffer_live_p, "buffer-live-p");
2180   defsymbol (&Qbuffer_or_string_p, "buffer-or-string-p");
2181   defsymbol (&Qmode_class, "mode-class");
2182   defsymbol (&Qrename_auto_save_file, "rename-auto-save-file");
2183   defsymbol (&Qkill_buffer_hook, "kill-buffer-hook");
2184   defsymbol (&Qpermanent_local, "permanent-local");
2185
2186   defsymbol (&Qfirst_change_hook, "first-change-hook");
2187   defsymbol (&Qbefore_change_functions, "before-change-functions");
2188   defsymbol (&Qafter_change_functions, "after-change-functions");
2189
2190   /* #### Obsolete, for compatibility */
2191   defsymbol (&Qbefore_change_function, "before-change-function");
2192   defsymbol (&Qafter_change_function, "after-change-function");
2193
2194   defsymbol (&Qdefault_directory, "default-directory");
2195
2196   defsymbol (&Qget_file_buffer, "get-file-buffer");
2197   defsymbol (&Qchange_major_mode_hook, "change-major-mode-hook");
2198
2199   defsymbol (&Qfundamental_mode, "fundamental-mode");
2200
2201   defsymbol (&Qfind_file_compare_truenames, "find-file-compare-truenames");
2202
2203   defsymbol (&Qswitch_to_buffer, "switch-to-buffer");
2204
2205   DEFSUBR (Fbufferp);
2206   DEFSUBR (Fbuffer_live_p);
2207   DEFSUBR (Fbuffer_list);
2208   DEFSUBR (Fdecode_buffer);
2209   DEFSUBR (Fget_buffer);
2210   DEFSUBR (Fget_file_buffer);
2211   DEFSUBR (Fget_buffer_create);
2212   DEFSUBR (Fmake_indirect_buffer);
2213
2214   DEFSUBR (Fgenerate_new_buffer_name);
2215   DEFSUBR (Fbuffer_name);
2216   DEFSUBR (Fbuffer_file_name);
2217   DEFSUBR (Fbuffer_base_buffer);
2218   DEFSUBR (Fbuffer_indirect_children);
2219   DEFSUBR (Fbuffer_local_variables);
2220   DEFSUBR (Fbuffer_dedicated_frame);
2221   DEFSUBR (Fset_buffer_dedicated_frame);
2222   DEFSUBR (Fbuffer_modified_p);
2223   DEFSUBR (Fset_buffer_modified_p);
2224   DEFSUBR (Fbuffer_modified_tick);
2225   DEFSUBR (Frename_buffer);
2226   DEFSUBR (Fother_buffer);
2227   DEFSUBR (Fbuffer_disable_undo);
2228   DEFSUBR (Fbuffer_enable_undo);
2229   DEFSUBR (Fkill_buffer);
2230   DEFSUBR (Ferase_buffer);
2231   DEFSUBR (Frecord_buffer);
2232   DEFSUBR (Fset_buffer_major_mode);
2233   DEFSUBR (Fcurrent_buffer);
2234   DEFSUBR (Fset_buffer);
2235   DEFSUBR (Fbarf_if_buffer_read_only);
2236   DEFSUBR (Fbury_buffer);
2237   DEFSUBR (Fkill_all_local_variables);
2238 #ifdef MEMORY_USAGE_STATS
2239   DEFSUBR (Fbuffer_memory_usage);
2240 #endif
2241
2242   deferror (&Qprotected_field, "protected-field",
2243             "Attempt to modify a protected field", Qerror);
2244 }
2245
2246 void
2247 reinit_vars_of_buffer (void)
2248 {
2249   conversion_in_dynarr_list = Dynarr_new2 (Bufbyte_dynarr_dynarr,
2250                                            Bufbyte_dynarr *);
2251   conversion_out_dynarr_list = Dynarr_new2 (Extbyte_dynarr_dynarr,
2252                                             Extbyte_dynarr *);
2253
2254   staticpro_nodump (&Vbuffer_alist);
2255   Vbuffer_alist = Qnil;
2256   current_buffer = 0;
2257 }
2258
2259 /* initialize the buffer routines */
2260 void
2261 vars_of_buffer (void)
2262 {
2263   /* This function can GC */
2264   reinit_vars_of_buffer ();
2265
2266   staticpro (&QSFundamental);
2267   staticpro (&QSscratch);
2268
2269   QSFundamental = build_string ("Fundamental");
2270   QSscratch = build_string (DEFER_GETTEXT ("*scratch*"));
2271
2272   DEFVAR_LISP ("change-major-mode-hook", &Vchange_major_mode_hook /*
2273 List of hooks to be run before killing local variables in a buffer.
2274 This should be used by any mode that temporarily alters the contents or
2275 the read-only state of the buffer.  See also `kill-all-local-variables'.
2276 */ );
2277   Vchange_major_mode_hook = Qnil;
2278
2279   DEFVAR_BOOL ("find-file-compare-truenames", &find_file_compare_truenames /*
2280 If this is true, then the find-file command will check the truenames
2281 of all visited files when deciding whether a given file is already in
2282 a buffer, instead of just the buffer-file-name.  This means that if you
2283 attempt to visit another file which is a symbolic-link to a file which is
2284 already in a buffer, the existing buffer will be found instead of a newly-
2285 created one.  This works if any component of the pathname (including a non-
2286 terminal component) is a symbolic link as well, but doesn't work with hard
2287 links (nothing does).
2288
2289 See also the variable find-file-use-truenames.
2290 */ );
2291   find_file_compare_truenames = 0;
2292
2293   DEFVAR_BOOL ("find-file-use-truenames", &find_file_use_truenames /*
2294 If this is true, then a buffer's visited file-name will always be
2295 chased back to the real file; it will never be a symbolic link, and there
2296 will never be a symbolic link anywhere in its directory path.
2297 That is, the buffer-file-name and buffer-file-truename will be equal.
2298 This doesn't work with hard links.
2299
2300 See also the variable find-file-compare-truenames.
2301 */ );
2302   find_file_use_truenames = 0;
2303
2304   DEFVAR_LISP ("before-change-functions", &Vbefore_change_functions /*
2305 List of functions to call before each text change.
2306 Two arguments are passed to each function: the positions of
2307 the beginning and end of the range of old text to be changed.
2308 \(For an insertion, the beginning and end are at the same place.)
2309 No information is given about the length of the text after the change.
2310
2311 Buffer changes made while executing the `before-change-functions'
2312 don't call any before-change or after-change functions.
2313 */ );
2314   Vbefore_change_functions = Qnil;
2315
2316   /* FSF Emacs has the following additional doc at the end of
2317      before-change-functions and after-change-functions:
2318
2319 That's because these variables are temporarily set to nil.
2320 As a result, a hook function cannot straightforwardly alter the value of
2321 these variables.  See the Emacs Lisp manual for a way of
2322 accomplishing an equivalent result by using other variables.
2323
2324      But this doesn't apply under XEmacs because things are
2325      handled better. */
2326
2327   DEFVAR_LISP ("after-change-functions", &Vafter_change_functions /*
2328 List of functions to call after each text change.
2329 Three arguments are passed to each function: the positions of
2330 the beginning and end of the range of changed text,
2331 and the length of the pre-change text replaced by that range.
2332 \(For an insertion, the pre-change length is zero;
2333 for a deletion, that length is the number of characters deleted,
2334 and the post-change beginning and end are at the same place.)
2335
2336 Buffer changes made while executing `after-change-functions'
2337 don't call any before-change or after-change functions.
2338 */ );
2339   Vafter_change_functions = Qnil;
2340
2341   DEFVAR_LISP ("before-change-function", &Vbefore_change_function /*
2342
2343 */ ); /* obsoleteness will be documented */
2344   Vbefore_change_function = Qnil;
2345
2346   DEFVAR_LISP ("after-change-function", &Vafter_change_function /*
2347
2348 */ ); /* obsoleteness will be documented */
2349   Vafter_change_function = Qnil;
2350
2351   DEFVAR_LISP ("first-change-hook", &Vfirst_change_hook /*
2352 A list of functions to call before changing a buffer which is unmodified.
2353 The functions are run using the `run-hooks' function.
2354 */ );
2355   Vfirst_change_hook = Qnil;
2356
2357 #if 0 /* FSFmacs */
2358   xxDEFVAR_LISP ("transient-mark-mode", &Vtransient_mark_mode /*
2359 *Non-nil means deactivate the mark when the buffer contents change.
2360 */ );
2361   Vtransient_mark_mode = Qnil;
2362 #endif /* FSFmacs */
2363
2364   DEFVAR_INT ("undo-threshold", &undo_threshold /*
2365 Keep no more undo information once it exceeds this size.
2366 This threshold is applied when garbage collection happens.
2367 The size is counted as the number of bytes occupied,
2368 which includes both saved text and other data.
2369 */ );
2370   undo_threshold = 20000;
2371
2372   DEFVAR_INT ("undo-high-threshold", &undo_high_threshold /*
2373 Don't keep more than this much size of undo information.
2374 A command which pushes past this size is itself forgotten.
2375 This threshold is applied when garbage collection happens.
2376 The size is counted as the number of bytes occupied,
2377 which includes both saved text and other data.
2378 */ );
2379   undo_high_threshold = 30000;
2380
2381   DEFVAR_LISP ("inhibit-read-only", &Vinhibit_read_only /*
2382 *Non-nil means disregard read-only status of buffers or characters.
2383 If the value is t, disregard `buffer-read-only' and all `read-only'
2384 text properties.  If the value is a list, disregard `buffer-read-only'
2385 and disregard a `read-only' extent property or text property if the
2386 property value is a member of the list.
2387 */ );
2388   Vinhibit_read_only = Qnil;
2389
2390   DEFVAR_LISP ("kill-buffer-query-functions", &Vkill_buffer_query_functions /*
2391 List of functions called with no args to query before killing a buffer.
2392 */ );
2393   Vkill_buffer_query_functions = Qnil;
2394
2395   DEFVAR_BOOL ("delete-auto-save-files", &delete_auto_save_files /*
2396 *Non-nil means delete auto-save file when a buffer is saved or killed.
2397 */ );
2398   delete_auto_save_files = 1;
2399 }
2400
2401 /* The docstrings for DEFVAR_* are recorded externally by make-docfile.  */
2402
2403 /* Renamed from DEFVAR_PER_BUFFER because FSFmacs D_P_B takes
2404    a bogus extra arg, which confuses an otherwise identical make-docfile.c */
2405 #define DEFVAR_BUFFER_LOCAL_1(lname, field_name, forward_type, magicfun) do {   \
2406   static const struct symbol_value_forward I_hate_C =                           \
2407   { /* struct symbol_value_forward */                                           \
2408     { /* struct symbol_value_magic */                                           \
2409       { /* struct lcrecord_header */                                            \
2410         { /* struct lrecord_header */                                           \
2411           lrecord_type_symbol_value_forward, /* lrecord_type_index */           \
2412           1, /* mark bit */                                                     \
2413           1, /* c_readonly bit */                                               \
2414           1  /* lisp_readonly bit */                                            \
2415         },                                                                      \
2416         0, /* next */                                                           \
2417         0, /* uid  */                                                           \
2418         0  /* free */                                                           \
2419       },                                                                        \
2420       &(buffer_local_flags.field_name),                                         \
2421       forward_type                                                              \
2422     },                                                                          \
2423     magicfun                                                                    \
2424   };                                                                            \
2425                                                                                 \
2426   {                                                                             \
2427     int offset = ((char *)symbol_value_forward_forward (&I_hate_C) -            \
2428                   (char *)&buffer_local_flags);                                 \
2429     defvar_magic (lname, &I_hate_C);                                            \
2430                                                                                 \
2431     *((Lisp_Object *)(offset + (char *)XBUFFER (Vbuffer_local_symbols)))        \
2432       = intern (lname);                                                         \
2433   }                                                                             \
2434 } while (0)
2435
2436 #define DEFVAR_BUFFER_LOCAL_MAGIC(lname, field_name, magicfun)          \
2437         DEFVAR_BUFFER_LOCAL_1 (lname, field_name,                       \
2438                                SYMVAL_CURRENT_BUFFER_FORWARD, magicfun)
2439 #define DEFVAR_BUFFER_LOCAL(lname, field_name)                          \
2440         DEFVAR_BUFFER_LOCAL_MAGIC (lname, field_name, 0)
2441 #define DEFVAR_CONST_BUFFER_LOCAL_MAGIC(lname, field_name, magicfun)    \
2442         DEFVAR_BUFFER_LOCAL_1 (lname, field_name,                       \
2443                                SYMVAL_CONST_CURRENT_BUFFER_FORWARD, magicfun)
2444 #define DEFVAR_CONST_BUFFER_LOCAL(lname, field_name)                    \
2445         DEFVAR_CONST_BUFFER_LOCAL_MAGIC (lname, field_name, 0)
2446
2447 #define DEFVAR_BUFFER_DEFAULTS_MAGIC(lname, field_name, magicfun)       \
2448         DEFVAR_SYMVAL_FWD (lname, &(buffer_local_flags.field_name),     \
2449                            SYMVAL_DEFAULT_BUFFER_FORWARD, magicfun)
2450 #define DEFVAR_BUFFER_DEFAULTS(lname, field_name)                       \
2451         DEFVAR_BUFFER_DEFAULTS_MAGIC (lname, field_name, 0)
2452
2453 static void
2454 nuke_all_buffer_slots (struct buffer *b, Lisp_Object zap)
2455 {
2456   zero_lcrecord (b);
2457
2458   b->extent_info = Qnil;
2459   b->indirect_children = Qnil;
2460   b->own_text.line_number_cache = Qnil;
2461
2462 #define MARKED_SLOT(x)  b->x = zap
2463 #include "bufslots.h"
2464 #undef MARKED_SLOT
2465 }
2466
2467 static void
2468 common_init_complex_vars_of_buffer (void)
2469 {
2470   /* Make sure all markable slots in buffer_defaults
2471      are initialized reasonably, so mark_buffer won't choke. */
2472   struct buffer *defs = alloc_lcrecord_type (struct buffer, &lrecord_buffer);
2473   struct buffer *syms = alloc_lcrecord_type (struct buffer, &lrecord_buffer);
2474
2475   staticpro_nodump (&Vbuffer_defaults);
2476   staticpro_nodump (&Vbuffer_local_symbols);
2477   XSETBUFFER (Vbuffer_defaults, defs);
2478   XSETBUFFER (Vbuffer_local_symbols, syms);
2479
2480   nuke_all_buffer_slots (syms, Qnil);
2481   nuke_all_buffer_slots (defs, Qnil);
2482   defs->text = &defs->own_text;
2483   syms->text = &syms->own_text;
2484
2485   /* Set up the non-nil default values of various buffer slots.
2486      Must do these before making the first buffer. */
2487   defs->major_mode = Qfundamental_mode;
2488   defs->mode_name = QSFundamental;
2489   defs->abbrev_table = Qnil;    /* real default setup by Lisp code */
2490
2491   defs->downcase_table   = Vascii_downcase_table;
2492   defs->upcase_table     = Vascii_upcase_table;
2493   defs->case_canon_table = Vascii_canon_table;
2494   defs->case_eqv_table   = Vascii_eqv_table;
2495 #ifdef MULE
2496   defs->mirror_downcase_table   = Vmirror_ascii_downcase_table;
2497   defs->mirror_upcase_table     = Vmirror_ascii_upcase_table;
2498   defs->mirror_case_canon_table = Vmirror_ascii_canon_table;
2499   defs->mirror_case_eqv_table   = Vmirror_ascii_eqv_table;
2500
2501   defs->category_table = Vstandard_category_table;
2502 #endif /* MULE */
2503   defs->syntax_table = Vstandard_syntax_table;
2504   defs->mirror_syntax_table =
2505     XCHAR_TABLE (Vstandard_syntax_table)->mirror_table;
2506   defs->modeline_format = build_string ("%-");  /* reset in loaddefs.el */
2507   defs->case_fold_search = Qt;
2508   defs->selective_display_ellipses = Qt;
2509   defs->tab_width = make_int (8);
2510   defs->ctl_arrow = Qt;
2511   defs->fill_column = make_int (70);
2512   defs->left_margin = Qzero;
2513   defs->saved_size = Qzero;     /* lisp code wants int-or-nil */
2514   defs->modtime = 0;
2515   defs->auto_save_modified = 0;
2516   defs->auto_save_failure_time = -1;
2517   defs->invisibility_spec = Qt;
2518
2519   defs->indirect_children = Qnil;
2520   syms->indirect_children = Qnil;
2521
2522   {
2523     /*  0 means var is always local.  Default used only at creation.
2524      * -1 means var is always local.  Default used only at reset and
2525      *    creation.
2526      * -2 means there's no lisp variable corresponding to this slot
2527      *    and the default is only used at creation.
2528      * -3 means no Lisp variable.  Default used only at reset and creation.
2529      * >0 is mask.  Var is local if ((buffer->local_var_flags & mask) != 0)
2530      *              Otherwise default is used.
2531      */
2532     Lisp_Object always_local_no_default = make_int (0);
2533     Lisp_Object always_local_resettable = make_int (-1);
2534     Lisp_Object resettable              = make_int (-3);
2535
2536     /* Assign the local-flags to the slots that have default values.
2537        The local flag is a bit that is used in the buffer
2538        to say that it has its own local value for the slot.
2539        The local flag bits are in the local_var_flags slot of the
2540        buffer.  */
2541
2542     nuke_all_buffer_slots (&buffer_local_flags, make_int (-2));
2543     buffer_local_flags.filename            = always_local_no_default;
2544     buffer_local_flags.directory           = always_local_no_default;
2545     buffer_local_flags.backed_up           = always_local_no_default;
2546     buffer_local_flags.saved_size          = always_local_no_default;
2547     buffer_local_flags.auto_save_file_name = always_local_no_default;
2548     buffer_local_flags.read_only           = always_local_no_default;
2549
2550     buffer_local_flags.major_mode          = always_local_resettable;
2551     buffer_local_flags.mode_name           = always_local_resettable;
2552     buffer_local_flags.undo_list           = always_local_no_default;
2553 #if 0 /* FSFmacs */
2554     buffer_local_flags.mark_active         = always_local_resettable;
2555 #endif
2556     buffer_local_flags.point_before_scroll = always_local_resettable;
2557     buffer_local_flags.file_truename       = always_local_no_default;
2558     buffer_local_flags.invisibility_spec   = always_local_resettable;
2559     buffer_local_flags.file_format         = always_local_resettable;
2560     buffer_local_flags.generated_modeline_string = always_local_no_default;
2561
2562     buffer_local_flags.keymap           = resettable;
2563     buffer_local_flags.downcase_table   = resettable;
2564     buffer_local_flags.upcase_table     = resettable;
2565     buffer_local_flags.case_canon_table = resettable;
2566     buffer_local_flags.case_eqv_table   = resettable;
2567     buffer_local_flags.syntax_table     = resettable;
2568 #ifdef MULE
2569     buffer_local_flags.category_table   = resettable;
2570 #endif
2571
2572     buffer_local_flags.modeline_format            = make_int (1<<0);
2573     buffer_local_flags.abbrev_mode                = make_int (1<<1);
2574     buffer_local_flags.overwrite_mode             = make_int (1<<2);
2575     buffer_local_flags.case_fold_search           = make_int (1<<3);
2576     buffer_local_flags.auto_fill_function         = make_int (1<<4);
2577     buffer_local_flags.selective_display          = make_int (1<<5);
2578     buffer_local_flags.selective_display_ellipses = make_int (1<<6);
2579     buffer_local_flags.tab_width                  = make_int (1<<7);
2580     buffer_local_flags.truncate_lines             = make_int (1<<8);
2581     buffer_local_flags.ctl_arrow                  = make_int (1<<9);
2582     buffer_local_flags.fill_column                = make_int (1<<10);
2583     buffer_local_flags.left_margin                = make_int (1<<11);
2584     buffer_local_flags.abbrev_table               = make_int (1<<12);
2585 #ifdef REGION_CACHE_NEEDS_WORK
2586     buffer_local_flags.cache_long_line_scans      = make_int (1<<13);
2587 #endif
2588 #ifdef FILE_CODING
2589     buffer_local_flags.buffer_file_coding_system  = make_int (1<<14);
2590 #endif
2591
2592     /* #### Warning: 1<<31 is the largest number currently allowable
2593        due to the XINT() handling of this value.  With some
2594        rearrangement you can get 3 more bits. */
2595   }
2596 }
2597
2598 #define BUFFER_SLOTS_SIZE (offsetof (struct buffer, BUFFER_SLOTS_LAST_NAME) - offsetof (struct buffer, BUFFER_SLOTS_FIRST_NAME) + sizeof (Lisp_Object))
2599 #define BUFFER_SLOTS_COUNT (BUFFER_SLOTS_SIZE / sizeof (Lisp_Object))
2600
2601 void
2602 reinit_complex_vars_of_buffer (void)
2603 {
2604   struct buffer *defs, *syms;
2605
2606   common_init_complex_vars_of_buffer ();
2607
2608   defs = XBUFFER (Vbuffer_defaults);
2609   syms = XBUFFER (Vbuffer_local_symbols);
2610   memcpy (&defs->BUFFER_SLOTS_FIRST_NAME,
2611           buffer_defaults_saved_slots,
2612           BUFFER_SLOTS_SIZE);
2613   memcpy (&syms->BUFFER_SLOTS_FIRST_NAME,
2614           buffer_local_symbols_saved_slots,
2615           BUFFER_SLOTS_SIZE);
2616 }
2617
2618
2619 static const struct lrecord_description buffer_slots_description_1[] = {
2620   { XD_LISP_OBJECT_ARRAY, 0, BUFFER_SLOTS_COUNT },
2621   { XD_END }
2622 };
2623
2624 static const struct struct_description buffer_slots_description = {
2625   BUFFER_SLOTS_SIZE,
2626   buffer_slots_description_1
2627 };
2628
2629 void
2630 complex_vars_of_buffer (void)
2631 {
2632   struct buffer *defs, *syms;
2633
2634   common_init_complex_vars_of_buffer ();
2635
2636   defs = XBUFFER (Vbuffer_defaults);
2637   syms = XBUFFER (Vbuffer_local_symbols);
2638   buffer_defaults_saved_slots      = &defs->BUFFER_SLOTS_FIRST_NAME;
2639   buffer_local_symbols_saved_slots = &syms->BUFFER_SLOTS_FIRST_NAME;
2640   dumpstruct (&buffer_defaults_saved_slots,      &buffer_slots_description);
2641   dumpstruct (&buffer_local_symbols_saved_slots, &buffer_slots_description);
2642
2643   DEFVAR_BUFFER_DEFAULTS ("default-modeline-format", modeline_format /*
2644 Default value of `modeline-format' for buffers that don't override it.
2645 This is the same as (default-value 'modeline-format).
2646 */ );
2647
2648   DEFVAR_BUFFER_DEFAULTS ("default-abbrev-mode", abbrev_mode /*
2649 Default value of `abbrev-mode' for buffers that do not override it.
2650 This is the same as (default-value 'abbrev-mode).
2651 */ );
2652
2653   DEFVAR_BUFFER_DEFAULTS ("default-ctl-arrow", ctl_arrow /*
2654 Default value of `ctl-arrow' for buffers that do not override it.
2655 This is the same as (default-value 'ctl-arrow).
2656 */ );
2657
2658 #if 0 /* #### make this a specifier! */
2659   DEFVAR_BUFFER_DEFAULTS ("default-display-direction", display_direction /*
2660 Default display-direction for buffers that do not override it.
2661 This is the same as (default-value 'display-direction).
2662 Note: This is not yet implemented.
2663 */ );
2664 #endif
2665
2666   DEFVAR_BUFFER_DEFAULTS ("default-truncate-lines", truncate_lines /*
2667 Default value of `truncate-lines' for buffers that do not override it.
2668 This is the same as (default-value 'truncate-lines).
2669 */ );
2670
2671   DEFVAR_BUFFER_DEFAULTS ("default-fill-column", fill_column /*
2672 Default value of `fill-column' for buffers that do not override it.
2673 This is the same as (default-value 'fill-column).
2674 */ );
2675
2676   DEFVAR_BUFFER_DEFAULTS ("default-left-margin", left_margin /*
2677 Default value of `left-margin' for buffers that do not override it.
2678 This is the same as (default-value 'left-margin).
2679 */ );
2680
2681   DEFVAR_BUFFER_DEFAULTS ("default-tab-width", tab_width /*
2682 Default value of `tab-width' for buffers that do not override it.
2683 This is the same as (default-value 'tab-width).
2684 */ );
2685
2686   DEFVAR_BUFFER_DEFAULTS ("default-case-fold-search", case_fold_search /*
2687 Default value of `case-fold-search' for buffers that don't override it.
2688 This is the same as (default-value 'case-fold-search).
2689 */ );
2690
2691   DEFVAR_BUFFER_LOCAL ("modeline-format", modeline_format /*
2692 Template for displaying modeline for current buffer.
2693 Each buffer has its own value of this variable.
2694 Value may be a string, symbol, glyph, generic specifier, list or cons cell.
2695 For a symbol, its value is processed (but it is ignored if t or nil).
2696  A string appearing directly as the value of a symbol is processed verbatim
2697  in that the %-constructs below are not recognized.
2698 For a glyph, it is inserted as is.
2699 For a generic specifier (i.e. a specifier of type `generic'), its instance
2700  is computed in the current window using the equivalent of `specifier-instance'
2701  and the value is processed.
2702 For a list whose car is a symbol, the symbol's value is taken,
2703  and if that is non-nil, the cadr of the list is processed recursively.
2704  Otherwise, the caddr of the list (if there is one) is processed.
2705 For a list whose car is a string or list, each element is processed
2706  recursively and the results are effectively concatenated.
2707 For a list whose car is an integer, the cdr of the list is processed
2708  and padded (if the number is positive) or truncated (if negative)
2709  to the width specified by that number.
2710 For a list whose car is an extent, the cdr of the list is processed
2711  normally but the results are displayed using the face of the
2712  extent, and mouse clicks over this section are processed using the
2713  keymap of the extent. (In addition, if the extent has a help-echo
2714  property, that string will be echoed when the mouse moves over this
2715  section.) If extents are nested, all keymaps are properly consulted
2716  when processing mouse clicks, but multiple faces are not correctly
2717  merged (only the first face is used), and lists of faces are not
2718  correctly handled.  See `generated-modeline-string' for more information.
2719 A string is printed verbatim in the modeline except for %-constructs:
2720   (%-constructs are processed when the string is the entire modeline-format
2721    or when it is found in a cons-cell or a list)
2722   %b -- print buffer name.      %c -- print the current column number.
2723   %f -- print visited file name.
2724   %* -- print %, * or hyphen.   %+ -- print *, % or hyphen.
2725         % means buffer is read-only and * means it is modified.
2726         For a modified read-only buffer, %* gives % and %+ gives *.
2727   %s -- print process status.   %l -- print the current line number.
2728   %S -- print name of selected frame (only meaningful under X Windows).
2729   %p -- print percent of buffer above top of window, or Top, Bot or All.
2730   %P -- print percent of buffer above bottom of window, perhaps plus Top,
2731         or print Bottom or All.
2732   %n -- print Narrow if appropriate.
2733   %C -- under XEmacs/mule, print the mnemonic for `buffer-file-coding-system'.
2734   %[ -- print one [ for each recursive editing level.  %] similar.
2735   %% -- print %.                %- -- print infinitely many dashes.
2736 Decimal digits after the % specify field width to which to pad.
2737 */ );
2738
2739   DEFVAR_BUFFER_DEFAULTS ("default-major-mode", major_mode /*
2740 *Major mode for new buffers.  Defaults to `fundamental-mode'.
2741 nil here means use current buffer's major mode.
2742 */ );
2743
2744   DEFVAR_BUFFER_DEFAULTS ("fundamental-mode-abbrev-table", abbrev_table /*
2745 The abbrev table of mode-specific abbrevs for Fundamental Mode.
2746 */ );
2747
2748   DEFVAR_BUFFER_LOCAL ("major-mode", major_mode /*
2749 Symbol for current buffer's major mode.
2750 */ );
2751
2752   DEFVAR_BUFFER_LOCAL ("mode-name", mode_name /*
2753 Pretty name of current buffer's major mode (a string).
2754 */ );
2755
2756   DEFVAR_BUFFER_LOCAL ("abbrev-mode", abbrev_mode /*
2757 Non-nil turns on automatic expansion of abbrevs as they are inserted.
2758 Automatically becomes buffer-local when set in any fashion.
2759 */ );
2760
2761   DEFVAR_BUFFER_LOCAL ("case-fold-search", case_fold_search /*
2762 *Non-nil if searches should ignore case.
2763 Automatically becomes buffer-local when set in any fashion.
2764
2765 BUG: Under XEmacs/Mule, translations to or from non-ASCII characters
2766  (this includes chars in the range 128 - 255) are ignored by
2767  the string/buffer-searching routines.  Thus, `case-fold-search'
2768  will not correctly conflate a-umlaut and A-umlaut even if the
2769  case tables call for this.
2770 */ );
2771
2772   DEFVAR_BUFFER_LOCAL ("fill-column", fill_column /*
2773 *Column beyond which automatic line-wrapping should happen.
2774 Automatically becomes buffer-local when set in any fashion.
2775 */ );
2776
2777   DEFVAR_BUFFER_LOCAL ("left-margin", left_margin /*
2778 *Column for the default indent-line-function to indent to.
2779 Linefeed indents to this column in Fundamental mode.
2780 Automatically becomes buffer-local when set in any fashion.
2781 Do not confuse this with the specifier `left-margin-width';
2782 that controls the size of a margin that is displayed outside
2783 of the text area.
2784 */ );
2785
2786   DEFVAR_BUFFER_LOCAL_MAGIC ("tab-width", tab_width /*
2787 *Distance between tab stops (for display of tab characters), in columns.
2788 Automatically becomes buffer-local when set in any fashion.
2789 */ , redisplay_variable_changed);
2790
2791   DEFVAR_BUFFER_LOCAL_MAGIC ("ctl-arrow", ctl_arrow /*
2792 *Non-nil means display control chars with uparrow.
2793 Nil means use backslash and octal digits.
2794 An integer means characters >= ctl-arrow are assumed to be printable, and
2795 will be displayed as a single glyph.
2796 Any other value is the same as 160 - the code SPC with the high bit on.
2797
2798 The interpretation of this variable is likely to change in the future.
2799
2800 Automatically becomes buffer-local when set in any fashion.
2801 This variable does not apply to characters whose display is specified
2802 in the current display table (if there is one).
2803 */ , redisplay_variable_changed);
2804
2805 #if 0 /* #### Make this a specifier! */
2806   xxDEFVAR_BUFFER_LOCAL ("display-direction", display_direction /*
2807 *Non-nil means lines in the buffer are displayed right to left.
2808 Nil means left to right. (Not yet implemented.)
2809 */ );
2810 #endif /* Not yet implemented */
2811
2812   DEFVAR_BUFFER_LOCAL_MAGIC ("truncate-lines", truncate_lines /*
2813 *Non-nil means do not display continuation lines;
2814 give each line of text one frame line.
2815 Automatically becomes buffer-local when set in any fashion.
2816
2817 Note that this is overridden by the variable
2818 `truncate-partial-width-windows' if that variable is non-nil
2819 and this buffer is not full-frame width.
2820 */ , redisplay_variable_changed);
2821
2822   DEFVAR_BUFFER_LOCAL ("default-directory", directory /*
2823 Name of default directory of current buffer.  Should end with slash.
2824 Each buffer has its own value of this variable.
2825 */ );
2826
2827 #ifdef FILE_CODING
2828   DEFVAR_BUFFER_DEFAULTS ("default-buffer-file-coding-system", buffer_file_coding_system /*
2829 Default value of `buffer-file-coding-system' for buffers that do not override it.
2830 This is the same as (default-value 'buffer-file-coding-system).
2831 This value is used both for buffers without associated files and
2832 for buffers whose files do not have any apparent coding system.
2833 See `buffer-file-coding-system'.
2834 */ );
2835
2836   DEFVAR_BUFFER_LOCAL ("buffer-file-coding-system", buffer_file_coding_system /*
2837 *Current coding system for the current buffer.
2838 When the buffer is written out into a file, this coding system will be
2839 used for the encoding.  Automatically buffer-local when set in any
2840 fashion.  This is normally set automatically when a file is loaded in
2841 based on the determined coding system of the file (assuming that
2842 `buffer-file-coding-system-for-read' is set to `undecided', which
2843 calls for automatic determination of the file's coding system).
2844 Normally the modeline indicates the current file coding system using
2845 its mnemonic abbreviation.
2846
2847 The default value for this variable (which is normally used for
2848 buffers without associated files) is also used when automatic
2849 detection of a file's encoding is called for and there was no
2850 discernible encoding in the file (i.e. it was entirely or almost
2851 entirely ASCII).  The default value should generally *not* be set to
2852 nil (equivalent to `no-conversion'), because if extended characters
2853 are ever inserted into the buffer, they will be lost when the file is
2854 written out.  A good choice is `iso-2022-8' (the simple ISO 2022 8-bit
2855 encoding), which will write out ASCII and Latin-1 characters in the
2856 standard (and highly portable) fashion and use standard escape
2857 sequences for other charsets.  Another reasonable choice is
2858 `escape-quoted', which is equivalent to `iso-2022-8' but prefixes
2859 certain control characters with ESC to make sure they are not
2860 interpreted as escape sequences when read in.  This latter coding
2861 system results in more "correct" output in the presence of control
2862 characters in the buffer, in the sense that when read in again using
2863 the same coding system, the result will virtually always match the
2864 original contents of the buffer, which is not the case with
2865 `iso-2022-8'; but the output is less portable when dealing with binary
2866 data -- there may be stray ESC characters when the file is read by
2867 another program.
2868
2869 `buffer-file-coding-system' does *not* control the coding system used when
2870 a file is read in.  Use the variables `buffer-file-coding-system-for-read'
2871 and `buffer-file-coding-system-alist' for that.  From a Lisp program, if
2872 you wish to unilaterally specify the coding system used for one
2873 particular operation, you should bind the variable
2874 `coding-system-for-read' rather than changing the other two
2875 variables just mentioned, which are intended to be used for
2876 global environment specification.
2877 */ );
2878 #endif /* FILE_CODING */
2879
2880   DEFVAR_BUFFER_LOCAL ("auto-fill-function", auto_fill_function /*
2881 Function called (if non-nil) to perform auto-fill.
2882 It is called after self-inserting a space at a column beyond `fill-column'.
2883 Each buffer has its own value of this variable.
2884 NOTE: This variable is not an ordinary hook;
2885 It may not be a list of functions.
2886 */ );
2887
2888   DEFVAR_BUFFER_LOCAL ("buffer-file-name", filename /*
2889 Name of file visited in current buffer, or nil if not visiting a file.
2890 Each buffer has its own value of this variable.
2891 */ );
2892
2893 #if 0 /* FSFmacs */
2894 /*
2895 Abbreviated truename of file visited in current buffer, or nil if none.
2896 The truename of a file is calculated by `file-truename'
2897 and then abbreviated with `abbreviate-file-name'.
2898 Each buffer has its own value of this variable.
2899 */
2900 #endif /* FSFmacs */
2901
2902   DEFVAR_BUFFER_LOCAL ("buffer-file-truename", file_truename /*
2903 The real name of the file visited in the current buffer,
2904 or nil if not visiting a file.  This is the result of passing
2905 buffer-file-name to the `file-truename' function.  Every buffer has
2906 its own value of this variable.  This variable is automatically
2907 maintained by the functions that change the file name associated
2908 with a buffer.
2909 */ );
2910
2911   DEFVAR_BUFFER_LOCAL ("buffer-auto-save-file-name", auto_save_file_name /*
2912 Name of file for auto-saving current buffer,
2913 or nil if buffer should not be auto-saved.
2914 Each buffer has its own value of this variable.
2915 */ );
2916
2917   DEFVAR_BUFFER_LOCAL ("buffer-read-only", read_only /*
2918 Non-nil if this buffer is read-only.
2919 Each buffer has its own value of this variable.
2920 */ );
2921
2922   DEFVAR_BUFFER_LOCAL ("buffer-backed-up", backed_up /*
2923 Non-nil if this buffer's file has been backed up.
2924 Backing up is done before the first time the file is saved.
2925 Each buffer has its own value of this variable.
2926 */ );
2927
2928   DEFVAR_BUFFER_LOCAL ("buffer-saved-size", saved_size /*
2929 Length of current buffer when last read in, saved or auto-saved.
2930 0 initially.
2931 Each buffer has its own value of this variable.
2932 */ );
2933
2934   DEFVAR_BUFFER_LOCAL_MAGIC ("selective-display", selective_display /*
2935 Non-nil enables selective display:
2936 Integer N as value means display only lines
2937  that start with less than n columns of space.
2938 A value of t means, after a ^M, all the rest of the line is invisible.
2939  Then ^M's in the file are written into files as newlines.
2940
2941 Automatically becomes buffer-local when set in any fashion.
2942 */, redisplay_variable_changed);
2943
2944 #ifndef old
2945   DEFVAR_BUFFER_LOCAL_MAGIC ("selective-display-ellipses",
2946                              selective_display_ellipses /*
2947 t means display ... on previous line when a line is invisible.
2948 Automatically becomes buffer-local when set in any fashion.
2949 */, redisplay_variable_changed);
2950 #endif
2951
2952   DEFVAR_BUFFER_LOCAL ("local-abbrev-table", abbrev_table /*
2953 Local (mode-specific) abbrev table of current buffer.
2954 */ );
2955
2956   DEFVAR_BUFFER_LOCAL ("overwrite-mode", overwrite_mode /*
2957 Non-nil if self-insertion should replace existing text.
2958 The value should be one of `overwrite-mode-textual',
2959 `overwrite-mode-binary', or nil.
2960 If it is `overwrite-mode-textual', self-insertion still
2961 inserts at the end of a line, and inserts when point is before a tab,
2962 until the tab is filled in.
2963 If `overwrite-mode-binary', self-insertion replaces newlines and tabs too.
2964 Automatically becomes buffer-local when set in any fashion.
2965
2966 Normally, you shouldn't modify this variable by hand, but use the functions
2967 `overwrite-mode' and `binary-overwrite-mode' instead. However, you can
2968 customize the default value from the options menu.
2969 */ );
2970
2971 #if 0 /* FSFmacs */
2972   /* Adds the following to the doc string for buffer-undo-list:
2973
2974 An entry (nil PROPERTY VALUE BEG . END) indicates that a text property
2975 was modified between BEG and END.  PROPERTY is the property name,
2976 and VALUE is the old value.
2977 */
2978 #endif /* FSFmacs */
2979
2980   DEFVAR_BUFFER_LOCAL ("buffer-undo-list", undo_list /*
2981 List of undo entries in current buffer.
2982 Recent changes come first; older changes follow newer.
2983
2984 An entry (BEG . END) represents an insertion which begins at
2985 position BEG and ends at position END.
2986
2987 An entry (TEXT . POSITION) represents the deletion of the string TEXT
2988 from (abs POSITION).  If POSITION is positive, point was at the front
2989 of the text being deleted; if negative, point was at the end.
2990
2991 An entry (t HIGH . LOW) indicates that the buffer previously had
2992 "unmodified" status.  HIGH and LOW are the high and low 16-bit portions
2993 of the visited file's modification time, as of that time.  If the
2994 modification time of the most recent save is different, this entry is
2995 obsolete.
2996
2997 An entry of the form EXTENT indicates that EXTENT was attached in
2998 the buffer.  Undoing an entry of this form detaches EXTENT.
2999
3000 An entry of the form (EXTENT START END) indicates that EXTENT was
3001 detached from the buffer.  Undoing an entry of this form attaches
3002 EXTENT from START to END.
3003
3004 An entry of the form POSITION indicates that point was at the buffer
3005 location given by the integer.  Undoing an entry of this form places
3006 point at POSITION.
3007
3008 nil marks undo boundaries.  The undo command treats the changes
3009 between two undo boundaries as a single step to be undone.
3010
3011 If the value of the variable is t, undo information is not recorded.
3012 */ );
3013
3014 #if 0 /* FSFmacs */
3015   xxDEFVAR_BUFFER_LOCAL ("mark-active", mark_active /*
3016 Non-nil means the mark and region are currently active in this buffer.
3017 Automatically local in all buffers.
3018 */ );
3019 #endif /* FSFmacs */
3020
3021 #ifdef REGION_CACHE_NEEDS_WORK
3022   xxDEFVAR_BUFFER_LOCAL ("cache-long-line-scans", cache_long_line_scans /*
3023 Non-nil means that Emacs should use caches to handle long lines more quickly.
3024 This variable is buffer-local, in all buffers.
3025
3026 Normally, the line-motion functions work by scanning the buffer for
3027 newlines.  Columnar operations (like move-to-column and
3028 compute-motion) also work by scanning the buffer, summing character
3029 widths as they go.  This works well for ordinary text, but if the
3030 buffer's lines are very long (say, more than 500 characters), these
3031 motion functions will take longer to execute.  Emacs may also take
3032 longer to update the display.
3033
3034 If cache-long-line-scans is non-nil, these motion functions cache the
3035 results of their scans, and consult the cache to avoid rescanning
3036 regions of the buffer until the text is modified.  The caches are most
3037 beneficial when they prevent the most searching---that is, when the
3038 buffer contains long lines and large regions of characters with the
3039 same, fixed screen width.
3040
3041 When cache-long-line-scans is non-nil, processing short lines will
3042 become slightly slower (because of the overhead of consulting the
3043 cache), and the caches will use memory roughly proportional to the
3044 number of newlines and characters whose screen width varies.
3045
3046 The caches require no explicit maintenance; their accuracy is
3047 maintained internally by the Emacs primitives.  Enabling or disabling
3048 the cache should not affect the behavior of any of the motion
3049 functions; it should only affect their performance.
3050 */ );
3051 #endif /* REGION_CACHE_NEEDS_WORK */
3052
3053   DEFVAR_BUFFER_LOCAL ("point-before-scroll", point_before_scroll /*
3054 Value of point before the last series of scroll operations, or nil.
3055 */ );
3056
3057   DEFVAR_BUFFER_LOCAL ("buffer-file-format", file_format /*
3058 List of formats to use when saving this buffer.
3059 Formats are defined by `format-alist'.  This variable is
3060 set when a file is visited.  Automatically local in all buffers.
3061 */ );
3062
3063   DEFVAR_BUFFER_LOCAL_MAGIC ("buffer-invisibility-spec", invisibility_spec /*
3064 Invisibility spec of this buffer.
3065 The default is t, which means that text is invisible
3066 if it has (or is covered by an extent with) a non-nil `invisible' property.
3067 If the value is a list, a text character is invisible if its `invisible'
3068 property is an element in that list.
3069 If an element is a cons cell of the form (PROP . ELLIPSIS),
3070 then characters with property value PROP are invisible,
3071 and they have an ellipsis as well if ELLIPSIS is non-nil.
3072 Note that the actual characters used for the ellipsis are controllable
3073 using `invisible-text-glyph', and default to "...".
3074 */, redisplay_variable_changed);
3075
3076   DEFVAR_CONST_BUFFER_LOCAL ("generated-modeline-string",
3077                              generated_modeline_string /*
3078 String of characters in this buffer's modeline as of the last redisplay.
3079 Each time the modeline is recomputed, the resulting characters are
3080 stored in this string, which is resized as necessary.  You may not
3081 set this variable, and modifying this string will not change the
3082 modeline; you have to change `modeline-format' if you want that.
3083
3084 For each extent in `modeline-format' that is encountered when
3085 processing the modeline, a corresponding extent is placed in
3086 `generated-modeline-string' and covers the text over which the
3087 extent in `modeline-format' applies.  The extent in
3088 `generated-modeline-string' is made a child of the extent in
3089 `modeline-format', which means that it inherits all properties from
3090 that extent.  Note that the extents in `generated-modeline-string'
3091 are managed automatically.  You should not explicitly put any extents
3092 in `generated-modeline-string'; if you do, they will disappear the
3093 next time the modeline is processed.
3094
3095 For extents in `modeline-format', the following properties are currently
3096 handled:
3097
3098 `face'
3099         Affects the face of the modeline text.  Currently, faces do
3100         not merge properly; only the most recently encountered face
3101         is used.  This is a bug.
3102
3103 `keymap'
3104         Affects the disposition of button events over the modeline
3105         text.  Multiple applicable keymaps *are* handled properly,
3106         and `modeline-map' still applies to any events that don't
3107         have bindings in extent-specific keymaps.
3108
3109 `help-echo'
3110         If a string, causes the string to be displayed when the mouse
3111         moves over the text.
3112 */ );
3113
3114   /* Check for DEFVAR_BUFFER_LOCAL without initializing the corresponding
3115      slot of buffer_local_flags and vice-versa.  Must be done after all
3116      DEFVAR_BUFFER_LOCAL() calls. */
3117 #define MARKED_SLOT(slot)                                       \
3118   if ((XINT (buffer_local_flags.slot) != -2 &&                  \
3119        XINT (buffer_local_flags.slot) != -3)                    \
3120       != !(NILP (XBUFFER (Vbuffer_local_symbols)->slot)))       \
3121   abort ()
3122 #include "bufslots.h"
3123 #undef MARKED_SLOT
3124
3125   {
3126     Lisp_Object scratch = Fget_buffer_create (QSscratch);
3127     Fset_buffer (scratch);
3128     /* Want no undo records for *scratch* until after Emacs is dumped */
3129     Fbuffer_disable_undo (scratch);
3130   }
3131 }
3132
3133 /* Is PWD another name for `.' ? */
3134 static int
3135 directory_is_current_directory (Extbyte *pwd)
3136 {
3137   Bufbyte *pwd_internal;
3138   Bytecount pwd_internal_len;
3139   struct stat dotstat, pwdstat;
3140
3141   TO_INTERNAL_FORMAT (DATA, (pwd, strlen ((char *)pwd) + 1),
3142                       ALLOCA, (pwd_internal, pwd_internal_len),
3143                       Qfile_name);
3144
3145   return (IS_DIRECTORY_SEP (*pwd_internal)
3146           && stat ((char *) pwd_internal, &pwdstat) == 0
3147           && stat (".", &dotstat) == 0
3148           && dotstat.st_ino == pwdstat.st_ino
3149           && dotstat.st_dev == pwdstat.st_dev
3150           && pwd_internal_len < MAXPATHLEN);
3151 }
3152
3153 void
3154 init_initial_directory (void)
3155 {
3156   /* This function can GC */
3157
3158   Extbyte *pwd;
3159
3160   initial_directory[0] = 0;
3161
3162   /* If PWD is accurate, use it instead of calling getcwd.  This is faster
3163      when PWD is right, and may avoid a fatal error.  */
3164   if ((pwd = (Extbyte *) getenv ("PWD")) != NULL
3165       && directory_is_current_directory (pwd))
3166     strcpy (initial_directory, (char *) pwd);
3167   else if (getcwd (initial_directory, MAXPATHLEN) == NULL)
3168     fatal ("`getcwd' failed: %s\n", strerror (errno));
3169
3170   /* Make sure pwd is DIRECTORY_SEP-terminated.
3171      Maybe this should really use some standard subroutine
3172      whose definition is filename syntax dependent.  */
3173   {
3174     int len = strlen (initial_directory);
3175
3176     if (! IS_DIRECTORY_SEP (initial_directory[len - 1]))
3177       {
3178         initial_directory[len] = DIRECTORY_SEP;
3179         initial_directory[len + 1] = '\0';
3180       }
3181   }
3182
3183   /* XEmacs change: store buffer's default directory
3184      using preferred (i.e. as defined at compile-time)
3185      directory separator. --marcpa */
3186 #ifdef DOS_NT
3187 #define CORRECT_DIR_SEPS(s) \
3188   do { if ('/' == DIRECTORY_SEP) dostounix_filename (s); \
3189        else unixtodos_filename (s); \
3190   } while (0)
3191
3192   CORRECT_DIR_SEPS(initial_directory);
3193 #endif
3194 }
3195
3196 void
3197 init_buffer (void)
3198 {
3199   /* This function can GC */
3200
3201   Fset_buffer (Fget_buffer_create (QSscratch));
3202
3203   current_buffer->directory =
3204     build_ext_string (initial_directory, Qfile_name);
3205
3206 #if 0 /* FSFmacs */
3207   /* #### is this correct? */
3208   temp = get_minibuffer (0);
3209   XBUFFER (temp)->directory = current_buffer->directory;
3210 #endif /* FSFmacs */
3211 }