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