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