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