(Fkeymap_parent): Undefined autoload -> 1.
[emacs.git] / src / editfns.c
blob4f7a7c7db1f644b4f0f95ddb4b3ee19fdeada9c0
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 && !char_property_eq (Qfield, new_pos, old_pos)
616 && (NILP (inhibit_capture_property)
617 || NILP (Fget_char_property(old_pos, inhibit_capture_property, Qnil))))
618 /* NEW_POS is not within the same field as OLD_POS; try to
619 move NEW_POS so that it is. */
621 int fwd, shortage;
622 Lisp_Object field_bound;
624 CHECK_NUMBER_COERCE_MARKER (new_pos, 0);
625 CHECK_NUMBER_COERCE_MARKER (old_pos, 0);
627 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
629 if (fwd)
630 field_bound = Ffield_end (old_pos, escape_from_edge);
631 else
632 field_bound = Ffield_beginning (old_pos, escape_from_edge);
634 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
635 other side of NEW_POS, which would mean that NEW_POS is
636 already acceptable, and it's not necessary to constrain it
637 to FIELD_BOUND. */
638 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
639 /* NEW_POS should be constrained, but only if either
640 ONLY_IN_LINE is nil (in which case any constraint is OK),
641 or NEW_POS and FIELD_BOUND are on the same line (in which
642 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
643 && (NILP (only_in_line)
644 /* This is the ONLY_IN_LINE case, check that NEW_POS and
645 FIELD_BOUND are on the same line by seeing whether
646 there's an intervening newline or not. */
647 || (scan_buffer ('\n',
648 XFASTINT (new_pos), XFASTINT (field_bound),
649 fwd ? -1 : 1, &shortage, 1),
650 shortage != 0)))
651 /* Constrain NEW_POS to FIELD_BOUND. */
652 new_pos = field_bound;
654 if (orig_point && XFASTINT (new_pos) != orig_point)
655 /* The NEW_POS argument was originally nil, so automatically set PT. */
656 SET_PT (XFASTINT (new_pos));
659 return new_pos;
663 DEFUN ("line-beginning-position", Fline_beginning_position, Sline_beginning_position,
664 0, 1, 0,
665 "Return the character position of the first character on the current line.\n\
666 With argument N not nil or 1, move forward N - 1 lines first.\n\
667 If scan reaches end of buffer, return that position.\n\
668 The scan does not cross a field boundary unless it would move\n\
669 beyond there to a different line. Field boundaries are not noticed if\n\
670 `inhibit-field-text-motion' is non-nil. .And if N is nil or 1,\n\
671 and scan starts at a field boundary, the scan stops as soon as it starts.\n\
673 This function does not move point.")
675 Lisp_Object n;
677 int orig, orig_byte, end;
679 if (NILP (n))
680 XSETFASTINT (n, 1);
681 else
682 CHECK_NUMBER (n, 0);
684 orig = PT;
685 orig_byte = PT_BYTE;
686 Fforward_line (make_number (XINT (n) - 1));
687 end = PT;
689 SET_PT_BOTH (orig, orig_byte);
691 /* Return END constrained to the current input field. */
692 return Fconstrain_to_field (make_number (end), make_number (orig),
693 XINT (n) != 1 ? Qt : Qnil,
694 Qt, Qnil);
697 DEFUN ("line-end-position", Fline_end_position, Sline_end_position,
698 0, 1, 0,
699 "Return the character position of the last character on the current line.\n\
700 With argument N not nil or 1, move forward N - 1 lines first.\n\
701 If scan reaches end of buffer, return that position.\n\
702 This function does not move point.")
704 Lisp_Object n;
706 int end_pos;
707 int orig = PT;
709 if (NILP (n))
710 XSETFASTINT (n, 1);
711 else
712 CHECK_NUMBER (n, 0);
714 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
716 /* Return END_POS constrained to the current input field. */
717 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
718 Qnil, Qt, Qnil);
721 Lisp_Object
722 save_excursion_save ()
724 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
725 == current_buffer);
727 return Fcons (Fpoint_marker (),
728 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
729 Fcons (visible ? Qt : Qnil,
730 Fcons (current_buffer->mark_active,
731 selected_window))));
734 Lisp_Object
735 save_excursion_restore (info)
736 Lisp_Object info;
738 Lisp_Object tem, tem1, omark, nmark;
739 struct gcpro gcpro1, gcpro2, gcpro3;
740 int visible_p;
742 tem = Fmarker_buffer (XCAR (info));
743 /* If buffer being returned to is now deleted, avoid error */
744 /* Otherwise could get error here while unwinding to top level
745 and crash */
746 /* In that case, Fmarker_buffer returns nil now. */
747 if (NILP (tem))
748 return Qnil;
750 omark = nmark = Qnil;
751 GCPRO3 (info, omark, nmark);
753 Fset_buffer (tem);
755 /* Point marker. */
756 tem = XCAR (info);
757 Fgoto_char (tem);
758 unchain_marker (tem);
760 /* Mark marker. */
761 info = XCDR (info);
762 tem = XCAR (info);
763 omark = Fmarker_position (current_buffer->mark);
764 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
765 nmark = Fmarker_position (tem);
766 unchain_marker (tem);
768 /* visible */
769 info = XCDR (info);
770 visible_p = !NILP (XCAR (info));
772 #if 0 /* We used to make the current buffer visible in the selected window
773 if that was true previously. That avoids some anomalies.
774 But it creates others, and it wasn't documented, and it is simpler
775 and cleaner never to alter the window/buffer connections. */
776 tem1 = Fcar (tem);
777 if (!NILP (tem1)
778 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
779 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
780 #endif /* 0 */
782 /* Mark active */
783 info = XCDR (info);
784 tem = XCAR (info);
785 tem1 = current_buffer->mark_active;
786 current_buffer->mark_active = tem;
788 if (!NILP (Vrun_hooks))
790 /* If mark is active now, and either was not active
791 or was at a different place, run the activate hook. */
792 if (! NILP (current_buffer->mark_active))
794 if (! EQ (omark, nmark))
795 call1 (Vrun_hooks, intern ("activate-mark-hook"));
797 /* If mark has ceased to be active, run deactivate hook. */
798 else if (! NILP (tem1))
799 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
802 /* If buffer was visible in a window, and a different window was
803 selected, and the old selected window is still live, restore
804 point in that window. */
805 tem = XCDR (info);
806 if (visible_p
807 && !EQ (tem, selected_window)
808 && !NILP (Fwindow_live_p (tem)))
809 Fset_window_point (tem, make_number (PT));
811 UNGCPRO;
812 return Qnil;
815 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
816 "Save point, mark, and current buffer; execute BODY; restore those things.\n\
817 Executes BODY just like `progn'.\n\
818 The values of point, mark and the current buffer are restored\n\
819 even in case of abnormal exit (throw or error).\n\
820 The state of activation of the mark is also restored.\n\
822 This construct does not save `deactivate-mark', and therefore\n\
823 functions that change the buffer will still cause deactivation\n\
824 of the mark at the end of the command. To prevent that, bind\n\
825 `deactivate-mark' with `let'.")
826 (args)
827 Lisp_Object args;
829 register Lisp_Object val;
830 int count = specpdl_ptr - specpdl;
832 record_unwind_protect (save_excursion_restore, save_excursion_save ());
834 val = Fprogn (args);
835 return unbind_to (count, val);
838 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
839 "Save the current buffer; execute BODY; restore the current buffer.\n\
840 Executes BODY just like `progn'.")
841 (args)
842 Lisp_Object args;
844 Lisp_Object val;
845 int count = specpdl_ptr - specpdl;
847 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
849 val = Fprogn (args);
850 return unbind_to (count, val);
853 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
854 "Return the number of characters in the current buffer.\n\
855 If BUFFER, return the number of characters in that buffer instead.")
856 (buffer)
857 Lisp_Object buffer;
859 if (NILP (buffer))
860 return make_number (Z - BEG);
861 else
863 CHECK_BUFFER (buffer, 1);
864 return make_number (BUF_Z (XBUFFER (buffer))
865 - BUF_BEG (XBUFFER (buffer)));
869 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
870 "Return the minimum permissible value of point in the current buffer.\n\
871 This is 1, unless narrowing (a buffer restriction) is in effect.")
874 Lisp_Object temp;
875 XSETFASTINT (temp, BEGV);
876 return temp;
879 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
880 "Return a marker to the minimum permissible value of point in this buffer.\n\
881 This is the beginning, unless narrowing (a buffer restriction) is in effect.")
884 return buildmark (BEGV, BEGV_BYTE);
887 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
888 "Return the maximum permissible value of point in the current buffer.\n\
889 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
890 is in effect, in which case it is less.")
893 Lisp_Object temp;
894 XSETFASTINT (temp, ZV);
895 return temp;
898 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
899 "Return a marker to the maximum permissible value of point in this buffer.\n\
900 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
901 is in effect, in which case it is less.")
904 return buildmark (ZV, ZV_BYTE);
907 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
908 "Return the position of the gap, in the current buffer.\n\
909 See also `gap-size'.")
912 Lisp_Object temp;
913 XSETFASTINT (temp, GPT);
914 return temp;
917 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
918 "Return the size of the current buffer's gap.\n\
919 See also `gap-position'.")
922 Lisp_Object temp;
923 XSETFASTINT (temp, GAP_SIZE);
924 return temp;
927 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
928 "Return the byte position for character position POSITION.\n\
929 If POSITION is out of range, the value is nil.")
930 (position)
931 Lisp_Object position;
933 CHECK_NUMBER_COERCE_MARKER (position, 1);
934 if (XINT (position) < BEG || XINT (position) > Z)
935 return Qnil;
936 return make_number (CHAR_TO_BYTE (XINT (position)));
939 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
940 "Return the character position for byte position BYTEPOS.\n\
941 If BYTEPOS is out of range, the value is nil.")
942 (bytepos)
943 Lisp_Object bytepos;
945 CHECK_NUMBER (bytepos, 1);
946 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
947 return Qnil;
948 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
951 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
952 "Return the character following point, as a number.\n\
953 At the end of the buffer or accessible region, return 0.")
956 Lisp_Object temp;
957 if (PT >= ZV)
958 XSETFASTINT (temp, 0);
959 else
960 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
961 return temp;
964 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
965 "Return the character preceding point, as a number.\n\
966 At the beginning of the buffer or accessible region, return 0.")
969 Lisp_Object temp;
970 if (PT <= BEGV)
971 XSETFASTINT (temp, 0);
972 else if (!NILP (current_buffer->enable_multibyte_characters))
974 int pos = PT_BYTE;
975 DEC_POS (pos);
976 XSETFASTINT (temp, FETCH_CHAR (pos));
978 else
979 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
980 return temp;
983 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
984 "Return t if point is at the beginning of the buffer.\n\
985 If the buffer is narrowed, this means the beginning of the narrowed part.")
988 if (PT == BEGV)
989 return Qt;
990 return Qnil;
993 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
994 "Return t if point is at the end of the buffer.\n\
995 If the buffer is narrowed, this means the end of the narrowed part.")
998 if (PT == ZV)
999 return Qt;
1000 return Qnil;
1003 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1004 "Return t if point is at the beginning of a line.")
1007 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1008 return Qt;
1009 return Qnil;
1012 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1013 "Return t if point is at the end of a line.\n\
1014 `End of a line' includes point being at the end of the buffer.")
1017 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1018 return Qt;
1019 return Qnil;
1022 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1023 "Return character in current buffer at position POS.\n\
1024 POS is an integer or a marker.\n\
1025 If POS is out of range, the value is nil.")
1026 (pos)
1027 Lisp_Object pos;
1029 register int pos_byte;
1031 if (NILP (pos))
1033 pos_byte = PT_BYTE;
1034 XSETFASTINT (pos, PT);
1037 if (MARKERP (pos))
1039 pos_byte = marker_byte_position (pos);
1040 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1041 return Qnil;
1043 else
1045 CHECK_NUMBER_COERCE_MARKER (pos, 0);
1046 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1047 return Qnil;
1049 pos_byte = CHAR_TO_BYTE (XINT (pos));
1052 return make_number (FETCH_CHAR (pos_byte));
1055 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1056 "Return character in current buffer preceding position POS.\n\
1057 POS is an integer or a marker.\n\
1058 If POS is out of range, the value is nil.")
1059 (pos)
1060 Lisp_Object pos;
1062 register Lisp_Object val;
1063 register int pos_byte;
1065 if (NILP (pos))
1067 pos_byte = PT_BYTE;
1068 XSETFASTINT (pos, PT);
1071 if (MARKERP (pos))
1073 pos_byte = marker_byte_position (pos);
1075 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1076 return Qnil;
1078 else
1080 CHECK_NUMBER_COERCE_MARKER (pos, 0);
1082 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1083 return Qnil;
1085 pos_byte = CHAR_TO_BYTE (XINT (pos));
1088 if (!NILP (current_buffer->enable_multibyte_characters))
1090 DEC_POS (pos_byte);
1091 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1093 else
1095 pos_byte--;
1096 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1098 return val;
1101 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1102 "Return the name under which the user logged in, as a string.\n\
1103 This is based on the effective uid, not the real uid.\n\
1104 Also, if the environment variable LOGNAME or USER is set,\n\
1105 that determines the value of this function.\n\n\
1106 If optional argument UID is an integer, return the login name of the user\n\
1107 with that uid, or nil if there is no such user.")
1108 (uid)
1109 Lisp_Object uid;
1111 struct passwd *pw;
1113 /* Set up the user name info if we didn't do it before.
1114 (That can happen if Emacs is dumpable
1115 but you decide to run `temacs -l loadup' and not dump. */
1116 if (INTEGERP (Vuser_login_name))
1117 init_editfns ();
1119 if (NILP (uid))
1120 return Vuser_login_name;
1122 CHECK_NUMBER (uid, 0);
1123 pw = (struct passwd *) getpwuid (XINT (uid));
1124 return (pw ? build_string (pw->pw_name) : Qnil);
1127 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1128 0, 0, 0,
1129 "Return the name of the user's real uid, as a string.\n\
1130 This ignores the environment variables LOGNAME and USER, so it differs from\n\
1131 `user-login-name' when running under `su'.")
1134 /* Set up the user name info if we didn't do it before.
1135 (That can happen if Emacs is dumpable
1136 but you decide to run `temacs -l loadup' and not dump. */
1137 if (INTEGERP (Vuser_login_name))
1138 init_editfns ();
1139 return Vuser_real_login_name;
1142 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1143 "Return the effective uid of Emacs, as an integer.")
1146 return make_number (geteuid ());
1149 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1150 "Return the real uid of Emacs, as an integer.")
1153 return make_number (getuid ());
1156 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1157 "Return the full name of the user logged in, as a string.\n\
1158 If the full name corresponding to Emacs's userid is not known,\n\
1159 return \"unknown\".\n\
1161 If optional argument UID is an integer, return the full name of the user\n\
1162 with that uid, or nil if there is no such user.\n\
1163 If UID is a string, return the full name of the user with that login\n\
1164 name, or nil if there is no such user.")
1165 (uid)
1166 Lisp_Object uid;
1168 struct passwd *pw;
1169 register unsigned char *p, *q;
1170 Lisp_Object full;
1172 if (NILP (uid))
1173 return Vuser_full_name;
1174 else if (NUMBERP (uid))
1175 pw = (struct passwd *) getpwuid (XINT (uid));
1176 else if (STRINGP (uid))
1177 pw = (struct passwd *) getpwnam (XSTRING (uid)->data);
1178 else
1179 error ("Invalid UID specification");
1181 if (!pw)
1182 return Qnil;
1184 p = (unsigned char *) USER_FULL_NAME;
1185 /* Chop off everything after the first comma. */
1186 q = (unsigned char *) index (p, ',');
1187 full = make_string (p, q ? q - p : strlen (p));
1189 #ifdef AMPERSAND_FULL_NAME
1190 p = XSTRING (full)->data;
1191 q = (unsigned char *) index (p, '&');
1192 /* Substitute the login name for the &, upcasing the first character. */
1193 if (q)
1195 register unsigned char *r;
1196 Lisp_Object login;
1198 login = Fuser_login_name (make_number (pw->pw_uid));
1199 r = (unsigned char *) alloca (strlen (p) + XSTRING (login)->size + 1);
1200 bcopy (p, r, q - p);
1201 r[q - p] = 0;
1202 strcat (r, XSTRING (login)->data);
1203 r[q - p] = UPCASE (r[q - p]);
1204 strcat (r, q + 1);
1205 full = build_string (r);
1207 #endif /* AMPERSAND_FULL_NAME */
1209 return full;
1212 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1213 "Return the name of the machine you are running on, as a string.")
1216 return Vsystem_name;
1219 /* For the benefit of callers who don't want to include lisp.h */
1221 char *
1222 get_system_name ()
1224 if (STRINGP (Vsystem_name))
1225 return (char *) XSTRING (Vsystem_name)->data;
1226 else
1227 return "";
1230 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1231 "Return the process ID of Emacs, as an integer.")
1234 return make_number (getpid ());
1237 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1238 "Return the current time, as the number of seconds since 1970-01-01 00:00:00.\n\
1239 The time is returned as a list of three integers. The first has the\n\
1240 most significant 16 bits of the seconds, while the second has the\n\
1241 least significant 16 bits. The third integer gives the microsecond\n\
1242 count.\n\
1244 The microsecond count is zero on systems that do not provide\n\
1245 resolution finer than a second.")
1248 EMACS_TIME t;
1249 Lisp_Object result[3];
1251 EMACS_GET_TIME (t);
1252 XSETINT (result[0], (EMACS_SECS (t) >> 16) & 0xffff);
1253 XSETINT (result[1], (EMACS_SECS (t) >> 0) & 0xffff);
1254 XSETINT (result[2], EMACS_USECS (t));
1256 return Flist (3, result);
1260 static int
1261 lisp_time_argument (specified_time, result, usec)
1262 Lisp_Object specified_time;
1263 time_t *result;
1264 int *usec;
1266 if (NILP (specified_time))
1268 if (usec)
1270 EMACS_TIME t;
1272 EMACS_GET_TIME (t);
1273 *usec = EMACS_USECS (t);
1274 *result = EMACS_SECS (t);
1275 return 1;
1277 else
1278 return time (result) != -1;
1280 else
1282 Lisp_Object high, low;
1283 high = Fcar (specified_time);
1284 CHECK_NUMBER (high, 0);
1285 low = Fcdr (specified_time);
1286 if (CONSP (low))
1288 if (usec)
1290 Lisp_Object usec_l = Fcdr (low);
1291 if (CONSP (usec_l))
1292 usec_l = Fcar (usec_l);
1293 if (NILP (usec_l))
1294 *usec = 0;
1295 else
1297 CHECK_NUMBER (usec_l, 0);
1298 *usec = XINT (usec_l);
1301 low = Fcar (low);
1303 else if (usec)
1304 *usec = 0;
1305 CHECK_NUMBER (low, 0);
1306 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1307 return *result >> 16 == XINT (high);
1311 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1312 "Return the current time, as a float number of seconds since the epoch.\n\
1313 If an argument is given, it specifies a time to convert to float\n\
1314 instead of the current time. The argument should have the forms:\n\
1315 (HIGH . LOW) or (HIGH LOW USEC) or (HIGH LOW . USEC).\n\
1316 Thus, you can use times obtained from `current-time'\n\
1317 and from `file-attributes'.")
1318 (specified_time)
1319 Lisp_Object specified_time;
1321 time_t sec;
1322 int usec;
1324 if (! lisp_time_argument (specified_time, &sec, &usec))
1325 error ("Invalid time specification");
1327 return make_float (sec + usec * 0.0000001);
1330 /* Write information into buffer S of size MAXSIZE, according to the
1331 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1332 Default to Universal Time if UT is nonzero, local time otherwise.
1333 Return the number of bytes written, not including the terminating
1334 '\0'. If S is NULL, nothing will be written anywhere; so to
1335 determine how many bytes would be written, use NULL for S and
1336 ((size_t) -1) for MAXSIZE.
1338 This function behaves like emacs_strftimeu, except it allows null
1339 bytes in FORMAT. */
1340 static size_t
1341 emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
1342 char *s;
1343 size_t maxsize;
1344 const char *format;
1345 size_t format_len;
1346 const struct tm *tp;
1347 int ut;
1349 size_t total = 0;
1351 /* Loop through all the null-terminated strings in the format
1352 argument. Normally there's just one null-terminated string, but
1353 there can be arbitrarily many, concatenated together, if the
1354 format contains '\0' bytes. emacs_strftimeu stops at the first
1355 '\0' byte so we must invoke it separately for each such string. */
1356 for (;;)
1358 size_t len;
1359 size_t result;
1361 if (s)
1362 s[0] = '\1';
1364 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1366 if (s)
1368 if (result == 0 && s[0] != '\0')
1369 return 0;
1370 s += result + 1;
1373 maxsize -= result + 1;
1374 total += result;
1375 len = strlen (format);
1376 if (len == format_len)
1377 return total;
1378 total++;
1379 format += len + 1;
1380 format_len -= len + 1;
1385 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1386 "Use FORMAT-STRING to format the time TIME, or now if omitted.\n\
1387 TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as returned by\n\
1388 `current-time' or `file-attributes'.\n\
1389 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME\n\
1390 as Universal Time; nil means describe TIME in the local time zone.\n\
1391 The value is a copy of FORMAT-STRING, but with certain constructs replaced\n\
1392 by text that describes the specified date and time in TIME:\n\
1394 %Y is the year, %y within the century, %C the century.\n\
1395 %G is the year corresponding to the ISO week, %g within the century.\n\
1396 %m is the numeric month.\n\
1397 %b and %h are the locale's abbreviated month name, %B the full name.\n\
1398 %d is the day of the month, zero-padded, %e is blank-padded.\n\
1399 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.\n\
1400 %a is the locale's abbreviated name of the day of week, %A the full name.\n\
1401 %U is the week number starting on Sunday, %W starting on Monday,\n\
1402 %V according to ISO 8601.\n\
1403 %j is the day of the year.\n\
1405 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H\n\
1406 only blank-padded, %l is like %I blank-padded.\n\
1407 %p is the locale's equivalent of either AM or PM.\n\
1408 %M is the minute.\n\
1409 %S is the second.\n\
1410 %Z is the time zone name, %z is the numeric form.\n\
1411 %s is the number of seconds since 1970-01-01 00:00:00 +0000.\n\
1413 %c is the locale's date and time format.\n\
1414 %x is the locale's \"preferred\" date format.\n\
1415 %D is like \"%m/%d/%y\".\n\
1417 %R is like \"%H:%M\", %T is like \"%H:%M:%S\", %r is like \"%I:%M:%S %p\".\n\
1418 %X is the locale's \"preferred\" time format.\n\
1420 Finally, %n is a newline, %t is a tab, %% is a literal %.\n\
1422 Certain flags and modifiers are available with some format controls.\n\
1423 The flags are `_' and `-'. For certain characters X, %_X is like %X,\n\
1424 but padded with blanks; %-X is like %X, but without padding.\n\
1425 %NX (where N stands for an integer) is like %X,\n\
1426 but takes up at least N (a number) positions.\n\
1427 The modifiers are `E' and `O'. For certain characters X,\n\
1428 %EX is a locale's alternative version of %X;\n\
1429 %OX is like %X, but uses the locale's number symbols.\n\
1431 For example, to produce full ISO 8601 format, use \"%Y-%m-%dT%T%z\".")
1432 (format_string, time, universal)
1435 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1436 0 /* See immediately above */)
1437 (format_string, time, universal)
1438 Lisp_Object format_string, time, universal;
1440 time_t value;
1441 int size;
1442 struct tm *tm;
1443 int ut = ! NILP (universal);
1445 CHECK_STRING (format_string, 1);
1447 if (! lisp_time_argument (time, &value, NULL))
1448 error ("Invalid time specification");
1450 format_string = code_convert_string_norecord (format_string,
1451 Vlocale_coding_system, 1);
1453 /* This is probably enough. */
1454 size = STRING_BYTES (XSTRING (format_string)) * 6 + 50;
1456 tm = ut ? gmtime (&value) : localtime (&value);
1457 if (! tm)
1458 error ("Specified time is not representable");
1460 synchronize_system_time_locale ();
1462 while (1)
1464 char *buf = (char *) alloca (size + 1);
1465 int result;
1467 buf[0] = '\1';
1468 result = emacs_memftimeu (buf, size, XSTRING (format_string)->data,
1469 STRING_BYTES (XSTRING (format_string)),
1470 tm, ut);
1471 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1472 return code_convert_string_norecord (make_string (buf, result),
1473 Vlocale_coding_system, 0);
1475 /* If buffer was too small, make it bigger and try again. */
1476 result = emacs_memftimeu (NULL, (size_t) -1,
1477 XSTRING (format_string)->data,
1478 STRING_BYTES (XSTRING (format_string)),
1479 tm, ut);
1480 size = result + 1;
1484 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1485 "Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).\n\
1486 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED)\n\
1487 or (HIGH . LOW), as from `current-time' and `file-attributes', or `nil'\n\
1488 to use the current time. The list has the following nine members:\n\
1489 SEC is an integer between 0 and 60; SEC is 60 for a leap second, which\n\
1490 only some operating systems support. MINUTE is an integer between 0 and 59.\n\
1491 HOUR is an integer between 0 and 23. DAY is an integer between 1 and 31.\n\
1492 MONTH is an integer between 1 and 12. YEAR is an integer indicating the\n\
1493 four-digit year. DOW is the day of week, an integer between 0 and 6, where\n\
1494 0 is Sunday. DST is t if daylight savings time is effect, otherwise nil.\n\
1495 ZONE is an integer indicating the number of seconds east of Greenwich.\n\
1496 \(Note that Common Lisp has different meanings for DOW and ZONE.)")
1497 (specified_time)
1498 Lisp_Object specified_time;
1500 time_t time_spec;
1501 struct tm save_tm;
1502 struct tm *decoded_time;
1503 Lisp_Object list_args[9];
1505 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1506 error ("Invalid time specification");
1508 decoded_time = localtime (&time_spec);
1509 if (! decoded_time)
1510 error ("Specified time is not representable");
1511 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1512 XSETFASTINT (list_args[1], decoded_time->tm_min);
1513 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1514 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1515 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1516 XSETINT (list_args[5], decoded_time->tm_year + 1900);
1517 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1518 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1520 /* Make a copy, in case gmtime modifies the struct. */
1521 save_tm = *decoded_time;
1522 decoded_time = gmtime (&time_spec);
1523 if (decoded_time == 0)
1524 list_args[8] = Qnil;
1525 else
1526 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1527 return Flist (9, list_args);
1530 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1531 "Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.\n\
1532 This is the reverse operation of `decode-time', which see.\n\
1533 ZONE defaults to the current time zone rule. This can\n\
1534 be a string or t (as from `set-time-zone-rule'), or it can be a list\n\
1535 \(as from `current-time-zone') or an integer (as from `decode-time')\n\
1536 applied without consideration for daylight savings time.\n\
1538 You can pass more than 7 arguments; then the first six arguments\n\
1539 are used as SECOND through YEAR, and the *last* argument is used as ZONE.\n\
1540 The intervening arguments are ignored.\n\
1541 This feature lets (apply 'encode-time (decode-time ...)) work.\n\
1543 Out-of-range values for SEC, MINUTE, HOUR, DAY, or MONTH are allowed;\n\
1544 for example, a DAY of 0 means the day preceding the given month.\n\
1545 Year numbers less than 100 are treated just like other year numbers.\n\
1546 If you want them to stand for years in this century, you must do that yourself.")
1547 (nargs, args)
1548 int nargs;
1549 register Lisp_Object *args;
1551 time_t time;
1552 struct tm tm;
1553 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1555 CHECK_NUMBER (args[0], 0); /* second */
1556 CHECK_NUMBER (args[1], 1); /* minute */
1557 CHECK_NUMBER (args[2], 2); /* hour */
1558 CHECK_NUMBER (args[3], 3); /* day */
1559 CHECK_NUMBER (args[4], 4); /* month */
1560 CHECK_NUMBER (args[5], 5); /* year */
1562 tm.tm_sec = XINT (args[0]);
1563 tm.tm_min = XINT (args[1]);
1564 tm.tm_hour = XINT (args[2]);
1565 tm.tm_mday = XINT (args[3]);
1566 tm.tm_mon = XINT (args[4]) - 1;
1567 tm.tm_year = XINT (args[5]) - 1900;
1568 tm.tm_isdst = -1;
1570 if (CONSP (zone))
1571 zone = Fcar (zone);
1572 if (NILP (zone))
1573 time = mktime (&tm);
1574 else
1576 char tzbuf[100];
1577 char *tzstring;
1578 char **oldenv = environ, **newenv;
1580 if (EQ (zone, Qt))
1581 tzstring = "UTC0";
1582 else if (STRINGP (zone))
1583 tzstring = (char *) XSTRING (zone)->data;
1584 else if (INTEGERP (zone))
1586 int abszone = abs (XINT (zone));
1587 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1588 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1589 tzstring = tzbuf;
1591 else
1592 error ("Invalid time zone specification");
1594 /* Set TZ before calling mktime; merely adjusting mktime's returned
1595 value doesn't suffice, since that would mishandle leap seconds. */
1596 set_time_zone_rule (tzstring);
1598 time = mktime (&tm);
1600 /* Restore TZ to previous value. */
1601 newenv = environ;
1602 environ = oldenv;
1603 xfree (newenv);
1604 #ifdef LOCALTIME_CACHE
1605 tzset ();
1606 #endif
1609 if (time == (time_t) -1)
1610 error ("Specified time is not representable");
1612 return make_time (time);
1615 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1616 "Return the current time, as a human-readable string.\n\
1617 Programs can use this function to decode a time,\n\
1618 since the number of columns in each field is fixed.\n\
1619 The format is `Sun Sep 16 01:03:52 1973'.\n\
1620 However, see also the functions `decode-time' and `format-time-string'\n\
1621 which provide a much more powerful and general facility.\n\
1623 If an argument is given, it specifies a time to format\n\
1624 instead of the current time. The argument should have the form:\n\
1625 (HIGH . LOW)\n\
1626 or the form:\n\
1627 (HIGH LOW . IGNORED).\n\
1628 Thus, you can use times obtained from `current-time'\n\
1629 and from `file-attributes'.")
1630 (specified_time)
1631 Lisp_Object specified_time;
1633 time_t value;
1634 char buf[30];
1635 register char *tem;
1637 if (! lisp_time_argument (specified_time, &value, NULL))
1638 value = -1;
1639 tem = (char *) ctime (&value);
1641 strncpy (buf, tem, 24);
1642 buf[24] = 0;
1644 return build_string (buf);
1647 #define TM_YEAR_BASE 1900
1649 /* Yield A - B, measured in seconds.
1650 This function is copied from the GNU C Library. */
1651 static int
1652 tm_diff (a, b)
1653 struct tm *a, *b;
1655 /* Compute intervening leap days correctly even if year is negative.
1656 Take care to avoid int overflow in leap day calculations,
1657 but it's OK to assume that A and B are close to each other. */
1658 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1659 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1660 int a100 = a4 / 25 - (a4 % 25 < 0);
1661 int b100 = b4 / 25 - (b4 % 25 < 0);
1662 int a400 = a100 >> 2;
1663 int b400 = b100 >> 2;
1664 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1665 int years = a->tm_year - b->tm_year;
1666 int days = (365 * years + intervening_leap_days
1667 + (a->tm_yday - b->tm_yday));
1668 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1669 + (a->tm_min - b->tm_min))
1670 + (a->tm_sec - b->tm_sec));
1673 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1674 "Return the offset and name for the local time zone.\n\
1675 This returns a list of the form (OFFSET NAME).\n\
1676 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).\n\
1677 A negative value means west of Greenwich.\n\
1678 NAME is a string giving the name of the time zone.\n\
1679 If an argument is given, it specifies when the time zone offset is determined\n\
1680 instead of using the current time. The argument should have the form:\n\
1681 (HIGH . LOW)\n\
1682 or the form:\n\
1683 (HIGH LOW . IGNORED).\n\
1684 Thus, you can use times obtained from `current-time'\n\
1685 and from `file-attributes'.\n\
1687 Some operating systems cannot provide all this information to Emacs;\n\
1688 in this case, `current-time-zone' returns a list containing nil for\n\
1689 the data it can't find.")
1690 (specified_time)
1691 Lisp_Object specified_time;
1693 time_t value;
1694 struct tm *t;
1695 struct tm gmt;
1697 if (lisp_time_argument (specified_time, &value, NULL)
1698 && (t = gmtime (&value)) != 0
1699 && (gmt = *t, t = localtime (&value)) != 0)
1701 int offset = tm_diff (t, &gmt);
1702 char *s = 0;
1703 char buf[6];
1704 #ifdef HAVE_TM_ZONE
1705 if (t->tm_zone)
1706 s = (char *)t->tm_zone;
1707 #else /* not HAVE_TM_ZONE */
1708 #ifdef HAVE_TZNAME
1709 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1710 s = tzname[t->tm_isdst];
1711 #endif
1712 #endif /* not HAVE_TM_ZONE */
1713 if (!s)
1715 /* No local time zone name is available; use "+-NNNN" instead. */
1716 int am = (offset < 0 ? -offset : offset) / 60;
1717 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1718 s = buf;
1720 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
1722 else
1723 return Fmake_list (make_number (2), Qnil);
1726 /* This holds the value of `environ' produced by the previous
1727 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
1728 has never been called. */
1729 static char **environbuf;
1731 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
1732 "Set the local time zone using TZ, a string specifying a time zone rule.\n\
1733 If TZ is nil, use implementation-defined default time zone information.\n\
1734 If TZ is t, use Universal Time.")
1735 (tz)
1736 Lisp_Object tz;
1738 char *tzstring;
1740 if (NILP (tz))
1741 tzstring = 0;
1742 else if (EQ (tz, Qt))
1743 tzstring = "UTC0";
1744 else
1746 CHECK_STRING (tz, 0);
1747 tzstring = (char *) XSTRING (tz)->data;
1750 set_time_zone_rule (tzstring);
1751 if (environbuf)
1752 free (environbuf);
1753 environbuf = environ;
1755 return Qnil;
1758 #ifdef LOCALTIME_CACHE
1760 /* These two values are known to load tz files in buggy implementations,
1761 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1762 Their values shouldn't matter in non-buggy implementations.
1763 We don't use string literals for these strings,
1764 since if a string in the environment is in readonly
1765 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
1766 See Sun bugs 1113095 and 1114114, ``Timezone routines
1767 improperly modify environment''. */
1769 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
1770 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
1772 #endif
1774 /* Set the local time zone rule to TZSTRING.
1775 This allocates memory into `environ', which it is the caller's
1776 responsibility to free. */
1778 void
1779 set_time_zone_rule (tzstring)
1780 char *tzstring;
1782 int envptrs;
1783 char **from, **to, **newenv;
1785 /* Make the ENVIRON vector longer with room for TZSTRING. */
1786 for (from = environ; *from; from++)
1787 continue;
1788 envptrs = from - environ + 2;
1789 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
1790 + (tzstring ? strlen (tzstring) + 4 : 0));
1792 /* Add TZSTRING to the end of environ, as a value for TZ. */
1793 if (tzstring)
1795 char *t = (char *) (to + envptrs);
1796 strcpy (t, "TZ=");
1797 strcat (t, tzstring);
1798 *to++ = t;
1801 /* Copy the old environ vector elements into NEWENV,
1802 but don't copy the TZ variable.
1803 So we have only one definition of TZ, which came from TZSTRING. */
1804 for (from = environ; *from; from++)
1805 if (strncmp (*from, "TZ=", 3) != 0)
1806 *to++ = *from;
1807 *to = 0;
1809 environ = newenv;
1811 /* If we do have a TZSTRING, NEWENV points to the vector slot where
1812 the TZ variable is stored. If we do not have a TZSTRING,
1813 TO points to the vector slot which has the terminating null. */
1815 #ifdef LOCALTIME_CACHE
1817 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
1818 "US/Pacific" that loads a tz file, then changes to a value like
1819 "XXX0" that does not load a tz file, and then changes back to
1820 its original value, the last change is (incorrectly) ignored.
1821 Also, if TZ changes twice in succession to values that do
1822 not load a tz file, tzset can dump core (see Sun bug#1225179).
1823 The following code works around these bugs. */
1825 if (tzstring)
1827 /* Temporarily set TZ to a value that loads a tz file
1828 and that differs from tzstring. */
1829 char *tz = *newenv;
1830 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
1831 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
1832 tzset ();
1833 *newenv = tz;
1835 else
1837 /* The implied tzstring is unknown, so temporarily set TZ to
1838 two different values that each load a tz file. */
1839 *to = set_time_zone_rule_tz1;
1840 to[1] = 0;
1841 tzset ();
1842 *to = set_time_zone_rule_tz2;
1843 tzset ();
1844 *to = 0;
1847 /* Now TZ has the desired value, and tzset can be invoked safely. */
1850 tzset ();
1851 #endif
1854 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
1855 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
1856 type of object is Lisp_String). INHERIT is passed to
1857 INSERT_FROM_STRING_FUNC as the last argument. */
1859 static void
1860 general_insert_function (insert_func, insert_from_string_func,
1861 inherit, nargs, args)
1862 void (*insert_func) P_ ((unsigned char *, int));
1863 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
1864 int inherit, nargs;
1865 register Lisp_Object *args;
1867 register int argnum;
1868 register Lisp_Object val;
1870 for (argnum = 0; argnum < nargs; argnum++)
1872 val = args[argnum];
1873 retry:
1874 if (INTEGERP (val))
1876 unsigned char str[MAX_MULTIBYTE_LENGTH];
1877 int len;
1879 if (!NILP (current_buffer->enable_multibyte_characters))
1880 len = CHAR_STRING (XFASTINT (val), str);
1881 else
1883 str[0] = (SINGLE_BYTE_CHAR_P (XINT (val))
1884 ? XINT (val)
1885 : multibyte_char_to_unibyte (XINT (val), Qnil));
1886 len = 1;
1888 (*insert_func) (str, len);
1890 else if (STRINGP (val))
1892 (*insert_from_string_func) (val, 0, 0,
1893 XSTRING (val)->size,
1894 STRING_BYTES (XSTRING (val)),
1895 inherit);
1897 else
1899 val = wrong_type_argument (Qchar_or_string_p, val);
1900 goto retry;
1905 void
1906 insert1 (arg)
1907 Lisp_Object arg;
1909 Finsert (1, &arg);
1913 /* Callers passing one argument to Finsert need not gcpro the
1914 argument "array", since the only element of the array will
1915 not be used after calling insert or insert_from_string, so
1916 we don't care if it gets trashed. */
1918 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
1919 "Insert the arguments, either strings or characters, at point.\n\
1920 Point and before-insertion markers move forward to end up\n\
1921 after the inserted text.\n\
1922 Any other markers at the point of insertion remain before the text.\n\
1924 If the current buffer is multibyte, unibyte strings are converted\n\
1925 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1926 If the current buffer is unibyte, multibyte strings are converted\n\
1927 to unibyte for insertion.")
1928 (nargs, args)
1929 int nargs;
1930 register Lisp_Object *args;
1932 general_insert_function (insert, insert_from_string, 0, nargs, args);
1933 return Qnil;
1936 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
1937 0, MANY, 0,
1938 "Insert the arguments at point, inheriting properties from adjoining text.\n\
1939 Point and before-insertion markers move forward to end up\n\
1940 after the inserted text.\n\
1941 Any other markers at the point of insertion remain before the text.\n\
1943 If the current buffer is multibyte, unibyte strings are converted\n\
1944 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1945 If the current buffer is unibyte, multibyte strings are converted\n\
1946 to unibyte for insertion.")
1947 (nargs, args)
1948 int nargs;
1949 register Lisp_Object *args;
1951 general_insert_function (insert_and_inherit, insert_from_string, 1,
1952 nargs, args);
1953 return Qnil;
1956 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
1957 "Insert strings or characters at point, relocating markers after the text.\n\
1958 Point and markers move forward to end up after the inserted text.\n\
1960 If the current buffer is multibyte, unibyte strings are converted\n\
1961 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1962 If the current buffer is unibyte, multibyte strings are converted\n\
1963 to unibyte for insertion.")
1964 (nargs, args)
1965 int nargs;
1966 register Lisp_Object *args;
1968 general_insert_function (insert_before_markers,
1969 insert_from_string_before_markers, 0,
1970 nargs, args);
1971 return Qnil;
1974 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
1975 Sinsert_and_inherit_before_markers, 0, MANY, 0,
1976 "Insert text at point, relocating markers and inheriting properties.\n\
1977 Point and markers move forward to end up after the inserted text.\n\
1979 If the current buffer is multibyte, unibyte strings are converted\n\
1980 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1981 If the current buffer is unibyte, multibyte strings are converted\n\
1982 to unibyte for insertion.")
1983 (nargs, args)
1984 int nargs;
1985 register Lisp_Object *args;
1987 general_insert_function (insert_before_markers_and_inherit,
1988 insert_from_string_before_markers, 1,
1989 nargs, args);
1990 return Qnil;
1993 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
1994 "Insert COUNT (second arg) copies of CHARACTER (first arg).\n\
1995 Both arguments are required.\n\
1996 Point, and before-insertion markers, are relocated as in the function `insert'.\n\
1997 The optional third arg INHERIT, if non-nil, says to inherit text properties\n\
1998 from adjoining text, if those properties are sticky.")
1999 (character, count, inherit)
2000 Lisp_Object character, count, inherit;
2002 register unsigned char *string;
2003 register int strlen;
2004 register int i, n;
2005 int len;
2006 unsigned char str[MAX_MULTIBYTE_LENGTH];
2008 CHECK_NUMBER (character, 0);
2009 CHECK_NUMBER (count, 1);
2011 if (!NILP (current_buffer->enable_multibyte_characters))
2012 len = CHAR_STRING (XFASTINT (character), str);
2013 else
2014 str[0] = XFASTINT (character), len = 1;
2015 n = XINT (count) * len;
2016 if (n <= 0)
2017 return Qnil;
2018 strlen = min (n, 256 * len);
2019 string = (unsigned char *) alloca (strlen);
2020 for (i = 0; i < strlen; i++)
2021 string[i] = str[i % len];
2022 while (n >= strlen)
2024 QUIT;
2025 if (!NILP (inherit))
2026 insert_and_inherit (string, strlen);
2027 else
2028 insert (string, strlen);
2029 n -= strlen;
2031 if (n > 0)
2033 if (!NILP (inherit))
2034 insert_and_inherit (string, n);
2035 else
2036 insert (string, n);
2038 return Qnil;
2042 /* Making strings from buffer contents. */
2044 /* Return a Lisp_String containing the text of the current buffer from
2045 START to END. If text properties are in use and the current buffer
2046 has properties in the range specified, the resulting string will also
2047 have them, if PROPS is nonzero.
2049 We don't want to use plain old make_string here, because it calls
2050 make_uninit_string, which can cause the buffer arena to be
2051 compacted. make_string has no way of knowing that the data has
2052 been moved, and thus copies the wrong data into the string. This
2053 doesn't effect most of the other users of make_string, so it should
2054 be left as is. But we should use this function when conjuring
2055 buffer substrings. */
2057 Lisp_Object
2058 make_buffer_string (start, end, props)
2059 int start, end;
2060 int props;
2062 int start_byte = CHAR_TO_BYTE (start);
2063 int end_byte = CHAR_TO_BYTE (end);
2065 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2068 /* Return a Lisp_String containing the text of the current buffer from
2069 START / START_BYTE to END / END_BYTE.
2071 If text properties are in use and the current buffer
2072 has properties in the range specified, the resulting string will also
2073 have them, if PROPS is nonzero.
2075 We don't want to use plain old make_string here, because it calls
2076 make_uninit_string, which can cause the buffer arena to be
2077 compacted. make_string has no way of knowing that the data has
2078 been moved, and thus copies the wrong data into the string. This
2079 doesn't effect most of the other users of make_string, so it should
2080 be left as is. But we should use this function when conjuring
2081 buffer substrings. */
2083 Lisp_Object
2084 make_buffer_string_both (start, start_byte, end, end_byte, props)
2085 int start, start_byte, end, end_byte;
2086 int props;
2088 Lisp_Object result, tem, tem1;
2090 if (start < GPT && GPT < end)
2091 move_gap (start);
2093 if (! NILP (current_buffer->enable_multibyte_characters))
2094 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2095 else
2096 result = make_uninit_string (end - start);
2097 bcopy (BYTE_POS_ADDR (start_byte), XSTRING (result)->data,
2098 end_byte - start_byte);
2100 /* If desired, update and copy the text properties. */
2101 if (props)
2103 update_buffer_properties (start, end);
2105 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2106 tem1 = Ftext_properties_at (make_number (start), Qnil);
2108 if (XINT (tem) != end || !NILP (tem1))
2109 copy_intervals_to_string (result, current_buffer, start,
2110 end - start);
2113 return result;
2116 /* Call Vbuffer_access_fontify_functions for the range START ... END
2117 in the current buffer, if necessary. */
2119 static void
2120 update_buffer_properties (start, end)
2121 int start, end;
2123 /* If this buffer has some access functions,
2124 call them, specifying the range of the buffer being accessed. */
2125 if (!NILP (Vbuffer_access_fontify_functions))
2127 Lisp_Object args[3];
2128 Lisp_Object tem;
2130 args[0] = Qbuffer_access_fontify_functions;
2131 XSETINT (args[1], start);
2132 XSETINT (args[2], end);
2134 /* But don't call them if we can tell that the work
2135 has already been done. */
2136 if (!NILP (Vbuffer_access_fontified_property))
2138 tem = Ftext_property_any (args[1], args[2],
2139 Vbuffer_access_fontified_property,
2140 Qnil, Qnil);
2141 if (! NILP (tem))
2142 Frun_hook_with_args (3, args);
2144 else
2145 Frun_hook_with_args (3, args);
2149 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2150 "Return the contents of part of the current buffer as a string.\n\
2151 The two arguments START and END are character positions;\n\
2152 they can be in either order.\n\
2153 The string returned is multibyte if the buffer is multibyte.")
2154 (start, end)
2155 Lisp_Object start, end;
2157 register int b, e;
2159 validate_region (&start, &end);
2160 b = XINT (start);
2161 e = XINT (end);
2163 return make_buffer_string (b, e, 1);
2166 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2167 Sbuffer_substring_no_properties, 2, 2, 0,
2168 "Return the characters of part of the buffer, without the text properties.\n\
2169 The two arguments START and END are character positions;\n\
2170 they can be in either order.")
2171 (start, end)
2172 Lisp_Object start, end;
2174 register int b, e;
2176 validate_region (&start, &end);
2177 b = XINT (start);
2178 e = XINT (end);
2180 return make_buffer_string (b, e, 0);
2183 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2184 "Return the contents of the current buffer as a string.\n\
2185 If narrowing is in effect, this function returns only the visible part\n\
2186 of the buffer.")
2189 return make_buffer_string (BEGV, ZV, 1);
2192 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2193 1, 3, 0,
2194 "Insert before point a substring of the contents of buffer BUFFER.\n\
2195 BUFFER may be a buffer or a buffer name.\n\
2196 Arguments START and END are character numbers specifying the substring.\n\
2197 They default to the beginning and the end of BUFFER.")
2198 (buf, start, end)
2199 Lisp_Object buf, start, end;
2201 register int b, e, temp;
2202 register struct buffer *bp, *obuf;
2203 Lisp_Object buffer;
2205 buffer = Fget_buffer (buf);
2206 if (NILP (buffer))
2207 nsberror (buf);
2208 bp = XBUFFER (buffer);
2209 if (NILP (bp->name))
2210 error ("Selecting deleted buffer");
2212 if (NILP (start))
2213 b = BUF_BEGV (bp);
2214 else
2216 CHECK_NUMBER_COERCE_MARKER (start, 0);
2217 b = XINT (start);
2219 if (NILP (end))
2220 e = BUF_ZV (bp);
2221 else
2223 CHECK_NUMBER_COERCE_MARKER (end, 1);
2224 e = XINT (end);
2227 if (b > e)
2228 temp = b, b = e, e = temp;
2230 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2231 args_out_of_range (start, end);
2233 obuf = current_buffer;
2234 set_buffer_internal_1 (bp);
2235 update_buffer_properties (b, e);
2236 set_buffer_internal_1 (obuf);
2238 insert_from_buffer (bp, b, e - b, 0);
2239 return Qnil;
2242 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2243 6, 6, 0,
2244 "Compare two substrings of two buffers; return result as number.\n\
2245 the value is -N if first string is less after N-1 chars,\n\
2246 +N if first string is greater after N-1 chars, or 0 if strings match.\n\
2247 Each substring is represented as three arguments: BUFFER, START and END.\n\
2248 That makes six args in all, three for each substring.\n\n\
2249 The value of `case-fold-search' in the current buffer\n\
2250 determines whether case is significant or ignored.")
2251 (buffer1, start1, end1, buffer2, start2, end2)
2252 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2254 register int begp1, endp1, begp2, endp2, temp;
2255 register struct buffer *bp1, *bp2;
2256 register Lisp_Object *trt
2257 = (!NILP (current_buffer->case_fold_search)
2258 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents : 0);
2259 int chars = 0;
2260 int i1, i2, i1_byte, i2_byte;
2262 /* Find the first buffer and its substring. */
2264 if (NILP (buffer1))
2265 bp1 = current_buffer;
2266 else
2268 Lisp_Object buf1;
2269 buf1 = Fget_buffer (buffer1);
2270 if (NILP (buf1))
2271 nsberror (buffer1);
2272 bp1 = XBUFFER (buf1);
2273 if (NILP (bp1->name))
2274 error ("Selecting deleted buffer");
2277 if (NILP (start1))
2278 begp1 = BUF_BEGV (bp1);
2279 else
2281 CHECK_NUMBER_COERCE_MARKER (start1, 1);
2282 begp1 = XINT (start1);
2284 if (NILP (end1))
2285 endp1 = BUF_ZV (bp1);
2286 else
2288 CHECK_NUMBER_COERCE_MARKER (end1, 2);
2289 endp1 = XINT (end1);
2292 if (begp1 > endp1)
2293 temp = begp1, begp1 = endp1, endp1 = temp;
2295 if (!(BUF_BEGV (bp1) <= begp1
2296 && begp1 <= endp1
2297 && endp1 <= BUF_ZV (bp1)))
2298 args_out_of_range (start1, end1);
2300 /* Likewise for second substring. */
2302 if (NILP (buffer2))
2303 bp2 = current_buffer;
2304 else
2306 Lisp_Object buf2;
2307 buf2 = Fget_buffer (buffer2);
2308 if (NILP (buf2))
2309 nsberror (buffer2);
2310 bp2 = XBUFFER (buf2);
2311 if (NILP (bp2->name))
2312 error ("Selecting deleted buffer");
2315 if (NILP (start2))
2316 begp2 = BUF_BEGV (bp2);
2317 else
2319 CHECK_NUMBER_COERCE_MARKER (start2, 4);
2320 begp2 = XINT (start2);
2322 if (NILP (end2))
2323 endp2 = BUF_ZV (bp2);
2324 else
2326 CHECK_NUMBER_COERCE_MARKER (end2, 5);
2327 endp2 = XINT (end2);
2330 if (begp2 > endp2)
2331 temp = begp2, begp2 = endp2, endp2 = temp;
2333 if (!(BUF_BEGV (bp2) <= begp2
2334 && begp2 <= endp2
2335 && endp2 <= BUF_ZV (bp2)))
2336 args_out_of_range (start2, end2);
2338 i1 = begp1;
2339 i2 = begp2;
2340 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2341 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2343 while (i1 < endp1 && i2 < endp2)
2345 /* When we find a mismatch, we must compare the
2346 characters, not just the bytes. */
2347 int c1, c2;
2349 if (! NILP (bp1->enable_multibyte_characters))
2351 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2352 BUF_INC_POS (bp1, i1_byte);
2353 i1++;
2355 else
2357 c1 = BUF_FETCH_BYTE (bp1, i1);
2358 c1 = unibyte_char_to_multibyte (c1);
2359 i1++;
2362 if (! NILP (bp2->enable_multibyte_characters))
2364 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2365 BUF_INC_POS (bp2, i2_byte);
2366 i2++;
2368 else
2370 c2 = BUF_FETCH_BYTE (bp2, i2);
2371 c2 = unibyte_char_to_multibyte (c2);
2372 i2++;
2375 if (trt)
2377 c1 = XINT (trt[c1]);
2378 c2 = XINT (trt[c2]);
2380 if (c1 < c2)
2381 return make_number (- 1 - chars);
2382 if (c1 > c2)
2383 return make_number (chars + 1);
2385 chars++;
2388 /* The strings match as far as they go.
2389 If one is shorter, that one is less. */
2390 if (chars < endp1 - begp1)
2391 return make_number (chars + 1);
2392 else if (chars < endp2 - begp2)
2393 return make_number (- chars - 1);
2395 /* Same length too => they are equal. */
2396 return make_number (0);
2399 static Lisp_Object
2400 subst_char_in_region_unwind (arg)
2401 Lisp_Object arg;
2403 return current_buffer->undo_list = arg;
2406 static Lisp_Object
2407 subst_char_in_region_unwind_1 (arg)
2408 Lisp_Object arg;
2410 return current_buffer->filename = arg;
2413 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2414 Ssubst_char_in_region, 4, 5, 0,
2415 "From START to END, replace FROMCHAR with TOCHAR each time it occurs.\n\
2416 If optional arg NOUNDO is non-nil, don't record this change for undo\n\
2417 and don't mark the buffer as really changed.\n\
2418 Both characters must have the same length of multi-byte form.")
2419 (start, end, fromchar, tochar, noundo)
2420 Lisp_Object start, end, fromchar, tochar, noundo;
2422 register int pos, pos_byte, stop, i, len, end_byte;
2423 int changed = 0;
2424 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2425 unsigned char *p;
2426 int count = specpdl_ptr - specpdl;
2427 #define COMBINING_NO 0
2428 #define COMBINING_BEFORE 1
2429 #define COMBINING_AFTER 2
2430 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2431 int maybe_byte_combining = COMBINING_NO;
2432 int last_changed = 0;
2433 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
2435 validate_region (&start, &end);
2436 CHECK_NUMBER (fromchar, 2);
2437 CHECK_NUMBER (tochar, 3);
2439 if (multibyte_p)
2441 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2442 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2443 error ("Characters in subst-char-in-region have different byte-lengths");
2444 if (!ASCII_BYTE_P (*tostr))
2446 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2447 complete multibyte character, it may be combined with the
2448 after bytes. If it is in the range 0xA0..0xFF, it may be
2449 combined with the before and after bytes. */
2450 if (!CHAR_HEAD_P (*tostr))
2451 maybe_byte_combining = COMBINING_BOTH;
2452 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2453 maybe_byte_combining = COMBINING_AFTER;
2456 else
2458 len = 1;
2459 fromstr[0] = XFASTINT (fromchar);
2460 tostr[0] = XFASTINT (tochar);
2463 pos = XINT (start);
2464 pos_byte = CHAR_TO_BYTE (pos);
2465 stop = CHAR_TO_BYTE (XINT (end));
2466 end_byte = stop;
2468 /* If we don't want undo, turn off putting stuff on the list.
2469 That's faster than getting rid of things,
2470 and it prevents even the entry for a first change.
2471 Also inhibit locking the file. */
2472 if (!NILP (noundo))
2474 record_unwind_protect (subst_char_in_region_unwind,
2475 current_buffer->undo_list);
2476 current_buffer->undo_list = Qt;
2477 /* Don't do file-locking. */
2478 record_unwind_protect (subst_char_in_region_unwind_1,
2479 current_buffer->filename);
2480 current_buffer->filename = Qnil;
2483 if (pos_byte < GPT_BYTE)
2484 stop = min (stop, GPT_BYTE);
2485 while (1)
2487 int pos_byte_next = pos_byte;
2489 if (pos_byte >= stop)
2491 if (pos_byte >= end_byte) break;
2492 stop = end_byte;
2494 p = BYTE_POS_ADDR (pos_byte);
2495 if (multibyte_p)
2496 INC_POS (pos_byte_next);
2497 else
2498 ++pos_byte_next;
2499 if (pos_byte_next - pos_byte == len
2500 && p[0] == fromstr[0]
2501 && (len == 1
2502 || (p[1] == fromstr[1]
2503 && (len == 2 || (p[2] == fromstr[2]
2504 && (len == 3 || p[3] == fromstr[3]))))))
2506 if (! changed)
2508 changed = pos;
2509 modify_region (current_buffer, changed, XINT (end));
2511 if (! NILP (noundo))
2513 if (MODIFF - 1 == SAVE_MODIFF)
2514 SAVE_MODIFF++;
2515 if (MODIFF - 1 == current_buffer->auto_save_modified)
2516 current_buffer->auto_save_modified++;
2520 /* Take care of the case where the new character
2521 combines with neighboring bytes. */
2522 if (maybe_byte_combining
2523 && (maybe_byte_combining == COMBINING_AFTER
2524 ? (pos_byte_next < Z_BYTE
2525 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2526 : ((pos_byte_next < Z_BYTE
2527 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2528 || (pos_byte > BEG_BYTE
2529 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2531 Lisp_Object tem, string;
2533 struct gcpro gcpro1;
2535 tem = current_buffer->undo_list;
2536 GCPRO1 (tem);
2538 /* Make a multibyte string containing this single character. */
2539 string = make_multibyte_string (tostr, 1, len);
2540 /* replace_range is less efficient, because it moves the gap,
2541 but it handles combining correctly. */
2542 replace_range (pos, pos + 1, string,
2543 0, 0, 1);
2544 pos_byte_next = CHAR_TO_BYTE (pos);
2545 if (pos_byte_next > pos_byte)
2546 /* Before combining happened. We should not increment
2547 POS. So, to cancel the later increment of POS,
2548 decrease it now. */
2549 pos--;
2550 else
2551 INC_POS (pos_byte_next);
2553 if (! NILP (noundo))
2554 current_buffer->undo_list = tem;
2556 UNGCPRO;
2558 else
2560 if (NILP (noundo))
2561 record_change (pos, 1);
2562 for (i = 0; i < len; i++) *p++ = tostr[i];
2564 last_changed = pos + 1;
2566 pos_byte = pos_byte_next;
2567 pos++;
2570 if (changed)
2572 signal_after_change (changed,
2573 last_changed - changed, last_changed - changed);
2574 update_compositions (changed, last_changed, CHECK_ALL);
2577 unbind_to (count, Qnil);
2578 return Qnil;
2581 DEFUN ("translate-region", Ftranslate_region, Stranslate_region, 3, 3, 0,
2582 "From START to END, translate characters according to TABLE.\n\
2583 TABLE is a string; the Nth character in it is the mapping\n\
2584 for the character with code N.\n\
2585 This function does not alter multibyte characters.\n\
2586 It returns the number of characters changed.")
2587 (start, end, table)
2588 Lisp_Object start;
2589 Lisp_Object end;
2590 register Lisp_Object table;
2592 register int pos_byte, stop; /* Limits of the region. */
2593 register unsigned char *tt; /* Trans table. */
2594 register int nc; /* New character. */
2595 int cnt; /* Number of changes made. */
2596 int size; /* Size of translate table. */
2597 int pos;
2598 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
2600 validate_region (&start, &end);
2601 CHECK_STRING (table, 2);
2603 size = STRING_BYTES (XSTRING (table));
2604 tt = XSTRING (table)->data;
2606 pos_byte = CHAR_TO_BYTE (XINT (start));
2607 stop = CHAR_TO_BYTE (XINT (end));
2608 modify_region (current_buffer, XINT (start), XINT (end));
2609 pos = XINT (start);
2611 cnt = 0;
2612 for (; pos_byte < stop; )
2614 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
2615 int len;
2616 int oc;
2617 int pos_byte_next;
2619 if (multibyte)
2620 oc = STRING_CHAR_AND_LENGTH (p, stop - pos_byte, len);
2621 else
2622 oc = *p, len = 1;
2623 pos_byte_next = pos_byte + len;
2624 if (oc < size && len == 1)
2626 nc = tt[oc];
2627 if (nc != oc)
2629 /* Take care of the case where the new character
2630 combines with neighboring bytes. */
2631 if (!ASCII_BYTE_P (nc)
2632 && (CHAR_HEAD_P (nc)
2633 ? ! CHAR_HEAD_P (FETCH_BYTE (pos_byte + 1))
2634 : (pos_byte > BEG_BYTE
2635 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1)))))
2637 Lisp_Object string;
2639 string = make_multibyte_string (tt + oc, 1, 1);
2640 /* This is less efficient, because it moves the gap,
2641 but it handles combining correctly. */
2642 replace_range (pos, pos + 1, string,
2643 1, 0, 1);
2644 pos_byte_next = CHAR_TO_BYTE (pos);
2645 if (pos_byte_next > pos_byte)
2646 /* Before combining happened. We should not
2647 increment POS. So, to cancel the later
2648 increment of POS, we decrease it now. */
2649 pos--;
2650 else
2651 INC_POS (pos_byte_next);
2653 else
2655 record_change (pos, 1);
2656 *p = nc;
2657 signal_after_change (pos, 1, 1);
2658 update_compositions (pos, pos + 1, CHECK_BORDER);
2660 ++cnt;
2663 pos_byte = pos_byte_next;
2664 pos++;
2667 return make_number (cnt);
2670 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
2671 "Delete the text between point and mark.\n\
2672 When called from a program, expects two arguments,\n\
2673 positions (integers or markers) specifying the stretch to be deleted.")
2674 (start, end)
2675 Lisp_Object start, end;
2677 validate_region (&start, &end);
2678 del_range (XINT (start), XINT (end));
2679 return Qnil;
2682 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
2683 Sdelete_and_extract_region, 2, 2, 0,
2684 "Delete the text between START and END and return it.")
2685 (start, end)
2686 Lisp_Object start, end;
2688 validate_region (&start, &end);
2689 return del_range_1 (XINT (start), XINT (end), 1, 1);
2692 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
2693 "Remove restrictions (narrowing) from current buffer.\n\
2694 This allows the buffer's full text to be seen and edited.")
2697 if (BEG != BEGV || Z != ZV)
2698 current_buffer->clip_changed = 1;
2699 BEGV = BEG;
2700 BEGV_BYTE = BEG_BYTE;
2701 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
2702 /* Changing the buffer bounds invalidates any recorded current column. */
2703 invalidate_current_column ();
2704 return Qnil;
2707 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
2708 "Restrict editing in this buffer to the current region.\n\
2709 The rest of the text becomes temporarily invisible and untouchable\n\
2710 but is not deleted; if you save the buffer in a file, the invisible\n\
2711 text is included in the file. \\[widen] makes all visible again.\n\
2712 See also `save-restriction'.\n\
2714 When calling from a program, pass two arguments; positions (integers\n\
2715 or markers) bounding the text that should remain visible.")
2716 (start, end)
2717 register Lisp_Object start, end;
2719 CHECK_NUMBER_COERCE_MARKER (start, 0);
2720 CHECK_NUMBER_COERCE_MARKER (end, 1);
2722 if (XINT (start) > XINT (end))
2724 Lisp_Object tem;
2725 tem = start; start = end; end = tem;
2728 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
2729 args_out_of_range (start, end);
2731 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
2732 current_buffer->clip_changed = 1;
2734 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2735 SET_BUF_ZV (current_buffer, XFASTINT (end));
2736 if (PT < XFASTINT (start))
2737 SET_PT (XFASTINT (start));
2738 if (PT > XFASTINT (end))
2739 SET_PT (XFASTINT (end));
2740 /* Changing the buffer bounds invalidates any recorded current column. */
2741 invalidate_current_column ();
2742 return Qnil;
2745 Lisp_Object
2746 save_restriction_save ()
2748 if (BEGV == BEG && ZV == Z)
2749 /* The common case that the buffer isn't narrowed.
2750 We return just the buffer object, which save_restriction_restore
2751 recognizes as meaning `no restriction'. */
2752 return Fcurrent_buffer ();
2753 else
2754 /* We have to save a restriction, so return a pair of markers, one
2755 for the beginning and one for the end. */
2757 Lisp_Object beg, end;
2759 beg = buildmark (BEGV, BEGV_BYTE);
2760 end = buildmark (ZV, ZV_BYTE);
2762 /* END must move forward if text is inserted at its exact location. */
2763 XMARKER(end)->insertion_type = 1;
2765 return Fcons (beg, end);
2769 Lisp_Object
2770 save_restriction_restore (data)
2771 Lisp_Object data;
2773 if (CONSP (data))
2774 /* A pair of marks bounding a saved restriction. */
2776 struct Lisp_Marker *beg = XMARKER (XCAR (data));
2777 struct Lisp_Marker *end = XMARKER (XCDR (data));
2778 struct buffer *buf = beg->buffer; /* END should have the same buffer. */
2780 if (beg->charpos != BUF_BEGV(buf) || end->charpos != BUF_ZV(buf))
2781 /* The restriction has changed from the saved one, so restore
2782 the saved restriction. */
2784 int pt = BUF_PT (buf);
2786 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
2787 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
2789 if (pt < beg->charpos || pt > end->charpos)
2790 /* The point is outside the new visible range, move it inside. */
2791 SET_BUF_PT_BOTH (buf,
2792 clip_to_bounds (beg->charpos, pt, end->charpos),
2793 clip_to_bounds (beg->bytepos, BUF_PT_BYTE(buf),
2794 end->bytepos));
2796 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2799 else
2800 /* A buffer, which means that there was no old restriction. */
2802 struct buffer *buf = XBUFFER (data);
2804 if (BUF_BEGV(buf) != BUF_BEG(buf) || BUF_ZV(buf) != BUF_Z(buf))
2805 /* The buffer has been narrowed, get rid of the narrowing. */
2807 SET_BUF_BEGV_BOTH (buf, BUF_BEG(buf), BUF_BEG_BYTE(buf));
2808 SET_BUF_ZV_BOTH (buf, BUF_Z(buf), BUF_Z_BYTE(buf));
2810 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2814 return Qnil;
2817 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
2818 "Execute BODY, saving and restoring current buffer's restrictions.\n\
2819 The buffer's restrictions make parts of the beginning and end invisible.\n\
2820 \(They are set up with `narrow-to-region' and eliminated with `widen'.)\n\
2821 This special form, `save-restriction', saves the current buffer's restrictions\n\
2822 when it is entered, and restores them when it is exited.\n\
2823 So any `narrow-to-region' within BODY lasts only until the end of the form.\n\
2824 The old restrictions settings are restored\n\
2825 even in case of abnormal exit (throw or error).\n\
2827 The value returned is the value of the last form in BODY.\n\
2829 Note: if you are using both `save-excursion' and `save-restriction',\n\
2830 use `save-excursion' outermost:\n\
2831 (save-excursion (save-restriction ...))")
2832 (body)
2833 Lisp_Object body;
2835 register Lisp_Object val;
2836 int count = specpdl_ptr - specpdl;
2838 record_unwind_protect (save_restriction_restore, save_restriction_save ());
2839 val = Fprogn (body);
2840 return unbind_to (count, val);
2843 #ifndef HAVE_MENUS
2845 /* Buffer for the most recent text displayed by Fmessage. */
2846 static char *message_text;
2848 /* Allocated length of that buffer. */
2849 static int message_length;
2851 #endif /* not HAVE_MENUS */
2853 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
2854 "Print a one-line message at the bottom of the screen.\n\
2855 The first argument is a format control string, and the rest are data\n\
2856 to be formatted under control of the string. See `format' for details.\n\
2858 If the first argument is nil, clear any existing message; let the\n\
2859 minibuffer contents show.")
2860 (nargs, args)
2861 int nargs;
2862 Lisp_Object *args;
2864 if (NILP (args[0]))
2866 message (0);
2867 return Qnil;
2869 else
2871 register Lisp_Object val;
2872 val = Fformat (nargs, args);
2873 message3 (val, STRING_BYTES (XSTRING (val)), STRING_MULTIBYTE (val));
2874 return val;
2878 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
2879 "Display a message, in a dialog box if possible.\n\
2880 If a dialog box is not available, use the echo area.\n\
2881 The first argument is a format control string, and the rest are data\n\
2882 to be formatted under control of the string. See `format' for details.\n\
2884 If the first argument is nil, clear any existing message; let the\n\
2885 minibuffer contents show.")
2886 (nargs, args)
2887 int nargs;
2888 Lisp_Object *args;
2890 if (NILP (args[0]))
2892 message (0);
2893 return Qnil;
2895 else
2897 register Lisp_Object val;
2898 val = Fformat (nargs, args);
2899 #ifdef HAVE_MENUS
2901 Lisp_Object pane, menu, obj;
2902 struct gcpro gcpro1;
2903 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
2904 GCPRO1 (pane);
2905 menu = Fcons (val, pane);
2906 obj = Fx_popup_dialog (Qt, menu);
2907 UNGCPRO;
2908 return val;
2910 #else /* not HAVE_MENUS */
2911 /* Copy the data so that it won't move when we GC. */
2912 if (! message_text)
2914 message_text = (char *)xmalloc (80);
2915 message_length = 80;
2917 if (STRING_BYTES (XSTRING (val)) > message_length)
2919 message_length = STRING_BYTES (XSTRING (val));
2920 message_text = (char *)xrealloc (message_text, message_length);
2922 bcopy (XSTRING (val)->data, message_text, STRING_BYTES (XSTRING (val)));
2923 message2 (message_text, STRING_BYTES (XSTRING (val)),
2924 STRING_MULTIBYTE (val));
2925 return val;
2926 #endif /* not HAVE_MENUS */
2929 #ifdef HAVE_MENUS
2930 extern Lisp_Object last_nonmenu_event;
2931 #endif
2933 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
2934 "Display a message in a dialog box or in the echo area.\n\
2935 If this command was invoked with the mouse, use a dialog box if\n\
2936 `use-dialog-box' is non-nil.\n\
2937 Otherwise, use the echo area.\n\
2938 The first argument is a format control string, and the rest are data\n\
2939 to be formatted under control of the string. See `format' for details.\n\
2941 If the first argument is nil, clear any existing message; let the\n\
2942 minibuffer contents show.")
2943 (nargs, args)
2944 int nargs;
2945 Lisp_Object *args;
2947 #ifdef HAVE_MENUS
2948 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2949 && use_dialog_box)
2950 return Fmessage_box (nargs, args);
2951 #endif
2952 return Fmessage (nargs, args);
2955 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
2956 "Return the string currently displayed in the echo area, or nil if none.")
2959 return current_message ();
2963 DEFUN ("propertize", Fpropertize, Spropertize, 3, MANY, 0,
2964 "Return a copy of STRING with text properties added.\n\
2965 First argument is the string to copy.\n\
2966 Remaining arguments form a sequence of PROPERTY VALUE pairs for text\n\
2967 properties to add to the result ")
2968 (nargs, args)
2969 int nargs;
2970 Lisp_Object *args;
2972 Lisp_Object properties, string;
2973 struct gcpro gcpro1, gcpro2;
2974 int i;
2976 /* Number of args must be odd. */
2977 if ((nargs & 1) == 0 || nargs < 3)
2978 error ("Wrong number of arguments");
2980 properties = string = Qnil;
2981 GCPRO2 (properties, string);
2983 /* First argument must be a string. */
2984 CHECK_STRING (args[0], 0);
2985 string = Fcopy_sequence (args[0]);
2987 for (i = 1; i < nargs; i += 2)
2989 CHECK_SYMBOL (args[i], i);
2990 properties = Fcons (args[i], Fcons (args[i + 1], properties));
2993 Fadd_text_properties (make_number (0),
2994 make_number (XSTRING (string)->size),
2995 properties, string);
2996 RETURN_UNGCPRO (string);
3000 /* Number of bytes that STRING will occupy when put into the result.
3001 MULTIBYTE is nonzero if the result should be multibyte. */
3003 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3004 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3005 ? count_size_as_multibyte (XSTRING (STRING)->data, \
3006 STRING_BYTES (XSTRING (STRING))) \
3007 : STRING_BYTES (XSTRING (STRING)))
3009 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3010 "Format a string out of a control-string and arguments.\n\
3011 The first argument is a control string.\n\
3012 The other arguments are substituted into it to make the result, a string.\n\
3013 It may contain %-sequences meaning to substitute the next argument.\n\
3014 %s means print a string argument. Actually, prints any object, with `princ'.\n\
3015 %d means print as number in decimal (%o octal, %x hex).\n\
3016 %e means print a number in exponential notation.\n\
3017 %f means print a number in decimal-point notation.\n\
3018 %g means print a number in exponential notation\n\
3019 or decimal-point notation, whichever uses fewer characters.\n\
3020 %c means print a number as a single character.\n\
3021 %S means print any object as an s-expression (using `prin1').\n\
3022 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.\n\
3023 Use %% to put a single % into the output.")
3024 (nargs, args)
3025 int nargs;
3026 register Lisp_Object *args;
3028 register int n; /* The number of the next arg to substitute */
3029 register int total; /* An estimate of the final length */
3030 char *buf, *p;
3031 register unsigned char *format, *end;
3032 int nchars;
3033 /* Nonzero if the output should be a multibyte string,
3034 which is true if any of the inputs is one. */
3035 int multibyte = 0;
3036 /* When we make a multibyte string, we must pay attention to the
3037 byte combining problem, i.e., a byte may be combined with a
3038 multibyte charcter of the previous string. This flag tells if we
3039 must consider such a situation or not. */
3040 int maybe_combine_byte;
3041 unsigned char *this_format;
3042 int longest_format;
3043 Lisp_Object val;
3044 struct info
3046 int start, end;
3047 } *info = 0;
3049 /* It should not be necessary to GCPRO ARGS, because
3050 the caller in the interpreter should take care of that. */
3052 /* Try to determine whether the result should be multibyte.
3053 This is not always right; sometimes the result needs to be multibyte
3054 because of an object that we will pass through prin1,
3055 and in that case, we won't know it here. */
3056 for (n = 0; n < nargs; n++)
3057 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3058 multibyte = 1;
3060 CHECK_STRING (args[0], 0);
3062 /* If we start out planning a unibyte result,
3063 and later find it has to be multibyte, we jump back to retry. */
3064 retry:
3066 format = XSTRING (args[0])->data;
3067 end = format + STRING_BYTES (XSTRING (args[0]));
3068 longest_format = 0;
3070 /* Make room in result for all the non-%-codes in the control string. */
3071 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]);
3073 /* Add to TOTAL enough space to hold the converted arguments. */
3075 n = 0;
3076 while (format != end)
3077 if (*format++ == '%')
3079 int minlen, thissize = 0;
3080 unsigned char *this_format_start = format - 1;
3082 /* Process a numeric arg and skip it. */
3083 minlen = atoi (format);
3084 if (minlen < 0)
3085 minlen = - minlen;
3087 while ((*format >= '0' && *format <= '9')
3088 || *format == '-' || *format == ' ' || *format == '.')
3089 format++;
3091 if (format - this_format_start + 1 > longest_format)
3092 longest_format = format - this_format_start + 1;
3094 if (format == end)
3095 error ("Format string ends in middle of format specifier");
3096 if (*format == '%')
3097 format++;
3098 else if (++n >= nargs)
3099 error ("Not enough arguments for format string");
3100 else if (*format == 'S')
3102 /* For `S', prin1 the argument and then treat like a string. */
3103 register Lisp_Object tem;
3104 tem = Fprin1_to_string (args[n], Qnil);
3105 if (STRING_MULTIBYTE (tem) && ! multibyte)
3107 multibyte = 1;
3108 goto retry;
3110 args[n] = tem;
3111 goto string;
3113 else if (SYMBOLP (args[n]))
3115 /* Use a temp var to avoid problems when ENABLE_CHECKING
3116 is turned on. */
3117 struct Lisp_String *t = XSYMBOL (args[n])->name;
3118 XSETSTRING (args[n], t);
3119 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3121 multibyte = 1;
3122 goto retry;
3124 goto string;
3126 else if (STRINGP (args[n]))
3128 string:
3129 if (*format != 's' && *format != 'S')
3130 error ("Format specifier doesn't match argument type");
3131 thissize = CONVERTED_BYTE_SIZE (multibyte, args[n]);
3133 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3134 else if (INTEGERP (args[n]) && *format != 's')
3136 /* The following loop assumes the Lisp type indicates
3137 the proper way to pass the argument.
3138 So make sure we have a flonum if the argument should
3139 be a double. */
3140 if (*format == 'e' || *format == 'f' || *format == 'g')
3141 args[n] = Ffloat (args[n]);
3142 else
3143 if (*format != 'd' && *format != 'o' && *format != 'x'
3144 && *format != 'i' && *format != 'X' && *format != 'c')
3145 error ("Invalid format operation %%%c", *format);
3147 thissize = 30;
3148 if (*format == 'c'
3149 && (! SINGLE_BYTE_CHAR_P (XINT (args[n]))
3150 || XINT (args[n]) == 0))
3152 if (! multibyte)
3154 multibyte = 1;
3155 goto retry;
3157 args[n] = Fchar_to_string (args[n]);
3158 thissize = STRING_BYTES (XSTRING (args[n]));
3161 else if (FLOATP (args[n]) && *format != 's')
3163 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3164 args[n] = Ftruncate (args[n], Qnil);
3165 thissize = 200;
3167 else
3169 /* Anything but a string, convert to a string using princ. */
3170 register Lisp_Object tem;
3171 tem = Fprin1_to_string (args[n], Qt);
3172 if (STRING_MULTIBYTE (tem) & ! multibyte)
3174 multibyte = 1;
3175 goto retry;
3177 args[n] = tem;
3178 goto string;
3181 if (thissize < minlen)
3182 thissize = minlen;
3184 total += thissize + 4;
3187 /* Now we can no longer jump to retry.
3188 TOTAL and LONGEST_FORMAT are known for certain. */
3190 this_format = (unsigned char *) alloca (longest_format + 1);
3192 /* Allocate the space for the result.
3193 Note that TOTAL is an overestimate. */
3194 if (total < 1000)
3195 buf = (char *) alloca (total + 1);
3196 else
3197 buf = (char *) xmalloc (total + 1);
3199 p = buf;
3200 nchars = 0;
3201 n = 0;
3203 /* Scan the format and store result in BUF. */
3204 format = XSTRING (args[0])->data;
3205 maybe_combine_byte = 0;
3206 while (format != end)
3208 if (*format == '%')
3210 int minlen;
3211 int negative = 0;
3212 unsigned char *this_format_start = format;
3214 format++;
3216 /* Process a numeric arg and skip it. */
3217 minlen = atoi (format);
3218 if (minlen < 0)
3219 minlen = - minlen, negative = 1;
3221 while ((*format >= '0' && *format <= '9')
3222 || *format == '-' || *format == ' ' || *format == '.')
3223 format++;
3225 if (*format++ == '%')
3227 *p++ = '%';
3228 nchars++;
3229 continue;
3232 ++n;
3234 if (STRINGP (args[n]))
3236 int padding, nbytes;
3237 int width = strwidth (XSTRING (args[n])->data,
3238 STRING_BYTES (XSTRING (args[n])));
3239 int start = nchars;
3241 /* If spec requires it, pad on right with spaces. */
3242 padding = minlen - width;
3243 if (! negative)
3244 while (padding-- > 0)
3246 *p++ = ' ';
3247 nchars++;
3250 if (p > buf
3251 && multibyte
3252 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3253 && STRING_MULTIBYTE (args[n])
3254 && !CHAR_HEAD_P (XSTRING (args[n])->data[0]))
3255 maybe_combine_byte = 1;
3256 nbytes = copy_text (XSTRING (args[n])->data, p,
3257 STRING_BYTES (XSTRING (args[n])),
3258 STRING_MULTIBYTE (args[n]), multibyte);
3259 p += nbytes;
3260 nchars += XSTRING (args[n])->size;
3262 if (negative)
3263 while (padding-- > 0)
3265 *p++ = ' ';
3266 nchars++;
3269 /* If this argument has text properties, record where
3270 in the result string it appears. */
3271 if (XSTRING (args[n])->intervals)
3273 if (!info)
3275 int nbytes = nargs * sizeof *info;
3276 info = (struct info *) alloca (nbytes);
3277 bzero (info, nbytes);
3280 info[n].start = start;
3281 info[n].end = nchars;
3284 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3286 int this_nchars;
3288 bcopy (this_format_start, this_format,
3289 format - this_format_start);
3290 this_format[format - this_format_start] = 0;
3292 if (INTEGERP (args[n]))
3293 sprintf (p, this_format, XINT (args[n]));
3294 else
3295 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3297 if (p > buf
3298 && multibyte
3299 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3300 && !CHAR_HEAD_P (*((unsigned char *) p)))
3301 maybe_combine_byte = 1;
3302 this_nchars = strlen (p);
3303 if (multibyte)
3304 p += str_to_multibyte (p, buf + total - p, this_nchars);
3305 else
3306 p += this_nchars;
3307 nchars += this_nchars;
3310 else if (STRING_MULTIBYTE (args[0]))
3312 /* Copy a whole multibyte character. */
3313 if (p > buf
3314 && multibyte
3315 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3316 && !CHAR_HEAD_P (*format))
3317 maybe_combine_byte = 1;
3318 *p++ = *format++;
3319 while (! CHAR_HEAD_P (*format)) *p++ = *format++;
3320 nchars++;
3322 else if (multibyte)
3324 /* Convert a single-byte character to multibyte. */
3325 int len = copy_text (format, p, 1, 0, 1);
3327 p += len;
3328 format++;
3329 nchars++;
3331 else
3332 *p++ = *format++, nchars++;
3335 if (maybe_combine_byte)
3336 nchars = multibyte_chars_in_text (buf, p - buf);
3337 val = make_specified_string (buf, nchars, p - buf, multibyte);
3339 /* If we allocated BUF with malloc, free it too. */
3340 if (total >= 1000)
3341 xfree (buf);
3343 /* If the format string has text properties, or any of the string
3344 arguments has text properties, set up text properties of the
3345 result string. */
3347 if (XSTRING (args[0])->intervals || info)
3349 Lisp_Object len, new_len, props;
3350 struct gcpro gcpro1;
3352 /* Add text properties from the format string. */
3353 len = make_number (XSTRING (args[0])->size);
3354 props = text_property_list (args[0], make_number (0), len, Qnil);
3355 GCPRO1 (props);
3357 if (CONSP (props))
3359 new_len = make_number (XSTRING (val)->size);
3360 extend_property_ranges (props, len, new_len);
3361 add_text_properties_from_list (val, props, make_number (0));
3364 /* Add text properties from arguments. */
3365 if (info)
3366 for (n = 1; n < nargs; ++n)
3367 if (info[n].end)
3369 len = make_number (XSTRING (args[n])->size);
3370 new_len = make_number (info[n].end - info[n].start);
3371 props = text_property_list (args[n], make_number (0), len, Qnil);
3372 extend_property_ranges (props, len, new_len);
3373 /* If successive arguments have properites, be sure that
3374 the value of `composition' property be the copy. */
3375 if (n > 1 && info[n - 1].end)
3376 make_composition_value_copy (props);
3377 add_text_properties_from_list (val, props,
3378 make_number (info[n].start));
3381 UNGCPRO;
3384 return val;
3388 /* VARARGS 1 */
3389 Lisp_Object
3390 #ifdef NO_ARG_ARRAY
3391 format1 (string1, arg0, arg1, arg2, arg3, arg4)
3392 EMACS_INT arg0, arg1, arg2, arg3, arg4;
3393 #else
3394 format1 (string1)
3395 #endif
3396 char *string1;
3398 char buf[100];
3399 #ifdef NO_ARG_ARRAY
3400 EMACS_INT args[5];
3401 args[0] = arg0;
3402 args[1] = arg1;
3403 args[2] = arg2;
3404 args[3] = arg3;
3405 args[4] = arg4;
3406 doprnt (buf, sizeof buf, string1, (char *)0, 5, (char **) args);
3407 #else
3408 doprnt (buf, sizeof buf, string1, (char *)0, 5, &string1 + 1);
3409 #endif
3410 return build_string (buf);
3413 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
3414 "Return t if two characters match, optionally ignoring case.\n\
3415 Both arguments must be characters (i.e. integers).\n\
3416 Case is ignored if `case-fold-search' is non-nil in the current buffer.")
3417 (c1, c2)
3418 register Lisp_Object c1, c2;
3420 int i1, i2;
3421 CHECK_NUMBER (c1, 0);
3422 CHECK_NUMBER (c2, 1);
3424 if (XINT (c1) == XINT (c2))
3425 return Qt;
3426 if (NILP (current_buffer->case_fold_search))
3427 return Qnil;
3429 /* Do these in separate statements,
3430 then compare the variables.
3431 because of the way DOWNCASE uses temp variables. */
3432 i1 = DOWNCASE (XFASTINT (c1));
3433 i2 = DOWNCASE (XFASTINT (c2));
3434 return (i1 == i2 ? Qt : Qnil);
3437 /* Transpose the markers in two regions of the current buffer, and
3438 adjust the ones between them if necessary (i.e.: if the regions
3439 differ in size).
3441 START1, END1 are the character positions of the first region.
3442 START1_BYTE, END1_BYTE are the byte positions.
3443 START2, END2 are the character positions of the second region.
3444 START2_BYTE, END2_BYTE are the byte positions.
3446 Traverses the entire marker list of the buffer to do so, adding an
3447 appropriate amount to some, subtracting from some, and leaving the
3448 rest untouched. Most of this is copied from adjust_markers in insdel.c.
3450 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
3452 static void
3453 transpose_markers (start1, end1, start2, end2,
3454 start1_byte, end1_byte, start2_byte, end2_byte)
3455 register int start1, end1, start2, end2;
3456 register int start1_byte, end1_byte, start2_byte, end2_byte;
3458 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
3459 register Lisp_Object marker;
3461 /* Update point as if it were a marker. */
3462 if (PT < start1)
3464 else if (PT < end1)
3465 TEMP_SET_PT_BOTH (PT + (end2 - end1),
3466 PT_BYTE + (end2_byte - end1_byte));
3467 else if (PT < start2)
3468 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
3469 (PT_BYTE + (end2_byte - start2_byte)
3470 - (end1_byte - start1_byte)));
3471 else if (PT < end2)
3472 TEMP_SET_PT_BOTH (PT - (start2 - start1),
3473 PT_BYTE - (start2_byte - start1_byte));
3475 /* We used to adjust the endpoints here to account for the gap, but that
3476 isn't good enough. Even if we assume the caller has tried to move the
3477 gap out of our way, it might still be at start1 exactly, for example;
3478 and that places it `inside' the interval, for our purposes. The amount
3479 of adjustment is nontrivial if there's a `denormalized' marker whose
3480 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
3481 the dirty work to Fmarker_position, below. */
3483 /* The difference between the region's lengths */
3484 diff = (end2 - start2) - (end1 - start1);
3485 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
3487 /* For shifting each marker in a region by the length of the other
3488 region plus the distance between the regions. */
3489 amt1 = (end2 - start2) + (start2 - end1);
3490 amt2 = (end1 - start1) + (start2 - end1);
3491 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
3492 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
3494 for (marker = BUF_MARKERS (current_buffer); !NILP (marker);
3495 marker = XMARKER (marker)->chain)
3497 mpos = marker_byte_position (marker);
3498 if (mpos >= start1_byte && mpos < end2_byte)
3500 if (mpos < end1_byte)
3501 mpos += amt1_byte;
3502 else if (mpos < start2_byte)
3503 mpos += diff_byte;
3504 else
3505 mpos -= amt2_byte;
3506 XMARKER (marker)->bytepos = mpos;
3508 mpos = XMARKER (marker)->charpos;
3509 if (mpos >= start1 && mpos < end2)
3511 if (mpos < end1)
3512 mpos += amt1;
3513 else if (mpos < start2)
3514 mpos += diff;
3515 else
3516 mpos -= amt2;
3518 XMARKER (marker)->charpos = mpos;
3522 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
3523 "Transpose region START1 to END1 with START2 to END2.\n\
3524 The regions may not be overlapping, because the size of the buffer is\n\
3525 never changed in a transposition.\n\
3527 Optional fifth arg LEAVE_MARKERS, if non-nil, means don't update\n\
3528 any markers that happen to be located in the regions.\n\
3530 Transposing beyond buffer boundaries is an error.")
3531 (startr1, endr1, startr2, endr2, leave_markers)
3532 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
3534 register int start1, end1, start2, end2;
3535 int start1_byte, start2_byte, len1_byte, len2_byte;
3536 int gap, len1, len_mid, len2;
3537 unsigned char *start1_addr, *start2_addr, *temp;
3538 struct gcpro gcpro1, gcpro2;
3540 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
3541 cur_intv = BUF_INTERVALS (current_buffer);
3543 validate_region (&startr1, &endr1);
3544 validate_region (&startr2, &endr2);
3546 start1 = XFASTINT (startr1);
3547 end1 = XFASTINT (endr1);
3548 start2 = XFASTINT (startr2);
3549 end2 = XFASTINT (endr2);
3550 gap = GPT;
3552 /* Swap the regions if they're reversed. */
3553 if (start2 < end1)
3555 register int glumph = start1;
3556 start1 = start2;
3557 start2 = glumph;
3558 glumph = end1;
3559 end1 = end2;
3560 end2 = glumph;
3563 len1 = end1 - start1;
3564 len2 = end2 - start2;
3566 if (start2 < end1)
3567 error ("Transposed regions overlap");
3568 else if (start1 == end1 || start2 == end2)
3569 error ("Transposed region has length 0");
3571 /* The possibilities are:
3572 1. Adjacent (contiguous) regions, or separate but equal regions
3573 (no, really equal, in this case!), or
3574 2. Separate regions of unequal size.
3576 The worst case is usually No. 2. It means that (aside from
3577 potential need for getting the gap out of the way), there also
3578 needs to be a shifting of the text between the two regions. So
3579 if they are spread far apart, we are that much slower... sigh. */
3581 /* It must be pointed out that the really studly thing to do would
3582 be not to move the gap at all, but to leave it in place and work
3583 around it if necessary. This would be extremely efficient,
3584 especially considering that people are likely to do
3585 transpositions near where they are working interactively, which
3586 is exactly where the gap would be found. However, such code
3587 would be much harder to write and to read. So, if you are
3588 reading this comment and are feeling squirrely, by all means have
3589 a go! I just didn't feel like doing it, so I will simply move
3590 the gap the minimum distance to get it out of the way, and then
3591 deal with an unbroken array. */
3593 /* Make sure the gap won't interfere, by moving it out of the text
3594 we will operate on. */
3595 if (start1 < gap && gap < end2)
3597 if (gap - start1 < end2 - gap)
3598 move_gap (start1);
3599 else
3600 move_gap (end2);
3603 start1_byte = CHAR_TO_BYTE (start1);
3604 start2_byte = CHAR_TO_BYTE (start2);
3605 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
3606 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
3608 #ifdef BYTE_COMBINING_DEBUG
3609 if (end1 == start2)
3611 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3612 len2_byte, start1, start1_byte)
3613 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3614 len1_byte, end2, start2_byte + len2_byte)
3615 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3616 len1_byte, end2, start2_byte + len2_byte))
3617 abort ();
3619 else
3621 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3622 len2_byte, start1, start1_byte)
3623 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3624 len1_byte, start2, start2_byte)
3625 || count_combining_after (BYTE_POS_ADDR (start2_byte),
3626 len2_byte, end1, start1_byte + len1_byte)
3627 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3628 len1_byte, end2, start2_byte + len2_byte))
3629 abort ();
3631 #endif
3633 /* Hmmm... how about checking to see if the gap is large
3634 enough to use as the temporary storage? That would avoid an
3635 allocation... interesting. Later, don't fool with it now. */
3637 /* Working without memmove, for portability (sigh), so must be
3638 careful of overlapping subsections of the array... */
3640 if (end1 == start2) /* adjacent regions */
3642 modify_region (current_buffer, start1, end2);
3643 record_change (start1, len1 + len2);
3645 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3646 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3647 Fset_text_properties (make_number (start1), make_number (end2),
3648 Qnil, Qnil);
3650 /* First region smaller than second. */
3651 if (len1_byte < len2_byte)
3653 /* We use alloca only if it is small,
3654 because we want to avoid stack overflow. */
3655 if (len2_byte > 20000)
3656 temp = (unsigned char *) xmalloc (len2_byte);
3657 else
3658 temp = (unsigned char *) alloca (len2_byte);
3660 /* Don't precompute these addresses. We have to compute them
3661 at the last minute, because the relocating allocator might
3662 have moved the buffer around during the xmalloc. */
3663 start1_addr = BYTE_POS_ADDR (start1_byte);
3664 start2_addr = BYTE_POS_ADDR (start2_byte);
3666 bcopy (start2_addr, temp, len2_byte);
3667 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
3668 bcopy (temp, start1_addr, len2_byte);
3669 if (len2_byte > 20000)
3670 xfree (temp);
3672 else
3673 /* First region not smaller than second. */
3675 if (len1_byte > 20000)
3676 temp = (unsigned char *) xmalloc (len1_byte);
3677 else
3678 temp = (unsigned char *) alloca (len1_byte);
3679 start1_addr = BYTE_POS_ADDR (start1_byte);
3680 start2_addr = BYTE_POS_ADDR (start2_byte);
3681 bcopy (start1_addr, temp, len1_byte);
3682 bcopy (start2_addr, start1_addr, len2_byte);
3683 bcopy (temp, start1_addr + len2_byte, len1_byte);
3684 if (len1_byte > 20000)
3685 xfree (temp);
3687 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
3688 len1, current_buffer, 0);
3689 graft_intervals_into_buffer (tmp_interval2, start1,
3690 len2, current_buffer, 0);
3691 update_compositions (start1, start1 + len2, CHECK_BORDER);
3692 update_compositions (start1 + len2, end2, CHECK_TAIL);
3694 /* Non-adjacent regions, because end1 != start2, bleagh... */
3695 else
3697 len_mid = start2_byte - (start1_byte + len1_byte);
3699 if (len1_byte == len2_byte)
3700 /* Regions are same size, though, how nice. */
3702 modify_region (current_buffer, start1, end1);
3703 modify_region (current_buffer, start2, end2);
3704 record_change (start1, len1);
3705 record_change (start2, len2);
3706 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3707 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3708 Fset_text_properties (make_number (start1), make_number (end1),
3709 Qnil, Qnil);
3710 Fset_text_properties (make_number (start2), make_number (end2),
3711 Qnil, Qnil);
3713 if (len1_byte > 20000)
3714 temp = (unsigned char *) xmalloc (len1_byte);
3715 else
3716 temp = (unsigned char *) alloca (len1_byte);
3717 start1_addr = BYTE_POS_ADDR (start1_byte);
3718 start2_addr = BYTE_POS_ADDR (start2_byte);
3719 bcopy (start1_addr, temp, len1_byte);
3720 bcopy (start2_addr, start1_addr, len2_byte);
3721 bcopy (temp, start2_addr, len1_byte);
3722 if (len1_byte > 20000)
3723 xfree (temp);
3724 graft_intervals_into_buffer (tmp_interval1, start2,
3725 len1, current_buffer, 0);
3726 graft_intervals_into_buffer (tmp_interval2, start1,
3727 len2, current_buffer, 0);
3730 else if (len1_byte < len2_byte) /* Second region larger than first */
3731 /* Non-adjacent & unequal size, area between must also be shifted. */
3733 modify_region (current_buffer, start1, end2);
3734 record_change (start1, (end2 - start1));
3735 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3736 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3737 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3738 Fset_text_properties (make_number (start1), make_number (end2),
3739 Qnil, Qnil);
3741 /* holds region 2 */
3742 if (len2_byte > 20000)
3743 temp = (unsigned char *) xmalloc (len2_byte);
3744 else
3745 temp = (unsigned char *) alloca (len2_byte);
3746 start1_addr = BYTE_POS_ADDR (start1_byte);
3747 start2_addr = BYTE_POS_ADDR (start2_byte);
3748 bcopy (start2_addr, temp, len2_byte);
3749 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
3750 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3751 bcopy (temp, start1_addr, len2_byte);
3752 if (len2_byte > 20000)
3753 xfree (temp);
3754 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3755 len1, current_buffer, 0);
3756 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3757 len_mid, current_buffer, 0);
3758 graft_intervals_into_buffer (tmp_interval2, start1,
3759 len2, current_buffer, 0);
3761 else
3762 /* Second region smaller than first. */
3764 record_change (start1, (end2 - start1));
3765 modify_region (current_buffer, start1, end2);
3767 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3768 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3769 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3770 Fset_text_properties (make_number (start1), make_number (end2),
3771 Qnil, Qnil);
3773 /* holds region 1 */
3774 if (len1_byte > 20000)
3775 temp = (unsigned char *) xmalloc (len1_byte);
3776 else
3777 temp = (unsigned char *) alloca (len1_byte);
3778 start1_addr = BYTE_POS_ADDR (start1_byte);
3779 start2_addr = BYTE_POS_ADDR (start2_byte);
3780 bcopy (start1_addr, temp, len1_byte);
3781 bcopy (start2_addr, start1_addr, len2_byte);
3782 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3783 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
3784 if (len1_byte > 20000)
3785 xfree (temp);
3786 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3787 len1, current_buffer, 0);
3788 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3789 len_mid, current_buffer, 0);
3790 graft_intervals_into_buffer (tmp_interval2, start1,
3791 len2, current_buffer, 0);
3794 update_compositions (start1, start1 + len2, CHECK_BORDER);
3795 update_compositions (end2 - len1, end2, CHECK_BORDER);
3798 /* When doing multiple transpositions, it might be nice
3799 to optimize this. Perhaps the markers in any one buffer
3800 should be organized in some sorted data tree. */
3801 if (NILP (leave_markers))
3803 transpose_markers (start1, end1, start2, end2,
3804 start1_byte, start1_byte + len1_byte,
3805 start2_byte, start2_byte + len2_byte);
3806 fix_overlays_in_range (start1, end2);
3809 return Qnil;
3813 void
3814 syms_of_editfns ()
3816 environbuf = 0;
3818 Qbuffer_access_fontify_functions
3819 = intern ("buffer-access-fontify-functions");
3820 staticpro (&Qbuffer_access_fontify_functions);
3822 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
3823 "Non-nil means.text motion commands don't notice fields.");
3824 Vinhibit_field_text_motion = Qnil;
3826 DEFVAR_LISP ("buffer-access-fontify-functions",
3827 &Vbuffer_access_fontify_functions,
3828 "List of functions called by `buffer-substring' to fontify if necessary.\n\
3829 Each function is called with two arguments which specify the range\n\
3830 of the buffer being accessed.");
3831 Vbuffer_access_fontify_functions = Qnil;
3834 Lisp_Object obuf;
3835 extern Lisp_Object Vprin1_to_string_buffer;
3836 obuf = Fcurrent_buffer ();
3837 /* Do this here, because init_buffer_once is too early--it won't work. */
3838 Fset_buffer (Vprin1_to_string_buffer);
3839 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
3840 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
3841 Qnil);
3842 Fset_buffer (obuf);
3845 DEFVAR_LISP ("buffer-access-fontified-property",
3846 &Vbuffer_access_fontified_property,
3847 "Property which (if non-nil) indicates text has been fontified.\n\
3848 `buffer-substring' need not call the `buffer-access-fontify-functions'\n\
3849 functions if all the text being accessed has this property.");
3850 Vbuffer_access_fontified_property = Qnil;
3852 DEFVAR_LISP ("system-name", &Vsystem_name,
3853 "The name of the machine Emacs is running on.");
3855 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
3856 "The full name of the user logged in.");
3858 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
3859 "The user's name, taken from environment variables if possible.");
3861 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
3862 "The user's name, based upon the real uid only.");
3864 defsubr (&Spropertize);
3865 defsubr (&Schar_equal);
3866 defsubr (&Sgoto_char);
3867 defsubr (&Sstring_to_char);
3868 defsubr (&Schar_to_string);
3869 defsubr (&Sbuffer_substring);
3870 defsubr (&Sbuffer_substring_no_properties);
3871 defsubr (&Sbuffer_string);
3873 defsubr (&Spoint_marker);
3874 defsubr (&Smark_marker);
3875 defsubr (&Spoint);
3876 defsubr (&Sregion_beginning);
3877 defsubr (&Sregion_end);
3879 staticpro (&Qfield);
3880 Qfield = intern ("field");
3881 staticpro (&Qboundary);
3882 Qboundary = intern ("boundary");
3883 defsubr (&Sfield_beginning);
3884 defsubr (&Sfield_end);
3885 defsubr (&Sfield_string);
3886 defsubr (&Sfield_string_no_properties);
3887 defsubr (&Sdelete_field);
3888 defsubr (&Sconstrain_to_field);
3890 defsubr (&Sline_beginning_position);
3891 defsubr (&Sline_end_position);
3893 /* defsubr (&Smark); */
3894 /* defsubr (&Sset_mark); */
3895 defsubr (&Ssave_excursion);
3896 defsubr (&Ssave_current_buffer);
3898 defsubr (&Sbufsize);
3899 defsubr (&Spoint_max);
3900 defsubr (&Spoint_min);
3901 defsubr (&Spoint_min_marker);
3902 defsubr (&Spoint_max_marker);
3903 defsubr (&Sgap_position);
3904 defsubr (&Sgap_size);
3905 defsubr (&Sposition_bytes);
3906 defsubr (&Sbyte_to_position);
3908 defsubr (&Sbobp);
3909 defsubr (&Seobp);
3910 defsubr (&Sbolp);
3911 defsubr (&Seolp);
3912 defsubr (&Sfollowing_char);
3913 defsubr (&Sprevious_char);
3914 defsubr (&Schar_after);
3915 defsubr (&Schar_before);
3916 defsubr (&Sinsert);
3917 defsubr (&Sinsert_before_markers);
3918 defsubr (&Sinsert_and_inherit);
3919 defsubr (&Sinsert_and_inherit_before_markers);
3920 defsubr (&Sinsert_char);
3922 defsubr (&Suser_login_name);
3923 defsubr (&Suser_real_login_name);
3924 defsubr (&Suser_uid);
3925 defsubr (&Suser_real_uid);
3926 defsubr (&Suser_full_name);
3927 defsubr (&Semacs_pid);
3928 defsubr (&Scurrent_time);
3929 defsubr (&Sformat_time_string);
3930 defsubr (&Sfloat_time);
3931 defsubr (&Sdecode_time);
3932 defsubr (&Sencode_time);
3933 defsubr (&Scurrent_time_string);
3934 defsubr (&Scurrent_time_zone);
3935 defsubr (&Sset_time_zone_rule);
3936 defsubr (&Ssystem_name);
3937 defsubr (&Smessage);
3938 defsubr (&Smessage_box);
3939 defsubr (&Smessage_or_box);
3940 defsubr (&Scurrent_message);
3941 defsubr (&Sformat);
3943 defsubr (&Sinsert_buffer_substring);
3944 defsubr (&Scompare_buffer_substrings);
3945 defsubr (&Ssubst_char_in_region);
3946 defsubr (&Stranslate_region);
3947 defsubr (&Sdelete_region);
3948 defsubr (&Sdelete_and_extract_region);
3949 defsubr (&Swiden);
3950 defsubr (&Snarrow_to_region);
3951 defsubr (&Ssave_restriction);
3952 defsubr (&Stranspose_regions);