(diff-find-file-name): Fix regex subgroup number.
[emacs.git] / src / editfns.c
blob57dbdaae0ccfd720f87e3a75713d23ab186de16d
1 /* Lisp functions pertaining to editing.
2 Copyright (C) 1985,86,87,89,93,94,95,96,97,98, 1999, 2000
3 Free Software Foundation, Inc.
5 This file is part of GNU Emacs.
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING. If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA. */
23 #include <config.h>
24 #include <sys/types.h>
26 #ifdef VMS
27 #include "vms-pwd.h"
28 #else
29 #include <pwd.h>
30 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
36 #include "lisp.h"
37 #include "intervals.h"
38 #include "buffer.h"
39 #include "charset.h"
40 #include "coding.h"
41 #include "window.h"
43 #include "systime.h"
45 #define min(a, b) ((a) < (b) ? (a) : (b))
46 #define max(a, b) ((a) > (b) ? (a) : (b))
48 #ifndef NULL
49 #define NULL 0
50 #endif
52 #ifndef USE_CRT_DLL
53 extern char **environ;
54 #endif
56 extern Lisp_Object make_time P_ ((time_t));
57 extern size_t emacs_strftimeu P_ ((char *, size_t, const char *,
58 const struct tm *, int));
59 static int tm_diff P_ ((struct tm *, struct tm *));
60 static void find_field P_ ((Lisp_Object, Lisp_Object, int *, int *));
61 static void update_buffer_properties P_ ((int, int));
62 static Lisp_Object region_limit P_ ((int));
63 static int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
64 static size_t emacs_memftimeu P_ ((char *, size_t, const char *,
65 size_t, const struct tm *, int));
66 static void general_insert_function P_ ((void (*) (unsigned char *, int),
67 void (*) (Lisp_Object, int, int, int,
68 int, int),
69 int, int, Lisp_Object *));
70 static Lisp_Object subst_char_in_region_unwind P_ ((Lisp_Object));
71 static Lisp_Object subst_char_in_region_unwind_1 P_ ((Lisp_Object));
72 static void transpose_markers P_ ((int, int, int, int, int, int, int, int));
74 #ifdef HAVE_INDEX
75 extern char *index P_ ((const char *, int));
76 #endif
78 Lisp_Object Vbuffer_access_fontify_functions;
79 Lisp_Object Qbuffer_access_fontify_functions;
80 Lisp_Object Vbuffer_access_fontified_property;
82 Lisp_Object Fuser_full_name P_ ((Lisp_Object));
84 /* Non-nil means don't stop at field boundary in text motion commands. */
86 Lisp_Object Vinhibit_field_text_motion;
88 /* Some static data, and a function to initialize it for each run */
90 Lisp_Object Vsystem_name;
91 Lisp_Object Vuser_real_login_name; /* login name of current user ID */
92 Lisp_Object Vuser_full_name; /* full name of current user */
93 Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
95 /* Symbol for the text property used to mark fields. */
97 Lisp_Object Qfield;
99 /* A special value for Qfield properties. */
101 Lisp_Object Qboundary;
104 void
105 init_editfns ()
107 char *user_name;
108 register unsigned char *p;
109 struct passwd *pw; /* password entry for the current user */
110 Lisp_Object tem;
112 /* Set up system_name even when dumping. */
113 init_system_name ();
115 #ifndef CANNOT_DUMP
116 /* Don't bother with this on initial start when just dumping out */
117 if (!initialized)
118 return;
119 #endif /* not CANNOT_DUMP */
121 pw = (struct passwd *) getpwuid (getuid ());
122 #ifdef MSDOS
123 /* We let the real user name default to "root" because that's quite
124 accurate on MSDOG and because it lets Emacs find the init file.
125 (The DVX libraries override the Djgpp libraries here.) */
126 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
127 #else
128 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
129 #endif
131 /* Get the effective user name, by consulting environment variables,
132 or the effective uid if those are unset. */
133 user_name = (char *) getenv ("LOGNAME");
134 if (!user_name)
135 #ifdef WINDOWSNT
136 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
137 #else /* WINDOWSNT */
138 user_name = (char *) getenv ("USER");
139 #endif /* WINDOWSNT */
140 if (!user_name)
142 pw = (struct passwd *) getpwuid (geteuid ());
143 user_name = (char *) (pw ? pw->pw_name : "unknown");
145 Vuser_login_name = build_string (user_name);
147 /* If the user name claimed in the environment vars differs from
148 the real uid, use the claimed name to find the full name. */
149 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
150 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
151 : Vuser_login_name);
153 p = (unsigned char *) getenv ("NAME");
154 if (p)
155 Vuser_full_name = build_string (p);
156 else if (NILP (Vuser_full_name))
157 Vuser_full_name = build_string ("unknown");
160 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
161 "Convert arg CHAR to a string containing that character.")
162 (character)
163 Lisp_Object character;
165 int len;
166 unsigned char str[MAX_MULTIBYTE_LENGTH];
168 CHECK_NUMBER (character, 0);
170 len = CHAR_STRING (XFASTINT (character), str);
171 return make_string_from_bytes (str, 1, len);
174 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
175 "Convert arg STRING to a character, the first character of that string.\n\
176 A multibyte character is handled correctly.")
177 (string)
178 register Lisp_Object string;
180 register Lisp_Object val;
181 register struct Lisp_String *p;
182 CHECK_STRING (string, 0);
183 p = XSTRING (string);
184 if (p->size)
186 if (STRING_MULTIBYTE (string))
187 XSETFASTINT (val, STRING_CHAR (p->data, STRING_BYTES (p)));
188 else
189 XSETFASTINT (val, p->data[0]);
191 else
192 XSETFASTINT (val, 0);
193 return val;
196 static Lisp_Object
197 buildmark (charpos, bytepos)
198 int charpos, bytepos;
200 register Lisp_Object mark;
201 mark = Fmake_marker ();
202 set_marker_both (mark, Qnil, charpos, bytepos);
203 return mark;
206 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
207 "Return value of point, as an integer.\n\
208 Beginning of buffer is position (point-min)")
211 Lisp_Object temp;
212 XSETFASTINT (temp, PT);
213 return temp;
216 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
217 "Return value of point, as a marker object.")
220 return buildmark (PT, PT_BYTE);
224 clip_to_bounds (lower, num, upper)
225 int lower, num, upper;
227 if (num < lower)
228 return lower;
229 else if (num > upper)
230 return upper;
231 else
232 return num;
235 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
236 "Set point to POSITION, a number or marker.\n\
237 Beginning of buffer is position (point-min), end is (point-max).\n\
238 If the position is in the middle of a multibyte form,\n\
239 the actual point is set at the head of the multibyte form\n\
240 except in the case that `enable-multibyte-characters' is nil.")
241 (position)
242 register Lisp_Object position;
244 int pos;
246 if (MARKERP (position)
247 && current_buffer == XMARKER (position)->buffer)
249 pos = marker_position (position);
250 if (pos < BEGV)
251 SET_PT_BOTH (BEGV, BEGV_BYTE);
252 else if (pos > ZV)
253 SET_PT_BOTH (ZV, ZV_BYTE);
254 else
255 SET_PT_BOTH (pos, marker_byte_position (position));
257 return position;
260 CHECK_NUMBER_COERCE_MARKER (position, 0);
262 pos = clip_to_bounds (BEGV, XINT (position), ZV);
263 SET_PT (pos);
264 return position;
268 /* Return the start or end position of the region.
269 BEGINNINGP non-zero means return the start.
270 If there is no region active, signal an error. */
272 static Lisp_Object
273 region_limit (beginningp)
274 int beginningp;
276 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
277 Lisp_Object m;
279 if (!NILP (Vtransient_mark_mode)
280 && NILP (Vmark_even_if_inactive)
281 && NILP (current_buffer->mark_active))
282 Fsignal (Qmark_inactive, Qnil);
284 m = Fmarker_position (current_buffer->mark);
285 if (NILP (m))
286 error ("There is no region now");
288 if ((PT < XFASTINT (m)) == beginningp)
289 m = make_number (PT);
290 return m;
293 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
294 "Return position of beginning of region, as an integer.")
297 return region_limit (1);
300 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
301 "Return position of end of region, as an integer.")
304 return region_limit (0);
307 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
308 "Return this buffer's mark, as a marker object.\n\
309 Watch out! Moving this marker changes the mark position.\n\
310 If you set the marker not to point anywhere, the buffer will have no mark.")
313 return current_buffer->mark;
317 /* Return nonzero if POS1 and POS2 have the same value
318 for the text property PROP. */
320 static int
321 char_property_eq (prop, pos1, pos2)
322 Lisp_Object prop;
323 Lisp_Object pos1, pos2;
325 Lisp_Object pval1, pval2;
327 pval1 = Fget_char_property (pos1, prop, Qnil);
328 pval2 = Fget_char_property (pos2, prop, Qnil);
330 return EQ (pval1, pval2);
333 /* Return the direction from which the char-property PROP would be
334 inherited by any new text inserted at POS: 1 if it would be
335 inherited from the char after POS, -1 if it would be inherited from
336 the char before POS, and 0 if from neither. */
338 static int
339 char_property_stickiness (prop, pos)
340 Lisp_Object prop;
341 Lisp_Object pos;
343 Lisp_Object front_sticky;
345 if (XINT (pos) > BEGV)
346 /* Consider previous character. */
348 Lisp_Object prev_pos, rear_non_sticky;
350 prev_pos = make_number (XINT (pos) - 1);
351 rear_non_sticky = Fget_char_property (prev_pos, Qrear_nonsticky, Qnil);
353 if (EQ (rear_non_sticky, Qnil)
354 || (CONSP (rear_non_sticky)
355 && NILP (Fmemq (prop, rear_non_sticky))))
356 /* PROP is not rear-non-sticky, and since this takes precedence over
357 any front-stickiness, PROP is inherited from before. */
358 return -1;
361 /* Consider following character. */
362 front_sticky = Fget_char_property (pos, Qfront_sticky, Qnil);
364 if (EQ (front_sticky, Qt)
365 || (CONSP (front_sticky)
366 && !NILP (Fmemq (prop, front_sticky))))
367 /* PROP is inherited from after. */
368 return 1;
370 /* PROP is not inherited from either side. */
371 return 0;
375 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
376 the value of point is used instead. If BEG or END null,
377 means don't store the beginning or end of the field.
379 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
380 position of a field, then the beginning of the previous field is
381 returned instead of the beginning of POS's field (since the end of a
382 field is actually also the beginning of the next input field, this
383 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
384 true case, if two fields are separated by a field with the special
385 value `boundary', and POS lies within it, then the two separated
386 fields are considered to be adjacent, and POS between them, when
387 finding the beginning and ending of the "merged" field.
389 Either BEG or END may be 0, in which case the corresponding value
390 is not stored. */
392 static void
393 find_field (pos, merge_at_boundary, beg, end)
394 Lisp_Object pos;
395 Lisp_Object merge_at_boundary;
396 int *beg, *end;
398 /* Fields right before and after the point. */
399 Lisp_Object before_field, after_field;
400 /* 1 if POS counts as the start of a field. */
401 int at_field_start = 0;
402 /* 1 if POS counts as the end of a field. */
403 int at_field_end = 0;
405 if (NILP (pos))
406 XSETFASTINT (pos, PT);
407 else
408 CHECK_NUMBER_COERCE_MARKER (pos, 0);
410 after_field
411 = Fget_char_property (pos, Qfield, Qnil);
412 before_field
413 = (XFASTINT (pos) > BEGV
414 ? Fget_char_property (make_number (XINT (pos) - 1), Qfield, Qnil)
415 : Qnil);
417 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
418 and POS is at beginning of a field, which can also be interpreted
419 as the end of the previous field. Note that the case where if
420 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
421 more natural one; then we avoid treating the beginning of a field
422 specially. */
423 if (NILP (merge_at_boundary) && !EQ (after_field, before_field))
424 /* We are at a boundary, see which direction is inclusive. We
425 decide by seeing which field the `field' property sticks to. */
427 int stickiness = char_property_stickiness (Qfield, pos);
429 if (stickiness > 0)
430 at_field_start = 1;
431 else if (stickiness < 0)
432 at_field_end = 1;
433 else
434 /* STICKINESS == 0 means that any inserted text will get a
435 `field' char-property of nil, so check to see if that
436 matches either of the adjacent characters (this being a
437 kind of "stickiness by default"). */
439 if (NILP (before_field))
440 at_field_end = 1; /* Sticks to the left. */
441 else if (NILP (after_field))
442 at_field_start = 1; /* Sticks to the right. */
446 /* Note about special `boundary' fields:
448 Consider the case where the point (`.') is between the fields `x' and `y':
450 xxxx.yyyy
452 In this situation, if merge_at_boundary is true, we consider the
453 `x' and `y' fields as forming one big merged field, and so the end
454 of the field is the end of `y'.
456 However, if `x' and `y' are separated by a special `boundary' field
457 (a field with a `field' char-property of 'boundary), then we ignore
458 this special field when merging adjacent fields. Here's the same
459 situation, but with a `boundary' field between the `x' and `y' fields:
461 xxx.BBBByyyy
463 Here, if point is at the end of `x', the beginning of `y', or
464 anywhere in-between (within the `boundary' field), we merge all
465 three fields and consider the beginning as being the beginning of
466 the `x' field, and the end as being the end of the `y' field. */
468 if (beg)
470 if (at_field_start)
471 /* POS is at the edge of a field, and we should consider it as
472 the beginning of the following field. */
473 *beg = XFASTINT (pos);
474 else
475 /* Find the previous field boundary. */
477 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
478 /* Skip a `boundary' field. */
479 pos = Fprevious_single_char_property_change (pos, Qfield, Qnil,Qnil);
481 pos = Fprevious_single_char_property_change (pos, Qfield, Qnil, Qnil);
482 *beg = NILP (pos) ? BEGV : XFASTINT (pos);
486 if (end)
488 if (at_field_end)
489 /* POS is at the edge of a field, and we should consider it as
490 the end of the previous field. */
491 *end = XFASTINT (pos);
492 else
493 /* Find the next field boundary. */
495 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
496 /* Skip a `boundary' field. */
497 pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
499 pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
500 *end = NILP (pos) ? ZV : XFASTINT (pos);
506 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
507 "Delete the field surrounding POS.\n\
508 A field is a region of text with the same `field' property.\n\
509 If POS is nil, the value of point is used for POS.")
510 (pos)
511 Lisp_Object pos;
513 int beg, end;
514 find_field (pos, Qnil, &beg, &end);
515 if (beg != end)
516 del_range (beg, end);
517 return Qnil;
520 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
521 "Return the contents of the field surrounding POS as a string.\n\
522 A field is a region of text with the same `field' property.\n\
523 If POS is nil, the value of point is used for POS.")
524 (pos)
525 Lisp_Object pos;
527 int beg, end;
528 find_field (pos, Qnil, &beg, &end);
529 return make_buffer_string (beg, end, 1);
532 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
533 "Return the contents of the field around POS, without text-properties.\n\
534 A field is a region of text with the same `field' property.\n\
535 If POS is nil, the value of point is used for POS.")
536 (pos)
537 Lisp_Object pos;
539 int beg, end;
540 find_field (pos, Qnil, &beg, &end);
541 return make_buffer_string (beg, end, 0);
544 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 2, 0,
545 "Return the beginning of the field surrounding POS.\n\
546 A field is a region of text with the same `field' property.\n\
547 If POS is nil, the value of point is used for POS.\n\
548 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its\n\
549 field, then the beginning of the *previous* field is returned.")
550 (pos, escape_from_edge)
551 Lisp_Object pos, escape_from_edge;
553 int beg;
554 find_field (pos, escape_from_edge, &beg, 0);
555 return make_number (beg);
558 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 2, 0,
559 "Return the end of the field surrounding POS.\n\
560 A field is a region of text with the same `field' property.\n\
561 If POS is nil, the value of point is used for POS.\n\
562 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,\n\
563 then the end of the *following* field is returned.")
564 (pos, escape_from_edge)
565 Lisp_Object pos, escape_from_edge;
567 int end;
568 find_field (pos, escape_from_edge, 0, &end);
569 return make_number (end);
572 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
573 "Return the position closest to NEW-POS that is in the same field as OLD-POS.\n\
575 A field is a region of text with the same `field' property.\n\
576 If NEW-POS is nil, then the current point is used instead, and set to the\n\
577 constrained position if that is is different.\n\
579 If OLD-POS is at the boundary of two fields, then the allowable\n\
580 positions for NEW-POS depends on the value of the optional argument\n\
581 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is\n\
582 constrained to the field that has the same `field' char-property\n\
583 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE\n\
584 is non-nil, NEW-POS is constrained to the union of the two adjacent\n\
585 fields. Additionally, if two fields are separated by another field with\n\
586 the special value `boundary', then any point within this special field is\n\
587 also considered to be `on the boundary'.\n\
589 If the optional argument ONLY-IN-LINE is non-nil and constraining\n\
590 NEW-POS would move it to a different line, NEW-POS is returned\n\
591 unconstrained. This useful for commands that move by line, like\n\
592 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries\n\
593 only in the case where they can still move to the right line.\n\
595 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has\n\
596 a non-nil property of that name, then any field boundaries are ignored.\n\
598 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil.")
599 (new_pos, old_pos, escape_from_edge, only_in_line, inhibit_capture_property)
600 Lisp_Object new_pos, old_pos;
601 Lisp_Object escape_from_edge, only_in_line, inhibit_capture_property;
603 /* If non-zero, then the original point, before re-positioning. */
604 int orig_point = 0;
606 if (NILP (new_pos))
607 /* Use the current point, and afterwards, set it. */
609 orig_point = PT;
610 XSETFASTINT (new_pos, PT);
613 if (NILP (Vinhibit_field_text_motion)
614 && !EQ (new_pos, old_pos)
615 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
616 || !NILP (Fget_char_property (old_pos, Qfield, Qnil)))
617 && (NILP (inhibit_capture_property)
618 || NILP (Fget_char_property(old_pos, inhibit_capture_property, Qnil))))
619 /* NEW_POS is not within the same field as OLD_POS; try to
620 move NEW_POS so that it is. */
622 int fwd, shortage;
623 Lisp_Object field_bound;
625 CHECK_NUMBER_COERCE_MARKER (new_pos, 0);
626 CHECK_NUMBER_COERCE_MARKER (old_pos, 0);
628 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
630 if (fwd)
631 field_bound = Ffield_end (old_pos, escape_from_edge);
632 else
633 field_bound = Ffield_beginning (old_pos, escape_from_edge);
635 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
636 other side of NEW_POS, which would mean that NEW_POS is
637 already acceptable, and it's not necessary to constrain it
638 to FIELD_BOUND. */
639 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
640 /* NEW_POS should be constrained, but only if either
641 ONLY_IN_LINE is nil (in which case any constraint is OK),
642 or NEW_POS and FIELD_BOUND are on the same line (in which
643 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
644 && (NILP (only_in_line)
645 /* This is the ONLY_IN_LINE case, check that NEW_POS and
646 FIELD_BOUND are on the same line by seeing whether
647 there's an intervening newline or not. */
648 || (scan_buffer ('\n',
649 XFASTINT (new_pos), XFASTINT (field_bound),
650 fwd ? -1 : 1, &shortage, 1),
651 shortage != 0)))
652 /* Constrain NEW_POS to FIELD_BOUND. */
653 new_pos = field_bound;
655 if (orig_point && XFASTINT (new_pos) != orig_point)
656 /* The NEW_POS argument was originally nil, so automatically set PT. */
657 SET_PT (XFASTINT (new_pos));
660 return new_pos;
664 DEFUN ("line-beginning-position", Fline_beginning_position, Sline_beginning_position,
665 0, 1, 0,
666 "Return the character position of the first character on the current line.\n\
667 With argument N not nil or 1, move forward N - 1 lines first.\n\
668 If scan reaches end of buffer, return that position.\n\
669 The scan does not cross a field boundary unless it would move\n\
670 beyond there to a different line. Field boundaries are not noticed if\n\
671 `inhibit-field-text-motion' is non-nil. .And if N is nil or 1,\n\
672 and scan starts at a field boundary, the scan stops as soon as it starts.\n\
674 This function does not move point.")
676 Lisp_Object n;
678 int orig, orig_byte, end;
680 if (NILP (n))
681 XSETFASTINT (n, 1);
682 else
683 CHECK_NUMBER (n, 0);
685 orig = PT;
686 orig_byte = PT_BYTE;
687 Fforward_line (make_number (XINT (n) - 1));
688 end = PT;
690 SET_PT_BOTH (orig, orig_byte);
692 /* Return END constrained to the current input field. */
693 return Fconstrain_to_field (make_number (end), make_number (orig),
694 XINT (n) != 1 ? Qt : Qnil,
695 Qt, Qnil);
698 DEFUN ("line-end-position", Fline_end_position, Sline_end_position,
699 0, 1, 0,
700 "Return the character position of the last character on the current line.\n\
701 With argument N not nil or 1, move forward N - 1 lines first.\n\
702 If scan reaches end of buffer, return that position.\n\
703 This function does not move point.")
705 Lisp_Object n;
707 int end_pos;
708 int orig = PT;
710 if (NILP (n))
711 XSETFASTINT (n, 1);
712 else
713 CHECK_NUMBER (n, 0);
715 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
717 /* Return END_POS constrained to the current input field. */
718 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
719 Qnil, Qt, Qnil);
722 Lisp_Object
723 save_excursion_save ()
725 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
726 == current_buffer);
728 return Fcons (Fpoint_marker (),
729 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
730 Fcons (visible ? Qt : Qnil,
731 Fcons (current_buffer->mark_active,
732 selected_window))));
735 Lisp_Object
736 save_excursion_restore (info)
737 Lisp_Object info;
739 Lisp_Object tem, tem1, omark, nmark;
740 struct gcpro gcpro1, gcpro2, gcpro3;
741 int visible_p;
743 tem = Fmarker_buffer (XCAR (info));
744 /* If buffer being returned to is now deleted, avoid error */
745 /* Otherwise could get error here while unwinding to top level
746 and crash */
747 /* In that case, Fmarker_buffer returns nil now. */
748 if (NILP (tem))
749 return Qnil;
751 omark = nmark = Qnil;
752 GCPRO3 (info, omark, nmark);
754 Fset_buffer (tem);
756 /* Point marker. */
757 tem = XCAR (info);
758 Fgoto_char (tem);
759 unchain_marker (tem);
761 /* Mark marker. */
762 info = XCDR (info);
763 tem = XCAR (info);
764 omark = Fmarker_position (current_buffer->mark);
765 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
766 nmark = Fmarker_position (tem);
767 unchain_marker (tem);
769 /* visible */
770 info = XCDR (info);
771 visible_p = !NILP (XCAR (info));
773 #if 0 /* We used to make the current buffer visible in the selected window
774 if that was true previously. That avoids some anomalies.
775 But it creates others, and it wasn't documented, and it is simpler
776 and cleaner never to alter the window/buffer connections. */
777 tem1 = Fcar (tem);
778 if (!NILP (tem1)
779 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
780 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
781 #endif /* 0 */
783 /* Mark active */
784 info = XCDR (info);
785 tem = XCAR (info);
786 tem1 = current_buffer->mark_active;
787 current_buffer->mark_active = tem;
789 if (!NILP (Vrun_hooks))
791 /* If mark is active now, and either was not active
792 or was at a different place, run the activate hook. */
793 if (! NILP (current_buffer->mark_active))
795 if (! EQ (omark, nmark))
796 call1 (Vrun_hooks, intern ("activate-mark-hook"));
798 /* If mark has ceased to be active, run deactivate hook. */
799 else if (! NILP (tem1))
800 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
803 /* If buffer was visible in a window, and a different window was
804 selected, and the old selected window is still live, restore
805 point in that window. */
806 tem = XCDR (info);
807 if (visible_p
808 && !EQ (tem, selected_window)
809 && !NILP (Fwindow_live_p (tem)))
810 Fset_window_point (tem, make_number (PT));
812 UNGCPRO;
813 return Qnil;
816 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
817 "Save point, mark, and current buffer; execute BODY; restore those things.\n\
818 Executes BODY just like `progn'.\n\
819 The values of point, mark and the current buffer are restored\n\
820 even in case of abnormal exit (throw or error).\n\
821 The state of activation of the mark is also restored.\n\
823 This construct does not save `deactivate-mark', and therefore\n\
824 functions that change the buffer will still cause deactivation\n\
825 of the mark at the end of the command. To prevent that, bind\n\
826 `deactivate-mark' with `let'.")
827 (args)
828 Lisp_Object args;
830 register Lisp_Object val;
831 int count = specpdl_ptr - specpdl;
833 record_unwind_protect (save_excursion_restore, save_excursion_save ());
835 val = Fprogn (args);
836 return unbind_to (count, val);
839 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
840 "Save the current buffer; execute BODY; restore the current buffer.\n\
841 Executes BODY just like `progn'.")
842 (args)
843 Lisp_Object args;
845 Lisp_Object val;
846 int count = specpdl_ptr - specpdl;
848 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
850 val = Fprogn (args);
851 return unbind_to (count, val);
854 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
855 "Return the number of characters in the current buffer.\n\
856 If BUFFER, return the number of characters in that buffer instead.")
857 (buffer)
858 Lisp_Object buffer;
860 if (NILP (buffer))
861 return make_number (Z - BEG);
862 else
864 CHECK_BUFFER (buffer, 1);
865 return make_number (BUF_Z (XBUFFER (buffer))
866 - BUF_BEG (XBUFFER (buffer)));
870 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
871 "Return the minimum permissible value of point in the current buffer.\n\
872 This is 1, unless narrowing (a buffer restriction) is in effect.")
875 Lisp_Object temp;
876 XSETFASTINT (temp, BEGV);
877 return temp;
880 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
881 "Return a marker to the minimum permissible value of point in this buffer.\n\
882 This is the beginning, unless narrowing (a buffer restriction) is in effect.")
885 return buildmark (BEGV, BEGV_BYTE);
888 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
889 "Return the maximum permissible value of point in the current buffer.\n\
890 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
891 is in effect, in which case it is less.")
894 Lisp_Object temp;
895 XSETFASTINT (temp, ZV);
896 return temp;
899 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
900 "Return a marker to the maximum permissible value of point in this buffer.\n\
901 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
902 is in effect, in which case it is less.")
905 return buildmark (ZV, ZV_BYTE);
908 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
909 "Return the position of the gap, in the current buffer.\n\
910 See also `gap-size'.")
913 Lisp_Object temp;
914 XSETFASTINT (temp, GPT);
915 return temp;
918 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
919 "Return the size of the current buffer's gap.\n\
920 See also `gap-position'.")
923 Lisp_Object temp;
924 XSETFASTINT (temp, GAP_SIZE);
925 return temp;
928 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
929 "Return the byte position for character position POSITION.\n\
930 If POSITION is out of range, the value is nil.")
931 (position)
932 Lisp_Object position;
934 CHECK_NUMBER_COERCE_MARKER (position, 1);
935 if (XINT (position) < BEG || XINT (position) > Z)
936 return Qnil;
937 return make_number (CHAR_TO_BYTE (XINT (position)));
940 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
941 "Return the character position for byte position BYTEPOS.\n\
942 If BYTEPOS is out of range, the value is nil.")
943 (bytepos)
944 Lisp_Object bytepos;
946 CHECK_NUMBER (bytepos, 1);
947 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
948 return Qnil;
949 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
952 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
953 "Return the character following point, as a number.\n\
954 At the end of the buffer or accessible region, return 0.")
957 Lisp_Object temp;
958 if (PT >= ZV)
959 XSETFASTINT (temp, 0);
960 else
961 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
962 return temp;
965 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
966 "Return the character preceding point, as a number.\n\
967 At the beginning of the buffer or accessible region, return 0.")
970 Lisp_Object temp;
971 if (PT <= BEGV)
972 XSETFASTINT (temp, 0);
973 else if (!NILP (current_buffer->enable_multibyte_characters))
975 int pos = PT_BYTE;
976 DEC_POS (pos);
977 XSETFASTINT (temp, FETCH_CHAR (pos));
979 else
980 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
981 return temp;
984 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
985 "Return t if point is at the beginning of the buffer.\n\
986 If the buffer is narrowed, this means the beginning of the narrowed part.")
989 if (PT == BEGV)
990 return Qt;
991 return Qnil;
994 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
995 "Return t if point is at the end of the buffer.\n\
996 If the buffer is narrowed, this means the end of the narrowed part.")
999 if (PT == ZV)
1000 return Qt;
1001 return Qnil;
1004 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1005 "Return t if point is at the beginning of a line.")
1008 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1009 return Qt;
1010 return Qnil;
1013 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1014 "Return t if point is at the end of a line.\n\
1015 `End of a line' includes point being at the end of the buffer.")
1018 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1019 return Qt;
1020 return Qnil;
1023 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1024 "Return character in current buffer at position POS.\n\
1025 POS is an integer or a marker.\n\
1026 If POS is out of range, the value is nil.")
1027 (pos)
1028 Lisp_Object pos;
1030 register int pos_byte;
1032 if (NILP (pos))
1034 pos_byte = PT_BYTE;
1035 XSETFASTINT (pos, PT);
1038 if (MARKERP (pos))
1040 pos_byte = marker_byte_position (pos);
1041 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1042 return Qnil;
1044 else
1046 CHECK_NUMBER_COERCE_MARKER (pos, 0);
1047 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1048 return Qnil;
1050 pos_byte = CHAR_TO_BYTE (XINT (pos));
1053 return make_number (FETCH_CHAR (pos_byte));
1056 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1057 "Return character in current buffer preceding position POS.\n\
1058 POS is an integer or a marker.\n\
1059 If POS is out of range, the value is nil.")
1060 (pos)
1061 Lisp_Object pos;
1063 register Lisp_Object val;
1064 register int pos_byte;
1066 if (NILP (pos))
1068 pos_byte = PT_BYTE;
1069 XSETFASTINT (pos, PT);
1072 if (MARKERP (pos))
1074 pos_byte = marker_byte_position (pos);
1076 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1077 return Qnil;
1079 else
1081 CHECK_NUMBER_COERCE_MARKER (pos, 0);
1083 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1084 return Qnil;
1086 pos_byte = CHAR_TO_BYTE (XINT (pos));
1089 if (!NILP (current_buffer->enable_multibyte_characters))
1091 DEC_POS (pos_byte);
1092 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1094 else
1096 pos_byte--;
1097 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1099 return val;
1102 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1103 "Return the name under which the user logged in, as a string.\n\
1104 This is based on the effective uid, not the real uid.\n\
1105 Also, if the environment variable LOGNAME or USER is set,\n\
1106 that determines the value of this function.\n\n\
1107 If optional argument UID is an integer, return the login name of the user\n\
1108 with that uid, or nil if there is no such user.")
1109 (uid)
1110 Lisp_Object uid;
1112 struct passwd *pw;
1114 /* Set up the user name info if we didn't do it before.
1115 (That can happen if Emacs is dumpable
1116 but you decide to run `temacs -l loadup' and not dump. */
1117 if (INTEGERP (Vuser_login_name))
1118 init_editfns ();
1120 if (NILP (uid))
1121 return Vuser_login_name;
1123 CHECK_NUMBER (uid, 0);
1124 pw = (struct passwd *) getpwuid (XINT (uid));
1125 return (pw ? build_string (pw->pw_name) : Qnil);
1128 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1129 0, 0, 0,
1130 "Return the name of the user's real uid, as a string.\n\
1131 This ignores the environment variables LOGNAME and USER, so it differs from\n\
1132 `user-login-name' when running under `su'.")
1135 /* Set up the user name info if we didn't do it before.
1136 (That can happen if Emacs is dumpable
1137 but you decide to run `temacs -l loadup' and not dump. */
1138 if (INTEGERP (Vuser_login_name))
1139 init_editfns ();
1140 return Vuser_real_login_name;
1143 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1144 "Return the effective uid of Emacs, as an integer.")
1147 return make_number (geteuid ());
1150 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1151 "Return the real uid of Emacs, as an integer.")
1154 return make_number (getuid ());
1157 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1158 "Return the full name of the user logged in, as a string.\n\
1159 If the full name corresponding to Emacs's userid is not known,\n\
1160 return \"unknown\".\n\
1162 If optional argument UID is an integer, return the full name of the user\n\
1163 with that uid, or nil if there is no such user.\n\
1164 If UID is a string, return the full name of the user with that login\n\
1165 name, or nil if there is no such user.")
1166 (uid)
1167 Lisp_Object uid;
1169 struct passwd *pw;
1170 register unsigned char *p, *q;
1171 Lisp_Object full;
1173 if (NILP (uid))
1174 return Vuser_full_name;
1175 else if (NUMBERP (uid))
1176 pw = (struct passwd *) getpwuid (XINT (uid));
1177 else if (STRINGP (uid))
1178 pw = (struct passwd *) getpwnam (XSTRING (uid)->data);
1179 else
1180 error ("Invalid UID specification");
1182 if (!pw)
1183 return Qnil;
1185 p = (unsigned char *) USER_FULL_NAME;
1186 /* Chop off everything after the first comma. */
1187 q = (unsigned char *) index (p, ',');
1188 full = make_string (p, q ? q - p : strlen (p));
1190 #ifdef AMPERSAND_FULL_NAME
1191 p = XSTRING (full)->data;
1192 q = (unsigned char *) index (p, '&');
1193 /* Substitute the login name for the &, upcasing the first character. */
1194 if (q)
1196 register unsigned char *r;
1197 Lisp_Object login;
1199 login = Fuser_login_name (make_number (pw->pw_uid));
1200 r = (unsigned char *) alloca (strlen (p) + XSTRING (login)->size + 1);
1201 bcopy (p, r, q - p);
1202 r[q - p] = 0;
1203 strcat (r, XSTRING (login)->data);
1204 r[q - p] = UPCASE (r[q - p]);
1205 strcat (r, q + 1);
1206 full = build_string (r);
1208 #endif /* AMPERSAND_FULL_NAME */
1210 return full;
1213 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1214 "Return the name of the machine you are running on, as a string.")
1217 return Vsystem_name;
1220 /* For the benefit of callers who don't want to include lisp.h */
1222 char *
1223 get_system_name ()
1225 if (STRINGP (Vsystem_name))
1226 return (char *) XSTRING (Vsystem_name)->data;
1227 else
1228 return "";
1231 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1232 "Return the process ID of Emacs, as an integer.")
1235 return make_number (getpid ());
1238 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1239 "Return the current time, as the number of seconds since 1970-01-01 00:00:00.\n\
1240 The time is returned as a list of three integers. The first has the\n\
1241 most significant 16 bits of the seconds, while the second has the\n\
1242 least significant 16 bits. The third integer gives the microsecond\n\
1243 count.\n\
1245 The microsecond count is zero on systems that do not provide\n\
1246 resolution finer than a second.")
1249 EMACS_TIME t;
1250 Lisp_Object result[3];
1252 EMACS_GET_TIME (t);
1253 XSETINT (result[0], (EMACS_SECS (t) >> 16) & 0xffff);
1254 XSETINT (result[1], (EMACS_SECS (t) >> 0) & 0xffff);
1255 XSETINT (result[2], EMACS_USECS (t));
1257 return Flist (3, result);
1261 static int
1262 lisp_time_argument (specified_time, result, usec)
1263 Lisp_Object specified_time;
1264 time_t *result;
1265 int *usec;
1267 if (NILP (specified_time))
1269 if (usec)
1271 EMACS_TIME t;
1273 EMACS_GET_TIME (t);
1274 *usec = EMACS_USECS (t);
1275 *result = EMACS_SECS (t);
1276 return 1;
1278 else
1279 return time (result) != -1;
1281 else
1283 Lisp_Object high, low;
1284 high = Fcar (specified_time);
1285 CHECK_NUMBER (high, 0);
1286 low = Fcdr (specified_time);
1287 if (CONSP (low))
1289 if (usec)
1291 Lisp_Object usec_l = Fcdr (low);
1292 if (CONSP (usec_l))
1293 usec_l = Fcar (usec_l);
1294 if (NILP (usec_l))
1295 *usec = 0;
1296 else
1298 CHECK_NUMBER (usec_l, 0);
1299 *usec = XINT (usec_l);
1302 low = Fcar (low);
1304 else if (usec)
1305 *usec = 0;
1306 CHECK_NUMBER (low, 0);
1307 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1308 return *result >> 16 == XINT (high);
1312 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1313 "Return the current time, as a float number of seconds since the epoch.\n\
1314 If an argument is given, it specifies a time to convert to float\n\
1315 instead of the current time. The argument should have the forms:\n\
1316 (HIGH . LOW) or (HIGH LOW USEC) or (HIGH LOW . USEC).\n\
1317 Thus, you can use times obtained from `current-time'\n\
1318 and from `file-attributes'.")
1319 (specified_time)
1320 Lisp_Object specified_time;
1322 time_t sec;
1323 int usec;
1325 if (! lisp_time_argument (specified_time, &sec, &usec))
1326 error ("Invalid time specification");
1328 return make_float (sec + usec * 0.0000001);
1331 /* Write information into buffer S of size MAXSIZE, according to the
1332 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1333 Default to Universal Time if UT is nonzero, local time otherwise.
1334 Return the number of bytes written, not including the terminating
1335 '\0'. If S is NULL, nothing will be written anywhere; so to
1336 determine how many bytes would be written, use NULL for S and
1337 ((size_t) -1) for MAXSIZE.
1339 This function behaves like emacs_strftimeu, except it allows null
1340 bytes in FORMAT. */
1341 static size_t
1342 emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
1343 char *s;
1344 size_t maxsize;
1345 const char *format;
1346 size_t format_len;
1347 const struct tm *tp;
1348 int ut;
1350 size_t total = 0;
1352 /* Loop through all the null-terminated strings in the format
1353 argument. Normally there's just one null-terminated string, but
1354 there can be arbitrarily many, concatenated together, if the
1355 format contains '\0' bytes. emacs_strftimeu stops at the first
1356 '\0' byte so we must invoke it separately for each such string. */
1357 for (;;)
1359 size_t len;
1360 size_t result;
1362 if (s)
1363 s[0] = '\1';
1365 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1367 if (s)
1369 if (result == 0 && s[0] != '\0')
1370 return 0;
1371 s += result + 1;
1374 maxsize -= result + 1;
1375 total += result;
1376 len = strlen (format);
1377 if (len == format_len)
1378 return total;
1379 total++;
1380 format += len + 1;
1381 format_len -= len + 1;
1386 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1387 "Use FORMAT-STRING to format the time TIME, or now if omitted.\n\
1388 TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as returned by\n\
1389 `current-time' or `file-attributes'.\n\
1390 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME\n\
1391 as Universal Time; nil means describe TIME in the local time zone.\n\
1392 The value is a copy of FORMAT-STRING, but with certain constructs replaced\n\
1393 by text that describes the specified date and time in TIME:\n\
1395 %Y is the year, %y within the century, %C the century.\n\
1396 %G is the year corresponding to the ISO week, %g within the century.\n\
1397 %m is the numeric month.\n\
1398 %b and %h are the locale's abbreviated month name, %B the full name.\n\
1399 %d is the day of the month, zero-padded, %e is blank-padded.\n\
1400 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.\n\
1401 %a is the locale's abbreviated name of the day of week, %A the full name.\n\
1402 %U is the week number starting on Sunday, %W starting on Monday,\n\
1403 %V according to ISO 8601.\n\
1404 %j is the day of the year.\n\
1406 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H\n\
1407 only blank-padded, %l is like %I blank-padded.\n\
1408 %p is the locale's equivalent of either AM or PM.\n\
1409 %M is the minute.\n\
1410 %S is the second.\n\
1411 %Z is the time zone name, %z is the numeric form.\n\
1412 %s is the number of seconds since 1970-01-01 00:00:00 +0000.\n\
1414 %c is the locale's date and time format.\n\
1415 %x is the locale's \"preferred\" date format.\n\
1416 %D is like \"%m/%d/%y\".\n\
1418 %R is like \"%H:%M\", %T is like \"%H:%M:%S\", %r is like \"%I:%M:%S %p\".\n\
1419 %X is the locale's \"preferred\" time format.\n\
1421 Finally, %n is a newline, %t is a tab, %% is a literal %.\n\
1423 Certain flags and modifiers are available with some format controls.\n\
1424 The flags are `_' and `-'. For certain characters X, %_X is like %X,\n\
1425 but padded with blanks; %-X is like %X, but without padding.\n\
1426 %NX (where N stands for an integer) is like %X,\n\
1427 but takes up at least N (a number) positions.\n\
1428 The modifiers are `E' and `O'. For certain characters X,\n\
1429 %EX is a locale's alternative version of %X;\n\
1430 %OX is like %X, but uses the locale's number symbols.\n\
1432 For example, to produce full ISO 8601 format, use \"%Y-%m-%dT%T%z\".")
1433 (format_string, time, universal)
1436 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1437 0 /* See immediately above */)
1438 (format_string, time, universal)
1439 Lisp_Object format_string, time, universal;
1441 time_t value;
1442 int size;
1443 struct tm *tm;
1444 int ut = ! NILP (universal);
1446 CHECK_STRING (format_string, 1);
1448 if (! lisp_time_argument (time, &value, NULL))
1449 error ("Invalid time specification");
1451 format_string = code_convert_string_norecord (format_string,
1452 Vlocale_coding_system, 1);
1454 /* This is probably enough. */
1455 size = STRING_BYTES (XSTRING (format_string)) * 6 + 50;
1457 tm = ut ? gmtime (&value) : localtime (&value);
1458 if (! tm)
1459 error ("Specified time is not representable");
1461 synchronize_system_time_locale ();
1463 while (1)
1465 char *buf = (char *) alloca (size + 1);
1466 int result;
1468 buf[0] = '\1';
1469 result = emacs_memftimeu (buf, size, XSTRING (format_string)->data,
1470 STRING_BYTES (XSTRING (format_string)),
1471 tm, ut);
1472 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1473 return code_convert_string_norecord (make_string (buf, result),
1474 Vlocale_coding_system, 0);
1476 /* If buffer was too small, make it bigger and try again. */
1477 result = emacs_memftimeu (NULL, (size_t) -1,
1478 XSTRING (format_string)->data,
1479 STRING_BYTES (XSTRING (format_string)),
1480 tm, ut);
1481 size = result + 1;
1485 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1486 "Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).\n\
1487 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED)\n\
1488 or (HIGH . LOW), as from `current-time' and `file-attributes', or `nil'\n\
1489 to use the current time. The list has the following nine members:\n\
1490 SEC is an integer between 0 and 60; SEC is 60 for a leap second, which\n\
1491 only some operating systems support. MINUTE is an integer between 0 and 59.\n\
1492 HOUR is an integer between 0 and 23. DAY is an integer between 1 and 31.\n\
1493 MONTH is an integer between 1 and 12. YEAR is an integer indicating the\n\
1494 four-digit year. DOW is the day of week, an integer between 0 and 6, where\n\
1495 0 is Sunday. DST is t if daylight savings time is effect, otherwise nil.\n\
1496 ZONE is an integer indicating the number of seconds east of Greenwich.\n\
1497 \(Note that Common Lisp has different meanings for DOW and ZONE.)")
1498 (specified_time)
1499 Lisp_Object specified_time;
1501 time_t time_spec;
1502 struct tm save_tm;
1503 struct tm *decoded_time;
1504 Lisp_Object list_args[9];
1506 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1507 error ("Invalid time specification");
1509 decoded_time = localtime (&time_spec);
1510 if (! decoded_time)
1511 error ("Specified time is not representable");
1512 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1513 XSETFASTINT (list_args[1], decoded_time->tm_min);
1514 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1515 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1516 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1517 XSETINT (list_args[5], decoded_time->tm_year + 1900);
1518 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1519 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1521 /* Make a copy, in case gmtime modifies the struct. */
1522 save_tm = *decoded_time;
1523 decoded_time = gmtime (&time_spec);
1524 if (decoded_time == 0)
1525 list_args[8] = Qnil;
1526 else
1527 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1528 return Flist (9, list_args);
1531 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1532 "Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.\n\
1533 This is the reverse operation of `decode-time', which see.\n\
1534 ZONE defaults to the current time zone rule. This can\n\
1535 be a string or t (as from `set-time-zone-rule'), or it can be a list\n\
1536 \(as from `current-time-zone') or an integer (as from `decode-time')\n\
1537 applied without consideration for daylight savings time.\n\
1539 You can pass more than 7 arguments; then the first six arguments\n\
1540 are used as SECOND through YEAR, and the *last* argument is used as ZONE.\n\
1541 The intervening arguments are ignored.\n\
1542 This feature lets (apply 'encode-time (decode-time ...)) work.\n\
1544 Out-of-range values for SEC, MINUTE, HOUR, DAY, or MONTH are allowed;\n\
1545 for example, a DAY of 0 means the day preceding the given month.\n\
1546 Year numbers less than 100 are treated just like other year numbers.\n\
1547 If you want them to stand for years in this century, you must do that yourself.")
1548 (nargs, args)
1549 int nargs;
1550 register Lisp_Object *args;
1552 time_t time;
1553 struct tm tm;
1554 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1556 CHECK_NUMBER (args[0], 0); /* second */
1557 CHECK_NUMBER (args[1], 1); /* minute */
1558 CHECK_NUMBER (args[2], 2); /* hour */
1559 CHECK_NUMBER (args[3], 3); /* day */
1560 CHECK_NUMBER (args[4], 4); /* month */
1561 CHECK_NUMBER (args[5], 5); /* year */
1563 tm.tm_sec = XINT (args[0]);
1564 tm.tm_min = XINT (args[1]);
1565 tm.tm_hour = XINT (args[2]);
1566 tm.tm_mday = XINT (args[3]);
1567 tm.tm_mon = XINT (args[4]) - 1;
1568 tm.tm_year = XINT (args[5]) - 1900;
1569 tm.tm_isdst = -1;
1571 if (CONSP (zone))
1572 zone = Fcar (zone);
1573 if (NILP (zone))
1574 time = mktime (&tm);
1575 else
1577 char tzbuf[100];
1578 char *tzstring;
1579 char **oldenv = environ, **newenv;
1581 if (EQ (zone, Qt))
1582 tzstring = "UTC0";
1583 else if (STRINGP (zone))
1584 tzstring = (char *) XSTRING (zone)->data;
1585 else if (INTEGERP (zone))
1587 int abszone = abs (XINT (zone));
1588 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1589 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1590 tzstring = tzbuf;
1592 else
1593 error ("Invalid time zone specification");
1595 /* Set TZ before calling mktime; merely adjusting mktime's returned
1596 value doesn't suffice, since that would mishandle leap seconds. */
1597 set_time_zone_rule (tzstring);
1599 time = mktime (&tm);
1601 /* Restore TZ to previous value. */
1602 newenv = environ;
1603 environ = oldenv;
1604 xfree (newenv);
1605 #ifdef LOCALTIME_CACHE
1606 tzset ();
1607 #endif
1610 if (time == (time_t) -1)
1611 error ("Specified time is not representable");
1613 return make_time (time);
1616 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1617 "Return the current time, as a human-readable string.\n\
1618 Programs can use this function to decode a time,\n\
1619 since the number of columns in each field is fixed.\n\
1620 The format is `Sun Sep 16 01:03:52 1973'.\n\
1621 However, see also the functions `decode-time' and `format-time-string'\n\
1622 which provide a much more powerful and general facility.\n\
1624 If an argument is given, it specifies a time to format\n\
1625 instead of the current time. The argument should have the form:\n\
1626 (HIGH . LOW)\n\
1627 or the form:\n\
1628 (HIGH LOW . IGNORED).\n\
1629 Thus, you can use times obtained from `current-time'\n\
1630 and from `file-attributes'.")
1631 (specified_time)
1632 Lisp_Object specified_time;
1634 time_t value;
1635 char buf[30];
1636 register char *tem;
1638 if (! lisp_time_argument (specified_time, &value, NULL))
1639 value = -1;
1640 tem = (char *) ctime (&value);
1642 strncpy (buf, tem, 24);
1643 buf[24] = 0;
1645 return build_string (buf);
1648 #define TM_YEAR_BASE 1900
1650 /* Yield A - B, measured in seconds.
1651 This function is copied from the GNU C Library. */
1652 static int
1653 tm_diff (a, b)
1654 struct tm *a, *b;
1656 /* Compute intervening leap days correctly even if year is negative.
1657 Take care to avoid int overflow in leap day calculations,
1658 but it's OK to assume that A and B are close to each other. */
1659 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1660 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1661 int a100 = a4 / 25 - (a4 % 25 < 0);
1662 int b100 = b4 / 25 - (b4 % 25 < 0);
1663 int a400 = a100 >> 2;
1664 int b400 = b100 >> 2;
1665 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1666 int years = a->tm_year - b->tm_year;
1667 int days = (365 * years + intervening_leap_days
1668 + (a->tm_yday - b->tm_yday));
1669 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1670 + (a->tm_min - b->tm_min))
1671 + (a->tm_sec - b->tm_sec));
1674 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1675 "Return the offset and name for the local time zone.\n\
1676 This returns a list of the form (OFFSET NAME).\n\
1677 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).\n\
1678 A negative value means west of Greenwich.\n\
1679 NAME is a string giving the name of the time zone.\n\
1680 If an argument is given, it specifies when the time zone offset is determined\n\
1681 instead of using the current time. The argument should have the form:\n\
1682 (HIGH . LOW)\n\
1683 or the form:\n\
1684 (HIGH LOW . IGNORED).\n\
1685 Thus, you can use times obtained from `current-time'\n\
1686 and from `file-attributes'.\n\
1688 Some operating systems cannot provide all this information to Emacs;\n\
1689 in this case, `current-time-zone' returns a list containing nil for\n\
1690 the data it can't find.")
1691 (specified_time)
1692 Lisp_Object specified_time;
1694 time_t value;
1695 struct tm *t;
1696 struct tm gmt;
1698 if (lisp_time_argument (specified_time, &value, NULL)
1699 && (t = gmtime (&value)) != 0
1700 && (gmt = *t, t = localtime (&value)) != 0)
1702 int offset = tm_diff (t, &gmt);
1703 char *s = 0;
1704 char buf[6];
1705 #ifdef HAVE_TM_ZONE
1706 if (t->tm_zone)
1707 s = (char *)t->tm_zone;
1708 #else /* not HAVE_TM_ZONE */
1709 #ifdef HAVE_TZNAME
1710 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1711 s = tzname[t->tm_isdst];
1712 #endif
1713 #endif /* not HAVE_TM_ZONE */
1714 if (!s)
1716 /* No local time zone name is available; use "+-NNNN" instead. */
1717 int am = (offset < 0 ? -offset : offset) / 60;
1718 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1719 s = buf;
1721 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
1723 else
1724 return Fmake_list (make_number (2), Qnil);
1727 /* This holds the value of `environ' produced by the previous
1728 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
1729 has never been called. */
1730 static char **environbuf;
1732 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
1733 "Set the local time zone using TZ, a string specifying a time zone rule.\n\
1734 If TZ is nil, use implementation-defined default time zone information.\n\
1735 If TZ is t, use Universal Time.")
1736 (tz)
1737 Lisp_Object tz;
1739 char *tzstring;
1741 if (NILP (tz))
1742 tzstring = 0;
1743 else if (EQ (tz, Qt))
1744 tzstring = "UTC0";
1745 else
1747 CHECK_STRING (tz, 0);
1748 tzstring = (char *) XSTRING (tz)->data;
1751 set_time_zone_rule (tzstring);
1752 if (environbuf)
1753 free (environbuf);
1754 environbuf = environ;
1756 return Qnil;
1759 #ifdef LOCALTIME_CACHE
1761 /* These two values are known to load tz files in buggy implementations,
1762 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1763 Their values shouldn't matter in non-buggy implementations.
1764 We don't use string literals for these strings,
1765 since if a string in the environment is in readonly
1766 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
1767 See Sun bugs 1113095 and 1114114, ``Timezone routines
1768 improperly modify environment''. */
1770 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
1771 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
1773 #endif
1775 /* Set the local time zone rule to TZSTRING.
1776 This allocates memory into `environ', which it is the caller's
1777 responsibility to free. */
1779 void
1780 set_time_zone_rule (tzstring)
1781 char *tzstring;
1783 int envptrs;
1784 char **from, **to, **newenv;
1786 /* Make the ENVIRON vector longer with room for TZSTRING. */
1787 for (from = environ; *from; from++)
1788 continue;
1789 envptrs = from - environ + 2;
1790 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
1791 + (tzstring ? strlen (tzstring) + 4 : 0));
1793 /* Add TZSTRING to the end of environ, as a value for TZ. */
1794 if (tzstring)
1796 char *t = (char *) (to + envptrs);
1797 strcpy (t, "TZ=");
1798 strcat (t, tzstring);
1799 *to++ = t;
1802 /* Copy the old environ vector elements into NEWENV,
1803 but don't copy the TZ variable.
1804 So we have only one definition of TZ, which came from TZSTRING. */
1805 for (from = environ; *from; from++)
1806 if (strncmp (*from, "TZ=", 3) != 0)
1807 *to++ = *from;
1808 *to = 0;
1810 environ = newenv;
1812 /* If we do have a TZSTRING, NEWENV points to the vector slot where
1813 the TZ variable is stored. If we do not have a TZSTRING,
1814 TO points to the vector slot which has the terminating null. */
1816 #ifdef LOCALTIME_CACHE
1818 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
1819 "US/Pacific" that loads a tz file, then changes to a value like
1820 "XXX0" that does not load a tz file, and then changes back to
1821 its original value, the last change is (incorrectly) ignored.
1822 Also, if TZ changes twice in succession to values that do
1823 not load a tz file, tzset can dump core (see Sun bug#1225179).
1824 The following code works around these bugs. */
1826 if (tzstring)
1828 /* Temporarily set TZ to a value that loads a tz file
1829 and that differs from tzstring. */
1830 char *tz = *newenv;
1831 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
1832 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
1833 tzset ();
1834 *newenv = tz;
1836 else
1838 /* The implied tzstring is unknown, so temporarily set TZ to
1839 two different values that each load a tz file. */
1840 *to = set_time_zone_rule_tz1;
1841 to[1] = 0;
1842 tzset ();
1843 *to = set_time_zone_rule_tz2;
1844 tzset ();
1845 *to = 0;
1848 /* Now TZ has the desired value, and tzset can be invoked safely. */
1851 tzset ();
1852 #endif
1855 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
1856 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
1857 type of object is Lisp_String). INHERIT is passed to
1858 INSERT_FROM_STRING_FUNC as the last argument. */
1860 static void
1861 general_insert_function (insert_func, insert_from_string_func,
1862 inherit, nargs, args)
1863 void (*insert_func) P_ ((unsigned char *, int));
1864 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
1865 int inherit, nargs;
1866 register Lisp_Object *args;
1868 register int argnum;
1869 register Lisp_Object val;
1871 for (argnum = 0; argnum < nargs; argnum++)
1873 val = args[argnum];
1874 retry:
1875 if (INTEGERP (val))
1877 unsigned char str[MAX_MULTIBYTE_LENGTH];
1878 int len;
1880 if (!NILP (current_buffer->enable_multibyte_characters))
1881 len = CHAR_STRING (XFASTINT (val), str);
1882 else
1884 str[0] = (SINGLE_BYTE_CHAR_P (XINT (val))
1885 ? XINT (val)
1886 : multibyte_char_to_unibyte (XINT (val), Qnil));
1887 len = 1;
1889 (*insert_func) (str, len);
1891 else if (STRINGP (val))
1893 (*insert_from_string_func) (val, 0, 0,
1894 XSTRING (val)->size,
1895 STRING_BYTES (XSTRING (val)),
1896 inherit);
1898 else
1900 val = wrong_type_argument (Qchar_or_string_p, val);
1901 goto retry;
1906 void
1907 insert1 (arg)
1908 Lisp_Object arg;
1910 Finsert (1, &arg);
1914 /* Callers passing one argument to Finsert need not gcpro the
1915 argument "array", since the only element of the array will
1916 not be used after calling insert or insert_from_string, so
1917 we don't care if it gets trashed. */
1919 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
1920 "Insert the arguments, either strings or characters, at point.\n\
1921 Point and before-insertion markers move forward to end up\n\
1922 after the inserted text.\n\
1923 Any other markers at the point of insertion remain before the text.\n\
1925 If the current buffer is multibyte, unibyte strings are converted\n\
1926 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1927 If the current buffer is unibyte, multibyte strings are converted\n\
1928 to unibyte for insertion.")
1929 (nargs, args)
1930 int nargs;
1931 register Lisp_Object *args;
1933 general_insert_function (insert, insert_from_string, 0, nargs, args);
1934 return Qnil;
1937 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
1938 0, MANY, 0,
1939 "Insert the arguments at point, inheriting properties from adjoining text.\n\
1940 Point and before-insertion markers move forward to end up\n\
1941 after the inserted text.\n\
1942 Any other markers at the point of insertion remain before the text.\n\
1944 If the current buffer is multibyte, unibyte strings are converted\n\
1945 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1946 If the current buffer is unibyte, multibyte strings are converted\n\
1947 to unibyte for insertion.")
1948 (nargs, args)
1949 int nargs;
1950 register Lisp_Object *args;
1952 general_insert_function (insert_and_inherit, insert_from_string, 1,
1953 nargs, args);
1954 return Qnil;
1957 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
1958 "Insert strings or characters at point, relocating markers after the text.\n\
1959 Point and markers move forward to end up after the inserted text.\n\
1961 If the current buffer is multibyte, unibyte strings are converted\n\
1962 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1963 If the current buffer is unibyte, multibyte strings are converted\n\
1964 to unibyte for insertion.")
1965 (nargs, args)
1966 int nargs;
1967 register Lisp_Object *args;
1969 general_insert_function (insert_before_markers,
1970 insert_from_string_before_markers, 0,
1971 nargs, args);
1972 return Qnil;
1975 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
1976 Sinsert_and_inherit_before_markers, 0, MANY, 0,
1977 "Insert text at point, relocating markers and inheriting properties.\n\
1978 Point and markers move forward to end up after the inserted text.\n\
1980 If the current buffer is multibyte, unibyte strings are converted\n\
1981 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1982 If the current buffer is unibyte, multibyte strings are converted\n\
1983 to unibyte for insertion.")
1984 (nargs, args)
1985 int nargs;
1986 register Lisp_Object *args;
1988 general_insert_function (insert_before_markers_and_inherit,
1989 insert_from_string_before_markers, 1,
1990 nargs, args);
1991 return Qnil;
1994 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
1995 "Insert COUNT (second arg) copies of CHARACTER (first arg).\n\
1996 Both arguments are required.\n\
1997 Point, and before-insertion markers, are relocated as in the function `insert'.\n\
1998 The optional third arg INHERIT, if non-nil, says to inherit text properties\n\
1999 from adjoining text, if those properties are sticky.")
2000 (character, count, inherit)
2001 Lisp_Object character, count, inherit;
2003 register unsigned char *string;
2004 register int strlen;
2005 register int i, n;
2006 int len;
2007 unsigned char str[MAX_MULTIBYTE_LENGTH];
2009 CHECK_NUMBER (character, 0);
2010 CHECK_NUMBER (count, 1);
2012 if (!NILP (current_buffer->enable_multibyte_characters))
2013 len = CHAR_STRING (XFASTINT (character), str);
2014 else
2015 str[0] = XFASTINT (character), len = 1;
2016 n = XINT (count) * len;
2017 if (n <= 0)
2018 return Qnil;
2019 strlen = min (n, 256 * len);
2020 string = (unsigned char *) alloca (strlen);
2021 for (i = 0; i < strlen; i++)
2022 string[i] = str[i % len];
2023 while (n >= strlen)
2025 QUIT;
2026 if (!NILP (inherit))
2027 insert_and_inherit (string, strlen);
2028 else
2029 insert (string, strlen);
2030 n -= strlen;
2032 if (n > 0)
2034 if (!NILP (inherit))
2035 insert_and_inherit (string, n);
2036 else
2037 insert (string, n);
2039 return Qnil;
2043 /* Making strings from buffer contents. */
2045 /* Return a Lisp_String containing the text of the current buffer from
2046 START to END. If text properties are in use and the current buffer
2047 has properties in the range specified, the resulting string will also
2048 have them, if PROPS is nonzero.
2050 We don't want to use plain old make_string here, because it calls
2051 make_uninit_string, which can cause the buffer arena to be
2052 compacted. make_string has no way of knowing that the data has
2053 been moved, and thus copies the wrong data into the string. This
2054 doesn't effect most of the other users of make_string, so it should
2055 be left as is. But we should use this function when conjuring
2056 buffer substrings. */
2058 Lisp_Object
2059 make_buffer_string (start, end, props)
2060 int start, end;
2061 int props;
2063 int start_byte = CHAR_TO_BYTE (start);
2064 int end_byte = CHAR_TO_BYTE (end);
2066 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2069 /* Return a Lisp_String containing the text of the current buffer from
2070 START / START_BYTE to END / END_BYTE.
2072 If text properties are in use and the current buffer
2073 has properties in the range specified, the resulting string will also
2074 have them, if PROPS is nonzero.
2076 We don't want to use plain old make_string here, because it calls
2077 make_uninit_string, which can cause the buffer arena to be
2078 compacted. make_string has no way of knowing that the data has
2079 been moved, and thus copies the wrong data into the string. This
2080 doesn't effect most of the other users of make_string, so it should
2081 be left as is. But we should use this function when conjuring
2082 buffer substrings. */
2084 Lisp_Object
2085 make_buffer_string_both (start, start_byte, end, end_byte, props)
2086 int start, start_byte, end, end_byte;
2087 int props;
2089 Lisp_Object result, tem, tem1;
2091 if (start < GPT && GPT < end)
2092 move_gap (start);
2094 if (! NILP (current_buffer->enable_multibyte_characters))
2095 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2096 else
2097 result = make_uninit_string (end - start);
2098 bcopy (BYTE_POS_ADDR (start_byte), XSTRING (result)->data,
2099 end_byte - start_byte);
2101 /* If desired, update and copy the text properties. */
2102 if (props)
2104 update_buffer_properties (start, end);
2106 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2107 tem1 = Ftext_properties_at (make_number (start), Qnil);
2109 if (XINT (tem) != end || !NILP (tem1))
2110 copy_intervals_to_string (result, current_buffer, start,
2111 end - start);
2114 return result;
2117 /* Call Vbuffer_access_fontify_functions for the range START ... END
2118 in the current buffer, if necessary. */
2120 static void
2121 update_buffer_properties (start, end)
2122 int start, end;
2124 /* If this buffer has some access functions,
2125 call them, specifying the range of the buffer being accessed. */
2126 if (!NILP (Vbuffer_access_fontify_functions))
2128 Lisp_Object args[3];
2129 Lisp_Object tem;
2131 args[0] = Qbuffer_access_fontify_functions;
2132 XSETINT (args[1], start);
2133 XSETINT (args[2], end);
2135 /* But don't call them if we can tell that the work
2136 has already been done. */
2137 if (!NILP (Vbuffer_access_fontified_property))
2139 tem = Ftext_property_any (args[1], args[2],
2140 Vbuffer_access_fontified_property,
2141 Qnil, Qnil);
2142 if (! NILP (tem))
2143 Frun_hook_with_args (3, args);
2145 else
2146 Frun_hook_with_args (3, args);
2150 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2151 "Return the contents of part of the current buffer as a string.\n\
2152 The two arguments START and END are character positions;\n\
2153 they can be in either order.\n\
2154 The string returned is multibyte if the buffer is multibyte.")
2155 (start, end)
2156 Lisp_Object start, end;
2158 register int b, e;
2160 validate_region (&start, &end);
2161 b = XINT (start);
2162 e = XINT (end);
2164 return make_buffer_string (b, e, 1);
2167 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2168 Sbuffer_substring_no_properties, 2, 2, 0,
2169 "Return the characters of part of the buffer, without the text properties.\n\
2170 The two arguments START and END are character positions;\n\
2171 they can be in either order.")
2172 (start, end)
2173 Lisp_Object start, end;
2175 register int b, e;
2177 validate_region (&start, &end);
2178 b = XINT (start);
2179 e = XINT (end);
2181 return make_buffer_string (b, e, 0);
2184 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2185 "Return the contents of the current buffer as a string.\n\
2186 If narrowing is in effect, this function returns only the visible part\n\
2187 of the buffer.")
2190 return make_buffer_string (BEGV, ZV, 1);
2193 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2194 1, 3, 0,
2195 "Insert before point a substring of the contents of buffer BUFFER.\n\
2196 BUFFER may be a buffer or a buffer name.\n\
2197 Arguments START and END are character numbers specifying the substring.\n\
2198 They default to the beginning and the end of BUFFER.")
2199 (buf, start, end)
2200 Lisp_Object buf, start, end;
2202 register int b, e, temp;
2203 register struct buffer *bp, *obuf;
2204 Lisp_Object buffer;
2206 buffer = Fget_buffer (buf);
2207 if (NILP (buffer))
2208 nsberror (buf);
2209 bp = XBUFFER (buffer);
2210 if (NILP (bp->name))
2211 error ("Selecting deleted buffer");
2213 if (NILP (start))
2214 b = BUF_BEGV (bp);
2215 else
2217 CHECK_NUMBER_COERCE_MARKER (start, 0);
2218 b = XINT (start);
2220 if (NILP (end))
2221 e = BUF_ZV (bp);
2222 else
2224 CHECK_NUMBER_COERCE_MARKER (end, 1);
2225 e = XINT (end);
2228 if (b > e)
2229 temp = b, b = e, e = temp;
2231 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2232 args_out_of_range (start, end);
2234 obuf = current_buffer;
2235 set_buffer_internal_1 (bp);
2236 update_buffer_properties (b, e);
2237 set_buffer_internal_1 (obuf);
2239 insert_from_buffer (bp, b, e - b, 0);
2240 return Qnil;
2243 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2244 6, 6, 0,
2245 "Compare two substrings of two buffers; return result as number.\n\
2246 the value is -N if first string is less after N-1 chars,\n\
2247 +N if first string is greater after N-1 chars, or 0 if strings match.\n\
2248 Each substring is represented as three arguments: BUFFER, START and END.\n\
2249 That makes six args in all, three for each substring.\n\n\
2250 The value of `case-fold-search' in the current buffer\n\
2251 determines whether case is significant or ignored.")
2252 (buffer1, start1, end1, buffer2, start2, end2)
2253 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2255 register int begp1, endp1, begp2, endp2, temp;
2256 register struct buffer *bp1, *bp2;
2257 register Lisp_Object *trt
2258 = (!NILP (current_buffer->case_fold_search)
2259 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents : 0);
2260 int chars = 0;
2261 int i1, i2, i1_byte, i2_byte;
2263 /* Find the first buffer and its substring. */
2265 if (NILP (buffer1))
2266 bp1 = current_buffer;
2267 else
2269 Lisp_Object buf1;
2270 buf1 = Fget_buffer (buffer1);
2271 if (NILP (buf1))
2272 nsberror (buffer1);
2273 bp1 = XBUFFER (buf1);
2274 if (NILP (bp1->name))
2275 error ("Selecting deleted buffer");
2278 if (NILP (start1))
2279 begp1 = BUF_BEGV (bp1);
2280 else
2282 CHECK_NUMBER_COERCE_MARKER (start1, 1);
2283 begp1 = XINT (start1);
2285 if (NILP (end1))
2286 endp1 = BUF_ZV (bp1);
2287 else
2289 CHECK_NUMBER_COERCE_MARKER (end1, 2);
2290 endp1 = XINT (end1);
2293 if (begp1 > endp1)
2294 temp = begp1, begp1 = endp1, endp1 = temp;
2296 if (!(BUF_BEGV (bp1) <= begp1
2297 && begp1 <= endp1
2298 && endp1 <= BUF_ZV (bp1)))
2299 args_out_of_range (start1, end1);
2301 /* Likewise for second substring. */
2303 if (NILP (buffer2))
2304 bp2 = current_buffer;
2305 else
2307 Lisp_Object buf2;
2308 buf2 = Fget_buffer (buffer2);
2309 if (NILP (buf2))
2310 nsberror (buffer2);
2311 bp2 = XBUFFER (buf2);
2312 if (NILP (bp2->name))
2313 error ("Selecting deleted buffer");
2316 if (NILP (start2))
2317 begp2 = BUF_BEGV (bp2);
2318 else
2320 CHECK_NUMBER_COERCE_MARKER (start2, 4);
2321 begp2 = XINT (start2);
2323 if (NILP (end2))
2324 endp2 = BUF_ZV (bp2);
2325 else
2327 CHECK_NUMBER_COERCE_MARKER (end2, 5);
2328 endp2 = XINT (end2);
2331 if (begp2 > endp2)
2332 temp = begp2, begp2 = endp2, endp2 = temp;
2334 if (!(BUF_BEGV (bp2) <= begp2
2335 && begp2 <= endp2
2336 && endp2 <= BUF_ZV (bp2)))
2337 args_out_of_range (start2, end2);
2339 i1 = begp1;
2340 i2 = begp2;
2341 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2342 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2344 while (i1 < endp1 && i2 < endp2)
2346 /* When we find a mismatch, we must compare the
2347 characters, not just the bytes. */
2348 int c1, c2;
2350 if (! NILP (bp1->enable_multibyte_characters))
2352 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2353 BUF_INC_POS (bp1, i1_byte);
2354 i1++;
2356 else
2358 c1 = BUF_FETCH_BYTE (bp1, i1);
2359 c1 = unibyte_char_to_multibyte (c1);
2360 i1++;
2363 if (! NILP (bp2->enable_multibyte_characters))
2365 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2366 BUF_INC_POS (bp2, i2_byte);
2367 i2++;
2369 else
2371 c2 = BUF_FETCH_BYTE (bp2, i2);
2372 c2 = unibyte_char_to_multibyte (c2);
2373 i2++;
2376 if (trt)
2378 c1 = XINT (trt[c1]);
2379 c2 = XINT (trt[c2]);
2381 if (c1 < c2)
2382 return make_number (- 1 - chars);
2383 if (c1 > c2)
2384 return make_number (chars + 1);
2386 chars++;
2389 /* The strings match as far as they go.
2390 If one is shorter, that one is less. */
2391 if (chars < endp1 - begp1)
2392 return make_number (chars + 1);
2393 else if (chars < endp2 - begp2)
2394 return make_number (- chars - 1);
2396 /* Same length too => they are equal. */
2397 return make_number (0);
2400 static Lisp_Object
2401 subst_char_in_region_unwind (arg)
2402 Lisp_Object arg;
2404 return current_buffer->undo_list = arg;
2407 static Lisp_Object
2408 subst_char_in_region_unwind_1 (arg)
2409 Lisp_Object arg;
2411 return current_buffer->filename = arg;
2414 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2415 Ssubst_char_in_region, 4, 5, 0,
2416 "From START to END, replace FROMCHAR with TOCHAR each time it occurs.\n\
2417 If optional arg NOUNDO is non-nil, don't record this change for undo\n\
2418 and don't mark the buffer as really changed.\n\
2419 Both characters must have the same length of multi-byte form.")
2420 (start, end, fromchar, tochar, noundo)
2421 Lisp_Object start, end, fromchar, tochar, noundo;
2423 register int pos, pos_byte, stop, i, len, end_byte;
2424 int changed = 0;
2425 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2426 unsigned char *p;
2427 int count = specpdl_ptr - specpdl;
2428 #define COMBINING_NO 0
2429 #define COMBINING_BEFORE 1
2430 #define COMBINING_AFTER 2
2431 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2432 int maybe_byte_combining = COMBINING_NO;
2433 int last_changed = 0;
2434 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
2436 validate_region (&start, &end);
2437 CHECK_NUMBER (fromchar, 2);
2438 CHECK_NUMBER (tochar, 3);
2440 if (multibyte_p)
2442 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2443 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2444 error ("Characters in subst-char-in-region have different byte-lengths");
2445 if (!ASCII_BYTE_P (*tostr))
2447 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2448 complete multibyte character, it may be combined with the
2449 after bytes. If it is in the range 0xA0..0xFF, it may be
2450 combined with the before and after bytes. */
2451 if (!CHAR_HEAD_P (*tostr))
2452 maybe_byte_combining = COMBINING_BOTH;
2453 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2454 maybe_byte_combining = COMBINING_AFTER;
2457 else
2459 len = 1;
2460 fromstr[0] = XFASTINT (fromchar);
2461 tostr[0] = XFASTINT (tochar);
2464 pos = XINT (start);
2465 pos_byte = CHAR_TO_BYTE (pos);
2466 stop = CHAR_TO_BYTE (XINT (end));
2467 end_byte = stop;
2469 /* If we don't want undo, turn off putting stuff on the list.
2470 That's faster than getting rid of things,
2471 and it prevents even the entry for a first change.
2472 Also inhibit locking the file. */
2473 if (!NILP (noundo))
2475 record_unwind_protect (subst_char_in_region_unwind,
2476 current_buffer->undo_list);
2477 current_buffer->undo_list = Qt;
2478 /* Don't do file-locking. */
2479 record_unwind_protect (subst_char_in_region_unwind_1,
2480 current_buffer->filename);
2481 current_buffer->filename = Qnil;
2484 if (pos_byte < GPT_BYTE)
2485 stop = min (stop, GPT_BYTE);
2486 while (1)
2488 int pos_byte_next = pos_byte;
2490 if (pos_byte >= stop)
2492 if (pos_byte >= end_byte) break;
2493 stop = end_byte;
2495 p = BYTE_POS_ADDR (pos_byte);
2496 if (multibyte_p)
2497 INC_POS (pos_byte_next);
2498 else
2499 ++pos_byte_next;
2500 if (pos_byte_next - pos_byte == len
2501 && p[0] == fromstr[0]
2502 && (len == 1
2503 || (p[1] == fromstr[1]
2504 && (len == 2 || (p[2] == fromstr[2]
2505 && (len == 3 || p[3] == fromstr[3]))))))
2507 if (! changed)
2509 changed = pos;
2510 modify_region (current_buffer, changed, XINT (end));
2512 if (! NILP (noundo))
2514 if (MODIFF - 1 == SAVE_MODIFF)
2515 SAVE_MODIFF++;
2516 if (MODIFF - 1 == current_buffer->auto_save_modified)
2517 current_buffer->auto_save_modified++;
2521 /* Take care of the case where the new character
2522 combines with neighboring bytes. */
2523 if (maybe_byte_combining
2524 && (maybe_byte_combining == COMBINING_AFTER
2525 ? (pos_byte_next < Z_BYTE
2526 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2527 : ((pos_byte_next < Z_BYTE
2528 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2529 || (pos_byte > BEG_BYTE
2530 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2532 Lisp_Object tem, string;
2534 struct gcpro gcpro1;
2536 tem = current_buffer->undo_list;
2537 GCPRO1 (tem);
2539 /* Make a multibyte string containing this single character. */
2540 string = make_multibyte_string (tostr, 1, len);
2541 /* replace_range is less efficient, because it moves the gap,
2542 but it handles combining correctly. */
2543 replace_range (pos, pos + 1, string,
2544 0, 0, 1);
2545 pos_byte_next = CHAR_TO_BYTE (pos);
2546 if (pos_byte_next > pos_byte)
2547 /* Before combining happened. We should not increment
2548 POS. So, to cancel the later increment of POS,
2549 decrease it now. */
2550 pos--;
2551 else
2552 INC_POS (pos_byte_next);
2554 if (! NILP (noundo))
2555 current_buffer->undo_list = tem;
2557 UNGCPRO;
2559 else
2561 if (NILP (noundo))
2562 record_change (pos, 1);
2563 for (i = 0; i < len; i++) *p++ = tostr[i];
2565 last_changed = pos + 1;
2567 pos_byte = pos_byte_next;
2568 pos++;
2571 if (changed)
2573 signal_after_change (changed,
2574 last_changed - changed, last_changed - changed);
2575 update_compositions (changed, last_changed, CHECK_ALL);
2578 unbind_to (count, Qnil);
2579 return Qnil;
2582 DEFUN ("translate-region", Ftranslate_region, Stranslate_region, 3, 3, 0,
2583 "From START to END, translate characters according to TABLE.\n\
2584 TABLE is a string; the Nth character in it is the mapping\n\
2585 for the character with code N.\n\
2586 This function does not alter multibyte characters.\n\
2587 It returns the number of characters changed.")
2588 (start, end, table)
2589 Lisp_Object start;
2590 Lisp_Object end;
2591 register Lisp_Object table;
2593 register int pos_byte, stop; /* Limits of the region. */
2594 register unsigned char *tt; /* Trans table. */
2595 register int nc; /* New character. */
2596 int cnt; /* Number of changes made. */
2597 int size; /* Size of translate table. */
2598 int pos;
2599 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
2601 validate_region (&start, &end);
2602 CHECK_STRING (table, 2);
2604 size = STRING_BYTES (XSTRING (table));
2605 tt = XSTRING (table)->data;
2607 pos_byte = CHAR_TO_BYTE (XINT (start));
2608 stop = CHAR_TO_BYTE (XINT (end));
2609 modify_region (current_buffer, XINT (start), XINT (end));
2610 pos = XINT (start);
2612 cnt = 0;
2613 for (; pos_byte < stop; )
2615 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
2616 int len;
2617 int oc;
2618 int pos_byte_next;
2620 if (multibyte)
2621 oc = STRING_CHAR_AND_LENGTH (p, stop - pos_byte, len);
2622 else
2623 oc = *p, len = 1;
2624 pos_byte_next = pos_byte + len;
2625 if (oc < size && len == 1)
2627 nc = tt[oc];
2628 if (nc != oc)
2630 /* Take care of the case where the new character
2631 combines with neighboring bytes. */
2632 if (!ASCII_BYTE_P (nc)
2633 && (CHAR_HEAD_P (nc)
2634 ? ! CHAR_HEAD_P (FETCH_BYTE (pos_byte + 1))
2635 : (pos_byte > BEG_BYTE
2636 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1)))))
2638 Lisp_Object string;
2640 string = make_multibyte_string (tt + oc, 1, 1);
2641 /* This is less efficient, because it moves the gap,
2642 but it handles combining correctly. */
2643 replace_range (pos, pos + 1, string,
2644 1, 0, 1);
2645 pos_byte_next = CHAR_TO_BYTE (pos);
2646 if (pos_byte_next > pos_byte)
2647 /* Before combining happened. We should not
2648 increment POS. So, to cancel the later
2649 increment of POS, we decrease it now. */
2650 pos--;
2651 else
2652 INC_POS (pos_byte_next);
2654 else
2656 record_change (pos, 1);
2657 *p = nc;
2658 signal_after_change (pos, 1, 1);
2659 update_compositions (pos, pos + 1, CHECK_BORDER);
2661 ++cnt;
2664 pos_byte = pos_byte_next;
2665 pos++;
2668 return make_number (cnt);
2671 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
2672 "Delete the text between point and mark.\n\
2673 When called from a program, expects two arguments,\n\
2674 positions (integers or markers) specifying the stretch to be deleted.")
2675 (start, end)
2676 Lisp_Object start, end;
2678 validate_region (&start, &end);
2679 del_range (XINT (start), XINT (end));
2680 return Qnil;
2683 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
2684 Sdelete_and_extract_region, 2, 2, 0,
2685 "Delete the text between START and END and return it.")
2686 (start, end)
2687 Lisp_Object start, end;
2689 validate_region (&start, &end);
2690 return del_range_1 (XINT (start), XINT (end), 1, 1);
2693 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
2694 "Remove restrictions (narrowing) from current buffer.\n\
2695 This allows the buffer's full text to be seen and edited.")
2698 if (BEG != BEGV || Z != ZV)
2699 current_buffer->clip_changed = 1;
2700 BEGV = BEG;
2701 BEGV_BYTE = BEG_BYTE;
2702 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
2703 /* Changing the buffer bounds invalidates any recorded current column. */
2704 invalidate_current_column ();
2705 return Qnil;
2708 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
2709 "Restrict editing in this buffer to the current region.\n\
2710 The rest of the text becomes temporarily invisible and untouchable\n\
2711 but is not deleted; if you save the buffer in a file, the invisible\n\
2712 text is included in the file. \\[widen] makes all visible again.\n\
2713 See also `save-restriction'.\n\
2715 When calling from a program, pass two arguments; positions (integers\n\
2716 or markers) bounding the text that should remain visible.")
2717 (start, end)
2718 register Lisp_Object start, end;
2720 CHECK_NUMBER_COERCE_MARKER (start, 0);
2721 CHECK_NUMBER_COERCE_MARKER (end, 1);
2723 if (XINT (start) > XINT (end))
2725 Lisp_Object tem;
2726 tem = start; start = end; end = tem;
2729 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
2730 args_out_of_range (start, end);
2732 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
2733 current_buffer->clip_changed = 1;
2735 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2736 SET_BUF_ZV (current_buffer, XFASTINT (end));
2737 if (PT < XFASTINT (start))
2738 SET_PT (XFASTINT (start));
2739 if (PT > XFASTINT (end))
2740 SET_PT (XFASTINT (end));
2741 /* Changing the buffer bounds invalidates any recorded current column. */
2742 invalidate_current_column ();
2743 return Qnil;
2746 Lisp_Object
2747 save_restriction_save ()
2749 if (BEGV == BEG && ZV == Z)
2750 /* The common case that the buffer isn't narrowed.
2751 We return just the buffer object, which save_restriction_restore
2752 recognizes as meaning `no restriction'. */
2753 return Fcurrent_buffer ();
2754 else
2755 /* We have to save a restriction, so return a pair of markers, one
2756 for the beginning and one for the end. */
2758 Lisp_Object beg, end;
2760 beg = buildmark (BEGV, BEGV_BYTE);
2761 end = buildmark (ZV, ZV_BYTE);
2763 /* END must move forward if text is inserted at its exact location. */
2764 XMARKER(end)->insertion_type = 1;
2766 return Fcons (beg, end);
2770 Lisp_Object
2771 save_restriction_restore (data)
2772 Lisp_Object data;
2774 if (CONSP (data))
2775 /* A pair of marks bounding a saved restriction. */
2777 struct Lisp_Marker *beg = XMARKER (XCAR (data));
2778 struct Lisp_Marker *end = XMARKER (XCDR (data));
2779 struct buffer *buf = beg->buffer; /* END should have the same buffer. */
2781 if (beg->charpos != BUF_BEGV(buf) || end->charpos != BUF_ZV(buf))
2782 /* The restriction has changed from the saved one, so restore
2783 the saved restriction. */
2785 int pt = BUF_PT (buf);
2787 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
2788 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
2790 if (pt < beg->charpos || pt > end->charpos)
2791 /* The point is outside the new visible range, move it inside. */
2792 SET_BUF_PT_BOTH (buf,
2793 clip_to_bounds (beg->charpos, pt, end->charpos),
2794 clip_to_bounds (beg->bytepos, BUF_PT_BYTE(buf),
2795 end->bytepos));
2797 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2800 else
2801 /* A buffer, which means that there was no old restriction. */
2803 struct buffer *buf = XBUFFER (data);
2805 if (BUF_BEGV(buf) != BUF_BEG(buf) || BUF_ZV(buf) != BUF_Z(buf))
2806 /* The buffer has been narrowed, get rid of the narrowing. */
2808 SET_BUF_BEGV_BOTH (buf, BUF_BEG(buf), BUF_BEG_BYTE(buf));
2809 SET_BUF_ZV_BOTH (buf, BUF_Z(buf), BUF_Z_BYTE(buf));
2811 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2815 return Qnil;
2818 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
2819 "Execute BODY, saving and restoring current buffer's restrictions.\n\
2820 The buffer's restrictions make parts of the beginning and end invisible.\n\
2821 \(They are set up with `narrow-to-region' and eliminated with `widen'.)\n\
2822 This special form, `save-restriction', saves the current buffer's restrictions\n\
2823 when it is entered, and restores them when it is exited.\n\
2824 So any `narrow-to-region' within BODY lasts only until the end of the form.\n\
2825 The old restrictions settings are restored\n\
2826 even in case of abnormal exit (throw or error).\n\
2828 The value returned is the value of the last form in BODY.\n\
2830 Note: if you are using both `save-excursion' and `save-restriction',\n\
2831 use `save-excursion' outermost:\n\
2832 (save-excursion (save-restriction ...))")
2833 (body)
2834 Lisp_Object body;
2836 register Lisp_Object val;
2837 int count = specpdl_ptr - specpdl;
2839 record_unwind_protect (save_restriction_restore, save_restriction_save ());
2840 val = Fprogn (body);
2841 return unbind_to (count, val);
2844 #ifndef HAVE_MENUS
2846 /* Buffer for the most recent text displayed by Fmessage. */
2847 static char *message_text;
2849 /* Allocated length of that buffer. */
2850 static int message_length;
2852 #endif /* not HAVE_MENUS */
2854 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
2855 "Print a one-line message at the bottom of the screen.\n\
2856 The first argument is a format control string, and the rest are data\n\
2857 to be formatted under control of the string. See `format' for details.\n\
2859 If the first argument is nil, clear any existing message; let the\n\
2860 minibuffer contents show.")
2861 (nargs, args)
2862 int nargs;
2863 Lisp_Object *args;
2865 if (NILP (args[0]))
2867 message (0);
2868 return Qnil;
2870 else
2872 register Lisp_Object val;
2873 val = Fformat (nargs, args);
2874 message3 (val, STRING_BYTES (XSTRING (val)), STRING_MULTIBYTE (val));
2875 return val;
2879 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
2880 "Display a message, in a dialog box if possible.\n\
2881 If a dialog box is not available, use the echo area.\n\
2882 The first argument is a format control string, and the rest are data\n\
2883 to be formatted under control of the string. See `format' for details.\n\
2885 If the first argument is nil, clear any existing message; let the\n\
2886 minibuffer contents show.")
2887 (nargs, args)
2888 int nargs;
2889 Lisp_Object *args;
2891 if (NILP (args[0]))
2893 message (0);
2894 return Qnil;
2896 else
2898 register Lisp_Object val;
2899 val = Fformat (nargs, args);
2900 #ifdef HAVE_MENUS
2902 Lisp_Object pane, menu, obj;
2903 struct gcpro gcpro1;
2904 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
2905 GCPRO1 (pane);
2906 menu = Fcons (val, pane);
2907 obj = Fx_popup_dialog (Qt, menu);
2908 UNGCPRO;
2909 return val;
2911 #else /* not HAVE_MENUS */
2912 /* Copy the data so that it won't move when we GC. */
2913 if (! message_text)
2915 message_text = (char *)xmalloc (80);
2916 message_length = 80;
2918 if (STRING_BYTES (XSTRING (val)) > message_length)
2920 message_length = STRING_BYTES (XSTRING (val));
2921 message_text = (char *)xrealloc (message_text, message_length);
2923 bcopy (XSTRING (val)->data, message_text, STRING_BYTES (XSTRING (val)));
2924 message2 (message_text, STRING_BYTES (XSTRING (val)),
2925 STRING_MULTIBYTE (val));
2926 return val;
2927 #endif /* not HAVE_MENUS */
2930 #ifdef HAVE_MENUS
2931 extern Lisp_Object last_nonmenu_event;
2932 #endif
2934 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
2935 "Display a message in a dialog box or in the echo area.\n\
2936 If this command was invoked with the mouse, use a dialog box if\n\
2937 `use-dialog-box' is non-nil.\n\
2938 Otherwise, use the echo area.\n\
2939 The first argument is a format control string, and the rest are data\n\
2940 to be formatted under control of the string. See `format' for details.\n\
2942 If the first argument is nil, clear any existing message; let the\n\
2943 minibuffer contents show.")
2944 (nargs, args)
2945 int nargs;
2946 Lisp_Object *args;
2948 #ifdef HAVE_MENUS
2949 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2950 && use_dialog_box)
2951 return Fmessage_box (nargs, args);
2952 #endif
2953 return Fmessage (nargs, args);
2956 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
2957 "Return the string currently displayed in the echo area, or nil if none.")
2960 return current_message ();
2964 DEFUN ("propertize", Fpropertize, Spropertize, 3, MANY, 0,
2965 "Return a copy of STRING with text properties added.\n\
2966 First argument is the string to copy.\n\
2967 Remaining arguments form a sequence of PROPERTY VALUE pairs for text\n\
2968 properties to add to the result ")
2969 (nargs, args)
2970 int nargs;
2971 Lisp_Object *args;
2973 Lisp_Object properties, string;
2974 struct gcpro gcpro1, gcpro2;
2975 int i;
2977 /* Number of args must be odd. */
2978 if ((nargs & 1) == 0 || nargs < 3)
2979 error ("Wrong number of arguments");
2981 properties = string = Qnil;
2982 GCPRO2 (properties, string);
2984 /* First argument must be a string. */
2985 CHECK_STRING (args[0], 0);
2986 string = Fcopy_sequence (args[0]);
2988 for (i = 1; i < nargs; i += 2)
2990 CHECK_SYMBOL (args[i], i);
2991 properties = Fcons (args[i], Fcons (args[i + 1], properties));
2994 Fadd_text_properties (make_number (0),
2995 make_number (XSTRING (string)->size),
2996 properties, string);
2997 RETURN_UNGCPRO (string);
3001 /* Number of bytes that STRING will occupy when put into the result.
3002 MULTIBYTE is nonzero if the result should be multibyte. */
3004 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3005 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3006 ? count_size_as_multibyte (XSTRING (STRING)->data, \
3007 STRING_BYTES (XSTRING (STRING))) \
3008 : STRING_BYTES (XSTRING (STRING)))
3010 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3011 "Format a string out of a control-string and arguments.\n\
3012 The first argument is a control string.\n\
3013 The other arguments are substituted into it to make the result, a string.\n\
3014 It may contain %-sequences meaning to substitute the next argument.\n\
3015 %s means print a string argument. Actually, prints any object, with `princ'.\n\
3016 %d means print as number in decimal (%o octal, %x hex).\n\
3017 %e means print a number in exponential notation.\n\
3018 %f means print a number in decimal-point notation.\n\
3019 %g means print a number in exponential notation\n\
3020 or decimal-point notation, whichever uses fewer characters.\n\
3021 %c means print a number as a single character.\n\
3022 %S means print any object as an s-expression (using `prin1').\n\
3023 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.\n\
3024 Use %% to put a single % into the output.")
3025 (nargs, args)
3026 int nargs;
3027 register Lisp_Object *args;
3029 register int n; /* The number of the next arg to substitute */
3030 register int total; /* An estimate of the final length */
3031 char *buf, *p;
3032 register unsigned char *format, *end;
3033 int nchars;
3034 /* Nonzero if the output should be a multibyte string,
3035 which is true if any of the inputs is one. */
3036 int multibyte = 0;
3037 /* When we make a multibyte string, we must pay attention to the
3038 byte combining problem, i.e., a byte may be combined with a
3039 multibyte charcter of the previous string. This flag tells if we
3040 must consider such a situation or not. */
3041 int maybe_combine_byte;
3042 unsigned char *this_format;
3043 int longest_format;
3044 Lisp_Object val;
3045 struct info
3047 int start, end;
3048 } *info = 0;
3050 /* It should not be necessary to GCPRO ARGS, because
3051 the caller in the interpreter should take care of that. */
3053 /* Try to determine whether the result should be multibyte.
3054 This is not always right; sometimes the result needs to be multibyte
3055 because of an object that we will pass through prin1,
3056 and in that case, we won't know it here. */
3057 for (n = 0; n < nargs; n++)
3058 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3059 multibyte = 1;
3061 CHECK_STRING (args[0], 0);
3063 /* If we start out planning a unibyte result,
3064 and later find it has to be multibyte, we jump back to retry. */
3065 retry:
3067 format = XSTRING (args[0])->data;
3068 end = format + STRING_BYTES (XSTRING (args[0]));
3069 longest_format = 0;
3071 /* Make room in result for all the non-%-codes in the control string. */
3072 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]);
3074 /* Add to TOTAL enough space to hold the converted arguments. */
3076 n = 0;
3077 while (format != end)
3078 if (*format++ == '%')
3080 int minlen, thissize = 0;
3081 unsigned char *this_format_start = format - 1;
3083 /* Process a numeric arg and skip it. */
3084 minlen = atoi (format);
3085 if (minlen < 0)
3086 minlen = - minlen;
3088 while ((*format >= '0' && *format <= '9')
3089 || *format == '-' || *format == ' ' || *format == '.')
3090 format++;
3092 if (format - this_format_start + 1 > longest_format)
3093 longest_format = format - this_format_start + 1;
3095 if (format == end)
3096 error ("Format string ends in middle of format specifier");
3097 if (*format == '%')
3098 format++;
3099 else if (++n >= nargs)
3100 error ("Not enough arguments for format string");
3101 else if (*format == 'S')
3103 /* For `S', prin1 the argument and then treat like a string. */
3104 register Lisp_Object tem;
3105 tem = Fprin1_to_string (args[n], Qnil);
3106 if (STRING_MULTIBYTE (tem) && ! multibyte)
3108 multibyte = 1;
3109 goto retry;
3111 args[n] = tem;
3112 goto string;
3114 else if (SYMBOLP (args[n]))
3116 /* Use a temp var to avoid problems when ENABLE_CHECKING
3117 is turned on. */
3118 struct Lisp_String *t = XSYMBOL (args[n])->name;
3119 XSETSTRING (args[n], t);
3120 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3122 multibyte = 1;
3123 goto retry;
3125 goto string;
3127 else if (STRINGP (args[n]))
3129 string:
3130 if (*format != 's' && *format != 'S')
3131 error ("Format specifier doesn't match argument type");
3132 thissize = CONVERTED_BYTE_SIZE (multibyte, args[n]);
3134 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3135 else if (INTEGERP (args[n]) && *format != 's')
3137 /* The following loop assumes the Lisp type indicates
3138 the proper way to pass the argument.
3139 So make sure we have a flonum if the argument should
3140 be a double. */
3141 if (*format == 'e' || *format == 'f' || *format == 'g')
3142 args[n] = Ffloat (args[n]);
3143 else
3144 if (*format != 'd' && *format != 'o' && *format != 'x'
3145 && *format != 'i' && *format != 'X' && *format != 'c')
3146 error ("Invalid format operation %%%c", *format);
3148 thissize = 30;
3149 if (*format == 'c'
3150 && (! SINGLE_BYTE_CHAR_P (XINT (args[n]))
3151 || XINT (args[n]) == 0))
3153 if (! multibyte)
3155 multibyte = 1;
3156 goto retry;
3158 args[n] = Fchar_to_string (args[n]);
3159 thissize = STRING_BYTES (XSTRING (args[n]));
3162 else if (FLOATP (args[n]) && *format != 's')
3164 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3165 args[n] = Ftruncate (args[n], Qnil);
3166 thissize = 200;
3168 else
3170 /* Anything but a string, convert to a string using princ. */
3171 register Lisp_Object tem;
3172 tem = Fprin1_to_string (args[n], Qt);
3173 if (STRING_MULTIBYTE (tem) & ! multibyte)
3175 multibyte = 1;
3176 goto retry;
3178 args[n] = tem;
3179 goto string;
3182 if (thissize < minlen)
3183 thissize = minlen;
3185 total += thissize + 4;
3188 /* Now we can no longer jump to retry.
3189 TOTAL and LONGEST_FORMAT are known for certain. */
3191 this_format = (unsigned char *) alloca (longest_format + 1);
3193 /* Allocate the space for the result.
3194 Note that TOTAL is an overestimate. */
3195 if (total < 1000)
3196 buf = (char *) alloca (total + 1);
3197 else
3198 buf = (char *) xmalloc (total + 1);
3200 p = buf;
3201 nchars = 0;
3202 n = 0;
3204 /* Scan the format and store result in BUF. */
3205 format = XSTRING (args[0])->data;
3206 maybe_combine_byte = 0;
3207 while (format != end)
3209 if (*format == '%')
3211 int minlen;
3212 int negative = 0;
3213 unsigned char *this_format_start = format;
3215 format++;
3217 /* Process a numeric arg and skip it. */
3218 minlen = atoi (format);
3219 if (minlen < 0)
3220 minlen = - minlen, negative = 1;
3222 while ((*format >= '0' && *format <= '9')
3223 || *format == '-' || *format == ' ' || *format == '.')
3224 format++;
3226 if (*format++ == '%')
3228 *p++ = '%';
3229 nchars++;
3230 continue;
3233 ++n;
3235 if (STRINGP (args[n]))
3237 int padding, nbytes;
3238 int width = strwidth (XSTRING (args[n])->data,
3239 STRING_BYTES (XSTRING (args[n])));
3240 int start = nchars;
3242 /* If spec requires it, pad on right with spaces. */
3243 padding = minlen - width;
3244 if (! negative)
3245 while (padding-- > 0)
3247 *p++ = ' ';
3248 nchars++;
3251 if (p > buf
3252 && multibyte
3253 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3254 && STRING_MULTIBYTE (args[n])
3255 && !CHAR_HEAD_P (XSTRING (args[n])->data[0]))
3256 maybe_combine_byte = 1;
3257 nbytes = copy_text (XSTRING (args[n])->data, p,
3258 STRING_BYTES (XSTRING (args[n])),
3259 STRING_MULTIBYTE (args[n]), multibyte);
3260 p += nbytes;
3261 nchars += XSTRING (args[n])->size;
3263 if (negative)
3264 while (padding-- > 0)
3266 *p++ = ' ';
3267 nchars++;
3270 /* If this argument has text properties, record where
3271 in the result string it appears. */
3272 if (XSTRING (args[n])->intervals)
3274 if (!info)
3276 int nbytes = nargs * sizeof *info;
3277 info = (struct info *) alloca (nbytes);
3278 bzero (info, nbytes);
3281 info[n].start = start;
3282 info[n].end = nchars;
3285 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3287 int this_nchars;
3289 bcopy (this_format_start, this_format,
3290 format - this_format_start);
3291 this_format[format - this_format_start] = 0;
3293 if (INTEGERP (args[n]))
3294 sprintf (p, this_format, XINT (args[n]));
3295 else
3296 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3298 if (p > buf
3299 && multibyte
3300 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3301 && !CHAR_HEAD_P (*((unsigned char *) p)))
3302 maybe_combine_byte = 1;
3303 this_nchars = strlen (p);
3304 if (multibyte)
3305 p += str_to_multibyte (p, buf + total - p, this_nchars);
3306 else
3307 p += this_nchars;
3308 nchars += this_nchars;
3311 else if (STRING_MULTIBYTE (args[0]))
3313 /* Copy a whole multibyte character. */
3314 if (p > buf
3315 && multibyte
3316 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3317 && !CHAR_HEAD_P (*format))
3318 maybe_combine_byte = 1;
3319 *p++ = *format++;
3320 while (! CHAR_HEAD_P (*format)) *p++ = *format++;
3321 nchars++;
3323 else if (multibyte)
3325 /* Convert a single-byte character to multibyte. */
3326 int len = copy_text (format, p, 1, 0, 1);
3328 p += len;
3329 format++;
3330 nchars++;
3332 else
3333 *p++ = *format++, nchars++;
3336 if (maybe_combine_byte)
3337 nchars = multibyte_chars_in_text (buf, p - buf);
3338 val = make_specified_string (buf, nchars, p - buf, multibyte);
3340 /* If we allocated BUF with malloc, free it too. */
3341 if (total >= 1000)
3342 xfree (buf);
3344 /* If the format string has text properties, or any of the string
3345 arguments has text properties, set up text properties of the
3346 result string. */
3348 if (XSTRING (args[0])->intervals || info)
3350 Lisp_Object len, new_len, props;
3351 struct gcpro gcpro1;
3353 /* Add text properties from the format string. */
3354 len = make_number (XSTRING (args[0])->size);
3355 props = text_property_list (args[0], make_number (0), len, Qnil);
3356 GCPRO1 (props);
3358 if (CONSP (props))
3360 new_len = make_number (XSTRING (val)->size);
3361 extend_property_ranges (props, len, new_len);
3362 add_text_properties_from_list (val, props, make_number (0));
3365 /* Add text properties from arguments. */
3366 if (info)
3367 for (n = 1; n < nargs; ++n)
3368 if (info[n].end)
3370 len = make_number (XSTRING (args[n])->size);
3371 new_len = make_number (info[n].end - info[n].start);
3372 props = text_property_list (args[n], make_number (0), len, Qnil);
3373 extend_property_ranges (props, len, new_len);
3374 /* If successive arguments have properites, be sure that
3375 the value of `composition' property be the copy. */
3376 if (n > 1 && info[n - 1].end)
3377 make_composition_value_copy (props);
3378 add_text_properties_from_list (val, props,
3379 make_number (info[n].start));
3382 UNGCPRO;
3385 return val;
3389 /* VARARGS 1 */
3390 Lisp_Object
3391 #ifdef NO_ARG_ARRAY
3392 format1 (string1, arg0, arg1, arg2, arg3, arg4)
3393 EMACS_INT arg0, arg1, arg2, arg3, arg4;
3394 #else
3395 format1 (string1)
3396 #endif
3397 char *string1;
3399 char buf[100];
3400 #ifdef NO_ARG_ARRAY
3401 EMACS_INT args[5];
3402 args[0] = arg0;
3403 args[1] = arg1;
3404 args[2] = arg2;
3405 args[3] = arg3;
3406 args[4] = arg4;
3407 doprnt (buf, sizeof buf, string1, (char *)0, 5, (char **) args);
3408 #else
3409 doprnt (buf, sizeof buf, string1, (char *)0, 5, &string1 + 1);
3410 #endif
3411 return build_string (buf);
3414 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
3415 "Return t if two characters match, optionally ignoring case.\n\
3416 Both arguments must be characters (i.e. integers).\n\
3417 Case is ignored if `case-fold-search' is non-nil in the current buffer.")
3418 (c1, c2)
3419 register Lisp_Object c1, c2;
3421 int i1, i2;
3422 CHECK_NUMBER (c1, 0);
3423 CHECK_NUMBER (c2, 1);
3425 if (XINT (c1) == XINT (c2))
3426 return Qt;
3427 if (NILP (current_buffer->case_fold_search))
3428 return Qnil;
3430 /* Do these in separate statements,
3431 then compare the variables.
3432 because of the way DOWNCASE uses temp variables. */
3433 i1 = DOWNCASE (XFASTINT (c1));
3434 i2 = DOWNCASE (XFASTINT (c2));
3435 return (i1 == i2 ? Qt : Qnil);
3438 /* Transpose the markers in two regions of the current buffer, and
3439 adjust the ones between them if necessary (i.e.: if the regions
3440 differ in size).
3442 START1, END1 are the character positions of the first region.
3443 START1_BYTE, END1_BYTE are the byte positions.
3444 START2, END2 are the character positions of the second region.
3445 START2_BYTE, END2_BYTE are the byte positions.
3447 Traverses the entire marker list of the buffer to do so, adding an
3448 appropriate amount to some, subtracting from some, and leaving the
3449 rest untouched. Most of this is copied from adjust_markers in insdel.c.
3451 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
3453 static void
3454 transpose_markers (start1, end1, start2, end2,
3455 start1_byte, end1_byte, start2_byte, end2_byte)
3456 register int start1, end1, start2, end2;
3457 register int start1_byte, end1_byte, start2_byte, end2_byte;
3459 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
3460 register Lisp_Object marker;
3462 /* Update point as if it were a marker. */
3463 if (PT < start1)
3465 else if (PT < end1)
3466 TEMP_SET_PT_BOTH (PT + (end2 - end1),
3467 PT_BYTE + (end2_byte - end1_byte));
3468 else if (PT < start2)
3469 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
3470 (PT_BYTE + (end2_byte - start2_byte)
3471 - (end1_byte - start1_byte)));
3472 else if (PT < end2)
3473 TEMP_SET_PT_BOTH (PT - (start2 - start1),
3474 PT_BYTE - (start2_byte - start1_byte));
3476 /* We used to adjust the endpoints here to account for the gap, but that
3477 isn't good enough. Even if we assume the caller has tried to move the
3478 gap out of our way, it might still be at start1 exactly, for example;
3479 and that places it `inside' the interval, for our purposes. The amount
3480 of adjustment is nontrivial if there's a `denormalized' marker whose
3481 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
3482 the dirty work to Fmarker_position, below. */
3484 /* The difference between the region's lengths */
3485 diff = (end2 - start2) - (end1 - start1);
3486 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
3488 /* For shifting each marker in a region by the length of the other
3489 region plus the distance between the regions. */
3490 amt1 = (end2 - start2) + (start2 - end1);
3491 amt2 = (end1 - start1) + (start2 - end1);
3492 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
3493 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
3495 for (marker = BUF_MARKERS (current_buffer); !NILP (marker);
3496 marker = XMARKER (marker)->chain)
3498 mpos = marker_byte_position (marker);
3499 if (mpos >= start1_byte && mpos < end2_byte)
3501 if (mpos < end1_byte)
3502 mpos += amt1_byte;
3503 else if (mpos < start2_byte)
3504 mpos += diff_byte;
3505 else
3506 mpos -= amt2_byte;
3507 XMARKER (marker)->bytepos = mpos;
3509 mpos = XMARKER (marker)->charpos;
3510 if (mpos >= start1 && mpos < end2)
3512 if (mpos < end1)
3513 mpos += amt1;
3514 else if (mpos < start2)
3515 mpos += diff;
3516 else
3517 mpos -= amt2;
3519 XMARKER (marker)->charpos = mpos;
3523 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
3524 "Transpose region START1 to END1 with START2 to END2.\n\
3525 The regions may not be overlapping, because the size of the buffer is\n\
3526 never changed in a transposition.\n\
3528 Optional fifth arg LEAVE_MARKERS, if non-nil, means don't update\n\
3529 any markers that happen to be located in the regions.\n\
3531 Transposing beyond buffer boundaries is an error.")
3532 (startr1, endr1, startr2, endr2, leave_markers)
3533 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
3535 register int start1, end1, start2, end2;
3536 int start1_byte, start2_byte, len1_byte, len2_byte;
3537 int gap, len1, len_mid, len2;
3538 unsigned char *start1_addr, *start2_addr, *temp;
3539 struct gcpro gcpro1, gcpro2;
3541 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
3542 cur_intv = BUF_INTERVALS (current_buffer);
3544 validate_region (&startr1, &endr1);
3545 validate_region (&startr2, &endr2);
3547 start1 = XFASTINT (startr1);
3548 end1 = XFASTINT (endr1);
3549 start2 = XFASTINT (startr2);
3550 end2 = XFASTINT (endr2);
3551 gap = GPT;
3553 /* Swap the regions if they're reversed. */
3554 if (start2 < end1)
3556 register int glumph = start1;
3557 start1 = start2;
3558 start2 = glumph;
3559 glumph = end1;
3560 end1 = end2;
3561 end2 = glumph;
3564 len1 = end1 - start1;
3565 len2 = end2 - start2;
3567 if (start2 < end1)
3568 error ("Transposed regions overlap");
3569 else if (start1 == end1 || start2 == end2)
3570 error ("Transposed region has length 0");
3572 /* The possibilities are:
3573 1. Adjacent (contiguous) regions, or separate but equal regions
3574 (no, really equal, in this case!), or
3575 2. Separate regions of unequal size.
3577 The worst case is usually No. 2. It means that (aside from
3578 potential need for getting the gap out of the way), there also
3579 needs to be a shifting of the text between the two regions. So
3580 if they are spread far apart, we are that much slower... sigh. */
3582 /* It must be pointed out that the really studly thing to do would
3583 be not to move the gap at all, but to leave it in place and work
3584 around it if necessary. This would be extremely efficient,
3585 especially considering that people are likely to do
3586 transpositions near where they are working interactively, which
3587 is exactly where the gap would be found. However, such code
3588 would be much harder to write and to read. So, if you are
3589 reading this comment and are feeling squirrely, by all means have
3590 a go! I just didn't feel like doing it, so I will simply move
3591 the gap the minimum distance to get it out of the way, and then
3592 deal with an unbroken array. */
3594 /* Make sure the gap won't interfere, by moving it out of the text
3595 we will operate on. */
3596 if (start1 < gap && gap < end2)
3598 if (gap - start1 < end2 - gap)
3599 move_gap (start1);
3600 else
3601 move_gap (end2);
3604 start1_byte = CHAR_TO_BYTE (start1);
3605 start2_byte = CHAR_TO_BYTE (start2);
3606 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
3607 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
3609 #ifdef BYTE_COMBINING_DEBUG
3610 if (end1 == start2)
3612 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3613 len2_byte, start1, start1_byte)
3614 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3615 len1_byte, end2, start2_byte + len2_byte)
3616 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3617 len1_byte, end2, start2_byte + len2_byte))
3618 abort ();
3620 else
3622 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3623 len2_byte, start1, start1_byte)
3624 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3625 len1_byte, start2, start2_byte)
3626 || count_combining_after (BYTE_POS_ADDR (start2_byte),
3627 len2_byte, end1, start1_byte + len1_byte)
3628 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3629 len1_byte, end2, start2_byte + len2_byte))
3630 abort ();
3632 #endif
3634 /* Hmmm... how about checking to see if the gap is large
3635 enough to use as the temporary storage? That would avoid an
3636 allocation... interesting. Later, don't fool with it now. */
3638 /* Working without memmove, for portability (sigh), so must be
3639 careful of overlapping subsections of the array... */
3641 if (end1 == start2) /* adjacent regions */
3643 modify_region (current_buffer, start1, end2);
3644 record_change (start1, len1 + len2);
3646 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3647 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3648 Fset_text_properties (make_number (start1), make_number (end2),
3649 Qnil, Qnil);
3651 /* First region smaller than second. */
3652 if (len1_byte < len2_byte)
3654 /* We use alloca only if it is small,
3655 because we want to avoid stack overflow. */
3656 if (len2_byte > 20000)
3657 temp = (unsigned char *) xmalloc (len2_byte);
3658 else
3659 temp = (unsigned char *) alloca (len2_byte);
3661 /* Don't precompute these addresses. We have to compute them
3662 at the last minute, because the relocating allocator might
3663 have moved the buffer around during the xmalloc. */
3664 start1_addr = BYTE_POS_ADDR (start1_byte);
3665 start2_addr = BYTE_POS_ADDR (start2_byte);
3667 bcopy (start2_addr, temp, len2_byte);
3668 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
3669 bcopy (temp, start1_addr, len2_byte);
3670 if (len2_byte > 20000)
3671 xfree (temp);
3673 else
3674 /* First region not smaller than second. */
3676 if (len1_byte > 20000)
3677 temp = (unsigned char *) xmalloc (len1_byte);
3678 else
3679 temp = (unsigned char *) alloca (len1_byte);
3680 start1_addr = BYTE_POS_ADDR (start1_byte);
3681 start2_addr = BYTE_POS_ADDR (start2_byte);
3682 bcopy (start1_addr, temp, len1_byte);
3683 bcopy (start2_addr, start1_addr, len2_byte);
3684 bcopy (temp, start1_addr + len2_byte, len1_byte);
3685 if (len1_byte > 20000)
3686 xfree (temp);
3688 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
3689 len1, current_buffer, 0);
3690 graft_intervals_into_buffer (tmp_interval2, start1,
3691 len2, current_buffer, 0);
3692 update_compositions (start1, start1 + len2, CHECK_BORDER);
3693 update_compositions (start1 + len2, end2, CHECK_TAIL);
3695 /* Non-adjacent regions, because end1 != start2, bleagh... */
3696 else
3698 len_mid = start2_byte - (start1_byte + len1_byte);
3700 if (len1_byte == len2_byte)
3701 /* Regions are same size, though, how nice. */
3703 modify_region (current_buffer, start1, end1);
3704 modify_region (current_buffer, start2, end2);
3705 record_change (start1, len1);
3706 record_change (start2, len2);
3707 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3708 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3709 Fset_text_properties (make_number (start1), make_number (end1),
3710 Qnil, Qnil);
3711 Fset_text_properties (make_number (start2), make_number (end2),
3712 Qnil, Qnil);
3714 if (len1_byte > 20000)
3715 temp = (unsigned char *) xmalloc (len1_byte);
3716 else
3717 temp = (unsigned char *) alloca (len1_byte);
3718 start1_addr = BYTE_POS_ADDR (start1_byte);
3719 start2_addr = BYTE_POS_ADDR (start2_byte);
3720 bcopy (start1_addr, temp, len1_byte);
3721 bcopy (start2_addr, start1_addr, len2_byte);
3722 bcopy (temp, start2_addr, len1_byte);
3723 if (len1_byte > 20000)
3724 xfree (temp);
3725 graft_intervals_into_buffer (tmp_interval1, start2,
3726 len1, current_buffer, 0);
3727 graft_intervals_into_buffer (tmp_interval2, start1,
3728 len2, current_buffer, 0);
3731 else if (len1_byte < len2_byte) /* Second region larger than first */
3732 /* Non-adjacent & unequal size, area between must also be shifted. */
3734 modify_region (current_buffer, start1, end2);
3735 record_change (start1, (end2 - start1));
3736 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3737 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3738 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3739 Fset_text_properties (make_number (start1), make_number (end2),
3740 Qnil, Qnil);
3742 /* holds region 2 */
3743 if (len2_byte > 20000)
3744 temp = (unsigned char *) xmalloc (len2_byte);
3745 else
3746 temp = (unsigned char *) alloca (len2_byte);
3747 start1_addr = BYTE_POS_ADDR (start1_byte);
3748 start2_addr = BYTE_POS_ADDR (start2_byte);
3749 bcopy (start2_addr, temp, len2_byte);
3750 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
3751 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3752 bcopy (temp, start1_addr, len2_byte);
3753 if (len2_byte > 20000)
3754 xfree (temp);
3755 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3756 len1, current_buffer, 0);
3757 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3758 len_mid, current_buffer, 0);
3759 graft_intervals_into_buffer (tmp_interval2, start1,
3760 len2, current_buffer, 0);
3762 else
3763 /* Second region smaller than first. */
3765 record_change (start1, (end2 - start1));
3766 modify_region (current_buffer, start1, end2);
3768 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3769 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3770 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3771 Fset_text_properties (make_number (start1), make_number (end2),
3772 Qnil, Qnil);
3774 /* holds region 1 */
3775 if (len1_byte > 20000)
3776 temp = (unsigned char *) xmalloc (len1_byte);
3777 else
3778 temp = (unsigned char *) alloca (len1_byte);
3779 start1_addr = BYTE_POS_ADDR (start1_byte);
3780 start2_addr = BYTE_POS_ADDR (start2_byte);
3781 bcopy (start1_addr, temp, len1_byte);
3782 bcopy (start2_addr, start1_addr, len2_byte);
3783 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3784 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
3785 if (len1_byte > 20000)
3786 xfree (temp);
3787 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3788 len1, current_buffer, 0);
3789 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3790 len_mid, current_buffer, 0);
3791 graft_intervals_into_buffer (tmp_interval2, start1,
3792 len2, current_buffer, 0);
3795 update_compositions (start1, start1 + len2, CHECK_BORDER);
3796 update_compositions (end2 - len1, end2, CHECK_BORDER);
3799 /* When doing multiple transpositions, it might be nice
3800 to optimize this. Perhaps the markers in any one buffer
3801 should be organized in some sorted data tree. */
3802 if (NILP (leave_markers))
3804 transpose_markers (start1, end1, start2, end2,
3805 start1_byte, start1_byte + len1_byte,
3806 start2_byte, start2_byte + len2_byte);
3807 fix_overlays_in_range (start1, end2);
3810 return Qnil;
3814 void
3815 syms_of_editfns ()
3817 environbuf = 0;
3819 Qbuffer_access_fontify_functions
3820 = intern ("buffer-access-fontify-functions");
3821 staticpro (&Qbuffer_access_fontify_functions);
3823 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
3824 "Non-nil means.text motion commands don't notice fields.");
3825 Vinhibit_field_text_motion = Qnil;
3827 DEFVAR_LISP ("buffer-access-fontify-functions",
3828 &Vbuffer_access_fontify_functions,
3829 "List of functions called by `buffer-substring' to fontify if necessary.\n\
3830 Each function is called with two arguments which specify the range\n\
3831 of the buffer being accessed.");
3832 Vbuffer_access_fontify_functions = Qnil;
3835 Lisp_Object obuf;
3836 extern Lisp_Object Vprin1_to_string_buffer;
3837 obuf = Fcurrent_buffer ();
3838 /* Do this here, because init_buffer_once is too early--it won't work. */
3839 Fset_buffer (Vprin1_to_string_buffer);
3840 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
3841 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
3842 Qnil);
3843 Fset_buffer (obuf);
3846 DEFVAR_LISP ("buffer-access-fontified-property",
3847 &Vbuffer_access_fontified_property,
3848 "Property which (if non-nil) indicates text has been fontified.\n\
3849 `buffer-substring' need not call the `buffer-access-fontify-functions'\n\
3850 functions if all the text being accessed has this property.");
3851 Vbuffer_access_fontified_property = Qnil;
3853 DEFVAR_LISP ("system-name", &Vsystem_name,
3854 "The name of the machine Emacs is running on.");
3856 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
3857 "The full name of the user logged in.");
3859 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
3860 "The user's name, taken from environment variables if possible.");
3862 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
3863 "The user's name, based upon the real uid only.");
3865 defsubr (&Spropertize);
3866 defsubr (&Schar_equal);
3867 defsubr (&Sgoto_char);
3868 defsubr (&Sstring_to_char);
3869 defsubr (&Schar_to_string);
3870 defsubr (&Sbuffer_substring);
3871 defsubr (&Sbuffer_substring_no_properties);
3872 defsubr (&Sbuffer_string);
3874 defsubr (&Spoint_marker);
3875 defsubr (&Smark_marker);
3876 defsubr (&Spoint);
3877 defsubr (&Sregion_beginning);
3878 defsubr (&Sregion_end);
3880 staticpro (&Qfield);
3881 Qfield = intern ("field");
3882 staticpro (&Qboundary);
3883 Qboundary = intern ("boundary");
3884 defsubr (&Sfield_beginning);
3885 defsubr (&Sfield_end);
3886 defsubr (&Sfield_string);
3887 defsubr (&Sfield_string_no_properties);
3888 defsubr (&Sdelete_field);
3889 defsubr (&Sconstrain_to_field);
3891 defsubr (&Sline_beginning_position);
3892 defsubr (&Sline_end_position);
3894 /* defsubr (&Smark); */
3895 /* defsubr (&Sset_mark); */
3896 defsubr (&Ssave_excursion);
3897 defsubr (&Ssave_current_buffer);
3899 defsubr (&Sbufsize);
3900 defsubr (&Spoint_max);
3901 defsubr (&Spoint_min);
3902 defsubr (&Spoint_min_marker);
3903 defsubr (&Spoint_max_marker);
3904 defsubr (&Sgap_position);
3905 defsubr (&Sgap_size);
3906 defsubr (&Sposition_bytes);
3907 defsubr (&Sbyte_to_position);
3909 defsubr (&Sbobp);
3910 defsubr (&Seobp);
3911 defsubr (&Sbolp);
3912 defsubr (&Seolp);
3913 defsubr (&Sfollowing_char);
3914 defsubr (&Sprevious_char);
3915 defsubr (&Schar_after);
3916 defsubr (&Schar_before);
3917 defsubr (&Sinsert);
3918 defsubr (&Sinsert_before_markers);
3919 defsubr (&Sinsert_and_inherit);
3920 defsubr (&Sinsert_and_inherit_before_markers);
3921 defsubr (&Sinsert_char);
3923 defsubr (&Suser_login_name);
3924 defsubr (&Suser_real_login_name);
3925 defsubr (&Suser_uid);
3926 defsubr (&Suser_real_uid);
3927 defsubr (&Suser_full_name);
3928 defsubr (&Semacs_pid);
3929 defsubr (&Scurrent_time);
3930 defsubr (&Sformat_time_string);
3931 defsubr (&Sfloat_time);
3932 defsubr (&Sdecode_time);
3933 defsubr (&Sencode_time);
3934 defsubr (&Scurrent_time_string);
3935 defsubr (&Scurrent_time_zone);
3936 defsubr (&Sset_time_zone_rule);
3937 defsubr (&Ssystem_name);
3938 defsubr (&Smessage);
3939 defsubr (&Smessage_box);
3940 defsubr (&Smessage_or_box);
3941 defsubr (&Scurrent_message);
3942 defsubr (&Sformat);
3944 defsubr (&Sinsert_buffer_substring);
3945 defsubr (&Scompare_buffer_substrings);
3946 defsubr (&Ssubst_char_in_region);
3947 defsubr (&Stranslate_region);
3948 defsubr (&Sdelete_region);
3949 defsubr (&Sdelete_and_extract_region);
3950 defsubr (&Swiden);
3951 defsubr (&Snarrow_to_region);
3952 defsubr (&Ssave_restriction);
3953 defsubr (&Stranspose_regions);