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