update.
[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 _XEMACS_BUFFER_H_
33 #define _XEMACS_BUFFER_H_
34
35 #include "character.h"
36 #include "multibyte.h"
37
38 /************************************************************************/
39 /*                                                                      */
40 /*                    definition of Lisp buffer object                  */
41 /*                                                                      */
42 /************************************************************************/
43
44 /* Note: we keep both Bytind and Bufpos versions of some of the
45    important buffer positions because they are accessed so much.
46    If we didn't do this, we would constantly be invalidating the
47    bufpos<->bytind cache under Mule.
48
49    Note that under non-Mule, both versions will always be the
50    same so we don't really need to keep track of them.  But it
51    simplifies the logic to go ahead and do so all the time and
52    the memory loss is insignificant. */
53
54 /* Formerly, it didn't much matter what went inside the struct buffer_text
55    and what went outside it.  Now it does, with the advent of "indirect
56    buffers" that share text with another buffer.  An indirect buffer
57    shares the same *text* as another buffer, but has its own buffer-local
58    variables, its own accessible region, and its own markers and extents.
59    (Due to the nature of markers, it doesn't actually matter much whether
60    we stick them inside or out of the struct buffer_text -- the user won't
61    notice any difference -- but we go ahead and put them outside for
62    consistency and overall saneness of algorithm.)
63
64    FSFmacs gets away with not maintaining any "children" pointers from
65    a buffer to the indirect buffers that refer to it by putting the
66    markers inside of the struct buffer_text, using markers to keep track
67    of BEGV and ZV in indirect buffers, and relying on the fact that
68    all intervals (text properties and overlays) use markers for their
69    start and end points.  We don't do this for extents (markers are
70    inefficient anyway and take up space), so we have to maintain
71    children pointers.  This is not terribly hard, though, and the
72    code to maintain this is just like the code already present in
73    extent-parent and extent-children.
74    */
75
76 struct buffer_text
77 {
78   Bufbyte *beg;         /* Actual address of buffer contents. */
79   Bytind gpt;           /* Index of gap in buffer. */
80   Bytind z;             /* Index of end of buffer. */
81   Bufpos bufz;          /* Equivalent as a Bufpos. */
82   int gap_size;         /* Size of buffer's gap */
83   int end_gap_size;     /* Size of buffer's end gap */
84   long modiff;          /* This counts buffer-modification events
85                            for this buffer.  It is incremented for
86                            each such event, and never otherwise
87                            changed.  */
88   long save_modiff;     /* Previous value of modiff, as of last
89                            time buffer visited or saved a file.  */
90
91 #ifdef MULE
92   /* We keep track of a "known" region for very fast access.
93      This information is text-only so it goes here. */
94   Bufpos mule_bufmin, mule_bufmax;
95   Bytind mule_bytmin, mule_bytmax;
96 #ifdef UTF2000
97   int mule_size;
98 #else
99   int mule_shifter, mule_three_p;
100 #endif
101
102   /* And we also cache 16 positions for fairly fast access near those
103      positions. */
104   Bufpos mule_bufpos_cache[16];
105   Bytind mule_bytind_cache[16];
106 #endif
107
108   /* Similar to the above, we keep track of positions for which line
109      number has last been calculated.  See line-number.c. */
110   Lisp_Object line_number_cache;
111
112   /* Change data that goes with the text. */
113   struct buffer_text_change_data *changes;
114
115 };
116
117 struct buffer
118 {
119   struct lcrecord_header header;
120
121   /* This structure holds the coordinates of the buffer contents
122      in ordinary buffers.  In indirect buffers, this is not used.  */
123   struct buffer_text own_text;
124
125   /* This points to the `struct buffer_text' that is used for this buffer.
126      In an ordinary buffer, this is the own_text field above.
127      In an indirect buffer, this is the own_text field of another buffer.  */
128   struct buffer_text *text;
129
130   Bytind pt;            /* Position of point in buffer. */
131   Bufpos bufpt;         /* Equivalent as a Bufpos. */
132   Bytind begv;          /* Index of beginning of accessible range. */
133   Bufpos bufbegv;       /* Equivalent as a Bufpos. */
134   Bytind zv;            /* Index of end of accessible range. */
135   Bufpos bufzv;         /* Equivalent as a Bufpos. */
136
137   int face_change;      /* This is set when a change in how the text should
138                            be displayed (e.g., font, color) is made. */
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   struct 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   int 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 GC_BUFFERP(x) GC_RECORDP (x, buffer)
226 #define CHECK_BUFFER(x) CHECK_RECORD (x, buffer)
227 #define CONCHECK_BUFFER(x) CONCHECK_RECORD (x, buffer)
228
229 #define BUFFER_LIVE_P(b) (!NILP ((b)->name))
230
231 #define CHECK_LIVE_BUFFER(x) do {                       \
232   CHECK_BUFFER (x);                                     \
233   if (!BUFFER_LIVE_P (XBUFFER (x)))                     \
234     dead_wrong_type_argument (Qbuffer_live_p, (x));     \
235 } while (0)
236
237 #define CONCHECK_LIVE_BUFFER(x) do {                    \
238   CONCHECK_BUFFER (x);                                  \
239   if (!BUFFER_LIVE_P (XBUFFER (x)))                     \
240     x = wrong_type_argument (Qbuffer_live_p, (x));      \
241 } while (0)
242
243 \f
244 #define BUFFER_BASE_BUFFER(b) ((b)->base_buffer ? (b)->base_buffer : (b))
245
246 /* Map over buffers sharing the same text as MPS_BUF.  MPS_BUFVAR is a
247    variable that gets the buffer values (beginning with the base
248    buffer, then the children), and MPS_BUFCONS should be a temporary
249    Lisp_Object variable.  */
250 #define MAP_INDIRECT_BUFFERS(mps_buf, mps_bufvar, mps_bufcons)                  \
251 for (mps_bufcons = Qunbound,                                                    \
252      mps_bufvar = BUFFER_BASE_BUFFER (mps_buf);                                 \
253      UNBOUNDP (mps_bufcons) ?                                                   \
254         (mps_bufcons = mps_bufvar->indirect_children,                           \
255         1)                                                                      \
256        : (!NILP (mps_bufcons)                                                   \
257           && (mps_bufvar = XBUFFER (XCAR (mps_bufcons)), 1)                     \
258           && (mps_bufcons = XCDR (mps_bufcons), 1));                            \
259      )
260
261 \f
262
263 /************************************************************************/
264 /*                                                                      */
265 /*                 working with raw internal-format data                */
266 /*                                                                      */
267 /************************************************************************/
268
269 /* NOTE: In all the following macros, we follow these rules concerning
270    multiple evaluation of the arguments:
271
272    1) Anything that's an lvalue can be evaluated more than once.
273    2) Anything that's a Lisp Object can be evaluated more than once.
274       This should probably be changed, but this follows the way
275       that all the macros in lisp.h do things.
276    3) 'struct buffer *' arguments can be evaluated more than once.
277    4) Nothing else can be evaluated more than once.  Use inline
278       functions, if necessary, to prevent multiple evaluation.
279    5) An exception to (4) is that there are some macros below that
280       may evaluate their arguments more than once.  They are all
281       denoted with the word "unsafe" in their name and are generally
282       meant to be called only by other macros that have already
283       stored the calling values in temporary variables.
284 */
285
286 \f
287 /*----------------------------------------------------------------------*/
288 /*          Accessor macros for important positions in a buffer         */
289 /*----------------------------------------------------------------------*/
290
291 /* We put them here because some stuff below wants them before the
292    place where we would normally put them. */
293
294 /* None of these are lvalues.  Use the settor macros below to change
295    the positions. */
296
297 /* Beginning of buffer.  */
298 #define BI_BUF_BEG(buf) ((Bytind) 1)
299 #define BUF_BEG(buf) ((Bufpos) 1)
300
301 /* Beginning of accessible range of buffer.  */
302 #define BI_BUF_BEGV(buf) ((buf)->begv + 0)
303 #define BUF_BEGV(buf) ((buf)->bufbegv + 0)
304
305 /* End of accessible range of buffer.  */
306 #define BI_BUF_ZV(buf) ((buf)->zv + 0)
307 #define BUF_ZV(buf) ((buf)->bufzv + 0)
308
309 /* End of buffer.  */
310 #define BI_BUF_Z(buf) ((buf)->text->z + 0)
311 #define BUF_Z(buf) ((buf)->text->bufz + 0)
312
313 /* Point. */
314 #define BI_BUF_PT(buf) ((buf)->pt + 0)
315 #define BUF_PT(buf) ((buf)->bufpt + 0)
316
317 /*----------------------------------------------------------------------*/
318 /*              Converting between positions and addresses              */
319 /*----------------------------------------------------------------------*/
320
321 /* Convert the address of a byte in the buffer into a position.  */
322 INLINE Bytind BI_BUF_PTR_BYTE_POS (struct buffer *buf, Bufbyte *ptr);
323 INLINE Bytind
324 BI_BUF_PTR_BYTE_POS (struct buffer *buf, Bufbyte *ptr)
325 {
326   return ((ptr) - (buf)->text->beg + 1
327           - ((ptr - (buf)->text->beg + 1) > (buf)->text->gpt
328              ? (buf)->text->gap_size : 0));
329 }
330
331 #define BUF_PTR_BYTE_POS(buf, ptr) \
332   bytind_to_bufpos (buf, BI_BUF_PTR_BYTE_POS (buf, ptr))
333
334 /* Address of byte at position POS in buffer. */
335 INLINE Bufbyte * BI_BUF_BYTE_ADDRESS (struct buffer *buf, Bytind pos);
336 INLINE Bufbyte *
337 BI_BUF_BYTE_ADDRESS (struct buffer *buf, Bytind pos)
338 {
339   return ((buf)->text->beg +
340           ((pos >= (buf)->text->gpt ? (pos + (buf)->text->gap_size) : pos)
341            - 1));
342 }
343
344 #define BUF_BYTE_ADDRESS(buf, pos) \
345   BI_BUF_BYTE_ADDRESS (buf, bufpos_to_bytind (buf, pos))
346
347 /* Address of byte before position POS in buffer. */
348 INLINE Bufbyte * BI_BUF_BYTE_ADDRESS_BEFORE (struct buffer *buf, Bytind pos);
349 INLINE Bufbyte *
350 BI_BUF_BYTE_ADDRESS_BEFORE (struct buffer *buf, Bytind pos)
351 {
352   return ((buf)->text->beg +
353           ((pos > (buf)->text->gpt ? (pos + (buf)->text->gap_size) : pos)
354            - 2));
355 }
356
357 #define BUF_BYTE_ADDRESS_BEFORE(buf, pos) \
358   BI_BUF_BYTE_ADDRESS_BEFORE (buf, bufpos_to_bytind (buf, pos))
359
360 /*----------------------------------------------------------------------*/
361 /*          Converting between byte indices and memory indices          */
362 /*----------------------------------------------------------------------*/
363
364 INLINE int valid_memind_p (struct buffer *buf, Memind x);
365 INLINE int
366 valid_memind_p (struct buffer *buf, Memind x)
367 {
368   return ((x >= 1 && x <= (Memind) (buf)->text->gpt) ||
369           (x  > (Memind) ((buf)->text->gpt + (buf)->text->gap_size) &&
370            x <= (Memind) ((buf)->text->z   + (buf)->text->gap_size)));
371 }
372
373 INLINE Memind bytind_to_memind (struct buffer *buf, Bytind x);
374 INLINE Memind
375 bytind_to_memind (struct buffer *buf, Bytind x)
376 {
377   return (Memind) ((x > (buf)->text->gpt) ? (x + (buf)->text->gap_size) : x);
378 }
379
380
381 INLINE Bytind memind_to_bytind (struct buffer *buf, Memind x);
382 INLINE Bytind
383 memind_to_bytind (struct buffer *buf, Memind x)
384 {
385 #ifdef ERROR_CHECK_BUFPOS
386   assert (valid_memind_p (buf, x));
387 #endif
388   return (Bytind) ((x > (Memind) (buf)->text->gpt) ?
389                    x - (buf)->text->gap_size :
390                    x);
391 }
392
393 #define memind_to_bufpos(buf, x) \
394   bytind_to_bufpos (buf, memind_to_bytind (buf, x))
395 #define bufpos_to_memind(buf, x) \
396   bytind_to_memind (buf, bufpos_to_bytind (buf, x))
397
398 /* These macros generalize many standard buffer-position functions to
399    either a buffer or a string. */
400
401 /* Converting between Meminds and Bytinds, for a buffer-or-string.
402    For strings, this is a no-op.  For buffers, this resolves
403    to the standard memind<->bytind converters. */
404
405 #define buffer_or_string_bytind_to_memind(obj, ind) \
406   (BUFFERP (obj) ? bytind_to_memind (XBUFFER (obj), ind) : (Memind) ind)
407
408 #define buffer_or_string_memind_to_bytind(obj, ind) \
409   (BUFFERP (obj) ? memind_to_bytind (XBUFFER (obj), ind) : (Bytind) ind)
410
411 /* Converting between Bufpos's and Bytinds, for a buffer-or-string.
412    For strings, this maps to the bytecount<->charcount converters. */
413
414 #define buffer_or_string_bufpos_to_bytind(obj, pos)             \
415   (BUFFERP (obj) ? bufpos_to_bytind (XBUFFER (obj), pos) :      \
416    (Bytind) charcount_to_bytecount (XSTRING_DATA (obj), pos))
417
418 #define buffer_or_string_bytind_to_bufpos(obj, ind)             \
419   (BUFFERP (obj) ? bytind_to_bufpos (XBUFFER (obj), ind) :      \
420    (Bufpos) bytecount_to_charcount (XSTRING_DATA (obj), ind))
421
422 /* Similar for Bufpos's and Meminds. */
423
424 #define buffer_or_string_bufpos_to_memind(obj, pos)             \
425   (BUFFERP (obj) ? bufpos_to_memind (XBUFFER (obj), pos) :      \
426    (Memind) charcount_to_bytecount (XSTRING_DATA (obj), pos))
427
428 #define buffer_or_string_memind_to_bufpos(obj, ind)             \
429   (BUFFERP (obj) ? memind_to_bufpos (XBUFFER (obj), ind) :      \
430    (Bufpos) bytecount_to_charcount (XSTRING_DATA (obj), ind))
431
432 /************************************************************************/
433 /*                                                                      */
434 /*                    working with buffer-level data                    */
435 /*                                                                      */
436 /************************************************************************/
437
438 /*
439
440    (A) Working with byte indices:
441    ------------------------------
442
443    VALID_BYTIND_P(buf, bi):
444         Given a byte index, does it point to the beginning of a character?
445
446    ASSERT_VALID_BYTIND_UNSAFE(buf, bi):
447         If error-checking is enabled, assert that the given byte index
448         is within range and points to the beginning of a character
449         or to the end of the buffer.  Otherwise, do nothing.
450
451    ASSERT_VALID_BYTIND_BACKWARD_UNSAFE(buf, bi):
452         If error-checking is enabled, assert that the given byte index
453         is within range and satisfies ASSERT_VALID_BYTIND() and also
454         does not refer to the beginning of the buffer. (i.e. movement
455         backwards is OK.) Otherwise, do nothing.
456
457    ASSERT_VALID_BYTIND_FORWARD_UNSAFE(buf, bi):
458         If error-checking is enabled, assert that the given byte index
459         is within range and satisfies ASSERT_VALID_BYTIND() and also
460         does not refer to the end of the buffer. (i.e. movement
461         forwards is OK.) Otherwise, do nothing.
462
463    VALIDATE_BYTIND_BACKWARD(buf, bi):
464         Make sure that the given byte index is pointing to the beginning
465         of a character.  If not, back up until this is the case.  Note
466         that there are not too many places where it is legitimate to do
467         this sort of thing.  It's an error if you're passed an "invalid"
468         byte index.
469
470    VALIDATE_BYTIND_FORWARD(buf, bi):
471         Make sure that the given byte index is pointing to the beginning
472         of a character.  If not, move forward until this is the case.
473         Note that there are not too many places where it is legitimate
474         to do this sort of thing.  It's an error if you're passed an
475         "invalid" byte index.
476
477    INC_BYTIND(buf, bi):
478         Given a byte index (assumed to point at the beginning of a
479         character), modify that value so it points to the beginning
480         of the next character.
481
482    DEC_BYTIND(buf, bi):
483         Given a byte index (assumed to point at the beginning of a
484         character), modify that value so it points to the beginning
485         of the previous character.  Unlike for DEC_CHARPTR(), we can
486         do all the assert()s because there are sentinels at the
487         beginning of the gap and the end of the buffer.
488
489    BYTIND_INVALID:
490         A constant representing an invalid Bytind.  Valid Bytinds
491         can never have this value.
492
493
494    (B) Converting between Bufpos's and Bytinds:
495    --------------------------------------------
496
497     bufpos_to_bytind(buf, bu):
498         Given a Bufpos, return the equivalent Bytind.
499
500     bytind_to_bufpos(buf, bi):
501         Given a Bytind, return the equivalent Bufpos.
502
503     make_bufpos(buf, bi):
504         Given a Bytind, return the equivalent Bufpos as a Lisp Object.
505  */
506
507
508 /*----------------------------------------------------------------------*/
509 /*                       working with byte indices                      */
510 /*----------------------------------------------------------------------*/
511
512 #ifdef MULE
513 # define VALID_BYTIND_P(buf, x) \
514   BUFBYTE_FIRST_BYTE_P (*BI_BUF_BYTE_ADDRESS (buf, x))
515 #else
516 # define VALID_BYTIND_P(buf, x) 1
517 #endif
518
519 #ifdef ERROR_CHECK_BUFPOS
520
521 # define ASSERT_VALID_BYTIND_UNSAFE(buf, x) do {                \
522   assert (BUFFER_LIVE_P (buf));                                 \
523   assert ((x) >= BI_BUF_BEG (buf) && x <= BI_BUF_Z (buf));      \
524   assert (VALID_BYTIND_P (buf, x));                             \
525 } while (0)
526 # define ASSERT_VALID_BYTIND_BACKWARD_UNSAFE(buf, x) do {       \
527   assert (BUFFER_LIVE_P (buf));                                 \
528   assert ((x) > BI_BUF_BEG (buf) && x <= BI_BUF_Z (buf));       \
529   assert (VALID_BYTIND_P (buf, x));                             \
530 } while (0)
531 # define ASSERT_VALID_BYTIND_FORWARD_UNSAFE(buf, x) do {        \
532   assert (BUFFER_LIVE_P (buf));                                 \
533   assert ((x) >= BI_BUF_BEG (buf) && x < BI_BUF_Z (buf));       \
534   assert (VALID_BYTIND_P (buf, x));                             \
535 } while (0)
536
537 #else /* not ERROR_CHECK_BUFPOS */
538 # define ASSERT_VALID_BYTIND_UNSAFE(buf, x)
539 # define ASSERT_VALID_BYTIND_BACKWARD_UNSAFE(buf, x)
540 # define ASSERT_VALID_BYTIND_FORWARD_UNSAFE(buf, x)
541
542 #endif /* not ERROR_CHECK_BUFPOS */
543
544 /* Note that, although the Mule version will work fine for non-Mule
545    as well (it should reduce down to nothing), we provide a separate
546    version to avoid compilation warnings and possible non-optimal
547    results with stupid compilers. */
548
549 #ifdef MULE
550 # define VALIDATE_BYTIND_BACKWARD(buf, x) do {          \
551   Bufbyte *VBB_ptr = BI_BUF_BYTE_ADDRESS (buf, x);      \
552   while (!BUFBYTE_FIRST_BYTE_P (*VBB_ptr))              \
553     VBB_ptr--, (x)--;                                   \
554 } while (0)
555 #else
556 # define VALIDATE_BYTIND_BACKWARD(buf, x)
557 #endif
558
559 /* Note that, although the Mule version will work fine for non-Mule
560    as well (it should reduce down to nothing), we provide a separate
561    version to avoid compilation warnings and possible non-optimal
562    results with stupid compilers. */
563
564 #ifdef MULE
565 # define VALIDATE_BYTIND_FORWARD(buf, x) do {           \
566   Bufbyte *VBF_ptr = BI_BUF_BYTE_ADDRESS (buf, x);      \
567   while (!BUFBYTE_FIRST_BYTE_P (*VBF_ptr))              \
568     VBF_ptr++, (x)++;                                   \
569 } while (0)
570 #else
571 # define VALIDATE_BYTIND_FORWARD(buf, x)
572 #endif
573
574 /* Note that in the simplest case (no MULE, no ERROR_CHECK_BUFPOS),
575    this crap reduces down to simply (x)++. */
576
577 #define INC_BYTIND(buf, x) do                           \
578 {                                                       \
579   ASSERT_VALID_BYTIND_FORWARD_UNSAFE (buf, x);          \
580   /* Note that we do the increment first to             \
581      make sure that the pointer in                      \
582      VALIDATE_BYTIND_FORWARD() ends up on               \
583      the correct side of the gap */                     \
584   (x)++;                                                \
585   VALIDATE_BYTIND_FORWARD (buf, x);                     \
586 } while (0)
587
588 /* Note that in the simplest case (no MULE, no ERROR_CHECK_BUFPOS),
589    this crap reduces down to simply (x)--. */
590
591 #define DEC_BYTIND(buf, x) do                           \
592 {                                                       \
593   ASSERT_VALID_BYTIND_BACKWARD_UNSAFE (buf, x);         \
594   /* Note that we do the decrement first to             \
595      make sure that the pointer in                      \
596      VALIDATE_BYTIND_BACKWARD() ends up on              \
597      the correct side of the gap */                     \
598   (x)--;                                                \
599   VALIDATE_BYTIND_BACKWARD (buf, x);                    \
600 } while (0)
601
602 INLINE Bytind prev_bytind (struct buffer *buf, Bytind x);
603 INLINE Bytind
604 prev_bytind (struct buffer *buf, Bytind x)
605 {
606   DEC_BYTIND (buf, x);
607   return x;
608 }
609
610 INLINE Bytind next_bytind (struct buffer *buf, Bytind x);
611 INLINE Bytind
612 next_bytind (struct buffer *buf, Bytind x)
613 {
614   INC_BYTIND (buf, x);
615   return x;
616 }
617
618 #define BYTIND_INVALID ((Bytind) -1)
619
620 /*----------------------------------------------------------------------*/
621 /*         Converting between buffer positions and byte indices         */
622 /*----------------------------------------------------------------------*/
623
624 #ifdef MULE
625
626 Bytind bufpos_to_bytind_func (struct buffer *buf, Bufpos x);
627 Bufpos bytind_to_bufpos_func (struct buffer *buf, Bytind x);
628
629 /* The basic algorithm we use is to keep track of a known region of
630    characters in each buffer, all of which are of the same width.  We
631    keep track of the boundaries of the region in both Bufpos and
632    Bytind coordinates and also keep track of the char width, which
633    is 1 - 4 bytes.  If the position we're translating is not in
634    the known region, then we invoke a function to update the known
635    region to surround the position in question.  This assumes
636    locality of reference, which is usually the case.
637
638    Note that the function to update the known region can be simple
639    or complicated depending on how much information we cache.
640    For the moment, we don't cache any information, and just move
641    linearly forward or back from the known region, with a few
642    shortcuts to catch all-ASCII buffers. (Note that this will
643    thrash with bad locality of reference.) A smarter method would
644    be to keep some sort of pseudo-extent layer over the buffer;
645    maybe keep track of the bufpos/bytind correspondence at the
646    beginning of each line, which would allow us to do a binary
647    search over the pseudo-extents to narrow things down to the
648    correct line, at which point you could use a linear movement
649    method.  This would also mesh well with efficiently
650    implementing a line-numbering scheme.
651
652    Note also that we have to multiply or divide by the char width
653    in order to convert the positions.  We do some tricks to avoid
654    ever actually having to do a multiply or divide, because that
655    is typically an expensive operation (esp. divide).  Multiplying
656    or dividing by 1, 2, or 4 can be implemented simply as a
657    shift left or shift right, and we keep track of a shifter value
658    (0, 1, or 2) indicating how much to shift.  Multiplying by 3
659    can be implemented by doubling and then adding the original
660    value.  Dividing by 3, alas, cannot be implemented in any
661    simple shift/subtract method, as far as I know; so we just
662    do a table lookup.  For simplicity, we use a table of size
663    128K, which indexes the "divide-by-3" values for the first
664    64K non-negative numbers. (Note that we can increase the
665    size up to 384K, i.e. indexing the first 192K non-negative
666    numbers, while still using shorts in the array.) This also
667    means that the size of the known region can be at most
668    64K for width-three characters.
669    */
670
671 #ifndef UTF2000
672 extern short three_to_one_table[];
673 #endif
674
675 INLINE int real_bufpos_to_bytind (struct buffer *buf, Bufpos x);
676 INLINE int
677 real_bufpos_to_bytind (struct buffer *buf, Bufpos x)
678 {
679   if (x >= buf->text->mule_bufmin && x <= buf->text->mule_bufmax)
680     return (buf->text->mule_bytmin +
681 #ifdef UTF2000
682             (x - buf->text->mule_bufmin) * buf->text->mule_size
683 #else
684             ((x - buf->text->mule_bufmin) << buf->text->mule_shifter) +
685             (buf->text->mule_three_p ? (x - buf->text->mule_bufmin) : 0)
686 #endif
687             );
688   else
689     return bufpos_to_bytind_func (buf, x);
690 }
691
692 INLINE int real_bytind_to_bufpos (struct buffer *buf, Bytind x);
693 INLINE int
694 real_bytind_to_bufpos (struct buffer *buf, Bytind x)
695 {
696   if (x >= buf->text->mule_bytmin && x <= buf->text->mule_bytmax)
697     return (buf->text->mule_bufmin +
698 #ifdef UTF2000
699             (buf->text->mule_size == 0 ? 0 :
700              (x - buf->text->mule_bytmin) / buf->text->mule_size)
701 #else
702             ((buf->text->mule_three_p
703               ? three_to_one_table[x - buf->text->mule_bytmin]
704               : (x - buf->text->mule_bytmin) >> buf->text->mule_shifter))
705 #endif
706             );
707   else
708     return bytind_to_bufpos_func (buf, x);
709 }
710
711 #else /* not MULE */
712
713 # define real_bufpos_to_bytind(buf, x)  ((Bytind) x)
714 # define real_bytind_to_bufpos(buf, x)  ((Bufpos) x)
715
716 #endif /* not MULE */
717
718 #ifdef ERROR_CHECK_BUFPOS
719
720 Bytind bufpos_to_bytind (struct buffer *buf, Bufpos x);
721 Bufpos bytind_to_bufpos (struct buffer *buf, Bytind x);
722
723 #else /* not ERROR_CHECK_BUFPOS */
724
725 #define bufpos_to_bytind real_bufpos_to_bytind
726 #define bytind_to_bufpos real_bytind_to_bufpos
727
728 #endif /* not ERROR_CHECK_BUFPOS */
729
730 #define make_bufpos(buf, ind) make_int (bytind_to_bufpos (buf, ind))
731
732 /*----------------------------------------------------------------------*/
733 /*         Converting between buffer bytes and Emacs characters         */
734 /*----------------------------------------------------------------------*/
735
736 /* The character at position POS in buffer. */
737 #define BI_BUF_FETCH_CHAR(buf, pos) \
738   charptr_emchar (BI_BUF_BYTE_ADDRESS (buf, pos))
739 #define BUF_FETCH_CHAR(buf, pos) \
740   BI_BUF_FETCH_CHAR (buf, bufpos_to_bytind (buf, pos))
741
742 /* The character at position POS in buffer, as a string.  This is
743    equivalent to set_charptr_emchar (str, BUF_FETCH_CHAR (buf, pos))
744    but is faster for Mule. */
745
746 # define BI_BUF_CHARPTR_COPY_CHAR(buf, pos, str) \
747   charptr_copy_char (BI_BUF_BYTE_ADDRESS (buf, pos), str)
748 #define BUF_CHARPTR_COPY_CHAR(buf, pos, str) \
749   BI_BUF_CHARPTR_COPY_CHAR (buf, bufpos_to_bytind (buf, pos), str)
750
751
752
753 \f
754 /************************************************************************/
755 /*                                                                      */
756 /*                  working with externally-formatted data              */
757 /*                                                                      */
758 /************************************************************************/
759
760 /* Sometimes strings need to be converted into one or another
761    external format, for passing to a library function. (Note
762    that we encapsulate and automatically convert the arguments
763    of some functions, but not others.) At times this conversion
764    also has to go the other way -- i.e. when we get external-
765    format strings back from a library function.
766 */
767
768 #ifdef FILE_CODING
769
770 /* WARNING: These use a static buffer.  This can lead to disaster if
771    these functions are not used *very* carefully.  Under normal
772    circumstances, do not call these functions; call the front ends
773    below. */
774
775 Extbyte *convert_to_external_format (CONST Bufbyte *ptr,
776                                      Bytecount len,
777                                      Extcount *len_out,
778                                      enum external_data_format fmt);
779 Bufbyte *convert_from_external_format (CONST Extbyte *ptr,
780                                        Extcount len,
781                                        Bytecount *len_out,
782                                        enum external_data_format fmt);
783
784 #else /* ! MULE */
785
786 #define convert_to_external_format(ptr, len, len_out, fmt) \
787      (*(len_out) = (int) (len), (Extbyte *) (ptr))
788 #define convert_from_external_format(ptr, len, len_out, fmt) \
789      (*(len_out) = (Bytecount) (len), (Bufbyte *) (ptr))
790
791 #endif /* ! MULE */
792
793 /* In all of the following macros we use the following general principles:
794
795    -- Functions that work with charptr's accept two sorts of charptr's:
796
797       a) Pointers to memory with a length specified.  The pointer will be
798          fundamentally of type `unsigned char *' (although labelled
799          as `Bufbyte *' for internal-format data and `Extbyte *' for
800          external-format data) and the length will be fundamentally of
801          type `int' (although labelled as `Bytecount' for internal-format
802          data and `Extcount' for external-format data).  The length is
803          always a count in bytes.
804       b) Zero-terminated pointers; no length specified.  The pointer
805          is of type `char *', whether the data pointed to is internal-format
806          or external-format.  These sorts of pointers are available for
807          convenience in working with C library functions and literal
808          strings.  In general you should use these sorts of pointers only
809          to interface to library routines and not for general manipulation,
810          as you are liable to lose embedded nulls and such.  This could
811          be a big problem for routines that want Unicode-formatted data,
812          which is likely to have lots of embedded nulls in it.
813          (In the real world, though, external Unicode data will be UTF-8,
814          which will not have embedded nulls and is ASCII-compatible - martin)
815
816    -- Functions that work with Lisp strings accept strings as Lisp Objects
817       (as opposed to the `struct Lisp_String *' for some of the other
818       string accessors).  This is for convenience in working with the
819       functions, as otherwise you will almost always have to call
820       XSTRING() on the object.
821
822    -- Functions that work with charptr's are not guaranteed to copy
823       their data into alloca()ed space.  Functions that work with
824       Lisp strings are, however.  The reason is that Lisp strings can
825       be relocated any time a GC happens, and it could happen at some
826       rather unexpected times.  The internal-external conversion is
827       rarely done in time-critical functions, and so the slight
828       extra time required for alloca() and copy is well-worth the
829       safety of knowing your string data won't be relocated out from
830       under you.
831       */
832
833
834 /* Maybe convert charptr's data into ext-format and store the result in
835    alloca()'ed space.
836
837    You may wonder why this is written in this fashion and not as a
838    function call.  With a little trickery it could certainly be
839    written this way, but it won't work because of those DAMN GCC WANKERS
840    who couldn't be bothered to handle alloca() properly on the x86
841    architecture. (If you put a call to alloca() in the argument to
842    a function call, the stack space gets allocated right in the
843    middle of the arguments to the function call and you are unbelievably
844    hosed.) */
845
846 #ifdef MULE
847
848 #define GET_CHARPTR_EXT_DATA_ALLOCA(ptr, len, fmt, ptr_out, len_out) do \
849 {                                                                       \
850   Bytecount gceda_len_in = (Bytecount) (len);                           \
851   Extcount  gceda_len_out;                                              \
852   CONST Bufbyte *gceda_ptr_in = (ptr);                                  \
853   Extbyte *gceda_ptr_out =                                              \
854     convert_to_external_format (gceda_ptr_in, gceda_len_in,             \
855                                 &gceda_len_out, fmt);                   \
856   /* If the new string is identical to the old (will be the case most   \
857      of the time), just return the same string back.  This saves        \
858      on alloca()ing, which can be useful on C alloca() machines and     \
859      on stack-space-challenged environments. */                         \
860                                                                         \
861   if (gceda_len_in == gceda_len_out &&                                  \
862       !memcmp (gceda_ptr_in, gceda_ptr_out, gceda_len_out))             \
863     {                                                                   \
864       (ptr_out) = (Extbyte *) gceda_ptr_in;                             \
865     }                                                                   \
866   else                                                                  \
867     {                                                                   \
868       (ptr_out) = (Extbyte *) alloca (1 + gceda_len_out);               \
869       memcpy ((void *) ptr_out, gceda_ptr_out, 1 + gceda_len_out);      \
870     }                                                                   \
871   (len_out) = gceda_len_out;                                            \
872 } while (0)
873
874 #else /* ! MULE */
875
876 #define GET_CHARPTR_EXT_DATA_ALLOCA(ptr, len, fmt, ptr_out, len_out) do \
877 {                                       \
878   (ptr_out) = (Extbyte *) (ptr);        \
879   (len_out) = (Extcount) (len);         \
880 } while (0)
881
882 #endif /* ! MULE */
883
884 #define GET_C_CHARPTR_EXT_DATA_ALLOCA(ptr, fmt, ptr_out) do     \
885 {                                                               \
886   Extcount gcceda_ignored_len;                                  \
887   CONST Bufbyte *gcceda_ptr_in = (CONST Bufbyte *) (ptr);       \
888   Extbyte *gcceda_ptr_out;                                      \
889                                                                 \
890   GET_CHARPTR_EXT_DATA_ALLOCA (gcceda_ptr_in,                   \
891                                strlen ((char *) gcceda_ptr_in), \
892                                fmt,                             \
893                                gcceda_ptr_out,                  \
894                                gcceda_ignored_len);             \
895   (ptr_out) = (char *) gcceda_ptr_out;                          \
896 } while (0)
897
898 #define GET_C_CHARPTR_EXT_BINARY_DATA_ALLOCA(ptr, ptr_out) \
899   GET_C_CHARPTR_EXT_DATA_ALLOCA (ptr, FORMAT_BINARY, ptr_out)
900 #define GET_CHARPTR_EXT_BINARY_DATA_ALLOCA(ptr, len, ptr_out, len_out) \
901   GET_CHARPTR_EXT_DATA_ALLOCA (ptr, len, FORMAT_BINARY, ptr_out, len_out)
902
903 #define GET_C_CHARPTR_EXT_FILENAME_DATA_ALLOCA(ptr, ptr_out) \
904   GET_C_CHARPTR_EXT_DATA_ALLOCA (ptr, FORMAT_FILENAME, ptr_out)
905 #define GET_CHARPTR_EXT_FILENAME_DATA_ALLOCA(ptr, len, ptr_out, len_out) \
906   GET_CHARPTR_EXT_DATA_ALLOCA (ptr, len, FORMAT_FILENAME, ptr_out, len_out)
907
908 #define GET_C_CHARPTR_EXT_CTEXT_DATA_ALLOCA(ptr, ptr_out) \
909   GET_C_CHARPTR_EXT_DATA_ALLOCA (ptr, FORMAT_CTEXT, ptr_out)
910 #define GET_CHARPTR_EXT_CTEXT_DATA_ALLOCA(ptr, len, ptr_out, len_out) \
911   GET_CHARPTR_EXT_DATA_ALLOCA (ptr, len, FORMAT_CTEXT, ptr_out, len_out)
912
913 /* Maybe convert external charptr's data into internal format and store
914    the result in alloca()'ed space.
915
916    You may wonder why this is written in this fashion and not as a
917    function call.  With a little trickery it could certainly be
918    written this way, but it won't work because of those DAMN GCC WANKERS
919    who couldn't be bothered to handle alloca() properly on the x86
920    architecture. (If you put a call to alloca() in the argument to
921    a function call, the stack space gets allocated right in the
922    middle of the arguments to the function call and you are unbelievably
923    hosed.) */
924
925 #ifdef MULE
926
927 #define GET_CHARPTR_INT_DATA_ALLOCA(ptr, len, fmt, ptr_out, len_out) do \
928 {                                                                       \
929   Extcount gcida_len_in = (Extcount) (len);                             \
930   Bytecount gcida_len_out;                                              \
931   CONST Extbyte *gcida_ptr_in = (ptr);                                  \
932   Bufbyte *gcida_ptr_out =                                              \
933     convert_from_external_format (gcida_ptr_in, gcida_len_in,           \
934                                   &gcida_len_out, fmt);                 \
935   /* If the new string is identical to the old (will be the case most   \
936      of the time), just return the same string back.  This saves        \
937      on alloca()ing, which can be useful on C alloca() machines and     \
938      on stack-space-challenged environments. */                         \
939                                                                         \
940   if (gcida_len_in == gcida_len_out &&                                  \
941       !memcmp (gcida_ptr_in, gcida_ptr_out, gcida_len_out))             \
942     {                                                                   \
943       (ptr_out) = (Bufbyte *) gcida_ptr_in;                             \
944     }                                                                   \
945   else                                                                  \
946     {                                                                   \
947       (ptr_out) = (Extbyte *) alloca (1 + gcida_len_out);               \
948       memcpy ((void *) ptr_out, gcida_ptr_out, 1 + gcida_len_out);      \
949     }                                                                   \
950   (len_out) = gcida_len_out;                                            \
951 } while (0)
952
953 #else /* ! MULE */
954
955 #define GET_CHARPTR_INT_DATA_ALLOCA(ptr, len, fmt, ptr_out, len_out) do \
956 {                                       \
957   (ptr_out) = (Bufbyte *) (ptr);        \
958   (len_out) = (Bytecount) (len);        \
959 } while (0)
960
961 #endif /* ! MULE */
962
963 #define GET_C_CHARPTR_INT_DATA_ALLOCA(ptr, fmt, ptr_out) do     \
964 {                                                               \
965   Bytecount gccida_ignored_len;                                 \
966   CONST Extbyte *gccida_ptr_in = (CONST Extbyte *) (ptr);       \
967   Bufbyte *gccida_ptr_out;                                      \
968                                                                 \
969   GET_CHARPTR_INT_DATA_ALLOCA (gccida_ptr_in,                   \
970                                strlen ((char *) gccida_ptr_in), \
971                                fmt,                             \
972                                gccida_ptr_out,                  \
973                                gccida_ignored_len);             \
974   (ptr_out) = gccida_ptr_out;                                   \
975 } while (0)
976
977 #define GET_C_CHARPTR_INT_BINARY_DATA_ALLOCA(ptr, ptr_out)      \
978   GET_C_CHARPTR_INT_DATA_ALLOCA (ptr, FORMAT_BINARY, ptr_out)
979 #define GET_CHARPTR_INT_BINARY_DATA_ALLOCA(ptr, len, ptr_out, len_out) \
980   GET_CHARPTR_INT_DATA_ALLOCA (ptr, len, FORMAT_BINARY, ptr_out, len_out)
981
982 #define GET_C_CHARPTR_INT_FILENAME_DATA_ALLOCA(ptr, ptr_out)    \
983   GET_C_CHARPTR_INT_DATA_ALLOCA (ptr, FORMAT_FILENAME, ptr_out)
984 #define GET_CHARPTR_INT_FILENAME_DATA_ALLOCA(ptr, len, ptr_out, len_out) \
985   GET_CHARPTR_INT_DATA_ALLOCA (ptr, len, FORMAT_FILENAME, ptr_out, len_out)
986
987 #define GET_C_CHARPTR_INT_CTEXT_DATA_ALLOCA(ptr, ptr_out)       \
988   GET_C_CHARPTR_INT_DATA_ALLOCA (ptr, FORMAT_CTEXT, ptr_out)
989 #define GET_CHARPTR_INT_CTEXT_DATA_ALLOCA(ptr, len, ptr_out, len_out) \
990   GET_CHARPTR_INT_DATA_ALLOCA (ptr, len, FORMAT_CTEXT, ptr_out, len_out)
991
992
993 /* Maybe convert Lisp string's data into ext-format and store the result in
994    alloca()'ed space.
995
996    You may wonder why this is written in this fashion and not as a
997    function call.  With a little trickery it could certainly be
998    written this way, but it won't work because of those DAMN GCC WANKERS
999    who couldn't be bothered to handle alloca() properly on the x86
1000    architecture. (If you put a call to alloca() in the argument to
1001    a function call, the stack space gets allocated right in the
1002    middle of the arguments to the function call and you are unbelievably
1003    hosed.) */
1004
1005 #define GET_STRING_EXT_DATA_ALLOCA(s, fmt, ptr_out, len_out) do \
1006 {                                                               \
1007   Extcount gseda_len_out;                                       \
1008   struct Lisp_String *gseda_s = XSTRING (s);                    \
1009   Extbyte * gseda_ptr_out =                                     \
1010     convert_to_external_format (string_data (gseda_s),          \
1011                                 string_length (gseda_s),        \
1012                                 &gseda_len_out, fmt);           \
1013   (ptr_out) = (Extbyte *) alloca (1 + gseda_len_out);           \
1014   memcpy ((void *) ptr_out, gseda_ptr_out, 1 + gseda_len_out);  \
1015   (len_out) = gseda_len_out;                                    \
1016 } while (0)
1017
1018
1019 #define GET_C_STRING_EXT_DATA_ALLOCA(s, fmt, ptr_out) do        \
1020 {                                                               \
1021   Extcount gcseda_ignored_len;                                  \
1022   Extbyte *gcseda_ptr_out;                                      \
1023                                                                 \
1024   GET_STRING_EXT_DATA_ALLOCA (s, fmt, gcseda_ptr_out,           \
1025                               gcseda_ignored_len);              \
1026   (ptr_out) = (char *) gcseda_ptr_out;                          \
1027 } while (0)
1028
1029 #define GET_STRING_BINARY_DATA_ALLOCA(s, ptr_out, len_out)      \
1030   GET_STRING_EXT_DATA_ALLOCA (s, FORMAT_BINARY, ptr_out, len_out)
1031 #define GET_C_STRING_BINARY_DATA_ALLOCA(s, ptr_out)             \
1032   GET_C_STRING_EXT_DATA_ALLOCA (s, FORMAT_BINARY, ptr_out)
1033
1034 #define GET_STRING_FILENAME_DATA_ALLOCA(s, ptr_out, len_out)    \
1035   GET_STRING_EXT_DATA_ALLOCA (s, FORMAT_FILENAME, ptr_out, len_out)
1036 #define GET_C_STRING_FILENAME_DATA_ALLOCA(s, ptr_out)           \
1037   GET_C_STRING_EXT_DATA_ALLOCA (s, FORMAT_FILENAME, ptr_out)
1038
1039 #define GET_STRING_OS_DATA_ALLOCA(s, ptr_out, len_out)          \
1040   GET_STRING_EXT_DATA_ALLOCA (s, FORMAT_OS, ptr_out, len_out)
1041 #define GET_C_STRING_OS_DATA_ALLOCA(s, ptr_out)                 \
1042   GET_C_STRING_EXT_DATA_ALLOCA (s, FORMAT_OS, ptr_out)
1043
1044 #define GET_STRING_CTEXT_DATA_ALLOCA(s, ptr_out, len_out)       \
1045   GET_STRING_EXT_DATA_ALLOCA (s, FORMAT_CTEXT, ptr_out, len_out)
1046 #define GET_C_STRING_CTEXT_DATA_ALLOCA(s, ptr_out)              \
1047   GET_C_STRING_EXT_DATA_ALLOCA (s, FORMAT_CTEXT, ptr_out)
1048
1049 \f
1050 /************************************************************************/
1051 /*                                                                      */
1052 /*                  higher-level buffer-position functions              */
1053 /*                                                                      */
1054 /************************************************************************/
1055
1056 /*----------------------------------------------------------------------*/
1057 /*           Settor macros for important positions in a buffer          */
1058 /*----------------------------------------------------------------------*/
1059
1060 /* Set beginning of accessible range of buffer.  */
1061 #define SET_BOTH_BUF_BEGV(buf, val, bival)      \
1062 do                                              \
1063 {                                               \
1064   (buf)->begv = (bival);                        \
1065   (buf)->bufbegv = (val);                       \
1066 } while (0)
1067
1068 /* Set end of accessible range of buffer.  */
1069 #define SET_BOTH_BUF_ZV(buf, val, bival)        \
1070 do                                              \
1071 {                                               \
1072   (buf)->zv = (bival);                          \
1073   (buf)->bufzv = (val);                         \
1074 } while (0)
1075
1076 /* Set point. */
1077 /* Since BEGV and ZV are almost never set, it's reasonable to enforce
1078    the restriction that the Bufpos and Bytind values must both be
1079    specified.  However, point is set in lots and lots of places.  So
1080    we provide the ability to specify both (for efficiency) or just
1081    one. */
1082 #define BOTH_BUF_SET_PT(buf, val, bival) set_buffer_point (buf, val, bival)
1083 #define BI_BUF_SET_PT(buf, bival) \
1084   BOTH_BUF_SET_PT (buf, bytind_to_bufpos (buf, bival), bival)
1085 #define BUF_SET_PT(buf, value) \
1086   BOTH_BUF_SET_PT (buf, value, bufpos_to_bytind (buf, value))
1087
1088
1089 #if 0 /* FSFmacs */
1090 /* These macros exist in FSFmacs because SET_PT() in FSFmacs incorrectly
1091    does too much stuff, such as moving out of invisible extents. */
1092 #define TEMP_SET_PT(position) (temp_set_point ((position), current_buffer))
1093 #define SET_BUF_PT(buf, value) ((buf)->pt = (value))
1094 #endif /* FSFmacs */
1095
1096 /*----------------------------------------------------------------------*/
1097 /*                      Miscellaneous buffer values                     */
1098 /*----------------------------------------------------------------------*/
1099
1100 /* Number of characters in buffer */
1101 #define BUF_SIZE(buf) (BUF_Z (buf) - BUF_BEG (buf))
1102
1103 /* Is this buffer narrowed? */
1104 #define BUF_NARROWED(buf) \
1105    ((BI_BUF_BEGV (buf) != BI_BUF_BEG (buf)) || \
1106     (BI_BUF_ZV   (buf) != BI_BUF_Z   (buf)))
1107
1108 /* Modification count.  */
1109 #define BUF_MODIFF(buf) ((buf)->text->modiff)
1110
1111 /* Saved modification count.  */
1112 #define BUF_SAVE_MODIFF(buf) ((buf)->text->save_modiff)
1113
1114 /* Face changed.  */
1115 #define BUF_FACECHANGE(buf) ((buf)->face_change)
1116
1117 #define POINT_MARKER_P(marker) \
1118    (XMARKER (marker)->buffer != 0 && \
1119     EQ ((marker), XMARKER (marker)->buffer->point_marker))
1120
1121 #define BUF_MARKERS(buf) ((buf)->markers)
1122
1123 /* WARNING:
1124
1125    The new definitions of CEILING_OF() and FLOOR_OF() differ semantically
1126    from the old ones (in FSF Emacs and XEmacs 19.11 and before).
1127    Conversion is as follows:
1128
1129    OLD_BI_CEILING_OF(n) = NEW_BI_CEILING_OF(n) - 1
1130    OLD_BI_FLOOR_OF(n) = NEW_BI_FLOOR_OF(n + 1)
1131
1132    The definitions were changed because the new definitions are more
1133    consistent with the way everything else works in Emacs.
1134  */
1135
1136 /* Properties of CEILING_OF and FLOOR_OF (also apply to BI_ variants):
1137
1138    1) FLOOR_OF (CEILING_OF (n)) = n
1139       CEILING_OF (FLOOR_OF (n)) = n
1140
1141    2) CEILING_OF (n) = n if and only if n = ZV
1142       FLOOR_OF (n) = n if and only if n = BEGV
1143
1144    3) CEILING_OF (CEILING_OF (n)) = ZV
1145       FLOOR_OF (FLOOR_OF (n)) = BEGV
1146
1147    4) The bytes in the regions
1148
1149       [BYTE_ADDRESS (n), BYTE_ADDRESS_BEFORE (CEILING_OF (n))]
1150
1151       and
1152
1153       [BYTE_ADDRESS (FLOOR_OF (n)), BYTE_ADDRESS_BEFORE (n)]
1154
1155       are contiguous.
1156    */
1157
1158
1159 /*  Return the maximum index in the buffer it is safe to scan forwards
1160     past N to.  This is used to prevent buffer scans from running into
1161     the gap (e.g. search.c).  All characters between N and CEILING_OF(N)
1162     are located contiguous in memory.  Note that the character *at*
1163     CEILING_OF(N) is not contiguous in memory. */
1164 #define BI_BUF_CEILING_OF(b, n)                                         \
1165   ((n) < (b)->text->gpt && (b)->text->gpt < BI_BUF_ZV (b) ?             \
1166    (b)->text->gpt : BI_BUF_ZV (b))
1167 #define BUF_CEILING_OF(b, n)                                            \
1168   bytind_to_bufpos (b, BI_BUF_CEILING_OF (b, bufpos_to_bytind (b, n)))
1169
1170 /*  Return the minimum index in the buffer it is safe to scan backwards
1171     past N to.  All characters between FLOOR_OF(N) and N are located
1172     contiguous in memory.  Note that the character *at* N may not be
1173     contiguous in memory. */
1174 #define BI_BUF_FLOOR_OF(b, n)                                           \
1175         (BI_BUF_BEGV (b) < (b)->text->gpt && (b)->text->gpt < (n) ?     \
1176          (b)->text->gpt : BI_BUF_BEGV (b))
1177 #define BUF_FLOOR_OF(b, n)                                              \
1178   bytind_to_bufpos (b, BI_BUF_FLOOR_OF (b, bufpos_to_bytind (b, n)))
1179
1180 #define BI_BUF_CEILING_OF_IGNORE_ACCESSIBLE(b, n)                       \
1181   ((n) < (b)->text->gpt && (b)->text->gpt < BI_BUF_Z (b) ?              \
1182    (b)->text->gpt : BI_BUF_Z (b))
1183 #define BUF_CEILING_OF_IGNORE_ACCESSIBLE(b, n)                          \
1184   bytind_to_bufpos                                                      \
1185    (b, BI_BUF_CEILING_OF_IGNORE_ACCESSIBLE (b, bufpos_to_bytind (b, n)))
1186
1187 #define BI_BUF_FLOOR_OF_IGNORE_ACCESSIBLE(b, n)                         \
1188         (BI_BUF_BEG (b) < (b)->text->gpt && (b)->text->gpt < (n) ?      \
1189          (b)->text->gpt : BI_BUF_BEG (b))
1190 #define BUF_FLOOR_OF_IGNORE_ACCESSIBLE(b, n)                            \
1191   bytind_to_bufpos                                                      \
1192    (b, BI_BUF_FLOOR_OF_IGNORE_ACCESSIBLE (b, bufpos_to_bytind (b, n)))
1193
1194
1195 extern struct buffer *current_buffer;
1196
1197 /* This is the initial (startup) directory, as used for the *scratch* buffer.
1198    We're making this a global to make others aware of the startup directory.
1199    `initial_directory' is stored in external format.
1200  */
1201 extern char initial_directory[];
1202 extern void init_initial_directory (void);   /* initialize initial_directory */
1203
1204 EXFUN (Fbuffer_disable_undo, 1);
1205 EXFUN (Fbuffer_modified_p, 1);
1206 EXFUN (Fbuffer_name, 1);
1207 EXFUN (Fcurrent_buffer, 0);
1208 EXFUN (Ferase_buffer, 1);
1209 EXFUN (Fget_buffer, 1);
1210 EXFUN (Fget_buffer_create, 1);
1211 EXFUN (Fget_file_buffer, 1);
1212 EXFUN (Fkill_buffer, 1);
1213 EXFUN (Fother_buffer, 3);
1214 EXFUN (Frecord_buffer, 1);
1215 EXFUN (Fset_buffer, 1);
1216 EXFUN (Fset_buffer_modified_p, 2);
1217
1218 extern Lisp_Object QSscratch, Qafter_change_function, Qafter_change_functions;
1219 extern Lisp_Object Qbefore_change_function, Qbefore_change_functions;
1220 extern Lisp_Object Qbuffer_or_string_p, Qdefault_directory, Qfirst_change_hook;
1221 extern Lisp_Object Qpermanent_local, Vafter_change_function;
1222 extern Lisp_Object Vafter_change_functions, Vbefore_change_function;
1223 extern Lisp_Object Vbefore_change_functions, Vbuffer_alist, Vbuffer_defaults;
1224 extern Lisp_Object Vinhibit_read_only, Vtransient_mark_mode;
1225
1226 /* This structure marks which slots in a buffer have corresponding
1227    default values in Vbuffer_defaults.
1228    Each such slot has a nonzero value in this structure.
1229    The value has only one nonzero bit.
1230
1231    When a buffer has its own local value for a slot,
1232    the bit for that slot (found in the same slot in this structure)
1233    is turned on in the buffer's local_var_flags slot.
1234
1235    If a slot in this structure is zero, then even though there may
1236    be a DEFVAR_BUFFER_LOCAL for the slot, there is no default value for it;
1237    and the corresponding slot in Vbuffer_defaults is not used.  */
1238
1239 extern struct buffer buffer_local_flags;
1240
1241
1242 /* Allocation of buffer data. */
1243
1244 #ifdef REL_ALLOC
1245
1246 char *r_alloc (unsigned char **, unsigned long);
1247 char *r_re_alloc (unsigned char **, unsigned long);
1248 void r_alloc_free (unsigned char **);
1249
1250 #define BUFFER_ALLOC(data, size) \
1251   ((Bufbyte *) r_alloc ((unsigned char **) &data, (size) * sizeof(Bufbyte)))
1252 #define BUFFER_REALLOC(data, size) \
1253   ((Bufbyte *) r_re_alloc ((unsigned char **) &data, (size) * sizeof(Bufbyte)))
1254 #define BUFFER_FREE(data) r_alloc_free ((unsigned char **) &(data))
1255 #define R_ALLOC_DECLARE(var,data) r_alloc_declare (&(var), data)
1256
1257 #else /* !REL_ALLOC */
1258
1259 #define BUFFER_ALLOC(data,size)\
1260         (data = xnew_array (Bufbyte, size))
1261 #define BUFFER_REALLOC(data,size)\
1262         ((Bufbyte *) xrealloc (data, (size) * sizeof(Bufbyte)))
1263 /* Avoid excess parentheses, or syntax errors may rear their heads. */
1264 #define BUFFER_FREE(data) xfree (data)
1265 #define R_ALLOC_DECLARE(var,data)
1266
1267 #endif /* !REL_ALLOC */
1268
1269 extern Lisp_Object Vbuffer_alist;
1270 void set_buffer_internal (struct buffer *b);
1271 struct buffer *decode_buffer (Lisp_Object buffer, int allow_string);
1272
1273 /* from editfns.c */
1274 void widen_buffer (struct buffer *b, int no_clip);
1275 int beginning_of_line_p (struct buffer *b, Bufpos pt);
1276
1277 /* from insdel.c */
1278 void set_buffer_point (struct buffer *buf, Bufpos pos, Bytind bipos);
1279 void find_charsets_in_bufbyte_string (Charset_ID *charsets,
1280                                       CONST Bufbyte *str,
1281                                       Bytecount len);
1282 void find_charsets_in_emchar_string (Charset_ID *charsets,
1283                                      CONST Emchar *str,
1284                                      Charcount len);
1285 int bufbyte_string_displayed_columns (CONST Bufbyte *str, Bytecount len);
1286 int emchar_string_displayed_columns (CONST Emchar *str, Charcount len);
1287 void convert_bufbyte_string_into_emchar_dynarr (CONST Bufbyte *str,
1288                                                 Bytecount len,
1289                                                 Emchar_dynarr *dyn);
1290 Charcount convert_bufbyte_string_into_emchar_string (CONST Bufbyte *str,
1291                                                      Bytecount len,
1292                                                      Emchar *arr);
1293 void convert_emchar_string_into_bufbyte_dynarr (Emchar *arr, int nels,
1294                                                 Bufbyte_dynarr *dyn);
1295 Bufbyte *convert_emchar_string_into_malloced_string (Emchar *arr, int nels,
1296                                                     Bytecount *len_out);
1297 /* from marker.c */
1298 void init_buffer_markers (struct buffer *b);
1299 void uninit_buffer_markers (struct buffer *b);
1300
1301 /* flags for get_buffer_pos_char(), get_buffer_range_char(), etc. */
1302 /* At most one of GB_COERCE_RANGE and GB_NO_ERROR_IF_BAD should be
1303    specified.  At most one of GB_NEGATIVE_FROM_END and GB_NO_ERROR_IF_BAD
1304    should be specified. */
1305
1306 #define GB_ALLOW_PAST_ACCESSIBLE        (1 << 0)
1307 #define GB_ALLOW_NIL                    (1 << 1)
1308 #define GB_CHECK_ORDER                  (1 << 2)
1309 #define GB_COERCE_RANGE                 (1 << 3)
1310 #define GB_NO_ERROR_IF_BAD              (1 << 4)
1311 #define GB_NEGATIVE_FROM_END            (1 << 5)
1312 #define GB_HISTORICAL_STRING_BEHAVIOR   (GB_NEGATIVE_FROM_END | GB_ALLOW_NIL)
1313
1314 Bufpos get_buffer_pos_char (struct buffer *b, Lisp_Object pos,
1315                             unsigned int flags);
1316 Bytind get_buffer_pos_byte (struct buffer *b, Lisp_Object pos,
1317                             unsigned int flags);
1318 void get_buffer_range_char (struct buffer *b, Lisp_Object from, Lisp_Object to,
1319                             Bufpos *from_out, Bufpos *to_out,
1320                             unsigned int flags);
1321 void get_buffer_range_byte (struct buffer *b, Lisp_Object from, Lisp_Object to,
1322                             Bytind *from_out, Bytind *to_out,
1323                             unsigned int flags);
1324 Charcount get_string_pos_char (Lisp_Object string, Lisp_Object pos,
1325                                unsigned int flags);
1326 Bytecount get_string_pos_byte (Lisp_Object string, Lisp_Object pos,
1327                                unsigned int flags);
1328 void get_string_range_char (Lisp_Object string, Lisp_Object from,
1329                             Lisp_Object to, Charcount *from_out,
1330                             Charcount *to_out, unsigned int flags);
1331 void get_string_range_byte (Lisp_Object string, Lisp_Object from,
1332                             Lisp_Object to, Bytecount *from_out,
1333                             Bytecount *to_out, unsigned int flags);
1334 Bufpos get_buffer_or_string_pos_char (Lisp_Object object, Lisp_Object pos,
1335                                       unsigned int flags);
1336 Bytind get_buffer_or_string_pos_byte (Lisp_Object object, Lisp_Object pos,
1337                                       unsigned int flags);
1338 void get_buffer_or_string_range_char (Lisp_Object object, Lisp_Object from,
1339                                       Lisp_Object to, Bufpos *from_out,
1340                                       Bufpos *to_out, unsigned int flags);
1341 void get_buffer_or_string_range_byte (Lisp_Object object, Lisp_Object from,
1342                                       Lisp_Object to, Bytind *from_out,
1343                                       Bytind *to_out, unsigned int flags);
1344 Bufpos buffer_or_string_accessible_begin_char (Lisp_Object object);
1345 Bufpos buffer_or_string_accessible_end_char (Lisp_Object object);
1346 Bytind buffer_or_string_accessible_begin_byte (Lisp_Object object);
1347 Bytind buffer_or_string_accessible_end_byte (Lisp_Object object);
1348 Bufpos buffer_or_string_absolute_begin_char (Lisp_Object object);
1349 Bufpos buffer_or_string_absolute_end_char (Lisp_Object object);
1350 Bytind buffer_or_string_absolute_begin_byte (Lisp_Object object);
1351 Bytind buffer_or_string_absolute_end_byte (Lisp_Object object);
1352 void record_buffer (Lisp_Object buf);
1353 Lisp_Object get_buffer (Lisp_Object name,
1354                         int error_if_deleted_or_does_not_exist);
1355 int map_over_sharing_buffers (struct buffer *buf,
1356                               int (*mapfun) (struct buffer *buf,
1357                                              void *closure),
1358                               void *closure);
1359
1360 \f
1361 /************************************************************************/
1362 /*                         Case conversion                              */
1363 /************************************************************************/
1364
1365 /* A "trt" table is a mapping from characters to other characters,
1366    typically used to convert between uppercase and lowercase.  For
1367    compatibility reasons, trt tables are currently in the form of
1368    a Lisp string of 256 characters, specifying the conversion for each
1369    of the first 256 Emacs characters (i.e. the 256 Latin-1 characters).
1370    This should be generalized at some point to support conversions for
1371    all of the allowable Mule characters.
1372    */
1373
1374 /* The _1 macros are named as such because they assume that you have
1375    already guaranteed that the character values are all in the range
1376    0 - 255.  Bad lossage will happen otherwise. */
1377
1378 # define MAKE_TRT_TABLE() Fmake_string (make_int (256), make_char (0))
1379 # define TRT_TABLE_AS_STRING(table) XSTRING_DATA (table)
1380 # define TRT_TABLE_CHAR_1(table, ch) \
1381   string_char (XSTRING (table), (Charcount) ch)
1382 # define SET_TRT_TABLE_CHAR_1(table, ch1, ch2) \
1383   set_string_char (XSTRING (table), (Charcount) ch1, ch2)
1384
1385 #ifdef MULE
1386 # define MAKE_MIRROR_TRT_TABLE() make_opaque (256, 0)
1387 # define MIRROR_TRT_TABLE_AS_STRING(table) ((Bufbyte *) XOPAQUE_DATA (table))
1388 # define MIRROR_TRT_TABLE_CHAR_1(table, ch) \
1389   ((Emchar) (MIRROR_TRT_TABLE_AS_STRING (table)[ch]))
1390 # define SET_MIRROR_TRT_TABLE_CHAR_1(table, ch1, ch2) \
1391   (MIRROR_TRT_TABLE_AS_STRING (table)[ch1] = (Bufbyte) (ch2))
1392 #endif
1393
1394 # define IN_TRT_TABLE_DOMAIN(c) (((EMACS_UINT) (c)) <= 255)
1395
1396 #ifdef MULE
1397 #define MIRROR_DOWNCASE_TABLE_AS_STRING(buf) \
1398   MIRROR_TRT_TABLE_AS_STRING (buf->mirror_downcase_table)
1399 #define MIRROR_UPCASE_TABLE_AS_STRING(buf) \
1400   MIRROR_TRT_TABLE_AS_STRING (buf->mirror_upcase_table)
1401 #define MIRROR_CANON_TABLE_AS_STRING(buf) \
1402   MIRROR_TRT_TABLE_AS_STRING (buf->mirror_case_canon_table)
1403 #define MIRROR_EQV_TABLE_AS_STRING(buf) \
1404   MIRROR_TRT_TABLE_AS_STRING (buf->mirror_case_eqv_table)
1405 #else
1406 #define MIRROR_DOWNCASE_TABLE_AS_STRING(buf) \
1407   TRT_TABLE_AS_STRING (buf->downcase_table)
1408 #define MIRROR_UPCASE_TABLE_AS_STRING(buf) \
1409   TRT_TABLE_AS_STRING (buf->upcase_table)
1410 #define MIRROR_CANON_TABLE_AS_STRING(buf) \
1411   TRT_TABLE_AS_STRING (buf->case_canon_table)
1412 #define MIRROR_EQV_TABLE_AS_STRING(buf) \
1413   TRT_TABLE_AS_STRING (buf->case_eqv_table)
1414 #endif
1415
1416 INLINE Emchar TRT_TABLE_OF (Lisp_Object trt, Emchar c);
1417 INLINE Emchar
1418 TRT_TABLE_OF (Lisp_Object trt, Emchar c)
1419 {
1420   return IN_TRT_TABLE_DOMAIN (c) ? TRT_TABLE_CHAR_1 (trt, c) : c;
1421 }
1422
1423 /* Macros used below. */
1424 #define DOWNCASE_TABLE_OF(buf, c) TRT_TABLE_OF (buf->downcase_table, c)
1425 #define UPCASE_TABLE_OF(buf, c) TRT_TABLE_OF (buf->upcase_table, c)
1426
1427 /* 1 if CH is upper case.  */
1428
1429 INLINE int UPPERCASEP (struct buffer *buf, Emchar ch);
1430 INLINE int
1431 UPPERCASEP (struct buffer *buf, Emchar ch)
1432 {
1433   return DOWNCASE_TABLE_OF (buf, ch) != ch;
1434 }
1435
1436 /* 1 if CH is lower case.  */
1437
1438 INLINE int LOWERCASEP (struct buffer *buf, Emchar ch);
1439 INLINE int
1440 LOWERCASEP (struct buffer *buf, Emchar ch)
1441 {
1442   return (UPCASE_TABLE_OF   (buf, ch) != ch &&
1443           DOWNCASE_TABLE_OF (buf, ch) == ch);
1444 }
1445
1446 /* 1 if CH is neither upper nor lower case.  */
1447
1448 INLINE int NOCASEP (struct buffer *buf, Emchar ch);
1449 INLINE int
1450 NOCASEP (struct buffer *buf, Emchar ch)
1451 {
1452   return UPCASE_TABLE_OF (buf, ch) == ch;
1453 }
1454
1455 /* Upcase a character, or make no change if that cannot be done.  */
1456
1457 INLINE Emchar UPCASE (struct buffer *buf, Emchar ch);
1458 INLINE Emchar
1459 UPCASE (struct buffer *buf, Emchar ch)
1460 {
1461   return (DOWNCASE_TABLE_OF (buf, ch) == ch) ? UPCASE_TABLE_OF (buf, ch) : ch;
1462 }
1463
1464 /* Upcase a character known to be not upper case.  Unused. */
1465
1466 #define UPCASE1(buf, ch) UPCASE_TABLE_OF (buf, ch)
1467
1468 /* Downcase a character, or make no change if that cannot be done. */
1469
1470 #define DOWNCASE(buf, ch) DOWNCASE_TABLE_OF (buf, ch)
1471
1472 #endif /* _XEMACS_BUFFER_H_ */