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