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