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