(set_lface_from_font_name): Fix incomplete merge.
[bpt/emacs.git] / src / editfns.c
CommitLineData
35692fe0 1/* Lisp functions pertaining to editing.
0daf6e8d 2 Copyright (C) 1985,86,87,89,93,94,95,96,97,98, 1999 Free Software Foundation, Inc.
35692fe0
JB
3
4This file is part of GNU Emacs.
5
6GNU Emacs is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
7c938215 8the Free Software Foundation; either version 2, or (at your option)
35692fe0
JB
9any later version.
10
11GNU Emacs is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with GNU Emacs; see the file COPYING. If not, write to
5a7670bf
RS
18the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19Boston, MA 02111-1307, USA. */
35692fe0
JB
20
21
18160b98 22#include <config.h>
68c45bf0 23#include <sys/types.h>
bfb61299
JB
24
25#ifdef VMS
956ace37 26#include "vms-pwd.h"
bfb61299 27#else
35692fe0 28#include <pwd.h>
bfb61299
JB
29#endif
30
dfcf069d
AS
31#ifdef HAVE_UNISTD_H
32#include <unistd.h>
33#endif
34
35692fe0 35#include "lisp.h"
74d6d8c5 36#include "intervals.h"
35692fe0 37#include "buffer.h"
fb8106e8 38#include "charset.h"
68c45bf0 39#include "coding.h"
35692fe0
JB
40#include "window.h"
41
956ace37 42#include "systime.h"
35692fe0
JB
43
44#define min(a, b) ((a) < (b) ? (a) : (b))
45#define max(a, b) ((a) > (b) ? (a) : (b))
46
a03eaf1c
RS
47#ifndef NULL
48#define NULL 0
49#endif
50
c59b5089 51extern char **environ;
5920df33 52extern int use_dialog_box;
c59b5089 53extern Lisp_Object make_time ();
b1b0ee5a 54extern void insert_from_buffer ();
94751666 55static int tm_diff ();
260e2e2a 56static void update_buffer_properties ();
68c45bf0 57size_t emacs_strftimeu ();
a92ae0ce 58void set_time_zone_rule ();
260e2e2a
KH
59
60Lisp_Object Vbuffer_access_fontify_functions;
61Lisp_Object Qbuffer_access_fontify_functions;
62Lisp_Object Vbuffer_access_fontified_property;
b1b0ee5a 63
e3ed8469
KH
64Lisp_Object Fuser_full_name ();
65
35692fe0
JB
66/* Some static data, and a function to initialize it for each run */
67
68Lisp_Object Vsystem_name;
35b34f72
KH
69Lisp_Object Vuser_real_login_name; /* login name of current user ID */
70Lisp_Object Vuser_full_name; /* full name of current user */
71Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
35692fe0
JB
72
73void
74init_editfns ()
75{
52b14ac0 76 char *user_name;
2ea0266e 77 register unsigned char *p;
35692fe0 78 struct passwd *pw; /* password entry for the current user */
35692fe0
JB
79 Lisp_Object tem;
80
81 /* Set up system_name even when dumping. */
ac988277 82 init_system_name ();
35692fe0
JB
83
84#ifndef CANNOT_DUMP
85 /* Don't bother with this on initial start when just dumping out */
86 if (!initialized)
87 return;
88#endif /* not CANNOT_DUMP */
89
90 pw = (struct passwd *) getpwuid (getuid ());
87485d6f
MW
91#ifdef MSDOS
92 /* We let the real user name default to "root" because that's quite
93 accurate on MSDOG and because it lets Emacs find the init file.
94 (The DVX libraries override the Djgpp libraries here.) */
35b34f72 95 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
87485d6f 96#else
35b34f72 97 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
87485d6f 98#endif
35692fe0 99
52b14ac0
JB
100 /* Get the effective user name, by consulting environment variables,
101 or the effective uid if those are unset. */
2c9ae24e 102 user_name = (char *) getenv ("LOGNAME");
35692fe0 103 if (!user_name)
4691c06d
RS
104#ifdef WINDOWSNT
105 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
106#else /* WINDOWSNT */
2c9ae24e 107 user_name = (char *) getenv ("USER");
4691c06d 108#endif /* WINDOWSNT */
52b14ac0
JB
109 if (!user_name)
110 {
111 pw = (struct passwd *) getpwuid (geteuid ());
112 user_name = (char *) (pw ? pw->pw_name : "unknown");
113 }
35b34f72 114 Vuser_login_name = build_string (user_name);
35692fe0 115
52b14ac0
JB
116 /* If the user name claimed in the environment vars differs from
117 the real uid, use the claimed name to find the full name. */
35b34f72 118 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
3415b0e9
RS
119 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
120 : Vuser_login_name);
35692fe0 121
8f1e2d16 122 p = (unsigned char *) getenv ("NAME");
9d36d071
RS
123 if (p)
124 Vuser_full_name = build_string (p);
3347526c
RS
125 else if (NILP (Vuser_full_name))
126 Vuser_full_name = build_string ("unknown");
35692fe0
JB
127}
128\f
129DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
5f75e666 130 "Convert arg CHAR to a string containing that character.")
2591ec64
EN
131 (character)
132 Lisp_Object character;
35692fe0 133{
fb8106e8 134 int len;
d11ba98c 135 unsigned char workbuf[4], *str;
fb8106e8 136
2591ec64 137 CHECK_NUMBER (character, 0);
35692fe0 138
fb8106e8 139 len = CHAR_STRING (XFASTINT (character), workbuf, str);
5f75e666 140 return make_string_from_bytes (str, 1, len);
35692fe0
JB
141}
142
143DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
fb8106e8
KH
144 "Convert arg STRING to a character, the first character of that string.\n\
145A multibyte character is handled correctly.")
2591ec64
EN
146 (string)
147 register Lisp_Object string;
35692fe0
JB
148{
149 register Lisp_Object val;
150 register struct Lisp_String *p;
2591ec64 151 CHECK_STRING (string, 0);
2591ec64 152 p = XSTRING (string);
35692fe0 153 if (p->size)
d9d851ea
KH
154 {
155 if (STRING_MULTIBYTE (string))
156 XSETFASTINT (val, STRING_CHAR (p->data, STRING_BYTES (p)));
157 else
158 XSETFASTINT (val, p->data[0]);
159 }
35692fe0 160 else
55561c63 161 XSETFASTINT (val, 0);
35692fe0
JB
162 return val;
163}
164\f
165static Lisp_Object
ec1c14f6
RS
166buildmark (charpos, bytepos)
167 int charpos, bytepos;
35692fe0
JB
168{
169 register Lisp_Object mark;
170 mark = Fmake_marker ();
ec1c14f6 171 set_marker_both (mark, Qnil, charpos, bytepos);
35692fe0
JB
172 return mark;
173}
174
175DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
176 "Return value of point, as an integer.\n\
177Beginning of buffer is position (point-min)")
178 ()
179{
180 Lisp_Object temp;
6ec8bbd2 181 XSETFASTINT (temp, PT);
35692fe0
JB
182 return temp;
183}
184
185DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
186 "Return value of point, as a marker object.")
187 ()
188{
ec1c14f6 189 return buildmark (PT, PT_BYTE);
35692fe0
JB
190}
191
192int
193clip_to_bounds (lower, num, upper)
194 int lower, num, upper;
195{
196 if (num < lower)
197 return lower;
198 else if (num > upper)
199 return upper;
200 else
201 return num;
202}
203
204DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
205 "Set point to POSITION, a number or marker.\n\
fb8106e8
KH
206Beginning of buffer is position (point-min), end is (point-max).\n\
207If the position is in the middle of a multibyte form,\n\
208the actual point is set at the head of the multibyte form\n\
209except in the case that `enable-multibyte-characters' is nil.")
2591ec64
EN
210 (position)
211 register Lisp_Object position;
35692fe0 212{
fb8106e8 213 int pos;
fb8106e8 214
72ef82ec
RS
215 if (MARKERP (position)
216 && current_buffer == XMARKER (position)->buffer)
ec1c14f6
RS
217 {
218 pos = marker_position (position);
219 if (pos < BEGV)
220 SET_PT_BOTH (BEGV, BEGV_BYTE);
221 else if (pos > ZV)
222 SET_PT_BOTH (ZV, ZV_BYTE);
223 else
224 SET_PT_BOTH (pos, marker_byte_position (position));
225
226 return position;
227 }
228
2591ec64 229 CHECK_NUMBER_COERCE_MARKER (position, 0);
35692fe0 230
fb8106e8 231 pos = clip_to_bounds (BEGV, XINT (position), ZV);
fb8106e8 232 SET_PT (pos);
2591ec64 233 return position;
35692fe0
JB
234}
235
236static Lisp_Object
237region_limit (beginningp)
238 int beginningp;
239{
646d9d18 240 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
35692fe0 241 register Lisp_Object m;
c9dd14e1
RM
242 if (!NILP (Vtransient_mark_mode) && NILP (Vmark_even_if_inactive)
243 && NILP (current_buffer->mark_active))
244 Fsignal (Qmark_inactive, Qnil);
35692fe0 245 m = Fmarker_position (current_buffer->mark);
56a98455 246 if (NILP (m)) error ("There is no region now");
6ec8bbd2
KH
247 if ((PT < XFASTINT (m)) == beginningp)
248 return (make_number (PT));
35692fe0
JB
249 else
250 return (m);
251}
252
253DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
254 "Return position of beginning of region, as an integer.")
255 ()
256{
257 return (region_limit (1));
258}
259
260DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
261 "Return position of end of region, as an integer.")
262 ()
263{
264 return (region_limit (0));
265}
266
35692fe0
JB
267DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
268 "Return this buffer's mark, as a marker object.\n\
269Watch out! Moving this marker changes the mark position.\n\
270If you set the marker not to point anywhere, the buffer will have no mark.")
271 ()
272{
273 return current_buffer->mark;
274}
c9ed721d 275\f
a3caef99
RS
276/* Return nonzero if POS1 and POS2 have the same value
277 for the text property PROP. */
0daf6e8d 278
0daf6e8d
GM
279static int
280text_property_eq (prop, pos1, pos2)
281 Lisp_Object prop;
282 Lisp_Object pos1, pos2;
283{
284 Lisp_Object pval1, pval2;
285
286 pval1 = Fget_text_property (pos1, prop, Qnil);
287 pval2 = Fget_text_property (pos2, prop, Qnil);
288
289 return EQ (pval1, pval2);
290}
291
a3caef99
RS
292/* Return the direction from which the text-property PROP would be
293 inherited by any new text inserted at POS: 1 if it would be
294 inherited from the char after POS, -1 if it would be inherited from
295 the char before POS, and 0 if from neither. */
296
0daf6e8d
GM
297static int
298text_property_stickiness (prop, pos)
299 Lisp_Object prop;
300 Lisp_Object pos;
301{
302 Lisp_Object front_sticky;
303
a3caef99
RS
304 if (XINT (pos) > BEGV)
305 /* Consider previous character. */
0daf6e8d
GM
306 {
307 Lisp_Object prev_pos, rear_non_sticky;
308
a3caef99 309 prev_pos = make_number (XINT (pos) - 1);
0daf6e8d
GM
310 rear_non_sticky = Fget_text_property (prev_pos, Qrear_nonsticky, Qnil);
311
312 if (EQ (rear_non_sticky, Qnil)
313 || (CONSP (rear_non_sticky)
314 && !Fmemq (prop, rear_non_sticky)))
315 /* PROP is not rear-non-sticky, and since this takes precedence over
a3caef99 316 any front-stickiness, PROP is inherited from before. */
0daf6e8d
GM
317 return -1;
318 }
319
a3caef99 320 /* Consider following character. */
0daf6e8d
GM
321 front_sticky = Fget_text_property (pos, Qfront_sticky, Qnil);
322
323 if (EQ (front_sticky, Qt)
324 || (CONSP (front_sticky)
325 && Fmemq (prop, front_sticky)))
a3caef99 326 /* PROP is inherited from after. */
0daf6e8d
GM
327 return 1;
328
a3caef99 329 /* PROP is not inherited from either side. */
0daf6e8d
GM
330 return 0;
331}
332\f
a3caef99 333/* Symbol for the text property used to mark fields. */
0daf6e8d
GM
334Lisp_Object Qfield;
335
a3caef99
RS
336/* Find the field surrounding POS in *BEG and *END. If POS is nil,
337 the value of point is used instead.
338
339 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
0daf6e8d
GM
340 position of a field, then the beginning of the previous field
341 is returned instead of the beginning of POS's field (since the end of
342 a field is actually also the beginning of the next input
a3caef99
RS
343 field, this behavior is sometimes useful).
344
345 Either BEG or END may be 0, in which case the corresponding value
346 is not stored. */
347
0daf6e8d
GM
348void
349find_field (pos, merge_at_boundary, beg, end)
350 Lisp_Object pos;
351 Lisp_Object merge_at_boundary;
352 int *beg, *end;
353{
a3caef99
RS
354 /* 1 if POS counts as the start of a field. */
355 int at_field_start = 0;
356 /* 1 if POS counts as the end of a field. */
357 int at_field_end = 0;
0daf6e8d
GM
358
359 if (NILP (pos))
360 XSETFASTINT (pos, PT);
361 else
362 CHECK_NUMBER_COERCE_MARKER (pos, 0);
363
364 if (NILP (merge_at_boundary) && XFASTINT (pos) > BEGV)
365 /* See if we need to handle the case where POS is at beginning of a
366 field, which can also be interpreted as the end of the previous
367 field. We decide which one by seeing which field the `field'
368 property sticks to. The case where if MERGE_AT_BOUNDARY is
369 non-nil (see function comment) is actually the more natural one;
370 then we avoid treating the beginning of a field specially. */
371 {
372 /* First see if POS is actually *at* a boundary. */
373 Lisp_Object after_field, before_field;
374
375 after_field = Fget_text_property (pos, Qfield, Qnil);
a3caef99
RS
376 before_field = Fget_text_property (make_number (XINT (pos) - 1),
377 Qfield, Qnil);
0daf6e8d
GM
378
379 if (! EQ (after_field, before_field))
380 /* We are at a boundary, see which direction is inclusive. */
381 {
a3caef99 382 int stickiness = text_property_stickiness (Qfield, pos);
0daf6e8d 383
a3caef99
RS
384 if (stickiness > 0)
385 at_field_start = 1;
386 else if (stickiness < 0)
387 at_field_end = 1;
388 else
0daf6e8d
GM
389 /* STICKINESS == 0 means that any inserted text will get a
390 `field' text-property of nil, so check to see if that
391 matches either of the adjacent characters (this being a
a3caef99 392 kind of "stickiness by default"). */
0daf6e8d
GM
393 {
394 if (NILP (before_field))
a3caef99 395 at_field_end = 1; /* Sticks to the left. */
0daf6e8d 396 else if (NILP (after_field))
a3caef99 397 at_field_start = 1; /* Sticks to the right. */
0daf6e8d
GM
398 }
399 }
400 }
401
402 if (beg)
403 {
a3caef99 404 if (at_field_start)
0daf6e8d
GM
405 /* POS is at the edge of a field, and we should consider it as
406 the beginning of the following field. */
407 *beg = XFASTINT (pos);
408 else
409 /* Find the previous field boundary. */
410 {
411 Lisp_Object prev;
412 prev = Fprevious_single_property_change (pos, Qfield, Qnil, Qnil);
a3caef99 413 *beg = NILP (prev) ? BEGV : XFASTINT (prev);
0daf6e8d
GM
414 }
415 }
416
417 if (end)
418 {
a3caef99 419 if (at_field_end)
0daf6e8d
GM
420 /* POS is at the edge of a field, and we should consider it as
421 the end of the previous field. */
422 *end = XFASTINT (pos);
423 else
424 /* Find the next field boundary. */
425 {
426 Lisp_Object next;
427 next = Fnext_single_property_change (pos, Qfield, Qnil, Qnil);
a3caef99 428 *end = NILP (next) ? ZV : XFASTINT (next);
0daf6e8d
GM
429 }
430 }
431}
432\f
d01f3570 433DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
8bf64fe8 434 "Delete the field surrounding POS.\n\
0daf6e8d 435A field is a region of text with the same `field' property.\n\
a3caef99 436If POS is nil, the value of point is used for POS.")
0daf6e8d
GM
437 (pos)
438 Lisp_Object pos;
439{
440 int beg, end;
441 find_field (pos, Qnil, &beg, &end);
442 if (beg != end)
443 del_range (beg, end);
d01f3570 444 return Qnil;
0daf6e8d
GM
445}
446
447DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
448 "Return the contents of the field surrounding POS as a string.\n\
449A field is a region of text with the same `field' property.\n\
a3caef99 450If POS is nil, the value of point is used for POS.")
0daf6e8d
GM
451 (pos)
452 Lisp_Object pos;
453{
454 int beg, end;
455 find_field (pos, Qnil, &beg, &end);
456 return make_buffer_string (beg, end, 1);
457}
458
459DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
460 "Return the contents of the field around POS, without text-properties.\n\
461A field is a region of text with the same `field' property.\n\
a3caef99 462If POS is nil, the value of point is used for POS.")
0daf6e8d
GM
463 (pos)
464 Lisp_Object pos;
465{
466 int beg, end;
467 find_field (pos, Qnil, &beg, &end);
468 return make_buffer_string (beg, end, 0);
469}
470
471DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 2, 0,
472 "Return the beginning of the field surrounding POS.\n\
473A field is a region of text with the same `field' property.\n\
a3caef99
RS
474If POS is nil, the value of point is used for POS.\n\
475If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its\n\
0daf6e8d
GM
476field, then the beginning of the *previous* field is returned.")
477 (pos, escape_from_edge)
478 Lisp_Object pos, escape_from_edge;
479{
480 int beg;
481 find_field (pos, escape_from_edge, &beg, 0);
482 return make_number (beg);
483}
484
485DEFUN ("field-end", Ffield_end, Sfield_end, 0, 2, 0,
486 "Return the end of the field surrounding POS.\n\
487A field is a region of text with the same `field' property.\n\
a3caef99
RS
488If POS is nil, the value of point is used for POS.\n\
489If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,\n\
0daf6e8d
GM
490then the end of the *following* field is returned.")
491 (pos, escape_from_edge)
492 Lisp_Object pos, escape_from_edge;
493{
494 int end;
495 find_field (pos, escape_from_edge, 0, &end);
496 return make_number (end);
497}
498
499DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 4, 0,
500 "Return the position closest to NEW-POS that is in the same field as OLD-POS.\n\
501A field is a region of text with the same `field' property.\n\
502If NEW-POS is nil, then the current point is used instead, and set to the\n\
503constrained position if that is is different.\n\
504\n\
505If OLD-POS is at the boundary of two fields, then the allowable\n\
506positions for NEW-POS depends on the value of the optional argument\n\
507ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is\n\
508constrained to the field that has the same `field' text-property\n\
509as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE\n\
510is non-nil, NEW-POS is constrained to the union of the two adjacent\n\
511fields.\n\
512\n\
513If the optional argument ONLY-IN-LINE is non-nil and constraining\n\
514NEW-POS would move it to a different line, NEW-POS is returned\n\
515unconstrained. This useful for commands that move by line, like\n\
516\\[next-line] or \\[beginning-of-line], which should generally respect field boundaries\n\
517only in the case where they can still move to the right line.")
518 (new_pos, old_pos, escape_from_edge, only_in_line)
519 Lisp_Object new_pos, old_pos, escape_from_edge, only_in_line;
520{
521 /* If non-zero, then the original point, before re-positioning. */
522 int orig_point = 0;
523
524 if (NILP (new_pos))
525 /* Use the current point, and afterwards, set it. */
526 {
527 orig_point = PT;
528 XSETFASTINT (new_pos, PT);
529 }
530
531 if (!EQ (new_pos, old_pos) && !text_property_eq (Qfield, new_pos, old_pos))
532 /* NEW_POS is not within the same field as OLD_POS; try to
533 move NEW_POS so that it is. */
534 {
535 int fwd;
536 Lisp_Object field_bound;
537
538 CHECK_NUMBER_COERCE_MARKER (new_pos, 0);
539 CHECK_NUMBER_COERCE_MARKER (old_pos, 0);
540
541 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
542
543 if (fwd)
544 field_bound = Ffield_end (old_pos, escape_from_edge);
545 else
546 field_bound = Ffield_beginning (old_pos, escape_from_edge);
547
548 if (/* If ONLY_IN_LINE is non-nil, we only constrain NEW_POS if doing
549 so would remain within the same line. */
550 NILP (only_in_line)
551 /* In that case, see if ESCAPE_FROM_EDGE caused FIELD_BOUND
552 to jump to the other side of NEW_POS, which would mean
553 that NEW_POS is already acceptable, and that we don't
554 have to do the line-check. */
555 || ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? !fwd : fwd)
556 /* If not, see if there's no newline intervening between
557 NEW_POS and FIELD_BOUND. */
558 || (find_before_next_newline (XFASTINT (new_pos),
559 XFASTINT (field_bound),
560 fwd ? -1 : 1)
561 == XFASTINT (field_bound)))
562 /* Constrain NEW_POS to FIELD_BOUND. */
563 new_pos = field_bound;
564
565 if (orig_point && XFASTINT (new_pos) != orig_point)
566 /* The NEW_POS argument was originally nil, so automatically set PT. */
567 SET_PT (XFASTINT (new_pos));
568 }
569
570 return new_pos;
571}
572\f
c9ed721d
RS
573DEFUN ("line-beginning-position", Fline_beginning_position, Sline_beginning_position,
574 0, 1, 0,
575 "Return the character position of the first character on the current line.\n\
576With argument N not nil or 1, move forward N - 1 lines first.\n\
577If scan reaches end of buffer, return that position.\n\
a3caef99
RS
578The scan does not cross a field boundary unless it would move\n\
579beyond there to a different line. And if N is nil or 1,\n\
580and scan starts at a field boundary, the scan stops as soon as it starts.\n\n\
581This function does not move point.")
c9ed721d
RS
582 (n)
583 Lisp_Object n;
584{
ec1c14f6 585 register int orig, orig_byte, end;
c9ed721d
RS
586
587 if (NILP (n))
588 XSETFASTINT (n, 1);
589 else
590 CHECK_NUMBER (n, 0);
591
592 orig = PT;
ec1c14f6 593 orig_byte = PT_BYTE;
c9ed721d
RS
594 Fforward_line (make_number (XINT (n) - 1));
595 end = PT;
e2dae3f2 596
ec1c14f6 597 SET_PT_BOTH (orig, orig_byte);
35692fe0 598
0daf6e8d 599 /* Return END constrained to the current input field. */
a3caef99
RS
600 return Fconstrain_to_field (make_number (end), make_number (orig),
601 XINT (n) != 1 ? Qt : Qnil,
602 Qt);
c9ed721d
RS
603}
604
605DEFUN ("line-end-position", Fline_end_position, Sline_end_position,
606 0, 1, 0,
607 "Return the character position of the last character on the current line.\n\
608With argument N not nil or 1, move forward N - 1 lines first.\n\
609If scan reaches end of buffer, return that position.\n\
610This function does not move point.")
611 (n)
612 Lisp_Object n;
613{
0daf6e8d
GM
614 int end_pos;
615 register int orig = PT;
616
c9ed721d
RS
617 if (NILP (n))
618 XSETFASTINT (n, 1);
619 else
620 CHECK_NUMBER (n, 0);
621
0daf6e8d
GM
622 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
623
624 /* Return END_POS constrained to the current input field. */
625 return
626 Fconstrain_to_field (make_number (end_pos), make_number (orig), Qnil, Qt);
c9ed721d
RS
627}
628\f
35692fe0
JB
629Lisp_Object
630save_excursion_save ()
631{
0e2c9c70
JB
632 register int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
633 == current_buffer);
35692fe0
JB
634
635 return Fcons (Fpoint_marker (),
aea4a109 636 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
9772455e
RS
637 Fcons (visible ? Qt : Qnil,
638 current_buffer->mark_active)));
35692fe0
JB
639}
640
641Lisp_Object
642save_excursion_restore (info)
4ad8681a 643 Lisp_Object info;
35692fe0 644{
4ad8681a
RS
645 Lisp_Object tem, tem1, omark, nmark;
646 struct gcpro gcpro1, gcpro2, gcpro3;
35692fe0
JB
647
648 tem = Fmarker_buffer (Fcar (info));
649 /* If buffer being returned to is now deleted, avoid error */
650 /* Otherwise could get error here while unwinding to top level
651 and crash */
652 /* In that case, Fmarker_buffer returns nil now. */
56a98455 653 if (NILP (tem))
35692fe0 654 return Qnil;
4ad8681a
RS
655
656 omark = nmark = Qnil;
657 GCPRO3 (info, omark, nmark);
658
35692fe0
JB
659 Fset_buffer (tem);
660 tem = Fcar (info);
661 Fgoto_char (tem);
662 unchain_marker (tem);
663 tem = Fcar (Fcdr (info));
03d18690 664 omark = Fmarker_position (current_buffer->mark);
35692fe0 665 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
03d18690 666 nmark = Fmarker_position (tem);
35692fe0
JB
667 unchain_marker (tem);
668 tem = Fcdr (Fcdr (info));
ef580991
RS
669#if 0 /* We used to make the current buffer visible in the selected window
670 if that was true previously. That avoids some anomalies.
671 But it creates others, and it wasn't documented, and it is simpler
672 and cleaner never to alter the window/buffer connections. */
9772455e
RS
673 tem1 = Fcar (tem);
674 if (!NILP (tem1)
0e2c9c70 675 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
35692fe0 676 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
ef580991 677#endif /* 0 */
9772455e
RS
678
679 tem1 = current_buffer->mark_active;
680 current_buffer->mark_active = Fcdr (tem);
9fed2b18
RS
681 if (!NILP (Vrun_hooks))
682 {
03d18690
RS
683 /* If mark is active now, and either was not active
684 or was at a different place, run the activate hook. */
9fed2b18 685 if (! NILP (current_buffer->mark_active))
03d18690
RS
686 {
687 if (! EQ (omark, nmark))
688 call1 (Vrun_hooks, intern ("activate-mark-hook"));
689 }
690 /* If mark has ceased to be active, run deactivate hook. */
9fed2b18
RS
691 else if (! NILP (tem1))
692 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
693 }
4ad8681a 694 UNGCPRO;
35692fe0
JB
695 return Qnil;
696}
697
698DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
699 "Save point, mark, and current buffer; execute BODY; restore those things.\n\
700Executes BODY just like `progn'.\n\
701The values of point, mark and the current buffer are restored\n\
9772455e 702even in case of abnormal exit (throw or error).\n\
85cac557
RS
703The state of activation of the mark is also restored.\n\
704\n\
705This construct does not save `deactivate-mark', and therefore\n\
706functions that change the buffer will still cause deactivation\n\
707of the mark at the end of the command. To prevent that, bind\n\
708`deactivate-mark' with `let'.")
35692fe0
JB
709 (args)
710 Lisp_Object args;
711{
712 register Lisp_Object val;
713 int count = specpdl_ptr - specpdl;
714
715 record_unwind_protect (save_excursion_restore, save_excursion_save ());
4bc8c7d2
RS
716
717 val = Fprogn (args);
718 return unbind_to (count, val);
719}
720
721DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
722 "Save the current buffer; execute BODY; restore the current buffer.\n\
723Executes BODY just like `progn'.")
724 (args)
725 Lisp_Object args;
726{
727 register Lisp_Object val;
728 int count = specpdl_ptr - specpdl;
729
cb5e5f74 730 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
4bc8c7d2 731
35692fe0
JB
732 val = Fprogn (args);
733 return unbind_to (count, val);
734}
735\f
95dccf75
RS
736DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
737 "Return the number of characters in the current buffer.\n\
738If BUFFER, return the number of characters in that buffer instead.")
739 (buffer)
740 Lisp_Object buffer;
35692fe0 741{
95dccf75
RS
742 if (NILP (buffer))
743 return make_number (Z - BEG);
02050596
RS
744 else
745 {
746 CHECK_BUFFER (buffer, 1);
747 return make_number (BUF_Z (XBUFFER (buffer))
748 - BUF_BEG (XBUFFER (buffer)));
749 }
35692fe0
JB
750}
751
752DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
753 "Return the minimum permissible value of point in the current buffer.\n\
4c390850 754This is 1, unless narrowing (a buffer restriction) is in effect.")
35692fe0
JB
755 ()
756{
757 Lisp_Object temp;
55561c63 758 XSETFASTINT (temp, BEGV);
35692fe0
JB
759 return temp;
760}
761
762DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
763 "Return a marker to the minimum permissible value of point in this buffer.\n\
4c390850 764This is the beginning, unless narrowing (a buffer restriction) is in effect.")
35692fe0
JB
765 ()
766{
ec1c14f6 767 return buildmark (BEGV, BEGV_BYTE);
35692fe0
JB
768}
769
770DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
771 "Return the maximum permissible value of point in the current buffer.\n\
4c390850
RS
772This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
773is in effect, in which case it is less.")
35692fe0
JB
774 ()
775{
776 Lisp_Object temp;
55561c63 777 XSETFASTINT (temp, ZV);
35692fe0
JB
778 return temp;
779}
780
781DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
782 "Return a marker to the maximum permissible value of point in this buffer.\n\
4c390850
RS
783This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
784is in effect, in which case it is less.")
35692fe0
JB
785 ()
786{
ec1c14f6 787 return buildmark (ZV, ZV_BYTE);
35692fe0
JB
788}
789
c86212b9
RS
790DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
791 "Return the position of the gap, in the current buffer.\n\
792See also `gap-size'.")
793 ()
794{
795 Lisp_Object temp;
796 XSETFASTINT (temp, GPT);
797 return temp;
798}
799
800DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
801 "Return the size of the current buffer's gap.\n\
802See also `gap-position'.")
803 ()
804{
805 Lisp_Object temp;
806 XSETFASTINT (temp, GAP_SIZE);
807 return temp;
808}
809
7df74da6 810DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
fcf9683e
KH
811 "Return the byte position for character position POSITION.\n\
812If POSITION is out of range, the value is nil.")
7df74da6 813 (position)
80e01f8d 814 Lisp_Object position;
7df74da6 815{
fa8a5a15 816 CHECK_NUMBER_COERCE_MARKER (position, 1);
fcf9683e
KH
817 if (XINT (position) < BEG || XINT (position) > Z)
818 return Qnil;
fa8a5a15 819 return make_number (CHAR_TO_BYTE (XINT (position)));
7df74da6 820}
3ab0732d
RS
821
822DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
fcf9683e
KH
823 "Return the character position for byte position BYTEPOS.\n\
824If BYTEPOS is out of range, the value is nil.")
3ab0732d
RS
825 (bytepos)
826 Lisp_Object bytepos;
827{
828 CHECK_NUMBER (bytepos, 1);
fcf9683e
KH
829 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
830 return Qnil;
3ab0732d
RS
831 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
832}
7df74da6 833\f
850a8179
JB
834DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
835 "Return the character following point, as a number.\n\
fb8106e8
KH
836At the end of the buffer or accessible region, return 0.\n\
837If `enable-multibyte-characters' is nil or point is not\n\
838 at character boundary, multibyte form is ignored,\n\
839 and only one byte following point is returned as a character.")
35692fe0
JB
840 ()
841{
842 Lisp_Object temp;
6ec8bbd2 843 if (PT >= ZV)
55561c63 844 XSETFASTINT (temp, 0);
850a8179 845 else
ec1c14f6 846 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
35692fe0
JB
847 return temp;
848}
849
850a8179
JB
850DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
851 "Return the character preceding point, as a number.\n\
fb8106e8
KH
852At the beginning of the buffer or accessible region, return 0.\n\
853If `enable-multibyte-characters' is nil or point is not\n\
854 at character boundary, multi-byte form is ignored,\n\
855 and only one byte preceding point is returned as a character.")
35692fe0
JB
856 ()
857{
858 Lisp_Object temp;
6ec8bbd2 859 if (PT <= BEGV)
55561c63 860 XSETFASTINT (temp, 0);
fb8106e8
KH
861 else if (!NILP (current_buffer->enable_multibyte_characters))
862 {
ec1c14f6 863 int pos = PT_BYTE;
fb8106e8
KH
864 DEC_POS (pos);
865 XSETFASTINT (temp, FETCH_CHAR (pos));
866 }
35692fe0 867 else
ec1c14f6 868 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
35692fe0
JB
869 return temp;
870}
871
872DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
ec1c14f6 873 "Return t if point is at the beginning of the buffer.\n\
35692fe0
JB
874If the buffer is narrowed, this means the beginning of the narrowed part.")
875 ()
876{
6ec8bbd2 877 if (PT == BEGV)
35692fe0
JB
878 return Qt;
879 return Qnil;
880}
881
882DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
ec1c14f6 883 "Return t if point is at the end of the buffer.\n\
35692fe0
JB
884If the buffer is narrowed, this means the end of the narrowed part.")
885 ()
886{
6ec8bbd2 887 if (PT == ZV)
35692fe0
JB
888 return Qt;
889 return Qnil;
890}
891
892DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
ec1c14f6 893 "Return t if point is at the beginning of a line.")
35692fe0
JB
894 ()
895{
ec1c14f6 896 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
35692fe0
JB
897 return Qt;
898 return Qnil;
899}
900
901DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
ec1c14f6 902 "Return t if point is at the end of a line.\n\
35692fe0
JB
903`End of a line' includes point being at the end of the buffer.")
904 ()
905{
ec1c14f6 906 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
35692fe0
JB
907 return Qt;
908 return Qnil;
909}
910
fa1d3816 911DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
35692fe0
JB
912 "Return character in current buffer at position POS.\n\
913POS is an integer or a buffer pointer.\n\
39a4c932 914If POS is out of range, the value is nil.")
35692fe0
JB
915 (pos)
916 Lisp_Object pos;
917{
ec1c14f6 918 register int pos_byte;
35692fe0 919
fa1d3816 920 if (NILP (pos))
39a4c932
RS
921 {
922 pos_byte = PT_BYTE;
3c52e568 923 XSETFASTINT (pos, PT);
39a4c932
RS
924 }
925
926 if (MARKERP (pos))
85cac557
RS
927 {
928 pos_byte = marker_byte_position (pos);
929 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
930 return Qnil;
931 }
fa1d3816
RS
932 else
933 {
934 CHECK_NUMBER_COERCE_MARKER (pos, 0);
b98ef0dc 935 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
85cac557 936 return Qnil;
ec1c14f6
RS
937
938 pos_byte = CHAR_TO_BYTE (XINT (pos));
fa1d3816 939 }
35692fe0 940
ec1c14f6 941 return make_number (FETCH_CHAR (pos_byte));
35692fe0 942}
fb8106e8 943
fa1d3816 944DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
fb8106e8
KH
945 "Return character in current buffer preceding position POS.\n\
946POS is an integer or a buffer pointer.\n\
39a4c932 947If POS is out of range, the value is nil.")
fb8106e8
KH
948 (pos)
949 Lisp_Object pos;
950{
951 register Lisp_Object val;
ec1c14f6 952 register int pos_byte;
fb8106e8 953
fa1d3816 954 if (NILP (pos))
39a4c932
RS
955 {
956 pos_byte = PT_BYTE;
3c52e568 957 XSETFASTINT (pos, PT);
39a4c932
RS
958 }
959
960 if (MARKERP (pos))
85cac557
RS
961 {
962 pos_byte = marker_byte_position (pos);
963
964 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
965 return Qnil;
966 }
fa1d3816
RS
967 else
968 {
969 CHECK_NUMBER_COERCE_MARKER (pos, 0);
fb8106e8 970
b98ef0dc 971 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
85cac557
RS
972 return Qnil;
973
ec1c14f6 974 pos_byte = CHAR_TO_BYTE (XINT (pos));
fa1d3816 975 }
fb8106e8
KH
976
977 if (!NILP (current_buffer->enable_multibyte_characters))
978 {
ec1c14f6
RS
979 DEC_POS (pos_byte);
980 XSETFASTINT (val, FETCH_CHAR (pos_byte));
fb8106e8
KH
981 }
982 else
983 {
ec1c14f6
RS
984 pos_byte--;
985 XSETFASTINT (val, FETCH_BYTE (pos_byte));
fb8106e8
KH
986 }
987 return val;
988}
35692fe0 989\f
87485d6f 990DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
35692fe0
JB
991 "Return the name under which the user logged in, as a string.\n\
992This is based on the effective uid, not the real uid.\n\
2c9ae24e 993Also, if the environment variable LOGNAME or USER is set,\n\
87485d6f
MW
994that determines the value of this function.\n\n\
995If optional argument UID is an integer, return the login name of the user\n\
996with that uid, or nil if there is no such user.")
997 (uid)
998 Lisp_Object uid;
35692fe0 999{
87485d6f
MW
1000 struct passwd *pw;
1001
f8a0e364
RS
1002 /* Set up the user name info if we didn't do it before.
1003 (That can happen if Emacs is dumpable
1004 but you decide to run `temacs -l loadup' and not dump. */
35b34f72 1005 if (INTEGERP (Vuser_login_name))
f8a0e364 1006 init_editfns ();
87485d6f
MW
1007
1008 if (NILP (uid))
35b34f72 1009 return Vuser_login_name;
87485d6f
MW
1010
1011 CHECK_NUMBER (uid, 0);
1012 pw = (struct passwd *) getpwuid (XINT (uid));
1013 return (pw ? build_string (pw->pw_name) : Qnil);
35692fe0
JB
1014}
1015
1016DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1017 0, 0, 0,
1018 "Return the name of the user's real uid, as a string.\n\
9658bdd0 1019This ignores the environment variables LOGNAME and USER, so it differs from\n\
b1da234a 1020`user-login-name' when running under `su'.")
35692fe0
JB
1021 ()
1022{
f8a0e364
RS
1023 /* Set up the user name info if we didn't do it before.
1024 (That can happen if Emacs is dumpable
1025 but you decide to run `temacs -l loadup' and not dump. */
35b34f72 1026 if (INTEGERP (Vuser_login_name))
f8a0e364 1027 init_editfns ();
35b34f72 1028 return Vuser_real_login_name;
35692fe0
JB
1029}
1030
1031DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1032 "Return the effective uid of Emacs, as an integer.")
1033 ()
1034{
1035 return make_number (geteuid ());
1036}
1037
1038DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1039 "Return the real uid of Emacs, as an integer.")
1040 ()
1041{
1042 return make_number (getuid ());
1043}
1044
c9ed721d
RS
1045DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1046 "Return the full name of the user logged in, as a string.\n\
016c8f3f
KH
1047If the full name corresponding to Emacs's userid is not known,\n\
1048return \"unknown\".\n\
1049\n\
c9ed721d 1050If optional argument UID is an integer, return the full name of the user\n\
016c8f3f 1051with that uid, or nil if there is no such user.\n\
3415b0e9 1052If UID is a string, return the full name of the user with that login\n\
016c8f3f 1053name, or nil if there is no such user.")
c9ed721d
RS
1054 (uid)
1055 Lisp_Object uid;
35692fe0 1056{
c9ed721d 1057 struct passwd *pw;
b0e92acd 1058 register unsigned char *p, *q;
3415b0e9
RS
1059 extern char *index ();
1060 Lisp_Object full;
c9ed721d
RS
1061
1062 if (NILP (uid))
3415b0e9
RS
1063 return Vuser_full_name;
1064 else if (NUMBERP (uid))
1065 pw = (struct passwd *) getpwuid (XINT (uid));
1066 else if (STRINGP (uid))
1067 pw = (struct passwd *) getpwnam (XSTRING (uid)->data);
1068 else
1069 error ("Invalid UID specification");
c9ed721d 1070
3415b0e9 1071 if (!pw)
3347526c 1072 return Qnil;
3415b0e9
RS
1073
1074 p = (unsigned char *) USER_FULL_NAME;
1075 /* Chop off everything after the first comma. */
1076 q = (unsigned char *) index (p, ',');
1077 full = make_string (p, q ? q - p : strlen (p));
1078
1079#ifdef AMPERSAND_FULL_NAME
1080 p = XSTRING (full)->data;
1081 q = (unsigned char *) index (p, '&');
1082 /* Substitute the login name for the &, upcasing the first character. */
1083 if (q)
1084 {
b0e92acd 1085 register unsigned char *r;
3415b0e9
RS
1086 Lisp_Object login;
1087
1088 login = Fuser_login_name (make_number (pw->pw_uid));
1089 r = (unsigned char *) alloca (strlen (p) + XSTRING (login)->size + 1);
1090 bcopy (p, r, q - p);
1091 r[q - p] = 0;
1092 strcat (r, XSTRING (login)->data);
1093 r[q - p] = UPCASE (r[q - p]);
1094 strcat (r, q + 1);
1095 full = build_string (r);
1096 }
1097#endif /* AMPERSAND_FULL_NAME */
1098
1099 return full;
35692fe0
JB
1100}
1101
1102DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1103 "Return the name of the machine you are running on, as a string.")
1104 ()
1105{
1106 return Vsystem_name;
1107}
1108
ac988277
KH
1109/* For the benefit of callers who don't want to include lisp.h */
1110char *
1111get_system_name ()
1112{
3d976a9a
RS
1113 if (STRINGP (Vsystem_name))
1114 return (char *) XSTRING (Vsystem_name)->data;
1115 else
1116 return "";
ac988277
KH
1117}
1118
7fd233b3
RS
1119DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1120 "Return the process ID of Emacs, as an integer.")
1121 ()
1122{
1123 return make_number (getpid ());
1124}
1125
d940e0e4 1126DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
e983fdb2 1127 "Return the current time, as the number of seconds since 1970-01-01 00:00:00.\n\
956ace37
JB
1128The time is returned as a list of three integers. The first has the\n\
1129most significant 16 bits of the seconds, while the second has the\n\
1130least significant 16 bits. The third integer gives the microsecond\n\
1131count.\n\
1132\n\
1133The microsecond count is zero on systems that do not provide\n\
1134resolution finer than a second.")
d940e0e4
JB
1135 ()
1136{
956ace37
JB
1137 EMACS_TIME t;
1138 Lisp_Object result[3];
1139
1140 EMACS_GET_TIME (t);
d2fd0445
KH
1141 XSETINT (result[0], (EMACS_SECS (t) >> 16) & 0xffff);
1142 XSETINT (result[1], (EMACS_SECS (t) >> 0) & 0xffff);
1143 XSETINT (result[2], EMACS_USECS (t));
956ace37
JB
1144
1145 return Flist (3, result);
d940e0e4
JB
1146}
1147\f
1148
e3120ab5
JB
1149static int
1150lisp_time_argument (specified_time, result)
1151 Lisp_Object specified_time;
1152 time_t *result;
1153{
1154 if (NILP (specified_time))
1155 return time (result) != -1;
1156 else
1157 {
1158 Lisp_Object high, low;
1159 high = Fcar (specified_time);
1160 CHECK_NUMBER (high, 0);
1161 low = Fcdr (specified_time);
ae683129 1162 if (CONSP (low))
e3120ab5
JB
1163 low = Fcar (low);
1164 CHECK_NUMBER (low, 0);
1165 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1166 return *result >> 16 == XINT (high);
1167 }
1168}
1169
70ebbe5f
PE
1170/* Write information into buffer S of size MAXSIZE, according to the
1171 FORMAT of length FORMAT_LEN, using time information taken from *TP.
68c45bf0 1172 Default to Universal Time if UT is nonzero, local time otherwise.
70ebbe5f
PE
1173 Return the number of bytes written, not including the terminating
1174 '\0'. If S is NULL, nothing will be written anywhere; so to
1175 determine how many bytes would be written, use NULL for S and
1176 ((size_t) -1) for MAXSIZE.
1177
68c45bf0 1178 This function behaves like emacs_strftimeu, except it allows null
70ebbe5f
PE
1179 bytes in FORMAT. */
1180static size_t
68c45bf0 1181emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
70ebbe5f
PE
1182 char *s;
1183 size_t maxsize;
1184 const char *format;
1185 size_t format_len;
1186 const struct tm *tp;
68c45bf0 1187 int ut;
70ebbe5f
PE
1188{
1189 size_t total = 0;
1190
be09e6e6
PE
1191 /* Loop through all the null-terminated strings in the format
1192 argument. Normally there's just one null-terminated string, but
1193 there can be arbitrarily many, concatenated together, if the
68c45bf0 1194 format contains '\0' bytes. emacs_strftimeu stops at the first
be09e6e6 1195 '\0' byte so we must invoke it separately for each such string. */
70ebbe5f
PE
1196 for (;;)
1197 {
1198 size_t len;
1199 size_t result;
1200
1201 if (s)
1202 s[0] = '\1';
1203
68c45bf0 1204 result = emacs_strftimeu (s, maxsize, format, tp, ut);
70ebbe5f
PE
1205
1206 if (s)
1207 {
1208 if (result == 0 && s[0] != '\0')
1209 return 0;
1210 s += result + 1;
1211 }
1212
1213 maxsize -= result + 1;
1214 total += result;
1215 len = strlen (format);
1216 if (len == format_len)
1217 return total;
1218 total++;
1219 format += len + 1;
1220 format_len -= len + 1;
1221 }
1222}
1223
3efcc98a 1224/*
b48382a0
RS
1225DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1226 "Use FORMAT-STRING to format the time TIME, or now if omitted.\n\
1227TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as returned by\n\
1228`current-time' or `file-attributes'.\n\
1229The third, optional, argument UNIVERSAL, if non-nil, means describe TIME\n\
1230as Universal Time; nil means describe TIME in the local time zone.\n\
1231The value is a copy of FORMAT-STRING, but with certain constructs replaced\n\
1232by text that describes the specified date and time in TIME:\n\
a82d387c 1233\n\
b48382a0
RS
1234%Y is the year, %y within the century, %C the century.\n\
1235%G is the year corresponding to the ISO week, %g within the century.\n\
b771d0da
PE
1236%m is the numeric month.\n\
1237%b and %h are the locale's abbreviated month name, %B the full name.\n\
b48382a0
RS
1238%d is the day of the month, zero-padded, %e is blank-padded.\n\
1239%u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.\n\
b771d0da 1240%a is the locale's abbreviated name of the day of week, %A the full name.\n\
b48382a0
RS
1241%U is the week number starting on Sunday, %W starting on Monday,\n\
1242 %V according to ISO 8601.\n\
1243%j is the day of the year.\n\
1244\n\
1245%H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H\n\
1246 only blank-padded, %l is like %I blank-padded.\n\
b771d0da 1247%p is the locale's equivalent of either AM or PM.\n\
b48382a0
RS
1248%M is the minute.\n\
1249%S is the second.\n\
1250%Z is the time zone name, %z is the numeric form.\n\
1251%s is the number of seconds since 1970-01-01 00:00:00 +0000.\n\
1252\n\
1253%c is the locale's date and time format.\n\
1254%x is the locale's \"preferred\" date format.\n\
1255%D is like \"%m/%d/%y\".\n\
1256\n\
1257%R is like \"%H:%M\", %T is like \"%H:%M:%S\", %r is like \"%I:%M:%S %p\".\n\
1258%X is the locale's \"preferred\" time format.\n\
1259\n\
b771d0da 1260Finally, %n is a newline, %t is a tab, %% is a literal %.\n\
b48382a0 1261\n\
3efcc98a 1262Certain flags and modifiers are available with some format controls.\n\
b48382a0
RS
1263The flags are `_' and `-'. For certain characters X, %_X is like %X,\n\
1264but padded with blanks; %-X is like %X, but without padding.\n\
1265%NX (where N stands for an integer) is like %X,\n\
1266but takes up at least N (a number) positions.\n\
1267The modifiers are `E' and `O'. For certain characters X,\n\
1268%EX is a locale's alternative version of %X;\n\
1269%OX is like %X, but uses the locale's number symbols.\n\
1270\n\
1271For example, to produce full ISO 8601 format, use \"%Y-%m-%dT%T%z\".")
726ed0da 1272 (format_string, time, universal)
3efcc98a
RS
1273*/
1274
1275DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1276 0 /* See immediately above */)
b48382a0
RS
1277 (format_string, time, universal)
1278 Lisp_Object format_string, time, universal;
a82d387c
RS
1279{
1280 time_t value;
1281 int size;
177ea5f1 1282 struct tm *tm;
68c45bf0 1283 int ut = ! NILP (universal);
a82d387c
RS
1284
1285 CHECK_STRING (format_string, 1);
1286
1287 if (! lisp_time_argument (time, &value))
1288 error ("Invalid time specification");
1289
68c45bf0
PE
1290 format_string = code_convert_string_norecord (format_string,
1291 Vlocale_coding_system, 1);
1292
a82d387c 1293 /* This is probably enough. */
dc3620af 1294 size = STRING_BYTES (XSTRING (format_string)) * 6 + 50;
a82d387c 1295
68c45bf0 1296 tm = ut ? gmtime (&value) : localtime (&value);
177ea5f1
PE
1297 if (! tm)
1298 error ("Specified time is not representable");
1299
ca9c0567 1300 synchronize_system_time_locale ();
68c45bf0 1301
a82d387c
RS
1302 while (1)
1303 {
b48382a0
RS
1304 char *buf = (char *) alloca (size + 1);
1305 int result;
1306
bfbcc5ee 1307 buf[0] = '\1';
68c45bf0
PE
1308 result = emacs_memftimeu (buf, size, XSTRING (format_string)->data,
1309 STRING_BYTES (XSTRING (format_string)),
1310 tm, ut);
bfbcc5ee 1311 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
68c45bf0
PE
1312 return code_convert_string_norecord (make_string (buf, result),
1313 Vlocale_coding_system, 0);
b48382a0
RS
1314
1315 /* If buffer was too small, make it bigger and try again. */
68c45bf0
PE
1316 result = emacs_memftimeu (NULL, (size_t) -1,
1317 XSTRING (format_string)->data,
1318 STRING_BYTES (XSTRING (format_string)),
1319 tm, ut);
b48382a0 1320 size = result + 1;
a82d387c
RS
1321 }
1322}
1323
4691c06d
RS
1324DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1325 "Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).\n\
1326The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED)\n\
1327or (HIGH . LOW), as from `current-time' and `file-attributes', or `nil'\n\
1328to use the current time. The list has the following nine members:\n\
145b0681
RS
1329SEC is an integer between 0 and 60; SEC is 60 for a leap second, which\n\
1330only some operating systems support. MINUTE is an integer between 0 and 59.\n\
4691c06d
RS
1331HOUR is an integer between 0 and 23. DAY is an integer between 1 and 31.\n\
1332MONTH is an integer between 1 and 12. YEAR is an integer indicating the\n\
1333four-digit year. DOW is the day of week, an integer between 0 and 6, where\n\
13340 is Sunday. DST is t if daylight savings time is effect, otherwise nil.\n\
1335ZONE is an integer indicating the number of seconds east of Greenwich.\n\
2c6c7c72 1336\(Note that Common Lisp has different meanings for DOW and ZONE.)")
4691c06d
RS
1337 (specified_time)
1338 Lisp_Object specified_time;
1339{
1340 time_t time_spec;
3c887943 1341 struct tm save_tm;
4691c06d
RS
1342 struct tm *decoded_time;
1343 Lisp_Object list_args[9];
1344
1345 if (! lisp_time_argument (specified_time, &time_spec))
1346 error ("Invalid time specification");
1347
1348 decoded_time = localtime (&time_spec);
177ea5f1
PE
1349 if (! decoded_time)
1350 error ("Specified time is not representable");
3c887943
KH
1351 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1352 XSETFASTINT (list_args[1], decoded_time->tm_min);
1353 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1354 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1355 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
236ebf35 1356 XSETINT (list_args[5], decoded_time->tm_year + 1900);
3c887943 1357 XSETFASTINT (list_args[6], decoded_time->tm_wday);
4691c06d 1358 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
3c887943
KH
1359
1360 /* Make a copy, in case gmtime modifies the struct. */
1361 save_tm = *decoded_time;
1362 decoded_time = gmtime (&time_spec);
1363 if (decoded_time == 0)
1364 list_args[8] = Qnil;
1365 else
94751666 1366 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
4691c06d
RS
1367 return Flist (9, list_args);
1368}
1369
6ee9061c 1370DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
2591ec64 1371 "Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.\n\
6ee9061c
RS
1372This is the reverse operation of `decode-time', which see.\n\
1373ZONE defaults to the current time zone rule. This can\n\
085e9fcb 1374be a string or t (as from `set-time-zone-rule'), or it can be a list\n\
7459d65b 1375\(as from `current-time-zone') or an integer (as from `decode-time')\n\
c59b5089 1376applied without consideration for daylight savings time.\n\
6ee9061c
RS
1377\n\
1378You can pass more than 7 arguments; then the first six arguments\n\
1379are used as SECOND through YEAR, and the *last* argument is used as ZONE.\n\
1380The intervening arguments are ignored.\n\
1381This feature lets (apply 'encode-time (decode-time ...)) work.\n\
1382\n\
c59b5089
PE
1383Out-of-range values for SEC, MINUTE, HOUR, DAY, or MONTH are allowed;\n\
1384for example, a DAY of 0 means the day preceding the given month.\n\
01ba8cce 1385Year numbers less than 100 are treated just like other year numbers.\n\
c59b5089 1386If you want them to stand for years in this century, you must do that yourself.")
6ee9061c
RS
1387 (nargs, args)
1388 int nargs;
1389 register Lisp_Object *args;
cce7b8a0 1390{
1b8fa736 1391 time_t time;
c59b5089 1392 struct tm tm;
60653898 1393 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
6ee9061c
RS
1394
1395 CHECK_NUMBER (args[0], 0); /* second */
1396 CHECK_NUMBER (args[1], 1); /* minute */
1397 CHECK_NUMBER (args[2], 2); /* hour */
1398 CHECK_NUMBER (args[3], 3); /* day */
1399 CHECK_NUMBER (args[4], 4); /* month */
1400 CHECK_NUMBER (args[5], 5); /* year */
1401
1402 tm.tm_sec = XINT (args[0]);
1403 tm.tm_min = XINT (args[1]);
1404 tm.tm_hour = XINT (args[2]);
1405 tm.tm_mday = XINT (args[3]);
1406 tm.tm_mon = XINT (args[4]) - 1;
1407 tm.tm_year = XINT (args[5]) - 1900;
c59b5089
PE
1408 tm.tm_isdst = -1;
1409
1410 if (CONSP (zone))
1411 zone = Fcar (zone);
1b8fa736 1412 if (NILP (zone))
c59b5089
PE
1413 time = mktime (&tm);
1414 else
1b8fa736 1415 {
c59b5089
PE
1416 char tzbuf[100];
1417 char *tzstring;
1418 char **oldenv = environ, **newenv;
1419
2e34157c 1420 if (EQ (zone, Qt))
085e9fcb
EN
1421 tzstring = "UTC0";
1422 else if (STRINGP (zone))
4d4c1514 1423 tzstring = (char *) XSTRING (zone)->data;
c59b5089 1424 else if (INTEGERP (zone))
1b8fa736 1425 {
c59b5089
PE
1426 int abszone = abs (XINT (zone));
1427 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1428 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1429 tzstring = tzbuf;
1b8fa736 1430 }
c59b5089
PE
1431 else
1432 error ("Invalid time zone specification");
1433
1434 /* Set TZ before calling mktime; merely adjusting mktime's returned
1435 value doesn't suffice, since that would mishandle leap seconds. */
1436 set_time_zone_rule (tzstring);
1437
1438 time = mktime (&tm);
1439
1440 /* Restore TZ to previous value. */
1441 newenv = environ;
1442 environ = oldenv;
c0efcacf 1443 xfree (newenv);
c59b5089
PE
1444#ifdef LOCALTIME_CACHE
1445 tzset ();
1446#endif
1b8fa736 1447 }
1b8fa736 1448
c59b5089
PE
1449 if (time == (time_t) -1)
1450 error ("Specified time is not representable");
1451
1452 return make_time (time);
cce7b8a0
RS
1453}
1454
2148f2b4 1455DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
35692fe0 1456 "Return the current time, as a human-readable string.\n\
2148f2b4
RS
1457Programs can use this function to decode a time,\n\
1458since the number of columns in each field is fixed.\n\
1459The format is `Sun Sep 16 01:03:52 1973'.\n\
7a8630da
RS
1460However, see also the functions `decode-time' and `format-time-string'\n\
1461which provide a much more powerful and general facility.\n\
1462\n\
2148f2b4
RS
1463If an argument is given, it specifies a time to format\n\
1464instead of the current time. The argument should have the form:\n\
1465 (HIGH . LOW)\n\
1466or the form:\n\
1467 (HIGH LOW . IGNORED).\n\
1468Thus, you can use times obtained from `current-time'\n\
1469and from `file-attributes'.")
1470 (specified_time)
1471 Lisp_Object specified_time;
1472{
e3120ab5 1473 time_t value;
35692fe0 1474 char buf[30];
2148f2b4
RS
1475 register char *tem;
1476
e3120ab5
JB
1477 if (! lisp_time_argument (specified_time, &value))
1478 value = -1;
2148f2b4 1479 tem = (char *) ctime (&value);
35692fe0
JB
1480
1481 strncpy (buf, tem, 24);
1482 buf[24] = 0;
1483
1484 return build_string (buf);
1485}
c2662aea 1486
94751666 1487#define TM_YEAR_BASE 1900
e3120ab5 1488
94751666
PE
1489/* Yield A - B, measured in seconds.
1490 This function is copied from the GNU C Library. */
1491static int
1492tm_diff (a, b)
e3120ab5
JB
1493 struct tm *a, *b;
1494{
94751666
PE
1495 /* Compute intervening leap days correctly even if year is negative.
1496 Take care to avoid int overflow in leap day calculations,
1497 but it's OK to assume that A and B are close to each other. */
1498 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1499 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1500 int a100 = a4 / 25 - (a4 % 25 < 0);
1501 int b100 = b4 / 25 - (b4 % 25 < 0);
1502 int a400 = a100 >> 2;
1503 int b400 = b100 >> 2;
1504 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1505 int years = a->tm_year - b->tm_year;
1506 int days = (365 * years + intervening_leap_days
1507 + (a->tm_yday - b->tm_yday));
1508 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1509 + (a->tm_min - b->tm_min))
8e718b4e 1510 + (a->tm_sec - b->tm_sec));
e3120ab5
JB
1511}
1512
1513DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1514 "Return the offset and name for the local time zone.\n\
1515This returns a list of the form (OFFSET NAME).\n\
1516OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).\n\
1517 A negative value means west of Greenwich.\n\
1518NAME is a string giving the name of the time zone.\n\
1519If an argument is given, it specifies when the time zone offset is determined\n\
1520instead of using the current time. The argument should have the form:\n\
1521 (HIGH . LOW)\n\
1522or the form:\n\
1523 (HIGH LOW . IGNORED).\n\
1524Thus, you can use times obtained from `current-time'\n\
1525and from `file-attributes'.\n\
773c1fd3
JB
1526\n\
1527Some operating systems cannot provide all this information to Emacs;\n\
2d88f747 1528in this case, `current-time-zone' returns a list containing nil for\n\
773c1fd3 1529the data it can't find.")
e3120ab5
JB
1530 (specified_time)
1531 Lisp_Object specified_time;
c2662aea 1532{
e3120ab5
JB
1533 time_t value;
1534 struct tm *t;
177ea5f1 1535 struct tm gmt;
c2662aea 1536
e3120ab5 1537 if (lisp_time_argument (specified_time, &value)
177ea5f1
PE
1538 && (t = gmtime (&value)) != 0
1539 && (gmt = *t, t = localtime (&value)) != 0)
e3120ab5 1540 {
177ea5f1
PE
1541 int offset = tm_diff (t, &gmt);
1542 char *s = 0;
1543 char buf[6];
e3120ab5
JB
1544#ifdef HAVE_TM_ZONE
1545 if (t->tm_zone)
5fd4de15 1546 s = (char *)t->tm_zone;
a7971c39
RS
1547#else /* not HAVE_TM_ZONE */
1548#ifdef HAVE_TZNAME
1549 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1550 s = tzname[t->tm_isdst];
c2662aea 1551#endif
a7971c39 1552#endif /* not HAVE_TM_ZONE */
e3120ab5
JB
1553 if (!s)
1554 {
1555 /* No local time zone name is available; use "+-NNNN" instead. */
00fc94d0 1556 int am = (offset < 0 ? -offset : offset) / 60;
e3120ab5
JB
1557 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1558 s = buf;
1559 }
1560 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
1561 }
1562 else
09dbcf71 1563 return Fmake_list (make_number (2), Qnil);
c2662aea
JB
1564}
1565
260e2e2a
KH
1566/* This holds the value of `environ' produced by the previous
1567 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
1568 has never been called. */
1569static char **environbuf;
1570
143cb9a9
RS
1571DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
1572 "Set the local time zone using TZ, a string specifying a time zone rule.\n\
085e9fcb
EN
1573If TZ is nil, use implementation-defined default time zone information.\n\
1574If TZ is t, use Universal Time.")
143cb9a9
RS
1575 (tz)
1576 Lisp_Object tz;
1577{
143cb9a9
RS
1578 char *tzstring;
1579
1580 if (NILP (tz))
1581 tzstring = 0;
2e34157c 1582 else if (EQ (tz, Qt))
085e9fcb 1583 tzstring = "UTC0";
143cb9a9
RS
1584 else
1585 {
1586 CHECK_STRING (tz, 0);
4d4c1514 1587 tzstring = (char *) XSTRING (tz)->data;
143cb9a9
RS
1588 }
1589
c59b5089
PE
1590 set_time_zone_rule (tzstring);
1591 if (environbuf)
1592 free (environbuf);
1593 environbuf = environ;
1594
1595 return Qnil;
1596}
1597
e0bf9faf
PE
1598#ifdef LOCALTIME_CACHE
1599
1600/* These two values are known to load tz files in buggy implementations,
1601 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1155c453
RS
1602 Their values shouldn't matter in non-buggy implementations.
1603 We don't use string literals for these strings,
1604 since if a string in the environment is in readonly
1605 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
1606 See Sun bugs 1113095 and 1114114, ``Timezone routines
1607 improperly modify environment''. */
1608
e0bf9faf
PE
1609static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
1610static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
1611
1612#endif
1155c453 1613
c59b5089
PE
1614/* Set the local time zone rule to TZSTRING.
1615 This allocates memory into `environ', which it is the caller's
1616 responsibility to free. */
a92ae0ce 1617void
c59b5089
PE
1618set_time_zone_rule (tzstring)
1619 char *tzstring;
1620{
1621 int envptrs;
1622 char **from, **to, **newenv;
1623
aafe5147 1624 /* Make the ENVIRON vector longer with room for TZSTRING. */
143cb9a9
RS
1625 for (from = environ; *from; from++)
1626 continue;
1627 envptrs = from - environ + 2;
1628 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
1629 + (tzstring ? strlen (tzstring) + 4 : 0));
aafe5147
RS
1630
1631 /* Add TZSTRING to the end of environ, as a value for TZ. */
143cb9a9
RS
1632 if (tzstring)
1633 {
1634 char *t = (char *) (to + envptrs);
1635 strcpy (t, "TZ=");
1636 strcat (t, tzstring);
1637 *to++ = t;
1638 }
1639
aafe5147
RS
1640 /* Copy the old environ vector elements into NEWENV,
1641 but don't copy the TZ variable.
1642 So we have only one definition of TZ, which came from TZSTRING. */
143cb9a9
RS
1643 for (from = environ; *from; from++)
1644 if (strncmp (*from, "TZ=", 3) != 0)
1645 *to++ = *from;
1646 *to = 0;
1647
1648 environ = newenv;
143cb9a9 1649
aafe5147
RS
1650 /* If we do have a TZSTRING, NEWENV points to the vector slot where
1651 the TZ variable is stored. If we do not have a TZSTRING,
1652 TO points to the vector slot which has the terminating null. */
1653
143cb9a9 1654#ifdef LOCALTIME_CACHE
aafe5147
RS
1655 {
1656 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
1657 "US/Pacific" that loads a tz file, then changes to a value like
1658 "XXX0" that does not load a tz file, and then changes back to
1659 its original value, the last change is (incorrectly) ignored.
1660 Also, if TZ changes twice in succession to values that do
1661 not load a tz file, tzset can dump core (see Sun bug#1225179).
1662 The following code works around these bugs. */
1663
aafe5147
RS
1664 if (tzstring)
1665 {
1666 /* Temporarily set TZ to a value that loads a tz file
1667 and that differs from tzstring. */
1668 char *tz = *newenv;
1155c453
RS
1669 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
1670 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
aafe5147
RS
1671 tzset ();
1672 *newenv = tz;
1673 }
1674 else
1675 {
1676 /* The implied tzstring is unknown, so temporarily set TZ to
1677 two different values that each load a tz file. */
1155c453 1678 *to = set_time_zone_rule_tz1;
aafe5147
RS
1679 to[1] = 0;
1680 tzset ();
1155c453 1681 *to = set_time_zone_rule_tz2;
aafe5147
RS
1682 tzset ();
1683 *to = 0;
1684 }
1685
1686 /* Now TZ has the desired value, and tzset can be invoked safely. */
1687 }
1688
143cb9a9
RS
1689 tzset ();
1690#endif
143cb9a9 1691}
35692fe0 1692\f
fb8106e8
KH
1693/* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
1694 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
1695 type of object is Lisp_String). INHERIT is passed to
1696 INSERT_FROM_STRING_FUNC as the last argument. */
1697
d11ba98c 1698void
fb8106e8
KH
1699general_insert_function (insert_func, insert_from_string_func,
1700 inherit, nargs, args)
d11ba98c 1701 void (*insert_func) P_ ((unsigned char *, int));
1f24f4fd 1702 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
fb8106e8
KH
1703 int inherit, nargs;
1704 register Lisp_Object *args;
1705{
1706 register int argnum;
1707 register Lisp_Object val;
1708
1709 for (argnum = 0; argnum < nargs; argnum++)
1710 {
1711 val = args[argnum];
1712 retry:
1713 if (INTEGERP (val))
1714 {
d11ba98c 1715 unsigned char workbuf[4], *str;
fb8106e8
KH
1716 int len;
1717
1718 if (!NILP (current_buffer->enable_multibyte_characters))
1719 len = CHAR_STRING (XFASTINT (val), workbuf, str);
1720 else
13c148b8
KH
1721 {
1722 workbuf[0] = (SINGLE_BYTE_CHAR_P (XINT (val))
1723 ? XINT (val)
1724 : multibyte_char_to_unibyte (XINT (val), Qnil));
1725 str = workbuf;
1726 len = 1;
1727 }
fb8106e8
KH
1728 (*insert_func) (str, len);
1729 }
1730 else if (STRINGP (val))
1731 {
1f24f4fd
RS
1732 (*insert_from_string_func) (val, 0, 0,
1733 XSTRING (val)->size,
dc3620af 1734 STRING_BYTES (XSTRING (val)),
1f24f4fd 1735 inherit);
fb8106e8
KH
1736 }
1737 else
1738 {
1739 val = wrong_type_argument (Qchar_or_string_p, val);
1740 goto retry;
1741 }
1742 }
1743}
1744
35692fe0
JB
1745void
1746insert1 (arg)
1747 Lisp_Object arg;
1748{
1749 Finsert (1, &arg);
1750}
1751
52b14ac0
JB
1752
1753/* Callers passing one argument to Finsert need not gcpro the
1754 argument "array", since the only element of the array will
1755 not be used after calling insert or insert_from_string, so
1756 we don't care if it gets trashed. */
1757
35692fe0
JB
1758DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
1759 "Insert the arguments, either strings or characters, at point.\n\
24d6bf26 1760Point and before-insertion markers move forward to end up\n\
fb8106e8 1761 after the inserted text.\n\
24d6bf26
RS
1762Any other markers at the point of insertion remain before the text.\n\
1763\n\
1764If the current buffer is multibyte, unibyte strings are converted\n\
1765to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
13903932 1766If the current buffer is unibyte, multibyte strings are converted\n\
24d6bf26 1767to unibyte for insertion.")
35692fe0
JB
1768 (nargs, args)
1769 int nargs;
1770 register Lisp_Object *args;
1771{
fb8106e8 1772 general_insert_function (insert, insert_from_string, 0, nargs, args);
be91036a
RS
1773 return Qnil;
1774}
1775
1776DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
1777 0, MANY, 0,
1778 "Insert the arguments at point, inheriting properties from adjoining text.\n\
24d6bf26 1779Point and before-insertion markers move forward to end up\n\
fb8106e8 1780 after the inserted text.\n\
24d6bf26
RS
1781Any other markers at the point of insertion remain before the text.\n\
1782\n\
1783If the current buffer is multibyte, unibyte strings are converted\n\
1784to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
13903932 1785If the current buffer is unibyte, multibyte strings are converted\n\
24d6bf26 1786to unibyte for insertion.")
be91036a
RS
1787 (nargs, args)
1788 int nargs;
1789 register Lisp_Object *args;
1790{
fb8106e8
KH
1791 general_insert_function (insert_and_inherit, insert_from_string, 1,
1792 nargs, args);
35692fe0
JB
1793 return Qnil;
1794}
1795
1796DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
1797 "Insert strings or characters at point, relocating markers after the text.\n\
24d6bf26
RS
1798Point and markers move forward to end up after the inserted text.\n\
1799\n\
1800If the current buffer is multibyte, unibyte strings are converted\n\
1801to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
13903932 1802If the current buffer is unibyte, multibyte strings are converted\n\
24d6bf26 1803to unibyte for insertion.")
35692fe0
JB
1804 (nargs, args)
1805 int nargs;
1806 register Lisp_Object *args;
1807{
fb8106e8
KH
1808 general_insert_function (insert_before_markers,
1809 insert_from_string_before_markers, 0,
1810 nargs, args);
be91036a
RS
1811 return Qnil;
1812}
1813
a0d76c27
EN
1814DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
1815 Sinsert_and_inherit_before_markers, 0, MANY, 0,
be91036a 1816 "Insert text at point, relocating markers and inheriting properties.\n\
24d6bf26
RS
1817Point and markers move forward to end up after the inserted text.\n\
1818\n\
1819If the current buffer is multibyte, unibyte strings are converted\n\
1820to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
13903932 1821If the current buffer is unibyte, multibyte strings are converted\n\
24d6bf26 1822to unibyte for insertion.")
be91036a
RS
1823 (nargs, args)
1824 int nargs;
1825 register Lisp_Object *args;
1826{
fb8106e8
KH
1827 general_insert_function (insert_before_markers_and_inherit,
1828 insert_from_string_before_markers, 1,
1829 nargs, args);
35692fe0
JB
1830 return Qnil;
1831}
1832\f
e2eeabbb 1833DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2591ec64 1834 "Insert COUNT (second arg) copies of CHARACTER (first arg).\n\
e2eeabbb 1835Both arguments are required.\n\
ba88b322 1836Point, and before-insertion markers, are relocated as in the function `insert'.\n\
e2eeabbb
RS
1837The optional third arg INHERIT, if non-nil, says to inherit text properties\n\
1838from adjoining text, if those properties are sticky.")
2591ec64
EN
1839 (character, count, inherit)
1840 Lisp_Object character, count, inherit;
35692fe0
JB
1841{
1842 register unsigned char *string;
1843 register int strlen;
1844 register int i, n;
fb8106e8
KH
1845 int len;
1846 unsigned char workbuf[4], *str;
35692fe0 1847
2591ec64 1848 CHECK_NUMBER (character, 0);
35692fe0
JB
1849 CHECK_NUMBER (count, 1);
1850
fb8106e8
KH
1851 if (!NILP (current_buffer->enable_multibyte_characters))
1852 len = CHAR_STRING (XFASTINT (character), workbuf, str);
1853 else
1854 workbuf[0] = XFASTINT (character), str = workbuf, len = 1;
1855 n = XINT (count) * len;
35692fe0
JB
1856 if (n <= 0)
1857 return Qnil;
fb8106e8 1858 strlen = min (n, 256 * len);
35692fe0
JB
1859 string = (unsigned char *) alloca (strlen);
1860 for (i = 0; i < strlen; i++)
fb8106e8 1861 string[i] = str[i % len];
35692fe0
JB
1862 while (n >= strlen)
1863 {
54e42e2d 1864 QUIT;
e2eeabbb
RS
1865 if (!NILP (inherit))
1866 insert_and_inherit (string, strlen);
1867 else
1868 insert (string, strlen);
35692fe0
JB
1869 n -= strlen;
1870 }
1871 if (n > 0)
83951f1e
KH
1872 {
1873 if (!NILP (inherit))
1874 insert_and_inherit (string, n);
1875 else
1876 insert (string, n);
1877 }
35692fe0
JB
1878 return Qnil;
1879}
1880
1881\f
ffd56f97
JB
1882/* Making strings from buffer contents. */
1883
1884/* Return a Lisp_String containing the text of the current buffer from
74d6d8c5 1885 START to END. If text properties are in use and the current buffer
eb8c3be9 1886 has properties in the range specified, the resulting string will also
260e2e2a 1887 have them, if PROPS is nonzero.
ffd56f97
JB
1888
1889 We don't want to use plain old make_string here, because it calls
1890 make_uninit_string, which can cause the buffer arena to be
1891 compacted. make_string has no way of knowing that the data has
1892 been moved, and thus copies the wrong data into the string. This
1893 doesn't effect most of the other users of make_string, so it should
1894 be left as is. But we should use this function when conjuring
1895 buffer substrings. */
74d6d8c5 1896
ffd56f97 1897Lisp_Object
260e2e2a 1898make_buffer_string (start, end, props)
ffd56f97 1899 int start, end;
260e2e2a 1900 int props;
ffd56f97 1901{
ec1c14f6
RS
1902 int start_byte = CHAR_TO_BYTE (start);
1903 int end_byte = CHAR_TO_BYTE (end);
ffd56f97 1904
88441c8e
RS
1905 return make_buffer_string_both (start, start_byte, end, end_byte, props);
1906}
1907
1908/* Return a Lisp_String containing the text of the current buffer from
1909 START / START_BYTE to END / END_BYTE.
1910
1911 If text properties are in use and the current buffer
1912 has properties in the range specified, the resulting string will also
1913 have them, if PROPS is nonzero.
1914
1915 We don't want to use plain old make_string here, because it calls
1916 make_uninit_string, which can cause the buffer arena to be
1917 compacted. make_string has no way of knowing that the data has
1918 been moved, and thus copies the wrong data into the string. This
1919 doesn't effect most of the other users of make_string, so it should
1920 be left as is. But we should use this function when conjuring
1921 buffer substrings. */
1922
1923Lisp_Object
1924make_buffer_string_both (start, start_byte, end, end_byte, props)
1925 int start, start_byte, end, end_byte;
1926 int props;
1927{
1928 Lisp_Object result, tem, tem1;
1929
ffd56f97
JB
1930 if (start < GPT && GPT < end)
1931 move_gap (start);
1932
5f75e666
RS
1933 if (! NILP (current_buffer->enable_multibyte_characters))
1934 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
1935 else
1936 result = make_uninit_string (end - start);
ec1c14f6
RS
1937 bcopy (BYTE_POS_ADDR (start_byte), XSTRING (result)->data,
1938 end_byte - start_byte);
ffd56f97 1939
260e2e2a 1940 /* If desired, update and copy the text properties. */
260e2e2a
KH
1941 if (props)
1942 {
1943 update_buffer_properties (start, end);
1944
1945 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
1946 tem1 = Ftext_properties_at (make_number (start), Qnil);
1947
1948 if (XINT (tem) != end || !NILP (tem1))
ec1c14f6
RS
1949 copy_intervals_to_string (result, current_buffer, start,
1950 end - start);
260e2e2a 1951 }
74d6d8c5 1952
ffd56f97
JB
1953 return result;
1954}
35692fe0 1955
260e2e2a
KH
1956/* Call Vbuffer_access_fontify_functions for the range START ... END
1957 in the current buffer, if necessary. */
1958
1959static void
1960update_buffer_properties (start, end)
1961 int start, end;
1962{
260e2e2a
KH
1963 /* If this buffer has some access functions,
1964 call them, specifying the range of the buffer being accessed. */
1965 if (!NILP (Vbuffer_access_fontify_functions))
1966 {
1967 Lisp_Object args[3];
1968 Lisp_Object tem;
1969
1970 args[0] = Qbuffer_access_fontify_functions;
1971 XSETINT (args[1], start);
1972 XSETINT (args[2], end);
1973
1974 /* But don't call them if we can tell that the work
1975 has already been done. */
1976 if (!NILP (Vbuffer_access_fontified_property))
1977 {
1978 tem = Ftext_property_any (args[1], args[2],
1979 Vbuffer_access_fontified_property,
1980 Qnil, Qnil);
1981 if (! NILP (tem))
ced1d19a 1982 Frun_hook_with_args (3, args);
260e2e2a
KH
1983 }
1984 else
ced1d19a 1985 Frun_hook_with_args (3, args);
260e2e2a 1986 }
260e2e2a
KH
1987}
1988
35692fe0
JB
1989DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
1990 "Return the contents of part of the current buffer as a string.\n\
1991The two arguments START and END are character positions;\n\
24d6bf26
RS
1992they can be in either order.\n\
1993The string returned is multibyte if the buffer is multibyte.")
2591ec64
EN
1994 (start, end)
1995 Lisp_Object start, end;
35692fe0 1996{
2591ec64 1997 register int b, e;
35692fe0 1998
2591ec64
EN
1999 validate_region (&start, &end);
2000 b = XINT (start);
2001 e = XINT (end);
35692fe0 2002
2591ec64 2003 return make_buffer_string (b, e, 1);
260e2e2a
KH
2004}
2005
2006DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2007 Sbuffer_substring_no_properties, 2, 2, 0,
2008 "Return the characters of part of the buffer, without the text properties.\n\
2009The two arguments START and END are character positions;\n\
2010they can be in either order.")
2591ec64
EN
2011 (start, end)
2012 Lisp_Object start, end;
260e2e2a 2013{
2591ec64 2014 register int b, e;
260e2e2a 2015
2591ec64
EN
2016 validate_region (&start, &end);
2017 b = XINT (start);
2018 e = XINT (end);
260e2e2a 2019
2591ec64 2020 return make_buffer_string (b, e, 0);
35692fe0
JB
2021}
2022
2023DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
af7bd86c
KH
2024 "Return the contents of the current buffer as a string.\n\
2025If narrowing is in effect, this function returns only the visible part\n\
2da8bf64
GM
2026of the buffer. If in a mini-buffer, don't include the prompt in the\n\
2027string returned.")
35692fe0
JB
2028 ()
2029{
0daf6e8d 2030 return make_buffer_string (BEGV, ZV, 1);
35692fe0
JB
2031}
2032
2033DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2034 1, 3, 0,
83ea6fc2 2035 "Insert before point a substring of the contents of buffer BUFFER.\n\
35692fe0
JB
2036BUFFER may be a buffer or a buffer name.\n\
2037Arguments START and END are character numbers specifying the substring.\n\
2038They default to the beginning and the end of BUFFER.")
2591ec64
EN
2039 (buf, start, end)
2040 Lisp_Object buf, start, end;
35692fe0 2041{
2591ec64 2042 register int b, e, temp;
260e2e2a 2043 register struct buffer *bp, *obuf;
3fff2dfa 2044 Lisp_Object buffer;
35692fe0 2045
3fff2dfa
RS
2046 buffer = Fget_buffer (buf);
2047 if (NILP (buffer))
2048 nsberror (buf);
2049 bp = XBUFFER (buffer);
93b62e82
KH
2050 if (NILP (bp->name))
2051 error ("Selecting deleted buffer");
35692fe0 2052
2591ec64
EN
2053 if (NILP (start))
2054 b = BUF_BEGV (bp);
35692fe0
JB
2055 else
2056 {
2591ec64
EN
2057 CHECK_NUMBER_COERCE_MARKER (start, 0);
2058 b = XINT (start);
35692fe0 2059 }
2591ec64
EN
2060 if (NILP (end))
2061 e = BUF_ZV (bp);
35692fe0
JB
2062 else
2063 {
2591ec64
EN
2064 CHECK_NUMBER_COERCE_MARKER (end, 1);
2065 e = XINT (end);
35692fe0
JB
2066 }
2067
2591ec64
EN
2068 if (b > e)
2069 temp = b, b = e, e = temp;
35692fe0 2070
2591ec64
EN
2071 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2072 args_out_of_range (start, end);
35692fe0 2073
260e2e2a
KH
2074 obuf = current_buffer;
2075 set_buffer_internal_1 (bp);
2591ec64 2076 update_buffer_properties (b, e);
260e2e2a
KH
2077 set_buffer_internal_1 (obuf);
2078
2591ec64 2079 insert_from_buffer (bp, b, e - b, 0);
35692fe0
JB
2080 return Qnil;
2081}
e9cf2084
RS
2082
2083DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2084 6, 6, 0,
2085 "Compare two substrings of two buffers; return result as number.\n\
2086the value is -N if first string is less after N-1 chars,\n\
2087+N if first string is greater after N-1 chars, or 0 if strings match.\n\
2088Each substring is represented as three arguments: BUFFER, START and END.\n\
2089That makes six args in all, three for each substring.\n\n\
2090The value of `case-fold-search' in the current buffer\n\
2091determines whether case is significant or ignored.")
2092 (buffer1, start1, end1, buffer2, start2, end2)
2093 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2094{
07422a12 2095 register int begp1, endp1, begp2, endp2, temp;
e9cf2084 2096 register struct buffer *bp1, *bp2;
2a8b0ff0 2097 register Lisp_Object *trt
e9cf2084 2098 = (!NILP (current_buffer->case_fold_search)
2a8b0ff0 2099 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents : 0);
ec1c14f6 2100 int chars = 0;
07422a12 2101 int i1, i2, i1_byte, i2_byte;
e9cf2084
RS
2102
2103 /* Find the first buffer and its substring. */
2104
2105 if (NILP (buffer1))
2106 bp1 = current_buffer;
2107 else
2108 {
3fff2dfa
RS
2109 Lisp_Object buf1;
2110 buf1 = Fget_buffer (buffer1);
2111 if (NILP (buf1))
2112 nsberror (buffer1);
2113 bp1 = XBUFFER (buf1);
93b62e82
KH
2114 if (NILP (bp1->name))
2115 error ("Selecting deleted buffer");
e9cf2084
RS
2116 }
2117
2118 if (NILP (start1))
2119 begp1 = BUF_BEGV (bp1);
2120 else
2121 {
2122 CHECK_NUMBER_COERCE_MARKER (start1, 1);
2123 begp1 = XINT (start1);
2124 }
2125 if (NILP (end1))
2126 endp1 = BUF_ZV (bp1);
2127 else
2128 {
2129 CHECK_NUMBER_COERCE_MARKER (end1, 2);
2130 endp1 = XINT (end1);
2131 }
2132
2133 if (begp1 > endp1)
2134 temp = begp1, begp1 = endp1, endp1 = temp;
2135
2136 if (!(BUF_BEGV (bp1) <= begp1
2137 && begp1 <= endp1
2138 && endp1 <= BUF_ZV (bp1)))
2139 args_out_of_range (start1, end1);
2140
2141 /* Likewise for second substring. */
2142
2143 if (NILP (buffer2))
2144 bp2 = current_buffer;
2145 else
2146 {
3fff2dfa
RS
2147 Lisp_Object buf2;
2148 buf2 = Fget_buffer (buffer2);
2149 if (NILP (buf2))
2150 nsberror (buffer2);
3b1fdd85 2151 bp2 = XBUFFER (buf2);
93b62e82
KH
2152 if (NILP (bp2->name))
2153 error ("Selecting deleted buffer");
e9cf2084
RS
2154 }
2155
2156 if (NILP (start2))
2157 begp2 = BUF_BEGV (bp2);
2158 else
2159 {
2160 CHECK_NUMBER_COERCE_MARKER (start2, 4);
2161 begp2 = XINT (start2);
2162 }
2163 if (NILP (end2))
2164 endp2 = BUF_ZV (bp2);
2165 else
2166 {
2167 CHECK_NUMBER_COERCE_MARKER (end2, 5);
2168 endp2 = XINT (end2);
2169 }
2170
2171 if (begp2 > endp2)
2172 temp = begp2, begp2 = endp2, endp2 = temp;
2173
2174 if (!(BUF_BEGV (bp2) <= begp2
2175 && begp2 <= endp2
2176 && endp2 <= BUF_ZV (bp2)))
2177 args_out_of_range (start2, end2);
2178
07422a12
RS
2179 i1 = begp1;
2180 i2 = begp2;
2181 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2182 i2_byte = buf_charpos_to_bytepos (bp2, i2);
e9cf2084 2183
07422a12 2184 while (i1 < endp1 && i2 < endp2)
e9cf2084 2185 {
07422a12
RS
2186 /* When we find a mismatch, we must compare the
2187 characters, not just the bytes. */
2188 int c1, c2;
ec1c14f6 2189
07422a12
RS
2190 if (! NILP (bp1->enable_multibyte_characters))
2191 {
2192 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2193 BUF_INC_POS (bp1, i1_byte);
2194 i1++;
2195 }
2196 else
2197 {
2198 c1 = BUF_FETCH_BYTE (bp1, i1);
2199 c1 = unibyte_char_to_multibyte (c1);
2200 i1++;
2201 }
2202
2203 if (! NILP (bp2->enable_multibyte_characters))
2204 {
2205 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2206 BUF_INC_POS (bp2, i2_byte);
2207 i2++;
2208 }
2209 else
2210 {
2211 c2 = BUF_FETCH_BYTE (bp2, i2);
2212 c2 = unibyte_char_to_multibyte (c2);
2213 i2++;
2214 }
ec1c14f6 2215
e9cf2084
RS
2216 if (trt)
2217 {
1b10fb77
RS
2218 c1 = XINT (trt[c1]);
2219 c2 = XINT (trt[c2]);
e9cf2084
RS
2220 }
2221 if (c1 < c2)
ec1c14f6 2222 return make_number (- 1 - chars);
e9cf2084 2223 if (c1 > c2)
ec1c14f6 2224 return make_number (chars + 1);
07422a12
RS
2225
2226 chars++;
e9cf2084
RS
2227 }
2228
2229 /* The strings match as far as they go.
2230 If one is shorter, that one is less. */
07422a12 2231 if (chars < endp1 - begp1)
ec1c14f6 2232 return make_number (chars + 1);
07422a12 2233 else if (chars < endp2 - begp2)
ec1c14f6 2234 return make_number (- chars - 1);
e9cf2084
RS
2235
2236 /* Same length too => they are equal. */
2237 return make_number (0);
2238}
35692fe0 2239\f
d5a539cd
RS
2240static Lisp_Object
2241subst_char_in_region_unwind (arg)
2242 Lisp_Object arg;
2243{
2244 return current_buffer->undo_list = arg;
2245}
2246
c8e76b47
RS
2247static Lisp_Object
2248subst_char_in_region_unwind_1 (arg)
2249 Lisp_Object arg;
2250{
2251 return current_buffer->filename = arg;
2252}
2253
35692fe0
JB
2254DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2255 Ssubst_char_in_region, 4, 5, 0,
2256 "From START to END, replace FROMCHAR with TOCHAR each time it occurs.\n\
2257If optional arg NOUNDO is non-nil, don't record this change for undo\n\
fb8106e8
KH
2258and don't mark the buffer as really changed.\n\
2259Both characters must have the same length of multi-byte form.")
35692fe0
JB
2260 (start, end, fromchar, tochar, noundo)
2261 Lisp_Object start, end, fromchar, tochar, noundo;
2262{
84246b95 2263 register int pos, pos_byte, stop, i, len, end_byte;
60b96ee7 2264 int changed = 0;
fb8106e8 2265 unsigned char fromwork[4], *fromstr, towork[4], *tostr, *p;
d5a539cd 2266 int count = specpdl_ptr - specpdl;
aa801467
KH
2267#define COMBINING_NO 0
2268#define COMBINING_BEFORE 1
2269#define COMBINING_AFTER 2
2270#define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2271 int maybe_byte_combining = COMBINING_NO;
35692fe0
JB
2272
2273 validate_region (&start, &end);
2274 CHECK_NUMBER (fromchar, 2);
2275 CHECK_NUMBER (tochar, 3);
2276
fb8106e8
KH
2277 if (! NILP (current_buffer->enable_multibyte_characters))
2278 {
2279 len = CHAR_STRING (XFASTINT (fromchar), fromwork, fromstr);
2280 if (CHAR_STRING (XFASTINT (tochar), towork, tostr) != len)
2281 error ("Characters in subst-char-in-region have different byte-lengths");
aa801467
KH
2282 if (!ASCII_BYTE_P (*tostr))
2283 {
2284 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2285 complete multibyte character, it may be combined with the
2286 after bytes. If it is in the range 0xA0..0xFF, it may be
2287 combined with the before and after bytes. */
2288 if (!CHAR_HEAD_P (*tostr))
2289 maybe_byte_combining = COMBINING_BOTH;
2290 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2291 maybe_byte_combining = COMBINING_AFTER;
2292 }
fb8106e8
KH
2293 }
2294 else
2295 {
2296 len = 1;
2297 fromwork[0] = XFASTINT (fromchar), fromstr = fromwork;
2298 towork[0] = XFASTINT (tochar), tostr = towork;
2299 }
2300
84246b95
KH
2301 pos = XINT (start);
2302 pos_byte = CHAR_TO_BYTE (pos);
ec1c14f6
RS
2303 stop = CHAR_TO_BYTE (XINT (end));
2304 end_byte = stop;
35692fe0 2305
d5a539cd
RS
2306 /* If we don't want undo, turn off putting stuff on the list.
2307 That's faster than getting rid of things,
c8e76b47
RS
2308 and it prevents even the entry for a first change.
2309 Also inhibit locking the file. */
d5a539cd
RS
2310 if (!NILP (noundo))
2311 {
2312 record_unwind_protect (subst_char_in_region_unwind,
2313 current_buffer->undo_list);
2314 current_buffer->undo_list = Qt;
c8e76b47
RS
2315 /* Don't do file-locking. */
2316 record_unwind_protect (subst_char_in_region_unwind_1,
2317 current_buffer->filename);
2318 current_buffer->filename = Qnil;
d5a539cd
RS
2319 }
2320
84246b95 2321 if (pos_byte < GPT_BYTE)
ec1c14f6 2322 stop = min (stop, GPT_BYTE);
fb8106e8 2323 while (1)
35692fe0 2324 {
a3360ff9
KH
2325 int pos_byte_next = pos_byte;
2326
84246b95 2327 if (pos_byte >= stop)
fb8106e8 2328 {
84246b95 2329 if (pos_byte >= end_byte) break;
ec1c14f6 2330 stop = end_byte;
fb8106e8 2331 }
84246b95 2332 p = BYTE_POS_ADDR (pos_byte);
a3360ff9
KH
2333 INC_POS (pos_byte_next);
2334 if (pos_byte_next - pos_byte == len
2335 && p[0] == fromstr[0]
fb8106e8
KH
2336 && (len == 1
2337 || (p[1] == fromstr[1]
2338 && (len == 2 || (p[2] == fromstr[2]
2339 && (len == 3 || p[3] == fromstr[3]))))))
35692fe0 2340 {
60b96ee7
RS
2341 if (! changed)
2342 {
fb8106e8 2343 modify_region (current_buffer, XINT (start), XINT (end));
7653d030
RS
2344
2345 if (! NILP (noundo))
2346 {
1e158d25
RS
2347 if (MODIFF - 1 == SAVE_MODIFF)
2348 SAVE_MODIFF++;
7653d030
RS
2349 if (MODIFF - 1 == current_buffer->auto_save_modified)
2350 current_buffer->auto_save_modified++;
2351 }
2352
fb8106e8 2353 changed = 1;
60b96ee7
RS
2354 }
2355
0c1e3b85
RS
2356 /* Take care of the case where the new character
2357 combines with neighboring bytes. */
a3360ff9 2358 if (maybe_byte_combining
aa801467
KH
2359 && (maybe_byte_combining == COMBINING_AFTER
2360 ? (pos_byte_next < Z_BYTE
2361 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2362 : ((pos_byte_next < Z_BYTE
2363 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2364 || (pos_byte > BEG_BYTE
2365 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
0c1e3b85
RS
2366 {
2367 Lisp_Object tem, string;
2368
2369 struct gcpro gcpro1;
2370
2371 tem = current_buffer->undo_list;
2372 GCPRO1 (tem);
2373
aa801467
KH
2374 /* Make a multibyte string containing this single character. */
2375 string = make_multibyte_string (tostr, 1, len);
0c1e3b85
RS
2376 /* replace_range is less efficient, because it moves the gap,
2377 but it handles combining correctly. */
2378 replace_range (pos, pos + 1, string,
9869520f 2379 0, 0, 1);
a3360ff9
KH
2380 pos_byte_next = CHAR_TO_BYTE (pos);
2381 if (pos_byte_next > pos_byte)
2382 /* Before combining happened. We should not increment
3f5409d3
KH
2383 POS. So, to cancel the later increment of POS,
2384 decrease it now. */
2385 pos--;
a3360ff9 2386 else
3f5409d3 2387 INC_POS (pos_byte_next);
a3360ff9 2388
0c1e3b85
RS
2389 if (! NILP (noundo))
2390 current_buffer->undo_list = tem;
2391
2392 UNGCPRO;
2393 }
2394 else
2395 {
2396 if (NILP (noundo))
2397 record_change (pos, 1);
2398 for (i = 0; i < len; i++) *p++ = tostr[i];
2399 }
35692fe0 2400 }
3f5409d3
KH
2401 pos_byte = pos_byte_next;
2402 pos++;
35692fe0
JB
2403 }
2404
60b96ee7
RS
2405 if (changed)
2406 signal_after_change (XINT (start),
84246b95 2407 XINT (end) - XINT (start), XINT (end) - XINT (start));
60b96ee7 2408
d5a539cd 2409 unbind_to (count, Qnil);
35692fe0
JB
2410 return Qnil;
2411}
2412
2413DEFUN ("translate-region", Ftranslate_region, Stranslate_region, 3, 3, 0,
2414 "From START to END, translate characters according to TABLE.\n\
2415TABLE is a string; the Nth character in it is the mapping\n\
1f24f4fd
RS
2416for the character with code N.\n\
2417This function does not alter multibyte characters.\n\
2418It returns the number of characters changed.")
35692fe0
JB
2419 (start, end, table)
2420 Lisp_Object start;
2421 Lisp_Object end;
2422 register Lisp_Object table;
2423{
ec1c14f6 2424 register int pos_byte, stop; /* Limits of the region. */
35692fe0 2425 register unsigned char *tt; /* Trans table. */
35692fe0
JB
2426 register int nc; /* New character. */
2427 int cnt; /* Number of changes made. */
35692fe0 2428 int size; /* Size of translate table. */
1f24f4fd 2429 int pos;
e8cce5af 2430 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
35692fe0
JB
2431
2432 validate_region (&start, &end);
2433 CHECK_STRING (table, 2);
2434
dc3620af 2435 size = STRING_BYTES (XSTRING (table));
35692fe0
JB
2436 tt = XSTRING (table)->data;
2437
ec1c14f6
RS
2438 pos_byte = CHAR_TO_BYTE (XINT (start));
2439 stop = CHAR_TO_BYTE (XINT (end));
2440 modify_region (current_buffer, XINT (start), XINT (end));
1f24f4fd 2441 pos = XINT (start);
35692fe0
JB
2442
2443 cnt = 0;
1f24f4fd 2444 for (; pos_byte < stop; )
35692fe0 2445 {
ec1c14f6 2446 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
1f24f4fd
RS
2447 int len;
2448 int oc;
a3360ff9 2449 int pos_byte_next;
ec1c14f6 2450
e8cce5af
KH
2451 if (multibyte)
2452 oc = STRING_CHAR_AND_LENGTH (p, stop - pos_byte, len);
2453 else
2454 oc = *p, len = 1;
a3360ff9 2455 pos_byte_next = pos_byte + len;
1f24f4fd 2456 if (oc < size && len == 1)
35692fe0
JB
2457 {
2458 nc = tt[oc];
2459 if (nc != oc)
2460 {
0c1e3b85
RS
2461 /* Take care of the case where the new character
2462 combines with neighboring bytes. */
a3360ff9
KH
2463 if (!ASCII_BYTE_P (nc)
2464 && (CHAR_HEAD_P (nc)
2465 ? ! CHAR_HEAD_P (FETCH_BYTE (pos_byte + 1))
48839d2e 2466 : (pos_byte > BEG_BYTE
a3360ff9 2467 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1)))))
0c1e3b85
RS
2468 {
2469 Lisp_Object string;
2470
a3360ff9 2471 string = make_multibyte_string (tt + oc, 1, 1);
0c1e3b85
RS
2472 /* This is less efficient, because it moves the gap,
2473 but it handles combining correctly. */
2474 replace_range (pos, pos + 1, string,
a3360ff9
KH
2475 1, 0, 1);
2476 pos_byte_next = CHAR_TO_BYTE (pos);
2477 if (pos_byte_next > pos_byte)
2478 /* Before combining happened. We should not
3f5409d3
KH
2479 increment POS. So, to cancel the later
2480 increment of POS, we decrease it now. */
2481 pos--;
a3360ff9 2482 else
3f5409d3 2483 INC_POS (pos_byte_next);
0c1e3b85
RS
2484 }
2485 else
2486 {
2487 record_change (pos, 1);
2488 *p = nc;
2489 signal_after_change (pos, 1, 1);
2490 }
35692fe0
JB
2491 ++cnt;
2492 }
2493 }
3f5409d3
KH
2494 pos_byte = pos_byte_next;
2495 pos++;
35692fe0
JB
2496 }
2497
ec1c14f6 2498 return make_number (cnt);
35692fe0
JB
2499}
2500
2501DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
2502 "Delete the text between point and mark.\n\
2503When called from a program, expects two arguments,\n\
2504positions (integers or markers) specifying the stretch to be deleted.")
2591ec64
EN
2505 (start, end)
2506 Lisp_Object start, end;
35692fe0 2507{
2591ec64
EN
2508 validate_region (&start, &end);
2509 del_range (XINT (start), XINT (end));
35692fe0
JB
2510 return Qnil;
2511}
2512\f
2513DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
2514 "Remove restrictions (narrowing) from current buffer.\n\
2515This allows the buffer's full text to be seen and edited.")
2516 ()
2517{
2cad2e34
RS
2518 if (BEG != BEGV || Z != ZV)
2519 current_buffer->clip_changed = 1;
35692fe0 2520 BEGV = BEG;
ec1c14f6
RS
2521 BEGV_BYTE = BEG_BYTE;
2522 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
52b14ac0
JB
2523 /* Changing the buffer bounds invalidates any recorded current column. */
2524 invalidate_current_column ();
35692fe0
JB
2525 return Qnil;
2526}
2527
2528DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
2529 "Restrict editing in this buffer to the current region.\n\
2530The rest of the text becomes temporarily invisible and untouchable\n\
2531but is not deleted; if you save the buffer in a file, the invisible\n\
2532text is included in the file. \\[widen] makes all visible again.\n\
2533See also `save-restriction'.\n\
2534\n\
2535When calling from a program, pass two arguments; positions (integers\n\
2536or markers) bounding the text that should remain visible.")
2591ec64
EN
2537 (start, end)
2538 register Lisp_Object start, end;
35692fe0 2539{
2591ec64
EN
2540 CHECK_NUMBER_COERCE_MARKER (start, 0);
2541 CHECK_NUMBER_COERCE_MARKER (end, 1);
35692fe0 2542
2591ec64 2543 if (XINT (start) > XINT (end))
35692fe0 2544 {
b5a6948e 2545 Lisp_Object tem;
2591ec64 2546 tem = start; start = end; end = tem;
35692fe0
JB
2547 }
2548
2591ec64
EN
2549 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
2550 args_out_of_range (start, end);
35692fe0 2551
2cad2e34
RS
2552 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
2553 current_buffer->clip_changed = 1;
2554
ec1c14f6 2555 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2591ec64 2556 SET_BUF_ZV (current_buffer, XFASTINT (end));
6ec8bbd2 2557 if (PT < XFASTINT (start))
2591ec64 2558 SET_PT (XFASTINT (start));
6ec8bbd2 2559 if (PT > XFASTINT (end))
2591ec64 2560 SET_PT (XFASTINT (end));
52b14ac0
JB
2561 /* Changing the buffer bounds invalidates any recorded current column. */
2562 invalidate_current_column ();
35692fe0
JB
2563 return Qnil;
2564}
2565
2566Lisp_Object
2567save_restriction_save ()
2568{
2569 register Lisp_Object bottom, top;
2570 /* Note: I tried using markers here, but it does not win
2571 because insertion at the end of the saved region
2572 does not advance mh and is considered "outside" the saved region. */
55561c63
KH
2573 XSETFASTINT (bottom, BEGV - BEG);
2574 XSETFASTINT (top, Z - ZV);
35692fe0
JB
2575
2576 return Fcons (Fcurrent_buffer (), Fcons (bottom, top));
2577}
2578
2579Lisp_Object
2580save_restriction_restore (data)
2581 Lisp_Object data;
2582{
2583 register struct buffer *buf;
2584 register int newhead, newtail;
2585 register Lisp_Object tem;
2cad2e34 2586 int obegv, ozv;
35692fe0 2587
03699b14 2588 buf = XBUFFER (XCAR (data));
35692fe0 2589
03699b14 2590 data = XCDR (data);
35692fe0 2591
03699b14 2592 tem = XCAR (data);
35692fe0 2593 newhead = XINT (tem);
03699b14 2594 tem = XCDR (data);
35692fe0
JB
2595 newtail = XINT (tem);
2596 if (newhead + newtail > BUF_Z (buf) - BUF_BEG (buf))
2597 {
2598 newhead = 0;
2599 newtail = 0;
2600 }
2cad2e34
RS
2601
2602 obegv = BUF_BEGV (buf);
2603 ozv = BUF_ZV (buf);
2604
ec1c14f6 2605 SET_BUF_BEGV (buf, BUF_BEG (buf) + newhead);
35692fe0 2606 SET_BUF_ZV (buf, BUF_Z (buf) - newtail);
2cad2e34
RS
2607
2608 if (obegv != BUF_BEGV (buf) || ozv != BUF_ZV (buf))
2609 current_buffer->clip_changed = 1;
35692fe0
JB
2610
2611 /* If point is outside the new visible range, move it inside. */
ec1c14f6
RS
2612 SET_BUF_PT_BOTH (buf,
2613 clip_to_bounds (BUF_BEGV (buf), BUF_PT (buf), BUF_ZV (buf)),
2614 clip_to_bounds (BUF_BEGV_BYTE (buf), BUF_PT_BYTE (buf),
2615 BUF_ZV_BYTE (buf)));
35692fe0
JB
2616
2617 return Qnil;
2618}
2619
2620DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
2621 "Execute BODY, saving and restoring current buffer's restrictions.\n\
2622The buffer's restrictions make parts of the beginning and end invisible.\n\
2623\(They are set up with `narrow-to-region' and eliminated with `widen'.)\n\
2624This special form, `save-restriction', saves the current buffer's restrictions\n\
2625when it is entered, and restores them when it is exited.\n\
2626So any `narrow-to-region' within BODY lasts only until the end of the form.\n\
2627The old restrictions settings are restored\n\
2628even in case of abnormal exit (throw or error).\n\
2629\n\
2630The value returned is the value of the last form in BODY.\n\
2631\n\
2632`save-restriction' can get confused if, within the BODY, you widen\n\
2633and then make changes outside the area within the saved restrictions.\n\
5b2a5316 2634See Info node `(elisp)Narrowing' for details and an appropriate technique.\n\
35692fe0
JB
2635\n\
2636Note: if you are using both `save-excursion' and `save-restriction',\n\
2637use `save-excursion' outermost:\n\
2638 (save-excursion (save-restriction ...))")
2639 (body)
2640 Lisp_Object body;
2641{
2642 register Lisp_Object val;
2643 int count = specpdl_ptr - specpdl;
2644
2645 record_unwind_protect (save_restriction_restore, save_restriction_save ());
2646 val = Fprogn (body);
2647 return unbind_to (count, val);
2648}
2649\f
2ea0266e
GM
2650#ifndef HAVE_MENUS
2651
671fbc4d
KH
2652/* Buffer for the most recent text displayed by Fmessage. */
2653static char *message_text;
2654
2655/* Allocated length of that buffer. */
2656static int message_length;
2657
2ea0266e
GM
2658#endif /* not HAVE_MENUS */
2659
35692fe0
JB
2660DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
2661 "Print a one-line message at the bottom of the screen.\n\
98fc5c3c
RS
2662The first argument is a format control string, and the rest are data\n\
2663to be formatted under control of the string. See `format' for details.\n\
2664\n\
ccdac5be
JB
2665If the first argument is nil, clear any existing message; let the\n\
2666minibuffer contents show.")
35692fe0
JB
2667 (nargs, args)
2668 int nargs;
2669 Lisp_Object *args;
2670{
ccdac5be 2671 if (NILP (args[0]))
f0250249
JB
2672 {
2673 message (0);
2674 return Qnil;
2675 }
ccdac5be
JB
2676 else
2677 {
2678 register Lisp_Object val;
2679 val = Fformat (nargs, args);
5e6d5493 2680 message3 (val, STRING_BYTES (XSTRING (val)), STRING_MULTIBYTE (val));
ccdac5be
JB
2681 return val;
2682 }
35692fe0
JB
2683}
2684
cacc3e2c
RS
2685DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
2686 "Display a message, in a dialog box if possible.\n\
2687If a dialog box is not available, use the echo area.\n\
f8250f01
RS
2688The first argument is a format control string, and the rest are data\n\
2689to be formatted under control of the string. See `format' for details.\n\
2690\n\
cacc3e2c
RS
2691If the first argument is nil, clear any existing message; let the\n\
2692minibuffer contents show.")
2693 (nargs, args)
2694 int nargs;
2695 Lisp_Object *args;
2696{
2697 if (NILP (args[0]))
2698 {
2699 message (0);
2700 return Qnil;
2701 }
2702 else
2703 {
2704 register Lisp_Object val;
2705 val = Fformat (nargs, args);
f8250f01 2706#ifdef HAVE_MENUS
cacc3e2c
RS
2707 {
2708 Lisp_Object pane, menu, obj;
2709 struct gcpro gcpro1;
2710 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
2711 GCPRO1 (pane);
2712 menu = Fcons (val, pane);
2713 obj = Fx_popup_dialog (Qt, menu);
2714 UNGCPRO;
2715 return val;
2716 }
f8250f01 2717#else /* not HAVE_MENUS */
cacc3e2c
RS
2718 /* Copy the data so that it won't move when we GC. */
2719 if (! message_text)
2720 {
2721 message_text = (char *)xmalloc (80);
2722 message_length = 80;
2723 }
dc3620af 2724 if (STRING_BYTES (XSTRING (val)) > message_length)
cacc3e2c 2725 {
dc3620af 2726 message_length = STRING_BYTES (XSTRING (val));
cacc3e2c
RS
2727 message_text = (char *)xrealloc (message_text, message_length);
2728 }
dc3620af 2729 bcopy (XSTRING (val)->data, message_text, STRING_BYTES (XSTRING (val)));
d13a8480
RS
2730 message2 (message_text, STRING_BYTES (XSTRING (val)),
2731 STRING_MULTIBYTE (val));
cacc3e2c 2732 return val;
f8250f01 2733#endif /* not HAVE_MENUS */
cacc3e2c
RS
2734 }
2735}
f8250f01 2736#ifdef HAVE_MENUS
cacc3e2c
RS
2737extern Lisp_Object last_nonmenu_event;
2738#endif
f8250f01 2739
cacc3e2c
RS
2740DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
2741 "Display a message in a dialog box or in the echo area.\n\
2742If this command was invoked with the mouse, use a dialog box.\n\
2743Otherwise, use the echo area.\n\
f8250f01
RS
2744The first argument is a format control string, and the rest are data\n\
2745to be formatted under control of the string. See `format' for details.\n\
cacc3e2c 2746\n\
cacc3e2c
RS
2747If the first argument is nil, clear any existing message; let the\n\
2748minibuffer contents show.")
2749 (nargs, args)
2750 int nargs;
2751 Lisp_Object *args;
2752{
f8250f01 2753#ifdef HAVE_MENUS
5920df33
DL
2754 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2755 && NILP (use_dialog_box))
0a56ee6b 2756 return Fmessage_box (nargs, args);
cacc3e2c
RS
2757#endif
2758 return Fmessage (nargs, args);
2759}
2760
b14dda8a
RS
2761DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
2762 "Return the string currently displayed in the echo area, or nil if none.")
2763 ()
2764{
0634a78e 2765 return current_message ();
b14dda8a
RS
2766}
2767
2d9811c4 2768
0963334d 2769DEFUN ("propertize", Fpropertize, Spropertize, 3, MANY, 0,
2d9811c4
GM
2770 "Return a copy of STRING with text properties added.\n\
2771First argument is the string to copy.\n\
2772Remaining arguments are sequences of PROPERTY VALUE pairs for text\n\
2773properties to add to the result ")
2774 (nargs, args)
2775 int nargs;
2776 Lisp_Object *args;
2777{
2778 Lisp_Object properties, string;
2779 struct gcpro gcpro1, gcpro2;
2780 int i;
2781
2782 /* Number of args must be odd. */
2783 if ((nargs & 1) == 0 || nargs < 3)
2784 error ("Wrong number of arguments");
2785
2786 properties = string = Qnil;
2787 GCPRO2 (properties, string);
2788
2789 /* First argument must be a string. */
2790 CHECK_STRING (args[0], 0);
2791 string = Fcopy_sequence (args[0]);
2792
2793 for (i = 1; i < nargs; i += 2)
2794 {
2795 CHECK_SYMBOL (args[i], i);
2796 properties = Fcons (args[i], Fcons (args[i + 1], properties));
2797 }
2798
2799 Fadd_text_properties (make_number (0),
2800 make_number (XSTRING (string)->size),
2801 properties, string);
2802 RETURN_UNGCPRO (string);
2803}
2804
2805
1f24f4fd
RS
2806/* Number of bytes that STRING will occupy when put into the result.
2807 MULTIBYTE is nonzero if the result should be multibyte. */
2808
2809#define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
2810 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
8d6179dc 2811 ? count_size_as_multibyte (XSTRING (STRING)->data, \
dc3620af
RS
2812 STRING_BYTES (XSTRING (STRING))) \
2813 : STRING_BYTES (XSTRING (STRING)))
1f24f4fd 2814
35692fe0
JB
2815DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
2816 "Format a string out of a control-string and arguments.\n\
2817The first argument is a control string.\n\
2818The other arguments are substituted into it to make the result, a string.\n\
2819It may contain %-sequences meaning to substitute the next argument.\n\
2820%s means print a string argument. Actually, prints any object, with `princ'.\n\
2821%d means print as number in decimal (%o octal, %x hex).\n\
9db1775a
RS
2822%e means print a number in exponential notation.\n\
2823%f means print a number in decimal-point notation.\n\
2824%g means print a number in exponential notation\n\
2825 or decimal-point notation, whichever uses fewer characters.\n\
35692fe0 2826%c means print a number as a single character.\n\
d6c0ea99 2827%S means print any object as an s-expression (using `prin1').\n\
9db1775a 2828 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.\n\
52b14ac0 2829Use %% to put a single % into the output.")
35692fe0
JB
2830 (nargs, args)
2831 int nargs;
2832 register Lisp_Object *args;
2833{
2834 register int n; /* The number of the next arg to substitute */
e781c49e 2835 register int total; /* An estimate of the final length */
1f24f4fd 2836 char *buf, *p;
35692fe0 2837 register unsigned char *format, *end;
2ea0266e 2838 int nchars;
1f24f4fd
RS
2839 /* Nonzero if the output should be a multibyte string,
2840 which is true if any of the inputs is one. */
2841 int multibyte = 0;
8f2917e4
KH
2842 /* When we make a multibyte string, we must pay attention to the
2843 byte combining problem, i.e., a byte may be combined with a
2844 multibyte charcter of the previous string. This flag tells if we
2845 must consider such a situation or not. */
2846 int maybe_combine_byte;
1f24f4fd 2847 unsigned char *this_format;
e781c49e 2848 int longest_format;
8d6179dc 2849 Lisp_Object val;
5e6d5493
GM
2850 struct info
2851 {
2852 int start, end;
2853 } *info = 0;
1f24f4fd 2854
35692fe0 2855 extern char *index ();
1f24f4fd 2856
35692fe0
JB
2857 /* It should not be necessary to GCPRO ARGS, because
2858 the caller in the interpreter should take care of that. */
2859
e781c49e
RS
2860 /* Try to determine whether the result should be multibyte.
2861 This is not always right; sometimes the result needs to be multibyte
2862 because of an object that we will pass through prin1,
2863 and in that case, we won't know it here. */
1f24f4fd
RS
2864 for (n = 0; n < nargs; n++)
2865 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
2866 multibyte = 1;
2867
35692fe0 2868 CHECK_STRING (args[0], 0);
e781c49e
RS
2869
2870 /* If we start out planning a unibyte result,
2871 and later find it has to be multibyte, we jump back to retry. */
2872 retry:
2873
35692fe0 2874 format = XSTRING (args[0])->data;
dc3620af 2875 end = format + STRING_BYTES (XSTRING (args[0]));
e781c49e 2876 longest_format = 0;
1f24f4fd
RS
2877
2878 /* Make room in result for all the non-%-codes in the control string. */
e781c49e 2879 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]);
1f24f4fd
RS
2880
2881 /* Add to TOTAL enough space to hold the converted arguments. */
35692fe0
JB
2882
2883 n = 0;
2884 while (format != end)
2885 if (*format++ == '%')
2886 {
1f24f4fd
RS
2887 int minlen, thissize = 0;
2888 unsigned char *this_format_start = format - 1;
35692fe0
JB
2889
2890 /* Process a numeric arg and skip it. */
2891 minlen = atoi (format);
537dfb13
RS
2892 if (minlen < 0)
2893 minlen = - minlen;
2894
35692fe0
JB
2895 while ((*format >= '0' && *format <= '9')
2896 || *format == '-' || *format == ' ' || *format == '.')
2897 format++;
2898
1f24f4fd
RS
2899 if (format - this_format_start + 1 > longest_format)
2900 longest_format = format - this_format_start + 1;
2901
bf6ab66c
KH
2902 if (format == end)
2903 error ("Format string ends in middle of format specifier");
35692fe0
JB
2904 if (*format == '%')
2905 format++;
2906 else if (++n >= nargs)
537dfb13 2907 error ("Not enough arguments for format string");
35692fe0
JB
2908 else if (*format == 'S')
2909 {
2910 /* For `S', prin1 the argument and then treat like a string. */
2911 register Lisp_Object tem;
2912 tem = Fprin1_to_string (args[n], Qnil);
e781c49e
RS
2913 if (STRING_MULTIBYTE (tem) && ! multibyte)
2914 {
2915 multibyte = 1;
2916 goto retry;
2917 }
35692fe0
JB
2918 args[n] = tem;
2919 goto string;
2920 }
ae683129 2921 else if (SYMBOLP (args[n]))
35692fe0 2922 {
d2fd0445 2923 XSETSTRING (args[n], XSYMBOL (args[n])->name);
7df74da6
RS
2924 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
2925 {
2926 multibyte = 1;
2927 goto retry;
2928 }
35692fe0
JB
2929 goto string;
2930 }
ae683129 2931 else if (STRINGP (args[n]))
35692fe0
JB
2932 {
2933 string:
b22e7ecc 2934 if (*format != 's' && *format != 'S')
bf6ab66c 2935 error ("Format specifier doesn't match argument type");
1f24f4fd 2936 thissize = CONVERTED_BYTE_SIZE (multibyte, args[n]);
35692fe0
JB
2937 }
2938 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
ae683129 2939 else if (INTEGERP (args[n]) && *format != 's')
35692fe0 2940 {
4746118a 2941#ifdef LISP_FLOAT_TYPE
eb8c3be9 2942 /* The following loop assumes the Lisp type indicates
35692fe0
JB
2943 the proper way to pass the argument.
2944 So make sure we have a flonum if the argument should
2945 be a double. */
2946 if (*format == 'e' || *format == 'f' || *format == 'g')
2947 args[n] = Ffloat (args[n]);
4224cb62 2948 else
4746118a 2949#endif
4224cb62 2950 if (*format != 'd' && *format != 'o' && *format != 'x'
00d65216 2951 && *format != 'i' && *format != 'X' && *format != 'c')
4224cb62
KH
2952 error ("Invalid format operation %%%c", *format);
2953
f49a2d74 2954 thissize = 30;
25c9e7fb
RS
2955 if (*format == 'c'
2956 && (! SINGLE_BYTE_CHAR_P (XINT (args[n]))
2957 || XINT (args[n]) == 0))
f49a2d74
KH
2958 {
2959 if (! multibyte)
2960 {
2961 multibyte = 1;
2962 goto retry;
2963 }
2964 args[n] = Fchar_to_string (args[n]);
dc3620af 2965 thissize = STRING_BYTES (XSTRING (args[n]));
f49a2d74 2966 }
35692fe0 2967 }
4746118a 2968#ifdef LISP_FLOAT_TYPE
ae683129 2969 else if (FLOATP (args[n]) && *format != 's')
35692fe0
JB
2970 {
2971 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
247422ce 2972 args[n] = Ftruncate (args[n], Qnil);
b413f895 2973 thissize = 200;
35692fe0 2974 }
4746118a 2975#endif
35692fe0
JB
2976 else
2977 {
2978 /* Anything but a string, convert to a string using princ. */
2979 register Lisp_Object tem;
2980 tem = Fprin1_to_string (args[n], Qt);
a4e91443 2981 if (STRING_MULTIBYTE (tem) & ! multibyte)
e781c49e
RS
2982 {
2983 multibyte = 1;
2984 goto retry;
2985 }
35692fe0
JB
2986 args[n] = tem;
2987 goto string;
2988 }
1f24f4fd
RS
2989
2990 if (thissize < minlen)
2991 thissize = minlen;
2992
2993 total += thissize + 4;
35692fe0
JB
2994 }
2995
e781c49e
RS
2996 /* Now we can no longer jump to retry.
2997 TOTAL and LONGEST_FORMAT are known for certain. */
2998
1f24f4fd 2999 this_format = (unsigned char *) alloca (longest_format + 1);
50aa2f90 3000
1f24f4fd
RS
3001 /* Allocate the space for the result.
3002 Note that TOTAL is an overestimate. */
3003 if (total < 1000)
3c6db9d5 3004 buf = (char *) alloca (total + 1);
1f24f4fd 3005 else
3c6db9d5 3006 buf = (char *) xmalloc (total + 1);
35692fe0 3007
1f24f4fd
RS
3008 p = buf;
3009 nchars = 0;
3010 n = 0;
35692fe0 3011
1f24f4fd
RS
3012 /* Scan the format and store result in BUF. */
3013 format = XSTRING (args[0])->data;
8f2917e4 3014 maybe_combine_byte = 0;
1f24f4fd
RS
3015 while (format != end)
3016 {
3017 if (*format == '%')
3018 {
3019 int minlen;
25c9e7fb 3020 int negative = 0;
1f24f4fd 3021 unsigned char *this_format_start = format;
35692fe0 3022
1f24f4fd 3023 format++;
fb893977 3024
1f24f4fd
RS
3025 /* Process a numeric arg and skip it. */
3026 minlen = atoi (format);
3027 if (minlen < 0)
25c9e7fb 3028 minlen = - minlen, negative = 1;
35692fe0 3029
1f24f4fd
RS
3030 while ((*format >= '0' && *format <= '9')
3031 || *format == '-' || *format == ' ' || *format == '.')
3032 format++;
35692fe0 3033
1f24f4fd
RS
3034 if (*format++ == '%')
3035 {
3036 *p++ = '%';
3037 nchars++;
3038 continue;
3039 }
3040
3041 ++n;
3042
3043 if (STRINGP (args[n]))
3044 {
25c9e7fb
RS
3045 int padding, nbytes;
3046 int width = strwidth (XSTRING (args[n])->data,
dc3620af 3047 STRING_BYTES (XSTRING (args[n])));
5e6d5493 3048 int start = nchars;
25c9e7fb
RS
3049
3050 /* If spec requires it, pad on right with spaces. */
3051 padding = minlen - width;
3052 if (! negative)
3053 while (padding-- > 0)
3054 {
3055 *p++ = ' ';
3056 nchars++;
3057 }
1f24f4fd 3058
8f2917e4
KH
3059 if (p > buf
3060 && multibyte
25aa5d64 3061 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
8f2917e4 3062 && STRING_MULTIBYTE (args[n])
25aa5d64 3063 && !CHAR_HEAD_P (XSTRING (args[n])->data[0]))
8f2917e4 3064 maybe_combine_byte = 1;
1f24f4fd 3065 nbytes = copy_text (XSTRING (args[n])->data, p,
dc3620af 3066 STRING_BYTES (XSTRING (args[n])),
1f24f4fd
RS
3067 STRING_MULTIBYTE (args[n]), multibyte);
3068 p += nbytes;
3069 nchars += XSTRING (args[n])->size;
3070
25c9e7fb
RS
3071 if (negative)
3072 while (padding-- > 0)
3073 {
3074 *p++ = ' ';
3075 nchars++;
3076 }
5e6d5493
GM
3077
3078 /* If this argument has text properties, record where
3079 in the result string it appears. */
3080 if (XSTRING (args[n])->intervals)
3081 {
3082 if (!info)
3083 {
3084 int nbytes = nargs * sizeof *info;
3085 info = (struct info *) alloca (nbytes);
3086 bzero (info, nbytes);
3087 }
3088
3089 info[n].start = start;
3090 info[n].end = nchars;
3091 }
1f24f4fd
RS
3092 }
3093 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3094 {
3095 int this_nchars;
3096
3097 bcopy (this_format_start, this_format,
3098 format - this_format_start);
3099 this_format[format - this_format_start] = 0;
3100
d0183d38
RS
3101 if (INTEGERP (args[n]))
3102 sprintf (p, this_format, XINT (args[n]));
3103 else
03699b14 3104 sprintf (p, this_format, XFLOAT_DATA (args[n]));
1f24f4fd 3105
8f2917e4
KH
3106 if (p > buf
3107 && multibyte
25aa5d64
KH
3108 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3109 && !CHAR_HEAD_P (*((unsigned char *) p)))
8f2917e4 3110 maybe_combine_byte = 1;
1f24f4fd
RS
3111 this_nchars = strlen (p);
3112 p += this_nchars;
3113 nchars += this_nchars;
3114 }
3115 }
7df74da6
RS
3116 else if (STRING_MULTIBYTE (args[0]))
3117 {
3118 /* Copy a whole multibyte character. */
8f2917e4
KH
3119 if (p > buf
3120 && multibyte
25aa5d64
KH
3121 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3122 && !CHAR_HEAD_P (*format))
8f2917e4 3123 maybe_combine_byte = 1;
7df74da6
RS
3124 *p++ = *format++;
3125 while (! CHAR_HEAD_P (*format)) *p++ = *format++;
3126 nchars++;
3127 }
3128 else if (multibyte)
1f24f4fd
RS
3129 {
3130 /* Convert a single-byte character to multibyte. */
3131 int len = copy_text (format, p, 1, 0, 1);
3132
3133 p += len;
3134 format++;
3135 nchars++;
3136 }
3137 else
3138 *p++ = *format++, nchars++;
3139 }
3140
8f2917e4
KH
3141 if (maybe_combine_byte)
3142 nchars = multibyte_chars_in_text (buf, p - buf);
5f75e666 3143 val = make_specified_string (buf, nchars, p - buf, multibyte);
8d6179dc 3144
1f24f4fd
RS
3145 /* If we allocated BUF with malloc, free it too. */
3146 if (total >= 1000)
3147 xfree (buf);
35692fe0 3148
5e6d5493
GM
3149 /* If the format string has text properties, or any of the string
3150 arguments has text properties, set up text properties of the
3151 result string. */
3152
3153 if (XSTRING (args[0])->intervals || info)
3154 {
3155 Lisp_Object len, new_len, props;
3156 struct gcpro gcpro1;
3157
3158 /* Add text properties from the format string. */
3159 len = make_number (XSTRING (args[0])->size);
3160 props = text_property_list (args[0], make_number (0), len, Qnil);
3161 GCPRO1 (props);
3162
3163 if (CONSP (props))
3164 {
3165 new_len = make_number (XSTRING (val)->size);
3166 extend_property_ranges (props, len, new_len);
3167 add_text_properties_from_list (val, props, make_number (0));
3168 }
3169
3170 /* Add text properties from arguments. */
3171 if (info)
3172 for (n = 1; n < nargs; ++n)
3173 if (info[n].end)
3174 {
3175 len = make_number (XSTRING (args[n])->size);
3176 new_len = make_number (info[n].end - info[n].start);
3177 props = text_property_list (args[n], make_number (0), len, Qnil);
3178 extend_property_ranges (props, len, new_len);
3179 add_text_properties_from_list (val, props,
3180 make_number (info[n].start));
3181 }
3182
3183 UNGCPRO;
3184 }
3185
8d6179dc 3186 return val;
35692fe0
JB
3187}
3188
2d9811c4 3189
35692fe0
JB
3190/* VARARGS 1 */
3191Lisp_Object
3192#ifdef NO_ARG_ARRAY
3193format1 (string1, arg0, arg1, arg2, arg3, arg4)
679e18b1 3194 EMACS_INT arg0, arg1, arg2, arg3, arg4;
35692fe0
JB
3195#else
3196format1 (string1)
3197#endif
3198 char *string1;
3199{
3200 char buf[100];
3201#ifdef NO_ARG_ARRAY
679e18b1 3202 EMACS_INT args[5];
35692fe0
JB
3203 args[0] = arg0;
3204 args[1] = arg1;
3205 args[2] = arg2;
3206 args[3] = arg3;
3207 args[4] = arg4;
e3670faa 3208 doprnt (buf, sizeof buf, string1, (char *)0, 5, (char **) args);
35692fe0 3209#else
ea4d2909 3210 doprnt (buf, sizeof buf, string1, (char *)0, 5, &string1 + 1);
35692fe0
JB
3211#endif
3212 return build_string (buf);
3213}
3214\f
3215DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
3216 "Return t if two characters match, optionally ignoring case.\n\
3217Both arguments must be characters (i.e. integers).\n\
3218Case is ignored if `case-fold-search' is non-nil in the current buffer.")
3219 (c1, c2)
3220 register Lisp_Object c1, c2;
3221{
1b5d98bb 3222 int i1, i2;
35692fe0
JB
3223 CHECK_NUMBER (c1, 0);
3224 CHECK_NUMBER (c2, 1);
3225
1b5d98bb 3226 if (XINT (c1) == XINT (c2))
35692fe0 3227 return Qt;
1b5d98bb
RS
3228 if (NILP (current_buffer->case_fold_search))
3229 return Qnil;
3230
3231 /* Do these in separate statements,
3232 then compare the variables.
3233 because of the way DOWNCASE uses temp variables. */
3234 i1 = DOWNCASE (XFASTINT (c1));
3235 i2 = DOWNCASE (XFASTINT (c2));
3236 return (i1 == i2 ? Qt : Qnil);
35692fe0 3237}
b229b8d1
RS
3238\f
3239/* Transpose the markers in two regions of the current buffer, and
3240 adjust the ones between them if necessary (i.e.: if the regions
3241 differ in size).
3242
ec1c14f6
RS
3243 START1, END1 are the character positions of the first region.
3244 START1_BYTE, END1_BYTE are the byte positions.
3245 START2, END2 are the character positions of the second region.
3246 START2_BYTE, END2_BYTE are the byte positions.
3247
b229b8d1
RS
3248 Traverses the entire marker list of the buffer to do so, adding an
3249 appropriate amount to some, subtracting from some, and leaving the
3250 rest untouched. Most of this is copied from adjust_markers in insdel.c.
3251
ec1c14f6 3252 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
b229b8d1
RS
3253
3254void
ec1c14f6
RS
3255transpose_markers (start1, end1, start2, end2,
3256 start1_byte, end1_byte, start2_byte, end2_byte)
b229b8d1 3257 register int start1, end1, start2, end2;
ec1c14f6 3258 register int start1_byte, end1_byte, start2_byte, end2_byte;
b229b8d1 3259{
ec1c14f6 3260 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
b229b8d1 3261 register Lisp_Object marker;
b229b8d1 3262
03240d11 3263 /* Update point as if it were a marker. */
8de1d5f0
KH
3264 if (PT < start1)
3265 ;
3266 else if (PT < end1)
ec1c14f6
RS
3267 TEMP_SET_PT_BOTH (PT + (end2 - end1),
3268 PT_BYTE + (end2_byte - end1_byte));
8de1d5f0 3269 else if (PT < start2)
ec1c14f6
RS
3270 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
3271 (PT_BYTE + (end2_byte - start2_byte)
3272 - (end1_byte - start1_byte)));
8de1d5f0 3273 else if (PT < end2)
ec1c14f6
RS
3274 TEMP_SET_PT_BOTH (PT - (start2 - start1),
3275 PT_BYTE - (start2_byte - start1_byte));
8de1d5f0 3276
03240d11
KH
3277 /* We used to adjust the endpoints here to account for the gap, but that
3278 isn't good enough. Even if we assume the caller has tried to move the
3279 gap out of our way, it might still be at start1 exactly, for example;
3280 and that places it `inside' the interval, for our purposes. The amount
3281 of adjustment is nontrivial if there's a `denormalized' marker whose
3282 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
3283 the dirty work to Fmarker_position, below. */
b229b8d1
RS
3284
3285 /* The difference between the region's lengths */
3286 diff = (end2 - start2) - (end1 - start1);
ec1c14f6 3287 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
b229b8d1
RS
3288
3289 /* For shifting each marker in a region by the length of the other
ec1c14f6 3290 region plus the distance between the regions. */
b229b8d1
RS
3291 amt1 = (end2 - start2) + (start2 - end1);
3292 amt2 = (end1 - start1) + (start2 - end1);
ec1c14f6
RS
3293 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
3294 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
b229b8d1 3295
1e158d25 3296 for (marker = BUF_MARKERS (current_buffer); !NILP (marker);
03240d11 3297 marker = XMARKER (marker)->chain)
b229b8d1 3298 {
ec1c14f6
RS
3299 mpos = marker_byte_position (marker);
3300 if (mpos >= start1_byte && mpos < end2_byte)
3301 {
3302 if (mpos < end1_byte)
3303 mpos += amt1_byte;
3304 else if (mpos < start2_byte)
3305 mpos += diff_byte;
3306 else
3307 mpos -= amt2_byte;
f3e1f752 3308 XMARKER (marker)->bytepos = mpos;
ec1c14f6
RS
3309 }
3310 mpos = XMARKER (marker)->charpos;
03240d11
KH
3311 if (mpos >= start1 && mpos < end2)
3312 {
3313 if (mpos < end1)
3314 mpos += amt1;
3315 else if (mpos < start2)
3316 mpos += diff;
3317 else
3318 mpos -= amt2;
03240d11 3319 }
ec1c14f6 3320 XMARKER (marker)->charpos = mpos;
b229b8d1
RS
3321 }
3322}
3323
3324DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
3325 "Transpose region START1 to END1 with START2 to END2.\n\
3326The regions may not be overlapping, because the size of the buffer is\n\
3327never changed in a transposition.\n\
3328\n\
ec1c14f6 3329Optional fifth arg LEAVE_MARKERS, if non-nil, means don't update\n\
b229b8d1
RS
3330any markers that happen to be located in the regions.\n\
3331\n\
3332Transposing beyond buffer boundaries is an error.")
3333 (startr1, endr1, startr2, endr2, leave_markers)
3334 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
3335{
ec1c14f6
RS
3336 register int start1, end1, start2, end2;
3337 int start1_byte, start2_byte, len1_byte, len2_byte;
3338 int gap, len1, len_mid, len2;
3c6bc7d0 3339 unsigned char *start1_addr, *start2_addr, *temp;
dc3620af
RS
3340 int combined_before_bytes_1, combined_after_bytes_1;
3341 int combined_before_bytes_2, combined_after_bytes_2;
3342 struct gcpro gcpro1, gcpro2;
b229b8d1 3343
b229b8d1 3344 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
1e158d25 3345 cur_intv = BUF_INTERVALS (current_buffer);
b229b8d1
RS
3346
3347 validate_region (&startr1, &endr1);
3348 validate_region (&startr2, &endr2);
3349
3350 start1 = XFASTINT (startr1);
3351 end1 = XFASTINT (endr1);
3352 start2 = XFASTINT (startr2);
3353 end2 = XFASTINT (endr2);
3354 gap = GPT;
3355
3356 /* Swap the regions if they're reversed. */
3357 if (start2 < end1)
3358 {
3359 register int glumph = start1;
3360 start1 = start2;
3361 start2 = glumph;
3362 glumph = end1;
3363 end1 = end2;
3364 end2 = glumph;
3365 }
3366
b229b8d1
RS
3367 len1 = end1 - start1;
3368 len2 = end2 - start2;
3369
3370 if (start2 < end1)
dc3620af 3371 error ("Transposed regions overlap");
b229b8d1 3372 else if (start1 == end1 || start2 == end2)
dc3620af 3373 error ("Transposed region has length 0");
b229b8d1
RS
3374
3375 /* The possibilities are:
3376 1. Adjacent (contiguous) regions, or separate but equal regions
3377 (no, really equal, in this case!), or
3378 2. Separate regions of unequal size.
3379
3380 The worst case is usually No. 2. It means that (aside from
3381 potential need for getting the gap out of the way), there also
3382 needs to be a shifting of the text between the two regions. So
3383 if they are spread far apart, we are that much slower... sigh. */
3384
3385 /* It must be pointed out that the really studly thing to do would
3386 be not to move the gap at all, but to leave it in place and work
3387 around it if necessary. This would be extremely efficient,
3388 especially considering that people are likely to do
3389 transpositions near where they are working interactively, which
3390 is exactly where the gap would be found. However, such code
3391 would be much harder to write and to read. So, if you are
3392 reading this comment and are feeling squirrely, by all means have
3393 a go! I just didn't feel like doing it, so I will simply move
3394 the gap the minimum distance to get it out of the way, and then
3395 deal with an unbroken array. */
3c6bc7d0
RS
3396
3397 /* Make sure the gap won't interfere, by moving it out of the text
3398 we will operate on. */
3399 if (start1 < gap && gap < end2)
3400 {
3401 if (gap - start1 < end2 - gap)
3402 move_gap (start1);
3403 else
3404 move_gap (end2);
3405 }
ec1c14f6
RS
3406
3407 start1_byte = CHAR_TO_BYTE (start1);
3408 start2_byte = CHAR_TO_BYTE (start2);
3409 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
3410 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
dc3620af
RS
3411
3412 if (end1 == start2)
3413 {
3414 combined_before_bytes_2
3415 = count_combining_before (BYTE_POS_ADDR (start2_byte),
3416 len2_byte, start1, start1_byte);
3417 combined_before_bytes_1
3418 = count_combining_before (BYTE_POS_ADDR (start1_byte),
3419 len1_byte, end2, start2_byte + len2_byte);
3420 combined_after_bytes_1
3421 = count_combining_after (BYTE_POS_ADDR (start1_byte),
3422 len1_byte, end2, start2_byte + len2_byte);
3423 combined_after_bytes_2 = 0;
3424 }
3425 else
3426 {
3427 combined_before_bytes_2
3428 = count_combining_before (BYTE_POS_ADDR (start2_byte),
3429 len2_byte, start1, start1_byte);
3430 combined_before_bytes_1
3431 = count_combining_before (BYTE_POS_ADDR (start1_byte),
3432 len1_byte, start2, start2_byte);
3433 combined_after_bytes_2
3434 = count_combining_after (BYTE_POS_ADDR (start2_byte),
3435 len2_byte, end1, start1_byte + len1_byte);
3436 combined_after_bytes_1
3437 = count_combining_after (BYTE_POS_ADDR (start1_byte),
3438 len1_byte, end2, start2_byte + len2_byte);
3439 }
3440
3441 /* If any combining is going to happen, do this the stupid way,
3442 because replace handles combining properly. */
3443 if (combined_before_bytes_1 || combined_before_bytes_2
3444 || combined_after_bytes_1 || combined_after_bytes_2)
3445 {
3446 Lisp_Object text1, text2;
3447
3448 text1 = text2 = Qnil;
3449 GCPRO2 (text1, text2);
3450
3451 text1 = make_buffer_string_both (start1, start1_byte,
3452 end1, start1_byte + len1_byte, 1);
3453 text2 = make_buffer_string_both (start2, start2_byte,
3454 end2, start2_byte + len2_byte, 1);
3455
3456 transpose_markers (start1, end1, start2, end2,
3457 start1_byte, start1_byte + len1_byte,
3458 start2_byte, start2_byte + len2_byte);
3459
c2b70590
RS
3460 replace_range (start2, end2, text1, 1, 0, 0);
3461 replace_range (start1, end1, text2, 1, 0, 0);
dc3620af
RS
3462
3463 UNGCPRO;
3464 return Qnil;
3465 }
b229b8d1
RS
3466
3467 /* Hmmm... how about checking to see if the gap is large
3468 enough to use as the temporary storage? That would avoid an
3469 allocation... interesting. Later, don't fool with it now. */
3470
3471 /* Working without memmove, for portability (sigh), so must be
3472 careful of overlapping subsections of the array... */
3473
3474 if (end1 == start2) /* adjacent regions */
3475 {
b229b8d1
RS
3476 modify_region (current_buffer, start1, end2);
3477 record_change (start1, len1 + len2);
3478
b229b8d1
RS
3479 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3480 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
09dbcf71
RS
3481 Fset_text_properties (make_number (start1), make_number (end2),
3482 Qnil, Qnil);
b229b8d1
RS
3483
3484 /* First region smaller than second. */
ec1c14f6 3485 if (len1_byte < len2_byte)
b229b8d1 3486 {
3c6bc7d0
RS
3487 /* We use alloca only if it is small,
3488 because we want to avoid stack overflow. */
ec1c14f6
RS
3489 if (len2_byte > 20000)
3490 temp = (unsigned char *) xmalloc (len2_byte);
3c6bc7d0 3491 else
ec1c14f6 3492 temp = (unsigned char *) alloca (len2_byte);
03240d11
KH
3493
3494 /* Don't precompute these addresses. We have to compute them
3495 at the last minute, because the relocating allocator might
3496 have moved the buffer around during the xmalloc. */
23017390
KH
3497 start1_addr = BYTE_POS_ADDR (start1_byte);
3498 start2_addr = BYTE_POS_ADDR (start2_byte);
03240d11 3499
ec1c14f6
RS
3500 bcopy (start2_addr, temp, len2_byte);
3501 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
3502 bcopy (temp, start1_addr, len2_byte);
3503 if (len2_byte > 20000)
3c6bc7d0 3504 free (temp);
b229b8d1
RS
3505 }
3506 else
3507 /* First region not smaller than second. */
3508 {
ec1c14f6
RS
3509 if (len1_byte > 20000)
3510 temp = (unsigned char *) xmalloc (len1_byte);
3c6bc7d0 3511 else
ec1c14f6 3512 temp = (unsigned char *) alloca (len1_byte);
23017390
KH
3513 start1_addr = BYTE_POS_ADDR (start1_byte);
3514 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
3515 bcopy (start1_addr, temp, len1_byte);
3516 bcopy (start2_addr, start1_addr, len2_byte);
3517 bcopy (temp, start1_addr + len2_byte, len1_byte);
3518 if (len1_byte > 20000)
3c6bc7d0 3519 free (temp);
b229b8d1 3520 }
b229b8d1
RS
3521 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
3522 len1, current_buffer, 0);
3523 graft_intervals_into_buffer (tmp_interval2, start1,
3524 len2, current_buffer, 0);
b229b8d1
RS
3525 }
3526 /* Non-adjacent regions, because end1 != start2, bleagh... */
3527 else
3528 {
ec1c14f6
RS
3529 len_mid = start2_byte - (start1_byte + len1_byte);
3530
3531 if (len1_byte == len2_byte)
b229b8d1
RS
3532 /* Regions are same size, though, how nice. */
3533 {
3534 modify_region (current_buffer, start1, end1);
3535 modify_region (current_buffer, start2, end2);
3536 record_change (start1, len1);
3537 record_change (start2, len2);
b229b8d1
RS
3538 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3539 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
09dbcf71
RS
3540 Fset_text_properties (make_number (start1), make_number (end1),
3541 Qnil, Qnil);
3542 Fset_text_properties (make_number (start2), make_number (end2),
3543 Qnil, Qnil);
b229b8d1 3544
ec1c14f6
RS
3545 if (len1_byte > 20000)
3546 temp = (unsigned char *) xmalloc (len1_byte);
3c6bc7d0 3547 else
ec1c14f6 3548 temp = (unsigned char *) alloca (len1_byte);
23017390
KH
3549 start1_addr = BYTE_POS_ADDR (start1_byte);
3550 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
3551 bcopy (start1_addr, temp, len1_byte);
3552 bcopy (start2_addr, start1_addr, len2_byte);
3553 bcopy (temp, start2_addr, len1_byte);
3554 if (len1_byte > 20000)
3c6bc7d0 3555 free (temp);
b229b8d1
RS
3556 graft_intervals_into_buffer (tmp_interval1, start2,
3557 len1, current_buffer, 0);
3558 graft_intervals_into_buffer (tmp_interval2, start1,
3559 len2, current_buffer, 0);
b229b8d1
RS
3560 }
3561
ec1c14f6 3562 else if (len1_byte < len2_byte) /* Second region larger than first */
b229b8d1
RS
3563 /* Non-adjacent & unequal size, area between must also be shifted. */
3564 {
b229b8d1
RS
3565 modify_region (current_buffer, start1, end2);
3566 record_change (start1, (end2 - start1));
b229b8d1
RS
3567 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3568 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3569 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
09dbcf71
RS
3570 Fset_text_properties (make_number (start1), make_number (end2),
3571 Qnil, Qnil);
b229b8d1 3572
3c6bc7d0 3573 /* holds region 2 */
ec1c14f6
RS
3574 if (len2_byte > 20000)
3575 temp = (unsigned char *) xmalloc (len2_byte);
3c6bc7d0 3576 else
ec1c14f6 3577 temp = (unsigned char *) alloca (len2_byte);
23017390
KH
3578 start1_addr = BYTE_POS_ADDR (start1_byte);
3579 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
3580 bcopy (start2_addr, temp, len2_byte);
3581 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
3582 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3583 bcopy (temp, start1_addr, len2_byte);
3584 if (len2_byte > 20000)
3c6bc7d0 3585 free (temp);
b229b8d1
RS
3586 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3587 len1, current_buffer, 0);
3588 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3589 len_mid, current_buffer, 0);
3590 graft_intervals_into_buffer (tmp_interval2, start1,
3591 len2, current_buffer, 0);
b229b8d1
RS
3592 }
3593 else
3594 /* Second region smaller than first. */
3595 {
b229b8d1
RS
3596 record_change (start1, (end2 - start1));
3597 modify_region (current_buffer, start1, end2);
3598
b229b8d1
RS
3599 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3600 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3601 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
09dbcf71
RS
3602 Fset_text_properties (make_number (start1), make_number (end2),
3603 Qnil, Qnil);
b229b8d1 3604
3c6bc7d0 3605 /* holds region 1 */
ec1c14f6
RS
3606 if (len1_byte > 20000)
3607 temp = (unsigned char *) xmalloc (len1_byte);
3c6bc7d0 3608 else
ec1c14f6 3609 temp = (unsigned char *) alloca (len1_byte);
23017390
KH
3610 start1_addr = BYTE_POS_ADDR (start1_byte);
3611 start2_addr = BYTE_POS_ADDR (start2_byte);
ec1c14f6
RS
3612 bcopy (start1_addr, temp, len1_byte);
3613 bcopy (start2_addr, start1_addr, len2_byte);
3614 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3615 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
3616 if (len1_byte > 20000)
3c6bc7d0 3617 free (temp);
b229b8d1
RS
3618 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3619 len1, current_buffer, 0);
3620 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3621 len_mid, current_buffer, 0);
3622 graft_intervals_into_buffer (tmp_interval2, start1,
3623 len2, current_buffer, 0);
b229b8d1
RS
3624 }
3625 }
3626
ec1c14f6
RS
3627 /* When doing multiple transpositions, it might be nice
3628 to optimize this. Perhaps the markers in any one buffer
3629 should be organized in some sorted data tree. */
b229b8d1 3630 if (NILP (leave_markers))
8de1d5f0 3631 {
ec1c14f6
RS
3632 transpose_markers (start1, end1, start2, end2,
3633 start1_byte, start1_byte + len1_byte,
3634 start2_byte, start2_byte + len2_byte);
8de1d5f0
KH
3635 fix_overlays_in_range (start1, end2);
3636 }
b229b8d1
RS
3637
3638 return Qnil;
3639}
35692fe0 3640
35692fe0
JB
3641\f
3642void
3643syms_of_editfns ()
3644{
260e2e2a
KH
3645 environbuf = 0;
3646
3647 Qbuffer_access_fontify_functions
3648 = intern ("buffer-access-fontify-functions");
3649 staticpro (&Qbuffer_access_fontify_functions);
3650
3651 DEFVAR_LISP ("buffer-access-fontify-functions",
3652 &Vbuffer_access_fontify_functions,
3653 "List of functions called by `buffer-substring' to fontify if necessary.\n\
3654Each function is called with two arguments which specify the range\n\
3655of the buffer being accessed.");
3656 Vbuffer_access_fontify_functions = Qnil;
3657
af209db8
RS
3658 {
3659 Lisp_Object obuf;
3660 extern Lisp_Object Vprin1_to_string_buffer;
3661 obuf = Fcurrent_buffer ();
3662 /* Do this here, because init_buffer_once is too early--it won't work. */
3663 Fset_buffer (Vprin1_to_string_buffer);
3664 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
3665 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
3666 Qnil);
3667 Fset_buffer (obuf);
3668 }
3669
0b6fd023 3670 DEFVAR_LISP ("buffer-access-fontified-property",
260e2e2a
KH
3671 &Vbuffer_access_fontified_property,
3672 "Property which (if non-nil) indicates text has been fontified.\n\
3673`buffer-substring' need not call the `buffer-access-fontify-functions'\n\
3674functions if all the text being accessed has this property.");
3675 Vbuffer_access_fontified_property = Qnil;
3676
f43754f6
KH
3677 DEFVAR_LISP ("system-name", &Vsystem_name,
3678 "The name of the machine Emacs is running on.");
3679
3680 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
3681 "The full name of the user logged in.");
3682
35b34f72 3683 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
f43754f6
KH
3684 "The user's name, taken from environment variables if possible.");
3685
35b34f72 3686 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
f43754f6 3687 "The user's name, based upon the real uid only.");
35692fe0 3688
0963334d 3689 defsubr (&Spropertize);
35692fe0
JB
3690 defsubr (&Schar_equal);
3691 defsubr (&Sgoto_char);
3692 defsubr (&Sstring_to_char);
3693 defsubr (&Schar_to_string);
3694 defsubr (&Sbuffer_substring);
260e2e2a 3695 defsubr (&Sbuffer_substring_no_properties);
35692fe0
JB
3696 defsubr (&Sbuffer_string);
3697
3698 defsubr (&Spoint_marker);
3699 defsubr (&Smark_marker);
3700 defsubr (&Spoint);
3701 defsubr (&Sregion_beginning);
3702 defsubr (&Sregion_end);
7df74da6 3703
0daf6e8d
GM
3704 staticpro (&Qfield);
3705 Qfield = intern ("field");
3706 defsubr (&Sfield_beginning);
3707 defsubr (&Sfield_end);
3708 defsubr (&Sfield_string);
3709 defsubr (&Sfield_string_no_properties);
8bf64fe8 3710 defsubr (&Sdelete_field);
0daf6e8d
GM
3711 defsubr (&Sconstrain_to_field);
3712
7df74da6
RS
3713 defsubr (&Sline_beginning_position);
3714 defsubr (&Sline_end_position);
3715
35692fe0
JB
3716/* defsubr (&Smark); */
3717/* defsubr (&Sset_mark); */
3718 defsubr (&Ssave_excursion);
4bc8c7d2 3719 defsubr (&Ssave_current_buffer);
35692fe0
JB
3720
3721 defsubr (&Sbufsize);
3722 defsubr (&Spoint_max);
3723 defsubr (&Spoint_min);
3724 defsubr (&Spoint_min_marker);
3725 defsubr (&Spoint_max_marker);
c86212b9
RS
3726 defsubr (&Sgap_position);
3727 defsubr (&Sgap_size);
7df74da6 3728 defsubr (&Sposition_bytes);
3ab0732d 3729 defsubr (&Sbyte_to_position);
c9ed721d 3730
35692fe0
JB
3731 defsubr (&Sbobp);
3732 defsubr (&Seobp);
3733 defsubr (&Sbolp);
3734 defsubr (&Seolp);
850a8179
JB
3735 defsubr (&Sfollowing_char);
3736 defsubr (&Sprevious_char);
35692fe0 3737 defsubr (&Schar_after);
fb8106e8 3738 defsubr (&Schar_before);
35692fe0
JB
3739 defsubr (&Sinsert);
3740 defsubr (&Sinsert_before_markers);
be91036a
RS
3741 defsubr (&Sinsert_and_inherit);
3742 defsubr (&Sinsert_and_inherit_before_markers);
35692fe0
JB
3743 defsubr (&Sinsert_char);
3744
3745 defsubr (&Suser_login_name);
3746 defsubr (&Suser_real_login_name);
3747 defsubr (&Suser_uid);
3748 defsubr (&Suser_real_uid);
3749 defsubr (&Suser_full_name);
7fd233b3 3750 defsubr (&Semacs_pid);
d940e0e4 3751 defsubr (&Scurrent_time);
a82d387c 3752 defsubr (&Sformat_time_string);
4691c06d 3753 defsubr (&Sdecode_time);
cce7b8a0 3754 defsubr (&Sencode_time);
35692fe0 3755 defsubr (&Scurrent_time_string);
c2662aea 3756 defsubr (&Scurrent_time_zone);
143cb9a9 3757 defsubr (&Sset_time_zone_rule);
35692fe0 3758 defsubr (&Ssystem_name);
35692fe0 3759 defsubr (&Smessage);
cacc3e2c
RS
3760 defsubr (&Smessage_box);
3761 defsubr (&Smessage_or_box);
b14dda8a 3762 defsubr (&Scurrent_message);
35692fe0 3763 defsubr (&Sformat);
35692fe0
JB
3764
3765 defsubr (&Sinsert_buffer_substring);
e9cf2084 3766 defsubr (&Scompare_buffer_substrings);
35692fe0
JB
3767 defsubr (&Ssubst_char_in_region);
3768 defsubr (&Stranslate_region);
3769 defsubr (&Sdelete_region);
3770 defsubr (&Swiden);
3771 defsubr (&Snarrow_to_region);
3772 defsubr (&Ssave_restriction);
b229b8d1 3773 defsubr (&Stranspose_regions);
35692fe0 3774}