import xemacs-21.2.37
[chise/xemacs-chise.git] / src / buffer.h
1 /* Header file for the buffer manipulation primitives.
2    Copyright (C) 1985, 1986, 1992, 1993, 1994, 1995
3    Free Software Foundation, Inc.
4    Copyright (C) 1995 Sun Microsystems, Inc.
5
6 This file is part of XEmacs.
7
8 XEmacs is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation; either version 2, or (at your option) any
11 later version.
12
13 XEmacs is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with XEmacs; see the file COPYING.  If not, write to
20 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 Boston, MA 02111-1307, USA.  */
22
23 /* Synched up with: FSF 19.30. */
24
25 /* Authorship:
26
27    FSF: long ago.
28    JWZ: separated out bufslots.h, early in Lemacs.
29    Ben Wing: almost completely rewritten for Mule, 19.12.
30  */
31
32 #ifndef INCLUDED_buffer_h_
33 #define INCLUDED_buffer_h_
34
35 #ifdef MULE
36 #include "mule-charset.h"
37 #endif
38
39 /************************************************************************/
40 /*                                                                      */
41 /*                    definition of Lisp buffer object                  */
42 /*                                                                      */
43 /************************************************************************/
44
45 /* Note: we keep both Bytind and Bufpos versions of some of the
46    important buffer positions because they are accessed so much.
47    If we didn't do this, we would constantly be invalidating the
48    bufpos<->bytind cache under Mule.
49
50    Note that under non-Mule, both versions will always be the
51    same so we don't really need to keep track of them.  But it
52    simplifies the logic to go ahead and do so all the time and
53    the memory loss is insignificant. */
54
55 /* Formerly, it didn't much matter what went inside the struct buffer_text
56    and what went outside it.  Now it does, with the advent of "indirect
57    buffers" that share text with another buffer.  An indirect buffer
58    shares the same *text* as another buffer, but has its own buffer-local
59    variables, its own accessible region, and its own markers and extents.
60    (Due to the nature of markers, it doesn't actually matter much whether
61    we stick them inside or out of the struct buffer_text -- the user won't
62    notice any difference -- but we go ahead and put them outside for
63    consistency and overall saneness of algorithm.)
64
65    FSFmacs gets away with not maintaining any "children" pointers from
66    a buffer to the indirect buffers that refer to it by putting the
67    markers inside of the struct buffer_text, using markers to keep track
68    of BEGV and ZV in indirect buffers, and relying on the fact that
69    all intervals (text properties and overlays) use markers for their
70    start and end points.  We don't do this for extents (markers are
71    inefficient anyway and take up space), so we have to maintain
72    children pointers.  This is not terribly hard, though, and the
73    code to maintain this is just like the code already present in
74    extent-parent and extent-children.
75    */
76
77 struct buffer_text
78 {
79   Bufbyte *beg;         /* Actual address of buffer contents. */
80   Bytind gpt;           /* Index of gap in buffer. */
81   Bytind z;             /* Index of end of buffer. */
82   Bufpos bufz;          /* Equivalent as a Bufpos. */
83   int gap_size;         /* Size of buffer's gap */
84   int end_gap_size;     /* Size of buffer's end gap */
85   long modiff;          /* This counts buffer-modification events
86                            for this buffer.  It is incremented for
87                            each such event, and never otherwise
88                            changed.  */
89   long save_modiff;     /* Previous value of modiff, as of last
90                            time buffer visited or saved a file.  */
91
92 #ifdef MULE
93   /* We keep track of a "known" region for very fast access.
94      This information is text-only so it goes here. */
95   Bufpos mule_bufmin, mule_bufmax;
96   Bytind mule_bytmin, mule_bytmax;
97   int mule_shifter, mule_three_p;
98
99   /* And we also cache 16 positions for fairly fast access near those
100      positions. */
101   Bufpos mule_bufpos_cache[16];
102   Bytind mule_bytind_cache[16];
103 #endif
104
105   /* Similar to the above, we keep track of positions for which line
106      number has last been calculated.  See line-number.c. */
107   Lisp_Object line_number_cache;
108
109   /* Change data that goes with the text. */
110   struct buffer_text_change_data *changes;
111
112 };
113
114 struct buffer
115 {
116   struct lcrecord_header header;
117
118   /* This structure holds the coordinates of the buffer contents
119      in ordinary buffers.  In indirect buffers, this is not used.  */
120   struct buffer_text own_text;
121
122   /* This points to the `struct buffer_text' that is used for this buffer.
123      In an ordinary buffer, this is the own_text field above.
124      In an indirect buffer, this is the own_text field of another buffer.  */
125   struct buffer_text *text;
126
127   Bytind pt;            /* Position of point in buffer. */
128   Bufpos bufpt;         /* Equivalent as a Bufpos. */
129   Bytind begv;          /* Index of beginning of accessible range. */
130   Bufpos bufbegv;       /* Equivalent as a Bufpos. */
131   Bytind zv;            /* Index of end of accessible range. */
132   Bufpos bufzv;         /* Equivalent as a Bufpos. */
133
134   int face_change;      /* This is set when a change in how the text should
135                            be displayed (e.g., font, color) is made. */
136
137   /* change data indicating what portion of the text has changed
138      since the last time this was reset.  Used by redisplay.
139      Logically we should keep this with the text structure, but
140      redisplay resets it for each buffer individually and we don't
141      want interference between an indirect buffer and its base
142      buffer. */
143   struct each_buffer_change_data *changes;
144
145 #ifdef REGION_CACHE_NEEDS_WORK
146   /* If the long line scan cache is enabled (i.e. the buffer-local
147      variable cache-long-line-scans is non-nil), newline_cache
148      points to the newline cache, and width_run_cache points to the
149      width run cache.
150
151      The newline cache records which stretches of the buffer are
152      known *not* to contain newlines, so that they can be skipped
153      quickly when we search for newlines.
154
155      The width run cache records which stretches of the buffer are
156      known to contain characters whose widths are all the same.  If
157      the width run cache maps a character to a value > 0, that value
158      is the character's width; if it maps a character to zero, we
159      don't know what its width is.  This allows compute_motion to
160      process such regions very quickly, using algebra instead of
161      inspecting each character.  See also width_table, below.  */
162   struct region_cache *newline_cache;
163   struct region_cache *width_run_cache;
164 #endif /* REGION_CACHE_NEEDS_WORK */
165
166   /* The markers that refer to this buffer.  This is actually a single
167      marker -- successive elements in its marker `chain' are the other
168      markers referring to this buffer */
169   Lisp_Marker *markers;
170
171   /* The buffer's extent info.  This is its own type, an extent-info
172      object (done this way for ease in marking / finalizing). */
173   Lisp_Object extent_info;
174
175   /* ----------------------------------------------------------------- */
176   /* All the stuff above this line is the responsibility of insdel.c,
177      with some help from marker.c and extents.c.
178      All the stuff below this line is the responsibility of buffer.c. */
179
180   /* In an indirect buffer, this points to the base buffer.
181      In an ordinary buffer, it is 0.
182      We DO mark through this slot. */
183   struct buffer *base_buffer;
184
185   /* List of indirect buffers whose base is this buffer.
186      If we are an indirect buffer, this will be nil.
187      Do NOT mark through this. */
188   Lisp_Object indirect_children;
189
190   /* Flags saying which DEFVAR_PER_BUFFER variables
191      are local to this buffer.  */
192   int local_var_flags;
193
194   /* Set to the modtime of the visited file when read or written.
195      -1 means visited file was nonexistent.
196      0  means visited file modtime unknown; in no case complain
197      about any mismatch on next save attempt.  */
198   int modtime;
199
200   /* the value of text->modiff at the last auto-save.  */
201   long auto_save_modified;
202
203   /* The time at which we detected a failure to auto-save,
204      Or -1 if we didn't have a failure.  */
205   int auto_save_failure_time;
206
207   /* Position in buffer at which display started
208      the last time this buffer was displayed.  */
209   int last_window_start;
210
211   /* Everything from here down must be a Lisp_Object */
212
213 #define MARKED_SLOT(x) Lisp_Object x
214 #include "bufslots.h"
215 #undef MARKED_SLOT
216 };
217
218 DECLARE_LRECORD (buffer, struct buffer);
219 #define XBUFFER(x) XRECORD (x, buffer, struct buffer)
220 #define XSETBUFFER(x, p) XSETRECORD (x, p, buffer)
221 #define BUFFERP(x) RECORDP (x, buffer)
222 #define CHECK_BUFFER(x) CHECK_RECORD (x, buffer)
223 #define CONCHECK_BUFFER(x) CONCHECK_RECORD (x, buffer)
224
225 #define BUFFER_LIVE_P(b) (!NILP ((b)->name))
226
227 #define CHECK_LIVE_BUFFER(x) do {                       \
228   CHECK_BUFFER (x);                                     \
229   if (!BUFFER_LIVE_P (XBUFFER (x)))                     \
230     dead_wrong_type_argument (Qbuffer_live_p, (x));     \
231 } while (0)
232
233 #define CONCHECK_LIVE_BUFFER(x) do {                    \
234   CONCHECK_BUFFER (x);                                  \
235   if (!BUFFER_LIVE_P (XBUFFER (x)))                     \
236     x = wrong_type_argument (Qbuffer_live_p, (x));      \
237 } while (0)
238
239 \f
240 #define BUFFER_BASE_BUFFER(b) ((b)->base_buffer ? (b)->base_buffer : (b))
241
242 /* Map over buffers sharing the same text as MPS_BUF.  MPS_BUFVAR is a
243    variable that gets the buffer values (beginning with the base
244    buffer, then the children), and MPS_BUFCONS should be a temporary
245    Lisp_Object variable.  */
246 #define MAP_INDIRECT_BUFFERS(mps_buf, mps_bufvar, mps_bufcons)                  \
247 for (mps_bufcons = Qunbound,                                                    \
248      mps_bufvar = BUFFER_BASE_BUFFER (mps_buf);                                 \
249      UNBOUNDP (mps_bufcons) ?                                                   \
250         (mps_bufcons = mps_bufvar->indirect_children,                           \
251         1)                                                                      \
252        : (!NILP (mps_bufcons)                                                   \
253           && (mps_bufvar = XBUFFER (XCAR (mps_bufcons)), 1)                     \
254           && (mps_bufcons = XCDR (mps_bufcons), 1));                            \
255      )
256
257 \f
258
259 /************************************************************************/
260 /*                                                                      */
261 /*                 working with raw internal-format data                */
262 /*                                                                      */
263 /************************************************************************/
264
265 /* NOTE: In all the following macros, we follow these rules concerning
266    multiple evaluation of the arguments:
267
268    1) Anything that's an lvalue can be evaluated more than once.
269    2) Anything that's a Lisp Object can be evaluated more than once.
270       This should probably be changed, but this follows the way
271       that all the macros in lisp.h do things.
272    3) 'struct buffer *' arguments can be evaluated more than once.
273    4) Nothing else can be evaluated more than once.  Use inline
274       functions, if necessary, to prevent multiple evaluation.
275    5) An exception to (4) is that there are some macros below that
276       may evaluate their arguments more than once.  They are all
277       denoted with the word "unsafe" in their name and are generally
278       meant to be called only by other macros that have already
279       stored the calling values in temporary variables.
280
281
282    Use the following functions/macros on contiguous strings of data.
283    If the text you're operating on is known to come from a buffer, use
284    the buffer-level functions below -- they know about the gap and may
285    be more efficient.
286
287
288   (A) For working with charptr's (pointers to internally-formatted text):
289   -----------------------------------------------------------------------
290
291    VALID_CHARPTR_P (ptr):
292         Given a charptr, does it point to the beginning of a character?
293
294    ASSERT_VALID_CHARPTR (ptr):
295         If error-checking is enabled, assert that the given charptr
296         points to the beginning of a character.  Otherwise, do nothing.
297
298    INC_CHARPTR (ptr):
299         Given a charptr (assumed to point at the beginning of a character),
300         modify that pointer so it points to the beginning of the next
301         character.
302
303    DEC_CHARPTR (ptr):
304         Given a charptr (assumed to point at the beginning of a
305         character or at the very end of the text), modify that pointer
306         so it points to the beginning of the previous character.
307
308    VALIDATE_CHARPTR_BACKWARD (ptr):
309         Make sure that PTR is pointing to the beginning of a character.
310         If not, back up until this is the case.   Note that there are not
311         too many places where it is legitimate to do this sort of thing.
312         It's an error if you're passed an "invalid" char * pointer.
313         NOTE: PTR *must* be pointing to a valid part of the string (i.e.
314         not the very end, unless the string is zero-terminated or
315         something) in order for this function to not cause crashes.
316
317    VALIDATE_CHARPTR_FORWARD (ptr):
318         Make sure that PTR is pointing to the beginning of a character.
319         If not, move forward until this is the case.  Note that there
320         are not too many places where it is legitimate to do this sort
321         of thing.  It's an error if you're passed an "invalid" char *
322         pointer.
323
324
325    (B) For working with the length (in bytes and characters) of a
326        section of internally-formatted text:
327    --------------------------------------------------------------
328
329    bytecount_to_charcount (ptr, nbi):
330         Given a pointer to a text string and a length in bytes,
331         return the equivalent length in characters.
332
333    charcount_to_bytecount (ptr, nch):
334         Given a pointer to a text string and a length in characters,
335         return the equivalent length in bytes.
336
337    charptr_n_addr (ptr, n):
338         Return a pointer to the beginning of the character offset N
339         (in characters) from PTR.
340
341
342    (C) For retrieving or changing the character pointed to by a charptr:
343    ---------------------------------------------------------------------
344
345    charptr_emchar (ptr):
346         Retrieve the character pointed to by PTR as an Emchar.
347
348    charptr_emchar_n (ptr, n):
349         Retrieve the character at offset N (in characters) from PTR,
350         as an Emchar.
351
352    set_charptr_emchar (ptr, ch):
353         Store the character CH (an Emchar) as internally-formatted
354         text starting at PTR.  Return the number of bytes stored.
355
356    charptr_copy_char (ptr, ptr2):
357         Retrieve the character pointed to by PTR and store it as
358         internally-formatted text in PTR2.
359
360
361    (D) For working with Emchars:
362    -----------------------------
363
364    [Note that there are other functions/macros for working with Emchars
365     in mule-charset.h, for retrieving the charset of an Emchar
366     and such.  These are only valid when MULE is defined.]
367
368    valid_char_p (ch):
369         Return whether the given Emchar is valid.
370
371    CHARP (ch):
372         Return whether the given Lisp_Object is a character.
373
374    CHECK_CHAR_COERCE_INT (ch):
375         Signal an error if CH is not a valid character or integer Lisp_Object.
376         If CH is an integer Lisp_Object, convert it to a character Lisp_Object,
377         but merely by repackaging, without performing tests for char validity.
378
379    MAX_EMCHAR_LEN:
380         Maximum number of buffer bytes per Emacs character.
381
382 */
383
384
385 /* ---------------------------------------------------------------------- */
386 /* (A) For working with charptr's (pointers to internally-formatted text) */
387 /* ---------------------------------------------------------------------- */
388
389 #ifdef MULE
390 # define VALID_CHARPTR_P(ptr) BUFBYTE_FIRST_BYTE_P (* (unsigned char *) ptr)
391 #else
392 # define VALID_CHARPTR_P(ptr) 1
393 #endif
394
395 #ifdef ERROR_CHECK_BUFPOS
396 # define ASSERT_VALID_CHARPTR(ptr) assert (VALID_CHARPTR_P (ptr))
397 #else
398 # define ASSERT_VALID_CHARPTR(ptr)
399 #endif
400
401 /* Note that INC_CHARPTR() and DEC_CHARPTR() have to be written in
402    completely separate ways.  INC_CHARPTR() cannot use the DEC_CHARPTR()
403    trick of looking for a valid first byte because it might run off
404    the end of the string.  DEC_CHARPTR() can't use the INC_CHARPTR()
405    method because it doesn't have easy access to the first byte of
406    the character it's moving over. */
407
408 #define REAL_INC_CHARPTR(ptr) \
409   ((void) ((ptr) += REP_BYTES_BY_FIRST_BYTE (* (unsigned char *) (ptr))))
410
411 #define REAL_INC_CHARBYTIND(ptr, pos) \
412   (pos += REP_BYTES_BY_FIRST_BYTE (* (unsigned char *) (ptr)))
413
414 #define REAL_DEC_CHARPTR(ptr) do {      \
415   (ptr)--;                              \
416 } while (!VALID_CHARPTR_P (ptr))
417
418 #ifdef ERROR_CHECK_BUFPOS
419 #define INC_CHARPTR(ptr) do {           \
420   ASSERT_VALID_CHARPTR (ptr);           \
421   REAL_INC_CHARPTR (ptr);               \
422 } while (0)
423
424 #define INC_CHARBYTIND(ptr, pos) do {           \
425   ASSERT_VALID_CHARPTR (ptr);                   \
426   REAL_INC_CHARBYTIND (ptr, pos);               \
427 } while (0)
428
429 #define DEC_CHARPTR(ptr) do {                   \
430   const Bufbyte *dc_ptr1 = (ptr);               \
431   const Bufbyte *dc_ptr2 = dc_ptr1;             \
432   REAL_DEC_CHARPTR (dc_ptr2);                   \
433   assert (dc_ptr1 - dc_ptr2 ==                  \
434           REP_BYTES_BY_FIRST_BYTE (*dc_ptr2));  \
435   (ptr) = (Bufbyte *) dc_ptr2;                  \
436 } while (0)
437
438 #else /* ! ERROR_CHECK_BUFPOS */
439 #define INC_CHARBYTIND(ptr, pos) REAL_INC_CHARBYTIND (ptr, pos)
440 #define INC_CHARPTR(ptr) REAL_INC_CHARPTR (ptr)
441 #define DEC_CHARPTR(ptr) REAL_DEC_CHARPTR (ptr)
442 #endif /* ! ERROR_CHECK_BUFPOS */
443
444 #ifdef MULE
445
446 #define VALIDATE_CHARPTR_BACKWARD(ptr) do {     \
447   while (!VALID_CHARPTR_P (ptr)) ptr--;         \
448 } while (0)
449
450 /* This needs to be trickier to avoid the possibility of running off
451    the end of the string. */
452
453 #define VALIDATE_CHARPTR_FORWARD(ptr) do {      \
454   Bufbyte *vcf_ptr = (ptr);                     \
455   VALIDATE_CHARPTR_BACKWARD (vcf_ptr);          \
456   if (vcf_ptr != (ptr))                         \
457     {                                           \
458       (ptr) = vcf_ptr;                          \
459       INC_CHARPTR (ptr);                        \
460     }                                           \
461 } while (0)
462
463 #else /* not MULE */
464 #define VALIDATE_CHARPTR_BACKWARD(ptr)
465 #define VALIDATE_CHARPTR_FORWARD(ptr)
466 #endif /* not MULE */
467
468 /* -------------------------------------------------------------- */
469 /* (B) For working with the length (in bytes and characters) of a */
470 /*     section of internally-formatted text                       */
471 /* -------------------------------------------------------------- */
472
473 INLINE_HEADER const Bufbyte *
474 charptr_n_addr (const Bufbyte *ptr, Charcount offset);
475 INLINE_HEADER const Bufbyte *
476 charptr_n_addr (const Bufbyte *ptr, Charcount offset)
477 {
478   return ptr + charcount_to_bytecount (ptr, offset);
479 }
480
481 /* -------------------------------------------------------------------- */
482 /* (C) For retrieving or changing the character pointed to by a charptr */
483 /* -------------------------------------------------------------------- */
484
485 #define simple_charptr_emchar(ptr)              ((Emchar) (ptr)[0])
486 #define simple_set_charptr_emchar(ptr, x)       ((ptr)[0] = (Bufbyte) (x), 1)
487 #define simple_charptr_copy_char(ptr, ptr2)     ((ptr2)[0] = *(ptr), 1)
488
489 #ifdef MULE
490
491 Emchar non_ascii_charptr_emchar (const Bufbyte *ptr);
492 Bytecount non_ascii_set_charptr_emchar (Bufbyte *ptr, Emchar c);
493 Bytecount non_ascii_charptr_copy_char (const Bufbyte *src, Bufbyte *dst);
494
495 INLINE_HEADER Emchar charptr_emchar (const Bufbyte *ptr);
496 INLINE_HEADER Emchar
497 charptr_emchar (const Bufbyte *ptr)
498 {
499   return BYTE_ASCII_P (*ptr) ?
500     simple_charptr_emchar (ptr) :
501     non_ascii_charptr_emchar (ptr);
502 }
503
504 INLINE_HEADER Bytecount set_charptr_emchar (Bufbyte *ptr, Emchar x);
505 INLINE_HEADER Bytecount
506 set_charptr_emchar (Bufbyte *ptr, Emchar x)
507 {
508   return !CHAR_MULTIBYTE_P (x) ?
509     simple_set_charptr_emchar (ptr, x) :
510     non_ascii_set_charptr_emchar (ptr, x);
511 }
512
513 /* Copy the character pointed to by SRC into DST.
514    Return the number of bytes copied.  */
515 INLINE_HEADER Bytecount
516 charptr_copy_char (const Bufbyte *src, Bufbyte *dst);
517 INLINE_HEADER Bytecount
518 charptr_copy_char (const Bufbyte *src, Bufbyte *dst)
519 {
520   return BYTE_ASCII_P (*src) ?
521     simple_charptr_copy_char (src, dst) :
522     non_ascii_charptr_copy_char (src, dst);
523 }
524
525 #else /* not MULE */
526
527 # define charptr_emchar(ptr)            simple_charptr_emchar (ptr)
528 # define set_charptr_emchar(ptr, x)     simple_set_charptr_emchar (ptr, x)
529 # define charptr_copy_char(ptr, ptr2)   simple_charptr_copy_char (ptr, ptr2)
530
531 #endif /* not MULE */
532
533 #define charptr_emchar_n(ptr, offset) \
534   charptr_emchar (charptr_n_addr (ptr, offset))
535
536
537 /* ---------------------------- */
538 /* (D) For working with Emchars */
539 /* ---------------------------- */
540
541 #ifdef MULE
542
543 int non_ascii_valid_char_p (Emchar ch);
544
545 INLINE_HEADER int valid_char_p (Emchar ch);
546 INLINE_HEADER int
547 valid_char_p (Emchar ch)
548 {
549   return ((unsigned int) (ch) <= 0xff) || non_ascii_valid_char_p (ch);
550 }
551
552 #else /* not MULE */
553
554 #define valid_char_p(ch) ((unsigned int) (ch) <= 0xff)
555
556 #endif /* not MULE */
557
558 #define CHAR_INTP(x) (INTP (x) && valid_char_p (XINT (x)))
559
560 #define CHAR_OR_CHAR_INTP(x) (CHARP (x) || CHAR_INTP (x))
561
562 INLINE_HEADER Emchar XCHAR_OR_CHAR_INT (Lisp_Object obj);
563 INLINE_HEADER Emchar
564 XCHAR_OR_CHAR_INT (Lisp_Object obj)
565 {
566   return CHARP (obj) ? XCHAR (obj) : XINT (obj);
567 }
568
569 #define CHECK_CHAR_COERCE_INT(x) do {           \
570   if (CHARP (x))                                \
571      ;                                          \
572   else if (CHAR_INTP (x))                       \
573     x = make_char (XINT (x));                   \
574   else                                          \
575     x = wrong_type_argument (Qcharacterp, x);   \
576 } while (0)
577
578 #ifdef MULE
579 # define MAX_EMCHAR_LEN 4
580 #else
581 # define MAX_EMCHAR_LEN 1
582 #endif
583
584 \f
585 /*----------------------------------------------------------------------*/
586 /*          Accessor macros for important positions in a buffer         */
587 /*----------------------------------------------------------------------*/
588
589 /* We put them here because some stuff below wants them before the
590    place where we would normally put them. */
591
592 /* None of these are lvalues.  Use the settor macros below to change
593    the positions. */
594
595 /* Beginning of buffer.  */
596 #define BI_BUF_BEG(buf) ((Bytind) 1)
597 #define BUF_BEG(buf) ((Bufpos) 1)
598
599 /* Beginning of accessible range of buffer.  */
600 #define BI_BUF_BEGV(buf) ((buf)->begv + 0)
601 #define BUF_BEGV(buf) ((buf)->bufbegv + 0)
602
603 /* End of accessible range of buffer.  */
604 #define BI_BUF_ZV(buf) ((buf)->zv + 0)
605 #define BUF_ZV(buf) ((buf)->bufzv + 0)
606
607 /* End of buffer.  */
608 #define BI_BUF_Z(buf) ((buf)->text->z + 0)
609 #define BUF_Z(buf) ((buf)->text->bufz + 0)
610
611 /* Point. */
612 #define BI_BUF_PT(buf) ((buf)->pt + 0)
613 #define BUF_PT(buf) ((buf)->bufpt + 0)
614
615 /*----------------------------------------------------------------------*/
616 /*              Converting between positions and addresses              */
617 /*----------------------------------------------------------------------*/
618
619 /* Convert the address of a byte in the buffer into a position.  */
620 INLINE_HEADER Bytind BI_BUF_PTR_BYTE_POS (struct buffer *buf, Bufbyte *ptr);
621 INLINE_HEADER Bytind
622 BI_BUF_PTR_BYTE_POS (struct buffer *buf, Bufbyte *ptr)
623 {
624   return (ptr - buf->text->beg + 1
625           - ((ptr - buf->text->beg + 1) > buf->text->gpt
626              ? buf->text->gap_size : 0));
627 }
628
629 #define BUF_PTR_BYTE_POS(buf, ptr) \
630   bytind_to_bufpos (buf, BI_BUF_PTR_BYTE_POS (buf, ptr))
631
632 /* Address of byte at position POS in buffer. */
633 INLINE_HEADER Bufbyte * BI_BUF_BYTE_ADDRESS (struct buffer *buf, Bytind pos);
634 INLINE_HEADER Bufbyte *
635 BI_BUF_BYTE_ADDRESS (struct buffer *buf, Bytind pos)
636 {
637   return (buf->text->beg +
638           ((pos >= buf->text->gpt ? (pos + buf->text->gap_size) : pos)
639            - 1));
640 }
641
642 #define BUF_BYTE_ADDRESS(buf, pos) \
643   BI_BUF_BYTE_ADDRESS (buf, bufpos_to_bytind (buf, pos))
644
645 /* Address of byte before position POS in buffer. */
646 INLINE_HEADER Bufbyte * BI_BUF_BYTE_ADDRESS_BEFORE (struct buffer *buf, Bytind pos);
647 INLINE_HEADER Bufbyte *
648 BI_BUF_BYTE_ADDRESS_BEFORE (struct buffer *buf, Bytind pos)
649 {
650   return (buf->text->beg +
651           ((pos > buf->text->gpt ? (pos + buf->text->gap_size) : pos)
652            - 2));
653 }
654
655 #define BUF_BYTE_ADDRESS_BEFORE(buf, pos) \
656   BI_BUF_BYTE_ADDRESS_BEFORE (buf, bufpos_to_bytind (buf, pos))
657
658 /*----------------------------------------------------------------------*/
659 /*          Converting between byte indices and memory indices          */
660 /*----------------------------------------------------------------------*/
661
662 INLINE_HEADER int valid_memind_p (struct buffer *buf, Memind x);
663 INLINE_HEADER int
664 valid_memind_p (struct buffer *buf, Memind x)
665 {
666   return ((x >= 1 && x <= (Memind) buf->text->gpt) ||
667           (x  > (Memind) (buf->text->gpt + buf->text->gap_size) &&
668            x <= (Memind) (buf->text->z   + buf->text->gap_size)));
669 }
670
671 INLINE_HEADER Memind bytind_to_memind (struct buffer *buf, Bytind x);
672 INLINE_HEADER Memind
673 bytind_to_memind (struct buffer *buf, Bytind x)
674 {
675   return (Memind) ((x > buf->text->gpt) ? (x + buf->text->gap_size) : x);
676 }
677
678
679 INLINE_HEADER Bytind memind_to_bytind (struct buffer *buf, Memind x);
680 INLINE_HEADER Bytind
681 memind_to_bytind (struct buffer *buf, Memind x)
682 {
683 #ifdef ERROR_CHECK_BUFPOS
684   assert (valid_memind_p (buf, x));
685 #endif
686   return (Bytind) ((x > (Memind) buf->text->gpt) ?
687                    x - buf->text->gap_size :
688                    x);
689 }
690
691 #define memind_to_bufpos(buf, x) \
692   bytind_to_bufpos (buf, memind_to_bytind (buf, x))
693 #define bufpos_to_memind(buf, x) \
694   bytind_to_memind (buf, bufpos_to_bytind (buf, x))
695
696 /* These macros generalize many standard buffer-position functions to
697    either a buffer or a string. */
698
699 /* Converting between Meminds and Bytinds, for a buffer-or-string.
700    For strings, this is a no-op.  For buffers, this resolves
701    to the standard memind<->bytind converters. */
702
703 #define buffer_or_string_bytind_to_memind(obj, ind) \
704   (BUFFERP (obj) ? bytind_to_memind (XBUFFER (obj), ind) : (Memind) ind)
705
706 #define buffer_or_string_memind_to_bytind(obj, ind) \
707   (BUFFERP (obj) ? memind_to_bytind (XBUFFER (obj), ind) : (Bytind) ind)
708
709 /* Converting between Bufpos's and Bytinds, for a buffer-or-string.
710    For strings, this maps to the bytecount<->charcount converters. */
711
712 #define buffer_or_string_bufpos_to_bytind(obj, pos)             \
713   (BUFFERP (obj) ? bufpos_to_bytind (XBUFFER (obj), pos) :      \
714    (Bytind) charcount_to_bytecount (XSTRING_DATA (obj), pos))
715
716 #define buffer_or_string_bytind_to_bufpos(obj, ind)             \
717   (BUFFERP (obj) ? bytind_to_bufpos (XBUFFER (obj), ind) :      \
718    (Bufpos) bytecount_to_charcount (XSTRING_DATA (obj), ind))
719
720 /* Similar for Bufpos's and Meminds. */
721
722 #define buffer_or_string_bufpos_to_memind(obj, pos)             \
723   (BUFFERP (obj) ? bufpos_to_memind (XBUFFER (obj), pos) :      \
724    (Memind) charcount_to_bytecount (XSTRING_DATA (obj), pos))
725
726 #define buffer_or_string_memind_to_bufpos(obj, ind)             \
727   (BUFFERP (obj) ? memind_to_bufpos (XBUFFER (obj), ind) :      \
728    (Bufpos) bytecount_to_charcount (XSTRING_DATA (obj), ind))
729
730 /************************************************************************/
731 /*                                                                      */
732 /*                    working with buffer-level data                    */
733 /*                                                                      */
734 /************************************************************************/
735
736 /*
737
738    (A) Working with byte indices:
739    ------------------------------
740
741    VALID_BYTIND_P(buf, bi):
742         Given a byte index, does it point to the beginning of a character?
743
744    ASSERT_VALID_BYTIND_UNSAFE(buf, bi):
745         If error-checking is enabled, assert that the given byte index
746         is within range and points to the beginning of a character
747         or to the end of the buffer.  Otherwise, do nothing.
748
749    ASSERT_VALID_BYTIND_BACKWARD_UNSAFE(buf, bi):
750         If error-checking is enabled, assert that the given byte index
751         is within range and satisfies ASSERT_VALID_BYTIND() and also
752         does not refer to the beginning of the buffer. (i.e. movement
753         backwards is OK.) Otherwise, do nothing.
754
755    ASSERT_VALID_BYTIND_FORWARD_UNSAFE(buf, bi):
756         If error-checking is enabled, assert that the given byte index
757         is within range and satisfies ASSERT_VALID_BYTIND() and also
758         does not refer to the end of the buffer. (i.e. movement
759         forwards is OK.) Otherwise, do nothing.
760
761    VALIDATE_BYTIND_BACKWARD(buf, bi):
762         Make sure that the given byte index is pointing to the beginning
763         of a character.  If not, back up until this is the case.  Note
764         that there are not too many places where it is legitimate to do
765         this sort of thing.  It's an error if you're passed an "invalid"
766         byte index.
767
768    VALIDATE_BYTIND_FORWARD(buf, bi):
769         Make sure that the given byte index is pointing to the beginning
770         of a character.  If not, move forward until this is the case.
771         Note that there are not too many places where it is legitimate
772         to do this sort of thing.  It's an error if you're passed an
773         "invalid" byte index.
774
775    INC_BYTIND(buf, bi):
776         Given a byte index (assumed to point at the beginning of a
777         character), modify that value so it points to the beginning
778         of the next character.
779
780    DEC_BYTIND(buf, bi):
781         Given a byte index (assumed to point at the beginning of a
782         character), modify that value so it points to the beginning
783         of the previous character.  Unlike for DEC_CHARPTR(), we can
784         do all the assert()s because there are sentinels at the
785         beginning of the gap and the end of the buffer.
786
787    BYTIND_INVALID:
788         A constant representing an invalid Bytind.  Valid Bytinds
789         can never have this value.
790
791
792    (B) Converting between Bufpos's and Bytinds:
793    --------------------------------------------
794
795     bufpos_to_bytind(buf, bu):
796         Given a Bufpos, return the equivalent Bytind.
797
798     bytind_to_bufpos(buf, bi):
799         Given a Bytind, return the equivalent Bufpos.
800
801     make_bufpos(buf, bi):
802         Given a Bytind, return the equivalent Bufpos as a Lisp Object.
803  */
804
805
806 /*----------------------------------------------------------------------*/
807 /*                       working with byte indices                      */
808 /*----------------------------------------------------------------------*/
809
810 #ifdef MULE
811 # define VALID_BYTIND_P(buf, x) \
812   BUFBYTE_FIRST_BYTE_P (*BI_BUF_BYTE_ADDRESS (buf, x))
813 #else
814 # define VALID_BYTIND_P(buf, x) 1
815 #endif
816
817 #ifdef ERROR_CHECK_BUFPOS
818
819 # define ASSERT_VALID_BYTIND_UNSAFE(buf, x) do {                \
820   assert (BUFFER_LIVE_P (buf));                                 \
821   assert ((x) >= BI_BUF_BEG (buf) && x <= BI_BUF_Z (buf));      \
822   assert (VALID_BYTIND_P (buf, x));                             \
823 } while (0)
824 # define ASSERT_VALID_BYTIND_BACKWARD_UNSAFE(buf, x) do {       \
825   assert (BUFFER_LIVE_P (buf));                                 \
826   assert ((x) > BI_BUF_BEG (buf) && x <= BI_BUF_Z (buf));       \
827   assert (VALID_BYTIND_P (buf, x));                             \
828 } while (0)
829 # define ASSERT_VALID_BYTIND_FORWARD_UNSAFE(buf, x) do {        \
830   assert (BUFFER_LIVE_P (buf));                                 \
831   assert ((x) >= BI_BUF_BEG (buf) && x < BI_BUF_Z (buf));       \
832   assert (VALID_BYTIND_P (buf, x));                             \
833 } while (0)
834
835 #else /* not ERROR_CHECK_BUFPOS */
836 # define ASSERT_VALID_BYTIND_UNSAFE(buf, x)
837 # define ASSERT_VALID_BYTIND_BACKWARD_UNSAFE(buf, x)
838 # define ASSERT_VALID_BYTIND_FORWARD_UNSAFE(buf, x)
839
840 #endif /* not ERROR_CHECK_BUFPOS */
841
842 /* Note that, although the Mule version will work fine for non-Mule
843    as well (it should reduce down to nothing), we provide a separate
844    version to avoid compilation warnings and possible non-optimal
845    results with stupid compilers. */
846
847 #ifdef MULE
848 # define VALIDATE_BYTIND_BACKWARD(buf, x) do {          \
849   Bufbyte *VBB_ptr = BI_BUF_BYTE_ADDRESS (buf, x);      \
850   while (!BUFBYTE_FIRST_BYTE_P (*VBB_ptr))              \
851     VBB_ptr--, (x)--;                                   \
852 } while (0)
853 #else
854 # define VALIDATE_BYTIND_BACKWARD(buf, x)
855 #endif
856
857 /* Note that, although the Mule version will work fine for non-Mule
858    as well (it should reduce down to nothing), we provide a separate
859    version to avoid compilation warnings and possible non-optimal
860    results with stupid compilers. */
861
862 #ifdef MULE
863 # define VALIDATE_BYTIND_FORWARD(buf, x) do {           \
864   Bufbyte *VBF_ptr = BI_BUF_BYTE_ADDRESS (buf, x);      \
865   while (!BUFBYTE_FIRST_BYTE_P (*VBF_ptr))              \
866     VBF_ptr++, (x)++;                                   \
867 } while (0)
868 #else
869 # define VALIDATE_BYTIND_FORWARD(buf, x)
870 #endif
871
872 /* Note that in the simplest case (no MULE, no ERROR_CHECK_BUFPOS),
873    this crap reduces down to simply (x)++. */
874
875 #define INC_BYTIND(buf, x) do                           \
876 {                                                       \
877   ASSERT_VALID_BYTIND_FORWARD_UNSAFE (buf, x);          \
878   /* Note that we do the increment first to             \
879      make sure that the pointer in                      \
880      VALIDATE_BYTIND_FORWARD() ends up on               \
881      the correct side of the gap */                     \
882   (x)++;                                                \
883   VALIDATE_BYTIND_FORWARD (buf, x);                     \
884 } while (0)
885
886 /* Note that in the simplest case (no MULE, no ERROR_CHECK_BUFPOS),
887    this crap reduces down to simply (x)--. */
888
889 #define DEC_BYTIND(buf, x) do                           \
890 {                                                       \
891   ASSERT_VALID_BYTIND_BACKWARD_UNSAFE (buf, x);         \
892   /* Note that we do the decrement first to             \
893      make sure that the pointer in                      \
894      VALIDATE_BYTIND_BACKWARD() ends up on              \
895      the correct side of the gap */                     \
896   (x)--;                                                \
897   VALIDATE_BYTIND_BACKWARD (buf, x);                    \
898 } while (0)
899
900 INLINE_HEADER Bytind prev_bytind (struct buffer *buf, Bytind x);
901 INLINE_HEADER Bytind
902 prev_bytind (struct buffer *buf, Bytind x)
903 {
904   DEC_BYTIND (buf, x);
905   return x;
906 }
907
908 INLINE_HEADER Bytind next_bytind (struct buffer *buf, Bytind x);
909 INLINE_HEADER Bytind
910 next_bytind (struct buffer *buf, Bytind x)
911 {
912   INC_BYTIND (buf, x);
913   return x;
914 }
915
916 #define BYTIND_INVALID ((Bytind) -1)
917
918 /*----------------------------------------------------------------------*/
919 /*         Converting between buffer positions and byte indices         */
920 /*----------------------------------------------------------------------*/
921
922 #ifdef MULE
923
924 Bytind bufpos_to_bytind_func (struct buffer *buf, Bufpos x);
925 Bufpos bytind_to_bufpos_func (struct buffer *buf, Bytind x);
926
927 /* The basic algorithm we use is to keep track of a known region of
928    characters in each buffer, all of which are of the same width.  We
929    keep track of the boundaries of the region in both Bufpos and
930    Bytind coordinates and also keep track of the char width, which
931    is 1 - 4 bytes.  If the position we're translating is not in
932    the known region, then we invoke a function to update the known
933    region to surround the position in question.  This assumes
934    locality of reference, which is usually the case.
935
936    Note that the function to update the known region can be simple
937    or complicated depending on how much information we cache.
938    For the moment, we don't cache any information, and just move
939    linearly forward or back from the known region, with a few
940    shortcuts to catch all-ASCII buffers. (Note that this will
941    thrash with bad locality of reference.) A smarter method would
942    be to keep some sort of pseudo-extent layer over the buffer;
943    maybe keep track of the bufpos/bytind correspondence at the
944    beginning of each line, which would allow us to do a binary
945    search over the pseudo-extents to narrow things down to the
946    correct line, at which point you could use a linear movement
947    method.  This would also mesh well with efficiently
948    implementing a line-numbering scheme.
949
950    Note also that we have to multiply or divide by the char width
951    in order to convert the positions.  We do some tricks to avoid
952    ever actually having to do a multiply or divide, because that
953    is typically an expensive operation (esp. divide).  Multiplying
954    or dividing by 1, 2, or 4 can be implemented simply as a
955    shift left or shift right, and we keep track of a shifter value
956    (0, 1, or 2) indicating how much to shift.  Multiplying by 3
957    can be implemented by doubling and then adding the original
958    value.  Dividing by 3, alas, cannot be implemented in any
959    simple shift/subtract method, as far as I know; so we just
960    do a table lookup.  For simplicity, we use a table of size
961    128K, which indexes the "divide-by-3" values for the first
962    64K non-negative numbers. (Note that we can increase the
963    size up to 384K, i.e. indexing the first 192K non-negative
964    numbers, while still using shorts in the array.) This also
965    means that the size of the known region can be at most
966    64K for width-three characters.
967    */
968
969 extern short three_to_one_table[];
970
971 INLINE_HEADER int real_bufpos_to_bytind (struct buffer *buf, Bufpos x);
972 INLINE_HEADER int
973 real_bufpos_to_bytind (struct buffer *buf, Bufpos x)
974 {
975   if (x >= buf->text->mule_bufmin && x <= buf->text->mule_bufmax)
976     return (buf->text->mule_bytmin +
977             ((x - buf->text->mule_bufmin) << buf->text->mule_shifter) +
978             (buf->text->mule_three_p ? (x - buf->text->mule_bufmin) : 0));
979   else
980     return bufpos_to_bytind_func (buf, x);
981 }
982
983 INLINE_HEADER int real_bytind_to_bufpos (struct buffer *buf, Bytind x);
984 INLINE_HEADER int
985 real_bytind_to_bufpos (struct buffer *buf, Bytind x)
986 {
987   if (x >= buf->text->mule_bytmin && x <= buf->text->mule_bytmax)
988     return (buf->text->mule_bufmin +
989             ((buf->text->mule_three_p
990               ? three_to_one_table[x - buf->text->mule_bytmin]
991               : (x - buf->text->mule_bytmin) >> buf->text->mule_shifter)));
992   else
993     return bytind_to_bufpos_func (buf, x);
994 }
995
996 #else /* not MULE */
997
998 # define real_bufpos_to_bytind(buf, x)  ((Bytind) x)
999 # define real_bytind_to_bufpos(buf, x)  ((Bufpos) x)
1000
1001 #endif /* not MULE */
1002
1003 #ifdef ERROR_CHECK_BUFPOS
1004
1005 Bytind bufpos_to_bytind (struct buffer *buf, Bufpos x);
1006 Bufpos bytind_to_bufpos (struct buffer *buf, Bytind x);
1007
1008 #else /* not ERROR_CHECK_BUFPOS */
1009
1010 #define bufpos_to_bytind real_bufpos_to_bytind
1011 #define bytind_to_bufpos real_bytind_to_bufpos
1012
1013 #endif /* not ERROR_CHECK_BUFPOS */
1014
1015 #define make_bufpos(buf, ind) make_int (bytind_to_bufpos (buf, ind))
1016
1017 /*----------------------------------------------------------------------*/
1018 /*         Converting between buffer bytes and Emacs characters         */
1019 /*----------------------------------------------------------------------*/
1020
1021 /* The character at position POS in buffer. */
1022 #define BI_BUF_FETCH_CHAR(buf, pos) \
1023   charptr_emchar (BI_BUF_BYTE_ADDRESS (buf, pos))
1024 #define BUF_FETCH_CHAR(buf, pos) \
1025   BI_BUF_FETCH_CHAR (buf, bufpos_to_bytind (buf, pos))
1026
1027 /* The character at position POS in buffer, as a string.  This is
1028    equivalent to set_charptr_emchar (str, BUF_FETCH_CHAR (buf, pos))
1029    but is faster for Mule. */
1030
1031 # define BI_BUF_CHARPTR_COPY_CHAR(buf, pos, str) \
1032   charptr_copy_char (BI_BUF_BYTE_ADDRESS (buf, pos), str)
1033 #define BUF_CHARPTR_COPY_CHAR(buf, pos, str) \
1034   BI_BUF_CHARPTR_COPY_CHAR (buf, bufpos_to_bytind (buf, pos), str)
1035
1036 \f
1037 /************************************************************************/
1038 /*                                                                      */
1039 /*         Converting between internal and external format              */
1040 /*                                                                      */
1041 /************************************************************************/
1042 /*
1043   All client code should use only the two macros
1044
1045   TO_EXTERNAL_FORMAT (source_type, source, sink_type, sink, coding_system)
1046   TO_INTERNAL_FORMAT (source_type, source, sink_type, sink, coding_system)
1047
1048   Typical use is
1049
1050   TO_EXTERNAL_FORMAT (DATA, (ptr, len),
1051                       LISP_BUFFER, buffer,
1052                       Qfile_name);
1053
1054   The source or sink can be specified in one of these ways:
1055
1056   DATA,   (ptr, len),    // input data is a fixed buffer of size len
1057   ALLOCA, (ptr, len),    // output data is in a alloca()ed buffer of size len
1058   MALLOC, (ptr, len),    // output data is in a malloc()ed buffer of size len
1059   C_STRING_ALLOCA, ptr,  // equivalent to ALLOCA (ptr, len_ignored) on output
1060   C_STRING_MALLOC, ptr,  // equivalent to MALLOC (ptr, len_ignored) on output
1061   C_STRING,     ptr,     // equivalent to DATA, (ptr, strlen (ptr) + 1) on input
1062   LISP_STRING,  string,  // input or output is a Lisp_Object of type string
1063   LISP_BUFFER,  buffer,  // output is written to (point) in lisp buffer
1064   LISP_LSTREAM, lstream, // input or output is a Lisp_Object of type lstream
1065   LISP_OPAQUE,  object,  // input or output is a Lisp_Object of type opaque
1066
1067   When specifying the sink, use lvalues, since the macro will assign to them,
1068   except when the sink is an lstream or a lisp buffer.
1069
1070   The macros accept the kinds of sources and sinks appropriate for
1071   internal and external data representation.  See the type_checking_assert
1072   macros below for the actual allowed types.
1073
1074   Since some sources and sinks use one argument (a Lisp_Object) to
1075   specify them, while others take a (pointer, length) pair, we use
1076   some C preprocessor trickery to allow pair arguments to be specified
1077   by parenthesizing them, as in the examples above.
1078
1079   Anything prefixed by dfc_ (`data format conversion') is private.
1080   They are only used to implement these macros.
1081
1082   Using C_STRING* is appropriate for using with external APIs that take
1083   null-terminated strings.  For internal data, we should try to be
1084   '\0'-clean - i.e. allow arbitrary data to contain embedded '\0'.
1085
1086   Sometime in the future we might allow output to C_STRING_ALLOCA or
1087   C_STRING_MALLOC _only_ with TO_EXTERNAL_FORMAT(), not
1088   TO_INTERNAL_FORMAT().  */
1089
1090 #define TO_EXTERNAL_FORMAT(source_type, source, sink_type, sink, coding_system) \
1091 do {                                                                            \
1092   dfc_conversion_type dfc_simplified_source_type;                               \
1093   dfc_conversion_type dfc_simplified_sink_type;                                 \
1094   dfc_conversion_data dfc_source;                                               \
1095   dfc_conversion_data dfc_sink;                                                 \
1096                                                                                 \
1097   type_checking_assert                                                          \
1098     ((DFC_TYPE_##source_type == DFC_TYPE_DATA ||                                \
1099       DFC_TYPE_##source_type == DFC_TYPE_C_STRING ||                            \
1100       DFC_TYPE_##source_type == DFC_TYPE_LISP_STRING ||                         \
1101       DFC_TYPE_##source_type == DFC_TYPE_LISP_OPAQUE ||                         \
1102       DFC_TYPE_##source_type == DFC_TYPE_LISP_LSTREAM)                          \
1103     &&                                                                          \
1104      (DFC_TYPE_##sink_type == DFC_TYPE_ALLOCA ||                                \
1105       DFC_TYPE_##sink_type == DFC_TYPE_MALLOC ||                                \
1106       DFC_TYPE_##sink_type == DFC_TYPE_C_STRING_ALLOCA ||                       \
1107       DFC_TYPE_##sink_type == DFC_TYPE_C_STRING_MALLOC ||                       \
1108       DFC_TYPE_##sink_type == DFC_TYPE_LISP_LSTREAM ||                          \
1109       DFC_TYPE_##sink_type == DFC_TYPE_LISP_OPAQUE));                           \
1110                                                                                 \
1111   DFC_SOURCE_##source_type##_TO_ARGS (source);                                  \
1112   DFC_SINK_##sink_type##_TO_ARGS     (sink);                                    \
1113                                                                                 \
1114   DFC_CONVERT_TO_EXTERNAL_FORMAT (dfc_simplified_source_type, &dfc_source,      \
1115                                   coding_system,                                \
1116                                   dfc_simplified_sink_type,   &dfc_sink);       \
1117                                                                                 \
1118   DFC_##sink_type##_USE_CONVERTED_DATA (sink);                                  \
1119 } while (0)
1120
1121 #define TO_INTERNAL_FORMAT(source_type, source, sink_type, sink, coding_system) \
1122 do {                                                                            \
1123   dfc_conversion_type dfc_simplified_source_type;                               \
1124   dfc_conversion_type dfc_simplified_sink_type;                                 \
1125   dfc_conversion_data dfc_source;                                               \
1126   dfc_conversion_data dfc_sink;                                                 \
1127                                                                                 \
1128   type_checking_assert                                                          \
1129     ((DFC_TYPE_##source_type == DFC_TYPE_DATA ||                                \
1130       DFC_TYPE_##source_type == DFC_TYPE_C_STRING ||                            \
1131       DFC_TYPE_##source_type == DFC_TYPE_LISP_OPAQUE ||                         \
1132       DFC_TYPE_##source_type == DFC_TYPE_LISP_LSTREAM)                          \
1133      &&                                                                         \
1134      (DFC_TYPE_##sink_type == DFC_TYPE_ALLOCA ||                                \
1135       DFC_TYPE_##sink_type == DFC_TYPE_MALLOC ||                                \
1136       DFC_TYPE_##sink_type == DFC_TYPE_C_STRING_ALLOCA ||                       \
1137       DFC_TYPE_##sink_type == DFC_TYPE_C_STRING_MALLOC ||                       \
1138       DFC_TYPE_##sink_type == DFC_TYPE_LISP_STRING ||                           \
1139       DFC_TYPE_##sink_type == DFC_TYPE_LISP_LSTREAM ||                          \
1140       DFC_TYPE_##sink_type == DFC_TYPE_LISP_BUFFER));                           \
1141                                                                                 \
1142   DFC_SOURCE_##source_type##_TO_ARGS (source);                                  \
1143   DFC_SINK_##sink_type##_TO_ARGS     (sink);                                    \
1144                                                                                 \
1145   DFC_CONVERT_TO_INTERNAL_FORMAT (dfc_simplified_source_type, &dfc_source,      \
1146                                   coding_system,                                \
1147                                   dfc_simplified_sink_type,   &dfc_sink);       \
1148                                                                                 \
1149   DFC_##sink_type##_USE_CONVERTED_DATA (sink);                                  \
1150 } while (0)
1151
1152 #ifdef FILE_CODING
1153 #define DFC_CONVERT_TO_EXTERNAL_FORMAT dfc_convert_to_external_format
1154 #define DFC_CONVERT_TO_INTERNAL_FORMAT dfc_convert_to_internal_format
1155 #else
1156 /* ignore coding_system argument */
1157 #define DFC_CONVERT_TO_EXTERNAL_FORMAT(a, b, coding_system, c, d) \
1158  dfc_convert_to_external_format (a, b, c, d)
1159 #define DFC_CONVERT_TO_INTERNAL_FORMAT(a, b, coding_system, c, d) \
1160  dfc_convert_to_internal_format (a, b, c, d)
1161 #endif
1162
1163 typedef union
1164 {
1165   struct { const void *ptr; size_t len; } data;
1166   Lisp_Object lisp_object;
1167 } dfc_conversion_data;
1168
1169 enum dfc_conversion_type
1170 {
1171   DFC_TYPE_DATA,
1172   DFC_TYPE_ALLOCA,
1173   DFC_TYPE_MALLOC,
1174   DFC_TYPE_C_STRING,
1175   DFC_TYPE_C_STRING_ALLOCA,
1176   DFC_TYPE_C_STRING_MALLOC,
1177   DFC_TYPE_LISP_STRING,
1178   DFC_TYPE_LISP_LSTREAM,
1179   DFC_TYPE_LISP_OPAQUE,
1180   DFC_TYPE_LISP_BUFFER
1181 };
1182 typedef enum dfc_conversion_type dfc_conversion_type;
1183
1184 /* WARNING: These use a static buffer.  This can lead to disaster if
1185    these functions are not used *very* carefully.  Another reason to only use
1186    TO_EXTERNAL_FORMAT() and TO_INTERNAL_FORMAT(). */
1187 void
1188 dfc_convert_to_external_format (dfc_conversion_type source_type,
1189                                 dfc_conversion_data *source,
1190 #ifdef FILE_CODING
1191                                 Lisp_Object coding_system,
1192 #endif
1193                                 dfc_conversion_type sink_type,
1194                                 dfc_conversion_data *sink);
1195 void
1196 dfc_convert_to_internal_format (dfc_conversion_type source_type,
1197                                 dfc_conversion_data *source,
1198 #ifdef FILE_CODING
1199                                 Lisp_Object coding_system,
1200 #endif
1201                                 dfc_conversion_type sink_type,
1202                                 dfc_conversion_data *sink);
1203 /* CPP Trickery */
1204 #define DFC_CPP_CAR(x,y) (x)
1205 #define DFC_CPP_CDR(x,y) (y)
1206
1207 /* Convert `source' to args for dfc_convert_to_*_format() */
1208 #define DFC_SOURCE_DATA_TO_ARGS(val) do {               \
1209   dfc_source.data.ptr = DFC_CPP_CAR val;                \
1210   dfc_source.data.len = DFC_CPP_CDR val;                \
1211   dfc_simplified_source_type = DFC_TYPE_DATA;           \
1212 } while (0)
1213 #define DFC_SOURCE_C_STRING_TO_ARGS(val) do {           \
1214   dfc_source.data.len =                                 \
1215     strlen ((char *) (dfc_source.data.ptr = (val)));    \
1216   dfc_simplified_source_type = DFC_TYPE_DATA;           \
1217 } while (0)
1218 #define DFC_SOURCE_LISP_STRING_TO_ARGS(val) do {        \
1219   Lisp_Object dfc_slsta = (val);                        \
1220   type_checking_assert (STRINGP (dfc_slsta));           \
1221   dfc_source.lisp_object = dfc_slsta;                   \
1222   dfc_simplified_source_type = DFC_TYPE_LISP_STRING;    \
1223 } while (0)
1224 #define DFC_SOURCE_LISP_LSTREAM_TO_ARGS(val) do {       \
1225   Lisp_Object dfc_sllta = (val);                        \
1226   type_checking_assert (LSTREAMP (dfc_sllta));          \
1227   dfc_source.lisp_object = dfc_sllta;                   \
1228   dfc_simplified_source_type = DFC_TYPE_LISP_LSTREAM;   \
1229 } while (0)
1230 #define DFC_SOURCE_LISP_OPAQUE_TO_ARGS(val) do {        \
1231   Lisp_Opaque *dfc_slota = XOPAQUE (val);               \
1232   dfc_source.data.ptr = OPAQUE_DATA (dfc_slota);        \
1233   dfc_source.data.len = OPAQUE_SIZE (dfc_slota);        \
1234   dfc_simplified_source_type = DFC_TYPE_DATA;           \
1235 } while (0)
1236
1237 /* Convert `sink' to args for dfc_convert_to_*_format() */
1238 #define DFC_SINK_ALLOCA_TO_ARGS(val)            \
1239   dfc_simplified_sink_type = DFC_TYPE_DATA
1240 #define DFC_SINK_C_STRING_ALLOCA_TO_ARGS(val)   \
1241   dfc_simplified_sink_type = DFC_TYPE_DATA
1242 #define DFC_SINK_MALLOC_TO_ARGS(val)            \
1243   dfc_simplified_sink_type = DFC_TYPE_DATA
1244 #define DFC_SINK_C_STRING_MALLOC_TO_ARGS(val)   \
1245   dfc_simplified_sink_type = DFC_TYPE_DATA
1246 #define DFC_SINK_LISP_STRING_TO_ARGS(val)       \
1247   dfc_simplified_sink_type = DFC_TYPE_DATA
1248 #define DFC_SINK_LISP_OPAQUE_TO_ARGS(val)       \
1249   dfc_simplified_sink_type = DFC_TYPE_DATA
1250 #define DFC_SINK_LISP_LSTREAM_TO_ARGS(val) do {         \
1251   Lisp_Object dfc_sllta = (val);                        \
1252   type_checking_assert (LSTREAMP (dfc_sllta));          \
1253   dfc_sink.lisp_object = dfc_sllta;                     \
1254   dfc_simplified_sink_type = DFC_TYPE_LISP_LSTREAM;     \
1255 } while (0)
1256 #define DFC_SINK_LISP_BUFFER_TO_ARGS(val) do {          \
1257   struct buffer *dfc_slbta = XBUFFER (val);             \
1258   dfc_sink.lisp_object =                                \
1259     make_lisp_buffer_output_stream                      \
1260     (dfc_slbta, BUF_PT (dfc_slbta), 0);                 \
1261   dfc_simplified_sink_type = DFC_TYPE_LISP_LSTREAM;     \
1262 } while (0)
1263
1264 /* Assign to the `sink' lvalue(s) using the converted data. */
1265 typedef union { char c; void *p; } *dfc_aliasing_voidpp;
1266 #define DFC_ALLOCA_USE_CONVERTED_DATA(sink) do {                        \
1267   void * dfc_sink_ret = alloca (dfc_sink.data.len + 1);                 \
1268   memcpy (dfc_sink_ret, dfc_sink.data.ptr, dfc_sink.data.len + 1);      \
1269   ((dfc_aliasing_voidpp) &(DFC_CPP_CAR sink))->p = dfc_sink_ret;        \
1270   (DFC_CPP_CDR sink) = dfc_sink.data.len;                               \
1271 } while (0)
1272 #define DFC_MALLOC_USE_CONVERTED_DATA(sink) do {                        \
1273   void * dfc_sink_ret = xmalloc (dfc_sink.data.len + 1);                \
1274   memcpy (dfc_sink_ret, dfc_sink.data.ptr, dfc_sink.data.len + 1);      \
1275   ((dfc_aliasing_voidpp) &(DFC_CPP_CAR sink))->p = dfc_sink_ret;        \
1276   (DFC_CPP_CDR sink) = dfc_sink.data.len;                               \
1277 } while (0)
1278 #define DFC_C_STRING_ALLOCA_USE_CONVERTED_DATA(sink) do {               \
1279   void * dfc_sink_ret = alloca (dfc_sink.data.len + 1);                 \
1280   memcpy (dfc_sink_ret, dfc_sink.data.ptr, dfc_sink.data.len + 1);      \
1281   (sink) = (char *) dfc_sink_ret;                                       \
1282 } while (0)
1283 #define DFC_C_STRING_MALLOC_USE_CONVERTED_DATA(sink) do {               \
1284   void * dfc_sink_ret = xmalloc (dfc_sink.data.len + 1);                \
1285   memcpy (dfc_sink_ret, dfc_sink.data.ptr, dfc_sink.data.len + 1);      \
1286   (sink) = (char *) dfc_sink_ret;                                       \
1287 } while (0)
1288 #define DFC_LISP_STRING_USE_CONVERTED_DATA(sink) \
1289   sink = make_string ((Bufbyte *) dfc_sink.data.ptr, dfc_sink.data.len)
1290 #define DFC_LISP_OPAQUE_USE_CONVERTED_DATA(sink) \
1291   sink = make_opaque (dfc_sink.data.ptr, dfc_sink.data.len)
1292 #define DFC_LISP_LSTREAM_USE_CONVERTED_DATA(sink) /* data already used */
1293 #define DFC_LISP_BUFFER_USE_CONVERTED_DATA(sink) \
1294   Lstream_delete (XLSTREAM (dfc_sink.lisp_object))
1295
1296 /* Someday we might want to distinguish between Qnative and Qfile_name
1297    by using coding-system aliases, but for now it suffices to have
1298    these be identical.  Qnative can be used as the coding_system
1299    argument to TO_EXTERNAL_FORMAT() and TO_INTERNAL_FORMAT(). */
1300 #define Qnative Qfile_name
1301
1302 #if defined (WIN32_NATIVE) || defined (CYGWIN)
1303 /* #### kludge!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1304    Remove this as soon as my Mule code is integrated. */
1305 #define Qmswindows_tstr Qnative
1306 #endif
1307
1308 /* More stand-ins */
1309 #define Qcommand_argument_encoding Qnative
1310 #define Qenvironment_variable_encoding Qnative
1311
1312 /* Convenience macros for extremely common invocations */
1313 #define C_STRING_TO_EXTERNAL(in, out, coding_system) \
1314   TO_EXTERNAL_FORMAT (C_STRING, in, C_STRING_ALLOCA, out, coding_system)
1315 #define C_STRING_TO_EXTERNAL_MALLOC(in, out, coding_system) \
1316   TO_EXTERNAL_FORMAT (C_STRING, in, C_STRING_MALLOC, out, coding_system)
1317 #define EXTERNAL_TO_C_STRING(in, out, coding_system) \
1318   TO_INTERNAL_FORMAT (C_STRING, in, C_STRING_ALLOCA, out, coding_system)
1319 #define EXTERNAL_TO_C_STRING_MALLOC(in, out, coding_system) \
1320   TO_INTERNAL_FORMAT (C_STRING, in, C_STRING_MALLOC, out, coding_system)
1321 #define LISP_STRING_TO_EXTERNAL(in, out, coding_system) \
1322   TO_EXTERNAL_FORMAT (LISP_STRING, in, C_STRING_ALLOCA, out, coding_system)
1323 #define LISP_STRING_TO_EXTERNAL_MALLOC(in, out, coding_system) \
1324   TO_EXTERNAL_FORMAT (LISP_STRING, in, C_STRING_MALLOC, out, coding_system)
1325
1326 \f
1327 /************************************************************************/
1328 /*                                                                      */
1329 /*                          fake charset functions                      */
1330 /*                                                                      */
1331 /************************************************************************/
1332
1333 /* used when MULE is not defined, so that Charset-type stuff can still
1334    be done */
1335
1336 #ifndef MULE
1337
1338 #define Vcharset_ascii Qnil
1339
1340 #define CHAR_CHARSET(ch) Vcharset_ascii
1341 #define CHAR_LEADING_BYTE(ch) LEADING_BYTE_ASCII
1342 #define LEADING_BYTE_ASCII 0x80
1343 #define NUM_LEADING_BYTES 1
1344 #define MIN_LEADING_BYTE 0x80
1345 #define CHARSETP(cs) 1
1346 #define CHARSET_BY_LEADING_BYTE(lb) Vcharset_ascii
1347 #define XCHARSET_LEADING_BYTE(cs) LEADING_BYTE_ASCII
1348 #define XCHARSET_GRAPHIC(cs) -1
1349 #define XCHARSET_COLUMNS(cs) 1
1350 #define XCHARSET_DIMENSION(cs) 1
1351 #define REP_BYTES_BY_FIRST_BYTE(fb) 1
1352 #define BREAKUP_CHAR(ch, charset, byte1, byte2) do {    \
1353   (charset) = Vcharset_ascii;                           \
1354   (byte1) = (ch);                                       \
1355   (byte2) = 0;                                          \
1356 } while (0)
1357 #define BYTE_ASCII_P(byte) 1
1358
1359 #endif /* ! MULE */
1360 \f
1361 /************************************************************************/
1362 /*                                                                      */
1363 /*                  higher-level buffer-position functions              */
1364 /*                                                                      */
1365 /************************************************************************/
1366
1367 /*----------------------------------------------------------------------*/
1368 /*           Settor macros for important positions in a buffer          */
1369 /*----------------------------------------------------------------------*/
1370
1371 /* Set beginning of accessible range of buffer.  */
1372 #define SET_BOTH_BUF_BEGV(buf, val, bival)      \
1373 do                                              \
1374 {                                               \
1375   (buf)->begv = (bival);                        \
1376   (buf)->bufbegv = (val);                       \
1377 } while (0)
1378
1379 /* Set end of accessible range of buffer.  */
1380 #define SET_BOTH_BUF_ZV(buf, val, bival)        \
1381 do                                              \
1382 {                                               \
1383   (buf)->zv = (bival);                          \
1384   (buf)->bufzv = (val);                         \
1385 } while (0)
1386
1387 /* Set point. */
1388 /* Since BEGV and ZV are almost never set, it's reasonable to enforce
1389    the restriction that the Bufpos and Bytind values must both be
1390    specified.  However, point is set in lots and lots of places.  So
1391    we provide the ability to specify both (for efficiency) or just
1392    one. */
1393 #define BOTH_BUF_SET_PT(buf, val, bival) set_buffer_point (buf, val, bival)
1394 #define BI_BUF_SET_PT(buf, bival) \
1395   BOTH_BUF_SET_PT (buf, bytind_to_bufpos (buf, bival), bival)
1396 #define BUF_SET_PT(buf, value) \
1397   BOTH_BUF_SET_PT (buf, value, bufpos_to_bytind (buf, value))
1398
1399
1400 #if 0 /* FSFmacs */
1401 /* These macros exist in FSFmacs because SET_PT() in FSFmacs incorrectly
1402    does too much stuff, such as moving out of invisible extents. */
1403 #define TEMP_SET_PT(position) (temp_set_point ((position), current_buffer))
1404 #define SET_BUF_PT(buf, value) ((buf)->pt = (value))
1405 #endif /* FSFmacs */
1406
1407 /*----------------------------------------------------------------------*/
1408 /*                      Miscellaneous buffer values                     */
1409 /*----------------------------------------------------------------------*/
1410
1411 /* Number of characters in buffer */
1412 #define BUF_SIZE(buf) (BUF_Z (buf) - BUF_BEG (buf))
1413
1414 /* Is this buffer narrowed? */
1415 #define BUF_NARROWED(buf) \
1416    ((BI_BUF_BEGV (buf) != BI_BUF_BEG (buf)) || \
1417     (BI_BUF_ZV   (buf) != BI_BUF_Z   (buf)))
1418
1419 /* Modification count.  */
1420 #define BUF_MODIFF(buf) ((buf)->text->modiff)
1421
1422 /* Saved modification count.  */
1423 #define BUF_SAVE_MODIFF(buf) ((buf)->text->save_modiff)
1424
1425 /* Face changed.  */
1426 #define BUF_FACECHANGE(buf) ((buf)->face_change)
1427
1428 #define POINT_MARKER_P(marker) \
1429    (XMARKER (marker)->buffer != 0 && \
1430     EQ (marker, XMARKER (marker)->buffer->point_marker))
1431
1432 #define BUF_MARKERS(buf) ((buf)->markers)
1433
1434 /* WARNING:
1435
1436    The new definitions of CEILING_OF() and FLOOR_OF() differ semantically
1437    from the old ones (in FSF Emacs and XEmacs 19.11 and before).
1438    Conversion is as follows:
1439
1440    OLD_BI_CEILING_OF(n) = NEW_BI_CEILING_OF(n) - 1
1441    OLD_BI_FLOOR_OF(n) = NEW_BI_FLOOR_OF(n + 1)
1442
1443    The definitions were changed because the new definitions are more
1444    consistent with the way everything else works in Emacs.
1445  */
1446
1447 /* Properties of CEILING_OF and FLOOR_OF (also apply to BI_ variants):
1448
1449    1) FLOOR_OF (CEILING_OF (n)) = n
1450       CEILING_OF (FLOOR_OF (n)) = n
1451
1452    2) CEILING_OF (n) = n if and only if n = ZV
1453       FLOOR_OF (n) = n if and only if n = BEGV
1454
1455    3) CEILING_OF (CEILING_OF (n)) = ZV
1456       FLOOR_OF (FLOOR_OF (n)) = BEGV
1457
1458    4) The bytes in the regions
1459
1460       [BYTE_ADDRESS (n), BYTE_ADDRESS_BEFORE (CEILING_OF (n))]
1461
1462       and
1463
1464       [BYTE_ADDRESS (FLOOR_OF (n)), BYTE_ADDRESS_BEFORE (n)]
1465
1466       are contiguous.
1467    */
1468
1469
1470 /*  Return the maximum index in the buffer it is safe to scan forwards
1471     past N to.  This is used to prevent buffer scans from running into
1472     the gap (e.g. search.c).  All characters between N and CEILING_OF(N)
1473     are located contiguous in memory.  Note that the character *at*
1474     CEILING_OF(N) is not contiguous in memory. */
1475 #define BI_BUF_CEILING_OF(b, n)                                         \
1476   ((n) < (b)->text->gpt && (b)->text->gpt < BI_BUF_ZV (b) ?             \
1477    (b)->text->gpt : BI_BUF_ZV (b))
1478 #define BUF_CEILING_OF(b, n)                                            \
1479   bytind_to_bufpos (b, BI_BUF_CEILING_OF (b, bufpos_to_bytind (b, n)))
1480
1481 /*  Return the minimum index in the buffer it is safe to scan backwards
1482     past N to.  All characters between FLOOR_OF(N) and N are located
1483     contiguous in memory.  Note that the character *at* N may not be
1484     contiguous in memory. */
1485 #define BI_BUF_FLOOR_OF(b, n)                                           \
1486         (BI_BUF_BEGV (b) < (b)->text->gpt && (b)->text->gpt < (n) ?     \
1487          (b)->text->gpt : BI_BUF_BEGV (b))
1488 #define BUF_FLOOR_OF(b, n)                                              \
1489   bytind_to_bufpos (b, BI_BUF_FLOOR_OF (b, bufpos_to_bytind (b, n)))
1490
1491 #define BI_BUF_CEILING_OF_IGNORE_ACCESSIBLE(b, n)                       \
1492   ((n) < (b)->text->gpt && (b)->text->gpt < BI_BUF_Z (b) ?              \
1493    (b)->text->gpt : BI_BUF_Z (b))
1494 #define BUF_CEILING_OF_IGNORE_ACCESSIBLE(b, n)                          \
1495   bytind_to_bufpos                                                      \
1496    (b, BI_BUF_CEILING_OF_IGNORE_ACCESSIBLE (b, bufpos_to_bytind (b, n)))
1497
1498 #define BI_BUF_FLOOR_OF_IGNORE_ACCESSIBLE(b, n)                         \
1499         (BI_BUF_BEG (b) < (b)->text->gpt && (b)->text->gpt < (n) ?      \
1500          (b)->text->gpt : BI_BUF_BEG (b))
1501 #define BUF_FLOOR_OF_IGNORE_ACCESSIBLE(b, n)                            \
1502   bytind_to_bufpos                                                      \
1503    (b, BI_BUF_FLOOR_OF_IGNORE_ACCESSIBLE (b, bufpos_to_bytind (b, n)))
1504
1505
1506 extern struct buffer *current_buffer;
1507
1508 /* This is the initial (startup) directory, as used for the *scratch* buffer.
1509    We're making this a global to make others aware of the startup directory.
1510    `initial_directory' is stored in external format.
1511  */
1512 extern char initial_directory[];
1513 extern void init_initial_directory (void);   /* initialize initial_directory */
1514
1515 EXFUN (Fbuffer_disable_undo, 1);
1516 EXFUN (Fbuffer_modified_p, 1);
1517 EXFUN (Fbuffer_name, 1);
1518 EXFUN (Fcurrent_buffer, 0);
1519 EXFUN (Ferase_buffer, 1);
1520 EXFUN (Fget_buffer, 1);
1521 EXFUN (Fget_buffer_create, 1);
1522 EXFUN (Fget_file_buffer, 1);
1523 EXFUN (Fkill_buffer, 1);
1524 EXFUN (Fother_buffer, 3);
1525 EXFUN (Frecord_buffer, 1);
1526 EXFUN (Fset_buffer, 1);
1527 EXFUN (Fset_buffer_modified_p, 2);
1528
1529 extern Lisp_Object QSscratch, Qafter_change_function, Qafter_change_functions;
1530 extern Lisp_Object Qbefore_change_function, Qbefore_change_functions;
1531 extern Lisp_Object Qbuffer_or_string_p, Qdefault_directory, Qfirst_change_hook;
1532 extern Lisp_Object Qpermanent_local, Vafter_change_function;
1533 extern Lisp_Object Vafter_change_functions, Vbefore_change_function;
1534 extern Lisp_Object Vbefore_change_functions, Vbuffer_alist, Vbuffer_defaults;
1535 extern Lisp_Object Vinhibit_read_only, Vtransient_mark_mode;
1536
1537 /* This structure marks which slots in a buffer have corresponding
1538    default values in Vbuffer_defaults.
1539    Each such slot has a nonzero value in this structure.
1540    The value has only one nonzero bit.
1541
1542    When a buffer has its own local value for a slot,
1543    the bit for that slot (found in the same slot in this structure)
1544    is turned on in the buffer's local_var_flags slot.
1545
1546    If a slot in this structure is zero, then even though there may
1547    be a DEFVAR_BUFFER_LOCAL for the slot, there is no default value for it;
1548    and the corresponding slot in Vbuffer_defaults is not used.  */
1549
1550 extern struct buffer buffer_local_flags;
1551
1552
1553 /* Allocation of buffer data. */
1554
1555 #ifdef REL_ALLOC
1556
1557 char *r_alloc (unsigned char **, size_t);
1558 char *r_re_alloc (unsigned char **, size_t);
1559 void r_alloc_free (unsigned char **);
1560
1561 #define BUFFER_ALLOC(data, size) \
1562   ((Bufbyte *) r_alloc ((unsigned char **) &data, (size) * sizeof(Bufbyte)))
1563 #define BUFFER_REALLOC(data, size) \
1564   ((Bufbyte *) r_re_alloc ((unsigned char **) &data, (size) * sizeof(Bufbyte)))
1565 #define BUFFER_FREE(data) r_alloc_free ((unsigned char **) &(data))
1566 #define R_ALLOC_DECLARE(var,data) r_alloc_declare (&(var), data)
1567
1568 #else /* !REL_ALLOC */
1569
1570 #define BUFFER_ALLOC(data,size)\
1571         (data = xnew_array (Bufbyte, size))
1572 #define BUFFER_REALLOC(data,size)\
1573         ((Bufbyte *) xrealloc (data, (size) * sizeof(Bufbyte)))
1574 /* Avoid excess parentheses, or syntax errors may rear their heads. */
1575 #define BUFFER_FREE(data) xfree (data)
1576 #define R_ALLOC_DECLARE(var,data)
1577
1578 #endif /* !REL_ALLOC */
1579
1580 extern Lisp_Object Vbuffer_alist;
1581 void set_buffer_internal (struct buffer *b);
1582 struct buffer *decode_buffer (Lisp_Object buffer, int allow_string);
1583
1584 /* from editfns.c */
1585 void widen_buffer (struct buffer *b, int no_clip);
1586 int beginning_of_line_p (struct buffer *b, Bufpos pt);
1587
1588 /* from insdel.c */
1589 void set_buffer_point (struct buffer *buf, Bufpos pos, Bytind bipos);
1590 void find_charsets_in_bufbyte_string (unsigned char *charsets,
1591                                       const Bufbyte *str,
1592                                       Bytecount len);
1593 void find_charsets_in_emchar_string (unsigned char *charsets,
1594                                      const Emchar *str,
1595                                      Charcount len);
1596 int bufbyte_string_displayed_columns (const Bufbyte *str, Bytecount len);
1597 int emchar_string_displayed_columns (const Emchar *str, Charcount len);
1598 void convert_bufbyte_string_into_emchar_dynarr (const Bufbyte *str,
1599                                                 Bytecount len,
1600                                                 Emchar_dynarr *dyn);
1601 Charcount convert_bufbyte_string_into_emchar_string (const Bufbyte *str,
1602                                                      Bytecount len,
1603                                                      Emchar *arr);
1604 void convert_emchar_string_into_bufbyte_dynarr (Emchar *arr, int nels,
1605                                                 Bufbyte_dynarr *dyn);
1606 Bufbyte *convert_emchar_string_into_malloced_string (Emchar *arr, int nels,
1607                                                     Bytecount *len_out);
1608 /* from marker.c */
1609 void init_buffer_markers (struct buffer *b);
1610 void uninit_buffer_markers (struct buffer *b);
1611
1612 /* flags for get_buffer_pos_char(), get_buffer_range_char(), etc. */
1613 /* At most one of GB_COERCE_RANGE and GB_NO_ERROR_IF_BAD should be
1614    specified.  At most one of GB_NEGATIVE_FROM_END and GB_NO_ERROR_IF_BAD
1615    should be specified. */
1616
1617 #define GB_ALLOW_PAST_ACCESSIBLE        (1 << 0)
1618 #define GB_ALLOW_NIL                    (1 << 1)
1619 #define GB_CHECK_ORDER                  (1 << 2)
1620 #define GB_COERCE_RANGE                 (1 << 3)
1621 #define GB_NO_ERROR_IF_BAD              (1 << 4)
1622 #define GB_NEGATIVE_FROM_END            (1 << 5)
1623 #define GB_HISTORICAL_STRING_BEHAVIOR   (GB_NEGATIVE_FROM_END | GB_ALLOW_NIL)
1624
1625 Bufpos get_buffer_pos_char (struct buffer *b, Lisp_Object pos,
1626                             unsigned int flags);
1627 Bytind get_buffer_pos_byte (struct buffer *b, Lisp_Object pos,
1628                             unsigned int flags);
1629 void get_buffer_range_char (struct buffer *b, Lisp_Object from, Lisp_Object to,
1630                             Bufpos *from_out, Bufpos *to_out,
1631                             unsigned int flags);
1632 void get_buffer_range_byte (struct buffer *b, Lisp_Object from, Lisp_Object to,
1633                             Bytind *from_out, Bytind *to_out,
1634                             unsigned int flags);
1635 Charcount get_string_pos_char (Lisp_Object string, Lisp_Object pos,
1636                                unsigned int flags);
1637 Bytecount get_string_pos_byte (Lisp_Object string, Lisp_Object pos,
1638                                unsigned int flags);
1639 void get_string_range_char (Lisp_Object string, Lisp_Object from,
1640                             Lisp_Object to, Charcount *from_out,
1641                             Charcount *to_out, unsigned int flags);
1642 void get_string_range_byte (Lisp_Object string, Lisp_Object from,
1643                             Lisp_Object to, Bytecount *from_out,
1644                             Bytecount *to_out, unsigned int flags);
1645 Bufpos get_buffer_or_string_pos_char (Lisp_Object object, Lisp_Object pos,
1646                                       unsigned int flags);
1647 Bytind get_buffer_or_string_pos_byte (Lisp_Object object, Lisp_Object pos,
1648                                       unsigned int flags);
1649 void get_buffer_or_string_range_char (Lisp_Object object, Lisp_Object from,
1650                                       Lisp_Object to, Bufpos *from_out,
1651                                       Bufpos *to_out, unsigned int flags);
1652 void get_buffer_or_string_range_byte (Lisp_Object object, Lisp_Object from,
1653                                       Lisp_Object to, Bytind *from_out,
1654                                       Bytind *to_out, unsigned int flags);
1655 Bufpos buffer_or_string_accessible_begin_char (Lisp_Object object);
1656 Bufpos buffer_or_string_accessible_end_char (Lisp_Object object);
1657 Bytind buffer_or_string_accessible_begin_byte (Lisp_Object object);
1658 Bytind buffer_or_string_accessible_end_byte (Lisp_Object object);
1659 Bufpos buffer_or_string_absolute_begin_char (Lisp_Object object);
1660 Bufpos buffer_or_string_absolute_end_char (Lisp_Object object);
1661 Bytind buffer_or_string_absolute_begin_byte (Lisp_Object object);
1662 Bytind buffer_or_string_absolute_end_byte (Lisp_Object object);
1663 void record_buffer (Lisp_Object buf);
1664 Lisp_Object get_buffer (Lisp_Object name,
1665                         int error_if_deleted_or_does_not_exist);
1666 int map_over_sharing_buffers (struct buffer *buf,
1667                               int (*mapfun) (struct buffer *buf,
1668                                              void *closure),
1669                               void *closure);
1670
1671 \f
1672 /************************************************************************/
1673 /*                         Case conversion                              */
1674 /************************************************************************/
1675
1676 /* A "trt" table is a mapping from characters to other characters,
1677    typically used to convert between uppercase and lowercase.  For
1678    compatibility reasons, trt tables are currently in the form of
1679    a Lisp string of 256 characters, specifying the conversion for each
1680    of the first 256 Emacs characters (i.e. the 256 Latin-1 characters).
1681    This should be generalized at some point to support conversions for
1682    all of the allowable Mule characters.
1683    */
1684
1685 /* The _1 macros are named as such because they assume that you have
1686    already guaranteed that the character values are all in the range
1687    0 - 255.  Bad lossage will happen otherwise. */
1688
1689 # define MAKE_TRT_TABLE() Fmake_string (make_int (256), make_char (0))
1690 # define TRT_TABLE_AS_STRING(table) XSTRING_DATA (table)
1691 # define TRT_TABLE_CHAR_1(table, ch) \
1692   string_char (XSTRING (table), (Charcount) ch)
1693 # define SET_TRT_TABLE_CHAR_1(table, ch1, ch2) \
1694   set_string_char (XSTRING (table), (Charcount) ch1, ch2)
1695
1696 #ifdef MULE
1697 # define MAKE_MIRROR_TRT_TABLE() make_opaque (OPAQUE_CLEAR, 256)
1698 # define MIRROR_TRT_TABLE_AS_STRING(table) ((Bufbyte *) XOPAQUE_DATA (table))
1699 # define MIRROR_TRT_TABLE_CHAR_1(table, ch) \
1700   ((Emchar) (MIRROR_TRT_TABLE_AS_STRING (table)[ch]))
1701 # define SET_MIRROR_TRT_TABLE_CHAR_1(table, ch1, ch2) \
1702   (MIRROR_TRT_TABLE_AS_STRING (table)[ch1] = (Bufbyte) (ch2))
1703 #endif
1704
1705 # define IN_TRT_TABLE_DOMAIN(c) (((EMACS_UINT) (c)) <= 255)
1706
1707 #ifdef MULE
1708 #define MIRROR_DOWNCASE_TABLE_AS_STRING(buf) \
1709   MIRROR_TRT_TABLE_AS_STRING (buf->mirror_downcase_table)
1710 #define MIRROR_UPCASE_TABLE_AS_STRING(buf) \
1711   MIRROR_TRT_TABLE_AS_STRING (buf->mirror_upcase_table)
1712 #define MIRROR_CANON_TABLE_AS_STRING(buf) \
1713   MIRROR_TRT_TABLE_AS_STRING (buf->mirror_case_canon_table)
1714 #define MIRROR_EQV_TABLE_AS_STRING(buf) \
1715   MIRROR_TRT_TABLE_AS_STRING (buf->mirror_case_eqv_table)
1716 #else
1717 #define MIRROR_DOWNCASE_TABLE_AS_STRING(buf) \
1718   TRT_TABLE_AS_STRING (buf->downcase_table)
1719 #define MIRROR_UPCASE_TABLE_AS_STRING(buf) \
1720   TRT_TABLE_AS_STRING (buf->upcase_table)
1721 #define MIRROR_CANON_TABLE_AS_STRING(buf) \
1722   TRT_TABLE_AS_STRING (buf->case_canon_table)
1723 #define MIRROR_EQV_TABLE_AS_STRING(buf) \
1724   TRT_TABLE_AS_STRING (buf->case_eqv_table)
1725 #endif
1726
1727 INLINE_HEADER Emchar TRT_TABLE_OF (Lisp_Object trt, Emchar c);
1728 INLINE_HEADER Emchar
1729 TRT_TABLE_OF (Lisp_Object trt, Emchar c)
1730 {
1731   return IN_TRT_TABLE_DOMAIN (c) ? TRT_TABLE_CHAR_1 (trt, c) : c;
1732 }
1733
1734 /* Macros used below. */
1735 #define DOWNCASE_TABLE_OF(buf, c) TRT_TABLE_OF (buf->downcase_table, c)
1736 #define UPCASE_TABLE_OF(buf, c) TRT_TABLE_OF (buf->upcase_table, c)
1737
1738 /* 1 if CH is upper case.  */
1739
1740 INLINE_HEADER int UPPERCASEP (struct buffer *buf, Emchar ch);
1741 INLINE_HEADER int
1742 UPPERCASEP (struct buffer *buf, Emchar ch)
1743 {
1744   return DOWNCASE_TABLE_OF (buf, ch) != ch;
1745 }
1746
1747 /* 1 if CH is lower case.  */
1748
1749 INLINE_HEADER int LOWERCASEP (struct buffer *buf, Emchar ch);
1750 INLINE_HEADER int
1751 LOWERCASEP (struct buffer *buf, Emchar ch)
1752 {
1753   return (UPCASE_TABLE_OF   (buf, ch) != ch &&
1754           DOWNCASE_TABLE_OF (buf, ch) == ch);
1755 }
1756
1757 /* 1 if CH is neither upper nor lower case.  */
1758
1759 INLINE_HEADER int NOCASEP (struct buffer *buf, Emchar ch);
1760 INLINE_HEADER int
1761 NOCASEP (struct buffer *buf, Emchar ch)
1762 {
1763   return UPCASE_TABLE_OF (buf, ch) == ch;
1764 }
1765
1766 /* Upcase a character, or make no change if that cannot be done.  */
1767
1768 INLINE_HEADER Emchar UPCASE (struct buffer *buf, Emchar ch);
1769 INLINE_HEADER Emchar
1770 UPCASE (struct buffer *buf, Emchar ch)
1771 {
1772   return (DOWNCASE_TABLE_OF (buf, ch) == ch) ? UPCASE_TABLE_OF (buf, ch) : ch;
1773 }
1774
1775 /* Upcase a character known to be not upper case.  Unused. */
1776
1777 #define UPCASE1(buf, ch) UPCASE_TABLE_OF (buf, ch)
1778
1779 /* Downcase a character, or make no change if that cannot be done. */
1780
1781 #define DOWNCASE(buf, ch) DOWNCASE_TABLE_OF (buf, ch)
1782
1783 /************************************************************************/
1784 /*              Lisp string representation convenience functions        */
1785 /************************************************************************/
1786 /* Because the representation of internally formatted data is subject to change,
1787    It's bad style to do something like strcmp (XSTRING_DATA (s), "foo")
1788    Instead, use the portable: bufbyte_strcmp (XSTRING_DATA (s), "foo")
1789    or bufbyte_memcmp (XSTRING_DATA (s), "foo", 3) */
1790
1791 /* Like strcmp, except first arg points at internally formatted data,
1792    while the second points at a string of only ASCII chars. */
1793 INLINE_HEADER int
1794 bufbyte_strcmp (const Bufbyte *bp, const char *ascii_string);
1795 INLINE_HEADER int
1796 bufbyte_strcmp (const Bufbyte *bp, const char *ascii_string)
1797 {
1798 #ifdef MULE
1799   while (1)
1800     {
1801       int diff;
1802       type_checking_assert (BYTE_ASCII_P (*ascii_string));
1803       if ((diff = charptr_emchar (bp) - *(Bufbyte *) ascii_string) != 0)
1804         return diff;
1805       if (*ascii_string == '\0')
1806         return 0;
1807       ascii_string++;
1808       INC_CHARPTR (bp);
1809     }
1810 #else
1811   return strcmp ((char *)bp, ascii_string);
1812 #endif
1813 }
1814
1815
1816 /* Like memcmp, except first arg points at internally formatted data,
1817    while the second points at a string of only ASCII chars. */
1818 INLINE_HEADER int
1819 bufbyte_memcmp (const Bufbyte *bp, const char *ascii_string, size_t len);
1820 INLINE_HEADER int
1821 bufbyte_memcmp (const Bufbyte *bp, const char *ascii_string, size_t len)
1822 {
1823 #ifdef MULE
1824   while (len--)
1825     {
1826       int diff = charptr_emchar (bp) - *(Bufbyte *) ascii_string;
1827       type_checking_assert (BYTE_ASCII_P (*ascii_string));
1828       if (diff != 0)
1829         return diff;
1830       ascii_string++;
1831       INC_CHARPTR (bp);
1832     }
1833   return 0;
1834 #else
1835   return memcmp (bp, ascii_string, len);
1836 #endif
1837 }
1838
1839 #endif /* INCLUDED_buffer_h_ */