Fix bounds checking for text properties in `format' (Bug#5306).
[bpt/emacs.git] / src / editfns.c
CommitLineData
35692fe0 1/* Lisp functions pertaining to editing.
0b5538bd
TTN
2 Copyright (C) 1985, 1986, 1987, 1989, 1993, 1994, 1995, 1996,
3 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
76b6f707 4 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
35692fe0
JB
5
6This file is part of GNU Emacs.
7
9ec0b715 8GNU Emacs is free software: you can redistribute it and/or modify
35692fe0 9it under the terms of the GNU General Public License as published by
9ec0b715
GM
10the Free Software Foundation, either version 3 of the License, or
11(at your option) any later version.
35692fe0
JB
12
13GNU Emacs is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
9ec0b715 19along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
35692fe0
JB
20
21
18160b98 22#include <config.h>
68c45bf0 23#include <sys/types.h>
3c14598c 24#include <stdio.h>
d7306fe6 25#include <setjmp.h>
bfb61299 26
5b9c0a1d 27#ifdef HAVE_PWD_H
35692fe0 28#include <pwd.h>
bfb61299
JB
29#endif
30
dfcf069d
AS
31#ifdef HAVE_UNISTD_H
32#include <unistd.h>
33#endif
34
3bb9abc8
ST
35#ifdef HAVE_SYS_UTSNAME_H
36#include <sys/utsname.h>
37#endif
38
b17f9379
DN
39#include "lisp.h"
40
3c14598c
EZ
41/* systime.h includes <sys/time.h> which, on some systems, is required
42 for <sys/resource.h>; thus systime.h must be included before
43 <sys/resource.h> */
44#include "systime.h"
21acf124
ST
45
46#if defined HAVE_SYS_RESOURCE_H
4211ee7d 47#include <sys/resource.h>
e0f712ba
AC
48#endif
49
409847a1
RS
50#include <ctype.h>
51
74d6d8c5 52#include "intervals.h"
35692fe0 53#include "buffer.h"
40fbd254 54#include "character.h"
68c45bf0 55#include "coding.h"
0ae83348 56#include "frame.h"
35692fe0 57#include "window.h"
b91834c3 58#include "blockinput.h"
35692fe0 59
ea229bec
GM
60#ifdef STDC_HEADERS
61#include <float.h>
62#define MAX_10_EXP DBL_MAX_10_EXP
63#else
64#define MAX_10_EXP 310
65#endif
66
a03eaf1c
RS
67#ifndef NULL
68#define NULL 0
69#endif
70
d823c26b
EZ
71#ifndef USER_FULL_NAME
72#define USER_FULL_NAME pw->pw_gecos
73#endif
74
f12ef5eb 75#ifndef USE_CRT_DLL
c59b5089 76extern char **environ;
f12ef5eb
AI
77#endif
78
aac18aa4
PE
79#define TM_YEAR_BASE 1900
80
d65b4235
PE
81/* Nonzero if TM_YEAR is a struct tm's tm_year value that causes
82 asctime to have well-defined behavior. */
83#ifndef TM_YEAR_IN_ASCTIME_RANGE
84# define TM_YEAR_IN_ASCTIME_RANGE(tm_year) \
85 (1000 - TM_YEAR_BASE <= (tm_year) && (tm_year) <= 9999 - TM_YEAR_BASE)
86#endif
87
acb7cc89
GM
88extern size_t emacs_strftimeu P_ ((char *, size_t, const char *,
89 const struct tm *, int));
c433c134
JR
90
91#ifdef WINDOWSNT
92extern Lisp_Object w32_get_internal_run_time ();
93#endif
94
acb7cc89 95static int tm_diff P_ ((struct tm *, struct tm *));
9ac741c5 96static void find_field P_ ((Lisp_Object, Lisp_Object, Lisp_Object, int *, Lisp_Object, int *));
acb7cc89
GM
97static void update_buffer_properties P_ ((int, int));
98static Lisp_Object region_limit P_ ((int));
5c5718b6 99int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
acb7cc89
GM
100static size_t emacs_memftimeu P_ ((char *, size_t, const char *,
101 size_t, const struct tm *, int));
9628fed7
SM
102static void general_insert_function (void (*) (const unsigned char *, EMACS_INT),
103 void (*) (Lisp_Object, EMACS_INT,
104 EMACS_INT, EMACS_INT,
105 EMACS_INT, int),
106 int, int, Lisp_Object *);
acb7cc89
GM
107static Lisp_Object subst_char_in_region_unwind P_ ((Lisp_Object));
108static Lisp_Object subst_char_in_region_unwind_1 P_ ((Lisp_Object));
109static void transpose_markers P_ ((int, int, int, int, int, int, int, int));
260e2e2a 110
8892f40b
GM
111#ifdef HAVE_INDEX
112extern char *index P_ ((const char *, int));
113#endif
114
260e2e2a
KH
115Lisp_Object Vbuffer_access_fontify_functions;
116Lisp_Object Qbuffer_access_fontify_functions;
117Lisp_Object Vbuffer_access_fontified_property;
b1b0ee5a 118
acb7cc89 119Lisp_Object Fuser_full_name P_ ((Lisp_Object));
e3ed8469 120
9a74e7e5
GM
121/* Non-nil means don't stop at field boundary in text motion commands. */
122
123Lisp_Object Vinhibit_field_text_motion;
124
35692fe0
JB
125/* Some static data, and a function to initialize it for each run */
126
127Lisp_Object Vsystem_name;
35b34f72
KH
128Lisp_Object Vuser_real_login_name; /* login name of current user ID */
129Lisp_Object Vuser_full_name; /* full name of current user */
130Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
3bb9abc8 131Lisp_Object Voperating_system_release; /* Operating System Release */
35692fe0 132
acb7cc89
GM
133/* Symbol for the text property used to mark fields. */
134
135Lisp_Object Qfield;
136
137/* A special value for Qfield properties. */
138
139Lisp_Object Qboundary;
140
141
35692fe0
JB
142void
143init_editfns ()
144{
52b14ac0 145 char *user_name;
2ea0266e 146 register unsigned char *p;
35692fe0 147 struct passwd *pw; /* password entry for the current user */
35692fe0
JB
148 Lisp_Object tem;
149
150 /* Set up system_name even when dumping. */
ac988277 151 init_system_name ();
35692fe0
JB
152
153#ifndef CANNOT_DUMP
154 /* Don't bother with this on initial start when just dumping out */
155 if (!initialized)
156 return;
157#endif /* not CANNOT_DUMP */
158
159 pw = (struct passwd *) getpwuid (getuid ());
87485d6f
MW
160#ifdef MSDOS
161 /* We let the real user name default to "root" because that's quite
162 accurate on MSDOG and because it lets Emacs find the init file.
163 (The DVX libraries override the Djgpp libraries here.) */
35b34f72 164 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
87485d6f 165#else
35b34f72 166 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
87485d6f 167#endif
35692fe0 168
52b14ac0
JB
169 /* Get the effective user name, by consulting environment variables,
170 or the effective uid if those are unset. */
2c9ae24e 171 user_name = (char *) getenv ("LOGNAME");
35692fe0 172 if (!user_name)
4691c06d
RS
173#ifdef WINDOWSNT
174 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
175#else /* WINDOWSNT */
2c9ae24e 176 user_name = (char *) getenv ("USER");
4691c06d 177#endif /* WINDOWSNT */
52b14ac0
JB
178 if (!user_name)
179 {
180 pw = (struct passwd *) getpwuid (geteuid ());
181 user_name = (char *) (pw ? pw->pw_name : "unknown");
182 }
35b34f72 183 Vuser_login_name = build_string (user_name);
35692fe0 184
52b14ac0
JB
185 /* If the user name claimed in the environment vars differs from
186 the real uid, use the claimed name to find the full name. */
35b34f72 187 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
3415b0e9
RS
188 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
189 : Vuser_login_name);
34a7a267 190
8f1e2d16 191 p = (unsigned char *) getenv ("NAME");
9d36d071
RS
192 if (p)
193 Vuser_full_name = build_string (p);
3347526c
RS
194 else if (NILP (Vuser_full_name))
195 Vuser_full_name = build_string ("unknown");
3bb9abc8
ST
196
197#ifdef HAVE_SYS_UTSNAME_H
198 {
199 struct utsname uts;
200 uname (&uts);
201 Voperating_system_release = build_string (uts.release);
202 }
203#else
204 Voperating_system_release = Qnil;
205#endif
35692fe0
JB
206}
207\f
208DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
06283081
PJ
209 doc: /* Convert arg CHAR to a string containing that character.
210usage: (char-to-string CHAR) */)
7ee72033 211 (character)
2591ec64 212 Lisp_Object character;
35692fe0 213{
fb8106e8 214 int len;
d5c2c403 215 unsigned char str[MAX_MULTIBYTE_LENGTH];
fb8106e8 216
1b9c91ed 217 CHECK_CHARACTER (character);
35692fe0 218
40fbd254 219 len = CHAR_STRING (XFASTINT (character), str);
5f75e666 220 return make_string_from_bytes (str, 1, len);
35692fe0
JB
221}
222
223DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
7ee72033
MB
224 doc: /* Convert arg STRING to a character, the first character of that string.
225A multibyte character is handled correctly. */)
226 (string)
2591ec64 227 register Lisp_Object string;
35692fe0
JB
228{
229 register Lisp_Object val;
b7826503 230 CHECK_STRING (string);
4e491f8d 231 if (SCHARS (string))
d9d851ea
KH
232 {
233 if (STRING_MULTIBYTE (string))
62a6e103 234 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
d9d851ea 235 else
4e491f8d 236 XSETFASTINT (val, SREF (string, 0));
d9d851ea 237 }
35692fe0 238 else
55561c63 239 XSETFASTINT (val, 0);
35692fe0
JB
240 return val;
241}
242\f
243static Lisp_Object
ec1c14f6
RS
244buildmark (charpos, bytepos)
245 int charpos, bytepos;
35692fe0
JB
246{
247 register Lisp_Object mark;
248 mark = Fmake_marker ();
ec1c14f6 249 set_marker_both (mark, Qnil, charpos, bytepos);
35692fe0
JB
250 return mark;
251}
252
253DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
7ee72033
MB
254 doc: /* Return value of point, as an integer.
255Beginning of buffer is position (point-min). */)
256 ()
35692fe0
JB
257{
258 Lisp_Object temp;
6ec8bbd2 259 XSETFASTINT (temp, PT);
35692fe0
JB
260 return temp;
261}
262
263DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
7ee72033
MB
264 doc: /* Return value of point, as a marker object. */)
265 ()
35692fe0 266{
ec1c14f6 267 return buildmark (PT, PT_BYTE);
35692fe0
JB
268}
269
270int
271clip_to_bounds (lower, num, upper)
272 int lower, num, upper;
273{
274 if (num < lower)
275 return lower;
276 else if (num > upper)
277 return upper;
278 else
279 return num;
280}
281
282DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
7ee72033 283 doc: /* Set point to POSITION, a number or marker.
8696b557
EZ
284Beginning of buffer is position (point-min), end is (point-max).
285
286The return value is POSITION. */)
7ee72033 287 (position)
2591ec64 288 register Lisp_Object position;
35692fe0 289{
fb8106e8 290 int pos;
fb8106e8 291
72ef82ec
RS
292 if (MARKERP (position)
293 && current_buffer == XMARKER (position)->buffer)
ec1c14f6
RS
294 {
295 pos = marker_position (position);
296 if (pos < BEGV)
297 SET_PT_BOTH (BEGV, BEGV_BYTE);
298 else if (pos > ZV)
299 SET_PT_BOTH (ZV, ZV_BYTE);
300 else
301 SET_PT_BOTH (pos, marker_byte_position (position));
302
303 return position;
304 }
305
b7826503 306 CHECK_NUMBER_COERCE_MARKER (position);
35692fe0 307
fb8106e8 308 pos = clip_to_bounds (BEGV, XINT (position), ZV);
fb8106e8 309 SET_PT (pos);
2591ec64 310 return position;
35692fe0
JB
311}
312
acb7cc89
GM
313
314/* Return the start or end position of the region.
315 BEGINNINGP non-zero means return the start.
316 If there is no region active, signal an error. */
317
35692fe0
JB
318static Lisp_Object
319region_limit (beginningp)
320 int beginningp;
321{
646d9d18 322 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
acb7cc89 323 Lisp_Object m;
177c0ea7 324
acb7cc89
GM
325 if (!NILP (Vtransient_mark_mode)
326 && NILP (Vmark_even_if_inactive)
c9dd14e1 327 && NILP (current_buffer->mark_active))
8a0ff744 328 xsignal0 (Qmark_inactive);
177c0ea7 329
35692fe0 330 m = Fmarker_position (current_buffer->mark);
acb7cc89 331 if (NILP (m))
7b5ad687 332 error ("The mark is not set now, so there is no region");
177c0ea7 333
f555f8cf 334 if ((PT < XFASTINT (m)) == (beginningp != 0))
acb7cc89
GM
335 m = make_number (PT);
336 return m;
35692fe0
JB
337}
338
339DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
7ee72033
MB
340 doc: /* Return position of beginning of region, as an integer. */)
341 ()
35692fe0 342{
acb7cc89 343 return region_limit (1);
35692fe0
JB
344}
345
346DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
7ee72033
MB
347 doc: /* Return position of end of region, as an integer. */)
348 ()
35692fe0 349{
acb7cc89 350 return region_limit (0);
35692fe0
JB
351}
352
35692fe0 353DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
7ee72033 354 doc: /* Return this buffer's mark, as a marker object.
a1f17501 355Watch out! Moving this marker changes the mark position.
7ee72033
MB
356If you set the marker not to point anywhere, the buffer will have no mark. */)
357 ()
35692fe0
JB
358{
359 return current_buffer->mark;
360}
acb7cc89 361
c9ed721d 362\f
58401a34
SM
363/* Find all the overlays in the current buffer that touch position POS.
364 Return the number found, and store them in a vector in VEC
365 of length LEN. */
366
367static int
368overlays_around (pos, vec, len)
369 int pos;
370 Lisp_Object *vec;
371 int len;
372{
88006f77
SM
373 Lisp_Object overlay, start, end;
374 struct Lisp_Overlay *tail;
58401a34
SM
375 int startpos, endpos;
376 int idx = 0;
377
88006f77 378 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
58401a34 379 {
88006f77 380 XSETMISC (overlay, tail);
58401a34
SM
381
382 end = OVERLAY_END (overlay);
383 endpos = OVERLAY_POSITION (end);
384 if (endpos < pos)
385 break;
386 start = OVERLAY_START (overlay);
387 startpos = OVERLAY_POSITION (start);
388 if (startpos <= pos)
389 {
390 if (idx < len)
391 vec[idx] = overlay;
392 /* Keep counting overlays even if we can't return them all. */
393 idx++;
394 }
395 }
396
88006f77 397 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
58401a34 398 {
88006f77 399 XSETMISC (overlay, tail);
58401a34
SM
400
401 start = OVERLAY_START (overlay);
402 startpos = OVERLAY_POSITION (start);
403 if (pos < startpos)
404 break;
405 end = OVERLAY_END (overlay);
406 endpos = OVERLAY_POSITION (end);
407 if (pos <= endpos)
408 {
409 if (idx < len)
410 vec[idx] = overlay;
411 idx++;
412 }
413 }
414
415 return idx;
416}
417
418/* Return the value of property PROP, in OBJECT at POSITION.
419 It's the value of PROP that a char inserted at POSITION would get.
420 OBJECT is optional and defaults to the current buffer.
421 If OBJECT is a buffer, then overlay properties are considered as well as
422 text properties.
423 If OBJECT is a window, then that window's buffer is used, but
424 window-specific overlays are considered only if they are associated
425 with OBJECT. */
538f9462 426Lisp_Object
58401a34
SM
427get_pos_property (position, prop, object)
428 Lisp_Object position, object;
429 register Lisp_Object prop;
430{
58401a34
SM
431 CHECK_NUMBER_COERCE_MARKER (position);
432
433 if (NILP (object))
434 XSETBUFFER (object, current_buffer);
dfe6cbf8
SM
435 else if (WINDOWP (object))
436 object = XWINDOW (object)->buffer;
437
438 if (!BUFFERP (object))
439 /* pos-property only makes sense in buffers right now, since strings
440 have no overlays and no notion of insertion for which stickiness
441 could be obeyed. */
442 return Fget_text_property (position, prop, object);
443 else
58401a34
SM
444 {
445 int posn = XINT (position);
446 int noverlays;
447 Lisp_Object *overlay_vec, tem;
448 struct buffer *obuf = current_buffer;
449
450 set_buffer_temp (XBUFFER (object));
451
452 /* First try with room for 40 overlays. */
453 noverlays = 40;
454 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
455 noverlays = overlays_around (posn, overlay_vec, noverlays);
456
457 /* If there are more than 40,
458 make enough space for all, and try again. */
459 if (noverlays > 40)
460 {
461 overlay_vec = (Lisp_Object *) alloca (noverlays * sizeof (Lisp_Object));
462 noverlays = overlays_around (posn, overlay_vec, noverlays);
463 }
464 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
465
466 set_buffer_temp (obuf);
467
468 /* Now check the overlays in order of decreasing priority. */
469 while (--noverlays >= 0)
470 {
471 Lisp_Object ol = overlay_vec[noverlays];
472 tem = Foverlay_get (ol, prop);
473 if (!NILP (tem))
474 {
475 /* Check the overlay is indeed active at point. */
476 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
477 if ((OVERLAY_POSITION (start) == posn
478 && XMARKER (start)->insertion_type == 1)
479 || (OVERLAY_POSITION (finish) == posn
480 && XMARKER (finish)->insertion_type == 0))
481 ; /* The overlay will not cover a char inserted at point. */
482 else
483 {
484 return tem;
485 }
486 }
487 }
177c0ea7 488
7a6a86ad 489 { /* Now check the text properties. */
dfe6cbf8
SM
490 int stickiness = text_property_stickiness (prop, position, object);
491 if (stickiness > 0)
492 return Fget_text_property (position, prop, object);
493 else if (stickiness < 0
494 && XINT (position) > BUF_BEGV (XBUFFER (object)))
495 return Fget_text_property (make_number (XINT (position) - 1),
496 prop, object);
497 else
498 return Qnil;
499 }
58401a34 500 }
58401a34
SM
501}
502
a3caef99 503/* Find the field surrounding POS in *BEG and *END. If POS is nil,
59062dce 504 the value of point is used instead. If BEG or END is null,
acb7cc89 505 means don't store the beginning or end of the field.
a3caef99 506
9ac741c5
MB
507 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
508 results; they do not effect boundary behavior.
509
a3caef99 510 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
ee547125
MB
511 position of a field, then the beginning of the previous field is
512 returned instead of the beginning of POS's field (since the end of a
513 field is actually also the beginning of the next input field, this
514 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
515 true case, if two fields are separated by a field with the special
516 value `boundary', and POS lies within it, then the two separated
517 fields are considered to be adjacent, and POS between them, when
518 finding the beginning and ending of the "merged" field.
a3caef99
RS
519
520 Either BEG or END may be 0, in which case the corresponding value
521 is not stored. */
522
acb7cc89 523static void
9ac741c5 524find_field (pos, merge_at_boundary, beg_limit, beg, end_limit, end)
0daf6e8d
GM
525 Lisp_Object pos;
526 Lisp_Object merge_at_boundary;
9ac741c5 527 Lisp_Object beg_limit, end_limit;
0daf6e8d
GM
528 int *beg, *end;
529{
ee547125
MB
530 /* Fields right before and after the point. */
531 Lisp_Object before_field, after_field;
a3caef99
RS
532 /* 1 if POS counts as the start of a field. */
533 int at_field_start = 0;
534 /* 1 if POS counts as the end of a field. */
535 int at_field_end = 0;
ee547125 536
0daf6e8d
GM
537 if (NILP (pos))
538 XSETFASTINT (pos, PT);
539 else
b7826503 540 CHECK_NUMBER_COERCE_MARKER (pos);
0daf6e8d 541
acb7cc89 542 after_field
58401a34 543 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
acb7cc89
GM
544 before_field
545 = (XFASTINT (pos) > BEGV
7ae1c032 546 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
58401a34 547 Qfield, Qnil, NULL)
e477bb04
KL
548 /* Using nil here would be a more obvious choice, but it would
549 fail when the buffer starts with a non-sticky field. */
550 : after_field);
ee547125
MB
551
552 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
553 and POS is at beginning of a field, which can also be interpreted
554 as the end of the previous field. Note that the case where if
555 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
556 more natural one; then we avoid treating the beginning of a field
557 specially. */
58401a34 558 if (NILP (merge_at_boundary))
ee547125 559 {
58401a34
SM
560 Lisp_Object field = get_pos_property (pos, Qfield, Qnil);
561 if (!EQ (field, after_field))
ee547125 562 at_field_end = 1;
58401a34
SM
563 if (!EQ (field, before_field))
564 at_field_start = 1;
2db1186a
SM
565 if (NILP (field) && at_field_start && at_field_end)
566 /* If an inserted char would have a nil field while the surrounding
567 text is non-nil, we're probably not looking at a
568 zero-length field, but instead at a non-nil field that's
569 not intended for editing (such as comint's prompts). */
570 at_field_end = at_field_start = 0;
0daf6e8d
GM
571 }
572
ee547125
MB
573 /* Note about special `boundary' fields:
574
575 Consider the case where the point (`.') is between the fields `x' and `y':
576
577 xxxx.yyyy
578
579 In this situation, if merge_at_boundary is true, we consider the
580 `x' and `y' fields as forming one big merged field, and so the end
581 of the field is the end of `y'.
582
583 However, if `x' and `y' are separated by a special `boundary' field
584 (a field with a `field' char-property of 'boundary), then we ignore
585 this special field when merging adjacent fields. Here's the same
586 situation, but with a `boundary' field between the `x' and `y' fields:
587
588 xxx.BBBByyyy
589
590 Here, if point is at the end of `x', the beginning of `y', or
591 anywhere in-between (within the `boundary' field), we merge all
592 three fields and consider the beginning as being the beginning of
593 the `x' field, and the end as being the end of the `y' field. */
594
0daf6e8d 595 if (beg)
acb7cc89
GM
596 {
597 if (at_field_start)
598 /* POS is at the edge of a field, and we should consider it as
599 the beginning of the following field. */
600 *beg = XFASTINT (pos);
601 else
602 /* Find the previous field boundary. */
603 {
58401a34 604 Lisp_Object p = pos;
acb7cc89
GM
605 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
606 /* Skip a `boundary' field. */
58401a34 607 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
9ac741c5 608 beg_limit);
58401a34
SM
609
610 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
611 beg_limit);
612 *beg = NILP (p) ? BEGV : XFASTINT (p);
acb7cc89
GM
613 }
614 }
0daf6e8d
GM
615
616 if (end)
acb7cc89
GM
617 {
618 if (at_field_end)
619 /* POS is at the edge of a field, and we should consider it as
620 the end of the previous field. */
621 *end = XFASTINT (pos);
622 else
623 /* Find the next field boundary. */
624 {
625 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
626 /* Skip a `boundary' field. */
9ac741c5
MB
627 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
628 end_limit);
ee547125 629
9ac741c5
MB
630 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
631 end_limit);
acb7cc89
GM
632 *end = NILP (pos) ? ZV : XFASTINT (pos);
633 }
634 }
0daf6e8d 635}
acb7cc89 636
0daf6e8d 637\f
d01f3570 638DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
7ee72033 639 doc: /* Delete the field surrounding POS.
a1f17501 640A field is a region of text with the same `field' property.
f554db0f 641If POS is nil, the value of point is used for POS. */)
7ee72033 642 (pos)
0daf6e8d
GM
643 Lisp_Object pos;
644{
645 int beg, end;
9ac741c5 646 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
0daf6e8d
GM
647 if (beg != end)
648 del_range (beg, end);
d01f3570 649 return Qnil;
0daf6e8d
GM
650}
651
652DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
7ee72033 653 doc: /* Return the contents of the field surrounding POS as a string.
a1f17501 654A field is a region of text with the same `field' property.
f554db0f 655If POS is nil, the value of point is used for POS. */)
7ee72033 656 (pos)
0daf6e8d
GM
657 Lisp_Object pos;
658{
659 int beg, end;
9ac741c5 660 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
0daf6e8d
GM
661 return make_buffer_string (beg, end, 1);
662}
663
664DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
7a6a86ad 665 doc: /* Return the contents of the field around POS, without text properties.
a1f17501 666A field is a region of text with the same `field' property.
f554db0f 667If POS is nil, the value of point is used for POS. */)
7ee72033 668 (pos)
0daf6e8d
GM
669 Lisp_Object pos;
670{
671 int beg, end;
9ac741c5 672 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
0daf6e8d
GM
673 return make_buffer_string (beg, end, 0);
674}
675
9ac741c5 676DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
7ee72033 677 doc: /* Return the beginning of the field surrounding POS.
a1f17501
PJ
678A field is a region of text with the same `field' property.
679If POS is nil, the value of point is used for POS.
680If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
9ac741c5
MB
681field, then the beginning of the *previous* field is returned.
682If LIMIT is non-nil, it is a buffer position; if the beginning of the field
f554db0f 683is before LIMIT, then LIMIT will be returned instead. */)
9ac741c5
MB
684 (pos, escape_from_edge, limit)
685 Lisp_Object pos, escape_from_edge, limit;
0daf6e8d
GM
686{
687 int beg;
9ac741c5 688 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
0daf6e8d
GM
689 return make_number (beg);
690}
691
9ac741c5 692DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
7ee72033 693 doc: /* Return the end of the field surrounding POS.
a1f17501
PJ
694A field is a region of text with the same `field' property.
695If POS is nil, the value of point is used for POS.
696If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
9ac741c5
MB
697then the end of the *following* field is returned.
698If LIMIT is non-nil, it is a buffer position; if the end of the field
f554db0f 699is after LIMIT, then LIMIT will be returned instead. */)
9ac741c5
MB
700 (pos, escape_from_edge, limit)
701 Lisp_Object pos, escape_from_edge, limit;
0daf6e8d
GM
702{
703 int end;
9ac741c5 704 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
0daf6e8d
GM
705 return make_number (end);
706}
707
ee547125 708DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
7ee72033 709 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
a1f17501
PJ
710
711A field is a region of text with the same `field' property.
712If NEW-POS is nil, then the current point is used instead, and set to the
713constrained position if that is different.
714
715If OLD-POS is at the boundary of two fields, then the allowable
716positions for NEW-POS depends on the value of the optional argument
717ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
718constrained to the field that has the same `field' char-property
719as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
720is non-nil, NEW-POS is constrained to the union of the two adjacent
721fields. Additionally, if two fields are separated by another field with
722the special value `boundary', then any point within this special field is
723also considered to be `on the boundary'.
724
725If the optional argument ONLY-IN-LINE is non-nil and constraining
726NEW-POS would move it to a different line, NEW-POS is returned
727unconstrained. This useful for commands that move by line, like
728\\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
729only in the case where they can still move to the right line.
730
731If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
732a non-nil property of that name, then any field boundaries are ignored.
733
7ee72033
MB
734Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
735 (new_pos, old_pos, escape_from_edge, only_in_line, inhibit_capture_property)
ee547125
MB
736 Lisp_Object new_pos, old_pos;
737 Lisp_Object escape_from_edge, only_in_line, inhibit_capture_property;
0daf6e8d
GM
738{
739 /* If non-zero, then the original point, before re-positioning. */
740 int orig_point = 0;
d63b4018
KR
741 int fwd;
742 Lisp_Object prev_old, prev_new;
aac18aa4 743
0daf6e8d
GM
744 if (NILP (new_pos))
745 /* Use the current point, and afterwards, set it. */
746 {
747 orig_point = PT;
748 XSETFASTINT (new_pos, PT);
749 }
750
e477bb04
KL
751 CHECK_NUMBER_COERCE_MARKER (new_pos);
752 CHECK_NUMBER_COERCE_MARKER (old_pos);
753
754 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
755
756 prev_old = make_number (XFASTINT (old_pos) - 1);
757 prev_new = make_number (XFASTINT (new_pos) - 1);
aac18aa4 758
ee5cd4db
GM
759 if (NILP (Vinhibit_field_text_motion)
760 && !EQ (new_pos, old_pos)
42ab8e36
MB
761 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
762 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
e477bb04
KL
763 /* To recognize field boundaries, we must also look at the
764 previous positions; we could use `get_pos_property'
765 instead, but in itself that would fail inside non-sticky
766 fields (like comint prompts). */
767 || (XFASTINT (new_pos) > BEGV
42ab8e36 768 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
e477bb04 769 || (XFASTINT (old_pos) > BEGV
42ab8e36 770 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
ee547125 771 && (NILP (inhibit_capture_property)
e477bb04
KL
772 /* Field boundaries are again a problem; but now we must
773 decide the case exactly, so we need to call
774 `get_pos_property' as well. */
775 || (NILP (get_pos_property (old_pos, inhibit_capture_property, Qnil))
776 && (XFASTINT (old_pos) <= BEGV
42ab8e36
MB
777 || NILP (Fget_char_property (old_pos, inhibit_capture_property, Qnil))
778 || NILP (Fget_char_property (prev_old, inhibit_capture_property, Qnil))))))
2cb3aec4
KL
779 /* It is possible that NEW_POS is not within the same field as
780 OLD_POS; try to move NEW_POS so that it is. */
0daf6e8d 781 {
e477bb04 782 int shortage;
0daf6e8d
GM
783 Lisp_Object field_bound;
784
0daf6e8d 785 if (fwd)
9ac741c5 786 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
0daf6e8d 787 else
9ac741c5 788 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
0daf6e8d 789
10b0f752
MB
790 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
791 other side of NEW_POS, which would mean that NEW_POS is
792 already acceptable, and it's not necessary to constrain it
793 to FIELD_BOUND. */
794 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
795 /* NEW_POS should be constrained, but only if either
796 ONLY_IN_LINE is nil (in which case any constraint is OK),
797 or NEW_POS and FIELD_BOUND are on the same line (in which
798 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
799 && (NILP (only_in_line)
800 /* This is the ONLY_IN_LINE case, check that NEW_POS and
801 FIELD_BOUND are on the same line by seeing whether
802 there's an intervening newline or not. */
803 || (scan_buffer ('\n',
804 XFASTINT (new_pos), XFASTINT (field_bound),
805 fwd ? -1 : 1, &shortage, 1),
806 shortage != 0)))
0daf6e8d
GM
807 /* Constrain NEW_POS to FIELD_BOUND. */
808 new_pos = field_bound;
809
810 if (orig_point && XFASTINT (new_pos) != orig_point)
811 /* The NEW_POS argument was originally nil, so automatically set PT. */
812 SET_PT (XFASTINT (new_pos));
813 }
814
815 return new_pos;
816}
acb7cc89 817
0daf6e8d 818\f
6d57c318
MB
819DEFUN ("line-beginning-position",
820 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
7ee72033 821 doc: /* Return the character position of the first character on the current line.
a1f17501
PJ
822With argument N not nil or 1, move forward N - 1 lines first.
823If scan reaches end of buffer, return that position.
6d57c318 824
2cb3aec4
KL
825This function constrains the returned position to the current field
826unless that would be on a different line than the original,
827unconstrained result. If N is nil or 1, and a front-sticky field
828starts at point, the scan stops as soon as it starts. To ignore field
6d57c318 829boundaries bind `inhibit-field-text-motion' to t.
a1f17501 830
7ee72033
MB
831This function does not move point. */)
832 (n)
c9ed721d
RS
833 Lisp_Object n;
834{
acb7cc89 835 int orig, orig_byte, end;
4e8f005c
CY
836 int count = SPECPDL_INDEX ();
837 specbind (Qinhibit_point_motion_hooks, Qt);
c9ed721d
RS
838
839 if (NILP (n))
840 XSETFASTINT (n, 1);
841 else
b7826503 842 CHECK_NUMBER (n);
c9ed721d
RS
843
844 orig = PT;
ec1c14f6 845 orig_byte = PT_BYTE;
c9ed721d
RS
846 Fforward_line (make_number (XINT (n) - 1));
847 end = PT;
e2dae3f2 848
ec1c14f6 849 SET_PT_BOTH (orig, orig_byte);
35692fe0 850
4e8f005c
CY
851 unbind_to (count, Qnil);
852
0daf6e8d 853 /* Return END constrained to the current input field. */
ee5cd4db
GM
854 return Fconstrain_to_field (make_number (end), make_number (orig),
855 XINT (n) != 1 ? Qt : Qnil,
ee547125 856 Qt, Qnil);
c9ed721d
RS
857}
858
6d57c318 859DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
7ee72033 860 doc: /* Return the character position of the last character on the current line.
a1f17501
PJ
861With argument N not nil or 1, move forward N - 1 lines first.
862If scan reaches end of buffer, return that position.
6d57c318 863
2cb3aec4
KL
864This function constrains the returned position to the current field
865unless that would be on a different line than the original,
866unconstrained result. If N is nil or 1, and a rear-sticky field ends
867at point, the scan stops as soon as it starts. To ignore field
6d57c318
MB
868boundaries bind `inhibit-field-text-motion' to t.
869
7ee72033
MB
870This function does not move point. */)
871 (n)
c9ed721d
RS
872 Lisp_Object n;
873{
0daf6e8d 874 int end_pos;
acb7cc89 875 int orig = PT;
0daf6e8d 876
c9ed721d
RS
877 if (NILP (n))
878 XSETFASTINT (n, 1);
879 else
b7826503 880 CHECK_NUMBER (n);
c9ed721d 881
0daf6e8d
GM
882 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
883
884 /* Return END_POS constrained to the current input field. */
ee5cd4db 885 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
ee547125 886 Qnil, Qt, Qnil);
c9ed721d 887}
6d57c318 888
c9ed721d 889\f
35692fe0
JB
890Lisp_Object
891save_excursion_save ()
892{
acb7cc89
GM
893 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
894 == current_buffer);
35692fe0
JB
895
896 return Fcons (Fpoint_marker (),
aea4a109 897 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
9772455e 898 Fcons (visible ? Qt : Qnil,
2483cf58
GM
899 Fcons (current_buffer->mark_active,
900 selected_window))));
35692fe0
JB
901}
902
903Lisp_Object
904save_excursion_restore (info)
4ad8681a 905 Lisp_Object info;
35692fe0 906{
4ad8681a
RS
907 Lisp_Object tem, tem1, omark, nmark;
908 struct gcpro gcpro1, gcpro2, gcpro3;
2483cf58 909 int visible_p;
35692fe0 910
2483cf58 911 tem = Fmarker_buffer (XCAR (info));
35692fe0
JB
912 /* If buffer being returned to is now deleted, avoid error */
913 /* Otherwise could get error here while unwinding to top level
914 and crash */
915 /* In that case, Fmarker_buffer returns nil now. */
56a98455 916 if (NILP (tem))
35692fe0 917 return Qnil;
4ad8681a
RS
918
919 omark = nmark = Qnil;
920 GCPRO3 (info, omark, nmark);
921
35692fe0 922 Fset_buffer (tem);
2483cf58
GM
923
924 /* Point marker. */
925 tem = XCAR (info);
35692fe0 926 Fgoto_char (tem);
12038f9f 927 unchain_marker (XMARKER (tem));
2483cf58
GM
928
929 /* Mark marker. */
930 info = XCDR (info);
931 tem = XCAR (info);
03d18690 932 omark = Fmarker_position (current_buffer->mark);
35692fe0 933 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
03d18690 934 nmark = Fmarker_position (tem);
12038f9f 935 unchain_marker (XMARKER (tem));
2483cf58
GM
936
937 /* visible */
938 info = XCDR (info);
939 visible_p = !NILP (XCAR (info));
177c0ea7 940
ef580991
RS
941#if 0 /* We used to make the current buffer visible in the selected window
942 if that was true previously. That avoids some anomalies.
943 But it creates others, and it wasn't documented, and it is simpler
944 and cleaner never to alter the window/buffer connections. */
9772455e
RS
945 tem1 = Fcar (tem);
946 if (!NILP (tem1)
0e2c9c70 947 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
35692fe0 948 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
ef580991 949#endif /* 0 */
9772455e 950
2483cf58
GM
951 /* Mark active */
952 info = XCDR (info);
953 tem = XCAR (info);
9772455e 954 tem1 = current_buffer->mark_active;
2483cf58
GM
955 current_buffer->mark_active = tem;
956
9fed2b18
RS
957 if (!NILP (Vrun_hooks))
958 {
03d18690
RS
959 /* If mark is active now, and either was not active
960 or was at a different place, run the activate hook. */
9fed2b18 961 if (! NILP (current_buffer->mark_active))
03d18690
RS
962 {
963 if (! EQ (omark, nmark))
964 call1 (Vrun_hooks, intern ("activate-mark-hook"));
965 }
966 /* If mark has ceased to be active, run deactivate hook. */
9fed2b18
RS
967 else if (! NILP (tem1))
968 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
969 }
2483cf58
GM
970
971 /* If buffer was visible in a window, and a different window was
793cd2c8
GM
972 selected, and the old selected window is still showing this
973 buffer, restore point in that window. */
2483cf58
GM
974 tem = XCDR (info);
975 if (visible_p
976 && !EQ (tem, selected_window)
ba973f7a
GM
977 && (tem1 = XWINDOW (tem)->buffer,
978 (/* Window is live... */
979 BUFFERP (tem1)
980 /* ...and it shows the current buffer. */
981 && XBUFFER (tem1) == current_buffer)))
2483cf58
GM
982 Fset_window_point (tem, make_number (PT));
983
4ad8681a 984 UNGCPRO;
35692fe0
JB
985 return Qnil;
986}
987
988DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
7ee72033 989 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
a1f17501
PJ
990Executes BODY just like `progn'.
991The values of point, mark and the current buffer are restored
992even in case of abnormal exit (throw or error).
993The state of activation of the mark is also restored.
994
995This construct does not save `deactivate-mark', and therefore
996functions that change the buffer will still cause deactivation
997of the mark at the end of the command. To prevent that, bind
33c2d29f
MB
998`deactivate-mark' with `let'.
999
7450fd36
SM
1000If you only want to save the current buffer but not point nor mark,
1001then just use `save-current-buffer', or even `with-current-buffer'.
1002
33c2d29f 1003usage: (save-excursion &rest BODY) */)
7ee72033 1004 (args)
35692fe0
JB
1005 Lisp_Object args;
1006{
1007 register Lisp_Object val;
aed13378 1008 int count = SPECPDL_INDEX ();
35692fe0
JB
1009
1010 record_unwind_protect (save_excursion_restore, save_excursion_save ());
4bc8c7d2
RS
1011
1012 val = Fprogn (args);
1013 return unbind_to (count, val);
1014}
1015
1016DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
7ee72033 1017 doc: /* Save the current buffer; execute BODY; restore the current buffer.
33c2d29f
MB
1018Executes BODY just like `progn'.
1019usage: (save-current-buffer &rest BODY) */)
7ee72033 1020 (args)
4bc8c7d2
RS
1021 Lisp_Object args;
1022{
acb7cc89 1023 Lisp_Object val;
aed13378 1024 int count = SPECPDL_INDEX ();
4bc8c7d2 1025
cb5e5f74 1026 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
4bc8c7d2 1027
35692fe0
JB
1028 val = Fprogn (args);
1029 return unbind_to (count, val);
1030}
1031\f
95dccf75 1032DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
7ee72033
MB
1033 doc: /* Return the number of characters in the current buffer.
1034If BUFFER, return the number of characters in that buffer instead. */)
1035 (buffer)
95dccf75 1036 Lisp_Object buffer;
35692fe0 1037{
95dccf75
RS
1038 if (NILP (buffer))
1039 return make_number (Z - BEG);
02050596
RS
1040 else
1041 {
b7826503 1042 CHECK_BUFFER (buffer);
02050596
RS
1043 return make_number (BUF_Z (XBUFFER (buffer))
1044 - BUF_BEG (XBUFFER (buffer)));
1045 }
35692fe0
JB
1046}
1047
1048DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
7ee72033
MB
1049 doc: /* Return the minimum permissible value of point in the current buffer.
1050This is 1, unless narrowing (a buffer restriction) is in effect. */)
1051 ()
35692fe0
JB
1052{
1053 Lisp_Object temp;
55561c63 1054 XSETFASTINT (temp, BEGV);
35692fe0
JB
1055 return temp;
1056}
1057
1058DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
7ee72033
MB
1059 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1060This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1061 ()
35692fe0 1062{
ec1c14f6 1063 return buildmark (BEGV, BEGV_BYTE);
35692fe0
JB
1064}
1065
1066DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
7ee72033 1067 doc: /* Return the maximum permissible value of point in the current buffer.
a1f17501 1068This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
7ee72033
MB
1069is in effect, in which case it is less. */)
1070 ()
35692fe0
JB
1071{
1072 Lisp_Object temp;
55561c63 1073 XSETFASTINT (temp, ZV);
35692fe0
JB
1074 return temp;
1075}
1076
1077DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
7ee72033 1078 doc: /* Return a marker to the maximum permissible value of point in this buffer.
a1f17501 1079This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
7ee72033
MB
1080is in effect, in which case it is less. */)
1081 ()
35692fe0 1082{
ec1c14f6 1083 return buildmark (ZV, ZV_BYTE);
35692fe0
JB
1084}
1085
c86212b9 1086DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
7ee72033
MB
1087 doc: /* Return the position of the gap, in the current buffer.
1088See also `gap-size'. */)
1089 ()
c86212b9
RS
1090{
1091 Lisp_Object temp;
1092 XSETFASTINT (temp, GPT);
1093 return temp;
1094}
1095
1096DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
7ee72033
MB
1097 doc: /* Return the size of the current buffer's gap.
1098See also `gap-position'. */)
1099 ()
c86212b9
RS
1100{
1101 Lisp_Object temp;
1102 XSETFASTINT (temp, GAP_SIZE);
1103 return temp;
1104}
1105
7df74da6 1106DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
7ee72033
MB
1107 doc: /* Return the byte position for character position POSITION.
1108If POSITION is out of range, the value is nil. */)
1109 (position)
80e01f8d 1110 Lisp_Object position;
7df74da6 1111{
b7826503 1112 CHECK_NUMBER_COERCE_MARKER (position);
fcf9683e
KH
1113 if (XINT (position) < BEG || XINT (position) > Z)
1114 return Qnil;
fa8a5a15 1115 return make_number (CHAR_TO_BYTE (XINT (position)));
7df74da6 1116}
3ab0732d
RS
1117
1118DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
7ee72033
MB
1119 doc: /* Return the character position for byte position BYTEPOS.
1120If BYTEPOS is out of range, the value is nil. */)
1121 (bytepos)
3ab0732d
RS
1122 Lisp_Object bytepos;
1123{
b7826503 1124 CHECK_NUMBER (bytepos);
fcf9683e
KH
1125 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1126 return Qnil;
3ab0732d
RS
1127 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1128}
7df74da6 1129\f
850a8179 1130DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
7ee72033
MB
1131 doc: /* Return the character following point, as a number.
1132At the end of the buffer or accessible region, return 0. */)
1133 ()
35692fe0
JB
1134{
1135 Lisp_Object temp;
6ec8bbd2 1136 if (PT >= ZV)
55561c63 1137 XSETFASTINT (temp, 0);
850a8179 1138 else
ec1c14f6 1139 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
35692fe0
JB
1140 return temp;
1141}
1142
850a8179 1143DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
7ee72033
MB
1144 doc: /* Return the character preceding point, as a number.
1145At the beginning of the buffer or accessible region, return 0. */)
1146 ()
35692fe0
JB
1147{
1148 Lisp_Object temp;
6ec8bbd2 1149 if (PT <= BEGV)
55561c63 1150 XSETFASTINT (temp, 0);
fb8106e8
KH
1151 else if (!NILP (current_buffer->enable_multibyte_characters))
1152 {
ec1c14f6 1153 int pos = PT_BYTE;
fb8106e8
KH
1154 DEC_POS (pos);
1155 XSETFASTINT (temp, FETCH_CHAR (pos));
1156 }
35692fe0 1157 else
ec1c14f6 1158 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
35692fe0
JB
1159 return temp;
1160}
1161
1162DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
7ee72033
MB
1163 doc: /* Return t if point is at the beginning of the buffer.
1164If the buffer is narrowed, this means the beginning of the narrowed part. */)
1165 ()
35692fe0 1166{
6ec8bbd2 1167 if (PT == BEGV)
35692fe0
JB
1168 return Qt;
1169 return Qnil;
1170}
1171
1172DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
7ee72033
MB
1173 doc: /* Return t if point is at the end of the buffer.
1174If the buffer is narrowed, this means the end of the narrowed part. */)
1175 ()
35692fe0 1176{
6ec8bbd2 1177 if (PT == ZV)
35692fe0
JB
1178 return Qt;
1179 return Qnil;
1180}
1181
1182DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
7ee72033
MB
1183 doc: /* Return t if point is at the beginning of a line. */)
1184 ()
35692fe0 1185{
ec1c14f6 1186 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
35692fe0
JB
1187 return Qt;
1188 return Qnil;
1189}
1190
1191DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
7ee72033
MB
1192 doc: /* Return t if point is at the end of a line.
1193`End of a line' includes point being at the end of the buffer. */)
1194 ()
35692fe0 1195{
ec1c14f6 1196 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
35692fe0
JB
1197 return Qt;
1198 return Qnil;
1199}
1200
fa1d3816 1201DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
7ee72033 1202 doc: /* Return character in current buffer at position POS.
f555f8cf 1203POS is an integer or a marker and defaults to point.
7ee72033
MB
1204If POS is out of range, the value is nil. */)
1205 (pos)
35692fe0
JB
1206 Lisp_Object pos;
1207{
ec1c14f6 1208 register int pos_byte;
35692fe0 1209
fa1d3816 1210 if (NILP (pos))
39a4c932
RS
1211 {
1212 pos_byte = PT_BYTE;
3c52e568 1213 XSETFASTINT (pos, PT);
39a4c932
RS
1214 }
1215
1216 if (MARKERP (pos))
85cac557
RS
1217 {
1218 pos_byte = marker_byte_position (pos);
1219 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1220 return Qnil;
1221 }
fa1d3816
RS
1222 else
1223 {
b7826503 1224 CHECK_NUMBER_COERCE_MARKER (pos);
b98ef0dc 1225 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
85cac557 1226 return Qnil;
34a7a267 1227
ec1c14f6 1228 pos_byte = CHAR_TO_BYTE (XINT (pos));
fa1d3816 1229 }
35692fe0 1230
ec1c14f6 1231 return make_number (FETCH_CHAR (pos_byte));
35692fe0 1232}
fb8106e8 1233
fa1d3816 1234DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
7ee72033 1235 doc: /* Return character in current buffer preceding position POS.
f555f8cf 1236POS is an integer or a marker and defaults to point.
7ee72033
MB
1237If POS is out of range, the value is nil. */)
1238 (pos)
fb8106e8
KH
1239 Lisp_Object pos;
1240{
1241 register Lisp_Object val;
ec1c14f6 1242 register int pos_byte;
fb8106e8 1243
fa1d3816 1244 if (NILP (pos))
39a4c932
RS
1245 {
1246 pos_byte = PT_BYTE;
3c52e568 1247 XSETFASTINT (pos, PT);
39a4c932
RS
1248 }
1249
1250 if (MARKERP (pos))
85cac557
RS
1251 {
1252 pos_byte = marker_byte_position (pos);
1253
1254 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1255 return Qnil;
1256 }
fa1d3816
RS
1257 else
1258 {
b7826503 1259 CHECK_NUMBER_COERCE_MARKER (pos);
fb8106e8 1260
b98ef0dc 1261 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
85cac557
RS
1262 return Qnil;
1263
ec1c14f6 1264 pos_byte = CHAR_TO_BYTE (XINT (pos));
fa1d3816 1265 }
fb8106e8
KH
1266
1267 if (!NILP (current_buffer->enable_multibyte_characters))
1268 {
ec1c14f6
RS
1269 DEC_POS (pos_byte);
1270 XSETFASTINT (val, FETCH_CHAR (pos_byte));
fb8106e8
KH
1271 }
1272 else
1273 {
ec1c14f6
RS
1274 pos_byte--;
1275 XSETFASTINT (val, FETCH_BYTE (pos_byte));
fb8106e8
KH
1276 }
1277 return val;
1278}
35692fe0 1279\f
87485d6f 1280DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
7ee72033 1281 doc: /* Return the name under which the user logged in, as a string.
a1f17501 1282This is based on the effective uid, not the real uid.
412f1fab 1283Also, if the environment variables LOGNAME or USER are set,
a1f17501
PJ
1284that determines the value of this function.
1285
7b1c38a4
EZ
1286If optional argument UID is an integer or a float, return the login name
1287of the user with that uid, or nil if there is no such user. */)
7ee72033 1288 (uid)
87485d6f 1289 Lisp_Object uid;
35692fe0 1290{
87485d6f 1291 struct passwd *pw;
7b1c38a4 1292 uid_t id;
87485d6f 1293
f8a0e364
RS
1294 /* Set up the user name info if we didn't do it before.
1295 (That can happen if Emacs is dumpable
1296 but you decide to run `temacs -l loadup' and not dump. */
35b34f72 1297 if (INTEGERP (Vuser_login_name))
f8a0e364 1298 init_editfns ();
87485d6f
MW
1299
1300 if (NILP (uid))
35b34f72 1301 return Vuser_login_name;
87485d6f 1302
7b1c38a4 1303 id = (uid_t)XFLOATINT (uid);
b91834c3 1304 BLOCK_INPUT;
7b1c38a4 1305 pw = (struct passwd *) getpwuid (id);
b91834c3 1306 UNBLOCK_INPUT;
87485d6f 1307 return (pw ? build_string (pw->pw_name) : Qnil);
35692fe0
JB
1308}
1309
1310DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
deb8e082 1311 0, 0, 0,
7ee72033 1312 doc: /* Return the name of the user's real uid, as a string.
a1f17501 1313This ignores the environment variables LOGNAME and USER, so it differs from
7ee72033
MB
1314`user-login-name' when running under `su'. */)
1315 ()
35692fe0 1316{
f8a0e364
RS
1317 /* Set up the user name info if we didn't do it before.
1318 (That can happen if Emacs is dumpable
1319 but you decide to run `temacs -l loadup' and not dump. */
35b34f72 1320 if (INTEGERP (Vuser_login_name))
f8a0e364 1321 init_editfns ();
35b34f72 1322 return Vuser_real_login_name;
35692fe0
JB
1323}
1324
1325DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
7ee72033 1326 doc: /* Return the effective uid of Emacs.
e00553bf 1327Value is an integer or a float, depending on the value. */)
7ee72033 1328 ()
35692fe0 1329{
3aef3c0a
EZ
1330 /* Assignment to EMACS_INT stops GCC whining about limited range of
1331 data type. */
1332 EMACS_INT euid = geteuid ();
e00553bf
EZ
1333
1334 /* Make sure we don't produce a negative UID due to signed integer
1335 overflow. */
1336 if (euid < 0)
1337 return make_float ((double)geteuid ());
3aef3c0a 1338 return make_fixnum_or_float (euid);
35692fe0
JB
1339}
1340
1341DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
7ee72033 1342 doc: /* Return the real uid of Emacs.
e00553bf 1343Value is an integer or a float, depending on the value. */)
7ee72033 1344 ()
35692fe0 1345{
3aef3c0a
EZ
1346 /* Assignment to EMACS_INT stops GCC whining about limited range of
1347 data type. */
1348 EMACS_INT uid = getuid ();
e00553bf
EZ
1349
1350 /* Make sure we don't produce a negative UID due to signed integer
1351 overflow. */
1352 if (uid < 0)
1353 return make_float ((double)getuid ());
3aef3c0a 1354 return make_fixnum_or_float (uid);
35692fe0
JB
1355}
1356
c9ed721d 1357DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
7ee72033 1358 doc: /* Return the full name of the user logged in, as a string.
a1f17501
PJ
1359If the full name corresponding to Emacs's userid is not known,
1360return "unknown".
1361
1362If optional argument UID is an integer or float, return the full name
1363of the user with that uid, or nil if there is no such user.
1364If UID is a string, return the full name of the user with that login
7ee72033
MB
1365name, or nil if there is no such user. */)
1366 (uid)
c9ed721d 1367 Lisp_Object uid;
35692fe0 1368{
c9ed721d 1369 struct passwd *pw;
b0e92acd 1370 register unsigned char *p, *q;
3415b0e9 1371 Lisp_Object full;
c9ed721d
RS
1372
1373 if (NILP (uid))
34a7a267 1374 return Vuser_full_name;
3415b0e9 1375 else if (NUMBERP (uid))
b91834c3
YM
1376 {
1377 BLOCK_INPUT;
1378 pw = (struct passwd *) getpwuid ((uid_t) XFLOATINT (uid));
1379 UNBLOCK_INPUT;
1380 }
34a7a267 1381 else if (STRINGP (uid))
b91834c3
YM
1382 {
1383 BLOCK_INPUT;
1384 pw = (struct passwd *) getpwnam (SDATA (uid));
1385 UNBLOCK_INPUT;
1386 }
3415b0e9
RS
1387 else
1388 error ("Invalid UID specification");
c9ed721d 1389
3415b0e9 1390 if (!pw)
3347526c 1391 return Qnil;
34a7a267 1392
d823c26b 1393 p = (unsigned char *) USER_FULL_NAME;
3415b0e9
RS
1394 /* Chop off everything after the first comma. */
1395 q = (unsigned char *) index (p, ',');
1396 full = make_string (p, q ? q - p : strlen (p));
34a7a267 1397
3415b0e9 1398#ifdef AMPERSAND_FULL_NAME
d5db4077 1399 p = SDATA (full);
3415b0e9
RS
1400 q = (unsigned char *) index (p, '&');
1401 /* Substitute the login name for the &, upcasing the first character. */
1402 if (q)
1403 {
b0e92acd 1404 register unsigned char *r;
3415b0e9
RS
1405 Lisp_Object login;
1406
1407 login = Fuser_login_name (make_number (pw->pw_uid));
d5db4077 1408 r = (unsigned char *) alloca (strlen (p) + SCHARS (login) + 1);
3415b0e9
RS
1409 bcopy (p, r, q - p);
1410 r[q - p] = 0;
d5db4077 1411 strcat (r, SDATA (login));
3415b0e9
RS
1412 r[q - p] = UPCASE (r[q - p]);
1413 strcat (r, q + 1);
1414 full = build_string (r);
1415 }
1416#endif /* AMPERSAND_FULL_NAME */
1417
1418 return full;
35692fe0
JB
1419}
1420
1421DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1a7e0117 1422 doc: /* Return the host name of the machine you are running on, as a string. */)
7ee72033 1423 ()
35692fe0
JB
1424{
1425 return Vsystem_name;
1426}
1427
ac988277 1428/* For the benefit of callers who don't want to include lisp.h */
acb7cc89 1429
ac988277
KH
1430char *
1431get_system_name ()
1432{
3d976a9a 1433 if (STRINGP (Vsystem_name))
d5db4077 1434 return (char *) SDATA (Vsystem_name);
3d976a9a
RS
1435 else
1436 return "";
ac988277
KH
1437}
1438
a15252fd
ST
1439char *
1440get_operating_system_release()
1441{
1442 if (STRINGP (Voperating_system_release))
1443 return (char *) SDATA (Voperating_system_release);
1444 else
1445 return "";
1446}
1447
7fd233b3 1448DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
7ee72033
MB
1449 doc: /* Return the process ID of Emacs, as an integer. */)
1450 ()
7fd233b3
RS
1451{
1452 return make_number (getpid ());
1453}
1454
d940e0e4 1455DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
7ee72033 1456 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
a1f17501
PJ
1457The time is returned as a list of three integers. The first has the
1458most significant 16 bits of the seconds, while the second has the
1459least significant 16 bits. The third integer gives the microsecond
1460count.
1461
1462The microsecond count is zero on systems that do not provide
7ee72033
MB
1463resolution finer than a second. */)
1464 ()
d940e0e4 1465{
956ace37 1466 EMACS_TIME t;
956ace37
JB
1467
1468 EMACS_GET_TIME (t);
799734b0
KS
1469 return list3 (make_number ((EMACS_SECS (t) >> 16) & 0xffff),
1470 make_number ((EMACS_SECS (t) >> 0) & 0xffff),
1471 make_number (EMACS_USECS (t)));
d940e0e4 1472}
4211ee7d
EZ
1473
1474DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1475 0, 0, 0,
1476 doc: /* Return the current run time used by Emacs.
1477The time is returned as a list of three integers. The first has the
1478most significant 16 bits of the seconds, while the second has the
1479least significant 16 bits. The third integer gives the microsecond
1480count.
1481
9671c13a
JB
1482On systems that can't determine the run time, `get-internal-run-time'
1483does the same thing as `current-time'. The microsecond count is zero
1484on systems that do not provide resolution finer than a second. */)
4211ee7d
EZ
1485 ()
1486{
1487#ifdef HAVE_GETRUSAGE
1488 struct rusage usage;
4211ee7d
EZ
1489 int secs, usecs;
1490
1491 if (getrusage (RUSAGE_SELF, &usage) < 0)
1492 /* This shouldn't happen. What action is appropriate? */
8a0ff744 1493 xsignal0 (Qerror);
4211ee7d
EZ
1494
1495 /* Sum up user time and system time. */
1496 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1497 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1498 if (usecs >= 1000000)
1499 {
1500 usecs -= 1000000;
1501 secs++;
1502 }
1503
799734b0
KS
1504 return list3 (make_number ((secs >> 16) & 0xffff),
1505 make_number ((secs >> 0) & 0xffff),
1506 make_number (usecs));
c433c134 1507#else /* ! HAVE_GETRUSAGE */
43db14bb 1508#ifdef WINDOWSNT
c433c134
JR
1509 return w32_get_internal_run_time ();
1510#else /* ! WINDOWSNT */
4211ee7d 1511 return Fcurrent_time ();
c433c134
JR
1512#endif /* WINDOWSNT */
1513#endif /* HAVE_GETRUSAGE */
4211ee7d 1514}
d940e0e4
JB
1515\f
1516
5c5718b6 1517int
34a7a267 1518lisp_time_argument (specified_time, result, usec)
e3120ab5
JB
1519 Lisp_Object specified_time;
1520 time_t *result;
34a7a267 1521 int *usec;
e3120ab5
JB
1522{
1523 if (NILP (specified_time))
34a7a267
SS
1524 {
1525 if (usec)
1526 {
1527 EMACS_TIME t;
1528
c0261b5e 1529 EMACS_GET_TIME (t);
34a7a267
SS
1530 *usec = EMACS_USECS (t);
1531 *result = EMACS_SECS (t);
1532 return 1;
1533 }
1534 else
1535 return time (result) != -1;
1536 }
e3120ab5
JB
1537 else
1538 {
1539 Lisp_Object high, low;
1540 high = Fcar (specified_time);
b7826503 1541 CHECK_NUMBER (high);
e3120ab5 1542 low = Fcdr (specified_time);
ae683129 1543 if (CONSP (low))
34a7a267
SS
1544 {
1545 if (usec)
1546 {
1547 Lisp_Object usec_l = Fcdr (low);
1548 if (CONSP (usec_l))
1549 usec_l = Fcar (usec_l);
1550 if (NILP (usec_l))
1551 *usec = 0;
1552 else
1553 {
b7826503 1554 CHECK_NUMBER (usec_l);
34a7a267
SS
1555 *usec = XINT (usec_l);
1556 }
1557 }
1558 low = Fcar (low);
1559 }
1560 else if (usec)
1561 *usec = 0;
b7826503 1562 CHECK_NUMBER (low);
e3120ab5
JB
1563 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1564 return *result >> 16 == XINT (high);
1565 }
1566}
1567
34a7a267 1568DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
7ee72033 1569 doc: /* Return the current time, as a float number of seconds since the epoch.
412f1fab 1570If SPECIFIED-TIME is given, it is the time to convert to float
5668fbb8 1571instead of the current time. The argument should have the form
c6493cdd 1572(HIGH LOW) or (HIGH LOW USEC). Thus, you can use times obtained from
5668fbb8
LT
1573`current-time' and from `file-attributes'. SPECIFIED-TIME can also
1574have the form (HIGH . LOW), but this is considered obsolete.
a1f17501
PJ
1575
1576WARNING: Since the result is floating point, it may not be exact.
d427a9fa
EZ
1577If precise time stamps are required, use either `current-time',
1578or (if you need time as a string) `format-time-string'. */)
7ee72033 1579 (specified_time)
34a7a267
SS
1580 Lisp_Object specified_time;
1581{
1582 time_t sec;
1583 int usec;
1584
1585 if (! lisp_time_argument (specified_time, &sec, &usec))
1586 error ("Invalid time specification");
1587
26fad6e5 1588 return make_float ((sec * 1e6 + usec) / 1e6);
34a7a267
SS
1589}
1590
70ebbe5f
PE
1591/* Write information into buffer S of size MAXSIZE, according to the
1592 FORMAT of length FORMAT_LEN, using time information taken from *TP.
68c45bf0 1593 Default to Universal Time if UT is nonzero, local time otherwise.
70ebbe5f
PE
1594 Return the number of bytes written, not including the terminating
1595 '\0'. If S is NULL, nothing will be written anywhere; so to
1596 determine how many bytes would be written, use NULL for S and
1597 ((size_t) -1) for MAXSIZE.
1598
68c45bf0 1599 This function behaves like emacs_strftimeu, except it allows null
70ebbe5f
PE
1600 bytes in FORMAT. */
1601static size_t
68c45bf0 1602emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
70ebbe5f
PE
1603 char *s;
1604 size_t maxsize;
1605 const char *format;
1606 size_t format_len;
1607 const struct tm *tp;
68c45bf0 1608 int ut;
70ebbe5f
PE
1609{
1610 size_t total = 0;
1611
be09e6e6
PE
1612 /* Loop through all the null-terminated strings in the format
1613 argument. Normally there's just one null-terminated string, but
1614 there can be arbitrarily many, concatenated together, if the
68c45bf0 1615 format contains '\0' bytes. emacs_strftimeu stops at the first
be09e6e6 1616 '\0' byte so we must invoke it separately for each such string. */
70ebbe5f
PE
1617 for (;;)
1618 {
1619 size_t len;
1620 size_t result;
1621
1622 if (s)
1623 s[0] = '\1';
1624
68c45bf0 1625 result = emacs_strftimeu (s, maxsize, format, tp, ut);
70ebbe5f
PE
1626
1627 if (s)
1628 {
1629 if (result == 0 && s[0] != '\0')
1630 return 0;
1631 s += result + 1;
1632 }
1633
1634 maxsize -= result + 1;
1635 total += result;
1636 len = strlen (format);
1637 if (len == format_len)
1638 return total;
1639 total++;
1640 format += len + 1;
1641 format_len -= len + 1;
1642 }
1643}
1644
3efcc98a 1645DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
7ee72033 1646 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
5668fbb8
LT
1647TIME is specified as (HIGH LOW . IGNORED), as returned by
1648`current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1649is also still accepted.
a1f17501
PJ
1650The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1651as Universal Time; nil means describe TIME in the local time zone.
1652The value is a copy of FORMAT-STRING, but with certain constructs replaced
1653by text that describes the specified date and time in TIME:
1654
1655%Y is the year, %y within the century, %C the century.
1656%G is the year corresponding to the ISO week, %g within the century.
1657%m is the numeric month.
1658%b and %h are the locale's abbreviated month name, %B the full name.
1659%d is the day of the month, zero-padded, %e is blank-padded.
1660%u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1661%a is the locale's abbreviated name of the day of week, %A the full name.
1662%U is the week number starting on Sunday, %W starting on Monday,
1663 %V according to ISO 8601.
1664%j is the day of the year.
1665
1666%H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1667 only blank-padded, %l is like %I blank-padded.
1668%p is the locale's equivalent of either AM or PM.
1669%M is the minute.
1670%S is the second.
1671%Z is the time zone name, %z is the numeric form.
1672%s is the number of seconds since 1970-01-01 00:00:00 +0000.
1673
1674%c is the locale's date and time format.
1675%x is the locale's "preferred" date format.
1676%D is like "%m/%d/%y".
1677
1678%R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1679%X is the locale's "preferred" time format.
1680
1681Finally, %n is a newline, %t is a tab, %% is a literal %.
1682
1683Certain flags and modifiers are available with some format controls.
1684The flags are `_', `-', `^' and `#'. For certain characters X,
1685%_X is like %X, but padded with blanks; %-X is like %X,
a67a233b
MR
1686but without padding. %^X is like %X, but with all textual
1687characters up-cased; %#X is like %X, but with letter-case of
a1f17501
PJ
1688all textual characters reversed.
1689%NX (where N stands for an integer) is like %X,
1690but takes up at least N (a number) positions.
1691The modifiers are `E' and `O'. For certain characters X,
1692%EX is a locale's alternative version of %X;
1693%OX is like %X, but uses the locale's number symbols.
1694
7ee72033
MB
1695For example, to produce full ISO 8601 format, use "%Y-%m-%dT%T%z". */)
1696 (format_string, time, universal)
b48382a0 1697 Lisp_Object format_string, time, universal;
a82d387c
RS
1698{
1699 time_t value;
1700 int size;
177ea5f1 1701 struct tm *tm;
68c45bf0 1702 int ut = ! NILP (universal);
a82d387c 1703
b7826503 1704 CHECK_STRING (format_string);
a82d387c 1705
34a7a267 1706 if (! lisp_time_argument (time, &value, NULL))
a82d387c
RS
1707 error ("Invalid time specification");
1708
68c45bf0
PE
1709 format_string = code_convert_string_norecord (format_string,
1710 Vlocale_coding_system, 1);
1711
a82d387c 1712 /* This is probably enough. */
d5db4077 1713 size = SBYTES (format_string) * 6 + 50;
a82d387c 1714
bcda42c8 1715 BLOCK_INPUT;
68c45bf0 1716 tm = ut ? gmtime (&value) : localtime (&value);
bcda42c8 1717 UNBLOCK_INPUT;
177ea5f1
PE
1718 if (! tm)
1719 error ("Specified time is not representable");
1720
ca9c0567 1721 synchronize_system_time_locale ();
68c45bf0 1722
a82d387c
RS
1723 while (1)
1724 {
b48382a0
RS
1725 char *buf = (char *) alloca (size + 1);
1726 int result;
1727
bfbcc5ee 1728 buf[0] = '\1';
bcda42c8 1729 BLOCK_INPUT;
d5db4077
KR
1730 result = emacs_memftimeu (buf, size, SDATA (format_string),
1731 SBYTES (format_string),
68c45bf0 1732 tm, ut);
bcda42c8 1733 UNBLOCK_INPUT;
bfbcc5ee 1734 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
04e28558 1735 return code_convert_string_norecord (make_unibyte_string (buf, result),
68c45bf0 1736 Vlocale_coding_system, 0);
b48382a0
RS
1737
1738 /* If buffer was too small, make it bigger and try again. */
bcda42c8 1739 BLOCK_INPUT;
68c45bf0 1740 result = emacs_memftimeu (NULL, (size_t) -1,
d5db4077
KR
1741 SDATA (format_string),
1742 SBYTES (format_string),
68c45bf0 1743 tm, ut);
bcda42c8 1744 UNBLOCK_INPUT;
b48382a0 1745 size = result + 1;
a82d387c
RS
1746 }
1747}
1748
4691c06d 1749DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
7ee72033 1750 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
5668fbb8 1751The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
9671c13a 1752as from `current-time' and `file-attributes', or nil to use the
5668fbb8
LT
1753current time. The obsolete form (HIGH . LOW) is also still accepted.
1754The list has the following nine members: SEC is an integer between 0
1755and 60; SEC is 60 for a leap second, which only some operating systems
1756support. MINUTE is an integer between 0 and 59. HOUR is an integer
1757between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
1758integer between 1 and 12. YEAR is an integer indicating the
1759four-digit year. DOW is the day of week, an integer between 0 and 6,
f1767e2b 1760where 0 is Sunday. DST is t if daylight saving time is in effect,
5668fbb8
LT
1761otherwise nil. ZONE is an integer indicating the number of seconds
1762east of Greenwich. (Note that Common Lisp has different meanings for
1763DOW and ZONE.) */)
7ee72033 1764 (specified_time)
4691c06d
RS
1765 Lisp_Object specified_time;
1766{
1767 time_t time_spec;
3c887943 1768 struct tm save_tm;
4691c06d
RS
1769 struct tm *decoded_time;
1770 Lisp_Object list_args[9];
34a7a267
SS
1771
1772 if (! lisp_time_argument (specified_time, &time_spec, NULL))
4691c06d
RS
1773 error ("Invalid time specification");
1774
bcda42c8 1775 BLOCK_INPUT;
4691c06d 1776 decoded_time = localtime (&time_spec);
bcda42c8 1777 UNBLOCK_INPUT;
177ea5f1
PE
1778 if (! decoded_time)
1779 error ("Specified time is not representable");
3c887943
KH
1780 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1781 XSETFASTINT (list_args[1], decoded_time->tm_min);
1782 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1783 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1784 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
71c3f28f
EZ
1785 /* On 64-bit machines an int is narrower than EMACS_INT, thus the
1786 cast below avoids overflow in int arithmetics. */
aac18aa4 1787 XSETINT (list_args[5], TM_YEAR_BASE + (EMACS_INT) decoded_time->tm_year);
3c887943 1788 XSETFASTINT (list_args[6], decoded_time->tm_wday);
4691c06d 1789 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
3c887943
KH
1790
1791 /* Make a copy, in case gmtime modifies the struct. */
1792 save_tm = *decoded_time;
bcda42c8 1793 BLOCK_INPUT;
3c887943 1794 decoded_time = gmtime (&time_spec);
bcda42c8 1795 UNBLOCK_INPUT;
3c887943
KH
1796 if (decoded_time == 0)
1797 list_args[8] = Qnil;
1798 else
94751666 1799 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
4691c06d
RS
1800 return Flist (9, list_args);
1801}
1802
6ee9061c 1803DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
7ee72033 1804 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
a1f17501
PJ
1805This is the reverse operation of `decode-time', which see.
1806ZONE defaults to the current time zone rule. This can
1807be a string or t (as from `set-time-zone-rule'), or it can be a list
b57c2708 1808\(as from `current-time-zone') or an integer (as from `decode-time')
9c279ddf 1809applied without consideration for daylight saving time.
a1f17501
PJ
1810
1811You can pass more than 7 arguments; then the first six arguments
1812are used as SECOND through YEAR, and the *last* argument is used as ZONE.
1813The intervening arguments are ignored.
1814This feature lets (apply 'encode-time (decode-time ...)) work.
1815
412f1fab 1816Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
a1f17501
PJ
1817for example, a DAY of 0 means the day preceding the given month.
1818Year numbers less than 100 are treated just like other year numbers.
4bfbe194
MB
1819If you want them to stand for years in this century, you must do that yourself.
1820
f555f8cf
KH
1821Years before 1970 are not guaranteed to work. On some systems,
1822year values as low as 1901 do work.
1823
4bfbe194 1824usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
7ee72033 1825 (nargs, args)
6ee9061c
RS
1826 int nargs;
1827 register Lisp_Object *args;
cce7b8a0 1828{
1b8fa736 1829 time_t time;
c59b5089 1830 struct tm tm;
60653898 1831 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
6ee9061c 1832
b7826503
PJ
1833 CHECK_NUMBER (args[0]); /* second */
1834 CHECK_NUMBER (args[1]); /* minute */
1835 CHECK_NUMBER (args[2]); /* hour */
1836 CHECK_NUMBER (args[3]); /* day */
1837 CHECK_NUMBER (args[4]); /* month */
1838 CHECK_NUMBER (args[5]); /* year */
6ee9061c
RS
1839
1840 tm.tm_sec = XINT (args[0]);
1841 tm.tm_min = XINT (args[1]);
1842 tm.tm_hour = XINT (args[2]);
1843 tm.tm_mday = XINT (args[3]);
1844 tm.tm_mon = XINT (args[4]) - 1;
aac18aa4 1845 tm.tm_year = XINT (args[5]) - TM_YEAR_BASE;
c59b5089
PE
1846 tm.tm_isdst = -1;
1847
1848 if (CONSP (zone))
1849 zone = Fcar (zone);
1b8fa736 1850 if (NILP (zone))
bcda42c8
YM
1851 {
1852 BLOCK_INPUT;
1853 time = mktime (&tm);
1854 UNBLOCK_INPUT;
1855 }
c59b5089 1856 else
1b8fa736 1857 {
c59b5089
PE
1858 char tzbuf[100];
1859 char *tzstring;
1860 char **oldenv = environ, **newenv;
34a7a267 1861
2e34157c 1862 if (EQ (zone, Qt))
085e9fcb
EN
1863 tzstring = "UTC0";
1864 else if (STRINGP (zone))
d5db4077 1865 tzstring = (char *) SDATA (zone);
c59b5089 1866 else if (INTEGERP (zone))
1b8fa736 1867 {
1ea40aa2 1868 int abszone = eabs (XINT (zone));
c59b5089
PE
1869 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1870 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1871 tzstring = tzbuf;
1b8fa736 1872 }
c59b5089
PE
1873 else
1874 error ("Invalid time zone specification");
1875
34a7a267 1876 /* Set TZ before calling mktime; merely adjusting mktime's returned
c59b5089
PE
1877 value doesn't suffice, since that would mishandle leap seconds. */
1878 set_time_zone_rule (tzstring);
1879
bcda42c8 1880 BLOCK_INPUT;
c59b5089 1881 time = mktime (&tm);
bcda42c8 1882 UNBLOCK_INPUT;
c59b5089
PE
1883
1884 /* Restore TZ to previous value. */
1885 newenv = environ;
1886 environ = oldenv;
c0efcacf 1887 xfree (newenv);
c59b5089
PE
1888#ifdef LOCALTIME_CACHE
1889 tzset ();
1890#endif
1b8fa736 1891 }
1b8fa736 1892
c59b5089
PE
1893 if (time == (time_t) -1)
1894 error ("Specified time is not representable");
1895
1896 return make_time (time);
cce7b8a0
RS
1897}
1898
2148f2b4 1899DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
7ee72033 1900 doc: /* Return the current time, as a human-readable string.
a1f17501 1901Programs can use this function to decode a time,
d65b4235
PE
1902since the number of columns in each field is fixed
1903if the year is in the range 1000-9999.
a1f17501
PJ
1904The format is `Sun Sep 16 01:03:52 1973'.
1905However, see also the functions `decode-time' and `format-time-string'
1906which provide a much more powerful and general facility.
1907
5668fbb8
LT
1908If SPECIFIED-TIME is given, it is a time to format instead of the
1909current time. The argument should have the form (HIGH LOW . IGNORED).
1910Thus, you can use times obtained from `current-time' and from
1911`file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
1912but this is considered obsolete. */)
7ee72033 1913 (specified_time)
2148f2b4
RS
1914 Lisp_Object specified_time;
1915{
e3120ab5 1916 time_t value;
aac18aa4 1917 struct tm *tm;
2148f2b4
RS
1918 register char *tem;
1919
34a7a267 1920 if (! lisp_time_argument (specified_time, &value, NULL))
aac18aa4 1921 error ("Invalid time specification");
d65b4235
PE
1922
1923 /* Convert to a string, checking for out-of-range time stamps.
1924 Don't use 'ctime', as that might dump core if VALUE is out of
1925 range. */
bcda42c8 1926 BLOCK_INPUT;
aac18aa4 1927 tm = localtime (&value);
bcda42c8 1928 UNBLOCK_INPUT;
d65b4235 1929 if (! (tm && TM_YEAR_IN_ASCTIME_RANGE (tm->tm_year) && (tem = asctime (tm))))
aac18aa4 1930 error ("Specified time is not representable");
35692fe0 1931
d65b4235
PE
1932 /* Remove the trailing newline. */
1933 tem[strlen (tem) - 1] = '\0';
35692fe0 1934
d65b4235 1935 return build_string (tem);
35692fe0 1936}
c2662aea 1937
94751666
PE
1938/* Yield A - B, measured in seconds.
1939 This function is copied from the GNU C Library. */
1940static int
1941tm_diff (a, b)
e3120ab5
JB
1942 struct tm *a, *b;
1943{
94751666
PE
1944 /* Compute intervening leap days correctly even if year is negative.
1945 Take care to avoid int overflow in leap day calculations,
1946 but it's OK to assume that A and B are close to each other. */
1947 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1948 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1949 int a100 = a4 / 25 - (a4 % 25 < 0);
1950 int b100 = b4 / 25 - (b4 % 25 < 0);
1951 int a400 = a100 >> 2;
1952 int b400 = b100 >> 2;
1953 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1954 int years = a->tm_year - b->tm_year;
1955 int days = (365 * years + intervening_leap_days
1956 + (a->tm_yday - b->tm_yday));
1957 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1958 + (a->tm_min - b->tm_min))
8e718b4e 1959 + (a->tm_sec - b->tm_sec));
e3120ab5
JB
1960}
1961
1962DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
7ee72033 1963 doc: /* Return the offset and name for the local time zone.
a1f17501
PJ
1964This returns a list of the form (OFFSET NAME).
1965OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
1966 A negative value means west of Greenwich.
1967NAME is a string giving the name of the time zone.
412f1fab 1968If SPECIFIED-TIME is given, the time zone offset is determined from it
5668fbb8
LT
1969instead of using the current time. The argument should have the form
1970(HIGH LOW . IGNORED). Thus, you can use times obtained from
1971`current-time' and from `file-attributes'. SPECIFIED-TIME can also
1972have the form (HIGH . LOW), but this is considered obsolete.
a1f17501
PJ
1973
1974Some operating systems cannot provide all this information to Emacs;
1975in this case, `current-time-zone' returns a list containing nil for
7ee72033
MB
1976the data it can't find. */)
1977 (specified_time)
e3120ab5 1978 Lisp_Object specified_time;
c2662aea 1979{
e3120ab5
JB
1980 time_t value;
1981 struct tm *t;
177ea5f1 1982 struct tm gmt;
c2662aea 1983
bcda42c8
YM
1984 if (!lisp_time_argument (specified_time, &value, NULL))
1985 t = NULL;
1986 else
1987 {
1988 BLOCK_INPUT;
1989 t = gmtime (&value);
1990 if (t)
1991 {
1992 gmt = *t;
1993 t = localtime (&value);
1994 }
1995 UNBLOCK_INPUT;
1996 }
1997
1998 if (t)
e3120ab5 1999 {
177ea5f1
PE
2000 int offset = tm_diff (t, &gmt);
2001 char *s = 0;
2002 char buf[6];
42c4c67a 2003
e3120ab5
JB
2004#ifdef HAVE_TM_ZONE
2005 if (t->tm_zone)
5fd4de15 2006 s = (char *)t->tm_zone;
a7971c39
RS
2007#else /* not HAVE_TM_ZONE */
2008#ifdef HAVE_TZNAME
2009 if (t->tm_isdst == 0 || t->tm_isdst == 1)
2010 s = tzname[t->tm_isdst];
c2662aea 2011#endif
a7971c39 2012#endif /* not HAVE_TM_ZONE */
cda0f4da 2013
e3120ab5
JB
2014 if (!s)
2015 {
2016 /* No local time zone name is available; use "+-NNNN" instead. */
00fc94d0 2017 int am = (offset < 0 ? -offset : offset) / 60;
e3120ab5
JB
2018 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
2019 s = buf;
2020 }
42c4c67a 2021
e3120ab5
JB
2022 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
2023 }
2024 else
09dbcf71 2025 return Fmake_list (make_number (2), Qnil);
c2662aea
JB
2026}
2027
260e2e2a
KH
2028/* This holds the value of `environ' produced by the previous
2029 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
2030 has never been called. */
2031static char **environbuf;
2032
a03fc5a6
JR
2033/* This holds the startup value of the TZ environment variable so it
2034 can be restored if the user calls set-time-zone-rule with a nil
2035 argument. */
2036static char *initial_tz;
2037
143cb9a9 2038DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
7ee72033 2039 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
a1f17501 2040If TZ is nil, use implementation-defined default time zone information.
7ee72033
MB
2041If TZ is t, use Universal Time. */)
2042 (tz)
143cb9a9
RS
2043 Lisp_Object tz;
2044{
143cb9a9
RS
2045 char *tzstring;
2046
a03fc5a6
JR
2047 /* When called for the first time, save the original TZ. */
2048 if (!environbuf)
2049 initial_tz = (char *) getenv ("TZ");
2050
143cb9a9 2051 if (NILP (tz))
a03fc5a6 2052 tzstring = initial_tz;
2e34157c 2053 else if (EQ (tz, Qt))
085e9fcb 2054 tzstring = "UTC0";
143cb9a9
RS
2055 else
2056 {
b7826503 2057 CHECK_STRING (tz);
d5db4077 2058 tzstring = (char *) SDATA (tz);
143cb9a9
RS
2059 }
2060
c59b5089 2061 set_time_zone_rule (tzstring);
c2cd06e6 2062 free (environbuf);
c59b5089
PE
2063 environbuf = environ;
2064
2065 return Qnil;
2066}
2067
e0bf9faf
PE
2068#ifdef LOCALTIME_CACHE
2069
2070/* These two values are known to load tz files in buggy implementations,
2071 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1155c453 2072 Their values shouldn't matter in non-buggy implementations.
34a7a267 2073 We don't use string literals for these strings,
1155c453
RS
2074 since if a string in the environment is in readonly
2075 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
2076 See Sun bugs 1113095 and 1114114, ``Timezone routines
2077 improperly modify environment''. */
2078
e0bf9faf
PE
2079static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
2080static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
2081
2082#endif
1155c453 2083
c59b5089
PE
2084/* Set the local time zone rule to TZSTRING.
2085 This allocates memory into `environ', which it is the caller's
2086 responsibility to free. */
acb7cc89 2087
a92ae0ce 2088void
c59b5089
PE
2089set_time_zone_rule (tzstring)
2090 char *tzstring;
2091{
2092 int envptrs;
2093 char **from, **to, **newenv;
2094
aafe5147 2095 /* Make the ENVIRON vector longer with room for TZSTRING. */
143cb9a9
RS
2096 for (from = environ; *from; from++)
2097 continue;
2098 envptrs = from - environ + 2;
2099 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
2100 + (tzstring ? strlen (tzstring) + 4 : 0));
aafe5147
RS
2101
2102 /* Add TZSTRING to the end of environ, as a value for TZ. */
143cb9a9
RS
2103 if (tzstring)
2104 {
2105 char *t = (char *) (to + envptrs);
2106 strcpy (t, "TZ=");
2107 strcat (t, tzstring);
2108 *to++ = t;
2109 }
2110
aafe5147
RS
2111 /* Copy the old environ vector elements into NEWENV,
2112 but don't copy the TZ variable.
2113 So we have only one definition of TZ, which came from TZSTRING. */
143cb9a9
RS
2114 for (from = environ; *from; from++)
2115 if (strncmp (*from, "TZ=", 3) != 0)
2116 *to++ = *from;
2117 *to = 0;
2118
2119 environ = newenv;
143cb9a9 2120
aafe5147
RS
2121 /* If we do have a TZSTRING, NEWENV points to the vector slot where
2122 the TZ variable is stored. If we do not have a TZSTRING,
2123 TO points to the vector slot which has the terminating null. */
2124
143cb9a9 2125#ifdef LOCALTIME_CACHE
aafe5147
RS
2126 {
2127 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
2128 "US/Pacific" that loads a tz file, then changes to a value like
2129 "XXX0" that does not load a tz file, and then changes back to
2130 its original value, the last change is (incorrectly) ignored.
2131 Also, if TZ changes twice in succession to values that do
2132 not load a tz file, tzset can dump core (see Sun bug#1225179).
2133 The following code works around these bugs. */
2134
aafe5147
RS
2135 if (tzstring)
2136 {
2137 /* Temporarily set TZ to a value that loads a tz file
2138 and that differs from tzstring. */
2139 char *tz = *newenv;
1155c453
RS
2140 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
2141 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
aafe5147
RS
2142 tzset ();
2143 *newenv = tz;
2144 }
2145 else
2146 {
2147 /* The implied tzstring is unknown, so temporarily set TZ to
2148 two different values that each load a tz file. */
1155c453 2149 *to = set_time_zone_rule_tz1;
aafe5147
RS
2150 to[1] = 0;
2151 tzset ();
1155c453 2152 *to = set_time_zone_rule_tz2;
aafe5147
RS
2153 tzset ();
2154 *to = 0;
2155 }
2156
2157 /* Now TZ has the desired value, and tzset can be invoked safely. */
2158 }
2159
143cb9a9
RS
2160 tzset ();
2161#endif
143cb9a9 2162}
35692fe0 2163\f
fb8106e8
KH
2164/* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2165 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2166 type of object is Lisp_String). INHERIT is passed to
2167 INSERT_FROM_STRING_FUNC as the last argument. */
2168
acb7cc89 2169static void
9628fed7
SM
2170general_insert_function (void (*insert_func)
2171 (const unsigned char *, EMACS_INT),
2172 void (*insert_from_string_func)
2173 (Lisp_Object, EMACS_INT, EMACS_INT,
2174 EMACS_INT, EMACS_INT, int),
2175 int inherit, int nargs, Lisp_Object *args)
fb8106e8
KH
2176{
2177 register int argnum;
2178 register Lisp_Object val;
2179
2180 for (argnum = 0; argnum < nargs; argnum++)
2181 {
2182 val = args[argnum];
1b9c91ed 2183 if (CHARACTERP (val))
fb8106e8 2184 {
d5c2c403 2185 unsigned char str[MAX_MULTIBYTE_LENGTH];
fb8106e8
KH
2186 int len;
2187
2188 if (!NILP (current_buffer->enable_multibyte_characters))
d5c2c403 2189 len = CHAR_STRING (XFASTINT (val), str);
fb8106e8 2190 else
13c148b8 2191 {
0f8ea88f 2192 str[0] = (ASCII_CHAR_P (XINT (val))
d5c2c403
KH
2193 ? XINT (val)
2194 : multibyte_char_to_unibyte (XINT (val), Qnil));
13c148b8
KH
2195 len = 1;
2196 }
fb8106e8
KH
2197 (*insert_func) (str, len);
2198 }
2199 else if (STRINGP (val))
2200 {
1f24f4fd 2201 (*insert_from_string_func) (val, 0, 0,
d5db4077
KR
2202 SCHARS (val),
2203 SBYTES (val),
1f24f4fd 2204 inherit);
fb8106e8
KH
2205 }
2206 else
b7f34213 2207 wrong_type_argument (Qchar_or_string_p, val);
fb8106e8
KH
2208 }
2209}
2210
35692fe0
JB
2211void
2212insert1 (arg)
2213 Lisp_Object arg;
2214{
2215 Finsert (1, &arg);
2216}
2217
52b14ac0
JB
2218
2219/* Callers passing one argument to Finsert need not gcpro the
2220 argument "array", since the only element of the array will
2221 not be used after calling insert or insert_from_string, so
2222 we don't care if it gets trashed. */
2223
35692fe0 2224DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
7ee72033 2225 doc: /* Insert the arguments, either strings or characters, at point.
a1f17501
PJ
2226Point and before-insertion markers move forward to end up
2227 after the inserted text.
2228Any other markers at the point of insertion remain before the text.
2229
2230If the current buffer is multibyte, unibyte strings are converted
72bb55c6 2231to multibyte for insertion (see `string-make-multibyte').
a1f17501 2232If the current buffer is unibyte, multibyte strings are converted
72bb55c6
KS
2233to unibyte for insertion (see `string-make-unibyte').
2234
2235When operating on binary data, it may be necessary to preserve the
2236original bytes of a unibyte string when inserting it into a multibyte
2237buffer; to accomplish this, apply `string-as-multibyte' to the string
2238and insert the result.
4bfbe194
MB
2239
2240usage: (insert &rest ARGS) */)
7ee72033 2241 (nargs, args)
35692fe0
JB
2242 int nargs;
2243 register Lisp_Object *args;
2244{
fb8106e8 2245 general_insert_function (insert, insert_from_string, 0, nargs, args);
be91036a
RS
2246 return Qnil;
2247}
2248
2249DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2250 0, MANY, 0,
7ee72033 2251 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
a1f17501
PJ
2252Point and before-insertion markers move forward to end up
2253 after the inserted text.
2254Any other markers at the point of insertion remain before the text.
2255
2256If the current buffer is multibyte, unibyte strings are converted
2257to multibyte for insertion (see `unibyte-char-to-multibyte').
2258If the current buffer is unibyte, multibyte strings are converted
4bfbe194
MB
2259to unibyte for insertion.
2260
2261usage: (insert-and-inherit &rest ARGS) */)
7ee72033 2262 (nargs, args)
be91036a
RS
2263 int nargs;
2264 register Lisp_Object *args;
2265{
fb8106e8
KH
2266 general_insert_function (insert_and_inherit, insert_from_string, 1,
2267 nargs, args);
35692fe0
JB
2268 return Qnil;
2269}
2270
2271DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
7ee72033 2272 doc: /* Insert strings or characters at point, relocating markers after the text.
a1f17501
PJ
2273Point and markers move forward to end up after the inserted text.
2274
2275If the current buffer is multibyte, unibyte strings are converted
2276to multibyte for insertion (see `unibyte-char-to-multibyte').
2277If the current buffer is unibyte, multibyte strings are converted
4bfbe194
MB
2278to unibyte for insertion.
2279
2280usage: (insert-before-markers &rest ARGS) */)
7ee72033 2281 (nargs, args)
35692fe0
JB
2282 int nargs;
2283 register Lisp_Object *args;
2284{
fb8106e8
KH
2285 general_insert_function (insert_before_markers,
2286 insert_from_string_before_markers, 0,
2287 nargs, args);
be91036a
RS
2288 return Qnil;
2289}
2290
a0d76c27
EN
2291DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2292 Sinsert_and_inherit_before_markers, 0, MANY, 0,
7ee72033 2293 doc: /* Insert text at point, relocating markers and inheriting properties.
a1f17501
PJ
2294Point and markers move forward to end up after the inserted text.
2295
2296If the current buffer is multibyte, unibyte strings are converted
2297to multibyte for insertion (see `unibyte-char-to-multibyte').
2298If the current buffer is unibyte, multibyte strings are converted
4bfbe194
MB
2299to unibyte for insertion.
2300
2301usage: (insert-before-markers-and-inherit &rest ARGS) */)
7ee72033 2302 (nargs, args)
be91036a
RS
2303 int nargs;
2304 register Lisp_Object *args;
2305{
fb8106e8
KH
2306 general_insert_function (insert_before_markers_and_inherit,
2307 insert_from_string_before_markers, 1,
2308 nargs, args);
35692fe0
JB
2309 return Qnil;
2310}
2311\f
e2eeabbb 2312DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
9671c13a 2313 doc: /* Insert COUNT copies of CHARACTER.
a1f17501
PJ
2314Point, and before-insertion markers, are relocated as in the function `insert'.
2315The optional third arg INHERIT, if non-nil, says to inherit text properties
7ee72033
MB
2316from adjoining text, if those properties are sticky. */)
2317 (character, count, inherit)
2591ec64 2318 Lisp_Object character, count, inherit;
35692fe0
JB
2319{
2320 register unsigned char *string;
2321 register int strlen;
2322 register int i, n;
fb8106e8 2323 int len;
d5c2c403 2324 unsigned char str[MAX_MULTIBYTE_LENGTH];
35692fe0 2325
b7826503
PJ
2326 CHECK_NUMBER (character);
2327 CHECK_NUMBER (count);
35692fe0 2328
fb8106e8 2329 if (!NILP (current_buffer->enable_multibyte_characters))
d5c2c403 2330 len = CHAR_STRING (XFASTINT (character), str);
fb8106e8 2331 else
d5c2c403 2332 str[0] = XFASTINT (character), len = 1;
fb8106e8 2333 n = XINT (count) * len;
35692fe0
JB
2334 if (n <= 0)
2335 return Qnil;
fb8106e8 2336 strlen = min (n, 256 * len);
35692fe0
JB
2337 string = (unsigned char *) alloca (strlen);
2338 for (i = 0; i < strlen; i++)
fb8106e8 2339 string[i] = str[i % len];
35692fe0
JB
2340 while (n >= strlen)
2341 {
54e42e2d 2342 QUIT;
e2eeabbb
RS
2343 if (!NILP (inherit))
2344 insert_and_inherit (string, strlen);
2345 else
2346 insert (string, strlen);
35692fe0
JB
2347 n -= strlen;
2348 }
2349 if (n > 0)
83951f1e
KH
2350 {
2351 if (!NILP (inherit))
2352 insert_and_inherit (string, n);
2353 else
2354 insert (string, n);
2355 }
35692fe0
JB
2356 return Qnil;
2357}
2358
48ef988f
KH
2359DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2360 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2361Both arguments are required.
2362BYTE is a number of the range 0..255.
2363
2364If BYTE is 128..255 and the current buffer is multibyte, the
2365corresponding eight-bit character is inserted.
2366
2367Point, and before-insertion markers, are relocated as in the function `insert'.
2368The optional third arg INHERIT, if non-nil, says to inherit text properties
2369from adjoining text, if those properties are sticky. */)
2370 (byte, count, inherit)
2371 Lisp_Object byte, count, inherit;
2372{
2373 CHECK_NUMBER (byte);
2374 if (XINT (byte) < 0 || XINT (byte) > 255)
2375 args_out_of_range_3 (byte, make_number (0), make_number (255));
2376 if (XINT (byte) >= 128
2377 && ! NILP (current_buffer->enable_multibyte_characters))
2378 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
ed398b0a 2379 return Finsert_char (byte, count, inherit);
48ef988f
KH
2380}
2381
35692fe0 2382\f
ffd56f97
JB
2383/* Making strings from buffer contents. */
2384
2385/* Return a Lisp_String containing the text of the current buffer from
74d6d8c5 2386 START to END. If text properties are in use and the current buffer
eb8c3be9 2387 has properties in the range specified, the resulting string will also
260e2e2a 2388 have them, if PROPS is nonzero.
ffd56f97
JB
2389
2390 We don't want to use plain old make_string here, because it calls
2391 make_uninit_string, which can cause the buffer arena to be
2392 compacted. make_string has no way of knowing that the data has
2393 been moved, and thus copies the wrong data into the string. This
2394 doesn't effect most of the other users of make_string, so it should
2395 be left as is. But we should use this function when conjuring
2396 buffer substrings. */
74d6d8c5 2397
ffd56f97 2398Lisp_Object
260e2e2a 2399make_buffer_string (start, end, props)
ffd56f97 2400 int start, end;
260e2e2a 2401 int props;
ffd56f97 2402{
ec1c14f6
RS
2403 int start_byte = CHAR_TO_BYTE (start);
2404 int end_byte = CHAR_TO_BYTE (end);
ffd56f97 2405
88441c8e
RS
2406 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2407}
2408
2409/* Return a Lisp_String containing the text of the current buffer from
2410 START / START_BYTE to END / END_BYTE.
2411
2412 If text properties are in use and the current buffer
2413 has properties in the range specified, the resulting string will also
2414 have them, if PROPS is nonzero.
2415
2416 We don't want to use plain old make_string here, because it calls
2417 make_uninit_string, which can cause the buffer arena to be
2418 compacted. make_string has no way of knowing that the data has
2419 been moved, and thus copies the wrong data into the string. This
2420 doesn't effect most of the other users of make_string, so it should
2421 be left as is. But we should use this function when conjuring
2422 buffer substrings. */
2423
2424Lisp_Object
2425make_buffer_string_both (start, start_byte, end, end_byte, props)
2426 int start, start_byte, end, end_byte;
2427 int props;
2428{
2429 Lisp_Object result, tem, tem1;
2430
ffd56f97
JB
2431 if (start < GPT && GPT < end)
2432 move_gap (start);
2433
5f75e666
RS
2434 if (! NILP (current_buffer->enable_multibyte_characters))
2435 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2436 else
2437 result = make_uninit_string (end - start);
d5db4077 2438 bcopy (BYTE_POS_ADDR (start_byte), SDATA (result),
ec1c14f6 2439 end_byte - start_byte);
ffd56f97 2440
260e2e2a 2441 /* If desired, update and copy the text properties. */
260e2e2a
KH
2442 if (props)
2443 {
2444 update_buffer_properties (start, end);
2445
2446 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2447 tem1 = Ftext_properties_at (make_number (start), Qnil);
2448
2449 if (XINT (tem) != end || !NILP (tem1))
ec1c14f6
RS
2450 copy_intervals_to_string (result, current_buffer, start,
2451 end - start);
260e2e2a 2452 }
74d6d8c5 2453
ffd56f97
JB
2454 return result;
2455}
35692fe0 2456
260e2e2a
KH
2457/* Call Vbuffer_access_fontify_functions for the range START ... END
2458 in the current buffer, if necessary. */
2459
2460static void
2461update_buffer_properties (start, end)
2462 int start, end;
2463{
260e2e2a
KH
2464 /* If this buffer has some access functions,
2465 call them, specifying the range of the buffer being accessed. */
2466 if (!NILP (Vbuffer_access_fontify_functions))
2467 {
2468 Lisp_Object args[3];
2469 Lisp_Object tem;
2470
2471 args[0] = Qbuffer_access_fontify_functions;
2472 XSETINT (args[1], start);
2473 XSETINT (args[2], end);
2474
2475 /* But don't call them if we can tell that the work
2476 has already been done. */
2477 if (!NILP (Vbuffer_access_fontified_property))
2478 {
2479 tem = Ftext_property_any (args[1], args[2],
2480 Vbuffer_access_fontified_property,
2481 Qnil, Qnil);
2482 if (! NILP (tem))
ced1d19a 2483 Frun_hook_with_args (3, args);
260e2e2a
KH
2484 }
2485 else
ced1d19a 2486 Frun_hook_with_args (3, args);
260e2e2a 2487 }
260e2e2a
KH
2488}
2489
35692fe0 2490DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
7ee72033 2491 doc: /* Return the contents of part of the current buffer as a string.
a1f17501
PJ
2492The two arguments START and END are character positions;
2493they can be in either order.
2494The string returned is multibyte if the buffer is multibyte.
2495
2496This function copies the text properties of that part of the buffer
2497into the result string; if you don't want the text properties,
7ee72033
MB
2498use `buffer-substring-no-properties' instead. */)
2499 (start, end)
2591ec64 2500 Lisp_Object start, end;
35692fe0 2501{
2591ec64 2502 register int b, e;
35692fe0 2503
2591ec64
EN
2504 validate_region (&start, &end);
2505 b = XINT (start);
2506 e = XINT (end);
35692fe0 2507
2591ec64 2508 return make_buffer_string (b, e, 1);
260e2e2a
KH
2509}
2510
2511DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2512 Sbuffer_substring_no_properties, 2, 2, 0,
7ee72033 2513 doc: /* Return the characters of part of the buffer, without the text properties.
a1f17501 2514The two arguments START and END are character positions;
7ee72033
MB
2515they can be in either order. */)
2516 (start, end)
2591ec64 2517 Lisp_Object start, end;
260e2e2a 2518{
2591ec64 2519 register int b, e;
260e2e2a 2520
2591ec64
EN
2521 validate_region (&start, &end);
2522 b = XINT (start);
2523 e = XINT (end);
260e2e2a 2524
2591ec64 2525 return make_buffer_string (b, e, 0);
35692fe0
JB
2526}
2527
2528DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
7ee72033 2529 doc: /* Return the contents of the current buffer as a string.
a1f17501 2530If narrowing is in effect, this function returns only the visible part
7ee72033
MB
2531of the buffer. */)
2532 ()
35692fe0 2533{
0daf6e8d 2534 return make_buffer_string (BEGV, ZV, 1);
35692fe0
JB
2535}
2536
2537DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
deb8e082 2538 1, 3, 0,
658ec670 2539 doc: /* Insert before point a substring of the contents of BUFFER.
a1f17501 2540BUFFER may be a buffer or a buffer name.
412f1fab
JB
2541Arguments START and END are character positions specifying the substring.
2542They default to the values of (point-min) and (point-max) in BUFFER. */)
658ec670
JB
2543 (buffer, start, end)
2544 Lisp_Object buffer, start, end;
35692fe0 2545{
2591ec64 2546 register int b, e, temp;
260e2e2a 2547 register struct buffer *bp, *obuf;
658ec670 2548 Lisp_Object buf;
35692fe0 2549
658ec670
JB
2550 buf = Fget_buffer (buffer);
2551 if (NILP (buf))
2552 nsberror (buffer);
2553 bp = XBUFFER (buf);
93b62e82
KH
2554 if (NILP (bp->name))
2555 error ("Selecting deleted buffer");
35692fe0 2556
2591ec64
EN
2557 if (NILP (start))
2558 b = BUF_BEGV (bp);
35692fe0
JB
2559 else
2560 {
b7826503 2561 CHECK_NUMBER_COERCE_MARKER (start);
2591ec64 2562 b = XINT (start);
35692fe0 2563 }
2591ec64
EN
2564 if (NILP (end))
2565 e = BUF_ZV (bp);
35692fe0
JB
2566 else
2567 {
b7826503 2568 CHECK_NUMBER_COERCE_MARKER (end);
2591ec64 2569 e = XINT (end);
35692fe0
JB
2570 }
2571
2591ec64
EN
2572 if (b > e)
2573 temp = b, b = e, e = temp;
35692fe0 2574
2591ec64
EN
2575 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2576 args_out_of_range (start, end);
35692fe0 2577
260e2e2a
KH
2578 obuf = current_buffer;
2579 set_buffer_internal_1 (bp);
2591ec64 2580 update_buffer_properties (b, e);
260e2e2a
KH
2581 set_buffer_internal_1 (obuf);
2582
2591ec64 2583 insert_from_buffer (bp, b, e - b, 0);
35692fe0
JB
2584 return Qnil;
2585}
e9cf2084
RS
2586
2587DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
deb8e082 2588 6, 6, 0,
7ee72033 2589 doc: /* Compare two substrings of two buffers; return result as number.
a1f17501
PJ
2590the value is -N if first string is less after N-1 chars,
2591+N if first string is greater after N-1 chars, or 0 if strings match.
2592Each substring is represented as three arguments: BUFFER, START and END.
2593That makes six args in all, three for each substring.
2594
2595The value of `case-fold-search' in the current buffer
7ee72033
MB
2596determines whether case is significant or ignored. */)
2597 (buffer1, start1, end1, buffer2, start2, end2)
e9cf2084
RS
2598 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2599{
07422a12 2600 register int begp1, endp1, begp2, endp2, temp;
e9cf2084 2601 register struct buffer *bp1, *bp2;
1149fd6f 2602 register Lisp_Object trt
e9cf2084 2603 = (!NILP (current_buffer->case_fold_search)
60758816 2604 ? current_buffer->case_canon_table : Qnil);
ec1c14f6 2605 int chars = 0;
07422a12 2606 int i1, i2, i1_byte, i2_byte;
e9cf2084
RS
2607
2608 /* Find the first buffer and its substring. */
2609
2610 if (NILP (buffer1))
2611 bp1 = current_buffer;
2612 else
2613 {
3fff2dfa
RS
2614 Lisp_Object buf1;
2615 buf1 = Fget_buffer (buffer1);
2616 if (NILP (buf1))
2617 nsberror (buffer1);
2618 bp1 = XBUFFER (buf1);
93b62e82
KH
2619 if (NILP (bp1->name))
2620 error ("Selecting deleted buffer");
e9cf2084
RS
2621 }
2622
2623 if (NILP (start1))
2624 begp1 = BUF_BEGV (bp1);
2625 else
2626 {
b7826503 2627 CHECK_NUMBER_COERCE_MARKER (start1);
e9cf2084
RS
2628 begp1 = XINT (start1);
2629 }
2630 if (NILP (end1))
2631 endp1 = BUF_ZV (bp1);
2632 else
2633 {
b7826503 2634 CHECK_NUMBER_COERCE_MARKER (end1);
e9cf2084
RS
2635 endp1 = XINT (end1);
2636 }
2637
2638 if (begp1 > endp1)
2639 temp = begp1, begp1 = endp1, endp1 = temp;
2640
2641 if (!(BUF_BEGV (bp1) <= begp1
2642 && begp1 <= endp1
2643 && endp1 <= BUF_ZV (bp1)))
2644 args_out_of_range (start1, end1);
2645
2646 /* Likewise for second substring. */
2647
2648 if (NILP (buffer2))
2649 bp2 = current_buffer;
2650 else
2651 {
3fff2dfa
RS
2652 Lisp_Object buf2;
2653 buf2 = Fget_buffer (buffer2);
2654 if (NILP (buf2))
2655 nsberror (buffer2);
3b1fdd85 2656 bp2 = XBUFFER (buf2);
93b62e82
KH
2657 if (NILP (bp2->name))
2658 error ("Selecting deleted buffer");
e9cf2084
RS
2659 }
2660
2661 if (NILP (start2))
2662 begp2 = BUF_BEGV (bp2);
2663 else
2664 {
b7826503 2665 CHECK_NUMBER_COERCE_MARKER (start2);
e9cf2084
RS
2666 begp2 = XINT (start2);
2667 }
2668 if (NILP (end2))
2669 endp2 = BUF_ZV (bp2);
2670 else
2671 {
b7826503 2672 CHECK_NUMBER_COERCE_MARKER (end2);
e9cf2084
RS
2673 endp2 = XINT (end2);
2674 }
2675
2676 if (begp2 > endp2)
2677 temp = begp2, begp2 = endp2, endp2 = temp;
2678
2679 if (!(BUF_BEGV (bp2) <= begp2
2680 && begp2 <= endp2
2681 && endp2 <= BUF_ZV (bp2)))
2682 args_out_of_range (start2, end2);
2683
07422a12
RS
2684 i1 = begp1;
2685 i2 = begp2;
2686 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2687 i2_byte = buf_charpos_to_bytepos (bp2, i2);
e9cf2084 2688
07422a12 2689 while (i1 < endp1 && i2 < endp2)
e9cf2084 2690 {
07422a12
RS
2691 /* When we find a mismatch, we must compare the
2692 characters, not just the bytes. */
2693 int c1, c2;
ec1c14f6 2694
2221451f
RS
2695 QUIT;
2696
07422a12
RS
2697 if (! NILP (bp1->enable_multibyte_characters))
2698 {
2699 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2700 BUF_INC_POS (bp1, i1_byte);
2701 i1++;
2702 }
2703 else
2704 {
2705 c1 = BUF_FETCH_BYTE (bp1, i1);
4c0354d7 2706 MAKE_CHAR_MULTIBYTE (c1);
07422a12
RS
2707 i1++;
2708 }
2709
2710 if (! NILP (bp2->enable_multibyte_characters))
2711 {
2712 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2713 BUF_INC_POS (bp2, i2_byte);
2714 i2++;
2715 }
2716 else
2717 {
2718 c2 = BUF_FETCH_BYTE (bp2, i2);
4c0354d7 2719 MAKE_CHAR_MULTIBYTE (c2);
07422a12
RS
2720 i2++;
2721 }
ec1c14f6 2722
1149fd6f 2723 if (!NILP (trt))
e9cf2084 2724 {
1149fd6f
SM
2725 c1 = CHAR_TABLE_TRANSLATE (trt, c1);
2726 c2 = CHAR_TABLE_TRANSLATE (trt, c2);
e9cf2084
RS
2727 }
2728 if (c1 < c2)
ec1c14f6 2729 return make_number (- 1 - chars);
e9cf2084 2730 if (c1 > c2)
ec1c14f6 2731 return make_number (chars + 1);
07422a12
RS
2732
2733 chars++;
e9cf2084
RS
2734 }
2735
2736 /* The strings match as far as they go.
2737 If one is shorter, that one is less. */
07422a12 2738 if (chars < endp1 - begp1)
ec1c14f6 2739 return make_number (chars + 1);
07422a12 2740 else if (chars < endp2 - begp2)
ec1c14f6 2741 return make_number (- chars - 1);
e9cf2084
RS
2742
2743 /* Same length too => they are equal. */
2744 return make_number (0);
2745}
35692fe0 2746\f
d5a539cd
RS
2747static Lisp_Object
2748subst_char_in_region_unwind (arg)
2749 Lisp_Object arg;
2750{
2751 return current_buffer->undo_list = arg;
2752}
2753
c8e76b47
RS
2754static Lisp_Object
2755subst_char_in_region_unwind_1 (arg)
2756 Lisp_Object arg;
2757{
2758 return current_buffer->filename = arg;
2759}
2760
35692fe0 2761DEFUN ("subst-char-in-region", Fsubst_char_in_region,
deb8e082 2762 Ssubst_char_in_region, 4, 5, 0,
7ee72033 2763 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
a1f17501
PJ
2764If optional arg NOUNDO is non-nil, don't record this change for undo
2765and don't mark the buffer as really changed.
7ee72033
MB
2766Both characters must have the same length of multi-byte form. */)
2767 (start, end, fromchar, tochar, noundo)
35692fe0
JB
2768 Lisp_Object start, end, fromchar, tochar, noundo;
2769{
84246b95 2770 register int pos, pos_byte, stop, i, len, end_byte;
0f2e2a3b
SM
2771 /* Keep track of the first change in the buffer:
2772 if 0 we haven't found it yet.
2773 if < 0 we've found it and we've run the before-change-function.
2774 if > 0 we've actually performed it and the value is its position. */
60b96ee7 2775 int changed = 0;
d5c2c403
KH
2776 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2777 unsigned char *p;
aed13378 2778 int count = SPECPDL_INDEX ();
aa801467
KH
2779#define COMBINING_NO 0
2780#define COMBINING_BEFORE 1
2781#define COMBINING_AFTER 2
2782#define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2783 int maybe_byte_combining = COMBINING_NO;
2483cf58 2784 int last_changed = 0;
7439e5b9 2785 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
35692fe0 2786
0f2e2a3b
SM
2787 restart:
2788
35692fe0 2789 validate_region (&start, &end);
b7826503
PJ
2790 CHECK_NUMBER (fromchar);
2791 CHECK_NUMBER (tochar);
35692fe0 2792
7439e5b9 2793 if (multibyte_p)
fb8106e8 2794 {
d5c2c403
KH
2795 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2796 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
fdd6025e 2797 error ("Characters in `subst-char-in-region' have different byte-lengths");
aa801467
KH
2798 if (!ASCII_BYTE_P (*tostr))
2799 {
2800 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2801 complete multibyte character, it may be combined with the
2802 after bytes. If it is in the range 0xA0..0xFF, it may be
2803 combined with the before and after bytes. */
2804 if (!CHAR_HEAD_P (*tostr))
2805 maybe_byte_combining = COMBINING_BOTH;
2806 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2807 maybe_byte_combining = COMBINING_AFTER;
2808 }
fb8106e8
KH
2809 }
2810 else
2811 {
2812 len = 1;
d5c2c403
KH
2813 fromstr[0] = XFASTINT (fromchar);
2814 tostr[0] = XFASTINT (tochar);
fb8106e8
KH
2815 }
2816
84246b95
KH
2817 pos = XINT (start);
2818 pos_byte = CHAR_TO_BYTE (pos);
ec1c14f6
RS
2819 stop = CHAR_TO_BYTE (XINT (end));
2820 end_byte = stop;
35692fe0 2821
d5a539cd
RS
2822 /* If we don't want undo, turn off putting stuff on the list.
2823 That's faster than getting rid of things,
c8e76b47
RS
2824 and it prevents even the entry for a first change.
2825 Also inhibit locking the file. */
0f2e2a3b 2826 if (!changed && !NILP (noundo))
d5a539cd
RS
2827 {
2828 record_unwind_protect (subst_char_in_region_unwind,
2829 current_buffer->undo_list);
2830 current_buffer->undo_list = Qt;
c8e76b47
RS
2831 /* Don't do file-locking. */
2832 record_unwind_protect (subst_char_in_region_unwind_1,
2833 current_buffer->filename);
2834 current_buffer->filename = Qnil;
d5a539cd
RS
2835 }
2836
84246b95 2837 if (pos_byte < GPT_BYTE)
ec1c14f6 2838 stop = min (stop, GPT_BYTE);
fb8106e8 2839 while (1)
35692fe0 2840 {
a3360ff9
KH
2841 int pos_byte_next = pos_byte;
2842
84246b95 2843 if (pos_byte >= stop)
fb8106e8 2844 {
84246b95 2845 if (pos_byte >= end_byte) break;
ec1c14f6 2846 stop = end_byte;
fb8106e8 2847 }
84246b95 2848 p = BYTE_POS_ADDR (pos_byte);
7439e5b9
GM
2849 if (multibyte_p)
2850 INC_POS (pos_byte_next);
2851 else
2852 ++pos_byte_next;
a3360ff9
KH
2853 if (pos_byte_next - pos_byte == len
2854 && p[0] == fromstr[0]
fb8106e8
KH
2855 && (len == 1
2856 || (p[1] == fromstr[1]
2857 && (len == 2 || (p[2] == fromstr[2]
2858 && (len == 3 || p[3] == fromstr[3]))))))
35692fe0 2859 {
0f2e2a3b
SM
2860 if (changed < 0)
2861 /* We've already seen this and run the before-change-function;
2862 this time we only need to record the actual position. */
2863 changed = pos;
2864 else if (!changed)
60b96ee7 2865 {
0f2e2a3b 2866 changed = -1;
3e145152 2867 modify_region (current_buffer, pos, XINT (end), 0);
7653d030
RS
2868
2869 if (! NILP (noundo))
2870 {
1e158d25
RS
2871 if (MODIFF - 1 == SAVE_MODIFF)
2872 SAVE_MODIFF++;
7653d030
RS
2873 if (MODIFF - 1 == current_buffer->auto_save_modified)
2874 current_buffer->auto_save_modified++;
2875 }
0f2e2a3b
SM
2876
2877 /* The before-change-function may have moved the gap
2878 or even modified the buffer so we should start over. */
2879 goto restart;
60b96ee7
RS
2880 }
2881
0c1e3b85 2882 /* Take care of the case where the new character
34a7a267 2883 combines with neighboring bytes. */
a3360ff9 2884 if (maybe_byte_combining
aa801467
KH
2885 && (maybe_byte_combining == COMBINING_AFTER
2886 ? (pos_byte_next < Z_BYTE
2887 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2888 : ((pos_byte_next < Z_BYTE
2889 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2890 || (pos_byte > BEG_BYTE
2891 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
0c1e3b85
RS
2892 {
2893 Lisp_Object tem, string;
2894
2895 struct gcpro gcpro1;
2896
2897 tem = current_buffer->undo_list;
2898 GCPRO1 (tem);
2899
aa801467
KH
2900 /* Make a multibyte string containing this single character. */
2901 string = make_multibyte_string (tostr, 1, len);
0c1e3b85
RS
2902 /* replace_range is less efficient, because it moves the gap,
2903 but it handles combining correctly. */
2904 replace_range (pos, pos + 1, string,
9869520f 2905 0, 0, 1);
a3360ff9
KH
2906 pos_byte_next = CHAR_TO_BYTE (pos);
2907 if (pos_byte_next > pos_byte)
2908 /* Before combining happened. We should not increment
3f5409d3
KH
2909 POS. So, to cancel the later increment of POS,
2910 decrease it now. */
2911 pos--;
a3360ff9 2912 else
3f5409d3 2913 INC_POS (pos_byte_next);
34a7a267 2914
0c1e3b85
RS
2915 if (! NILP (noundo))
2916 current_buffer->undo_list = tem;
2917
2918 UNGCPRO;
2919 }
2920 else
2921 {
2922 if (NILP (noundo))
2923 record_change (pos, 1);
2924 for (i = 0; i < len; i++) *p++ = tostr[i];
2925 }
d5c2c403 2926 last_changed = pos + 1;
35692fe0 2927 }
3f5409d3
KH
2928 pos_byte = pos_byte_next;
2929 pos++;
35692fe0
JB
2930 }
2931
0f2e2a3b 2932 if (changed > 0)
d5c2c403
KH
2933 {
2934 signal_after_change (changed,
2935 last_changed - changed, last_changed - changed);
2936 update_compositions (changed, last_changed, CHECK_ALL);
2937 }
60b96ee7 2938
d5a539cd 2939 unbind_to (count, Qnil);
35692fe0
JB
2940 return Qnil;
2941}
2942
f555f8cf
KH
2943
2944static Lisp_Object check_translation P_ ((int, int, int, Lisp_Object));
2945
2946/* Helper function for Ftranslate_region_internal.
2947
2948 Check if a character sequence at POS (POS_BYTE) matches an element
2949 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
2950 element is found, return it. Otherwise return Qnil. */
2951
2952static Lisp_Object
2953check_translation (pos, pos_byte, end, val)
2954 int pos, pos_byte, end;
2955 Lisp_Object val;
2956{
2957 int buf_size = 16, buf_used = 0;
2958 int *buf = alloca (sizeof (int) * buf_size);
2959
2960 for (; CONSP (val); val = XCDR (val))
2961 {
2962 Lisp_Object elt;
2963 int len, i;
2964
2965 elt = XCAR (val);
2966 if (! CONSP (elt))
2967 continue;
2968 elt = XCAR (elt);
2969 if (! VECTORP (elt))
2970 continue;
2971 len = ASIZE (elt);
2972 if (len <= end - pos)
2973 {
2974 for (i = 0; i < len; i++)
2975 {
2976 if (buf_used <= i)
2977 {
2978 unsigned char *p = BYTE_POS_ADDR (pos_byte);
2979 int len;
2980
2981 if (buf_used == buf_size)
2982 {
2983 int *newbuf;
2984
2985 buf_size += 16;
2986 newbuf = alloca (sizeof (int) * buf_size);
2987 memcpy (newbuf, buf, sizeof (int) * buf_used);
2988 buf = newbuf;
2989 }
62a6e103 2990 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len);
f555f8cf
KH
2991 pos_byte += len;
2992 }
2993 if (XINT (AREF (elt, i)) != buf[i])
2994 break;
2995 }
2996 if (i == len)
2997 return XCAR (val);
2998 }
2999 }
3000 return Qnil;
3001}
3002
3003
8583605b
KH
3004DEFUN ("translate-region-internal", Ftranslate_region_internal,
3005 Stranslate_region_internal, 3, 3, 0,
3006 doc: /* Internal use only.
3007From START to END, translate characters according to TABLE.
f555f8cf
KH
3008TABLE is a string or a char-table; the Nth character in it is the
3009mapping for the character with code N.
7ee72033
MB
3010It returns the number of characters changed. */)
3011 (start, end, table)
35692fe0
JB
3012 Lisp_Object start;
3013 Lisp_Object end;
3014 register Lisp_Object table;
3015{
35692fe0 3016 register unsigned char *tt; /* Trans table. */
35692fe0
JB
3017 register int nc; /* New character. */
3018 int cnt; /* Number of changes made. */
35692fe0 3019 int size; /* Size of translate table. */
f555f8cf 3020 int pos, pos_byte, end_pos;
e8cce5af 3021 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
8583605b
KH
3022 int string_multibyte;
3023 Lisp_Object val;
35692fe0
JB
3024
3025 validate_region (&start, &end);
8583605b 3026 if (CHAR_TABLE_P (table))
f555f8cf
KH
3027 {
3028 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3029 error ("Not a translation table");
eb3d9ec7 3030 size = MAX_CHAR;
f555f8cf
KH
3031 tt = NULL;
3032 }
8583605b
KH
3033 else
3034 {
3035 CHECK_STRING (table);
3036
eb3d9ec7
KH
3037 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3038 table = string_make_unibyte (table);
8583605b
KH
3039 string_multibyte = SCHARS (table) < SBYTES (table);
3040 size = SBYTES (table);
3041 tt = SDATA (table);
3042 }
35692fe0 3043
1f24f4fd 3044 pos = XINT (start);
8583605b 3045 pos_byte = CHAR_TO_BYTE (pos);
e65837df 3046 end_pos = XINT (end);
af6ea8ad 3047 modify_region (current_buffer, pos, end_pos, 0);
35692fe0
JB
3048
3049 cnt = 0;
f555f8cf 3050 for (; pos < end_pos; )
35692fe0 3051 {
ec1c14f6 3052 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
8583605b
KH
3053 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3054 int len, str_len;
1f24f4fd 3055 int oc;
f555f8cf 3056 Lisp_Object val;
ec1c14f6 3057
e8cce5af 3058 if (multibyte)
62a6e103 3059 oc = STRING_CHAR_AND_LENGTH (p, len);
e8cce5af 3060 else
eb3d9ec7
KH
3061 oc = *p, len = 1;
3062 if (oc < size)
35692fe0 3063 {
eb3d9ec7 3064 if (tt)
35692fe0 3065 {
fa056b08
KS
3066 /* Reload as signal_after_change in last iteration may GC. */
3067 tt = SDATA (table);
8583605b 3068 if (string_multibyte)
0c1e3b85 3069 {
8583605b 3070 str = tt + string_char_to_byte (table, oc);
62a6e103 3071 nc = STRING_CHAR_AND_LENGTH (str, str_len);
0c1e3b85
RS
3072 }
3073 else
3074 {
eb3d9ec7
KH
3075 nc = tt[oc];
3076 if (! ASCII_BYTE_P (nc) && multibyte)
3077 {
3078 str_len = BYTE8_STRING (nc, buf);
3079 str = buf;
3080 }
3081 else
3082 {
3083 str_len = 1;
3084 str = tt + oc;
3085 }
0c1e3b85 3086 }
35692fe0 3087 }
eb3d9ec7 3088 else
f555f8cf 3089 {
eb3d9ec7
KH
3090 int c;
3091
3092 nc = oc;
3093 val = CHAR_TABLE_REF (table, oc);
3094 if (CHARACTERP (val)
3095 && (c = XINT (val), CHAR_VALID_P (c, 0)))
3096 {
3097 nc = c;
3098 str_len = CHAR_STRING (nc, buf);
3099 str = buf;
3100 }
3101 else if (VECTORP (val) || (CONSP (val)))
3102 {
3103 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3104 where TO is TO-CHAR or [TO-CHAR ...]. */
3105 nc = -1;
3106 }
f555f8cf 3107 }
8583605b 3108
eb3d9ec7 3109 if (nc != oc && nc >= 0)
8583605b 3110 {
f555f8cf
KH
3111 /* Simple one char to one char translation. */
3112 if (len != str_len)
3113 {
3114 Lisp_Object string;
8583605b 3115
f555f8cf
KH
3116 /* This is less efficient, because it moves the gap,
3117 but it should handle multibyte characters correctly. */
3118 string = make_multibyte_string (str, 1, str_len);
3119 replace_range (pos, pos + 1, string, 1, 0, 1);
3120 len = str_len;
3121 }
3122 else
3123 {
3124 record_change (pos, 1);
3125 while (str_len-- > 0)
3126 *p++ = *str++;
3127 signal_after_change (pos, 1, 1);
3128 update_compositions (pos, pos + 1, CHECK_BORDER);
3129 }
3130 ++cnt;
8583605b 3131 }
eb3d9ec7 3132 else if (nc < 0)
8583605b 3133 {
f555f8cf
KH
3134 Lisp_Object string;
3135
3136 if (CONSP (val))
3137 {
3138 val = check_translation (pos, pos_byte, end_pos, val);
3139 if (NILP (val))
3140 {
3141 pos_byte += len;
3142 pos++;
3143 continue;
3144 }
3145 /* VAL is ([FROM-CHAR ...] . TO). */
3146 len = ASIZE (XCAR (val));
3147 val = XCDR (val);
3148 }
3149 else
3150 len = 1;
3151
3152 if (VECTORP (val))
3153 {
bde25748 3154 string = Fconcat (1, &val);
f555f8cf
KH
3155 }
3156 else
3157 {
3158 string = Fmake_string (make_number (1), val);
3159 }
3160 replace_range (pos, pos + len, string, 1, 0, 1);
3161 pos_byte += SBYTES (string);
3162 pos += SCHARS (string);
3163 cnt += SCHARS (string);
3164 end_pos += SCHARS (string) - len;
3165 continue;
8583605b 3166 }
8583605b
KH
3167 }
3168 pos_byte += len;
3f5409d3 3169 pos++;
35692fe0
JB
3170 }
3171
ec1c14f6 3172 return make_number (cnt);
35692fe0
JB
3173}
3174
3175DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
7ee72033 3176 doc: /* Delete the text between point and mark.
412f1fab 3177
a1f17501 3178When called from a program, expects two arguments,
7ee72033
MB
3179positions (integers or markers) specifying the stretch to be deleted. */)
3180 (start, end)
2591ec64 3181 Lisp_Object start, end;
35692fe0 3182{
2591ec64
EN
3183 validate_region (&start, &end);
3184 del_range (XINT (start), XINT (end));
35692fe0
JB
3185 return Qnil;
3186}
7dae4502
SM
3187
3188DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3189 Sdelete_and_extract_region, 2, 2, 0,
7ee72033
MB
3190 doc: /* Delete the text between START and END and return it. */)
3191 (start, end)
7dae4502
SM
3192 Lisp_Object start, end;
3193{
3194 validate_region (&start, &end);
8550b998 3195 if (XINT (start) == XINT (end))
977f6cfb 3196 return empty_unibyte_string;
7dae4502
SM
3197 return del_range_1 (XINT (start), XINT (end), 1, 1);
3198}
35692fe0
JB
3199\f
3200DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
7ee72033
MB
3201 doc: /* Remove restrictions (narrowing) from current buffer.
3202This allows the buffer's full text to be seen and edited. */)
3203 ()
35692fe0 3204{
2cad2e34
RS
3205 if (BEG != BEGV || Z != ZV)
3206 current_buffer->clip_changed = 1;
35692fe0 3207 BEGV = BEG;
ec1c14f6
RS
3208 BEGV_BYTE = BEG_BYTE;
3209 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
52b14ac0
JB
3210 /* Changing the buffer bounds invalidates any recorded current column. */
3211 invalidate_current_column ();
35692fe0
JB
3212 return Qnil;
3213}
3214
3215DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
7ee72033 3216 doc: /* Restrict editing in this buffer to the current region.
a1f17501
PJ
3217The rest of the text becomes temporarily invisible and untouchable
3218but is not deleted; if you save the buffer in a file, the invisible
3219text is included in the file. \\[widen] makes all visible again.
3220See also `save-restriction'.
3221
3222When calling from a program, pass two arguments; positions (integers
7ee72033
MB
3223or markers) bounding the text that should remain visible. */)
3224 (start, end)
2591ec64 3225 register Lisp_Object start, end;
35692fe0 3226{
b7826503
PJ
3227 CHECK_NUMBER_COERCE_MARKER (start);
3228 CHECK_NUMBER_COERCE_MARKER (end);
35692fe0 3229
2591ec64 3230 if (XINT (start) > XINT (end))
35692fe0 3231 {
b5a6948e 3232 Lisp_Object tem;
2591ec64 3233 tem = start; start = end; end = tem;
35692fe0
JB
3234 }
3235
2591ec64
EN
3236 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3237 args_out_of_range (start, end);
35692fe0 3238
2cad2e34
RS
3239 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3240 current_buffer->clip_changed = 1;
3241
ec1c14f6 3242 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2591ec64 3243 SET_BUF_ZV (current_buffer, XFASTINT (end));
6ec8bbd2 3244 if (PT < XFASTINT (start))
2591ec64 3245 SET_PT (XFASTINT (start));
6ec8bbd2 3246 if (PT > XFASTINT (end))
2591ec64 3247 SET_PT (XFASTINT (end));
52b14ac0
JB
3248 /* Changing the buffer bounds invalidates any recorded current column. */
3249 invalidate_current_column ();
35692fe0
JB
3250 return Qnil;
3251}
3252
3253Lisp_Object
3254save_restriction_save ()
3255{
d6abb4c7
MB
3256 if (BEGV == BEG && ZV == Z)
3257 /* The common case that the buffer isn't narrowed.
3258 We return just the buffer object, which save_restriction_restore
3259 recognizes as meaning `no restriction'. */
3260 return Fcurrent_buffer ();
3261 else
3262 /* We have to save a restriction, so return a pair of markers, one
3263 for the beginning and one for the end. */
3264 {
3265 Lisp_Object beg, end;
3266
3267 beg = buildmark (BEGV, BEGV_BYTE);
3268 end = buildmark (ZV, ZV_BYTE);
35692fe0 3269
d6abb4c7
MB
3270 /* END must move forward if text is inserted at its exact location. */
3271 XMARKER(end)->insertion_type = 1;
3272
3273 return Fcons (beg, end);
3274 }
35692fe0
JB
3275}
3276
3277Lisp_Object
3278save_restriction_restore (data)
3279 Lisp_Object data;
3280{
d528b1ce
SM
3281 struct buffer *cur = NULL;
3282 struct buffer *buf = (CONSP (data)
3283 ? XMARKER (XCAR (data))->buffer
3284 : XBUFFER (data));
3285
3286 if (buf && buf != current_buffer && !NILP (buf->pt_marker))
3287 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3288 is the case if it is or has an indirect buffer), then make
3289 sure it is current before we update BEGV, so
3290 set_buffer_internal takes care of managing those markers. */
3291 cur = current_buffer;
3292 set_buffer_internal (buf);
3293 }
3294
d6abb4c7
MB
3295 if (CONSP (data))
3296 /* A pair of marks bounding a saved restriction. */
35692fe0 3297 {
d6abb4c7
MB
3298 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3299 struct Lisp_Marker *end = XMARKER (XCDR (data));
d528b1ce 3300 eassert (buf == end->buffer);
2cad2e34 3301
63884563
RS
3302 if (buf /* Verify marker still points to a buffer. */
3303 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
d6abb4c7
MB
3304 /* The restriction has changed from the saved one, so restore
3305 the saved restriction. */
3306 {
3307 int pt = BUF_PT (buf);
3308
3309 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3310 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3311
3312 if (pt < beg->charpos || pt > end->charpos)
3313 /* The point is outside the new visible range, move it inside. */
3314 SET_BUF_PT_BOTH (buf,
3315 clip_to_bounds (beg->charpos, pt, end->charpos),
63884563 3316 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
d6abb4c7 3317 end->bytepos));
177c0ea7 3318
d6abb4c7
MB
3319 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3320 }
3321 }
3322 else
3323 /* A buffer, which means that there was no old restriction. */
3324 {
63884563
RS
3325 if (buf /* Verify marker still points to a buffer. */
3326 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
d6abb4c7
MB
3327 /* The buffer has been narrowed, get rid of the narrowing. */
3328 {
63884563
RS
3329 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3330 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
35692fe0 3331
d6abb4c7
MB
3332 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3333 }
3334 }
35692fe0 3335
d528b1ce
SM
3336 if (cur)
3337 set_buffer_internal (cur);
3338
35692fe0
JB
3339 return Qnil;
3340}
3341
3342DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
7ee72033 3343 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
a1f17501 3344The buffer's restrictions make parts of the beginning and end invisible.
9671c13a 3345\(They are set up with `narrow-to-region' and eliminated with `widen'.)
a1f17501
PJ
3346This special form, `save-restriction', saves the current buffer's restrictions
3347when it is entered, and restores them when it is exited.
3348So any `narrow-to-region' within BODY lasts only until the end of the form.
3349The old restrictions settings are restored
3350even in case of abnormal exit (throw or error).
3351
3352The value returned is the value of the last form in BODY.
3353
3354Note: if you are using both `save-excursion' and `save-restriction',
3355use `save-excursion' outermost:
33c2d29f
MB
3356 (save-excursion (save-restriction ...))
3357
3358usage: (save-restriction &rest BODY) */)
7ee72033 3359 (body)
35692fe0
JB
3360 Lisp_Object body;
3361{
3362 register Lisp_Object val;
aed13378 3363 int count = SPECPDL_INDEX ();
35692fe0
JB
3364
3365 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3366 val = Fprogn (body);
3367 return unbind_to (count, val);
3368}
3369\f
0ae83348 3370/* Buffer for the most recent text displayed by Fmessage_box. */
671fbc4d
KH
3371static char *message_text;
3372
3373/* Allocated length of that buffer. */
3374static int message_length;
3375
35692fe0 3376DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
db18da59 3377 doc: /* Display a message at the bottom of the screen.
281c1721
RS
3378The message also goes into the `*Messages*' buffer.
3379\(In keyboard macros, that's all it does.)
db18da59 3380Return the message.
281c1721 3381
a1f17501
PJ
3382The first argument is a format control string, and the rest are data
3383to be formatted under control of the string. See `format' for details.
3384
7bd5bcfb
KS
3385Note: Use (message "%s" VALUE) to print the value of expressions and
3386variables to avoid accidentally interpreting `%' as format specifiers.
3387
fa056b08
KS
3388If the first argument is nil or the empty string, the function clears
3389any existing message; this lets the minibuffer contents show. See
3390also `current-message'.
4bfbe194 3391
867b9600 3392usage: (message FORMAT-STRING &rest ARGS) */)
7ee72033 3393 (nargs, args)
35692fe0
JB
3394 int nargs;
3395 Lisp_Object *args;
3396{
6076e561
RS
3397 if (NILP (args[0])
3398 || (STRINGP (args[0])
3399 && SBYTES (args[0]) == 0))
f0250249
JB
3400 {
3401 message (0);
674a954a 3402 return args[0];
f0250249 3403 }
ccdac5be
JB
3404 else
3405 {
3406 register Lisp_Object val;
304f1f12 3407 val = Fformat (nargs, args);
d5db4077 3408 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
ccdac5be
JB
3409 return val;
3410 }
35692fe0
JB
3411}
3412
cacc3e2c 3413DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
7ee72033 3414 doc: /* Display a message, in a dialog box if possible.
a1f17501
PJ
3415If a dialog box is not available, use the echo area.
3416The first argument is a format control string, and the rest are data
3417to be formatted under control of the string. See `format' for details.
3418
fa056b08
KS
3419If the first argument is nil or the empty string, clear any existing
3420message; let the minibuffer contents show.
4bfbe194 3421
867b9600 3422usage: (message-box FORMAT-STRING &rest ARGS) */)
7ee72033 3423 (nargs, args)
cacc3e2c
RS
3424 int nargs;
3425 Lisp_Object *args;
3426{
3427 if (NILP (args[0]))
3428 {
3429 message (0);
3430 return Qnil;
3431 }
3432 else
3433 {
3434 register Lisp_Object val;
3435 val = Fformat (nargs, args);
f8250f01 3436#ifdef HAVE_MENUS
0ae83348
EZ
3437 /* The MS-DOS frames support popup menus even though they are
3438 not FRAME_WINDOW_P. */
3439 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3440 || FRAME_MSDOS_P (XFRAME (selected_frame)))
cacc3e2c
RS
3441 {
3442 Lisp_Object pane, menu, obj;
3443 struct gcpro gcpro1;
3444 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3445 GCPRO1 (pane);
3446 menu = Fcons (val, pane);
87944384 3447 obj = Fx_popup_dialog (Qt, menu, Qt);
cacc3e2c
RS
3448 UNGCPRO;
3449 return val;
3450 }
0ae83348 3451#endif /* HAVE_MENUS */
cacc3e2c
RS
3452 /* Copy the data so that it won't move when we GC. */
3453 if (! message_text)
3454 {
3455 message_text = (char *)xmalloc (80);
3456 message_length = 80;
3457 }
d5db4077 3458 if (SBYTES (val) > message_length)
cacc3e2c 3459 {
d5db4077 3460 message_length = SBYTES (val);
cacc3e2c
RS
3461 message_text = (char *)xrealloc (message_text, message_length);
3462 }
d5db4077
KR
3463 bcopy (SDATA (val), message_text, SBYTES (val));
3464 message2 (message_text, SBYTES (val),
d13a8480 3465 STRING_MULTIBYTE (val));
cacc3e2c 3466 return val;
cacc3e2c
RS
3467 }
3468}
f8250f01 3469#ifdef HAVE_MENUS
cacc3e2c
RS
3470extern Lisp_Object last_nonmenu_event;
3471#endif
f8250f01 3472
cacc3e2c 3473DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
7ee72033 3474 doc: /* Display a message in a dialog box or in the echo area.
a1f17501
PJ
3475If this command was invoked with the mouse, use a dialog box if
3476`use-dialog-box' is non-nil.
3477Otherwise, use the echo area.
3478The first argument is a format control string, and the rest are data
3479to be formatted under control of the string. See `format' for details.
3480
fa056b08
KS
3481If the first argument is nil or the empty string, clear any existing
3482message; let the minibuffer contents show.
4bfbe194 3483
867b9600 3484usage: (message-or-box FORMAT-STRING &rest ARGS) */)
7ee72033 3485 (nargs, args)
cacc3e2c
RS
3486 int nargs;
3487 Lisp_Object *args;
3488{
f8250f01 3489#ifdef HAVE_MENUS
5920df33 3490 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
c01fbf95 3491 && use_dialog_box)
0a56ee6b 3492 return Fmessage_box (nargs, args);
cacc3e2c
RS
3493#endif
3494 return Fmessage (nargs, args);
3495}
3496
b14dda8a 3497DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
7ee72033
MB
3498 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3499 ()
b14dda8a 3500{
0634a78e 3501 return current_message ();
b14dda8a
RS
3502}
3503
2d9811c4 3504
d2936d21 3505DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
7ee72033 3506 doc: /* Return a copy of STRING with text properties added.
a1f17501
PJ
3507First argument is the string to copy.
3508Remaining arguments form a sequence of PROPERTY VALUE pairs for text
4bfbe194
MB
3509properties to add to the result.
3510usage: (propertize STRING &rest PROPERTIES) */)
7ee72033 3511 (nargs, args)
2d9811c4
GM
3512 int nargs;
3513 Lisp_Object *args;
3514{
3515 Lisp_Object properties, string;
3516 struct gcpro gcpro1, gcpro2;
3517 int i;
3518
3519 /* Number of args must be odd. */
d2936d21 3520 if ((nargs & 1) == 0 || nargs < 1)
2d9811c4
GM
3521 error ("Wrong number of arguments");
3522
3523 properties = string = Qnil;
3524 GCPRO2 (properties, string);
34a7a267 3525
2d9811c4 3526 /* First argument must be a string. */
b7826503 3527 CHECK_STRING (args[0]);
2d9811c4
GM
3528 string = Fcopy_sequence (args[0]);
3529
3530 for (i = 1; i < nargs; i += 2)
9b7a2369 3531 properties = Fcons (args[i], Fcons (args[i + 1], properties));
2d9811c4
GM
3532
3533 Fadd_text_properties (make_number (0),
d5db4077 3534 make_number (SCHARS (string)),
2d9811c4
GM
3535 properties, string);
3536 RETURN_UNGCPRO (string);
3537}
3538
3539
1f24f4fd
RS
3540/* Number of bytes that STRING will occupy when put into the result.
3541 MULTIBYTE is nonzero if the result should be multibyte. */
3542
3543#define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3544 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
d5db4077
KR
3545 ? count_size_as_multibyte (SDATA (STRING), SBYTES (STRING)) \
3546 : SBYTES (STRING))
1f24f4fd 3547
35692fe0 3548DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
867b9600
JL
3549 doc: /* Format a string out of a format-string and arguments.
3550The first argument is a format control string.
a1f17501 3551The other arguments are substituted into it to make the result, a string.
575b782f
CY
3552
3553The format control string may contain %-sequences meaning to substitute
3554the next available argument:
3555
a1f17501
PJ
3556%s means print a string argument. Actually, prints any object, with `princ'.
3557%d means print as number in decimal (%o octal, %x hex).
3558%X is like %x, but uses upper case.
3559%e means print a number in exponential notation.
3560%f means print a number in decimal-point notation.
3561%g means print a number in exponential notation
3562 or decimal-point notation, whichever uses fewer characters.
3563%c means print a number as a single character.
3564%S means print any object as an s-expression (using `prin1').
575b782f
CY
3565
3566The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
4bfbe194
MB
3567Use %% to put a single % into the output.
3568
575b782f
CY
3569A %-sequence may contain optional flag, width, and precision
3570specifiers, as follows:
3571
3572 %<flags><width><precision>character
3573
3574where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3575
3576The + flag character inserts a + before any positive number, while a
3577space inserts a space before any positive number; these flags only
3578affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3579The # flag means to use an alternate display form for %o, %x, %X, %e,
3580%f, and %g sequences. The - and 0 flags affect the width specifier,
3581as described below.
3582
3583The width specifier supplies a lower limit for the length of the
3584printed representation. The padding, if any, normally goes on the
3585left, but it goes on the right if the - flag is present. The padding
3586character is normally a space, but it is 0 if the 0 flag is present.
3587The - flag takes precedence over the 0 flag.
3588
3589For %e, %f, and %g sequences, the number after the "." in the
3590precision specifier says how many decimal places to show; if zero, the
3591decimal point itself is omitted. For %s and %S, the precision
3592specifier truncates the string to the given width.
f555f8cf 3593
4bfbe194 3594usage: (format STRING &rest OBJECTS) */)
7ee72033 3595 (nargs, args)
35692fe0
JB
3596 int nargs;
3597 register Lisp_Object *args;
3598{
3599 register int n; /* The number of the next arg to substitute */
e781c49e 3600 register int total; /* An estimate of the final length */
1f24f4fd 3601 char *buf, *p;
d147ee84 3602 register unsigned char *format, *end, *format_start;
2ea0266e 3603 int nchars;
1f24f4fd
RS
3604 /* Nonzero if the output should be a multibyte string,
3605 which is true if any of the inputs is one. */
3606 int multibyte = 0;
8f2917e4
KH
3607 /* When we make a multibyte string, we must pay attention to the
3608 byte combining problem, i.e., a byte may be combined with a
3609 multibyte charcter of the previous string. This flag tells if we
3610 must consider such a situation or not. */
3611 int maybe_combine_byte;
1f24f4fd 3612 unsigned char *this_format;
ac42d7b9
KG
3613 /* Precision for each spec, or -1, a flag value meaning no precision
3614 was given in that spec. Element 0, corresonding to the format
3615 string itself, will not be used. Element NARGS, corresponding to
3616 no argument, *will* be assigned to in the case that a `%' and `.'
3617 occur after the final format specifier. */
6b61353c 3618 int *precision = (int *) (alloca((nargs + 1) * sizeof (int)));
e781c49e 3619 int longest_format;
8d6179dc 3620 Lisp_Object val;
d147ee84 3621 int arg_intervals = 0;
7e2c051b 3622 USE_SAFE_ALLOCA;
d147ee84
RS
3623
3624 /* discarded[I] is 1 if byte I of the format
3625 string was not copied into the output.
3626 It is 2 if byte I was not the first byte of its character. */
e65837df 3627 char *discarded = 0;
d147ee84
RS
3628
3629 /* Each element records, for one argument,
3630 the start and end bytepos in the output string,
3631 and whether the argument is a string with intervals.
3632 info[0] is unused. Unused elements have -1 for start. */
5e6d5493
GM
3633 struct info
3634 {
d147ee84 3635 int start, end, intervals;
5e6d5493 3636 } *info = 0;
1f24f4fd 3637
35692fe0
JB
3638 /* It should not be necessary to GCPRO ARGS, because
3639 the caller in the interpreter should take care of that. */
3640
e781c49e
RS
3641 /* Try to determine whether the result should be multibyte.
3642 This is not always right; sometimes the result needs to be multibyte
3643 because of an object that we will pass through prin1,
3644 and in that case, we won't know it here. */
d147ee84
RS
3645 for (n = 0; n < nargs; n++)
3646 {
3647 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3648 multibyte = 1;
3649 /* Piggyback on this loop to initialize precision[N]. */
3650 precision[n] = -1;
3651 }
7c111482 3652 precision[nargs] = -1;
1f24f4fd 3653
b7826503 3654 CHECK_STRING (args[0]);
aa8b70ae
KH
3655 /* We may have to change "%S" to "%s". */
3656 args[0] = Fcopy_sequence (args[0]);
e781c49e 3657
67965a98
RS
3658 /* GC should never happen here, so abort if it does. */
3659 abort_on_gc++;
3660
e781c49e 3661 /* If we start out planning a unibyte result,
67965a98
RS
3662 then discover it has to be multibyte, we jump back to retry.
3663 That can only happen from the first large while loop below. */
e781c49e
RS
3664 retry:
3665
d5db4077 3666 format = SDATA (args[0]);
d147ee84 3667 format_start = format;
d5db4077 3668 end = format + SBYTES (args[0]);
e781c49e 3669 longest_format = 0;
1f24f4fd
RS
3670
3671 /* Make room in result for all the non-%-codes in the control string. */
7e2c051b 3672 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]) + 1;
1f24f4fd 3673
6b61353c 3674 /* Allocate the info and discarded tables. */
d147ee84 3675 {
7c111482 3676 int nbytes = (nargs+1) * sizeof *info;
d147ee84 3677 int i;
e65837df
KS
3678 if (!info)
3679 info = (struct info *) alloca (nbytes);
d147ee84 3680 bzero (info, nbytes);
7c111482 3681 for (i = 0; i <= nargs; i++)
d147ee84 3682 info[i].start = -1;
e65837df
KS
3683 if (!discarded)
3684 SAFE_ALLOCA (discarded, char *, SBYTES (args[0]));
d147ee84
RS
3685 bzero (discarded, SBYTES (args[0]));
3686 }
3687
1f24f4fd 3688 /* Add to TOTAL enough space to hold the converted arguments. */
35692fe0
JB
3689
3690 n = 0;
3691 while (format != end)
3692 if (*format++ == '%')
3693 {
a432bfe5 3694 int thissize = 0;
308dd672 3695 int actual_width = 0;
1f24f4fd 3696 unsigned char *this_format_start = format - 1;
ac42d7b9 3697 int field_width = 0;
35692fe0 3698
a432bfe5 3699 /* General format specifications look like
537dfb13 3700
a432bfe5
GM
3701 '%' [flags] [field-width] [precision] format
3702
3703 where
3704
cb06e570 3705 flags ::= [-+ #0]+
a432bfe5
GM
3706 field-width ::= [0-9]+
3707 precision ::= '.' [0-9]*
3708
3709 If a field-width is specified, it specifies to which width
e0f24100 3710 the output should be padded with blanks, if the output
a432bfe5
GM
3711 string is shorter than field-width.
3712
ac42d7b9 3713 If precision is specified, it specifies the number of
a432bfe5
GM
3714 digits to print after the '.' for floats, or the max.
3715 number of chars to print from a string. */
3716
913f73d4
RS
3717 while (format != end
3718 && (*format == '-' || *format == '0' || *format == '#'
cb06e570 3719 || * format == ' ' || *format == '+'))
a432bfe5
GM
3720 ++format;
3721
3722 if (*format >= '0' && *format <= '9')
3723 {
3724 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3725 field_width = 10 * field_width + *format - '0';
3726 }
3727
ac42d7b9
KG
3728 /* N is not incremented for another few lines below, so refer to
3729 element N+1 (which might be precision[NARGS]). */
a432bfe5
GM
3730 if (*format == '.')
3731 {
3732 ++format;
ac42d7b9
KG
3733 for (precision[n+1] = 0; *format >= '0' && *format <= '9'; ++format)
3734 precision[n+1] = 10 * precision[n+1] + *format - '0';
a432bfe5 3735 }
35692fe0 3736
6e1ada1b
AS
3737 /* Extra +1 for 'l' that we may need to insert into the
3738 format. */
3739 if (format - this_format_start + 2 > longest_format)
3740 longest_format = format - this_format_start + 2;
1f24f4fd 3741
bf6ab66c
KH
3742 if (format == end)
3743 error ("Format string ends in middle of format specifier");
35692fe0
JB
3744 if (*format == '%')
3745 format++;
3746 else if (++n >= nargs)
537dfb13 3747 error ("Not enough arguments for format string");
35692fe0
JB
3748 else if (*format == 'S')
3749 {
3750 /* For `S', prin1 the argument and then treat like a string. */
3751 register Lisp_Object tem;
3752 tem = Fprin1_to_string (args[n], Qnil);
e781c49e
RS
3753 if (STRING_MULTIBYTE (tem) && ! multibyte)
3754 {
3755 multibyte = 1;
3756 goto retry;
3757 }
35692fe0 3758 args[n] = tem;
aa8b70ae
KH
3759 /* If we restart the loop, we should not come here again
3760 because args[n] is now a string and calling
3761 Fprin1_to_string on it produces superflous double
3762 quotes. So, change "%S" to "%s" now. */
3763 *format = 's';
35692fe0
JB
3764 goto string;
3765 }
ae683129 3766 else if (SYMBOLP (args[n]))
35692fe0 3767 {
1e5d9116 3768 args[n] = SYMBOL_NAME (args[n]);
7df74da6
RS
3769 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3770 {
3771 multibyte = 1;
3772 goto retry;
3773 }
35692fe0
JB
3774 goto string;
3775 }
ae683129 3776 else if (STRINGP (args[n]))
35692fe0
JB
3777 {
3778 string:
b22e7ecc 3779 if (*format != 's' && *format != 'S')
bf6ab66c 3780 error ("Format specifier doesn't match argument type");
ac42d7b9
KG
3781 /* In the case (PRECISION[N] > 0), THISSIZE may not need
3782 to be as large as is calculated here. Easy check for
3783 the case PRECISION = 0. */
3784 thissize = precision[n] ? CONVERTED_BYTE_SIZE (multibyte, args[n]) : 0;
308dd672 3785 actual_width = lisp_string_width (args[n], -1, NULL, NULL);
35692fe0
JB
3786 }
3787 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
ae683129 3788 else if (INTEGERP (args[n]) && *format != 's')
35692fe0 3789 {
eb8c3be9 3790 /* The following loop assumes the Lisp type indicates
35692fe0
JB
3791 the proper way to pass the argument.
3792 So make sure we have a flonum if the argument should
3793 be a double. */
3794 if (*format == 'e' || *format == 'f' || *format == 'g')
3795 args[n] = Ffloat (args[n]);
4224cb62 3796 else
4224cb62 3797 if (*format != 'd' && *format != 'o' && *format != 'x'
00d65216 3798 && *format != 'i' && *format != 'X' && *format != 'c')
4224cb62
KH
3799 error ("Invalid format operation %%%c", *format);
3800
0e4df721 3801 thissize = 30 + (precision[n] > 0 ? precision[n] : 0);
063b53b1 3802 if (*format == 'c')
f49a2d74 3803 {
8f924df7 3804 if (! ASCII_CHAR_P (XINT (args[n]))
231a3316
KH
3805 /* Note: No one can remeber why we have to treat
3806 the character 0 as a multibyte character here.
3807 But, until it causes a real problem, let's
3808 don't change it. */
063b53b1 3809 || XINT (args[n]) == 0)
f49a2d74 3810 {
063b53b1
KH
3811 if (! multibyte)
3812 {
3813 multibyte = 1;
3814 goto retry;
3815 }
3816 args[n] = Fchar_to_string (args[n]);
3817 thissize = SBYTES (args[n]);
3818 }
3819 else if (! ASCII_BYTE_P (XINT (args[n])) && multibyte)
3820 {
3821 args[n]
3822 = Fchar_to_string (Funibyte_char_to_multibyte (args[n]));
3823 thissize = SBYTES (args[n]);
f49a2d74 3824 }
f49a2d74 3825 }
35692fe0 3826 }
ae683129 3827 else if (FLOATP (args[n]) && *format != 's')
35692fe0
JB
3828 {
3829 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
f98176d2
RS
3830 {
3831 if (*format != 'd' && *format != 'o' && *format != 'x'
3832 && *format != 'i' && *format != 'X' && *format != 'c')
3833 error ("Invalid format operation %%%c", *format);
c5c6b2cc
SM
3834 /* This fails unnecessarily if args[n] is bigger than
3835 most-positive-fixnum but smaller than MAXINT.
3836 These cases are important because we sometimes use floats
3837 to represent such integer values (typically such values
3838 come from UIDs or PIDs). */
3839 /* args[n] = Ftruncate (args[n], Qnil); */
f98176d2 3840 }
a432bfe5
GM
3841
3842 /* Note that we're using sprintf to print floats,
3843 so we have to take into account what that function
3844 prints. */
b11f1d8a 3845 /* Filter out flag value of -1. */
6b381c3a
RS
3846 thissize = (MAX_10_EXP + 100
3847 + (precision[n] > 0 ? precision[n] : 0));
35692fe0
JB
3848 }
3849 else
3850 {
3851 /* Anything but a string, convert to a string using princ. */
3852 register Lisp_Object tem;
3853 tem = Fprin1_to_string (args[n], Qt);
f555f8cf 3854 if (STRING_MULTIBYTE (tem) && ! multibyte)
e781c49e
RS
3855 {
3856 multibyte = 1;
3857 goto retry;
3858 }
35692fe0
JB
3859 args[n] = tem;
3860 goto string;
3861 }
34a7a267 3862
308dd672 3863 thissize += max (0, field_width - actual_width);
1f24f4fd 3864 total += thissize + 4;
35692fe0
JB
3865 }
3866
67965a98
RS
3867 abort_on_gc--;
3868
e781c49e
RS
3869 /* Now we can no longer jump to retry.
3870 TOTAL and LONGEST_FORMAT are known for certain. */
3871
1f24f4fd 3872 this_format = (unsigned char *) alloca (longest_format + 1);
50aa2f90 3873
1f24f4fd
RS
3874 /* Allocate the space for the result.
3875 Note that TOTAL is an overestimate. */
7e2c051b 3876 SAFE_ALLOCA (buf, char *, total);
35692fe0 3877
1f24f4fd
RS
3878 p = buf;
3879 nchars = 0;
3880 n = 0;
35692fe0 3881
1f24f4fd 3882 /* Scan the format and store result in BUF. */
d5db4077 3883 format = SDATA (args[0]);
67965a98
RS
3884 format_start = format;
3885 end = format + SBYTES (args[0]);
8f2917e4 3886 maybe_combine_byte = 0;
1f24f4fd
RS
3887 while (format != end)
3888 {
3889 if (*format == '%')
3890 {
3891 int minlen;
25c9e7fb 3892 int negative = 0;
1f24f4fd 3893 unsigned char *this_format_start = format;
35692fe0 3894
d147ee84 3895 discarded[format - format_start] = 1;
1f24f4fd 3896 format++;
fb893977 3897
cb06e570 3898 while (index("-+0# ", *format))
f555f8cf
KH
3899 {
3900 if (*format == '-')
3901 {
3902 negative = 1;
3903 }
3904 discarded[format - format_start] = 1;
3905 ++format;
3906 }
3907
1f24f4fd 3908 minlen = atoi (format);
f555f8cf
KH
3909
3910 while ((*format >= '0' && *format <= '9') || *format == '.')
d147ee84
RS
3911 {
3912 discarded[format - format_start] = 1;
3913 format++;
3914 }
35692fe0 3915
1f24f4fd
RS
3916 if (*format++ == '%')
3917 {
3918 *p++ = '%';
3919 nchars++;
3920 continue;
3921 }
3922
3923 ++n;
3924
d147ee84
RS
3925 discarded[format - format_start - 1] = 1;
3926 info[n].start = nchars;
3927
1f24f4fd
RS
3928 if (STRINGP (args[n]))
3929 {
ac42d7b9
KG
3930 /* handle case (precision[n] >= 0) */
3931
3932 int width, padding;
3933 int nbytes, start, end;
3934 int nchars_string;
3935
3936 /* lisp_string_width ignores a precision of 0, but GNU
3937 libc functions print 0 characters when the precision
3938 is 0. Imitate libc behavior here. Changing
3939 lisp_string_width is the right thing, and will be
3940 done, but meanwhile we work with it. */
3941
3942 if (precision[n] == 0)
3943 width = nchars_string = nbytes = 0;
3944 else if (precision[n] > 0)
3945 width = lisp_string_width (args[n], precision[n], &nchars_string, &nbytes);
3946 else
3947 { /* no precision spec given for this argument */
3948 width = lisp_string_width (args[n], -1, NULL, NULL);
3949 nbytes = SBYTES (args[n]);
3950 nchars_string = SCHARS (args[n]);
3951 }
25c9e7fb
RS
3952
3953 /* If spec requires it, pad on right with spaces. */
3954 padding = minlen - width;
3955 if (! negative)
3956 while (padding-- > 0)
3957 {
3958 *p++ = ' ';
50606b4c 3959 ++nchars;
25c9e7fb 3960 }
1f24f4fd 3961
8f2c9ed8 3962 info[n].start = start = nchars;
ac42d7b9
KG
3963 nchars += nchars_string;
3964 end = nchars;
3965
8f2917e4
KH
3966 if (p > buf
3967 && multibyte
25aa5d64 3968 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
8f2917e4 3969 && STRING_MULTIBYTE (args[n])
d5db4077 3970 && !CHAR_HEAD_P (SREF (args[n], 0)))
8f2917e4 3971 maybe_combine_byte = 1;
ac42d7b9
KG
3972
3973 p += copy_text (SDATA (args[n]), p,
3974 nbytes,
3975 STRING_MULTIBYTE (args[n]), multibyte);
1f24f4fd 3976
8f2c9ed8
RS
3977 info[n].end = nchars;
3978
25c9e7fb
RS
3979 if (negative)
3980 while (padding-- > 0)
3981 {
3982 *p++ = ' ';
3983 nchars++;
3984 }
5e6d5493
GM
3985
3986 /* If this argument has text properties, record where
3987 in the result string it appears. */
d5db4077 3988 if (STRING_INTERVALS (args[n]))
d147ee84 3989 info[n].intervals = arg_intervals = 1;
1f24f4fd
RS
3990 }
3991 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3992 {
3993 int this_nchars;
3994
3995 bcopy (this_format_start, this_format,
3996 format - this_format_start);
3997 this_format[format - this_format_start] = 0;
3998
0f860bd7
AS
3999 if (format[-1] == 'e' || format[-1] == 'f' || format[-1] == 'g')
4000 sprintf (p, this_format, XFLOAT_DATA (args[n]));
4001 else
de92d4d4 4002 {
ff6e6ac8
AS
4003 if (sizeof (EMACS_INT) > sizeof (int)
4004 && format[-1] != 'c')
0f860bd7
AS
4005 {
4006 /* Insert 'l' before format spec. */
4007 this_format[format - this_format_start]
4008 = this_format[format - this_format_start - 1];
4009 this_format[format - this_format_start - 1] = 'l';
4010 this_format[format - this_format_start + 1] = 0;
4011 }
4012
ff6e6ac8
AS
4013 if (INTEGERP (args[n]))
4014 {
4015 if (format[-1] == 'c')
4016 sprintf (p, this_format, (int) XINT (args[n]));
4017 else if (format[-1] == 'd')
4018 sprintf (p, this_format, XINT (args[n]));
4019 /* Don't sign-extend for octal or hex printing. */
4020 else
4021 sprintf (p, this_format, XUINT (args[n]));
4022 }
4023 else if (format[-1] == 'c')
4024 sprintf (p, this_format, (int) XFLOAT_DATA (args[n]));
4025 else if (format[-1] == 'd')
4026 /* Maybe we should use "%1.0f" instead so it also works
4027 for values larger than MAXINT. */
4028 sprintf (p, this_format, (EMACS_INT) XFLOAT_DATA (args[n]));
de92d4d4 4029 else
0f860bd7 4030 /* Don't sign-extend for octal or hex printing. */
ff6e6ac8 4031 sprintf (p, this_format, (EMACS_UINT) XFLOAT_DATA (args[n]));
de92d4d4 4032 }
1f24f4fd 4033
8f2917e4
KH
4034 if (p > buf
4035 && multibyte
25aa5d64
KH
4036 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4037 && !CHAR_HEAD_P (*((unsigned char *) p)))
8f2917e4 4038 maybe_combine_byte = 1;
1f24f4fd 4039 this_nchars = strlen (p);
9a599130 4040 if (multibyte)
7e2c051b 4041 p += str_to_multibyte (p, buf + total - 1 - p, this_nchars);
9a599130
KH
4042 else
4043 p += this_nchars;
1f24f4fd 4044 nchars += this_nchars;
8f2c9ed8 4045 info[n].end = nchars;
1f24f4fd 4046 }
d147ee84 4047
1f24f4fd 4048 }
7df74da6
RS
4049 else if (STRING_MULTIBYTE (args[0]))
4050 {
4051 /* Copy a whole multibyte character. */
8f2917e4
KH
4052 if (p > buf
4053 && multibyte
25aa5d64
KH
4054 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4055 && !CHAR_HEAD_P (*format))
8f2917e4 4056 maybe_combine_byte = 1;
7df74da6 4057 *p++ = *format++;
d147ee84
RS
4058 while (! CHAR_HEAD_P (*format))
4059 {
4060 discarded[format - format_start] = 2;
4061 *p++ = *format++;
4062 }
7df74da6
RS
4063 nchars++;
4064 }
4065 else if (multibyte)
1f24f4fd
RS
4066 {
4067 /* Convert a single-byte character to multibyte. */
4068 int len = copy_text (format, p, 1, 0, 1);
4069
4070 p += len;
4071 format++;
4072 nchars++;
4073 }
4074 else
4075 *p++ = *format++, nchars++;
4076 }
4077
7e2c051b 4078 if (p > buf + total)
a432bfe5
GM
4079 abort ();
4080
8f2917e4
KH
4081 if (maybe_combine_byte)
4082 nchars = multibyte_chars_in_text (buf, p - buf);
5f75e666 4083 val = make_specified_string (buf, nchars, p - buf, multibyte);
8d6179dc 4084
1f24f4fd 4085 /* If we allocated BUF with malloc, free it too. */
e65837df 4086 SAFE_FREE ();
35692fe0 4087
5e6d5493
GM
4088 /* If the format string has text properties, or any of the string
4089 arguments has text properties, set up text properties of the
4090 result string. */
34a7a267 4091
d147ee84 4092 if (STRING_INTERVALS (args[0]) || arg_intervals)
5e6d5493
GM
4093 {
4094 Lisp_Object len, new_len, props;
4095 struct gcpro gcpro1;
34a7a267 4096
5e6d5493 4097 /* Add text properties from the format string. */
d5db4077 4098 len = make_number (SCHARS (args[0]));
5e6d5493
GM
4099 props = text_property_list (args[0], make_number (0), len, Qnil);
4100 GCPRO1 (props);
34a7a267 4101
5e6d5493
GM
4102 if (CONSP (props))
4103 {
d147ee84
RS
4104 int bytepos = 0, position = 0, translated = 0, argn = 1;
4105 Lisp_Object list;
4106
4107 /* Adjust the bounds of each text property
4108 to the proper start and end in the output string. */
d147ee84 4109
15fad037
KS
4110 /* Put the positions in PROPS in increasing order, so that
4111 we can do (effectively) one scan through the position
4112 space of the format string. */
4113 props = Fnreverse (props);
4114
4115 /* BYTEPOS is the byte position in the format string,
d147ee84
RS
4116 POSITION is the untranslated char position in it,
4117 TRANSLATED is the translated char position in BUF,
4118 and ARGN is the number of the next arg we will come to. */
4119 for (list = props; CONSP (list); list = XCDR (list))
4120 {
f3ce1df8
SM
4121 Lisp_Object item;
4122 int pos;
d147ee84
RS
4123
4124 item = XCAR (list);
4125
4126 /* First adjust the property start position. */
4127 pos = XINT (XCAR (item));
4128
4129 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4130 up to this position. */
4131 for (; position < pos; bytepos++)
4132 {
4133 if (! discarded[bytepos])
4134 position++, translated++;
4135 else if (discarded[bytepos] == 1)
4136 {
4137 position++;
4138 if (translated == info[argn].start)
4139 {
4140 translated += info[argn].end - info[argn].start;
4141 argn++;
4142 }
4143 }
4144 }
4145
4146 XSETCAR (item, make_number (translated));
4147
4148 /* Likewise adjust the property end position. */
4149 pos = XINT (XCAR (XCDR (item)));
4150
d40ec4a0 4151 for (; position < pos; bytepos++)
d147ee84
RS
4152 {
4153 if (! discarded[bytepos])
4154 position++, translated++;
4155 else if (discarded[bytepos] == 1)
4156 {
4157 position++;
4158 if (translated == info[argn].start)
4159 {
4160 translated += info[argn].end - info[argn].start;
4161 argn++;
4162 }
4163 }
4164 }
4165
4166 XSETCAR (XCDR (item), make_number (translated));
4167 }
4168
5e6d5493
GM
4169 add_text_properties_from_list (val, props, make_number (0));
4170 }
4171
4172 /* Add text properties from arguments. */
d147ee84 4173 if (arg_intervals)
5e6d5493 4174 for (n = 1; n < nargs; ++n)
d147ee84 4175 if (info[n].intervals)
5e6d5493 4176 {
d5db4077 4177 len = make_number (SCHARS (args[n]));
5e6d5493
GM
4178 new_len = make_number (info[n].end - info[n].start);
4179 props = text_property_list (args[n], make_number (0), len, Qnil);
e398c61c
CY
4180 props = extend_property_ranges (props, new_len);
4181 /* If successive arguments have properties, be sure that
be17069b
KH
4182 the value of `composition' property be the copy. */
4183 if (n > 1 && info[n - 1].end)
4184 make_composition_value_copy (props);
5e6d5493
GM
4185 add_text_properties_from_list (val, props,
4186 make_number (info[n].start));
4187 }
4188
4189 UNGCPRO;
4190 }
4191
8d6179dc 4192 return val;
35692fe0
JB
4193}
4194
35692fe0 4195Lisp_Object
d40dc1d0 4196format2 (string1, arg0, arg1)
35692fe0 4197 char *string1;
d40dc1d0
RS
4198 Lisp_Object arg0, arg1;
4199{
4200 Lisp_Object args[3];
d40dc1d0
RS
4201 args[0] = build_string (string1);
4202 args[1] = arg0;
4203 args[2] = arg1;
4204 return Fformat (3, args);
35692fe0
JB
4205}
4206\f
4207DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
7ee72033 4208 doc: /* Return t if two characters match, optionally ignoring case.
a1f17501 4209Both arguments must be characters (i.e. integers).
7ee72033
MB
4210Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4211 (c1, c2)
35692fe0
JB
4212 register Lisp_Object c1, c2;
4213{
1b5d98bb 4214 int i1, i2;
253c3c82
SM
4215 /* Check they're chars, not just integers, otherwise we could get array
4216 bounds violations in DOWNCASE. */
4217 CHECK_CHARACTER (c1);
4218 CHECK_CHARACTER (c2);
35692fe0 4219
1b5d98bb 4220 if (XINT (c1) == XINT (c2))
35692fe0 4221 return Qt;
1b5d98bb
RS
4222 if (NILP (current_buffer->case_fold_search))
4223 return Qnil;
4224
4225 /* Do these in separate statements,
4226 then compare the variables.
4227 because of the way DOWNCASE uses temp variables. */
e5112ecb
KH
4228 i1 = XFASTINT (c1);
4229 if (NILP (current_buffer->enable_multibyte_characters)
4230 && ! ASCII_CHAR_P (i1))
4231 {
4232 MAKE_CHAR_MULTIBYTE (i1);
4233 }
4234 i2 = XFASTINT (c2);
4235 if (NILP (current_buffer->enable_multibyte_characters)
4236 && ! ASCII_CHAR_P (i2))
4237 {
4238 MAKE_CHAR_MULTIBYTE (i2);
4239 }
4240 i1 = DOWNCASE (i1);
4241 i2 = DOWNCASE (i2);
1b5d98bb 4242 return (i1 == i2 ? Qt : Qnil);
35692fe0 4243}
b229b8d1
RS
4244\f
4245/* Transpose the markers in two regions of the current buffer, and
4246 adjust the ones between them if necessary (i.e.: if the regions
4247 differ in size).
4248
ec1c14f6
RS
4249 START1, END1 are the character positions of the first region.
4250 START1_BYTE, END1_BYTE are the byte positions.
4251 START2, END2 are the character positions of the second region.
4252 START2_BYTE, END2_BYTE are the byte positions.
4253
b229b8d1
RS
4254 Traverses the entire marker list of the buffer to do so, adding an
4255 appropriate amount to some, subtracting from some, and leaving the
4256 rest untouched. Most of this is copied from adjust_markers in insdel.c.
34a7a267 4257
ec1c14f6 4258 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
b229b8d1 4259
acb7cc89 4260static void
ec1c14f6
RS
4261transpose_markers (start1, end1, start2, end2,
4262 start1_byte, end1_byte, start2_byte, end2_byte)
b229b8d1 4263 register int start1, end1, start2, end2;
ec1c14f6 4264 register int start1_byte, end1_byte, start2_byte, end2_byte;
b229b8d1 4265{
ec1c14f6 4266 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
12038f9f 4267 register struct Lisp_Marker *marker;
b229b8d1 4268
03240d11 4269 /* Update point as if it were a marker. */
8de1d5f0
KH
4270 if (PT < start1)
4271 ;
4272 else if (PT < end1)
ec1c14f6
RS
4273 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4274 PT_BYTE + (end2_byte - end1_byte));
8de1d5f0 4275 else if (PT < start2)
ec1c14f6
RS
4276 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4277 (PT_BYTE + (end2_byte - start2_byte)
4278 - (end1_byte - start1_byte)));
8de1d5f0 4279 else if (PT < end2)
ec1c14f6
RS
4280 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4281 PT_BYTE - (start2_byte - start1_byte));
8de1d5f0 4282
03240d11
KH
4283 /* We used to adjust the endpoints here to account for the gap, but that
4284 isn't good enough. Even if we assume the caller has tried to move the
4285 gap out of our way, it might still be at start1 exactly, for example;
4286 and that places it `inside' the interval, for our purposes. The amount
4287 of adjustment is nontrivial if there's a `denormalized' marker whose
4288 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4289 the dirty work to Fmarker_position, below. */
b229b8d1
RS
4290
4291 /* The difference between the region's lengths */
4292 diff = (end2 - start2) - (end1 - start1);
ec1c14f6 4293 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
34a7a267 4294
b229b8d1 4295 /* For shifting each marker in a region by the length of the other
ec1c14f6 4296 region plus the distance between the regions. */
b229b8d1
RS
4297 amt1 = (end2 - start2) + (start2 - end1);
4298 amt2 = (end1 - start1) + (start2 - end1);
ec1c14f6
RS
4299 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4300 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
b229b8d1 4301
12038f9f 4302 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
b229b8d1 4303 {
12038f9f 4304 mpos = marker->bytepos;
ec1c14f6
RS
4305 if (mpos >= start1_byte && mpos < end2_byte)
4306 {
4307 if (mpos < end1_byte)
4308 mpos += amt1_byte;
4309 else if (mpos < start2_byte)
4310 mpos += diff_byte;
4311 else
4312 mpos -= amt2_byte;
12038f9f 4313 marker->bytepos = mpos;
ec1c14f6 4314 }
12038f9f 4315 mpos = marker->charpos;
03240d11
KH
4316 if (mpos >= start1 && mpos < end2)
4317 {
4318 if (mpos < end1)
4319 mpos += amt1;
4320 else if (mpos < start2)
4321 mpos += diff;
4322 else
4323 mpos -= amt2;
03240d11 4324 }
12038f9f 4325 marker->charpos = mpos;
b229b8d1
RS
4326 }
4327}
4328
4329DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
412f1fab 4330 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
27a69fd9 4331The regions should not be overlapping, because the size of the buffer is
a1f17501
PJ
4332never changed in a transposition.
4333
412f1fab 4334Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
a1f17501
PJ
4335any markers that happen to be located in the regions.
4336
7ee72033
MB
4337Transposing beyond buffer boundaries is an error. */)
4338 (startr1, endr1, startr2, endr2, leave_markers)
b229b8d1
RS
4339 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
4340{
d47ecf8b
SM
4341 register EMACS_INT start1, end1, start2, end2;
4342 EMACS_INT start1_byte, start2_byte, len1_byte, len2_byte;
4343 EMACS_INT gap, len1, len_mid, len2;
3c6bc7d0 4344 unsigned char *start1_addr, *start2_addr, *temp;
b229b8d1 4345
6cd0f478 4346 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
916480c4
CY
4347 Lisp_Object buf;
4348
4349 XSETBUFFER (buf, current_buffer);
1e158d25 4350 cur_intv = BUF_INTERVALS (current_buffer);
b229b8d1
RS
4351
4352 validate_region (&startr1, &endr1);
4353 validate_region (&startr2, &endr2);
4354
4355 start1 = XFASTINT (startr1);
4356 end1 = XFASTINT (endr1);
4357 start2 = XFASTINT (startr2);
4358 end2 = XFASTINT (endr2);
4359 gap = GPT;
4360
4361 /* Swap the regions if they're reversed. */
4362 if (start2 < end1)
4363 {
4364 register int glumph = start1;
4365 start1 = start2;
4366 start2 = glumph;
4367 glumph = end1;
4368 end1 = end2;
4369 end2 = glumph;
4370 }
4371
b229b8d1
RS
4372 len1 = end1 - start1;
4373 len2 = end2 - start2;
4374
4375 if (start2 < end1)
dc3620af 4376 error ("Transposed regions overlap");
b229b8d1 4377 else if (start1 == end1 || start2 == end2)
dc3620af 4378 error ("Transposed region has length 0");
b229b8d1
RS
4379
4380 /* The possibilities are:
4381 1. Adjacent (contiguous) regions, or separate but equal regions
4382 (no, really equal, in this case!), or
4383 2. Separate regions of unequal size.
34a7a267 4384
b229b8d1
RS
4385 The worst case is usually No. 2. It means that (aside from
4386 potential need for getting the gap out of the way), there also
4387 needs to be a shifting of the text between the two regions. So
4388 if they are spread far apart, we are that much slower... sigh. */
4389
4390 /* It must be pointed out that the really studly thing to do would
4391 be not to move the gap at all, but to leave it in place and work
4392 around it if necessary. This would be extremely efficient,
4393 especially considering that people are likely to do
4394 transpositions near where they are working interactively, which
4395 is exactly where the gap would be found. However, such code
4396 would be much harder to write and to read. So, if you are
4397 reading this comment and are feeling squirrely, by all means have
4398 a go! I just didn't feel like doing it, so I will simply move
4399 the gap the minimum distance to get it out of the way, and then
4400 deal with an unbroken array. */
3c6bc7d0
RS
4401
4402 /* Make sure the gap won't interfere, by moving it out of the text
4403 we will operate on. */
4404 if (start1 < gap && gap < end2)
4405 {
4406 if (gap - start1 < end2 - gap)
4407 move_gap (start1);
4408 else
4409 move_gap (end2);
4410 }
ec1c14f6
RS
4411
4412 start1_byte = CHAR_TO_BYTE (start1);
4413 start2_byte = CHAR_TO_BYTE (start2);
4414 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4415 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
dc3620af 4416
9a599130 4417#ifdef BYTE_COMBINING_DEBUG
dc3620af
RS
4418 if (end1 == start2)
4419 {
9a599130
KH
4420 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4421 len2_byte, start1, start1_byte)
4422 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4423 len1_byte, end2, start2_byte + len2_byte)
4424 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4425 len1_byte, end2, start2_byte + len2_byte))
4426 abort ();
dc3620af
RS
4427 }
4428 else
4429 {
9a599130
KH
4430 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4431 len2_byte, start1, start1_byte)
4432 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4433 len1_byte, start2, start2_byte)
4434 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4435 len2_byte, end1, start1_byte + len1_byte)
4436 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4437 len1_byte, end2, start2_byte + len2_byte))
4438 abort ();
dc3620af 4439 }
9a599130 4440#endif
dc3620af 4441
b229b8d1
RS
4442 /* Hmmm... how about checking to see if the gap is large
4443 enough to use as the temporary storage? That would avoid an
4444 allocation... interesting. Later, don't fool with it now. */
4445
4446 /* Working without memmove, for portability (sigh), so must be
4447 careful of overlapping subsections of the array... */
4448
4449 if (end1 == start2) /* adjacent regions */
4450 {
3e145152 4451 modify_region (current_buffer, start1, end2, 0);
b229b8d1
RS
4452 record_change (start1, len1 + len2);
4453
b229b8d1
RS
4454 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4455 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
916480c4
CY
4456 /* Don't use Fset_text_properties: that can cause GC, which can
4457 clobber objects stored in the tmp_intervals. */
6cd0f478
CY
4458 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4459 if (!NULL_INTERVAL_P (tmp_interval3))
4460 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
b229b8d1
RS
4461
4462 /* First region smaller than second. */
ec1c14f6 4463 if (len1_byte < len2_byte)
b229b8d1 4464 {
7e2c051b
KS
4465 USE_SAFE_ALLOCA;
4466
4467 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
03240d11
KH
4468
4469 /* Don't precompute these addresses. We have to compute them
4470 at the last minute, because the relocating allocator might
4471 have moved the buffer around during the xmalloc. */
23017390
KH
4472 start1_addr = BYTE_POS_ADDR (start1_byte);
4473 start2_addr = BYTE_POS_ADDR (start2_byte);
03240d11 4474
ec1c14f6
RS
4475 bcopy (start2_addr, temp, len2_byte);
4476 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
4477 bcopy (temp, start1_addr, len2_byte);
e65837df 4478 SAFE_FREE ();
b229b8d1
RS
4479 }
4480 else
4481 /* First region not smaller than second. */
4482 {
7e2c051b
KS
4483 USE_SAFE_ALLOCA;
4484
4485 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
23017390
KH
4486 start1_addr = BYTE_POS_ADDR (start1_byte);
4487 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
4488 bcopy (start1_addr, temp, len1_byte);
4489 bcopy (start2_addr, start1_addr, len2_byte);
4490 bcopy (temp, start1_addr + len2_byte, len1_byte);
e65837df 4491 SAFE_FREE ();
b229b8d1 4492 }
b229b8d1
RS
4493 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4494 len1, current_buffer, 0);
4495 graft_intervals_into_buffer (tmp_interval2, start1,
4496 len2, current_buffer, 0);
d5c2c403
KH
4497 update_compositions (start1, start1 + len2, CHECK_BORDER);
4498 update_compositions (start1 + len2, end2, CHECK_TAIL);
b229b8d1
RS
4499 }
4500 /* Non-adjacent regions, because end1 != start2, bleagh... */
4501 else
4502 {
ec1c14f6
RS
4503 len_mid = start2_byte - (start1_byte + len1_byte);
4504
4505 if (len1_byte == len2_byte)
b229b8d1
RS
4506 /* Regions are same size, though, how nice. */
4507 {
7e2c051b
KS
4508 USE_SAFE_ALLOCA;
4509
3e145152
CY
4510 modify_region (current_buffer, start1, end1, 0);
4511 modify_region (current_buffer, start2, end2, 0);
b229b8d1
RS
4512 record_change (start1, len1);
4513 record_change (start2, len2);
b229b8d1
RS
4514 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4515 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
6cd0f478
CY
4516
4517 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4518 if (!NULL_INTERVAL_P (tmp_interval3))
4519 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4520
4521 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4522 if (!NULL_INTERVAL_P (tmp_interval3))
4523 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
b229b8d1 4524
7e2c051b 4525 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
23017390
KH
4526 start1_addr = BYTE_POS_ADDR (start1_byte);
4527 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
4528 bcopy (start1_addr, temp, len1_byte);
4529 bcopy (start2_addr, start1_addr, len2_byte);
4530 bcopy (temp, start2_addr, len1_byte);
e65837df 4531 SAFE_FREE ();
7e2c051b 4532
b229b8d1
RS
4533 graft_intervals_into_buffer (tmp_interval1, start2,
4534 len1, current_buffer, 0);
4535 graft_intervals_into_buffer (tmp_interval2, start1,
4536 len2, current_buffer, 0);
b229b8d1
RS
4537 }
4538
ec1c14f6 4539 else if (len1_byte < len2_byte) /* Second region larger than first */
b229b8d1
RS
4540 /* Non-adjacent & unequal size, area between must also be shifted. */
4541 {
7e2c051b
KS
4542 USE_SAFE_ALLOCA;
4543
3e145152 4544 modify_region (current_buffer, start1, end2, 0);
b229b8d1 4545 record_change (start1, (end2 - start1));
b229b8d1
RS
4546 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4547 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4548 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
6cd0f478
CY
4549
4550 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4551 if (!NULL_INTERVAL_P (tmp_interval3))
4552 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
b229b8d1 4553
3c6bc7d0 4554 /* holds region 2 */
7e2c051b 4555 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
23017390
KH
4556 start1_addr = BYTE_POS_ADDR (start1_byte);
4557 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
4558 bcopy (start2_addr, temp, len2_byte);
4559 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
4560 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4561 bcopy (temp, start1_addr, len2_byte);
e65837df 4562 SAFE_FREE ();
7e2c051b 4563
b229b8d1
RS
4564 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4565 len1, current_buffer, 0);
4566 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4567 len_mid, current_buffer, 0);
4568 graft_intervals_into_buffer (tmp_interval2, start1,
4569 len2, current_buffer, 0);
b229b8d1
RS
4570 }
4571 else
4572 /* Second region smaller than first. */
4573 {
7e2c051b
KS
4574 USE_SAFE_ALLOCA;
4575
b229b8d1 4576 record_change (start1, (end2 - start1));
3e145152 4577 modify_region (current_buffer, start1, end2, 0);
b229b8d1 4578
b229b8d1
RS
4579 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4580 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4581 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
6cd0f478
CY
4582
4583 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4584 if (!NULL_INTERVAL_P (tmp_interval3))
4585 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
b229b8d1 4586
3c6bc7d0 4587 /* holds region 1 */
7e2c051b 4588 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
23017390
KH
4589 start1_addr = BYTE_POS_ADDR (start1_byte);
4590 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
4591 bcopy (start1_addr, temp, len1_byte);
4592 bcopy (start2_addr, start1_addr, len2_byte);
4593 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4594 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
e65837df 4595 SAFE_FREE ();
7e2c051b 4596
b229b8d1
RS
4597 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4598 len1, current_buffer, 0);
4599 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4600 len_mid, current_buffer, 0);
4601 graft_intervals_into_buffer (tmp_interval2, start1,
4602 len2, current_buffer, 0);
b229b8d1 4603 }
d5c2c403
KH
4604
4605 update_compositions (start1, start1 + len2, CHECK_BORDER);
4606 update_compositions (end2 - len1, end2, CHECK_BORDER);
b229b8d1
RS
4607 }
4608
ec1c14f6
RS
4609 /* When doing multiple transpositions, it might be nice
4610 to optimize this. Perhaps the markers in any one buffer
4611 should be organized in some sorted data tree. */
b229b8d1 4612 if (NILP (leave_markers))
8de1d5f0 4613 {
ec1c14f6
RS
4614 transpose_markers (start1, end1, start2, end2,
4615 start1_byte, start1_byte + len1_byte,
4616 start2_byte, start2_byte + len2_byte);
6b61353c 4617 fix_start_end_in_overlays (start1, end2);
8de1d5f0 4618 }
b229b8d1 4619
c10b2810 4620 signal_after_change (start1, end2 - start1, end2 - start1);
b229b8d1
RS
4621 return Qnil;
4622}
35692fe0 4623
35692fe0
JB
4624\f
4625void
4626syms_of_editfns ()
4627{
260e2e2a 4628 environbuf = 0;
a03fc5a6 4629 initial_tz = 0;
260e2e2a
KH
4630
4631 Qbuffer_access_fontify_functions
d67b4f80 4632 = intern_c_string ("buffer-access-fontify-functions");
260e2e2a
KH
4633 staticpro (&Qbuffer_access_fontify_functions);
4634
7ee72033 4635 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
7dcece14 4636 doc: /* Non-nil means text motion commands don't notice fields. */);
9a74e7e5
GM
4637 Vinhibit_field_text_motion = Qnil;
4638
260e2e2a 4639 DEFVAR_LISP ("buffer-access-fontify-functions",
7ee72033
MB
4640 &Vbuffer_access_fontify_functions,
4641 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
a1f17501
PJ
4642Each function is called with two arguments which specify the range
4643of the buffer being accessed. */);
260e2e2a
KH
4644 Vbuffer_access_fontify_functions = Qnil;
4645
af209db8
RS
4646 {
4647 Lisp_Object obuf;
4648 extern Lisp_Object Vprin1_to_string_buffer;
4649 obuf = Fcurrent_buffer ();
4650 /* Do this here, because init_buffer_once is too early--it won't work. */
4651 Fset_buffer (Vprin1_to_string_buffer);
4652 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
d67b4f80 4653 Fset (Fmake_local_variable (intern_c_string ("buffer-access-fontify-functions")),
af209db8
RS
4654 Qnil);
4655 Fset_buffer (obuf);
4656 }
4657
0b6fd023 4658 DEFVAR_LISP ("buffer-access-fontified-property",
7ee72033
MB
4659 &Vbuffer_access_fontified_property,
4660 doc: /* Property which (if non-nil) indicates text has been fontified.
a1f17501
PJ
4661`buffer-substring' need not call the `buffer-access-fontify-functions'
4662functions if all the text being accessed has this property. */);
260e2e2a
KH
4663 Vbuffer_access_fontified_property = Qnil;
4664
7ee72033 4665 DEFVAR_LISP ("system-name", &Vsystem_name,
1a7e0117 4666 doc: /* The host name of the machine Emacs is running on. */);
34a7a267 4667
7ee72033
MB
4668 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
4669 doc: /* The full name of the user logged in. */);
f43754f6 4670
7ee72033
MB
4671 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
4672 doc: /* The user's name, taken from environment variables if possible. */);
f43754f6 4673
7ee72033
MB
4674 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
4675 doc: /* The user's name, based upon the real uid only. */);
35692fe0 4676
3bb9abc8
ST
4677 DEFVAR_LISP ("operating-system-release", &Voperating_system_release,
4678 doc: /* The release of the operating system Emacs is running on. */);
4679
0963334d 4680 defsubr (&Spropertize);
35692fe0
JB
4681 defsubr (&Schar_equal);
4682 defsubr (&Sgoto_char);
4683 defsubr (&Sstring_to_char);
4684 defsubr (&Schar_to_string);
4685 defsubr (&Sbuffer_substring);
260e2e2a 4686 defsubr (&Sbuffer_substring_no_properties);
35692fe0
JB
4687 defsubr (&Sbuffer_string);
4688
4689 defsubr (&Spoint_marker);
4690 defsubr (&Smark_marker);
4691 defsubr (&Spoint);
4692 defsubr (&Sregion_beginning);
4693 defsubr (&Sregion_end);
7df74da6 4694
0daf6e8d 4695 staticpro (&Qfield);
d67b4f80 4696 Qfield = intern_c_string ("field");
ee547125 4697 staticpro (&Qboundary);
d67b4f80 4698 Qboundary = intern_c_string ("boundary");
0daf6e8d
GM
4699 defsubr (&Sfield_beginning);
4700 defsubr (&Sfield_end);
4701 defsubr (&Sfield_string);
4702 defsubr (&Sfield_string_no_properties);
8bf64fe8 4703 defsubr (&Sdelete_field);
0daf6e8d
GM
4704 defsubr (&Sconstrain_to_field);
4705
7df74da6
RS
4706 defsubr (&Sline_beginning_position);
4707 defsubr (&Sline_end_position);
4708
35692fe0
JB
4709/* defsubr (&Smark); */
4710/* defsubr (&Sset_mark); */
4711 defsubr (&Ssave_excursion);
4bc8c7d2 4712 defsubr (&Ssave_current_buffer);
35692fe0
JB
4713
4714 defsubr (&Sbufsize);
4715 defsubr (&Spoint_max);
4716 defsubr (&Spoint_min);
4717 defsubr (&Spoint_min_marker);
4718 defsubr (&Spoint_max_marker);
c86212b9
RS
4719 defsubr (&Sgap_position);
4720 defsubr (&Sgap_size);
7df74da6 4721 defsubr (&Sposition_bytes);
3ab0732d 4722 defsubr (&Sbyte_to_position);
c9ed721d 4723
35692fe0
JB
4724 defsubr (&Sbobp);
4725 defsubr (&Seobp);
4726 defsubr (&Sbolp);
4727 defsubr (&Seolp);
850a8179
JB
4728 defsubr (&Sfollowing_char);
4729 defsubr (&Sprevious_char);
35692fe0 4730 defsubr (&Schar_after);
fb8106e8 4731 defsubr (&Schar_before);
35692fe0
JB
4732 defsubr (&Sinsert);
4733 defsubr (&Sinsert_before_markers);
be91036a
RS
4734 defsubr (&Sinsert_and_inherit);
4735 defsubr (&Sinsert_and_inherit_before_markers);
35692fe0 4736 defsubr (&Sinsert_char);
48ef988f 4737 defsubr (&Sinsert_byte);
35692fe0
JB
4738
4739 defsubr (&Suser_login_name);
4740 defsubr (&Suser_real_login_name);
4741 defsubr (&Suser_uid);
4742 defsubr (&Suser_real_uid);
4743 defsubr (&Suser_full_name);
7fd233b3 4744 defsubr (&Semacs_pid);
d940e0e4 4745 defsubr (&Scurrent_time);
4211ee7d 4746 defsubr (&Sget_internal_run_time);
a82d387c 4747 defsubr (&Sformat_time_string);
34a7a267 4748 defsubr (&Sfloat_time);
4691c06d 4749 defsubr (&Sdecode_time);
cce7b8a0 4750 defsubr (&Sencode_time);
35692fe0 4751 defsubr (&Scurrent_time_string);
c2662aea 4752 defsubr (&Scurrent_time_zone);
143cb9a9 4753 defsubr (&Sset_time_zone_rule);
35692fe0 4754 defsubr (&Ssystem_name);
35692fe0 4755 defsubr (&Smessage);
cacc3e2c
RS
4756 defsubr (&Smessage_box);
4757 defsubr (&Smessage_or_box);
b14dda8a 4758 defsubr (&Scurrent_message);
35692fe0 4759 defsubr (&Sformat);
35692fe0
JB
4760
4761 defsubr (&Sinsert_buffer_substring);
e9cf2084 4762 defsubr (&Scompare_buffer_substrings);
35692fe0 4763 defsubr (&Ssubst_char_in_region);
8583605b 4764 defsubr (&Stranslate_region_internal);
35692fe0 4765 defsubr (&Sdelete_region);
7dae4502 4766 defsubr (&Sdelete_and_extract_region);
35692fe0
JB
4767 defsubr (&Swiden);
4768 defsubr (&Snarrow_to_region);
4769 defsubr (&Ssave_restriction);
b229b8d1 4770 defsubr (&Stranspose_regions);
35692fe0 4771}
f555f8cf
KH
4772
4773/* arch-tag: fc3827d8-6f60-4067-b11e-c3218031b018
4774 (do not change this comment) */