(solar-sunrises-buffer): New constant.
[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 2040 set_time_zone_rule (tzstring);
c2cd06e6 2041 free (environbuf);
c59b5089
PE
2042 environbuf = environ;
2043
2044 return Qnil;
2045}
2046
e0bf9faf
PE
2047#ifdef LOCALTIME_CACHE
2048
2049/* These two values are known to load tz files in buggy implementations,
2050 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1155c453 2051 Their values shouldn't matter in non-buggy implementations.
34a7a267 2052 We don't use string literals for these strings,
1155c453
RS
2053 since if a string in the environment is in readonly
2054 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
2055 See Sun bugs 1113095 and 1114114, ``Timezone routines
2056 improperly modify environment''. */
2057
e0bf9faf
PE
2058static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
2059static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
2060
2061#endif
1155c453 2062
c59b5089
PE
2063/* Set the local time zone rule to TZSTRING.
2064 This allocates memory into `environ', which it is the caller's
2065 responsibility to free. */
acb7cc89 2066
a92ae0ce 2067void
c59b5089
PE
2068set_time_zone_rule (tzstring)
2069 char *tzstring;
2070{
2071 int envptrs;
2072 char **from, **to, **newenv;
2073
aafe5147 2074 /* Make the ENVIRON vector longer with room for TZSTRING. */
143cb9a9
RS
2075 for (from = environ; *from; from++)
2076 continue;
2077 envptrs = from - environ + 2;
2078 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
2079 + (tzstring ? strlen (tzstring) + 4 : 0));
aafe5147
RS
2080
2081 /* Add TZSTRING to the end of environ, as a value for TZ. */
143cb9a9
RS
2082 if (tzstring)
2083 {
2084 char *t = (char *) (to + envptrs);
2085 strcpy (t, "TZ=");
2086 strcat (t, tzstring);
2087 *to++ = t;
2088 }
2089
aafe5147
RS
2090 /* Copy the old environ vector elements into NEWENV,
2091 but don't copy the TZ variable.
2092 So we have only one definition of TZ, which came from TZSTRING. */
143cb9a9
RS
2093 for (from = environ; *from; from++)
2094 if (strncmp (*from, "TZ=", 3) != 0)
2095 *to++ = *from;
2096 *to = 0;
2097
2098 environ = newenv;
143cb9a9 2099
aafe5147
RS
2100 /* If we do have a TZSTRING, NEWENV points to the vector slot where
2101 the TZ variable is stored. If we do not have a TZSTRING,
2102 TO points to the vector slot which has the terminating null. */
2103
143cb9a9 2104#ifdef LOCALTIME_CACHE
aafe5147
RS
2105 {
2106 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
2107 "US/Pacific" that loads a tz file, then changes to a value like
2108 "XXX0" that does not load a tz file, and then changes back to
2109 its original value, the last change is (incorrectly) ignored.
2110 Also, if TZ changes twice in succession to values that do
2111 not load a tz file, tzset can dump core (see Sun bug#1225179).
2112 The following code works around these bugs. */
2113
aafe5147
RS
2114 if (tzstring)
2115 {
2116 /* Temporarily set TZ to a value that loads a tz file
2117 and that differs from tzstring. */
2118 char *tz = *newenv;
1155c453
RS
2119 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
2120 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
aafe5147
RS
2121 tzset ();
2122 *newenv = tz;
2123 }
2124 else
2125 {
2126 /* The implied tzstring is unknown, so temporarily set TZ to
2127 two different values that each load a tz file. */
1155c453 2128 *to = set_time_zone_rule_tz1;
aafe5147
RS
2129 to[1] = 0;
2130 tzset ();
1155c453 2131 *to = set_time_zone_rule_tz2;
aafe5147
RS
2132 tzset ();
2133 *to = 0;
2134 }
2135
2136 /* Now TZ has the desired value, and tzset can be invoked safely. */
2137 }
2138
143cb9a9
RS
2139 tzset ();
2140#endif
143cb9a9 2141}
35692fe0 2142\f
fb8106e8
KH
2143/* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2144 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2145 type of object is Lisp_String). INHERIT is passed to
2146 INSERT_FROM_STRING_FUNC as the last argument. */
2147
acb7cc89 2148static void
fb8106e8
KH
2149general_insert_function (insert_func, insert_from_string_func,
2150 inherit, nargs, args)
439e8af4 2151 void (*insert_func) P_ ((const unsigned char *, int));
1f24f4fd 2152 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
fb8106e8
KH
2153 int inherit, nargs;
2154 register Lisp_Object *args;
2155{
2156 register int argnum;
2157 register Lisp_Object val;
2158
2159 for (argnum = 0; argnum < nargs; argnum++)
2160 {
2161 val = args[argnum];
1b9c91ed 2162 if (CHARACTERP (val))
fb8106e8 2163 {
d5c2c403 2164 unsigned char str[MAX_MULTIBYTE_LENGTH];
fb8106e8
KH
2165 int len;
2166
2167 if (!NILP (current_buffer->enable_multibyte_characters))
d5c2c403 2168 len = CHAR_STRING (XFASTINT (val), str);
fb8106e8 2169 else
13c148b8 2170 {
0f8ea88f 2171 str[0] = (ASCII_CHAR_P (XINT (val))
d5c2c403
KH
2172 ? XINT (val)
2173 : multibyte_char_to_unibyte (XINT (val), Qnil));
13c148b8
KH
2174 len = 1;
2175 }
fb8106e8
KH
2176 (*insert_func) (str, len);
2177 }
2178 else if (STRINGP (val))
2179 {
1f24f4fd 2180 (*insert_from_string_func) (val, 0, 0,
d5db4077
KR
2181 SCHARS (val),
2182 SBYTES (val),
1f24f4fd 2183 inherit);
fb8106e8
KH
2184 }
2185 else
b7f34213 2186 wrong_type_argument (Qchar_or_string_p, val);
fb8106e8
KH
2187 }
2188}
2189
35692fe0
JB
2190void
2191insert1 (arg)
2192 Lisp_Object arg;
2193{
2194 Finsert (1, &arg);
2195}
2196
52b14ac0
JB
2197
2198/* Callers passing one argument to Finsert need not gcpro the
2199 argument "array", since the only element of the array will
2200 not be used after calling insert or insert_from_string, so
2201 we don't care if it gets trashed. */
2202
35692fe0 2203DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
7ee72033 2204 doc: /* Insert the arguments, either strings or characters, at point.
a1f17501
PJ
2205Point and before-insertion markers move forward to end up
2206 after the inserted text.
2207Any other markers at the point of insertion remain before the text.
2208
2209If the current buffer is multibyte, unibyte strings are converted
72bb55c6 2210to multibyte for insertion (see `string-make-multibyte').
a1f17501 2211If the current buffer is unibyte, multibyte strings are converted
72bb55c6
KS
2212to unibyte for insertion (see `string-make-unibyte').
2213
2214When operating on binary data, it may be necessary to preserve the
2215original bytes of a unibyte string when inserting it into a multibyte
2216buffer; to accomplish this, apply `string-as-multibyte' to the string
2217and insert the result.
4bfbe194
MB
2218
2219usage: (insert &rest ARGS) */)
7ee72033 2220 (nargs, args)
35692fe0
JB
2221 int nargs;
2222 register Lisp_Object *args;
2223{
fb8106e8 2224 general_insert_function (insert, insert_from_string, 0, nargs, args);
be91036a
RS
2225 return Qnil;
2226}
2227
2228DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2229 0, MANY, 0,
7ee72033 2230 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
a1f17501
PJ
2231Point and before-insertion markers move forward to end up
2232 after the inserted text.
2233Any other markers at the point of insertion remain before the text.
2234
2235If the current buffer is multibyte, unibyte strings are converted
2236to multibyte for insertion (see `unibyte-char-to-multibyte').
2237If the current buffer is unibyte, multibyte strings are converted
4bfbe194
MB
2238to unibyte for insertion.
2239
2240usage: (insert-and-inherit &rest ARGS) */)
7ee72033 2241 (nargs, args)
be91036a
RS
2242 int nargs;
2243 register Lisp_Object *args;
2244{
fb8106e8
KH
2245 general_insert_function (insert_and_inherit, insert_from_string, 1,
2246 nargs, args);
35692fe0
JB
2247 return Qnil;
2248}
2249
2250DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
7ee72033 2251 doc: /* Insert strings or characters at point, relocating markers after the text.
a1f17501
PJ
2252Point and markers move forward to end up after the inserted text.
2253
2254If the current buffer is multibyte, unibyte strings are converted
2255to multibyte for insertion (see `unibyte-char-to-multibyte').
2256If the current buffer is unibyte, multibyte strings are converted
4bfbe194
MB
2257to unibyte for insertion.
2258
2259usage: (insert-before-markers &rest ARGS) */)
7ee72033 2260 (nargs, args)
35692fe0
JB
2261 int nargs;
2262 register Lisp_Object *args;
2263{
fb8106e8
KH
2264 general_insert_function (insert_before_markers,
2265 insert_from_string_before_markers, 0,
2266 nargs, args);
be91036a
RS
2267 return Qnil;
2268}
2269
a0d76c27
EN
2270DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2271 Sinsert_and_inherit_before_markers, 0, MANY, 0,
7ee72033 2272 doc: /* Insert text at point, relocating markers and inheriting properties.
a1f17501
PJ
2273Point and markers move forward to end up after the inserted text.
2274
2275If the current buffer is multibyte, unibyte strings are converted
2276to multibyte for insertion (see `unibyte-char-to-multibyte').
2277If the current buffer is unibyte, multibyte strings are converted
4bfbe194
MB
2278to unibyte for insertion.
2279
2280usage: (insert-before-markers-and-inherit &rest ARGS) */)
7ee72033 2281 (nargs, args)
be91036a
RS
2282 int nargs;
2283 register Lisp_Object *args;
2284{
fb8106e8
KH
2285 general_insert_function (insert_before_markers_and_inherit,
2286 insert_from_string_before_markers, 1,
2287 nargs, args);
35692fe0
JB
2288 return Qnil;
2289}
2290\f
e2eeabbb 2291DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
9671c13a 2292 doc: /* Insert COUNT copies of CHARACTER.
a1f17501
PJ
2293Point, and before-insertion markers, are relocated as in the function `insert'.
2294The optional third arg INHERIT, if non-nil, says to inherit text properties
7ee72033
MB
2295from adjoining text, if those properties are sticky. */)
2296 (character, count, inherit)
2591ec64 2297 Lisp_Object character, count, inherit;
35692fe0
JB
2298{
2299 register unsigned char *string;
2300 register int strlen;
2301 register int i, n;
fb8106e8 2302 int len;
d5c2c403 2303 unsigned char str[MAX_MULTIBYTE_LENGTH];
35692fe0 2304
b7826503
PJ
2305 CHECK_NUMBER (character);
2306 CHECK_NUMBER (count);
35692fe0 2307
fb8106e8 2308 if (!NILP (current_buffer->enable_multibyte_characters))
d5c2c403 2309 len = CHAR_STRING (XFASTINT (character), str);
fb8106e8 2310 else
d5c2c403 2311 str[0] = XFASTINT (character), len = 1;
fb8106e8 2312 n = XINT (count) * len;
35692fe0
JB
2313 if (n <= 0)
2314 return Qnil;
fb8106e8 2315 strlen = min (n, 256 * len);
35692fe0
JB
2316 string = (unsigned char *) alloca (strlen);
2317 for (i = 0; i < strlen; i++)
fb8106e8 2318 string[i] = str[i % len];
35692fe0
JB
2319 while (n >= strlen)
2320 {
54e42e2d 2321 QUIT;
e2eeabbb
RS
2322 if (!NILP (inherit))
2323 insert_and_inherit (string, strlen);
2324 else
2325 insert (string, strlen);
35692fe0
JB
2326 n -= strlen;
2327 }
2328 if (n > 0)
83951f1e
KH
2329 {
2330 if (!NILP (inherit))
2331 insert_and_inherit (string, n);
2332 else
2333 insert (string, n);
2334 }
35692fe0
JB
2335 return Qnil;
2336}
2337
48ef988f
KH
2338DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2339 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2340Both arguments are required.
2341BYTE is a number of the range 0..255.
2342
2343If BYTE is 128..255 and the current buffer is multibyte, the
2344corresponding eight-bit character is inserted.
2345
2346Point, and before-insertion markers, are relocated as in the function `insert'.
2347The optional third arg INHERIT, if non-nil, says to inherit text properties
2348from adjoining text, if those properties are sticky. */)
2349 (byte, count, inherit)
2350 Lisp_Object byte, count, inherit;
2351{
2352 CHECK_NUMBER (byte);
2353 if (XINT (byte) < 0 || XINT (byte) > 255)
2354 args_out_of_range_3 (byte, make_number (0), make_number (255));
2355 if (XINT (byte) >= 128
2356 && ! NILP (current_buffer->enable_multibyte_characters))
2357 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
ed398b0a 2358 return Finsert_char (byte, count, inherit);
48ef988f
KH
2359}
2360
35692fe0 2361\f
ffd56f97
JB
2362/* Making strings from buffer contents. */
2363
2364/* Return a Lisp_String containing the text of the current buffer from
74d6d8c5 2365 START to END. If text properties are in use and the current buffer
eb8c3be9 2366 has properties in the range specified, the resulting string will also
260e2e2a 2367 have them, if PROPS is nonzero.
ffd56f97
JB
2368
2369 We don't want to use plain old make_string here, because it calls
2370 make_uninit_string, which can cause the buffer arena to be
2371 compacted. make_string has no way of knowing that the data has
2372 been moved, and thus copies the wrong data into the string. This
2373 doesn't effect most of the other users of make_string, so it should
2374 be left as is. But we should use this function when conjuring
2375 buffer substrings. */
74d6d8c5 2376
ffd56f97 2377Lisp_Object
260e2e2a 2378make_buffer_string (start, end, props)
ffd56f97 2379 int start, end;
260e2e2a 2380 int props;
ffd56f97 2381{
ec1c14f6
RS
2382 int start_byte = CHAR_TO_BYTE (start);
2383 int end_byte = CHAR_TO_BYTE (end);
ffd56f97 2384
88441c8e
RS
2385 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2386}
2387
2388/* Return a Lisp_String containing the text of the current buffer from
2389 START / START_BYTE to END / END_BYTE.
2390
2391 If text properties are in use and the current buffer
2392 has properties in the range specified, the resulting string will also
2393 have them, if PROPS is nonzero.
2394
2395 We don't want to use plain old make_string here, because it calls
2396 make_uninit_string, which can cause the buffer arena to be
2397 compacted. make_string has no way of knowing that the data has
2398 been moved, and thus copies the wrong data into the string. This
2399 doesn't effect most of the other users of make_string, so it should
2400 be left as is. But we should use this function when conjuring
2401 buffer substrings. */
2402
2403Lisp_Object
2404make_buffer_string_both (start, start_byte, end, end_byte, props)
2405 int start, start_byte, end, end_byte;
2406 int props;
2407{
2408 Lisp_Object result, tem, tem1;
2409
ffd56f97
JB
2410 if (start < GPT && GPT < end)
2411 move_gap (start);
2412
5f75e666
RS
2413 if (! NILP (current_buffer->enable_multibyte_characters))
2414 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2415 else
2416 result = make_uninit_string (end - start);
d5db4077 2417 bcopy (BYTE_POS_ADDR (start_byte), SDATA (result),
ec1c14f6 2418 end_byte - start_byte);
ffd56f97 2419
260e2e2a 2420 /* If desired, update and copy the text properties. */
260e2e2a
KH
2421 if (props)
2422 {
2423 update_buffer_properties (start, end);
2424
2425 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2426 tem1 = Ftext_properties_at (make_number (start), Qnil);
2427
2428 if (XINT (tem) != end || !NILP (tem1))
ec1c14f6
RS
2429 copy_intervals_to_string (result, current_buffer, start,
2430 end - start);
260e2e2a 2431 }
74d6d8c5 2432
ffd56f97
JB
2433 return result;
2434}
35692fe0 2435
260e2e2a
KH
2436/* Call Vbuffer_access_fontify_functions for the range START ... END
2437 in the current buffer, if necessary. */
2438
2439static void
2440update_buffer_properties (start, end)
2441 int start, end;
2442{
260e2e2a
KH
2443 /* If this buffer has some access functions,
2444 call them, specifying the range of the buffer being accessed. */
2445 if (!NILP (Vbuffer_access_fontify_functions))
2446 {
2447 Lisp_Object args[3];
2448 Lisp_Object tem;
2449
2450 args[0] = Qbuffer_access_fontify_functions;
2451 XSETINT (args[1], start);
2452 XSETINT (args[2], end);
2453
2454 /* But don't call them if we can tell that the work
2455 has already been done. */
2456 if (!NILP (Vbuffer_access_fontified_property))
2457 {
2458 tem = Ftext_property_any (args[1], args[2],
2459 Vbuffer_access_fontified_property,
2460 Qnil, Qnil);
2461 if (! NILP (tem))
ced1d19a 2462 Frun_hook_with_args (3, args);
260e2e2a
KH
2463 }
2464 else
ced1d19a 2465 Frun_hook_with_args (3, args);
260e2e2a 2466 }
260e2e2a
KH
2467}
2468
35692fe0 2469DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
7ee72033 2470 doc: /* Return the contents of part of the current buffer as a string.
a1f17501
PJ
2471The two arguments START and END are character positions;
2472they can be in either order.
2473The string returned is multibyte if the buffer is multibyte.
2474
2475This function copies the text properties of that part of the buffer
2476into the result string; if you don't want the text properties,
7ee72033
MB
2477use `buffer-substring-no-properties' instead. */)
2478 (start, end)
2591ec64 2479 Lisp_Object start, end;
35692fe0 2480{
2591ec64 2481 register int b, e;
35692fe0 2482
2591ec64
EN
2483 validate_region (&start, &end);
2484 b = XINT (start);
2485 e = XINT (end);
35692fe0 2486
2591ec64 2487 return make_buffer_string (b, e, 1);
260e2e2a
KH
2488}
2489
2490DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2491 Sbuffer_substring_no_properties, 2, 2, 0,
7ee72033 2492 doc: /* Return the characters of part of the buffer, without the text properties.
a1f17501 2493The two arguments START and END are character positions;
7ee72033
MB
2494they can be in either order. */)
2495 (start, end)
2591ec64 2496 Lisp_Object start, end;
260e2e2a 2497{
2591ec64 2498 register int b, e;
260e2e2a 2499
2591ec64
EN
2500 validate_region (&start, &end);
2501 b = XINT (start);
2502 e = XINT (end);
260e2e2a 2503
2591ec64 2504 return make_buffer_string (b, e, 0);
35692fe0
JB
2505}
2506
2507DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
7ee72033 2508 doc: /* Return the contents of the current buffer as a string.
a1f17501 2509If narrowing is in effect, this function returns only the visible part
7ee72033
MB
2510of the buffer. */)
2511 ()
35692fe0 2512{
0daf6e8d 2513 return make_buffer_string (BEGV, ZV, 1);
35692fe0
JB
2514}
2515
2516DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
deb8e082 2517 1, 3, 0,
658ec670 2518 doc: /* Insert before point a substring of the contents of BUFFER.
a1f17501 2519BUFFER may be a buffer or a buffer name.
412f1fab
JB
2520Arguments START and END are character positions specifying the substring.
2521They default to the values of (point-min) and (point-max) in BUFFER. */)
658ec670
JB
2522 (buffer, start, end)
2523 Lisp_Object buffer, start, end;
35692fe0 2524{
2591ec64 2525 register int b, e, temp;
260e2e2a 2526 register struct buffer *bp, *obuf;
658ec670 2527 Lisp_Object buf;
35692fe0 2528
658ec670
JB
2529 buf = Fget_buffer (buffer);
2530 if (NILP (buf))
2531 nsberror (buffer);
2532 bp = XBUFFER (buf);
93b62e82
KH
2533 if (NILP (bp->name))
2534 error ("Selecting deleted buffer");
35692fe0 2535
2591ec64
EN
2536 if (NILP (start))
2537 b = BUF_BEGV (bp);
35692fe0
JB
2538 else
2539 {
b7826503 2540 CHECK_NUMBER_COERCE_MARKER (start);
2591ec64 2541 b = XINT (start);
35692fe0 2542 }
2591ec64
EN
2543 if (NILP (end))
2544 e = BUF_ZV (bp);
35692fe0
JB
2545 else
2546 {
b7826503 2547 CHECK_NUMBER_COERCE_MARKER (end);
2591ec64 2548 e = XINT (end);
35692fe0
JB
2549 }
2550
2591ec64
EN
2551 if (b > e)
2552 temp = b, b = e, e = temp;
35692fe0 2553
2591ec64
EN
2554 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2555 args_out_of_range (start, end);
35692fe0 2556
260e2e2a
KH
2557 obuf = current_buffer;
2558 set_buffer_internal_1 (bp);
2591ec64 2559 update_buffer_properties (b, e);
260e2e2a
KH
2560 set_buffer_internal_1 (obuf);
2561
2591ec64 2562 insert_from_buffer (bp, b, e - b, 0);
35692fe0
JB
2563 return Qnil;
2564}
e9cf2084
RS
2565
2566DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
deb8e082 2567 6, 6, 0,
7ee72033 2568 doc: /* Compare two substrings of two buffers; return result as number.
a1f17501
PJ
2569the value is -N if first string is less after N-1 chars,
2570+N if first string is greater after N-1 chars, or 0 if strings match.
2571Each substring is represented as three arguments: BUFFER, START and END.
2572That makes six args in all, three for each substring.
2573
2574The value of `case-fold-search' in the current buffer
7ee72033
MB
2575determines whether case is significant or ignored. */)
2576 (buffer1, start1, end1, buffer2, start2, end2)
e9cf2084
RS
2577 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2578{
07422a12 2579 register int begp1, endp1, begp2, endp2, temp;
e9cf2084 2580 register struct buffer *bp1, *bp2;
1149fd6f 2581 register Lisp_Object trt
e9cf2084 2582 = (!NILP (current_buffer->case_fold_search)
60758816 2583 ? current_buffer->case_canon_table : Qnil);
ec1c14f6 2584 int chars = 0;
07422a12 2585 int i1, i2, i1_byte, i2_byte;
e9cf2084
RS
2586
2587 /* Find the first buffer and its substring. */
2588
2589 if (NILP (buffer1))
2590 bp1 = current_buffer;
2591 else
2592 {
3fff2dfa
RS
2593 Lisp_Object buf1;
2594 buf1 = Fget_buffer (buffer1);
2595 if (NILP (buf1))
2596 nsberror (buffer1);
2597 bp1 = XBUFFER (buf1);
93b62e82
KH
2598 if (NILP (bp1->name))
2599 error ("Selecting deleted buffer");
e9cf2084
RS
2600 }
2601
2602 if (NILP (start1))
2603 begp1 = BUF_BEGV (bp1);
2604 else
2605 {
b7826503 2606 CHECK_NUMBER_COERCE_MARKER (start1);
e9cf2084
RS
2607 begp1 = XINT (start1);
2608 }
2609 if (NILP (end1))
2610 endp1 = BUF_ZV (bp1);
2611 else
2612 {
b7826503 2613 CHECK_NUMBER_COERCE_MARKER (end1);
e9cf2084
RS
2614 endp1 = XINT (end1);
2615 }
2616
2617 if (begp1 > endp1)
2618 temp = begp1, begp1 = endp1, endp1 = temp;
2619
2620 if (!(BUF_BEGV (bp1) <= begp1
2621 && begp1 <= endp1
2622 && endp1 <= BUF_ZV (bp1)))
2623 args_out_of_range (start1, end1);
2624
2625 /* Likewise for second substring. */
2626
2627 if (NILP (buffer2))
2628 bp2 = current_buffer;
2629 else
2630 {
3fff2dfa
RS
2631 Lisp_Object buf2;
2632 buf2 = Fget_buffer (buffer2);
2633 if (NILP (buf2))
2634 nsberror (buffer2);
3b1fdd85 2635 bp2 = XBUFFER (buf2);
93b62e82
KH
2636 if (NILP (bp2->name))
2637 error ("Selecting deleted buffer");
e9cf2084
RS
2638 }
2639
2640 if (NILP (start2))
2641 begp2 = BUF_BEGV (bp2);
2642 else
2643 {
b7826503 2644 CHECK_NUMBER_COERCE_MARKER (start2);
e9cf2084
RS
2645 begp2 = XINT (start2);
2646 }
2647 if (NILP (end2))
2648 endp2 = BUF_ZV (bp2);
2649 else
2650 {
b7826503 2651 CHECK_NUMBER_COERCE_MARKER (end2);
e9cf2084
RS
2652 endp2 = XINT (end2);
2653 }
2654
2655 if (begp2 > endp2)
2656 temp = begp2, begp2 = endp2, endp2 = temp;
2657
2658 if (!(BUF_BEGV (bp2) <= begp2
2659 && begp2 <= endp2
2660 && endp2 <= BUF_ZV (bp2)))
2661 args_out_of_range (start2, end2);
2662
07422a12
RS
2663 i1 = begp1;
2664 i2 = begp2;
2665 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2666 i2_byte = buf_charpos_to_bytepos (bp2, i2);
e9cf2084 2667
07422a12 2668 while (i1 < endp1 && i2 < endp2)
e9cf2084 2669 {
07422a12
RS
2670 /* When we find a mismatch, we must compare the
2671 characters, not just the bytes. */
2672 int c1, c2;
ec1c14f6 2673
2221451f
RS
2674 QUIT;
2675
07422a12
RS
2676 if (! NILP (bp1->enable_multibyte_characters))
2677 {
2678 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2679 BUF_INC_POS (bp1, i1_byte);
2680 i1++;
2681 }
2682 else
2683 {
2684 c1 = BUF_FETCH_BYTE (bp1, i1);
2685 c1 = unibyte_char_to_multibyte (c1);
2686 i1++;
2687 }
2688
2689 if (! NILP (bp2->enable_multibyte_characters))
2690 {
2691 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2692 BUF_INC_POS (bp2, i2_byte);
2693 i2++;
2694 }
2695 else
2696 {
2697 c2 = BUF_FETCH_BYTE (bp2, i2);
2698 c2 = unibyte_char_to_multibyte (c2);
2699 i2++;
2700 }
ec1c14f6 2701
1149fd6f 2702 if (!NILP (trt))
e9cf2084 2703 {
1149fd6f
SM
2704 c1 = CHAR_TABLE_TRANSLATE (trt, c1);
2705 c2 = CHAR_TABLE_TRANSLATE (trt, c2);
e9cf2084
RS
2706 }
2707 if (c1 < c2)
ec1c14f6 2708 return make_number (- 1 - chars);
e9cf2084 2709 if (c1 > c2)
ec1c14f6 2710 return make_number (chars + 1);
07422a12
RS
2711
2712 chars++;
e9cf2084
RS
2713 }
2714
2715 /* The strings match as far as they go.
2716 If one is shorter, that one is less. */
07422a12 2717 if (chars < endp1 - begp1)
ec1c14f6 2718 return make_number (chars + 1);
07422a12 2719 else if (chars < endp2 - begp2)
ec1c14f6 2720 return make_number (- chars - 1);
e9cf2084
RS
2721
2722 /* Same length too => they are equal. */
2723 return make_number (0);
2724}
35692fe0 2725\f
d5a539cd
RS
2726static Lisp_Object
2727subst_char_in_region_unwind (arg)
2728 Lisp_Object arg;
2729{
2730 return current_buffer->undo_list = arg;
2731}
2732
c8e76b47
RS
2733static Lisp_Object
2734subst_char_in_region_unwind_1 (arg)
2735 Lisp_Object arg;
2736{
2737 return current_buffer->filename = arg;
2738}
2739
35692fe0 2740DEFUN ("subst-char-in-region", Fsubst_char_in_region,
deb8e082 2741 Ssubst_char_in_region, 4, 5, 0,
7ee72033 2742 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
a1f17501
PJ
2743If optional arg NOUNDO is non-nil, don't record this change for undo
2744and don't mark the buffer as really changed.
7ee72033
MB
2745Both characters must have the same length of multi-byte form. */)
2746 (start, end, fromchar, tochar, noundo)
35692fe0
JB
2747 Lisp_Object start, end, fromchar, tochar, noundo;
2748{
84246b95 2749 register int pos, pos_byte, stop, i, len, end_byte;
0f2e2a3b
SM
2750 /* Keep track of the first change in the buffer:
2751 if 0 we haven't found it yet.
2752 if < 0 we've found it and we've run the before-change-function.
2753 if > 0 we've actually performed it and the value is its position. */
60b96ee7 2754 int changed = 0;
d5c2c403
KH
2755 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2756 unsigned char *p;
aed13378 2757 int count = SPECPDL_INDEX ();
aa801467
KH
2758#define COMBINING_NO 0
2759#define COMBINING_BEFORE 1
2760#define COMBINING_AFTER 2
2761#define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2762 int maybe_byte_combining = COMBINING_NO;
2483cf58 2763 int last_changed = 0;
7439e5b9 2764 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
35692fe0 2765
0f2e2a3b
SM
2766 restart:
2767
35692fe0 2768 validate_region (&start, &end);
b7826503
PJ
2769 CHECK_NUMBER (fromchar);
2770 CHECK_NUMBER (tochar);
35692fe0 2771
7439e5b9 2772 if (multibyte_p)
fb8106e8 2773 {
d5c2c403
KH
2774 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2775 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
fdd6025e 2776 error ("Characters in `subst-char-in-region' have different byte-lengths");
aa801467
KH
2777 if (!ASCII_BYTE_P (*tostr))
2778 {
2779 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2780 complete multibyte character, it may be combined with the
2781 after bytes. If it is in the range 0xA0..0xFF, it may be
2782 combined with the before and after bytes. */
2783 if (!CHAR_HEAD_P (*tostr))
2784 maybe_byte_combining = COMBINING_BOTH;
2785 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2786 maybe_byte_combining = COMBINING_AFTER;
2787 }
fb8106e8
KH
2788 }
2789 else
2790 {
2791 len = 1;
d5c2c403
KH
2792 fromstr[0] = XFASTINT (fromchar);
2793 tostr[0] = XFASTINT (tochar);
fb8106e8
KH
2794 }
2795
84246b95
KH
2796 pos = XINT (start);
2797 pos_byte = CHAR_TO_BYTE (pos);
ec1c14f6
RS
2798 stop = CHAR_TO_BYTE (XINT (end));
2799 end_byte = stop;
35692fe0 2800
d5a539cd
RS
2801 /* If we don't want undo, turn off putting stuff on the list.
2802 That's faster than getting rid of things,
c8e76b47
RS
2803 and it prevents even the entry for a first change.
2804 Also inhibit locking the file. */
0f2e2a3b 2805 if (!changed && !NILP (noundo))
d5a539cd
RS
2806 {
2807 record_unwind_protect (subst_char_in_region_unwind,
2808 current_buffer->undo_list);
2809 current_buffer->undo_list = Qt;
c8e76b47
RS
2810 /* Don't do file-locking. */
2811 record_unwind_protect (subst_char_in_region_unwind_1,
2812 current_buffer->filename);
2813 current_buffer->filename = Qnil;
d5a539cd
RS
2814 }
2815
84246b95 2816 if (pos_byte < GPT_BYTE)
ec1c14f6 2817 stop = min (stop, GPT_BYTE);
fb8106e8 2818 while (1)
35692fe0 2819 {
a3360ff9
KH
2820 int pos_byte_next = pos_byte;
2821
84246b95 2822 if (pos_byte >= stop)
fb8106e8 2823 {
84246b95 2824 if (pos_byte >= end_byte) break;
ec1c14f6 2825 stop = end_byte;
fb8106e8 2826 }
84246b95 2827 p = BYTE_POS_ADDR (pos_byte);
7439e5b9
GM
2828 if (multibyte_p)
2829 INC_POS (pos_byte_next);
2830 else
2831 ++pos_byte_next;
a3360ff9
KH
2832 if (pos_byte_next - pos_byte == len
2833 && p[0] == fromstr[0]
fb8106e8
KH
2834 && (len == 1
2835 || (p[1] == fromstr[1]
2836 && (len == 2 || (p[2] == fromstr[2]
2837 && (len == 3 || p[3] == fromstr[3]))))))
35692fe0 2838 {
0f2e2a3b
SM
2839 if (changed < 0)
2840 /* We've already seen this and run the before-change-function;
2841 this time we only need to record the actual position. */
2842 changed = pos;
2843 else if (!changed)
60b96ee7 2844 {
0f2e2a3b 2845 changed = -1;
3e145152 2846 modify_region (current_buffer, pos, XINT (end), 0);
7653d030
RS
2847
2848 if (! NILP (noundo))
2849 {
1e158d25
RS
2850 if (MODIFF - 1 == SAVE_MODIFF)
2851 SAVE_MODIFF++;
7653d030
RS
2852 if (MODIFF - 1 == current_buffer->auto_save_modified)
2853 current_buffer->auto_save_modified++;
2854 }
0f2e2a3b
SM
2855
2856 /* The before-change-function may have moved the gap
2857 or even modified the buffer so we should start over. */
2858 goto restart;
60b96ee7
RS
2859 }
2860
0c1e3b85 2861 /* Take care of the case where the new character
34a7a267 2862 combines with neighboring bytes. */
a3360ff9 2863 if (maybe_byte_combining
aa801467
KH
2864 && (maybe_byte_combining == COMBINING_AFTER
2865 ? (pos_byte_next < Z_BYTE
2866 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2867 : ((pos_byte_next < Z_BYTE
2868 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2869 || (pos_byte > BEG_BYTE
2870 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
0c1e3b85
RS
2871 {
2872 Lisp_Object tem, string;
2873
2874 struct gcpro gcpro1;
2875
2876 tem = current_buffer->undo_list;
2877 GCPRO1 (tem);
2878
aa801467
KH
2879 /* Make a multibyte string containing this single character. */
2880 string = make_multibyte_string (tostr, 1, len);
0c1e3b85
RS
2881 /* replace_range is less efficient, because it moves the gap,
2882 but it handles combining correctly. */
2883 replace_range (pos, pos + 1, string,
9869520f 2884 0, 0, 1);
a3360ff9
KH
2885 pos_byte_next = CHAR_TO_BYTE (pos);
2886 if (pos_byte_next > pos_byte)
2887 /* Before combining happened. We should not increment
3f5409d3
KH
2888 POS. So, to cancel the later increment of POS,
2889 decrease it now. */
2890 pos--;
a3360ff9 2891 else
3f5409d3 2892 INC_POS (pos_byte_next);
34a7a267 2893
0c1e3b85
RS
2894 if (! NILP (noundo))
2895 current_buffer->undo_list = tem;
2896
2897 UNGCPRO;
2898 }
2899 else
2900 {
2901 if (NILP (noundo))
2902 record_change (pos, 1);
2903 for (i = 0; i < len; i++) *p++ = tostr[i];
2904 }
d5c2c403 2905 last_changed = pos + 1;
35692fe0 2906 }
3f5409d3
KH
2907 pos_byte = pos_byte_next;
2908 pos++;
35692fe0
JB
2909 }
2910
0f2e2a3b 2911 if (changed > 0)
d5c2c403
KH
2912 {
2913 signal_after_change (changed,
2914 last_changed - changed, last_changed - changed);
2915 update_compositions (changed, last_changed, CHECK_ALL);
2916 }
60b96ee7 2917
d5a539cd 2918 unbind_to (count, Qnil);
35692fe0
JB
2919 return Qnil;
2920}
2921
f555f8cf
KH
2922
2923static Lisp_Object check_translation P_ ((int, int, int, Lisp_Object));
2924
2925/* Helper function for Ftranslate_region_internal.
2926
2927 Check if a character sequence at POS (POS_BYTE) matches an element
2928 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
2929 element is found, return it. Otherwise return Qnil. */
2930
2931static Lisp_Object
2932check_translation (pos, pos_byte, end, val)
2933 int pos, pos_byte, end;
2934 Lisp_Object val;
2935{
2936 int buf_size = 16, buf_used = 0;
2937 int *buf = alloca (sizeof (int) * buf_size);
2938
2939 for (; CONSP (val); val = XCDR (val))
2940 {
2941 Lisp_Object elt;
2942 int len, i;
2943
2944 elt = XCAR (val);
2945 if (! CONSP (elt))
2946 continue;
2947 elt = XCAR (elt);
2948 if (! VECTORP (elt))
2949 continue;
2950 len = ASIZE (elt);
2951 if (len <= end - pos)
2952 {
2953 for (i = 0; i < len; i++)
2954 {
2955 if (buf_used <= i)
2956 {
2957 unsigned char *p = BYTE_POS_ADDR (pos_byte);
2958 int len;
2959
2960 if (buf_used == buf_size)
2961 {
2962 int *newbuf;
2963
2964 buf_size += 16;
2965 newbuf = alloca (sizeof (int) * buf_size);
2966 memcpy (newbuf, buf, sizeof (int) * buf_used);
2967 buf = newbuf;
2968 }
2969 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, 0, len);
2970 pos_byte += len;
2971 }
2972 if (XINT (AREF (elt, i)) != buf[i])
2973 break;
2974 }
2975 if (i == len)
2976 return XCAR (val);
2977 }
2978 }
2979 return Qnil;
2980}
2981
2982
8583605b
KH
2983DEFUN ("translate-region-internal", Ftranslate_region_internal,
2984 Stranslate_region_internal, 3, 3, 0,
2985 doc: /* Internal use only.
2986From START to END, translate characters according to TABLE.
f555f8cf
KH
2987TABLE is a string or a char-table; the Nth character in it is the
2988mapping for the character with code N.
7ee72033
MB
2989It returns the number of characters changed. */)
2990 (start, end, table)
35692fe0
JB
2991 Lisp_Object start;
2992 Lisp_Object end;
2993 register Lisp_Object table;
2994{
35692fe0 2995 register unsigned char *tt; /* Trans table. */
35692fe0
JB
2996 register int nc; /* New character. */
2997 int cnt; /* Number of changes made. */
35692fe0 2998 int size; /* Size of translate table. */
f555f8cf 2999 int pos, pos_byte, end_pos;
e8cce5af 3000 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
8583605b
KH
3001 int string_multibyte;
3002 Lisp_Object val;
35692fe0
JB
3003
3004 validate_region (&start, &end);
8583605b 3005 if (CHAR_TABLE_P (table))
f555f8cf
KH
3006 {
3007 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3008 error ("Not a translation table");
eb3d9ec7 3009 size = MAX_CHAR;
f555f8cf
KH
3010 tt = NULL;
3011 }
8583605b
KH
3012 else
3013 {
3014 CHECK_STRING (table);
3015
eb3d9ec7
KH
3016 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3017 table = string_make_unibyte (table);
8583605b
KH
3018 string_multibyte = SCHARS (table) < SBYTES (table);
3019 size = SBYTES (table);
3020 tt = SDATA (table);
3021 }
35692fe0 3022
1f24f4fd 3023 pos = XINT (start);
8583605b 3024 pos_byte = CHAR_TO_BYTE (pos);
e65837df 3025 end_pos = XINT (end);
af6ea8ad 3026 modify_region (current_buffer, pos, end_pos, 0);
35692fe0
JB
3027
3028 cnt = 0;
f555f8cf 3029 for (; pos < end_pos; )
35692fe0 3030 {
ec1c14f6 3031 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
8583605b
KH
3032 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3033 int len, str_len;
1f24f4fd 3034 int oc;
f555f8cf 3035 Lisp_Object val;
ec1c14f6 3036
e8cce5af 3037 if (multibyte)
eb3d9ec7 3038 oc = STRING_CHAR_AND_LENGTH (p, MAX_MULTIBYTE_LENGTH, len);
e8cce5af 3039 else
eb3d9ec7
KH
3040 oc = *p, len = 1;
3041 if (oc < size)
35692fe0 3042 {
eb3d9ec7 3043 if (tt)
35692fe0 3044 {
fa056b08
KS
3045 /* Reload as signal_after_change in last iteration may GC. */
3046 tt = SDATA (table);
8583605b 3047 if (string_multibyte)
0c1e3b85 3048 {
8583605b 3049 str = tt + string_char_to_byte (table, oc);
7a6a86ad 3050 nc = STRING_CHAR_AND_LENGTH (str, MAX_MULTIBYTE_LENGTH,
eb3d9ec7 3051 str_len);
0c1e3b85
RS
3052 }
3053 else
3054 {
eb3d9ec7
KH
3055 nc = tt[oc];
3056 if (! ASCII_BYTE_P (nc) && multibyte)
3057 {
3058 str_len = BYTE8_STRING (nc, buf);
3059 str = buf;
3060 }
3061 else
3062 {
3063 str_len = 1;
3064 str = tt + oc;
3065 }
0c1e3b85 3066 }
35692fe0 3067 }
eb3d9ec7 3068 else
f555f8cf 3069 {
eb3d9ec7
KH
3070 int c;
3071
3072 nc = oc;
3073 val = CHAR_TABLE_REF (table, oc);
3074 if (CHARACTERP (val)
3075 && (c = XINT (val), CHAR_VALID_P (c, 0)))
3076 {
3077 nc = c;
3078 str_len = CHAR_STRING (nc, buf);
3079 str = buf;
3080 }
3081 else if (VECTORP (val) || (CONSP (val)))
3082 {
3083 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3084 where TO is TO-CHAR or [TO-CHAR ...]. */
3085 nc = -1;
3086 }
f555f8cf 3087 }
8583605b 3088
eb3d9ec7 3089 if (nc != oc && nc >= 0)
8583605b 3090 {
f555f8cf
KH
3091 /* Simple one char to one char translation. */
3092 if (len != str_len)
3093 {
3094 Lisp_Object string;
8583605b 3095
f555f8cf
KH
3096 /* This is less efficient, because it moves the gap,
3097 but it should handle multibyte characters correctly. */
3098 string = make_multibyte_string (str, 1, str_len);
3099 replace_range (pos, pos + 1, string, 1, 0, 1);
3100 len = str_len;
3101 }
3102 else
3103 {
3104 record_change (pos, 1);
3105 while (str_len-- > 0)
3106 *p++ = *str++;
3107 signal_after_change (pos, 1, 1);
3108 update_compositions (pos, pos + 1, CHECK_BORDER);
3109 }
3110 ++cnt;
8583605b 3111 }
eb3d9ec7 3112 else if (nc < 0)
8583605b 3113 {
f555f8cf
KH
3114 Lisp_Object string;
3115
3116 if (CONSP (val))
3117 {
3118 val = check_translation (pos, pos_byte, end_pos, val);
3119 if (NILP (val))
3120 {
3121 pos_byte += len;
3122 pos++;
3123 continue;
3124 }
3125 /* VAL is ([FROM-CHAR ...] . TO). */
3126 len = ASIZE (XCAR (val));
3127 val = XCDR (val);
3128 }
3129 else
3130 len = 1;
3131
3132 if (VECTORP (val))
3133 {
3134 int i;
3135
3136 string = Fmake_string (make_number (ASIZE (val)),
3137 AREF (val, 0));
3138 for (i = 1; i < ASIZE (val); i++)
3139 Faset (string, make_number (i), AREF (val, i));
3140 }
3141 else
3142 {
3143 string = Fmake_string (make_number (1), val);
3144 }
3145 replace_range (pos, pos + len, string, 1, 0, 1);
3146 pos_byte += SBYTES (string);
3147 pos += SCHARS (string);
3148 cnt += SCHARS (string);
3149 end_pos += SCHARS (string) - len;
3150 continue;
8583605b 3151 }
8583605b
KH
3152 }
3153 pos_byte += len;
3f5409d3 3154 pos++;
35692fe0
JB
3155 }
3156
ec1c14f6 3157 return make_number (cnt);
35692fe0
JB
3158}
3159
3160DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
7ee72033 3161 doc: /* Delete the text between point and mark.
412f1fab 3162
a1f17501 3163When called from a program, expects two arguments,
7ee72033
MB
3164positions (integers or markers) specifying the stretch to be deleted. */)
3165 (start, end)
2591ec64 3166 Lisp_Object start, end;
35692fe0 3167{
2591ec64
EN
3168 validate_region (&start, &end);
3169 del_range (XINT (start), XINT (end));
35692fe0
JB
3170 return Qnil;
3171}
7dae4502
SM
3172
3173DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3174 Sdelete_and_extract_region, 2, 2, 0,
7ee72033
MB
3175 doc: /* Delete the text between START and END and return it. */)
3176 (start, end)
7dae4502
SM
3177 Lisp_Object start, end;
3178{
3179 validate_region (&start, &end);
8550b998 3180 if (XINT (start) == XINT (end))
977f6cfb 3181 return empty_unibyte_string;
7dae4502
SM
3182 return del_range_1 (XINT (start), XINT (end), 1, 1);
3183}
35692fe0
JB
3184\f
3185DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
7ee72033
MB
3186 doc: /* Remove restrictions (narrowing) from current buffer.
3187This allows the buffer's full text to be seen and edited. */)
3188 ()
35692fe0 3189{
2cad2e34
RS
3190 if (BEG != BEGV || Z != ZV)
3191 current_buffer->clip_changed = 1;
35692fe0 3192 BEGV = BEG;
ec1c14f6
RS
3193 BEGV_BYTE = BEG_BYTE;
3194 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
52b14ac0
JB
3195 /* Changing the buffer bounds invalidates any recorded current column. */
3196 invalidate_current_column ();
35692fe0
JB
3197 return Qnil;
3198}
3199
3200DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
7ee72033 3201 doc: /* Restrict editing in this buffer to the current region.
a1f17501
PJ
3202The rest of the text becomes temporarily invisible and untouchable
3203but is not deleted; if you save the buffer in a file, the invisible
3204text is included in the file. \\[widen] makes all visible again.
3205See also `save-restriction'.
3206
3207When calling from a program, pass two arguments; positions (integers
7ee72033
MB
3208or markers) bounding the text that should remain visible. */)
3209 (start, end)
2591ec64 3210 register Lisp_Object start, end;
35692fe0 3211{
b7826503
PJ
3212 CHECK_NUMBER_COERCE_MARKER (start);
3213 CHECK_NUMBER_COERCE_MARKER (end);
35692fe0 3214
2591ec64 3215 if (XINT (start) > XINT (end))
35692fe0 3216 {
b5a6948e 3217 Lisp_Object tem;
2591ec64 3218 tem = start; start = end; end = tem;
35692fe0
JB
3219 }
3220
2591ec64
EN
3221 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3222 args_out_of_range (start, end);
35692fe0 3223
2cad2e34
RS
3224 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3225 current_buffer->clip_changed = 1;
3226
ec1c14f6 3227 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2591ec64 3228 SET_BUF_ZV (current_buffer, XFASTINT (end));
6ec8bbd2 3229 if (PT < XFASTINT (start))
2591ec64 3230 SET_PT (XFASTINT (start));
6ec8bbd2 3231 if (PT > XFASTINT (end))
2591ec64 3232 SET_PT (XFASTINT (end));
52b14ac0
JB
3233 /* Changing the buffer bounds invalidates any recorded current column. */
3234 invalidate_current_column ();
35692fe0
JB
3235 return Qnil;
3236}
3237
3238Lisp_Object
3239save_restriction_save ()
3240{
d6abb4c7
MB
3241 if (BEGV == BEG && ZV == Z)
3242 /* The common case that the buffer isn't narrowed.
3243 We return just the buffer object, which save_restriction_restore
3244 recognizes as meaning `no restriction'. */
3245 return Fcurrent_buffer ();
3246 else
3247 /* We have to save a restriction, so return a pair of markers, one
3248 for the beginning and one for the end. */
3249 {
3250 Lisp_Object beg, end;
3251
3252 beg = buildmark (BEGV, BEGV_BYTE);
3253 end = buildmark (ZV, ZV_BYTE);
35692fe0 3254
d6abb4c7
MB
3255 /* END must move forward if text is inserted at its exact location. */
3256 XMARKER(end)->insertion_type = 1;
3257
3258 return Fcons (beg, end);
3259 }
35692fe0
JB
3260}
3261
3262Lisp_Object
3263save_restriction_restore (data)
3264 Lisp_Object data;
3265{
d6abb4c7
MB
3266 if (CONSP (data))
3267 /* A pair of marks bounding a saved restriction. */
35692fe0 3268 {
d6abb4c7
MB
3269 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3270 struct Lisp_Marker *end = XMARKER (XCDR (data));
3271 struct buffer *buf = beg->buffer; /* END should have the same buffer. */
2cad2e34 3272
63884563
RS
3273 if (buf /* Verify marker still points to a buffer. */
3274 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
d6abb4c7
MB
3275 /* The restriction has changed from the saved one, so restore
3276 the saved restriction. */
3277 {
3278 int pt = BUF_PT (buf);
3279
3280 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3281 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3282
3283 if (pt < beg->charpos || pt > end->charpos)
3284 /* The point is outside the new visible range, move it inside. */
3285 SET_BUF_PT_BOTH (buf,
3286 clip_to_bounds (beg->charpos, pt, end->charpos),
63884563 3287 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
d6abb4c7 3288 end->bytepos));
177c0ea7 3289
d6abb4c7
MB
3290 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3291 }
3292 }
3293 else
3294 /* A buffer, which means that there was no old restriction. */
3295 {
3296 struct buffer *buf = XBUFFER (data);
2cad2e34 3297
63884563
RS
3298 if (buf /* Verify marker still points to a buffer. */
3299 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
d6abb4c7
MB
3300 /* The buffer has been narrowed, get rid of the narrowing. */
3301 {
63884563
RS
3302 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3303 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
35692fe0 3304
d6abb4c7
MB
3305 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3306 }
3307 }
35692fe0
JB
3308
3309 return Qnil;
3310}
3311
3312DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
7ee72033 3313 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
a1f17501 3314The buffer's restrictions make parts of the beginning and end invisible.
9671c13a 3315\(They are set up with `narrow-to-region' and eliminated with `widen'.)
a1f17501
PJ
3316This special form, `save-restriction', saves the current buffer's restrictions
3317when it is entered, and restores them when it is exited.
3318So any `narrow-to-region' within BODY lasts only until the end of the form.
3319The old restrictions settings are restored
3320even in case of abnormal exit (throw or error).
3321
3322The value returned is the value of the last form in BODY.
3323
3324Note: if you are using both `save-excursion' and `save-restriction',
3325use `save-excursion' outermost:
33c2d29f
MB
3326 (save-excursion (save-restriction ...))
3327
3328usage: (save-restriction &rest BODY) */)
7ee72033 3329 (body)
35692fe0
JB
3330 Lisp_Object body;
3331{
3332 register Lisp_Object val;
aed13378 3333 int count = SPECPDL_INDEX ();
35692fe0
JB
3334
3335 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3336 val = Fprogn (body);
3337 return unbind_to (count, val);
3338}
3339\f
0ae83348 3340/* Buffer for the most recent text displayed by Fmessage_box. */
671fbc4d
KH
3341static char *message_text;
3342
3343/* Allocated length of that buffer. */
3344static int message_length;
3345
35692fe0 3346DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
db18da59 3347 doc: /* Display a message at the bottom of the screen.
281c1721
RS
3348The message also goes into the `*Messages*' buffer.
3349\(In keyboard macros, that's all it does.)
db18da59 3350Return the message.
281c1721 3351
a1f17501
PJ
3352The first argument is a format control string, and the rest are data
3353to be formatted under control of the string. See `format' for details.
3354
7bd5bcfb
KS
3355Note: Use (message "%s" VALUE) to print the value of expressions and
3356variables to avoid accidentally interpreting `%' as format specifiers.
3357
fa056b08
KS
3358If the first argument is nil or the empty string, the function clears
3359any existing message; this lets the minibuffer contents show. See
3360also `current-message'.
4bfbe194 3361
867b9600 3362usage: (message FORMAT-STRING &rest ARGS) */)
7ee72033 3363 (nargs, args)
35692fe0
JB
3364 int nargs;
3365 Lisp_Object *args;
3366{
6076e561
RS
3367 if (NILP (args[0])
3368 || (STRINGP (args[0])
3369 && SBYTES (args[0]) == 0))
f0250249
JB
3370 {
3371 message (0);
674a954a 3372 return args[0];
f0250249 3373 }
ccdac5be
JB
3374 else
3375 {
3376 register Lisp_Object val;
304f1f12 3377 val = Fformat (nargs, args);
d5db4077 3378 message3 (val, SBYTES (val), STRING_MULTIBYTE (val));
ccdac5be
JB
3379 return val;
3380 }
35692fe0
JB
3381}
3382
cacc3e2c 3383DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
7ee72033 3384 doc: /* Display a message, in a dialog box if possible.
a1f17501
PJ
3385If a dialog box is not available, use the echo area.
3386The first argument is a format control string, and the rest are data
3387to be formatted under control of the string. See `format' for details.
3388
fa056b08
KS
3389If the first argument is nil or the empty string, clear any existing
3390message; let the minibuffer contents show.
4bfbe194 3391
867b9600 3392usage: (message-box FORMAT-STRING &rest ARGS) */)
7ee72033 3393 (nargs, args)
cacc3e2c
RS
3394 int nargs;
3395 Lisp_Object *args;
3396{
3397 if (NILP (args[0]))
3398 {
3399 message (0);
3400 return Qnil;
3401 }
3402 else
3403 {
3404 register Lisp_Object val;
3405 val = Fformat (nargs, args);
f8250f01 3406#ifdef HAVE_MENUS
0ae83348
EZ
3407 /* The MS-DOS frames support popup menus even though they are
3408 not FRAME_WINDOW_P. */
3409 if (FRAME_WINDOW_P (XFRAME (selected_frame))
3410 || FRAME_MSDOS_P (XFRAME (selected_frame)))
cacc3e2c
RS
3411 {
3412 Lisp_Object pane, menu, obj;
3413 struct gcpro gcpro1;
3414 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
3415 GCPRO1 (pane);
3416 menu = Fcons (val, pane);
87944384 3417 obj = Fx_popup_dialog (Qt, menu, Qt);
cacc3e2c
RS
3418 UNGCPRO;
3419 return val;
3420 }
0ae83348 3421#endif /* HAVE_MENUS */
cacc3e2c
RS
3422 /* Copy the data so that it won't move when we GC. */
3423 if (! message_text)
3424 {
3425 message_text = (char *)xmalloc (80);
3426 message_length = 80;
3427 }
d5db4077 3428 if (SBYTES (val) > message_length)
cacc3e2c 3429 {
d5db4077 3430 message_length = SBYTES (val);
cacc3e2c
RS
3431 message_text = (char *)xrealloc (message_text, message_length);
3432 }
d5db4077
KR
3433 bcopy (SDATA (val), message_text, SBYTES (val));
3434 message2 (message_text, SBYTES (val),
d13a8480 3435 STRING_MULTIBYTE (val));
cacc3e2c 3436 return val;
cacc3e2c
RS
3437 }
3438}
f8250f01 3439#ifdef HAVE_MENUS
cacc3e2c
RS
3440extern Lisp_Object last_nonmenu_event;
3441#endif
f8250f01 3442
cacc3e2c 3443DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
7ee72033 3444 doc: /* Display a message in a dialog box or in the echo area.
a1f17501
PJ
3445If this command was invoked with the mouse, use a dialog box if
3446`use-dialog-box' is non-nil.
3447Otherwise, use the echo area.
3448The first argument is a format control string, and the rest are data
3449to be formatted under control of the string. See `format' for details.
3450
fa056b08
KS
3451If the first argument is nil or the empty string, clear any existing
3452message; let the minibuffer contents show.
4bfbe194 3453
867b9600 3454usage: (message-or-box FORMAT-STRING &rest ARGS) */)
7ee72033 3455 (nargs, args)
cacc3e2c
RS
3456 int nargs;
3457 Lisp_Object *args;
3458{
f8250f01 3459#ifdef HAVE_MENUS
5920df33 3460 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
c01fbf95 3461 && use_dialog_box)
0a56ee6b 3462 return Fmessage_box (nargs, args);
cacc3e2c
RS
3463#endif
3464 return Fmessage (nargs, args);
3465}
3466
b14dda8a 3467DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
7ee72033
MB
3468 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3469 ()
b14dda8a 3470{
0634a78e 3471 return current_message ();
b14dda8a
RS
3472}
3473
2d9811c4 3474
d2936d21 3475DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
7ee72033 3476 doc: /* Return a copy of STRING with text properties added.
a1f17501
PJ
3477First argument is the string to copy.
3478Remaining arguments form a sequence of PROPERTY VALUE pairs for text
4bfbe194
MB
3479properties to add to the result.
3480usage: (propertize STRING &rest PROPERTIES) */)
7ee72033 3481 (nargs, args)
2d9811c4
GM
3482 int nargs;
3483 Lisp_Object *args;
3484{
3485 Lisp_Object properties, string;
3486 struct gcpro gcpro1, gcpro2;
3487 int i;
3488
3489 /* Number of args must be odd. */
d2936d21 3490 if ((nargs & 1) == 0 || nargs < 1)
2d9811c4
GM
3491 error ("Wrong number of arguments");
3492
3493 properties = string = Qnil;
3494 GCPRO2 (properties, string);
34a7a267 3495
2d9811c4 3496 /* First argument must be a string. */
b7826503 3497 CHECK_STRING (args[0]);
2d9811c4
GM
3498 string = Fcopy_sequence (args[0]);
3499
3500 for (i = 1; i < nargs; i += 2)
9b7a2369 3501 properties = Fcons (args[i], Fcons (args[i + 1], properties));
2d9811c4
GM
3502
3503 Fadd_text_properties (make_number (0),
d5db4077 3504 make_number (SCHARS (string)),
2d9811c4
GM
3505 properties, string);
3506 RETURN_UNGCPRO (string);
3507}
3508
3509
1f24f4fd
RS
3510/* Number of bytes that STRING will occupy when put into the result.
3511 MULTIBYTE is nonzero if the result should be multibyte. */
3512
3513#define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3514 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
d5db4077
KR
3515 ? count_size_as_multibyte (SDATA (STRING), SBYTES (STRING)) \
3516 : SBYTES (STRING))
1f24f4fd 3517
35692fe0 3518DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
867b9600
JL
3519 doc: /* Format a string out of a format-string and arguments.
3520The first argument is a format control string.
a1f17501 3521The other arguments are substituted into it to make the result, a string.
575b782f
CY
3522
3523The format control string may contain %-sequences meaning to substitute
3524the next available argument:
3525
a1f17501
PJ
3526%s means print a string argument. Actually, prints any object, with `princ'.
3527%d means print as number in decimal (%o octal, %x hex).
3528%X is like %x, but uses upper case.
3529%e means print a number in exponential notation.
3530%f means print a number in decimal-point notation.
3531%g means print a number in exponential notation
3532 or decimal-point notation, whichever uses fewer characters.
3533%c means print a number as a single character.
3534%S means print any object as an s-expression (using `prin1').
575b782f
CY
3535
3536The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
4bfbe194
MB
3537Use %% to put a single % into the output.
3538
575b782f
CY
3539A %-sequence may contain optional flag, width, and precision
3540specifiers, as follows:
3541
3542 %<flags><width><precision>character
3543
3544where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3545
3546The + flag character inserts a + before any positive number, while a
3547space inserts a space before any positive number; these flags only
3548affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3549The # flag means to use an alternate display form for %o, %x, %X, %e,
3550%f, and %g sequences. The - and 0 flags affect the width specifier,
3551as described below.
3552
3553The width specifier supplies a lower limit for the length of the
3554printed representation. The padding, if any, normally goes on the
3555left, but it goes on the right if the - flag is present. The padding
3556character is normally a space, but it is 0 if the 0 flag is present.
3557The - flag takes precedence over the 0 flag.
3558
3559For %e, %f, and %g sequences, the number after the "." in the
3560precision specifier says how many decimal places to show; if zero, the
3561decimal point itself is omitted. For %s and %S, the precision
3562specifier truncates the string to the given width.
f555f8cf 3563
4bfbe194 3564usage: (format STRING &rest OBJECTS) */)
7ee72033 3565 (nargs, args)
35692fe0
JB
3566 int nargs;
3567 register Lisp_Object *args;
3568{
3569 register int n; /* The number of the next arg to substitute */
e781c49e 3570 register int total; /* An estimate of the final length */
1f24f4fd 3571 char *buf, *p;
d147ee84 3572 register unsigned char *format, *end, *format_start;
2ea0266e 3573 int nchars;
1f24f4fd
RS
3574 /* Nonzero if the output should be a multibyte string,
3575 which is true if any of the inputs is one. */
3576 int multibyte = 0;
8f2917e4
KH
3577 /* When we make a multibyte string, we must pay attention to the
3578 byte combining problem, i.e., a byte may be combined with a
3579 multibyte charcter of the previous string. This flag tells if we
3580 must consider such a situation or not. */
3581 int maybe_combine_byte;
1f24f4fd 3582 unsigned char *this_format;
ac42d7b9
KG
3583 /* Precision for each spec, or -1, a flag value meaning no precision
3584 was given in that spec. Element 0, corresonding to the format
3585 string itself, will not be used. Element NARGS, corresponding to
3586 no argument, *will* be assigned to in the case that a `%' and `.'
3587 occur after the final format specifier. */
6b61353c 3588 int *precision = (int *) (alloca((nargs + 1) * sizeof (int)));
e781c49e 3589 int longest_format;
8d6179dc 3590 Lisp_Object val;
d147ee84 3591 int arg_intervals = 0;
7e2c051b 3592 USE_SAFE_ALLOCA;
d147ee84
RS
3593
3594 /* discarded[I] is 1 if byte I of the format
3595 string was not copied into the output.
3596 It is 2 if byte I was not the first byte of its character. */
e65837df 3597 char *discarded = 0;
d147ee84
RS
3598
3599 /* Each element records, for one argument,
3600 the start and end bytepos in the output string,
3601 and whether the argument is a string with intervals.
3602 info[0] is unused. Unused elements have -1 for start. */
5e6d5493
GM
3603 struct info
3604 {
d147ee84 3605 int start, end, intervals;
5e6d5493 3606 } *info = 0;
1f24f4fd 3607
35692fe0
JB
3608 /* It should not be necessary to GCPRO ARGS, because
3609 the caller in the interpreter should take care of that. */
3610
e781c49e
RS
3611 /* Try to determine whether the result should be multibyte.
3612 This is not always right; sometimes the result needs to be multibyte
3613 because of an object that we will pass through prin1,
3614 and in that case, we won't know it here. */
d147ee84
RS
3615 for (n = 0; n < nargs; n++)
3616 {
3617 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3618 multibyte = 1;
3619 /* Piggyback on this loop to initialize precision[N]. */
3620 precision[n] = -1;
3621 }
7c111482 3622 precision[nargs] = -1;
1f24f4fd 3623
b7826503 3624 CHECK_STRING (args[0]);
aa8b70ae
KH
3625 /* We may have to change "%S" to "%s". */
3626 args[0] = Fcopy_sequence (args[0]);
e781c49e 3627
67965a98
RS
3628 /* GC should never happen here, so abort if it does. */
3629 abort_on_gc++;
3630
e781c49e 3631 /* If we start out planning a unibyte result,
67965a98
RS
3632 then discover it has to be multibyte, we jump back to retry.
3633 That can only happen from the first large while loop below. */
e781c49e
RS
3634 retry:
3635
d5db4077 3636 format = SDATA (args[0]);
d147ee84 3637 format_start = format;
d5db4077 3638 end = format + SBYTES (args[0]);
e781c49e 3639 longest_format = 0;
1f24f4fd
RS
3640
3641 /* Make room in result for all the non-%-codes in the control string. */
7e2c051b 3642 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]) + 1;
1f24f4fd 3643
6b61353c 3644 /* Allocate the info and discarded tables. */
d147ee84 3645 {
7c111482 3646 int nbytes = (nargs+1) * sizeof *info;
d147ee84 3647 int i;
e65837df
KS
3648 if (!info)
3649 info = (struct info *) alloca (nbytes);
d147ee84 3650 bzero (info, nbytes);
7c111482 3651 for (i = 0; i <= nargs; i++)
d147ee84 3652 info[i].start = -1;
e65837df
KS
3653 if (!discarded)
3654 SAFE_ALLOCA (discarded, char *, SBYTES (args[0]));
d147ee84
RS
3655 bzero (discarded, SBYTES (args[0]));
3656 }
3657
1f24f4fd 3658 /* Add to TOTAL enough space to hold the converted arguments. */
35692fe0
JB
3659
3660 n = 0;
3661 while (format != end)
3662 if (*format++ == '%')
3663 {
a432bfe5 3664 int thissize = 0;
308dd672 3665 int actual_width = 0;
1f24f4fd 3666 unsigned char *this_format_start = format - 1;
ac42d7b9 3667 int field_width = 0;
35692fe0 3668
a432bfe5 3669 /* General format specifications look like
537dfb13 3670
a432bfe5
GM
3671 '%' [flags] [field-width] [precision] format
3672
3673 where
3674
cb06e570 3675 flags ::= [-+ #0]+
a432bfe5
GM
3676 field-width ::= [0-9]+
3677 precision ::= '.' [0-9]*
3678
3679 If a field-width is specified, it specifies to which width
e0f24100 3680 the output should be padded with blanks, if the output
a432bfe5
GM
3681 string is shorter than field-width.
3682
ac42d7b9 3683 If precision is specified, it specifies the number of
a432bfe5
GM
3684 digits to print after the '.' for floats, or the max.
3685 number of chars to print from a string. */
3686
913f73d4
RS
3687 while (format != end
3688 && (*format == '-' || *format == '0' || *format == '#'
cb06e570 3689 || * format == ' ' || *format == '+'))
a432bfe5
GM
3690 ++format;
3691
3692 if (*format >= '0' && *format <= '9')
3693 {
3694 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3695 field_width = 10 * field_width + *format - '0';
3696 }
3697
ac42d7b9
KG
3698 /* N is not incremented for another few lines below, so refer to
3699 element N+1 (which might be precision[NARGS]). */
a432bfe5
GM
3700 if (*format == '.')
3701 {
3702 ++format;
ac42d7b9
KG
3703 for (precision[n+1] = 0; *format >= '0' && *format <= '9'; ++format)
3704 precision[n+1] = 10 * precision[n+1] + *format - '0';
a432bfe5 3705 }
35692fe0 3706
6e1ada1b
AS
3707 /* Extra +1 for 'l' that we may need to insert into the
3708 format. */
3709 if (format - this_format_start + 2 > longest_format)
3710 longest_format = format - this_format_start + 2;
1f24f4fd 3711
bf6ab66c
KH
3712 if (format == end)
3713 error ("Format string ends in middle of format specifier");
35692fe0
JB
3714 if (*format == '%')
3715 format++;
3716 else if (++n >= nargs)
537dfb13 3717 error ("Not enough arguments for format string");
35692fe0
JB
3718 else if (*format == 'S')
3719 {
3720 /* For `S', prin1 the argument and then treat like a string. */
3721 register Lisp_Object tem;
3722 tem = Fprin1_to_string (args[n], Qnil);
e781c49e
RS
3723 if (STRING_MULTIBYTE (tem) && ! multibyte)
3724 {
3725 multibyte = 1;
3726 goto retry;
3727 }
35692fe0 3728 args[n] = tem;
aa8b70ae
KH
3729 /* If we restart the loop, we should not come here again
3730 because args[n] is now a string and calling
3731 Fprin1_to_string on it produces superflous double
3732 quotes. So, change "%S" to "%s" now. */
3733 *format = 's';
35692fe0
JB
3734 goto string;
3735 }
ae683129 3736 else if (SYMBOLP (args[n]))
35692fe0 3737 {
1e5d9116 3738 args[n] = SYMBOL_NAME (args[n]);
7df74da6
RS
3739 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3740 {
3741 multibyte = 1;
3742 goto retry;
3743 }
35692fe0
JB
3744 goto string;
3745 }
ae683129 3746 else if (STRINGP (args[n]))
35692fe0
JB
3747 {
3748 string:
b22e7ecc 3749 if (*format != 's' && *format != 'S')
bf6ab66c 3750 error ("Format specifier doesn't match argument type");
ac42d7b9
KG
3751 /* In the case (PRECISION[N] > 0), THISSIZE may not need
3752 to be as large as is calculated here. Easy check for
3753 the case PRECISION = 0. */
3754 thissize = precision[n] ? CONVERTED_BYTE_SIZE (multibyte, args[n]) : 0;
308dd672 3755 actual_width = lisp_string_width (args[n], -1, NULL, NULL);
35692fe0
JB
3756 }
3757 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
ae683129 3758 else if (INTEGERP (args[n]) && *format != 's')
35692fe0 3759 {
eb8c3be9 3760 /* The following loop assumes the Lisp type indicates
35692fe0
JB
3761 the proper way to pass the argument.
3762 So make sure we have a flonum if the argument should
3763 be a double. */
3764 if (*format == 'e' || *format == 'f' || *format == 'g')
3765 args[n] = Ffloat (args[n]);
4224cb62 3766 else
4224cb62 3767 if (*format != 'd' && *format != 'o' && *format != 'x'
00d65216 3768 && *format != 'i' && *format != 'X' && *format != 'c')
4224cb62
KH
3769 error ("Invalid format operation %%%c", *format);
3770
0e4df721 3771 thissize = 30 + (precision[n] > 0 ? precision[n] : 0);
063b53b1 3772 if (*format == 'c')
f49a2d74 3773 {
8f924df7 3774 if (! ASCII_CHAR_P (XINT (args[n]))
231a3316
KH
3775 /* Note: No one can remeber why we have to treat
3776 the character 0 as a multibyte character here.
3777 But, until it causes a real problem, let's
3778 don't change it. */
063b53b1 3779 || XINT (args[n]) == 0)
f49a2d74 3780 {
063b53b1
KH
3781 if (! multibyte)
3782 {
3783 multibyte = 1;
3784 goto retry;
3785 }
3786 args[n] = Fchar_to_string (args[n]);
3787 thissize = SBYTES (args[n]);
3788 }
3789 else if (! ASCII_BYTE_P (XINT (args[n])) && multibyte)
3790 {
3791 args[n]
3792 = Fchar_to_string (Funibyte_char_to_multibyte (args[n]));
3793 thissize = SBYTES (args[n]);
f49a2d74 3794 }
f49a2d74 3795 }
35692fe0 3796 }
ae683129 3797 else if (FLOATP (args[n]) && *format != 's')
35692fe0
JB
3798 {
3799 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
f98176d2
RS
3800 {
3801 if (*format != 'd' && *format != 'o' && *format != 'x'
3802 && *format != 'i' && *format != 'X' && *format != 'c')
3803 error ("Invalid format operation %%%c", *format);
c5c6b2cc
SM
3804 /* This fails unnecessarily if args[n] is bigger than
3805 most-positive-fixnum but smaller than MAXINT.
3806 These cases are important because we sometimes use floats
3807 to represent such integer values (typically such values
3808 come from UIDs or PIDs). */
3809 /* args[n] = Ftruncate (args[n], Qnil); */
f98176d2 3810 }
a432bfe5
GM
3811
3812 /* Note that we're using sprintf to print floats,
3813 so we have to take into account what that function
3814 prints. */
b11f1d8a 3815 /* Filter out flag value of -1. */
6b381c3a
RS
3816 thissize = (MAX_10_EXP + 100
3817 + (precision[n] > 0 ? precision[n] : 0));
35692fe0
JB
3818 }
3819 else
3820 {
3821 /* Anything but a string, convert to a string using princ. */
3822 register Lisp_Object tem;
3823 tem = Fprin1_to_string (args[n], Qt);
f555f8cf 3824 if (STRING_MULTIBYTE (tem) && ! multibyte)
e781c49e
RS
3825 {
3826 multibyte = 1;
3827 goto retry;
3828 }
35692fe0
JB
3829 args[n] = tem;
3830 goto string;
3831 }
34a7a267 3832
308dd672 3833 thissize += max (0, field_width - actual_width);
1f24f4fd 3834 total += thissize + 4;
35692fe0
JB
3835 }
3836
67965a98
RS
3837 abort_on_gc--;
3838
e781c49e
RS
3839 /* Now we can no longer jump to retry.
3840 TOTAL and LONGEST_FORMAT are known for certain. */
3841
1f24f4fd 3842 this_format = (unsigned char *) alloca (longest_format + 1);
50aa2f90 3843
1f24f4fd
RS
3844 /* Allocate the space for the result.
3845 Note that TOTAL is an overestimate. */
7e2c051b 3846 SAFE_ALLOCA (buf, char *, total);
35692fe0 3847
1f24f4fd
RS
3848 p = buf;
3849 nchars = 0;
3850 n = 0;
35692fe0 3851
1f24f4fd 3852 /* Scan the format and store result in BUF. */
d5db4077 3853 format = SDATA (args[0]);
67965a98
RS
3854 format_start = format;
3855 end = format + SBYTES (args[0]);
8f2917e4 3856 maybe_combine_byte = 0;
1f24f4fd
RS
3857 while (format != end)
3858 {
3859 if (*format == '%')
3860 {
3861 int minlen;
25c9e7fb 3862 int negative = 0;
1f24f4fd 3863 unsigned char *this_format_start = format;
35692fe0 3864
d147ee84 3865 discarded[format - format_start] = 1;
1f24f4fd 3866 format++;
fb893977 3867
cb06e570 3868 while (index("-+0# ", *format))
f555f8cf
KH
3869 {
3870 if (*format == '-')
3871 {
3872 negative = 1;
3873 }
3874 discarded[format - format_start] = 1;
3875 ++format;
3876 }
3877
1f24f4fd 3878 minlen = atoi (format);
f555f8cf
KH
3879
3880 while ((*format >= '0' && *format <= '9') || *format == '.')
d147ee84
RS
3881 {
3882 discarded[format - format_start] = 1;
3883 format++;
3884 }
35692fe0 3885
1f24f4fd
RS
3886 if (*format++ == '%')
3887 {
3888 *p++ = '%';
3889 nchars++;
3890 continue;
3891 }
3892
3893 ++n;
3894
d147ee84
RS
3895 discarded[format - format_start - 1] = 1;
3896 info[n].start = nchars;
3897
1f24f4fd
RS
3898 if (STRINGP (args[n]))
3899 {
ac42d7b9
KG
3900 /* handle case (precision[n] >= 0) */
3901
3902 int width, padding;
3903 int nbytes, start, end;
3904 int nchars_string;
3905
3906 /* lisp_string_width ignores a precision of 0, but GNU
3907 libc functions print 0 characters when the precision
3908 is 0. Imitate libc behavior here. Changing
3909 lisp_string_width is the right thing, and will be
3910 done, but meanwhile we work with it. */
3911
3912 if (precision[n] == 0)
3913 width = nchars_string = nbytes = 0;
3914 else if (precision[n] > 0)
3915 width = lisp_string_width (args[n], precision[n], &nchars_string, &nbytes);
3916 else
3917 { /* no precision spec given for this argument */
3918 width = lisp_string_width (args[n], -1, NULL, NULL);
3919 nbytes = SBYTES (args[n]);
3920 nchars_string = SCHARS (args[n]);
3921 }
25c9e7fb
RS
3922
3923 /* If spec requires it, pad on right with spaces. */
3924 padding = minlen - width;
3925 if (! negative)
3926 while (padding-- > 0)
3927 {
3928 *p++ = ' ';
50606b4c 3929 ++nchars;
25c9e7fb 3930 }
1f24f4fd 3931
8f2c9ed8 3932 info[n].start = start = nchars;
ac42d7b9
KG
3933 nchars += nchars_string;
3934 end = nchars;
3935
8f2917e4
KH
3936 if (p > buf
3937 && multibyte
25aa5d64 3938 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
8f2917e4 3939 && STRING_MULTIBYTE (args[n])
d5db4077 3940 && !CHAR_HEAD_P (SREF (args[n], 0)))
8f2917e4 3941 maybe_combine_byte = 1;
ac42d7b9
KG
3942
3943 p += copy_text (SDATA (args[n]), p,
3944 nbytes,
3945 STRING_MULTIBYTE (args[n]), multibyte);
1f24f4fd 3946
8f2c9ed8
RS
3947 info[n].end = nchars;
3948
25c9e7fb
RS
3949 if (negative)
3950 while (padding-- > 0)
3951 {
3952 *p++ = ' ';
3953 nchars++;
3954 }
5e6d5493
GM
3955
3956 /* If this argument has text properties, record where
3957 in the result string it appears. */
d5db4077 3958 if (STRING_INTERVALS (args[n]))
d147ee84 3959 info[n].intervals = arg_intervals = 1;
1f24f4fd
RS
3960 }
3961 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3962 {
3963 int this_nchars;
3964
3965 bcopy (this_format_start, this_format,
3966 format - this_format_start);
3967 this_format[format - this_format_start] = 0;
3968
0f860bd7
AS
3969 if (format[-1] == 'e' || format[-1] == 'f' || format[-1] == 'g')
3970 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3971 else
de92d4d4 3972 {
ff6e6ac8
AS
3973 if (sizeof (EMACS_INT) > sizeof (int)
3974 && format[-1] != 'c')
0f860bd7
AS
3975 {
3976 /* Insert 'l' before format spec. */
3977 this_format[format - this_format_start]
3978 = this_format[format - this_format_start - 1];
3979 this_format[format - this_format_start - 1] = 'l';
3980 this_format[format - this_format_start + 1] = 0;
3981 }
3982
ff6e6ac8
AS
3983 if (INTEGERP (args[n]))
3984 {
3985 if (format[-1] == 'c')
3986 sprintf (p, this_format, (int) XINT (args[n]));
3987 else if (format[-1] == 'd')
3988 sprintf (p, this_format, XINT (args[n]));
3989 /* Don't sign-extend for octal or hex printing. */
3990 else
3991 sprintf (p, this_format, XUINT (args[n]));
3992 }
3993 else if (format[-1] == 'c')
3994 sprintf (p, this_format, (int) XFLOAT_DATA (args[n]));
3995 else if (format[-1] == 'd')
3996 /* Maybe we should use "%1.0f" instead so it also works
3997 for values larger than MAXINT. */
3998 sprintf (p, this_format, (EMACS_INT) XFLOAT_DATA (args[n]));
de92d4d4 3999 else
0f860bd7 4000 /* Don't sign-extend for octal or hex printing. */
ff6e6ac8 4001 sprintf (p, this_format, (EMACS_UINT) XFLOAT_DATA (args[n]));
de92d4d4 4002 }
1f24f4fd 4003
8f2917e4
KH
4004 if (p > buf
4005 && multibyte
25aa5d64
KH
4006 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4007 && !CHAR_HEAD_P (*((unsigned char *) p)))
8f2917e4 4008 maybe_combine_byte = 1;
1f24f4fd 4009 this_nchars = strlen (p);
9a599130 4010 if (multibyte)
7e2c051b 4011 p += str_to_multibyte (p, buf + total - 1 - p, this_nchars);
9a599130
KH
4012 else
4013 p += this_nchars;
1f24f4fd 4014 nchars += this_nchars;
8f2c9ed8 4015 info[n].end = nchars;
1f24f4fd 4016 }
d147ee84 4017
1f24f4fd 4018 }
7df74da6
RS
4019 else if (STRING_MULTIBYTE (args[0]))
4020 {
4021 /* Copy a whole multibyte character. */
8f2917e4
KH
4022 if (p > buf
4023 && multibyte
25aa5d64
KH
4024 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
4025 && !CHAR_HEAD_P (*format))
8f2917e4 4026 maybe_combine_byte = 1;
7df74da6 4027 *p++ = *format++;
d147ee84
RS
4028 while (! CHAR_HEAD_P (*format))
4029 {
4030 discarded[format - format_start] = 2;
4031 *p++ = *format++;
4032 }
7df74da6
RS
4033 nchars++;
4034 }
4035 else if (multibyte)
1f24f4fd
RS
4036 {
4037 /* Convert a single-byte character to multibyte. */
4038 int len = copy_text (format, p, 1, 0, 1);
4039
4040 p += len;
4041 format++;
4042 nchars++;
4043 }
4044 else
4045 *p++ = *format++, nchars++;
4046 }
4047
7e2c051b 4048 if (p > buf + total)
a432bfe5
GM
4049 abort ();
4050
8f2917e4
KH
4051 if (maybe_combine_byte)
4052 nchars = multibyte_chars_in_text (buf, p - buf);
5f75e666 4053 val = make_specified_string (buf, nchars, p - buf, multibyte);
8d6179dc 4054
1f24f4fd 4055 /* If we allocated BUF with malloc, free it too. */
e65837df 4056 SAFE_FREE ();
35692fe0 4057
5e6d5493
GM
4058 /* If the format string has text properties, or any of the string
4059 arguments has text properties, set up text properties of the
4060 result string. */
34a7a267 4061
d147ee84 4062 if (STRING_INTERVALS (args[0]) || arg_intervals)
5e6d5493
GM
4063 {
4064 Lisp_Object len, new_len, props;
4065 struct gcpro gcpro1;
34a7a267 4066
5e6d5493 4067 /* Add text properties from the format string. */
d5db4077 4068 len = make_number (SCHARS (args[0]));
5e6d5493
GM
4069 props = text_property_list (args[0], make_number (0), len, Qnil);
4070 GCPRO1 (props);
34a7a267 4071
5e6d5493
GM
4072 if (CONSP (props))
4073 {
d147ee84
RS
4074 int bytepos = 0, position = 0, translated = 0, argn = 1;
4075 Lisp_Object list;
4076
4077 /* Adjust the bounds of each text property
4078 to the proper start and end in the output string. */
d147ee84 4079
15fad037
KS
4080 /* Put the positions in PROPS in increasing order, so that
4081 we can do (effectively) one scan through the position
4082 space of the format string. */
4083 props = Fnreverse (props);
4084
4085 /* BYTEPOS is the byte position in the format string,
d147ee84
RS
4086 POSITION is the untranslated char position in it,
4087 TRANSLATED is the translated char position in BUF,
4088 and ARGN is the number of the next arg we will come to. */
4089 for (list = props; CONSP (list); list = XCDR (list))
4090 {
f3ce1df8
SM
4091 Lisp_Object item;
4092 int pos;
d147ee84
RS
4093
4094 item = XCAR (list);
4095
4096 /* First adjust the property start position. */
4097 pos = XINT (XCAR (item));
4098
4099 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4100 up to this position. */
4101 for (; position < pos; bytepos++)
4102 {
4103 if (! discarded[bytepos])
4104 position++, translated++;
4105 else if (discarded[bytepos] == 1)
4106 {
4107 position++;
4108 if (translated == info[argn].start)
4109 {
4110 translated += info[argn].end - info[argn].start;
4111 argn++;
4112 }
4113 }
4114 }
4115
4116 XSETCAR (item, make_number (translated));
4117
4118 /* Likewise adjust the property end position. */
4119 pos = XINT (XCAR (XCDR (item)));
4120
d40ec4a0 4121 for (; position < pos; bytepos++)
d147ee84
RS
4122 {
4123 if (! discarded[bytepos])
4124 position++, translated++;
4125 else if (discarded[bytepos] == 1)
4126 {
4127 position++;
4128 if (translated == info[argn].start)
4129 {
4130 translated += info[argn].end - info[argn].start;
4131 argn++;
4132 }
4133 }
4134 }
4135
4136 XSETCAR (XCDR (item), make_number (translated));
4137 }
4138
5e6d5493
GM
4139 add_text_properties_from_list (val, props, make_number (0));
4140 }
4141
4142 /* Add text properties from arguments. */
d147ee84 4143 if (arg_intervals)
5e6d5493 4144 for (n = 1; n < nargs; ++n)
d147ee84 4145 if (info[n].intervals)
5e6d5493 4146 {
d5db4077 4147 len = make_number (SCHARS (args[n]));
5e6d5493
GM
4148 new_len = make_number (info[n].end - info[n].start);
4149 props = text_property_list (args[n], make_number (0), len, Qnil);
4150 extend_property_ranges (props, len, new_len);
be17069b
KH
4151 /* If successive arguments have properites, be sure that
4152 the value of `composition' property be the copy. */
4153 if (n > 1 && info[n - 1].end)
4154 make_composition_value_copy (props);
5e6d5493
GM
4155 add_text_properties_from_list (val, props,
4156 make_number (info[n].start));
4157 }
4158
4159 UNGCPRO;
4160 }
4161
8d6179dc 4162 return val;
35692fe0
JB
4163}
4164
35692fe0 4165Lisp_Object
d40dc1d0 4166format2 (string1, arg0, arg1)
35692fe0 4167 char *string1;
d40dc1d0
RS
4168 Lisp_Object arg0, arg1;
4169{
4170 Lisp_Object args[3];
d40dc1d0
RS
4171 args[0] = build_string (string1);
4172 args[1] = arg0;
4173 args[2] = arg1;
4174 return Fformat (3, args);
35692fe0
JB
4175}
4176\f
4177DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
7ee72033 4178 doc: /* Return t if two characters match, optionally ignoring case.
a1f17501 4179Both arguments must be characters (i.e. integers).
7ee72033
MB
4180Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4181 (c1, c2)
35692fe0
JB
4182 register Lisp_Object c1, c2;
4183{
1b5d98bb 4184 int i1, i2;
253c3c82
SM
4185 /* Check they're chars, not just integers, otherwise we could get array
4186 bounds violations in DOWNCASE. */
4187 CHECK_CHARACTER (c1);
4188 CHECK_CHARACTER (c2);
35692fe0 4189
1b5d98bb 4190 if (XINT (c1) == XINT (c2))
35692fe0 4191 return Qt;
1b5d98bb
RS
4192 if (NILP (current_buffer->case_fold_search))
4193 return Qnil;
4194
4195 /* Do these in separate statements,
4196 then compare the variables.
4197 because of the way DOWNCASE uses temp variables. */
e5112ecb
KH
4198 i1 = XFASTINT (c1);
4199 if (NILP (current_buffer->enable_multibyte_characters)
4200 && ! ASCII_CHAR_P (i1))
4201 {
4202 MAKE_CHAR_MULTIBYTE (i1);
4203 }
4204 i2 = XFASTINT (c2);
4205 if (NILP (current_buffer->enable_multibyte_characters)
4206 && ! ASCII_CHAR_P (i2))
4207 {
4208 MAKE_CHAR_MULTIBYTE (i2);
4209 }
4210 i1 = DOWNCASE (i1);
4211 i2 = DOWNCASE (i2);
1b5d98bb 4212 return (i1 == i2 ? Qt : Qnil);
35692fe0 4213}
b229b8d1
RS
4214\f
4215/* Transpose the markers in two regions of the current buffer, and
4216 adjust the ones between them if necessary (i.e.: if the regions
4217 differ in size).
4218
ec1c14f6
RS
4219 START1, END1 are the character positions of the first region.
4220 START1_BYTE, END1_BYTE are the byte positions.
4221 START2, END2 are the character positions of the second region.
4222 START2_BYTE, END2_BYTE are the byte positions.
4223
b229b8d1
RS
4224 Traverses the entire marker list of the buffer to do so, adding an
4225 appropriate amount to some, subtracting from some, and leaving the
4226 rest untouched. Most of this is copied from adjust_markers in insdel.c.
34a7a267 4227
ec1c14f6 4228 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
b229b8d1 4229
acb7cc89 4230static void
ec1c14f6
RS
4231transpose_markers (start1, end1, start2, end2,
4232 start1_byte, end1_byte, start2_byte, end2_byte)
b229b8d1 4233 register int start1, end1, start2, end2;
ec1c14f6 4234 register int start1_byte, end1_byte, start2_byte, end2_byte;
b229b8d1 4235{
ec1c14f6 4236 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
12038f9f 4237 register struct Lisp_Marker *marker;
b229b8d1 4238
03240d11 4239 /* Update point as if it were a marker. */
8de1d5f0
KH
4240 if (PT < start1)
4241 ;
4242 else if (PT < end1)
ec1c14f6
RS
4243 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4244 PT_BYTE + (end2_byte - end1_byte));
8de1d5f0 4245 else if (PT < start2)
ec1c14f6
RS
4246 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4247 (PT_BYTE + (end2_byte - start2_byte)
4248 - (end1_byte - start1_byte)));
8de1d5f0 4249 else if (PT < end2)
ec1c14f6
RS
4250 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4251 PT_BYTE - (start2_byte - start1_byte));
8de1d5f0 4252
03240d11
KH
4253 /* We used to adjust the endpoints here to account for the gap, but that
4254 isn't good enough. Even if we assume the caller has tried to move the
4255 gap out of our way, it might still be at start1 exactly, for example;
4256 and that places it `inside' the interval, for our purposes. The amount
4257 of adjustment is nontrivial if there's a `denormalized' marker whose
4258 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4259 the dirty work to Fmarker_position, below. */
b229b8d1
RS
4260
4261 /* The difference between the region's lengths */
4262 diff = (end2 - start2) - (end1 - start1);
ec1c14f6 4263 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
34a7a267 4264
b229b8d1 4265 /* For shifting each marker in a region by the length of the other
ec1c14f6 4266 region plus the distance between the regions. */
b229b8d1
RS
4267 amt1 = (end2 - start2) + (start2 - end1);
4268 amt2 = (end1 - start1) + (start2 - end1);
ec1c14f6
RS
4269 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4270 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
b229b8d1 4271
12038f9f 4272 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
b229b8d1 4273 {
12038f9f 4274 mpos = marker->bytepos;
ec1c14f6
RS
4275 if (mpos >= start1_byte && mpos < end2_byte)
4276 {
4277 if (mpos < end1_byte)
4278 mpos += amt1_byte;
4279 else if (mpos < start2_byte)
4280 mpos += diff_byte;
4281 else
4282 mpos -= amt2_byte;
12038f9f 4283 marker->bytepos = mpos;
ec1c14f6 4284 }
12038f9f 4285 mpos = marker->charpos;
03240d11
KH
4286 if (mpos >= start1 && mpos < end2)
4287 {
4288 if (mpos < end1)
4289 mpos += amt1;
4290 else if (mpos < start2)
4291 mpos += diff;
4292 else
4293 mpos -= amt2;
03240d11 4294 }
12038f9f 4295 marker->charpos = mpos;
b229b8d1
RS
4296 }
4297}
4298
4299DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
412f1fab 4300 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
a1f17501
PJ
4301The regions may not be overlapping, because the size of the buffer is
4302never changed in a transposition.
4303
412f1fab 4304Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
a1f17501
PJ
4305any markers that happen to be located in the regions.
4306
7ee72033
MB
4307Transposing beyond buffer boundaries is an error. */)
4308 (startr1, endr1, startr2, endr2, leave_markers)
b229b8d1
RS
4309 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
4310{
d47ecf8b
SM
4311 register EMACS_INT start1, end1, start2, end2;
4312 EMACS_INT start1_byte, start2_byte, len1_byte, len2_byte;
4313 EMACS_INT gap, len1, len_mid, len2;
3c6bc7d0 4314 unsigned char *start1_addr, *start2_addr, *temp;
b229b8d1 4315
6cd0f478 4316 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
916480c4
CY
4317 Lisp_Object buf;
4318
4319 XSETBUFFER (buf, current_buffer);
1e158d25 4320 cur_intv = BUF_INTERVALS (current_buffer);
b229b8d1
RS
4321
4322 validate_region (&startr1, &endr1);
4323 validate_region (&startr2, &endr2);
4324
4325 start1 = XFASTINT (startr1);
4326 end1 = XFASTINT (endr1);
4327 start2 = XFASTINT (startr2);
4328 end2 = XFASTINT (endr2);
4329 gap = GPT;
4330
4331 /* Swap the regions if they're reversed. */
4332 if (start2 < end1)
4333 {
4334 register int glumph = start1;
4335 start1 = start2;
4336 start2 = glumph;
4337 glumph = end1;
4338 end1 = end2;
4339 end2 = glumph;
4340 }
4341
b229b8d1
RS
4342 len1 = end1 - start1;
4343 len2 = end2 - start2;
4344
4345 if (start2 < end1)
dc3620af 4346 error ("Transposed regions overlap");
b229b8d1 4347 else if (start1 == end1 || start2 == end2)
dc3620af 4348 error ("Transposed region has length 0");
b229b8d1
RS
4349
4350 /* The possibilities are:
4351 1. Adjacent (contiguous) regions, or separate but equal regions
4352 (no, really equal, in this case!), or
4353 2. Separate regions of unequal size.
34a7a267 4354
b229b8d1
RS
4355 The worst case is usually No. 2. It means that (aside from
4356 potential need for getting the gap out of the way), there also
4357 needs to be a shifting of the text between the two regions. So
4358 if they are spread far apart, we are that much slower... sigh. */
4359
4360 /* It must be pointed out that the really studly thing to do would
4361 be not to move the gap at all, but to leave it in place and work
4362 around it if necessary. This would be extremely efficient,
4363 especially considering that people are likely to do
4364 transpositions near where they are working interactively, which
4365 is exactly where the gap would be found. However, such code
4366 would be much harder to write and to read. So, if you are
4367 reading this comment and are feeling squirrely, by all means have
4368 a go! I just didn't feel like doing it, so I will simply move
4369 the gap the minimum distance to get it out of the way, and then
4370 deal with an unbroken array. */
3c6bc7d0
RS
4371
4372 /* Make sure the gap won't interfere, by moving it out of the text
4373 we will operate on. */
4374 if (start1 < gap && gap < end2)
4375 {
4376 if (gap - start1 < end2 - gap)
4377 move_gap (start1);
4378 else
4379 move_gap (end2);
4380 }
ec1c14f6
RS
4381
4382 start1_byte = CHAR_TO_BYTE (start1);
4383 start2_byte = CHAR_TO_BYTE (start2);
4384 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4385 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
dc3620af 4386
9a599130 4387#ifdef BYTE_COMBINING_DEBUG
dc3620af
RS
4388 if (end1 == start2)
4389 {
9a599130
KH
4390 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4391 len2_byte, start1, start1_byte)
4392 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4393 len1_byte, end2, start2_byte + len2_byte)
4394 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4395 len1_byte, end2, start2_byte + len2_byte))
4396 abort ();
dc3620af
RS
4397 }
4398 else
4399 {
9a599130
KH
4400 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4401 len2_byte, start1, start1_byte)
4402 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4403 len1_byte, start2, start2_byte)
4404 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4405 len2_byte, end1, start1_byte + len1_byte)
4406 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4407 len1_byte, end2, start2_byte + len2_byte))
4408 abort ();
dc3620af 4409 }
9a599130 4410#endif
dc3620af 4411
b229b8d1
RS
4412 /* Hmmm... how about checking to see if the gap is large
4413 enough to use as the temporary storage? That would avoid an
4414 allocation... interesting. Later, don't fool with it now. */
4415
4416 /* Working without memmove, for portability (sigh), so must be
4417 careful of overlapping subsections of the array... */
4418
4419 if (end1 == start2) /* adjacent regions */
4420 {
3e145152 4421 modify_region (current_buffer, start1, end2, 0);
b229b8d1
RS
4422 record_change (start1, len1 + len2);
4423
b229b8d1
RS
4424 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4425 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
916480c4
CY
4426 /* Don't use Fset_text_properties: that can cause GC, which can
4427 clobber objects stored in the tmp_intervals. */
6cd0f478
CY
4428 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4429 if (!NULL_INTERVAL_P (tmp_interval3))
4430 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
b229b8d1
RS
4431
4432 /* First region smaller than second. */
ec1c14f6 4433 if (len1_byte < len2_byte)
b229b8d1 4434 {
7e2c051b
KS
4435 USE_SAFE_ALLOCA;
4436
4437 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
03240d11
KH
4438
4439 /* Don't precompute these addresses. We have to compute them
4440 at the last minute, because the relocating allocator might
4441 have moved the buffer around during the xmalloc. */
23017390
KH
4442 start1_addr = BYTE_POS_ADDR (start1_byte);
4443 start2_addr = BYTE_POS_ADDR (start2_byte);
03240d11 4444
ec1c14f6
RS
4445 bcopy (start2_addr, temp, len2_byte);
4446 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
4447 bcopy (temp, start1_addr, len2_byte);
e65837df 4448 SAFE_FREE ();
b229b8d1
RS
4449 }
4450 else
4451 /* First region not smaller than second. */
4452 {
7e2c051b
KS
4453 USE_SAFE_ALLOCA;
4454
4455 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
23017390
KH
4456 start1_addr = BYTE_POS_ADDR (start1_byte);
4457 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
4458 bcopy (start1_addr, temp, len1_byte);
4459 bcopy (start2_addr, start1_addr, len2_byte);
4460 bcopy (temp, start1_addr + len2_byte, len1_byte);
e65837df 4461 SAFE_FREE ();
b229b8d1 4462 }
b229b8d1
RS
4463 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4464 len1, current_buffer, 0);
4465 graft_intervals_into_buffer (tmp_interval2, start1,
4466 len2, current_buffer, 0);
d5c2c403
KH
4467 update_compositions (start1, start1 + len2, CHECK_BORDER);
4468 update_compositions (start1 + len2, end2, CHECK_TAIL);
b229b8d1
RS
4469 }
4470 /* Non-adjacent regions, because end1 != start2, bleagh... */
4471 else
4472 {
ec1c14f6
RS
4473 len_mid = start2_byte - (start1_byte + len1_byte);
4474
4475 if (len1_byte == len2_byte)
b229b8d1
RS
4476 /* Regions are same size, though, how nice. */
4477 {
7e2c051b
KS
4478 USE_SAFE_ALLOCA;
4479
3e145152
CY
4480 modify_region (current_buffer, start1, end1, 0);
4481 modify_region (current_buffer, start2, end2, 0);
b229b8d1
RS
4482 record_change (start1, len1);
4483 record_change (start2, len2);
b229b8d1
RS
4484 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4485 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
6cd0f478
CY
4486
4487 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4488 if (!NULL_INTERVAL_P (tmp_interval3))
4489 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4490
4491 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4492 if (!NULL_INTERVAL_P (tmp_interval3))
4493 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
b229b8d1 4494
7e2c051b 4495 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
23017390
KH
4496 start1_addr = BYTE_POS_ADDR (start1_byte);
4497 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
4498 bcopy (start1_addr, temp, len1_byte);
4499 bcopy (start2_addr, start1_addr, len2_byte);
4500 bcopy (temp, start2_addr, len1_byte);
e65837df 4501 SAFE_FREE ();
7e2c051b 4502
b229b8d1
RS
4503 graft_intervals_into_buffer (tmp_interval1, start2,
4504 len1, current_buffer, 0);
4505 graft_intervals_into_buffer (tmp_interval2, start1,
4506 len2, current_buffer, 0);
b229b8d1
RS
4507 }
4508
ec1c14f6 4509 else if (len1_byte < len2_byte) /* Second region larger than first */
b229b8d1
RS
4510 /* Non-adjacent & unequal size, area between must also be shifted. */
4511 {
7e2c051b
KS
4512 USE_SAFE_ALLOCA;
4513
3e145152 4514 modify_region (current_buffer, start1, end2, 0);
b229b8d1 4515 record_change (start1, (end2 - start1));
b229b8d1
RS
4516 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4517 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4518 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
6cd0f478
CY
4519
4520 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4521 if (!NULL_INTERVAL_P (tmp_interval3))
4522 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
b229b8d1 4523
3c6bc7d0 4524 /* holds region 2 */
7e2c051b 4525 SAFE_ALLOCA (temp, unsigned char *, len2_byte);
23017390
KH
4526 start1_addr = BYTE_POS_ADDR (start1_byte);
4527 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
4528 bcopy (start2_addr, temp, len2_byte);
4529 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
4530 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4531 bcopy (temp, start1_addr, len2_byte);
e65837df 4532 SAFE_FREE ();
7e2c051b 4533
b229b8d1
RS
4534 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4535 len1, current_buffer, 0);
4536 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4537 len_mid, current_buffer, 0);
4538 graft_intervals_into_buffer (tmp_interval2, start1,
4539 len2, current_buffer, 0);
b229b8d1
RS
4540 }
4541 else
4542 /* Second region smaller than first. */
4543 {
7e2c051b
KS
4544 USE_SAFE_ALLOCA;
4545
b229b8d1 4546 record_change (start1, (end2 - start1));
3e145152 4547 modify_region (current_buffer, start1, end2, 0);
b229b8d1 4548
b229b8d1
RS
4549 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4550 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4551 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
6cd0f478
CY
4552
4553 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4554 if (!NULL_INTERVAL_P (tmp_interval3))
4555 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
b229b8d1 4556
3c6bc7d0 4557 /* holds region 1 */
7e2c051b 4558 SAFE_ALLOCA (temp, unsigned char *, len1_byte);
23017390
KH
4559 start1_addr = BYTE_POS_ADDR (start1_byte);
4560 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
4561 bcopy (start1_addr, temp, len1_byte);
4562 bcopy (start2_addr, start1_addr, len2_byte);
4563 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
4564 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
e65837df 4565 SAFE_FREE ();
7e2c051b 4566
b229b8d1
RS
4567 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4568 len1, current_buffer, 0);
4569 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4570 len_mid, current_buffer, 0);
4571 graft_intervals_into_buffer (tmp_interval2, start1,
4572 len2, current_buffer, 0);
b229b8d1 4573 }
d5c2c403
KH
4574
4575 update_compositions (start1, start1 + len2, CHECK_BORDER);
4576 update_compositions (end2 - len1, end2, CHECK_BORDER);
b229b8d1
RS
4577 }
4578
ec1c14f6
RS
4579 /* When doing multiple transpositions, it might be nice
4580 to optimize this. Perhaps the markers in any one buffer
4581 should be organized in some sorted data tree. */
b229b8d1 4582 if (NILP (leave_markers))
8de1d5f0 4583 {
ec1c14f6
RS
4584 transpose_markers (start1, end1, start2, end2,
4585 start1_byte, start1_byte + len1_byte,
4586 start2_byte, start2_byte + len2_byte);
6b61353c 4587 fix_start_end_in_overlays (start1, end2);
8de1d5f0 4588 }
b229b8d1 4589
c10b2810 4590 signal_after_change (start1, end2 - start1, end2 - start1);
b229b8d1
RS
4591 return Qnil;
4592}
35692fe0 4593
35692fe0
JB
4594\f
4595void
4596syms_of_editfns ()
4597{
260e2e2a 4598 environbuf = 0;
a03fc5a6 4599 initial_tz = 0;
260e2e2a
KH
4600
4601 Qbuffer_access_fontify_functions
4602 = intern ("buffer-access-fontify-functions");
4603 staticpro (&Qbuffer_access_fontify_functions);
4604
7ee72033 4605 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
7dcece14 4606 doc: /* Non-nil means text motion commands don't notice fields. */);
9a74e7e5
GM
4607 Vinhibit_field_text_motion = Qnil;
4608
260e2e2a 4609 DEFVAR_LISP ("buffer-access-fontify-functions",
7ee72033
MB
4610 &Vbuffer_access_fontify_functions,
4611 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
a1f17501
PJ
4612Each function is called with two arguments which specify the range
4613of the buffer being accessed. */);
260e2e2a
KH
4614 Vbuffer_access_fontify_functions = Qnil;
4615
af209db8
RS
4616 {
4617 Lisp_Object obuf;
4618 extern Lisp_Object Vprin1_to_string_buffer;
4619 obuf = Fcurrent_buffer ();
4620 /* Do this here, because init_buffer_once is too early--it won't work. */
4621 Fset_buffer (Vprin1_to_string_buffer);
4622 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4623 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
4624 Qnil);
4625 Fset_buffer (obuf);
4626 }
4627
0b6fd023 4628 DEFVAR_LISP ("buffer-access-fontified-property",
7ee72033
MB
4629 &Vbuffer_access_fontified_property,
4630 doc: /* Property which (if non-nil) indicates text has been fontified.
a1f17501
PJ
4631`buffer-substring' need not call the `buffer-access-fontify-functions'
4632functions if all the text being accessed has this property. */);
260e2e2a
KH
4633 Vbuffer_access_fontified_property = Qnil;
4634
7ee72033 4635 DEFVAR_LISP ("system-name", &Vsystem_name,
1a7e0117 4636 doc: /* The host name of the machine Emacs is running on. */);
34a7a267 4637
7ee72033
MB
4638 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
4639 doc: /* The full name of the user logged in. */);
f43754f6 4640
7ee72033
MB
4641 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
4642 doc: /* The user's name, taken from environment variables if possible. */);
f43754f6 4643
7ee72033
MB
4644 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
4645 doc: /* The user's name, based upon the real uid only. */);
35692fe0 4646
3bb9abc8
ST
4647 DEFVAR_LISP ("operating-system-release", &Voperating_system_release,
4648 doc: /* The release of the operating system Emacs is running on. */);
4649
0963334d 4650 defsubr (&Spropertize);
35692fe0
JB
4651 defsubr (&Schar_equal);
4652 defsubr (&Sgoto_char);
4653 defsubr (&Sstring_to_char);
4654 defsubr (&Schar_to_string);
4655 defsubr (&Sbuffer_substring);
260e2e2a 4656 defsubr (&Sbuffer_substring_no_properties);
35692fe0
JB
4657 defsubr (&Sbuffer_string);
4658
4659 defsubr (&Spoint_marker);
4660 defsubr (&Smark_marker);
4661 defsubr (&Spoint);
4662 defsubr (&Sregion_beginning);
4663 defsubr (&Sregion_end);
7df74da6 4664
0daf6e8d
GM
4665 staticpro (&Qfield);
4666 Qfield = intern ("field");
ee547125
MB
4667 staticpro (&Qboundary);
4668 Qboundary = intern ("boundary");
0daf6e8d
GM
4669 defsubr (&Sfield_beginning);
4670 defsubr (&Sfield_end);
4671 defsubr (&Sfield_string);
4672 defsubr (&Sfield_string_no_properties);
8bf64fe8 4673 defsubr (&Sdelete_field);
0daf6e8d
GM
4674 defsubr (&Sconstrain_to_field);
4675
7df74da6
RS
4676 defsubr (&Sline_beginning_position);
4677 defsubr (&Sline_end_position);
4678
35692fe0
JB
4679/* defsubr (&Smark); */
4680/* defsubr (&Sset_mark); */
4681 defsubr (&Ssave_excursion);
4bc8c7d2 4682 defsubr (&Ssave_current_buffer);
35692fe0
JB
4683
4684 defsubr (&Sbufsize);
4685 defsubr (&Spoint_max);
4686 defsubr (&Spoint_min);
4687 defsubr (&Spoint_min_marker);
4688 defsubr (&Spoint_max_marker);
c86212b9
RS
4689 defsubr (&Sgap_position);
4690 defsubr (&Sgap_size);
7df74da6 4691 defsubr (&Sposition_bytes);
3ab0732d 4692 defsubr (&Sbyte_to_position);
c9ed721d 4693
35692fe0
JB
4694 defsubr (&Sbobp);
4695 defsubr (&Seobp);
4696 defsubr (&Sbolp);
4697 defsubr (&Seolp);
850a8179
JB
4698 defsubr (&Sfollowing_char);
4699 defsubr (&Sprevious_char);
35692fe0 4700 defsubr (&Schar_after);
fb8106e8 4701 defsubr (&Schar_before);
35692fe0
JB
4702 defsubr (&Sinsert);
4703 defsubr (&Sinsert_before_markers);
be91036a
RS
4704 defsubr (&Sinsert_and_inherit);
4705 defsubr (&Sinsert_and_inherit_before_markers);
35692fe0 4706 defsubr (&Sinsert_char);
48ef988f 4707 defsubr (&Sinsert_byte);
35692fe0
JB
4708
4709 defsubr (&Suser_login_name);
4710 defsubr (&Suser_real_login_name);
4711 defsubr (&Suser_uid);
4712 defsubr (&Suser_real_uid);
4713 defsubr (&Suser_full_name);
7fd233b3 4714 defsubr (&Semacs_pid);
d940e0e4 4715 defsubr (&Scurrent_time);
4211ee7d 4716 defsubr (&Sget_internal_run_time);
a82d387c 4717 defsubr (&Sformat_time_string);
34a7a267 4718 defsubr (&Sfloat_time);
4691c06d 4719 defsubr (&Sdecode_time);
cce7b8a0 4720 defsubr (&Sencode_time);
35692fe0 4721 defsubr (&Scurrent_time_string);
c2662aea 4722 defsubr (&Scurrent_time_zone);
143cb9a9 4723 defsubr (&Sset_time_zone_rule);
35692fe0 4724 defsubr (&Ssystem_name);
35692fe0 4725 defsubr (&Smessage);
cacc3e2c
RS
4726 defsubr (&Smessage_box);
4727 defsubr (&Smessage_or_box);
b14dda8a 4728 defsubr (&Scurrent_message);
35692fe0 4729 defsubr (&Sformat);
35692fe0
JB
4730
4731 defsubr (&Sinsert_buffer_substring);
e9cf2084 4732 defsubr (&Scompare_buffer_substrings);
35692fe0 4733 defsubr (&Ssubst_char_in_region);
8583605b 4734 defsubr (&Stranslate_region_internal);
35692fe0 4735 defsubr (&Sdelete_region);
7dae4502 4736 defsubr (&Sdelete_and_extract_region);
35692fe0
JB
4737 defsubr (&Swiden);
4738 defsubr (&Snarrow_to_region);
4739 defsubr (&Ssave_restriction);
b229b8d1 4740 defsubr (&Stranspose_regions);
35692fe0 4741}
f555f8cf
KH
4742
4743/* arch-tag: fc3827d8-6f60-4067-b11e-c3218031b018
4744 (do not change this comment) */