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