(File Shadowing): New.
[emacs.git] / src / editfns.c
blobeab21a4e82a308e83aaa26ccfb364a2874772d0e
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 extern char **environ;
53 extern Lisp_Object make_time P_ ((time_t));
54 extern size_t emacs_strftimeu P_ ((char *, size_t, const char *,
55 const struct tm *, int));
56 static int tm_diff P_ ((struct tm *, struct tm *));
57 static void find_field P_ ((Lisp_Object, Lisp_Object, int *, int *));
58 static void update_buffer_properties P_ ((int, int));
59 static Lisp_Object region_limit P_ ((int));
60 static int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
61 static size_t emacs_memftimeu P_ ((char *, size_t, const char *,
62 size_t, const struct tm *, int));
63 static void general_insert_function P_ ((void (*) (unsigned char *, int),
64 void (*) (Lisp_Object, int, int, int,
65 int, int),
66 int, int, Lisp_Object *));
67 static Lisp_Object subst_char_in_region_unwind P_ ((Lisp_Object));
68 static Lisp_Object subst_char_in_region_unwind_1 P_ ((Lisp_Object));
69 static void transpose_markers P_ ((int, int, int, int, int, int, int, int));
71 Lisp_Object Vbuffer_access_fontify_functions;
72 Lisp_Object Qbuffer_access_fontify_functions;
73 Lisp_Object Vbuffer_access_fontified_property;
75 Lisp_Object Fuser_full_name P_ ((Lisp_Object));
77 /* Non-nil means don't stop at field boundary in text motion commands. */
79 Lisp_Object Vinhibit_field_text_motion;
81 /* Some static data, and a function to initialize it for each run */
83 Lisp_Object Vsystem_name;
84 Lisp_Object Vuser_real_login_name; /* login name of current user ID */
85 Lisp_Object Vuser_full_name; /* full name of current user */
86 Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
88 /* Symbol for the text property used to mark fields. */
90 Lisp_Object Qfield;
92 /* A special value for Qfield properties. */
94 Lisp_Object Qboundary;
97 void
98 init_editfns ()
100 char *user_name;
101 register unsigned char *p;
102 struct passwd *pw; /* password entry for the current user */
103 Lisp_Object tem;
105 /* Set up system_name even when dumping. */
106 init_system_name ();
108 #ifndef CANNOT_DUMP
109 /* Don't bother with this on initial start when just dumping out */
110 if (!initialized)
111 return;
112 #endif /* not CANNOT_DUMP */
114 pw = (struct passwd *) getpwuid (getuid ());
115 #ifdef MSDOS
116 /* We let the real user name default to "root" because that's quite
117 accurate on MSDOG and because it lets Emacs find the init file.
118 (The DVX libraries override the Djgpp libraries here.) */
119 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
120 #else
121 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
122 #endif
124 /* Get the effective user name, by consulting environment variables,
125 or the effective uid if those are unset. */
126 user_name = (char *) getenv ("LOGNAME");
127 if (!user_name)
128 #ifdef WINDOWSNT
129 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
130 #else /* WINDOWSNT */
131 user_name = (char *) getenv ("USER");
132 #endif /* WINDOWSNT */
133 if (!user_name)
135 pw = (struct passwd *) getpwuid (geteuid ());
136 user_name = (char *) (pw ? pw->pw_name : "unknown");
138 Vuser_login_name = build_string (user_name);
140 /* If the user name claimed in the environment vars differs from
141 the real uid, use the claimed name to find the full name. */
142 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
143 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
144 : Vuser_login_name);
146 p = (unsigned char *) getenv ("NAME");
147 if (p)
148 Vuser_full_name = build_string (p);
149 else if (NILP (Vuser_full_name))
150 Vuser_full_name = build_string ("unknown");
153 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
154 "Convert arg CHAR to a string containing that character.")
155 (character)
156 Lisp_Object character;
158 int len;
159 unsigned char str[MAX_MULTIBYTE_LENGTH];
161 CHECK_NUMBER (character, 0);
163 len = CHAR_STRING (XFASTINT (character), str);
164 return make_string_from_bytes (str, 1, len);
167 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
168 "Convert arg STRING to a character, the first character of that string.\n\
169 A multibyte character is handled correctly.")
170 (string)
171 register Lisp_Object string;
173 register Lisp_Object val;
174 register struct Lisp_String *p;
175 CHECK_STRING (string, 0);
176 p = XSTRING (string);
177 if (p->size)
179 if (STRING_MULTIBYTE (string))
180 XSETFASTINT (val, STRING_CHAR (p->data, STRING_BYTES (p)));
181 else
182 XSETFASTINT (val, p->data[0]);
184 else
185 XSETFASTINT (val, 0);
186 return val;
189 static Lisp_Object
190 buildmark (charpos, bytepos)
191 int charpos, bytepos;
193 register Lisp_Object mark;
194 mark = Fmake_marker ();
195 set_marker_both (mark, Qnil, charpos, bytepos);
196 return mark;
199 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
200 "Return value of point, as an integer.\n\
201 Beginning of buffer is position (point-min)")
204 Lisp_Object temp;
205 XSETFASTINT (temp, PT);
206 return temp;
209 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
210 "Return value of point, as a marker object.")
213 return buildmark (PT, PT_BYTE);
217 clip_to_bounds (lower, num, upper)
218 int lower, num, upper;
220 if (num < lower)
221 return lower;
222 else if (num > upper)
223 return upper;
224 else
225 return num;
228 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
229 "Set point to POSITION, a number or marker.\n\
230 Beginning of buffer is position (point-min), end is (point-max).\n\
231 If the position is in the middle of a multibyte form,\n\
232 the actual point is set at the head of the multibyte form\n\
233 except in the case that `enable-multibyte-characters' is nil.")
234 (position)
235 register Lisp_Object position;
237 int pos;
239 if (MARKERP (position)
240 && current_buffer == XMARKER (position)->buffer)
242 pos = marker_position (position);
243 if (pos < BEGV)
244 SET_PT_BOTH (BEGV, BEGV_BYTE);
245 else if (pos > ZV)
246 SET_PT_BOTH (ZV, ZV_BYTE);
247 else
248 SET_PT_BOTH (pos, marker_byte_position (position));
250 return position;
253 CHECK_NUMBER_COERCE_MARKER (position, 0);
255 pos = clip_to_bounds (BEGV, XINT (position), ZV);
256 SET_PT (pos);
257 return position;
261 /* Return the start or end position of the region.
262 BEGINNINGP non-zero means return the start.
263 If there is no region active, signal an error. */
265 static Lisp_Object
266 region_limit (beginningp)
267 int beginningp;
269 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
270 Lisp_Object m;
272 if (!NILP (Vtransient_mark_mode)
273 && NILP (Vmark_even_if_inactive)
274 && NILP (current_buffer->mark_active))
275 Fsignal (Qmark_inactive, Qnil);
277 m = Fmarker_position (current_buffer->mark);
278 if (NILP (m))
279 error ("There is no region now");
281 if ((PT < XFASTINT (m)) == beginningp)
282 m = make_number (PT);
283 return m;
286 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
287 "Return position of beginning of region, as an integer.")
290 return region_limit (1);
293 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
294 "Return position of end of region, as an integer.")
297 return region_limit (0);
300 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
301 "Return this buffer's mark, as a marker object.\n\
302 Watch out! Moving this marker changes the mark position.\n\
303 If you set the marker not to point anywhere, the buffer will have no mark.")
306 return current_buffer->mark;
310 /* Return nonzero if POS1 and POS2 have the same value
311 for the text property PROP. */
313 static int
314 char_property_eq (prop, pos1, pos2)
315 Lisp_Object prop;
316 Lisp_Object pos1, pos2;
318 Lisp_Object pval1, pval2;
320 pval1 = Fget_char_property (pos1, prop, Qnil);
321 pval2 = Fget_char_property (pos2, prop, Qnil);
323 return EQ (pval1, pval2);
326 /* Return the direction from which the char-property PROP would be
327 inherited by any new text inserted at POS: 1 if it would be
328 inherited from the char after POS, -1 if it would be inherited from
329 the char before POS, and 0 if from neither. */
331 static int
332 char_property_stickiness (prop, pos)
333 Lisp_Object prop;
334 Lisp_Object pos;
336 Lisp_Object front_sticky;
338 if (XINT (pos) > BEGV)
339 /* Consider previous character. */
341 Lisp_Object prev_pos, rear_non_sticky;
343 prev_pos = make_number (XINT (pos) - 1);
344 rear_non_sticky = Fget_char_property (prev_pos, Qrear_nonsticky, Qnil);
346 if (EQ (rear_non_sticky, Qnil)
347 || (CONSP (rear_non_sticky)
348 && NILP (Fmemq (prop, rear_non_sticky))))
349 /* PROP is not rear-non-sticky, and since this takes precedence over
350 any front-stickiness, PROP is inherited from before. */
351 return -1;
354 /* Consider following character. */
355 front_sticky = Fget_char_property (pos, Qfront_sticky, Qnil);
357 if (EQ (front_sticky, Qt)
358 || (CONSP (front_sticky)
359 && !NILP (Fmemq (prop, front_sticky))))
360 /* PROP is inherited from after. */
361 return 1;
363 /* PROP is not inherited from either side. */
364 return 0;
368 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
369 the value of point is used instead. If BEG or END null,
370 means don't store the beginning or end of the field.
372 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
373 position of a field, then the beginning of the previous field is
374 returned instead of the beginning of POS's field (since the end of a
375 field is actually also the beginning of the next input field, this
376 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
377 true case, if two fields are separated by a field with the special
378 value `boundary', and POS lies within it, then the two separated
379 fields are considered to be adjacent, and POS between them, when
380 finding the beginning and ending of the "merged" field.
382 Either BEG or END may be 0, in which case the corresponding value
383 is not stored. */
385 static void
386 find_field (pos, merge_at_boundary, beg, end)
387 Lisp_Object pos;
388 Lisp_Object merge_at_boundary;
389 int *beg, *end;
391 /* Fields right before and after the point. */
392 Lisp_Object before_field, after_field;
393 /* 1 if POS counts as the start of a field. */
394 int at_field_start = 0;
395 /* 1 if POS counts as the end of a field. */
396 int at_field_end = 0;
398 if (NILP (pos))
399 XSETFASTINT (pos, PT);
400 else
401 CHECK_NUMBER_COERCE_MARKER (pos, 0);
403 after_field
404 = Fget_char_property (pos, Qfield, Qnil);
405 before_field
406 = (XFASTINT (pos) > BEGV
407 ? Fget_char_property (make_number (XINT (pos) - 1), Qfield, Qnil)
408 : Qnil);
410 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
411 and POS is at beginning of a field, which can also be interpreted
412 as the end of the previous field. Note that the case where if
413 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
414 more natural one; then we avoid treating the beginning of a field
415 specially. */
416 if (NILP (merge_at_boundary) && !EQ (after_field, before_field))
417 /* We are at a boundary, see which direction is inclusive. We
418 decide by seeing which field the `field' property sticks to. */
420 int stickiness = char_property_stickiness (Qfield, pos);
422 if (stickiness > 0)
423 at_field_start = 1;
424 else if (stickiness < 0)
425 at_field_end = 1;
426 else
427 /* STICKINESS == 0 means that any inserted text will get a
428 `field' char-property of nil, so check to see if that
429 matches either of the adjacent characters (this being a
430 kind of "stickiness by default"). */
432 if (NILP (before_field))
433 at_field_end = 1; /* Sticks to the left. */
434 else if (NILP (after_field))
435 at_field_start = 1; /* Sticks to the right. */
439 /* Note about special `boundary' fields:
441 Consider the case where the point (`.') is between the fields `x' and `y':
443 xxxx.yyyy
445 In this situation, if merge_at_boundary is true, we consider the
446 `x' and `y' fields as forming one big merged field, and so the end
447 of the field is the end of `y'.
449 However, if `x' and `y' are separated by a special `boundary' field
450 (a field with a `field' char-property of 'boundary), then we ignore
451 this special field when merging adjacent fields. Here's the same
452 situation, but with a `boundary' field between the `x' and `y' fields:
454 xxx.BBBByyyy
456 Here, if point is at the end of `x', the beginning of `y', or
457 anywhere in-between (within the `boundary' field), we merge all
458 three fields and consider the beginning as being the beginning of
459 the `x' field, and the end as being the end of the `y' field. */
461 if (beg)
463 if (at_field_start)
464 /* POS is at the edge of a field, and we should consider it as
465 the beginning of the following field. */
466 *beg = XFASTINT (pos);
467 else
468 /* Find the previous field boundary. */
470 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
471 /* Skip a `boundary' field. */
472 pos = Fprevious_single_char_property_change (pos, Qfield, Qnil,Qnil);
474 pos = Fprevious_single_char_property_change (pos, Qfield, Qnil, Qnil);
475 *beg = NILP (pos) ? BEGV : XFASTINT (pos);
479 if (end)
481 if (at_field_end)
482 /* POS is at the edge of a field, and we should consider it as
483 the end of the previous field. */
484 *end = XFASTINT (pos);
485 else
486 /* Find the next field boundary. */
488 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
489 /* Skip a `boundary' field. */
490 pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
492 pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
493 *end = NILP (pos) ? ZV : XFASTINT (pos);
499 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
500 "Delete the field surrounding POS.\n\
501 A field is a region of text with the same `field' property.\n\
502 If POS is nil, the value of point is used for POS.")
503 (pos)
504 Lisp_Object pos;
506 int beg, end;
507 find_field (pos, Qnil, &beg, &end);
508 if (beg != end)
509 del_range (beg, end);
510 return Qnil;
513 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
514 "Return the contents of the field surrounding POS as a string.\n\
515 A field is a region of text with the same `field' property.\n\
516 If POS is nil, the value of point is used for POS.")
517 (pos)
518 Lisp_Object pos;
520 int beg, end;
521 find_field (pos, Qnil, &beg, &end);
522 return make_buffer_string (beg, end, 1);
525 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
526 "Return the contents of the field around POS, without text-properties.\n\
527 A field is a region of text with the same `field' property.\n\
528 If POS is nil, the value of point is used for POS.")
529 (pos)
530 Lisp_Object pos;
532 int beg, end;
533 find_field (pos, Qnil, &beg, &end);
534 return make_buffer_string (beg, end, 0);
537 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 2, 0,
538 "Return the beginning of the field surrounding POS.\n\
539 A field is a region of text with the same `field' property.\n\
540 If POS is nil, the value of point is used for POS.\n\
541 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its\n\
542 field, then the beginning of the *previous* field is returned.")
543 (pos, escape_from_edge)
544 Lisp_Object pos, escape_from_edge;
546 int beg;
547 find_field (pos, escape_from_edge, &beg, 0);
548 return make_number (beg);
551 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 2, 0,
552 "Return the end of the field surrounding POS.\n\
553 A field is a region of text with the same `field' property.\n\
554 If POS is nil, the value of point is used for POS.\n\
555 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,\n\
556 then the end of the *following* field is returned.")
557 (pos, escape_from_edge)
558 Lisp_Object pos, escape_from_edge;
560 int end;
561 find_field (pos, escape_from_edge, 0, &end);
562 return make_number (end);
565 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
566 "Return the position closest to NEW-POS that is in the same field as OLD-POS.\n\
568 A field is a region of text with the same `field' property.\n\
569 If NEW-POS is nil, then the current point is used instead, and set to the\n\
570 constrained position if that is is different.\n\
572 If OLD-POS is at the boundary of two fields, then the allowable\n\
573 positions for NEW-POS depends on the value of the optional argument\n\
574 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is\n\
575 constrained to the field that has the same `field' char-property\n\
576 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE\n\
577 is non-nil, NEW-POS is constrained to the union of the two adjacent\n\
578 fields. Additionally, if two fields are separated by another field with\n\
579 the special value `boundary', then any point within this special field is\n\
580 also considered to be `on the boundary'.\n\
582 If the optional argument ONLY-IN-LINE is non-nil and constraining\n\
583 NEW-POS would move it to a different line, NEW-POS is returned\n\
584 unconstrained. This useful for commands that move by line, like\n\
585 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries\n\
586 only in the case where they can still move to the right line.\n\
588 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has\n\
589 a non-nil property of that name, then any field boundaries are ignored.\n\
591 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil.")
592 (new_pos, old_pos, escape_from_edge, only_in_line, inhibit_capture_property)
593 Lisp_Object new_pos, old_pos;
594 Lisp_Object escape_from_edge, only_in_line, inhibit_capture_property;
596 /* If non-zero, then the original point, before re-positioning. */
597 int orig_point = 0;
599 if (NILP (new_pos))
600 /* Use the current point, and afterwards, set it. */
602 orig_point = PT;
603 XSETFASTINT (new_pos, PT);
606 if (NILP (Vinhibit_field_text_motion)
607 && !EQ (new_pos, old_pos)
608 && !char_property_eq (Qfield, new_pos, old_pos)
609 && (NILP (inhibit_capture_property)
610 || NILP (Fget_char_property(old_pos, inhibit_capture_property, Qnil))))
611 /* NEW_POS is not within the same field as OLD_POS; try to
612 move NEW_POS so that it is. */
614 int fwd, shortage;
615 Lisp_Object field_bound;
617 CHECK_NUMBER_COERCE_MARKER (new_pos, 0);
618 CHECK_NUMBER_COERCE_MARKER (old_pos, 0);
620 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
622 if (fwd)
623 field_bound = Ffield_end (old_pos, escape_from_edge);
624 else
625 field_bound = Ffield_beginning (old_pos, escape_from_edge);
627 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
628 other side of NEW_POS, which would mean that NEW_POS is
629 already acceptable, and it's not necessary to constrain it
630 to FIELD_BOUND. */
631 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
632 /* NEW_POS should be constrained, but only if either
633 ONLY_IN_LINE is nil (in which case any constraint is OK),
634 or NEW_POS and FIELD_BOUND are on the same line (in which
635 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
636 && (NILP (only_in_line)
637 /* This is the ONLY_IN_LINE case, check that NEW_POS and
638 FIELD_BOUND are on the same line by seeing whether
639 there's an intervening newline or not. */
640 || (scan_buffer ('\n',
641 XFASTINT (new_pos), XFASTINT (field_bound),
642 fwd ? -1 : 1, &shortage, 1),
643 shortage != 0)))
644 /* Constrain NEW_POS to FIELD_BOUND. */
645 new_pos = field_bound;
647 if (orig_point && XFASTINT (new_pos) != orig_point)
648 /* The NEW_POS argument was originally nil, so automatically set PT. */
649 SET_PT (XFASTINT (new_pos));
652 return new_pos;
656 DEFUN ("line-beginning-position", Fline_beginning_position, Sline_beginning_position,
657 0, 1, 0,
658 "Return the character position of the first character on the current line.\n\
659 With argument N not nil or 1, move forward N - 1 lines first.\n\
660 If scan reaches end of buffer, return that position.\n\
661 The scan does not cross a field boundary unless it would move\n\
662 beyond there to a different line. Field boundaries are not noticed if\n\
663 `inhibit-field-text-motion' is non-nil. .And if N is nil or 1,\n\
664 and scan starts at a field boundary, the scan stops as soon as it starts.\n\
666 This function does not move point.")
668 Lisp_Object n;
670 int orig, orig_byte, end;
672 if (NILP (n))
673 XSETFASTINT (n, 1);
674 else
675 CHECK_NUMBER (n, 0);
677 orig = PT;
678 orig_byte = PT_BYTE;
679 Fforward_line (make_number (XINT (n) - 1));
680 end = PT;
682 SET_PT_BOTH (orig, orig_byte);
684 /* Return END constrained to the current input field. */
685 return Fconstrain_to_field (make_number (end), make_number (orig),
686 XINT (n) != 1 ? Qt : Qnil,
687 Qt, Qnil);
690 DEFUN ("line-end-position", Fline_end_position, Sline_end_position,
691 0, 1, 0,
692 "Return the character position of the last character on the current line.\n\
693 With argument N not nil or 1, move forward N - 1 lines first.\n\
694 If scan reaches end of buffer, return that position.\n\
695 This function does not move point.")
697 Lisp_Object n;
699 int end_pos;
700 int orig = PT;
702 if (NILP (n))
703 XSETFASTINT (n, 1);
704 else
705 CHECK_NUMBER (n, 0);
707 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
709 /* Return END_POS constrained to the current input field. */
710 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
711 Qnil, Qt, Qnil);
714 Lisp_Object
715 save_excursion_save ()
717 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
718 == current_buffer);
720 return Fcons (Fpoint_marker (),
721 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
722 Fcons (visible ? Qt : Qnil,
723 current_buffer->mark_active)));
726 Lisp_Object
727 save_excursion_restore (info)
728 Lisp_Object info;
730 Lisp_Object tem, tem1, omark, nmark;
731 struct gcpro gcpro1, gcpro2, gcpro3;
733 tem = Fmarker_buffer (Fcar (info));
734 /* If buffer being returned to is now deleted, avoid error */
735 /* Otherwise could get error here while unwinding to top level
736 and crash */
737 /* In that case, Fmarker_buffer returns nil now. */
738 if (NILP (tem))
739 return Qnil;
741 omark = nmark = Qnil;
742 GCPRO3 (info, omark, nmark);
744 Fset_buffer (tem);
745 tem = Fcar (info);
746 Fgoto_char (tem);
747 unchain_marker (tem);
748 tem = Fcar (Fcdr (info));
749 omark = Fmarker_position (current_buffer->mark);
750 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
751 nmark = Fmarker_position (tem);
752 unchain_marker (tem);
753 tem = Fcdr (Fcdr (info));
754 #if 0 /* We used to make the current buffer visible in the selected window
755 if that was true previously. That avoids some anomalies.
756 But it creates others, and it wasn't documented, and it is simpler
757 and cleaner never to alter the window/buffer connections. */
758 tem1 = Fcar (tem);
759 if (!NILP (tem1)
760 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
761 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
762 #endif /* 0 */
764 tem1 = current_buffer->mark_active;
765 current_buffer->mark_active = Fcdr (tem);
766 if (!NILP (Vrun_hooks))
768 /* If mark is active now, and either was not active
769 or was at a different place, run the activate hook. */
770 if (! NILP (current_buffer->mark_active))
772 if (! EQ (omark, nmark))
773 call1 (Vrun_hooks, intern ("activate-mark-hook"));
775 /* If mark has ceased to be active, run deactivate hook. */
776 else if (! NILP (tem1))
777 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
779 UNGCPRO;
780 return Qnil;
783 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
784 "Save point, mark, and current buffer; execute BODY; restore those things.\n\
785 Executes BODY just like `progn'.\n\
786 The values of point, mark and the current buffer are restored\n\
787 even in case of abnormal exit (throw or error).\n\
788 The state of activation of the mark is also restored.\n\
790 This construct does not save `deactivate-mark', and therefore\n\
791 functions that change the buffer will still cause deactivation\n\
792 of the mark at the end of the command. To prevent that, bind\n\
793 `deactivate-mark' with `let'.")
794 (args)
795 Lisp_Object args;
797 register Lisp_Object val;
798 int count = specpdl_ptr - specpdl;
800 record_unwind_protect (save_excursion_restore, save_excursion_save ());
802 val = Fprogn (args);
803 return unbind_to (count, val);
806 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
807 "Save the current buffer; execute BODY; restore the current buffer.\n\
808 Executes BODY just like `progn'.")
809 (args)
810 Lisp_Object args;
812 Lisp_Object val;
813 int count = specpdl_ptr - specpdl;
815 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
817 val = Fprogn (args);
818 return unbind_to (count, val);
821 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
822 "Return the number of characters in the current buffer.\n\
823 If BUFFER, return the number of characters in that buffer instead.")
824 (buffer)
825 Lisp_Object buffer;
827 if (NILP (buffer))
828 return make_number (Z - BEG);
829 else
831 CHECK_BUFFER (buffer, 1);
832 return make_number (BUF_Z (XBUFFER (buffer))
833 - BUF_BEG (XBUFFER (buffer)));
837 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
838 "Return the minimum permissible value of point in the current buffer.\n\
839 This is 1, unless narrowing (a buffer restriction) is in effect.")
842 Lisp_Object temp;
843 XSETFASTINT (temp, BEGV);
844 return temp;
847 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
848 "Return a marker to the minimum permissible value of point in this buffer.\n\
849 This is the beginning, unless narrowing (a buffer restriction) is in effect.")
852 return buildmark (BEGV, BEGV_BYTE);
855 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
856 "Return the maximum permissible value of point in the current buffer.\n\
857 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
858 is in effect, in which case it is less.")
861 Lisp_Object temp;
862 XSETFASTINT (temp, ZV);
863 return temp;
866 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
867 "Return a marker to the maximum permissible value of point in this buffer.\n\
868 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
869 is in effect, in which case it is less.")
872 return buildmark (ZV, ZV_BYTE);
875 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
876 "Return the position of the gap, in the current buffer.\n\
877 See also `gap-size'.")
880 Lisp_Object temp;
881 XSETFASTINT (temp, GPT);
882 return temp;
885 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
886 "Return the size of the current buffer's gap.\n\
887 See also `gap-position'.")
890 Lisp_Object temp;
891 XSETFASTINT (temp, GAP_SIZE);
892 return temp;
895 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
896 "Return the byte position for character position POSITION.\n\
897 If POSITION is out of range, the value is nil.")
898 (position)
899 Lisp_Object position;
901 CHECK_NUMBER_COERCE_MARKER (position, 1);
902 if (XINT (position) < BEG || XINT (position) > Z)
903 return Qnil;
904 return make_number (CHAR_TO_BYTE (XINT (position)));
907 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
908 "Return the character position for byte position BYTEPOS.\n\
909 If BYTEPOS is out of range, the value is nil.")
910 (bytepos)
911 Lisp_Object bytepos;
913 CHECK_NUMBER (bytepos, 1);
914 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
915 return Qnil;
916 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
919 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
920 "Return the character following point, as a number.\n\
921 At the end of the buffer or accessible region, return 0.")
924 Lisp_Object temp;
925 if (PT >= ZV)
926 XSETFASTINT (temp, 0);
927 else
928 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
929 return temp;
932 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
933 "Return the character preceding point, as a number.\n\
934 At the beginning of the buffer or accessible region, return 0.")
937 Lisp_Object temp;
938 if (PT <= BEGV)
939 XSETFASTINT (temp, 0);
940 else if (!NILP (current_buffer->enable_multibyte_characters))
942 int pos = PT_BYTE;
943 DEC_POS (pos);
944 XSETFASTINT (temp, FETCH_CHAR (pos));
946 else
947 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
948 return temp;
951 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
952 "Return t if point is at the beginning of the buffer.\n\
953 If the buffer is narrowed, this means the beginning of the narrowed part.")
956 if (PT == BEGV)
957 return Qt;
958 return Qnil;
961 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
962 "Return t if point is at the end of the buffer.\n\
963 If the buffer is narrowed, this means the end of the narrowed part.")
966 if (PT == ZV)
967 return Qt;
968 return Qnil;
971 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
972 "Return t if point is at the beginning of a line.")
975 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
976 return Qt;
977 return Qnil;
980 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
981 "Return t if point is at the end of a line.\n\
982 `End of a line' includes point being at the end of the buffer.")
985 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
986 return Qt;
987 return Qnil;
990 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
991 "Return character in current buffer at position POS.\n\
992 POS is an integer or a marker.\n\
993 If POS is out of range, the value is nil.")
994 (pos)
995 Lisp_Object pos;
997 register int pos_byte;
999 if (NILP (pos))
1001 pos_byte = PT_BYTE;
1002 XSETFASTINT (pos, PT);
1005 if (MARKERP (pos))
1007 pos_byte = marker_byte_position (pos);
1008 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1009 return Qnil;
1011 else
1013 CHECK_NUMBER_COERCE_MARKER (pos, 0);
1014 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1015 return Qnil;
1017 pos_byte = CHAR_TO_BYTE (XINT (pos));
1020 return make_number (FETCH_CHAR (pos_byte));
1023 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1024 "Return character in current buffer preceding position POS.\n\
1025 POS is an integer or a marker.\n\
1026 If POS is out of range, the value is nil.")
1027 (pos)
1028 Lisp_Object pos;
1030 register Lisp_Object val;
1031 register int pos_byte;
1033 if (NILP (pos))
1035 pos_byte = PT_BYTE;
1036 XSETFASTINT (pos, PT);
1039 if (MARKERP (pos))
1041 pos_byte = marker_byte_position (pos);
1043 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1044 return Qnil;
1046 else
1048 CHECK_NUMBER_COERCE_MARKER (pos, 0);
1050 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1051 return Qnil;
1053 pos_byte = CHAR_TO_BYTE (XINT (pos));
1056 if (!NILP (current_buffer->enable_multibyte_characters))
1058 DEC_POS (pos_byte);
1059 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1061 else
1063 pos_byte--;
1064 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1066 return val;
1069 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1070 "Return the name under which the user logged in, as a string.\n\
1071 This is based on the effective uid, not the real uid.\n\
1072 Also, if the environment variable LOGNAME or USER is set,\n\
1073 that determines the value of this function.\n\n\
1074 If optional argument UID is an integer, return the login name of the user\n\
1075 with that uid, or nil if there is no such user.")
1076 (uid)
1077 Lisp_Object uid;
1079 struct passwd *pw;
1081 /* Set up the user name info if we didn't do it before.
1082 (That can happen if Emacs is dumpable
1083 but you decide to run `temacs -l loadup' and not dump. */
1084 if (INTEGERP (Vuser_login_name))
1085 init_editfns ();
1087 if (NILP (uid))
1088 return Vuser_login_name;
1090 CHECK_NUMBER (uid, 0);
1091 pw = (struct passwd *) getpwuid (XINT (uid));
1092 return (pw ? build_string (pw->pw_name) : Qnil);
1095 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1096 0, 0, 0,
1097 "Return the name of the user's real uid, as a string.\n\
1098 This ignores the environment variables LOGNAME and USER, so it differs from\n\
1099 `user-login-name' when running under `su'.")
1102 /* Set up the user name info if we didn't do it before.
1103 (That can happen if Emacs is dumpable
1104 but you decide to run `temacs -l loadup' and not dump. */
1105 if (INTEGERP (Vuser_login_name))
1106 init_editfns ();
1107 return Vuser_real_login_name;
1110 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1111 "Return the effective uid of Emacs, as an integer.")
1114 return make_number (geteuid ());
1117 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1118 "Return the real uid of Emacs, as an integer.")
1121 return make_number (getuid ());
1124 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1125 "Return the full name of the user logged in, as a string.\n\
1126 If the full name corresponding to Emacs's userid is not known,\n\
1127 return \"unknown\".\n\
1129 If optional argument UID is an integer, return the full name of the user\n\
1130 with that uid, or nil if there is no such user.\n\
1131 If UID is a string, return the full name of the user with that login\n\
1132 name, or nil if there is no such user.")
1133 (uid)
1134 Lisp_Object uid;
1136 struct passwd *pw;
1137 register unsigned char *p, *q;
1138 extern char *index ();
1139 Lisp_Object full;
1141 if (NILP (uid))
1142 return Vuser_full_name;
1143 else if (NUMBERP (uid))
1144 pw = (struct passwd *) getpwuid (XINT (uid));
1145 else if (STRINGP (uid))
1146 pw = (struct passwd *) getpwnam (XSTRING (uid)->data);
1147 else
1148 error ("Invalid UID specification");
1150 if (!pw)
1151 return Qnil;
1153 p = (unsigned char *) USER_FULL_NAME;
1154 /* Chop off everything after the first comma. */
1155 q = (unsigned char *) index (p, ',');
1156 full = make_string (p, q ? q - p : strlen (p));
1158 #ifdef AMPERSAND_FULL_NAME
1159 p = XSTRING (full)->data;
1160 q = (unsigned char *) index (p, '&');
1161 /* Substitute the login name for the &, upcasing the first character. */
1162 if (q)
1164 register unsigned char *r;
1165 Lisp_Object login;
1167 login = Fuser_login_name (make_number (pw->pw_uid));
1168 r = (unsigned char *) alloca (strlen (p) + XSTRING (login)->size + 1);
1169 bcopy (p, r, q - p);
1170 r[q - p] = 0;
1171 strcat (r, XSTRING (login)->data);
1172 r[q - p] = UPCASE (r[q - p]);
1173 strcat (r, q + 1);
1174 full = build_string (r);
1176 #endif /* AMPERSAND_FULL_NAME */
1178 return full;
1181 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1182 "Return the name of the machine you are running on, as a string.")
1185 return Vsystem_name;
1188 /* For the benefit of callers who don't want to include lisp.h */
1190 char *
1191 get_system_name ()
1193 if (STRINGP (Vsystem_name))
1194 return (char *) XSTRING (Vsystem_name)->data;
1195 else
1196 return "";
1199 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1200 "Return the process ID of Emacs, as an integer.")
1203 return make_number (getpid ());
1206 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1207 "Return the current time, as the number of seconds since 1970-01-01 00:00:00.\n\
1208 The time is returned as a list of three integers. The first has the\n\
1209 most significant 16 bits of the seconds, while the second has the\n\
1210 least significant 16 bits. The third integer gives the microsecond\n\
1211 count.\n\
1213 The microsecond count is zero on systems that do not provide\n\
1214 resolution finer than a second.")
1217 EMACS_TIME t;
1218 Lisp_Object result[3];
1220 EMACS_GET_TIME (t);
1221 XSETINT (result[0], (EMACS_SECS (t) >> 16) & 0xffff);
1222 XSETINT (result[1], (EMACS_SECS (t) >> 0) & 0xffff);
1223 XSETINT (result[2], EMACS_USECS (t));
1225 return Flist (3, result);
1229 static int
1230 lisp_time_argument (specified_time, result, usec)
1231 Lisp_Object specified_time;
1232 time_t *result;
1233 int *usec;
1235 if (NILP (specified_time))
1237 if (usec)
1239 EMACS_TIME t;
1241 EMACS_GET_TIME (t);
1242 *usec = EMACS_USECS (t);
1243 *result = EMACS_SECS (t);
1244 return 1;
1246 else
1247 return time (result) != -1;
1249 else
1251 Lisp_Object high, low;
1252 high = Fcar (specified_time);
1253 CHECK_NUMBER (high, 0);
1254 low = Fcdr (specified_time);
1255 if (CONSP (low))
1257 if (usec)
1259 Lisp_Object usec_l = Fcdr (low);
1260 if (CONSP (usec_l))
1261 usec_l = Fcar (usec_l);
1262 if (NILP (usec_l))
1263 *usec = 0;
1264 else
1266 CHECK_NUMBER (usec_l, 0);
1267 *usec = XINT (usec_l);
1270 low = Fcar (low);
1272 else if (usec)
1273 *usec = 0;
1274 CHECK_NUMBER (low, 0);
1275 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1276 return *result >> 16 == XINT (high);
1280 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1281 "Return the current time, as a float number of seconds since the epoch.\n\
1282 If an argument is given, it specifies a time to convert to float\n\
1283 instead of the current time. The argument should have the forms:\n\
1284 (HIGH . LOW) or (HIGH LOW USEC) or (HIGH LOW . USEC).\n\
1285 Thus, you can use times obtained from `current-time'\n\
1286 and from `file-attributes'.")
1287 (specified_time)
1288 Lisp_Object specified_time;
1290 time_t sec;
1291 int usec;
1293 if (! lisp_time_argument (specified_time, &sec, &usec))
1294 error ("Invalid time specification");
1296 return make_float (sec + usec * 0.0000001);
1299 /* Write information into buffer S of size MAXSIZE, according to the
1300 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1301 Default to Universal Time if UT is nonzero, local time otherwise.
1302 Return the number of bytes written, not including the terminating
1303 '\0'. If S is NULL, nothing will be written anywhere; so to
1304 determine how many bytes would be written, use NULL for S and
1305 ((size_t) -1) for MAXSIZE.
1307 This function behaves like emacs_strftimeu, except it allows null
1308 bytes in FORMAT. */
1309 static size_t
1310 emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
1311 char *s;
1312 size_t maxsize;
1313 const char *format;
1314 size_t format_len;
1315 const struct tm *tp;
1316 int ut;
1318 size_t total = 0;
1320 /* Loop through all the null-terminated strings in the format
1321 argument. Normally there's just one null-terminated string, but
1322 there can be arbitrarily many, concatenated together, if the
1323 format contains '\0' bytes. emacs_strftimeu stops at the first
1324 '\0' byte so we must invoke it separately for each such string. */
1325 for (;;)
1327 size_t len;
1328 size_t result;
1330 if (s)
1331 s[0] = '\1';
1333 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1335 if (s)
1337 if (result == 0 && s[0] != '\0')
1338 return 0;
1339 s += result + 1;
1342 maxsize -= result + 1;
1343 total += result;
1344 len = strlen (format);
1345 if (len == format_len)
1346 return total;
1347 total++;
1348 format += len + 1;
1349 format_len -= len + 1;
1354 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1355 "Use FORMAT-STRING to format the time TIME, or now if omitted.\n\
1356 TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as returned by\n\
1357 `current-time' or `file-attributes'.\n\
1358 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME\n\
1359 as Universal Time; nil means describe TIME in the local time zone.\n\
1360 The value is a copy of FORMAT-STRING, but with certain constructs replaced\n\
1361 by text that describes the specified date and time in TIME:\n\
1363 %Y is the year, %y within the century, %C the century.\n\
1364 %G is the year corresponding to the ISO week, %g within the century.\n\
1365 %m is the numeric month.\n\
1366 %b and %h are the locale's abbreviated month name, %B the full name.\n\
1367 %d is the day of the month, zero-padded, %e is blank-padded.\n\
1368 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.\n\
1369 %a is the locale's abbreviated name of the day of week, %A the full name.\n\
1370 %U is the week number starting on Sunday, %W starting on Monday,\n\
1371 %V according to ISO 8601.\n\
1372 %j is the day of the year.\n\
1374 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H\n\
1375 only blank-padded, %l is like %I blank-padded.\n\
1376 %p is the locale's equivalent of either AM or PM.\n\
1377 %M is the minute.\n\
1378 %S is the second.\n\
1379 %Z is the time zone name, %z is the numeric form.\n\
1380 %s is the number of seconds since 1970-01-01 00:00:00 +0000.\n\
1382 %c is the locale's date and time format.\n\
1383 %x is the locale's \"preferred\" date format.\n\
1384 %D is like \"%m/%d/%y\".\n\
1386 %R is like \"%H:%M\", %T is like \"%H:%M:%S\", %r is like \"%I:%M:%S %p\".\n\
1387 %X is the locale's \"preferred\" time format.\n\
1389 Finally, %n is a newline, %t is a tab, %% is a literal %.\n\
1391 Certain flags and modifiers are available with some format controls.\n\
1392 The flags are `_' and `-'. For certain characters X, %_X is like %X,\n\
1393 but padded with blanks; %-X is like %X, but without padding.\n\
1394 %NX (where N stands for an integer) is like %X,\n\
1395 but takes up at least N (a number) positions.\n\
1396 The modifiers are `E' and `O'. For certain characters X,\n\
1397 %EX is a locale's alternative version of %X;\n\
1398 %OX is like %X, but uses the locale's number symbols.\n\
1400 For example, to produce full ISO 8601 format, use \"%Y-%m-%dT%T%z\".")
1401 (format_string, time, universal)
1404 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1405 0 /* See immediately above */)
1406 (format_string, time, universal)
1407 Lisp_Object format_string, time, universal;
1409 time_t value;
1410 int size;
1411 struct tm *tm;
1412 int ut = ! NILP (universal);
1414 CHECK_STRING (format_string, 1);
1416 if (! lisp_time_argument (time, &value, NULL))
1417 error ("Invalid time specification");
1419 format_string = code_convert_string_norecord (format_string,
1420 Vlocale_coding_system, 1);
1422 /* This is probably enough. */
1423 size = STRING_BYTES (XSTRING (format_string)) * 6 + 50;
1425 tm = ut ? gmtime (&value) : localtime (&value);
1426 if (! tm)
1427 error ("Specified time is not representable");
1429 synchronize_system_time_locale ();
1431 while (1)
1433 char *buf = (char *) alloca (size + 1);
1434 int result;
1436 buf[0] = '\1';
1437 result = emacs_memftimeu (buf, size, XSTRING (format_string)->data,
1438 STRING_BYTES (XSTRING (format_string)),
1439 tm, ut);
1440 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1441 return code_convert_string_norecord (make_string (buf, result),
1442 Vlocale_coding_system, 0);
1444 /* If buffer was too small, make it bigger and try again. */
1445 result = emacs_memftimeu (NULL, (size_t) -1,
1446 XSTRING (format_string)->data,
1447 STRING_BYTES (XSTRING (format_string)),
1448 tm, ut);
1449 size = result + 1;
1453 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1454 "Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).\n\
1455 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED)\n\
1456 or (HIGH . LOW), as from `current-time' and `file-attributes', or `nil'\n\
1457 to use the current time. The list has the following nine members:\n\
1458 SEC is an integer between 0 and 60; SEC is 60 for a leap second, which\n\
1459 only some operating systems support. MINUTE is an integer between 0 and 59.\n\
1460 HOUR is an integer between 0 and 23. DAY is an integer between 1 and 31.\n\
1461 MONTH is an integer between 1 and 12. YEAR is an integer indicating the\n\
1462 four-digit year. DOW is the day of week, an integer between 0 and 6, where\n\
1463 0 is Sunday. DST is t if daylight savings time is effect, otherwise nil.\n\
1464 ZONE is an integer indicating the number of seconds east of Greenwich.\n\
1465 \(Note that Common Lisp has different meanings for DOW and ZONE.)")
1466 (specified_time)
1467 Lisp_Object specified_time;
1469 time_t time_spec;
1470 struct tm save_tm;
1471 struct tm *decoded_time;
1472 Lisp_Object list_args[9];
1474 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1475 error ("Invalid time specification");
1477 decoded_time = localtime (&time_spec);
1478 if (! decoded_time)
1479 error ("Specified time is not representable");
1480 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1481 XSETFASTINT (list_args[1], decoded_time->tm_min);
1482 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1483 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1484 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1485 XSETINT (list_args[5], decoded_time->tm_year + 1900);
1486 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1487 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1489 /* Make a copy, in case gmtime modifies the struct. */
1490 save_tm = *decoded_time;
1491 decoded_time = gmtime (&time_spec);
1492 if (decoded_time == 0)
1493 list_args[8] = Qnil;
1494 else
1495 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1496 return Flist (9, list_args);
1499 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1500 "Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.\n\
1501 This is the reverse operation of `decode-time', which see.\n\
1502 ZONE defaults to the current time zone rule. This can\n\
1503 be a string or t (as from `set-time-zone-rule'), or it can be a list\n\
1504 \(as from `current-time-zone') or an integer (as from `decode-time')\n\
1505 applied without consideration for daylight savings time.\n\
1507 You can pass more than 7 arguments; then the first six arguments\n\
1508 are used as SECOND through YEAR, and the *last* argument is used as ZONE.\n\
1509 The intervening arguments are ignored.\n\
1510 This feature lets (apply 'encode-time (decode-time ...)) work.\n\
1512 Out-of-range values for SEC, MINUTE, HOUR, DAY, or MONTH are allowed;\n\
1513 for example, a DAY of 0 means the day preceding the given month.\n\
1514 Year numbers less than 100 are treated just like other year numbers.\n\
1515 If you want them to stand for years in this century, you must do that yourself.")
1516 (nargs, args)
1517 int nargs;
1518 register Lisp_Object *args;
1520 time_t time;
1521 struct tm tm;
1522 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1524 CHECK_NUMBER (args[0], 0); /* second */
1525 CHECK_NUMBER (args[1], 1); /* minute */
1526 CHECK_NUMBER (args[2], 2); /* hour */
1527 CHECK_NUMBER (args[3], 3); /* day */
1528 CHECK_NUMBER (args[4], 4); /* month */
1529 CHECK_NUMBER (args[5], 5); /* year */
1531 tm.tm_sec = XINT (args[0]);
1532 tm.tm_min = XINT (args[1]);
1533 tm.tm_hour = XINT (args[2]);
1534 tm.tm_mday = XINT (args[3]);
1535 tm.tm_mon = XINT (args[4]) - 1;
1536 tm.tm_year = XINT (args[5]) - 1900;
1537 tm.tm_isdst = -1;
1539 if (CONSP (zone))
1540 zone = Fcar (zone);
1541 if (NILP (zone))
1542 time = mktime (&tm);
1543 else
1545 char tzbuf[100];
1546 char *tzstring;
1547 char **oldenv = environ, **newenv;
1549 if (EQ (zone, Qt))
1550 tzstring = "UTC0";
1551 else if (STRINGP (zone))
1552 tzstring = (char *) XSTRING (zone)->data;
1553 else if (INTEGERP (zone))
1555 int abszone = abs (XINT (zone));
1556 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1557 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1558 tzstring = tzbuf;
1560 else
1561 error ("Invalid time zone specification");
1563 /* Set TZ before calling mktime; merely adjusting mktime's returned
1564 value doesn't suffice, since that would mishandle leap seconds. */
1565 set_time_zone_rule (tzstring);
1567 time = mktime (&tm);
1569 /* Restore TZ to previous value. */
1570 newenv = environ;
1571 environ = oldenv;
1572 xfree (newenv);
1573 #ifdef LOCALTIME_CACHE
1574 tzset ();
1575 #endif
1578 if (time == (time_t) -1)
1579 error ("Specified time is not representable");
1581 return make_time (time);
1584 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1585 "Return the current time, as a human-readable string.\n\
1586 Programs can use this function to decode a time,\n\
1587 since the number of columns in each field is fixed.\n\
1588 The format is `Sun Sep 16 01:03:52 1973'.\n\
1589 However, see also the functions `decode-time' and `format-time-string'\n\
1590 which provide a much more powerful and general facility.\n\
1592 If an argument is given, it specifies a time to format\n\
1593 instead of the current time. The argument should have the form:\n\
1594 (HIGH . LOW)\n\
1595 or the form:\n\
1596 (HIGH LOW . IGNORED).\n\
1597 Thus, you can use times obtained from `current-time'\n\
1598 and from `file-attributes'.")
1599 (specified_time)
1600 Lisp_Object specified_time;
1602 time_t value;
1603 char buf[30];
1604 register char *tem;
1606 if (! lisp_time_argument (specified_time, &value, NULL))
1607 value = -1;
1608 tem = (char *) ctime (&value);
1610 strncpy (buf, tem, 24);
1611 buf[24] = 0;
1613 return build_string (buf);
1616 #define TM_YEAR_BASE 1900
1618 /* Yield A - B, measured in seconds.
1619 This function is copied from the GNU C Library. */
1620 static int
1621 tm_diff (a, b)
1622 struct tm *a, *b;
1624 /* Compute intervening leap days correctly even if year is negative.
1625 Take care to avoid int overflow in leap day calculations,
1626 but it's OK to assume that A and B are close to each other. */
1627 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1628 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1629 int a100 = a4 / 25 - (a4 % 25 < 0);
1630 int b100 = b4 / 25 - (b4 % 25 < 0);
1631 int a400 = a100 >> 2;
1632 int b400 = b100 >> 2;
1633 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1634 int years = a->tm_year - b->tm_year;
1635 int days = (365 * years + intervening_leap_days
1636 + (a->tm_yday - b->tm_yday));
1637 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1638 + (a->tm_min - b->tm_min))
1639 + (a->tm_sec - b->tm_sec));
1642 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1643 "Return the offset and name for the local time zone.\n\
1644 This returns a list of the form (OFFSET NAME).\n\
1645 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).\n\
1646 A negative value means west of Greenwich.\n\
1647 NAME is a string giving the name of the time zone.\n\
1648 If an argument is given, it specifies when the time zone offset is determined\n\
1649 instead of using the current time. The argument should have the form:\n\
1650 (HIGH . LOW)\n\
1651 or the form:\n\
1652 (HIGH LOW . IGNORED).\n\
1653 Thus, you can use times obtained from `current-time'\n\
1654 and from `file-attributes'.\n\
1656 Some operating systems cannot provide all this information to Emacs;\n\
1657 in this case, `current-time-zone' returns a list containing nil for\n\
1658 the data it can't find.")
1659 (specified_time)
1660 Lisp_Object specified_time;
1662 time_t value;
1663 struct tm *t;
1664 struct tm gmt;
1666 if (lisp_time_argument (specified_time, &value, NULL)
1667 && (t = gmtime (&value)) != 0
1668 && (gmt = *t, t = localtime (&value)) != 0)
1670 int offset = tm_diff (t, &gmt);
1671 char *s = 0;
1672 char buf[6];
1673 #ifdef HAVE_TM_ZONE
1674 if (t->tm_zone)
1675 s = (char *)t->tm_zone;
1676 #else /* not HAVE_TM_ZONE */
1677 #ifdef HAVE_TZNAME
1678 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1679 s = tzname[t->tm_isdst];
1680 #endif
1681 #endif /* not HAVE_TM_ZONE */
1682 if (!s)
1684 /* No local time zone name is available; use "+-NNNN" instead. */
1685 int am = (offset < 0 ? -offset : offset) / 60;
1686 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1687 s = buf;
1689 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
1691 else
1692 return Fmake_list (make_number (2), Qnil);
1695 /* This holds the value of `environ' produced by the previous
1696 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
1697 has never been called. */
1698 static char **environbuf;
1700 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
1701 "Set the local time zone using TZ, a string specifying a time zone rule.\n\
1702 If TZ is nil, use implementation-defined default time zone information.\n\
1703 If TZ is t, use Universal Time.")
1704 (tz)
1705 Lisp_Object tz;
1707 char *tzstring;
1709 if (NILP (tz))
1710 tzstring = 0;
1711 else if (EQ (tz, Qt))
1712 tzstring = "UTC0";
1713 else
1715 CHECK_STRING (tz, 0);
1716 tzstring = (char *) XSTRING (tz)->data;
1719 set_time_zone_rule (tzstring);
1720 if (environbuf)
1721 free (environbuf);
1722 environbuf = environ;
1724 return Qnil;
1727 #ifdef LOCALTIME_CACHE
1729 /* These two values are known to load tz files in buggy implementations,
1730 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1731 Their values shouldn't matter in non-buggy implementations.
1732 We don't use string literals for these strings,
1733 since if a string in the environment is in readonly
1734 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
1735 See Sun bugs 1113095 and 1114114, ``Timezone routines
1736 improperly modify environment''. */
1738 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
1739 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
1741 #endif
1743 /* Set the local time zone rule to TZSTRING.
1744 This allocates memory into `environ', which it is the caller's
1745 responsibility to free. */
1747 void
1748 set_time_zone_rule (tzstring)
1749 char *tzstring;
1751 int envptrs;
1752 char **from, **to, **newenv;
1754 /* Make the ENVIRON vector longer with room for TZSTRING. */
1755 for (from = environ; *from; from++)
1756 continue;
1757 envptrs = from - environ + 2;
1758 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
1759 + (tzstring ? strlen (tzstring) + 4 : 0));
1761 /* Add TZSTRING to the end of environ, as a value for TZ. */
1762 if (tzstring)
1764 char *t = (char *) (to + envptrs);
1765 strcpy (t, "TZ=");
1766 strcat (t, tzstring);
1767 *to++ = t;
1770 /* Copy the old environ vector elements into NEWENV,
1771 but don't copy the TZ variable.
1772 So we have only one definition of TZ, which came from TZSTRING. */
1773 for (from = environ; *from; from++)
1774 if (strncmp (*from, "TZ=", 3) != 0)
1775 *to++ = *from;
1776 *to = 0;
1778 environ = newenv;
1780 /* If we do have a TZSTRING, NEWENV points to the vector slot where
1781 the TZ variable is stored. If we do not have a TZSTRING,
1782 TO points to the vector slot which has the terminating null. */
1784 #ifdef LOCALTIME_CACHE
1786 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
1787 "US/Pacific" that loads a tz file, then changes to a value like
1788 "XXX0" that does not load a tz file, and then changes back to
1789 its original value, the last change is (incorrectly) ignored.
1790 Also, if TZ changes twice in succession to values that do
1791 not load a tz file, tzset can dump core (see Sun bug#1225179).
1792 The following code works around these bugs. */
1794 if (tzstring)
1796 /* Temporarily set TZ to a value that loads a tz file
1797 and that differs from tzstring. */
1798 char *tz = *newenv;
1799 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
1800 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
1801 tzset ();
1802 *newenv = tz;
1804 else
1806 /* The implied tzstring is unknown, so temporarily set TZ to
1807 two different values that each load a tz file. */
1808 *to = set_time_zone_rule_tz1;
1809 to[1] = 0;
1810 tzset ();
1811 *to = set_time_zone_rule_tz2;
1812 tzset ();
1813 *to = 0;
1816 /* Now TZ has the desired value, and tzset can be invoked safely. */
1819 tzset ();
1820 #endif
1823 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
1824 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
1825 type of object is Lisp_String). INHERIT is passed to
1826 INSERT_FROM_STRING_FUNC as the last argument. */
1828 static void
1829 general_insert_function (insert_func, insert_from_string_func,
1830 inherit, nargs, args)
1831 void (*insert_func) P_ ((unsigned char *, int));
1832 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
1833 int inherit, nargs;
1834 register Lisp_Object *args;
1836 register int argnum;
1837 register Lisp_Object val;
1839 for (argnum = 0; argnum < nargs; argnum++)
1841 val = args[argnum];
1842 retry:
1843 if (INTEGERP (val))
1845 unsigned char str[MAX_MULTIBYTE_LENGTH];
1846 int len;
1848 if (!NILP (current_buffer->enable_multibyte_characters))
1849 len = CHAR_STRING (XFASTINT (val), str);
1850 else
1852 str[0] = (SINGLE_BYTE_CHAR_P (XINT (val))
1853 ? XINT (val)
1854 : multibyte_char_to_unibyte (XINT (val), Qnil));
1855 len = 1;
1857 (*insert_func) (str, len);
1859 else if (STRINGP (val))
1861 (*insert_from_string_func) (val, 0, 0,
1862 XSTRING (val)->size,
1863 STRING_BYTES (XSTRING (val)),
1864 inherit);
1866 else
1868 val = wrong_type_argument (Qchar_or_string_p, val);
1869 goto retry;
1874 void
1875 insert1 (arg)
1876 Lisp_Object arg;
1878 Finsert (1, &arg);
1882 /* Callers passing one argument to Finsert need not gcpro the
1883 argument "array", since the only element of the array will
1884 not be used after calling insert or insert_from_string, so
1885 we don't care if it gets trashed. */
1887 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
1888 "Insert the arguments, either strings or characters, at point.\n\
1889 Point and before-insertion markers move forward to end up\n\
1890 after the inserted text.\n\
1891 Any other markers at the point of insertion remain before the text.\n\
1893 If the current buffer is multibyte, unibyte strings are converted\n\
1894 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1895 If the current buffer is unibyte, multibyte strings are converted\n\
1896 to unibyte for insertion.")
1897 (nargs, args)
1898 int nargs;
1899 register Lisp_Object *args;
1901 general_insert_function (insert, insert_from_string, 0, nargs, args);
1902 return Qnil;
1905 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
1906 0, MANY, 0,
1907 "Insert the arguments at point, inheriting properties from adjoining text.\n\
1908 Point and before-insertion markers move forward to end up\n\
1909 after the inserted text.\n\
1910 Any other markers at the point of insertion remain before the text.\n\
1912 If the current buffer is multibyte, unibyte strings are converted\n\
1913 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1914 If the current buffer is unibyte, multibyte strings are converted\n\
1915 to unibyte for insertion.")
1916 (nargs, args)
1917 int nargs;
1918 register Lisp_Object *args;
1920 general_insert_function (insert_and_inherit, insert_from_string, 1,
1921 nargs, args);
1922 return Qnil;
1925 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
1926 "Insert strings or characters at point, relocating markers after the text.\n\
1927 Point and markers move forward to end up after the inserted text.\n\
1929 If the current buffer is multibyte, unibyte strings are converted\n\
1930 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1931 If the current buffer is unibyte, multibyte strings are converted\n\
1932 to unibyte for insertion.")
1933 (nargs, args)
1934 int nargs;
1935 register Lisp_Object *args;
1937 general_insert_function (insert_before_markers,
1938 insert_from_string_before_markers, 0,
1939 nargs, args);
1940 return Qnil;
1943 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
1944 Sinsert_and_inherit_before_markers, 0, MANY, 0,
1945 "Insert text at point, relocating markers and inheriting properties.\n\
1946 Point and markers move forward to end up after the inserted text.\n\
1948 If the current buffer is multibyte, unibyte strings are converted\n\
1949 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1950 If the current buffer is unibyte, multibyte strings are converted\n\
1951 to unibyte for insertion.")
1952 (nargs, args)
1953 int nargs;
1954 register Lisp_Object *args;
1956 general_insert_function (insert_before_markers_and_inherit,
1957 insert_from_string_before_markers, 1,
1958 nargs, args);
1959 return Qnil;
1962 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
1963 "Insert COUNT (second arg) copies of CHARACTER (first arg).\n\
1964 Both arguments are required.\n\
1965 Point, and before-insertion markers, are relocated as in the function `insert'.\n\
1966 The optional third arg INHERIT, if non-nil, says to inherit text properties\n\
1967 from adjoining text, if those properties are sticky.")
1968 (character, count, inherit)
1969 Lisp_Object character, count, inherit;
1971 register unsigned char *string;
1972 register int strlen;
1973 register int i, n;
1974 int len;
1975 unsigned char str[MAX_MULTIBYTE_LENGTH];
1977 CHECK_NUMBER (character, 0);
1978 CHECK_NUMBER (count, 1);
1980 if (!NILP (current_buffer->enable_multibyte_characters))
1981 len = CHAR_STRING (XFASTINT (character), str);
1982 else
1983 str[0] = XFASTINT (character), len = 1;
1984 n = XINT (count) * len;
1985 if (n <= 0)
1986 return Qnil;
1987 strlen = min (n, 256 * len);
1988 string = (unsigned char *) alloca (strlen);
1989 for (i = 0; i < strlen; i++)
1990 string[i] = str[i % len];
1991 while (n >= strlen)
1993 QUIT;
1994 if (!NILP (inherit))
1995 insert_and_inherit (string, strlen);
1996 else
1997 insert (string, strlen);
1998 n -= strlen;
2000 if (n > 0)
2002 if (!NILP (inherit))
2003 insert_and_inherit (string, n);
2004 else
2005 insert (string, n);
2007 return Qnil;
2011 /* Making strings from buffer contents. */
2013 /* Return a Lisp_String containing the text of the current buffer from
2014 START to END. If text properties are in use and the current buffer
2015 has properties in the range specified, the resulting string will also
2016 have them, if PROPS is nonzero.
2018 We don't want to use plain old make_string here, because it calls
2019 make_uninit_string, which can cause the buffer arena to be
2020 compacted. make_string has no way of knowing that the data has
2021 been moved, and thus copies the wrong data into the string. This
2022 doesn't effect most of the other users of make_string, so it should
2023 be left as is. But we should use this function when conjuring
2024 buffer substrings. */
2026 Lisp_Object
2027 make_buffer_string (start, end, props)
2028 int start, end;
2029 int props;
2031 int start_byte = CHAR_TO_BYTE (start);
2032 int end_byte = CHAR_TO_BYTE (end);
2034 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2037 /* Return a Lisp_String containing the text of the current buffer from
2038 START / START_BYTE to END / END_BYTE.
2040 If text properties are in use and the current buffer
2041 has properties in the range specified, the resulting string will also
2042 have them, if PROPS is nonzero.
2044 We don't want to use plain old make_string here, because it calls
2045 make_uninit_string, which can cause the buffer arena to be
2046 compacted. make_string has no way of knowing that the data has
2047 been moved, and thus copies the wrong data into the string. This
2048 doesn't effect most of the other users of make_string, so it should
2049 be left as is. But we should use this function when conjuring
2050 buffer substrings. */
2052 Lisp_Object
2053 make_buffer_string_both (start, start_byte, end, end_byte, props)
2054 int start, start_byte, end, end_byte;
2055 int props;
2057 Lisp_Object result, tem, tem1;
2059 if (start < GPT && GPT < end)
2060 move_gap (start);
2062 if (! NILP (current_buffer->enable_multibyte_characters))
2063 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2064 else
2065 result = make_uninit_string (end - start);
2066 bcopy (BYTE_POS_ADDR (start_byte), XSTRING (result)->data,
2067 end_byte - start_byte);
2069 /* If desired, update and copy the text properties. */
2070 if (props)
2072 update_buffer_properties (start, end);
2074 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2075 tem1 = Ftext_properties_at (make_number (start), Qnil);
2077 if (XINT (tem) != end || !NILP (tem1))
2078 copy_intervals_to_string (result, current_buffer, start,
2079 end - start);
2082 return result;
2085 /* Call Vbuffer_access_fontify_functions for the range START ... END
2086 in the current buffer, if necessary. */
2088 static void
2089 update_buffer_properties (start, end)
2090 int start, end;
2092 /* If this buffer has some access functions,
2093 call them, specifying the range of the buffer being accessed. */
2094 if (!NILP (Vbuffer_access_fontify_functions))
2096 Lisp_Object args[3];
2097 Lisp_Object tem;
2099 args[0] = Qbuffer_access_fontify_functions;
2100 XSETINT (args[1], start);
2101 XSETINT (args[2], end);
2103 /* But don't call them if we can tell that the work
2104 has already been done. */
2105 if (!NILP (Vbuffer_access_fontified_property))
2107 tem = Ftext_property_any (args[1], args[2],
2108 Vbuffer_access_fontified_property,
2109 Qnil, Qnil);
2110 if (! NILP (tem))
2111 Frun_hook_with_args (3, args);
2113 else
2114 Frun_hook_with_args (3, args);
2118 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2119 "Return the contents of part of the current buffer as a string.\n\
2120 The two arguments START and END are character positions;\n\
2121 they can be in either order.\n\
2122 The string returned is multibyte if the buffer is multibyte.")
2123 (start, end)
2124 Lisp_Object start, end;
2126 register int b, e;
2128 validate_region (&start, &end);
2129 b = XINT (start);
2130 e = XINT (end);
2132 return make_buffer_string (b, e, 1);
2135 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2136 Sbuffer_substring_no_properties, 2, 2, 0,
2137 "Return the characters of part of the buffer, without the text properties.\n\
2138 The two arguments START and END are character positions;\n\
2139 they can be in either order.")
2140 (start, end)
2141 Lisp_Object start, end;
2143 register int b, e;
2145 validate_region (&start, &end);
2146 b = XINT (start);
2147 e = XINT (end);
2149 return make_buffer_string (b, e, 0);
2152 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2153 "Return the contents of the current buffer as a string.\n\
2154 If narrowing is in effect, this function returns only the visible part\n\
2155 of the buffer. If in a mini-buffer, don't include the prompt in the\n\
2156 string returned.")
2159 return make_buffer_string (BEGV, ZV, 1);
2162 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2163 1, 3, 0,
2164 "Insert before point a substring of the contents of buffer BUFFER.\n\
2165 BUFFER may be a buffer or a buffer name.\n\
2166 Arguments START and END are character numbers specifying the substring.\n\
2167 They default to the beginning and the end of BUFFER.")
2168 (buf, start, end)
2169 Lisp_Object buf, start, end;
2171 register int b, e, temp;
2172 register struct buffer *bp, *obuf;
2173 Lisp_Object buffer;
2175 buffer = Fget_buffer (buf);
2176 if (NILP (buffer))
2177 nsberror (buf);
2178 bp = XBUFFER (buffer);
2179 if (NILP (bp->name))
2180 error ("Selecting deleted buffer");
2182 if (NILP (start))
2183 b = BUF_BEGV (bp);
2184 else
2186 CHECK_NUMBER_COERCE_MARKER (start, 0);
2187 b = XINT (start);
2189 if (NILP (end))
2190 e = BUF_ZV (bp);
2191 else
2193 CHECK_NUMBER_COERCE_MARKER (end, 1);
2194 e = XINT (end);
2197 if (b > e)
2198 temp = b, b = e, e = temp;
2200 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2201 args_out_of_range (start, end);
2203 obuf = current_buffer;
2204 set_buffer_internal_1 (bp);
2205 update_buffer_properties (b, e);
2206 set_buffer_internal_1 (obuf);
2208 insert_from_buffer (bp, b, e - b, 0);
2209 return Qnil;
2212 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2213 6, 6, 0,
2214 "Compare two substrings of two buffers; return result as number.\n\
2215 the value is -N if first string is less after N-1 chars,\n\
2216 +N if first string is greater after N-1 chars, or 0 if strings match.\n\
2217 Each substring is represented as three arguments: BUFFER, START and END.\n\
2218 That makes six args in all, three for each substring.\n\n\
2219 The value of `case-fold-search' in the current buffer\n\
2220 determines whether case is significant or ignored.")
2221 (buffer1, start1, end1, buffer2, start2, end2)
2222 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2224 register int begp1, endp1, begp2, endp2, temp;
2225 register struct buffer *bp1, *bp2;
2226 register Lisp_Object *trt
2227 = (!NILP (current_buffer->case_fold_search)
2228 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents : 0);
2229 int chars = 0;
2230 int i1, i2, i1_byte, i2_byte;
2232 /* Find the first buffer and its substring. */
2234 if (NILP (buffer1))
2235 bp1 = current_buffer;
2236 else
2238 Lisp_Object buf1;
2239 buf1 = Fget_buffer (buffer1);
2240 if (NILP (buf1))
2241 nsberror (buffer1);
2242 bp1 = XBUFFER (buf1);
2243 if (NILP (bp1->name))
2244 error ("Selecting deleted buffer");
2247 if (NILP (start1))
2248 begp1 = BUF_BEGV (bp1);
2249 else
2251 CHECK_NUMBER_COERCE_MARKER (start1, 1);
2252 begp1 = XINT (start1);
2254 if (NILP (end1))
2255 endp1 = BUF_ZV (bp1);
2256 else
2258 CHECK_NUMBER_COERCE_MARKER (end1, 2);
2259 endp1 = XINT (end1);
2262 if (begp1 > endp1)
2263 temp = begp1, begp1 = endp1, endp1 = temp;
2265 if (!(BUF_BEGV (bp1) <= begp1
2266 && begp1 <= endp1
2267 && endp1 <= BUF_ZV (bp1)))
2268 args_out_of_range (start1, end1);
2270 /* Likewise for second substring. */
2272 if (NILP (buffer2))
2273 bp2 = current_buffer;
2274 else
2276 Lisp_Object buf2;
2277 buf2 = Fget_buffer (buffer2);
2278 if (NILP (buf2))
2279 nsberror (buffer2);
2280 bp2 = XBUFFER (buf2);
2281 if (NILP (bp2->name))
2282 error ("Selecting deleted buffer");
2285 if (NILP (start2))
2286 begp2 = BUF_BEGV (bp2);
2287 else
2289 CHECK_NUMBER_COERCE_MARKER (start2, 4);
2290 begp2 = XINT (start2);
2292 if (NILP (end2))
2293 endp2 = BUF_ZV (bp2);
2294 else
2296 CHECK_NUMBER_COERCE_MARKER (end2, 5);
2297 endp2 = XINT (end2);
2300 if (begp2 > endp2)
2301 temp = begp2, begp2 = endp2, endp2 = temp;
2303 if (!(BUF_BEGV (bp2) <= begp2
2304 && begp2 <= endp2
2305 && endp2 <= BUF_ZV (bp2)))
2306 args_out_of_range (start2, end2);
2308 i1 = begp1;
2309 i2 = begp2;
2310 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2311 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2313 while (i1 < endp1 && i2 < endp2)
2315 /* When we find a mismatch, we must compare the
2316 characters, not just the bytes. */
2317 int c1, c2;
2319 if (! NILP (bp1->enable_multibyte_characters))
2321 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2322 BUF_INC_POS (bp1, i1_byte);
2323 i1++;
2325 else
2327 c1 = BUF_FETCH_BYTE (bp1, i1);
2328 c1 = unibyte_char_to_multibyte (c1);
2329 i1++;
2332 if (! NILP (bp2->enable_multibyte_characters))
2334 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2335 BUF_INC_POS (bp2, i2_byte);
2336 i2++;
2338 else
2340 c2 = BUF_FETCH_BYTE (bp2, i2);
2341 c2 = unibyte_char_to_multibyte (c2);
2342 i2++;
2345 if (trt)
2347 c1 = XINT (trt[c1]);
2348 c2 = XINT (trt[c2]);
2350 if (c1 < c2)
2351 return make_number (- 1 - chars);
2352 if (c1 > c2)
2353 return make_number (chars + 1);
2355 chars++;
2358 /* The strings match as far as they go.
2359 If one is shorter, that one is less. */
2360 if (chars < endp1 - begp1)
2361 return make_number (chars + 1);
2362 else if (chars < endp2 - begp2)
2363 return make_number (- chars - 1);
2365 /* Same length too => they are equal. */
2366 return make_number (0);
2369 static Lisp_Object
2370 subst_char_in_region_unwind (arg)
2371 Lisp_Object arg;
2373 return current_buffer->undo_list = arg;
2376 static Lisp_Object
2377 subst_char_in_region_unwind_1 (arg)
2378 Lisp_Object arg;
2380 return current_buffer->filename = arg;
2383 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2384 Ssubst_char_in_region, 4, 5, 0,
2385 "From START to END, replace FROMCHAR with TOCHAR each time it occurs.\n\
2386 If optional arg NOUNDO is non-nil, don't record this change for undo\n\
2387 and don't mark the buffer as really changed.\n\
2388 Both characters must have the same length of multi-byte form.")
2389 (start, end, fromchar, tochar, noundo)
2390 Lisp_Object start, end, fromchar, tochar, noundo;
2392 register int pos, pos_byte, stop, i, len, end_byte;
2393 int changed = 0;
2394 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2395 unsigned char *p;
2396 int count = specpdl_ptr - specpdl;
2397 #define COMBINING_NO 0
2398 #define COMBINING_BEFORE 1
2399 #define COMBINING_AFTER 2
2400 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2401 int maybe_byte_combining = COMBINING_NO;
2402 int last_changed;
2403 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
2405 validate_region (&start, &end);
2406 CHECK_NUMBER (fromchar, 2);
2407 CHECK_NUMBER (tochar, 3);
2409 if (multibyte_p)
2411 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2412 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2413 error ("Characters in subst-char-in-region have different byte-lengths");
2414 if (!ASCII_BYTE_P (*tostr))
2416 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2417 complete multibyte character, it may be combined with the
2418 after bytes. If it is in the range 0xA0..0xFF, it may be
2419 combined with the before and after bytes. */
2420 if (!CHAR_HEAD_P (*tostr))
2421 maybe_byte_combining = COMBINING_BOTH;
2422 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2423 maybe_byte_combining = COMBINING_AFTER;
2426 else
2428 len = 1;
2429 fromstr[0] = XFASTINT (fromchar);
2430 tostr[0] = XFASTINT (tochar);
2433 pos = XINT (start);
2434 pos_byte = CHAR_TO_BYTE (pos);
2435 stop = CHAR_TO_BYTE (XINT (end));
2436 end_byte = stop;
2438 /* If we don't want undo, turn off putting stuff on the list.
2439 That's faster than getting rid of things,
2440 and it prevents even the entry for a first change.
2441 Also inhibit locking the file. */
2442 if (!NILP (noundo))
2444 record_unwind_protect (subst_char_in_region_unwind,
2445 current_buffer->undo_list);
2446 current_buffer->undo_list = Qt;
2447 /* Don't do file-locking. */
2448 record_unwind_protect (subst_char_in_region_unwind_1,
2449 current_buffer->filename);
2450 current_buffer->filename = Qnil;
2453 if (pos_byte < GPT_BYTE)
2454 stop = min (stop, GPT_BYTE);
2455 while (1)
2457 int pos_byte_next = pos_byte;
2459 if (pos_byte >= stop)
2461 if (pos_byte >= end_byte) break;
2462 stop = end_byte;
2464 p = BYTE_POS_ADDR (pos_byte);
2465 if (multibyte_p)
2466 INC_POS (pos_byte_next);
2467 else
2468 ++pos_byte_next;
2469 if (pos_byte_next - pos_byte == len
2470 && p[0] == fromstr[0]
2471 && (len == 1
2472 || (p[1] == fromstr[1]
2473 && (len == 2 || (p[2] == fromstr[2]
2474 && (len == 3 || p[3] == fromstr[3]))))))
2476 if (! changed)
2478 changed = pos;
2479 modify_region (current_buffer, changed, XINT (end));
2481 if (! NILP (noundo))
2483 if (MODIFF - 1 == SAVE_MODIFF)
2484 SAVE_MODIFF++;
2485 if (MODIFF - 1 == current_buffer->auto_save_modified)
2486 current_buffer->auto_save_modified++;
2490 /* Take care of the case where the new character
2491 combines with neighboring bytes. */
2492 if (maybe_byte_combining
2493 && (maybe_byte_combining == COMBINING_AFTER
2494 ? (pos_byte_next < Z_BYTE
2495 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2496 : ((pos_byte_next < Z_BYTE
2497 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2498 || (pos_byte > BEG_BYTE
2499 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2501 Lisp_Object tem, string;
2503 struct gcpro gcpro1;
2505 tem = current_buffer->undo_list;
2506 GCPRO1 (tem);
2508 /* Make a multibyte string containing this single character. */
2509 string = make_multibyte_string (tostr, 1, len);
2510 /* replace_range is less efficient, because it moves the gap,
2511 but it handles combining correctly. */
2512 replace_range (pos, pos + 1, string,
2513 0, 0, 1);
2514 pos_byte_next = CHAR_TO_BYTE (pos);
2515 if (pos_byte_next > pos_byte)
2516 /* Before combining happened. We should not increment
2517 POS. So, to cancel the later increment of POS,
2518 decrease it now. */
2519 pos--;
2520 else
2521 INC_POS (pos_byte_next);
2523 if (! NILP (noundo))
2524 current_buffer->undo_list = tem;
2526 UNGCPRO;
2528 else
2530 if (NILP (noundo))
2531 record_change (pos, 1);
2532 for (i = 0; i < len; i++) *p++ = tostr[i];
2534 last_changed = pos + 1;
2536 pos_byte = pos_byte_next;
2537 pos++;
2540 if (changed)
2542 signal_after_change (changed,
2543 last_changed - changed, last_changed - changed);
2544 update_compositions (changed, last_changed, CHECK_ALL);
2547 unbind_to (count, Qnil);
2548 return Qnil;
2551 DEFUN ("translate-region", Ftranslate_region, Stranslate_region, 3, 3, 0,
2552 "From START to END, translate characters according to TABLE.\n\
2553 TABLE is a string; the Nth character in it is the mapping\n\
2554 for the character with code N.\n\
2555 This function does not alter multibyte characters.\n\
2556 It returns the number of characters changed.")
2557 (start, end, table)
2558 Lisp_Object start;
2559 Lisp_Object end;
2560 register Lisp_Object table;
2562 register int pos_byte, stop; /* Limits of the region. */
2563 register unsigned char *tt; /* Trans table. */
2564 register int nc; /* New character. */
2565 int cnt; /* Number of changes made. */
2566 int size; /* Size of translate table. */
2567 int pos;
2568 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
2570 validate_region (&start, &end);
2571 CHECK_STRING (table, 2);
2573 size = STRING_BYTES (XSTRING (table));
2574 tt = XSTRING (table)->data;
2576 pos_byte = CHAR_TO_BYTE (XINT (start));
2577 stop = CHAR_TO_BYTE (XINT (end));
2578 modify_region (current_buffer, XINT (start), XINT (end));
2579 pos = XINT (start);
2581 cnt = 0;
2582 for (; pos_byte < stop; )
2584 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
2585 int len;
2586 int oc;
2587 int pos_byte_next;
2589 if (multibyte)
2590 oc = STRING_CHAR_AND_LENGTH (p, stop - pos_byte, len);
2591 else
2592 oc = *p, len = 1;
2593 pos_byte_next = pos_byte + len;
2594 if (oc < size && len == 1)
2596 nc = tt[oc];
2597 if (nc != oc)
2599 /* Take care of the case where the new character
2600 combines with neighboring bytes. */
2601 if (!ASCII_BYTE_P (nc)
2602 && (CHAR_HEAD_P (nc)
2603 ? ! CHAR_HEAD_P (FETCH_BYTE (pos_byte + 1))
2604 : (pos_byte > BEG_BYTE
2605 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1)))))
2607 Lisp_Object string;
2609 string = make_multibyte_string (tt + oc, 1, 1);
2610 /* This is less efficient, because it moves the gap,
2611 but it handles combining correctly. */
2612 replace_range (pos, pos + 1, string,
2613 1, 0, 1);
2614 pos_byte_next = CHAR_TO_BYTE (pos);
2615 if (pos_byte_next > pos_byte)
2616 /* Before combining happened. We should not
2617 increment POS. So, to cancel the later
2618 increment of POS, we decrease it now. */
2619 pos--;
2620 else
2621 INC_POS (pos_byte_next);
2623 else
2625 record_change (pos, 1);
2626 *p = nc;
2627 signal_after_change (pos, 1, 1);
2628 update_compositions (pos, pos + 1, CHECK_BORDER);
2630 ++cnt;
2633 pos_byte = pos_byte_next;
2634 pos++;
2637 return make_number (cnt);
2640 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
2641 "Delete the text between point and mark.\n\
2642 When called from a program, expects two arguments,\n\
2643 positions (integers or markers) specifying the stretch to be deleted.")
2644 (start, end)
2645 Lisp_Object start, end;
2647 validate_region (&start, &end);
2648 del_range (XINT (start), XINT (end));
2649 return Qnil;
2652 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
2653 Sdelete_and_extract_region, 2, 2, 0,
2654 "Delete the text between START and END and return it.")
2655 (start, end)
2656 Lisp_Object start, end;
2658 validate_region (&start, &end);
2659 return del_range_1 (XINT (start), XINT (end), 1, 1);
2662 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
2663 "Remove restrictions (narrowing) from current buffer.\n\
2664 This allows the buffer's full text to be seen and edited.")
2667 if (BEG != BEGV || Z != ZV)
2668 current_buffer->clip_changed = 1;
2669 BEGV = BEG;
2670 BEGV_BYTE = BEG_BYTE;
2671 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
2672 /* Changing the buffer bounds invalidates any recorded current column. */
2673 invalidate_current_column ();
2674 return Qnil;
2677 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
2678 "Restrict editing in this buffer to the current region.\n\
2679 The rest of the text becomes temporarily invisible and untouchable\n\
2680 but is not deleted; if you save the buffer in a file, the invisible\n\
2681 text is included in the file. \\[widen] makes all visible again.\n\
2682 See also `save-restriction'.\n\
2684 When calling from a program, pass two arguments; positions (integers\n\
2685 or markers) bounding the text that should remain visible.")
2686 (start, end)
2687 register Lisp_Object start, end;
2689 CHECK_NUMBER_COERCE_MARKER (start, 0);
2690 CHECK_NUMBER_COERCE_MARKER (end, 1);
2692 if (XINT (start) > XINT (end))
2694 Lisp_Object tem;
2695 tem = start; start = end; end = tem;
2698 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
2699 args_out_of_range (start, end);
2701 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
2702 current_buffer->clip_changed = 1;
2704 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2705 SET_BUF_ZV (current_buffer, XFASTINT (end));
2706 if (PT < XFASTINT (start))
2707 SET_PT (XFASTINT (start));
2708 if (PT > XFASTINT (end))
2709 SET_PT (XFASTINT (end));
2710 /* Changing the buffer bounds invalidates any recorded current column. */
2711 invalidate_current_column ();
2712 return Qnil;
2715 Lisp_Object
2716 save_restriction_save ()
2718 if (BEGV == BEG && ZV == Z)
2719 /* The common case that the buffer isn't narrowed.
2720 We return just the buffer object, which save_restriction_restore
2721 recognizes as meaning `no restriction'. */
2722 return Fcurrent_buffer ();
2723 else
2724 /* We have to save a restriction, so return a pair of markers, one
2725 for the beginning and one for the end. */
2727 Lisp_Object beg, end;
2729 beg = buildmark (BEGV, BEGV_BYTE);
2730 end = buildmark (ZV, ZV_BYTE);
2732 /* END must move forward if text is inserted at its exact location. */
2733 XMARKER(end)->insertion_type = 1;
2735 return Fcons (beg, end);
2739 Lisp_Object
2740 save_restriction_restore (data)
2741 Lisp_Object data;
2743 if (CONSP (data))
2744 /* A pair of marks bounding a saved restriction. */
2746 struct Lisp_Marker *beg = XMARKER (XCAR (data));
2747 struct Lisp_Marker *end = XMARKER (XCDR (data));
2748 struct buffer *buf = beg->buffer; /* END should have the same buffer. */
2750 if (beg->charpos != BUF_BEGV(buf) || end->charpos != BUF_ZV(buf))
2751 /* The restriction has changed from the saved one, so restore
2752 the saved restriction. */
2754 int pt = BUF_PT (buf);
2756 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
2757 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
2759 if (pt < beg->charpos || pt > end->charpos)
2760 /* The point is outside the new visible range, move it inside. */
2761 SET_BUF_PT_BOTH (buf,
2762 clip_to_bounds (beg->charpos, pt, end->charpos),
2763 clip_to_bounds (beg->bytepos, BUF_PT_BYTE(buf),
2764 end->bytepos));
2766 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2769 else
2770 /* A buffer, which means that there was no old restriction. */
2772 struct buffer *buf = XBUFFER (data);
2774 if (BUF_BEGV(buf) != BUF_BEG(buf) || BUF_ZV(buf) != BUF_Z(buf))
2775 /* The buffer has been narrowed, get rid of the narrowing. */
2777 SET_BUF_BEGV_BOTH (buf, BUF_BEG(buf), BUF_BEG_BYTE(buf));
2778 SET_BUF_ZV_BOTH (buf, BUF_Z(buf), BUF_Z_BYTE(buf));
2780 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2784 return Qnil;
2787 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
2788 "Execute BODY, saving and restoring current buffer's restrictions.\n\
2789 The buffer's restrictions make parts of the beginning and end invisible.\n\
2790 \(They are set up with `narrow-to-region' and eliminated with `widen'.)\n\
2791 This special form, `save-restriction', saves the current buffer's restrictions\n\
2792 when it is entered, and restores them when it is exited.\n\
2793 So any `narrow-to-region' within BODY lasts only until the end of the form.\n\
2794 The old restrictions settings are restored\n\
2795 even in case of abnormal exit (throw or error).\n\
2797 The value returned is the value of the last form in BODY.\n\
2799 Note: if you are using both `save-excursion' and `save-restriction',\n\
2800 use `save-excursion' outermost:\n\
2801 (save-excursion (save-restriction ...))")
2802 (body)
2803 Lisp_Object body;
2805 register Lisp_Object val;
2806 int count = specpdl_ptr - specpdl;
2808 record_unwind_protect (save_restriction_restore, save_restriction_save ());
2809 val = Fprogn (body);
2810 return unbind_to (count, val);
2813 #ifndef HAVE_MENUS
2815 /* Buffer for the most recent text displayed by Fmessage. */
2816 static char *message_text;
2818 /* Allocated length of that buffer. */
2819 static int message_length;
2821 #endif /* not HAVE_MENUS */
2823 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
2824 "Print a one-line message at the bottom of the screen.\n\
2825 The first argument is a format control string, and the rest are data\n\
2826 to be formatted under control of the string. See `format' for details.\n\
2828 If the first argument is nil, clear any existing message; let the\n\
2829 minibuffer contents show.")
2830 (nargs, args)
2831 int nargs;
2832 Lisp_Object *args;
2834 if (NILP (args[0]))
2836 message (0);
2837 return Qnil;
2839 else
2841 register Lisp_Object val;
2842 val = Fformat (nargs, args);
2843 message3 (val, STRING_BYTES (XSTRING (val)), STRING_MULTIBYTE (val));
2844 return val;
2848 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
2849 "Display a message, in a dialog box if possible.\n\
2850 If a dialog box is not available, use the echo area.\n\
2851 The first argument is a format control string, and the rest are data\n\
2852 to be formatted under control of the string. See `format' for details.\n\
2854 If the first argument is nil, clear any existing message; let the\n\
2855 minibuffer contents show.")
2856 (nargs, args)
2857 int nargs;
2858 Lisp_Object *args;
2860 if (NILP (args[0]))
2862 message (0);
2863 return Qnil;
2865 else
2867 register Lisp_Object val;
2868 val = Fformat (nargs, args);
2869 #ifdef HAVE_MENUS
2871 Lisp_Object pane, menu, obj;
2872 struct gcpro gcpro1;
2873 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
2874 GCPRO1 (pane);
2875 menu = Fcons (val, pane);
2876 obj = Fx_popup_dialog (Qt, menu);
2877 UNGCPRO;
2878 return val;
2880 #else /* not HAVE_MENUS */
2881 /* Copy the data so that it won't move when we GC. */
2882 if (! message_text)
2884 message_text = (char *)xmalloc (80);
2885 message_length = 80;
2887 if (STRING_BYTES (XSTRING (val)) > message_length)
2889 message_length = STRING_BYTES (XSTRING (val));
2890 message_text = (char *)xrealloc (message_text, message_length);
2892 bcopy (XSTRING (val)->data, message_text, STRING_BYTES (XSTRING (val)));
2893 message2 (message_text, STRING_BYTES (XSTRING (val)),
2894 STRING_MULTIBYTE (val));
2895 return val;
2896 #endif /* not HAVE_MENUS */
2899 #ifdef HAVE_MENUS
2900 extern Lisp_Object last_nonmenu_event;
2901 #endif
2903 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
2904 "Display a message in a dialog box or in the echo area.\n\
2905 If this command was invoked with the mouse, use a dialog box.\n\
2906 Otherwise, use the echo area.\n\
2907 The first argument is a format control string, and the rest are data\n\
2908 to be formatted under control of the string. See `format' for details.\n\
2910 If the first argument is nil, clear any existing message; let the\n\
2911 minibuffer contents show.")
2912 (nargs, args)
2913 int nargs;
2914 Lisp_Object *args;
2916 #ifdef HAVE_MENUS
2917 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
2918 && use_dialog_box)
2919 return Fmessage_box (nargs, args);
2920 #endif
2921 return Fmessage (nargs, args);
2924 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
2925 "Return the string currently displayed in the echo area, or nil if none.")
2928 return current_message ();
2932 DEFUN ("propertize", Fpropertize, Spropertize, 3, MANY, 0,
2933 "Return a copy of STRING with text properties added.\n\
2934 First argument is the string to copy.\n\
2935 Remaining arguments form a sequence of PROPERTY VALUE pairs for text\n\
2936 properties to add to the result ")
2937 (nargs, args)
2938 int nargs;
2939 Lisp_Object *args;
2941 Lisp_Object properties, string;
2942 struct gcpro gcpro1, gcpro2;
2943 int i;
2945 /* Number of args must be odd. */
2946 if ((nargs & 1) == 0 || nargs < 3)
2947 error ("Wrong number of arguments");
2949 properties = string = Qnil;
2950 GCPRO2 (properties, string);
2952 /* First argument must be a string. */
2953 CHECK_STRING (args[0], 0);
2954 string = Fcopy_sequence (args[0]);
2956 for (i = 1; i < nargs; i += 2)
2958 CHECK_SYMBOL (args[i], i);
2959 properties = Fcons (args[i], Fcons (args[i + 1], properties));
2962 Fadd_text_properties (make_number (0),
2963 make_number (XSTRING (string)->size),
2964 properties, string);
2965 RETURN_UNGCPRO (string);
2969 /* Number of bytes that STRING will occupy when put into the result.
2970 MULTIBYTE is nonzero if the result should be multibyte. */
2972 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
2973 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
2974 ? count_size_as_multibyte (XSTRING (STRING)->data, \
2975 STRING_BYTES (XSTRING (STRING))) \
2976 : STRING_BYTES (XSTRING (STRING)))
2978 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
2979 "Format a string out of a control-string and arguments.\n\
2980 The first argument is a control string.\n\
2981 The other arguments are substituted into it to make the result, a string.\n\
2982 It may contain %-sequences meaning to substitute the next argument.\n\
2983 %s means print a string argument. Actually, prints any object, with `princ'.\n\
2984 %d means print as number in decimal (%o octal, %x hex).\n\
2985 %e means print a number in exponential notation.\n\
2986 %f means print a number in decimal-point notation.\n\
2987 %g means print a number in exponential notation\n\
2988 or decimal-point notation, whichever uses fewer characters.\n\
2989 %c means print a number as a single character.\n\
2990 %S means print any object as an s-expression (using `prin1').\n\
2991 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.\n\
2992 Use %% to put a single % into the output.")
2993 (nargs, args)
2994 int nargs;
2995 register Lisp_Object *args;
2997 register int n; /* The number of the next arg to substitute */
2998 register int total; /* An estimate of the final length */
2999 char *buf, *p;
3000 register unsigned char *format, *end;
3001 int nchars;
3002 /* Nonzero if the output should be a multibyte string,
3003 which is true if any of the inputs is one. */
3004 int multibyte = 0;
3005 /* When we make a multibyte string, we must pay attention to the
3006 byte combining problem, i.e., a byte may be combined with a
3007 multibyte charcter of the previous string. This flag tells if we
3008 must consider such a situation or not. */
3009 int maybe_combine_byte;
3010 unsigned char *this_format;
3011 int longest_format;
3012 Lisp_Object val;
3013 struct info
3015 int start, end;
3016 } *info = 0;
3018 extern char *index ();
3020 /* It should not be necessary to GCPRO ARGS, because
3021 the caller in the interpreter should take care of that. */
3023 /* Try to determine whether the result should be multibyte.
3024 This is not always right; sometimes the result needs to be multibyte
3025 because of an object that we will pass through prin1,
3026 and in that case, we won't know it here. */
3027 for (n = 0; n < nargs; n++)
3028 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3029 multibyte = 1;
3031 CHECK_STRING (args[0], 0);
3033 /* If we start out planning a unibyte result,
3034 and later find it has to be multibyte, we jump back to retry. */
3035 retry:
3037 format = XSTRING (args[0])->data;
3038 end = format + STRING_BYTES (XSTRING (args[0]));
3039 longest_format = 0;
3041 /* Make room in result for all the non-%-codes in the control string. */
3042 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]);
3044 /* Add to TOTAL enough space to hold the converted arguments. */
3046 n = 0;
3047 while (format != end)
3048 if (*format++ == '%')
3050 int minlen, thissize = 0;
3051 unsigned char *this_format_start = format - 1;
3053 /* Process a numeric arg and skip it. */
3054 minlen = atoi (format);
3055 if (minlen < 0)
3056 minlen = - minlen;
3058 while ((*format >= '0' && *format <= '9')
3059 || *format == '-' || *format == ' ' || *format == '.')
3060 format++;
3062 if (format - this_format_start + 1 > longest_format)
3063 longest_format = format - this_format_start + 1;
3065 if (format == end)
3066 error ("Format string ends in middle of format specifier");
3067 if (*format == '%')
3068 format++;
3069 else if (++n >= nargs)
3070 error ("Not enough arguments for format string");
3071 else if (*format == 'S')
3073 /* For `S', prin1 the argument and then treat like a string. */
3074 register Lisp_Object tem;
3075 tem = Fprin1_to_string (args[n], Qnil);
3076 if (STRING_MULTIBYTE (tem) && ! multibyte)
3078 multibyte = 1;
3079 goto retry;
3081 args[n] = tem;
3082 goto string;
3084 else if (SYMBOLP (args[n]))
3086 /* Use a temp var to avoid problems when ENABLE_CHECKING
3087 is turned on. */
3088 struct Lisp_String *t = XSYMBOL (args[n])->name;
3089 XSETSTRING (args[n], t);
3090 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3092 multibyte = 1;
3093 goto retry;
3095 goto string;
3097 else if (STRINGP (args[n]))
3099 string:
3100 if (*format != 's' && *format != 'S')
3101 error ("Format specifier doesn't match argument type");
3102 thissize = CONVERTED_BYTE_SIZE (multibyte, args[n]);
3104 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3105 else if (INTEGERP (args[n]) && *format != 's')
3107 /* The following loop assumes the Lisp type indicates
3108 the proper way to pass the argument.
3109 So make sure we have a flonum if the argument should
3110 be a double. */
3111 if (*format == 'e' || *format == 'f' || *format == 'g')
3112 args[n] = Ffloat (args[n]);
3113 else
3114 if (*format != 'd' && *format != 'o' && *format != 'x'
3115 && *format != 'i' && *format != 'X' && *format != 'c')
3116 error ("Invalid format operation %%%c", *format);
3118 thissize = 30;
3119 if (*format == 'c'
3120 && (! SINGLE_BYTE_CHAR_P (XINT (args[n]))
3121 || XINT (args[n]) == 0))
3123 if (! multibyte)
3125 multibyte = 1;
3126 goto retry;
3128 args[n] = Fchar_to_string (args[n]);
3129 thissize = STRING_BYTES (XSTRING (args[n]));
3132 else if (FLOATP (args[n]) && *format != 's')
3134 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3135 args[n] = Ftruncate (args[n], Qnil);
3136 thissize = 200;
3138 else
3140 /* Anything but a string, convert to a string using princ. */
3141 register Lisp_Object tem;
3142 tem = Fprin1_to_string (args[n], Qt);
3143 if (STRING_MULTIBYTE (tem) & ! multibyte)
3145 multibyte = 1;
3146 goto retry;
3148 args[n] = tem;
3149 goto string;
3152 if (thissize < minlen)
3153 thissize = minlen;
3155 total += thissize + 4;
3158 /* Now we can no longer jump to retry.
3159 TOTAL and LONGEST_FORMAT are known for certain. */
3161 this_format = (unsigned char *) alloca (longest_format + 1);
3163 /* Allocate the space for the result.
3164 Note that TOTAL is an overestimate. */
3165 if (total < 1000)
3166 buf = (char *) alloca (total + 1);
3167 else
3168 buf = (char *) xmalloc (total + 1);
3170 p = buf;
3171 nchars = 0;
3172 n = 0;
3174 /* Scan the format and store result in BUF. */
3175 format = XSTRING (args[0])->data;
3176 maybe_combine_byte = 0;
3177 while (format != end)
3179 if (*format == '%')
3181 int minlen;
3182 int negative = 0;
3183 unsigned char *this_format_start = format;
3185 format++;
3187 /* Process a numeric arg and skip it. */
3188 minlen = atoi (format);
3189 if (minlen < 0)
3190 minlen = - minlen, negative = 1;
3192 while ((*format >= '0' && *format <= '9')
3193 || *format == '-' || *format == ' ' || *format == '.')
3194 format++;
3196 if (*format++ == '%')
3198 *p++ = '%';
3199 nchars++;
3200 continue;
3203 ++n;
3205 if (STRINGP (args[n]))
3207 int padding, nbytes;
3208 int width = strwidth (XSTRING (args[n])->data,
3209 STRING_BYTES (XSTRING (args[n])));
3210 int start = nchars;
3212 /* If spec requires it, pad on right with spaces. */
3213 padding = minlen - width;
3214 if (! negative)
3215 while (padding-- > 0)
3217 *p++ = ' ';
3218 nchars++;
3221 if (p > buf
3222 && multibyte
3223 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3224 && STRING_MULTIBYTE (args[n])
3225 && !CHAR_HEAD_P (XSTRING (args[n])->data[0]))
3226 maybe_combine_byte = 1;
3227 nbytes = copy_text (XSTRING (args[n])->data, p,
3228 STRING_BYTES (XSTRING (args[n])),
3229 STRING_MULTIBYTE (args[n]), multibyte);
3230 p += nbytes;
3231 nchars += XSTRING (args[n])->size;
3233 if (negative)
3234 while (padding-- > 0)
3236 *p++ = ' ';
3237 nchars++;
3240 /* If this argument has text properties, record where
3241 in the result string it appears. */
3242 if (XSTRING (args[n])->intervals)
3244 if (!info)
3246 int nbytes = nargs * sizeof *info;
3247 info = (struct info *) alloca (nbytes);
3248 bzero (info, nbytes);
3251 info[n].start = start;
3252 info[n].end = nchars;
3255 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3257 int this_nchars;
3259 bcopy (this_format_start, this_format,
3260 format - this_format_start);
3261 this_format[format - this_format_start] = 0;
3263 if (INTEGERP (args[n]))
3264 sprintf (p, this_format, XINT (args[n]));
3265 else
3266 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3268 if (p > buf
3269 && multibyte
3270 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3271 && !CHAR_HEAD_P (*((unsigned char *) p)))
3272 maybe_combine_byte = 1;
3273 this_nchars = strlen (p);
3274 if (multibyte)
3275 p += str_to_multibyte (p, buf + total - p, this_nchars);
3276 else
3277 p += this_nchars;
3278 nchars += this_nchars;
3281 else if (STRING_MULTIBYTE (args[0]))
3283 /* Copy a whole multibyte character. */
3284 if (p > buf
3285 && multibyte
3286 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3287 && !CHAR_HEAD_P (*format))
3288 maybe_combine_byte = 1;
3289 *p++ = *format++;
3290 while (! CHAR_HEAD_P (*format)) *p++ = *format++;
3291 nchars++;
3293 else if (multibyte)
3295 /* Convert a single-byte character to multibyte. */
3296 int len = copy_text (format, p, 1, 0, 1);
3298 p += len;
3299 format++;
3300 nchars++;
3302 else
3303 *p++ = *format++, nchars++;
3306 if (maybe_combine_byte)
3307 nchars = multibyte_chars_in_text (buf, p - buf);
3308 val = make_specified_string (buf, nchars, p - buf, multibyte);
3310 /* If we allocated BUF with malloc, free it too. */
3311 if (total >= 1000)
3312 xfree (buf);
3314 /* If the format string has text properties, or any of the string
3315 arguments has text properties, set up text properties of the
3316 result string. */
3318 if (XSTRING (args[0])->intervals || info)
3320 Lisp_Object len, new_len, props;
3321 struct gcpro gcpro1;
3323 /* Add text properties from the format string. */
3324 len = make_number (XSTRING (args[0])->size);
3325 props = text_property_list (args[0], make_number (0), len, Qnil);
3326 GCPRO1 (props);
3328 if (CONSP (props))
3330 new_len = make_number (XSTRING (val)->size);
3331 extend_property_ranges (props, len, new_len);
3332 add_text_properties_from_list (val, props, make_number (0));
3335 /* Add text properties from arguments. */
3336 if (info)
3337 for (n = 1; n < nargs; ++n)
3338 if (info[n].end)
3340 len = make_number (XSTRING (args[n])->size);
3341 new_len = make_number (info[n].end - info[n].start);
3342 props = text_property_list (args[n], make_number (0), len, Qnil);
3343 extend_property_ranges (props, len, new_len);
3344 /* If successive arguments have properites, be sure that
3345 the value of `composition' property be the copy. */
3346 if (n > 1 && info[n - 1].end)
3347 make_composition_value_copy (props);
3348 add_text_properties_from_list (val, props,
3349 make_number (info[n].start));
3352 UNGCPRO;
3355 return val;
3359 /* VARARGS 1 */
3360 Lisp_Object
3361 #ifdef NO_ARG_ARRAY
3362 format1 (string1, arg0, arg1, arg2, arg3, arg4)
3363 EMACS_INT arg0, arg1, arg2, arg3, arg4;
3364 #else
3365 format1 (string1)
3366 #endif
3367 char *string1;
3369 char buf[100];
3370 #ifdef NO_ARG_ARRAY
3371 EMACS_INT args[5];
3372 args[0] = arg0;
3373 args[1] = arg1;
3374 args[2] = arg2;
3375 args[3] = arg3;
3376 args[4] = arg4;
3377 doprnt (buf, sizeof buf, string1, (char *)0, 5, (char **) args);
3378 #else
3379 doprnt (buf, sizeof buf, string1, (char *)0, 5, &string1 + 1);
3380 #endif
3381 return build_string (buf);
3384 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
3385 "Return t if two characters match, optionally ignoring case.\n\
3386 Both arguments must be characters (i.e. integers).\n\
3387 Case is ignored if `case-fold-search' is non-nil in the current buffer.")
3388 (c1, c2)
3389 register Lisp_Object c1, c2;
3391 int i1, i2;
3392 CHECK_NUMBER (c1, 0);
3393 CHECK_NUMBER (c2, 1);
3395 if (XINT (c1) == XINT (c2))
3396 return Qt;
3397 if (NILP (current_buffer->case_fold_search))
3398 return Qnil;
3400 /* Do these in separate statements,
3401 then compare the variables.
3402 because of the way DOWNCASE uses temp variables. */
3403 i1 = DOWNCASE (XFASTINT (c1));
3404 i2 = DOWNCASE (XFASTINT (c2));
3405 return (i1 == i2 ? Qt : Qnil);
3408 /* Transpose the markers in two regions of the current buffer, and
3409 adjust the ones between them if necessary (i.e.: if the regions
3410 differ in size).
3412 START1, END1 are the character positions of the first region.
3413 START1_BYTE, END1_BYTE are the byte positions.
3414 START2, END2 are the character positions of the second region.
3415 START2_BYTE, END2_BYTE are the byte positions.
3417 Traverses the entire marker list of the buffer to do so, adding an
3418 appropriate amount to some, subtracting from some, and leaving the
3419 rest untouched. Most of this is copied from adjust_markers in insdel.c.
3421 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
3423 static void
3424 transpose_markers (start1, end1, start2, end2,
3425 start1_byte, end1_byte, start2_byte, end2_byte)
3426 register int start1, end1, start2, end2;
3427 register int start1_byte, end1_byte, start2_byte, end2_byte;
3429 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
3430 register Lisp_Object marker;
3432 /* Update point as if it were a marker. */
3433 if (PT < start1)
3435 else if (PT < end1)
3436 TEMP_SET_PT_BOTH (PT + (end2 - end1),
3437 PT_BYTE + (end2_byte - end1_byte));
3438 else if (PT < start2)
3439 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
3440 (PT_BYTE + (end2_byte - start2_byte)
3441 - (end1_byte - start1_byte)));
3442 else if (PT < end2)
3443 TEMP_SET_PT_BOTH (PT - (start2 - start1),
3444 PT_BYTE - (start2_byte - start1_byte));
3446 /* We used to adjust the endpoints here to account for the gap, but that
3447 isn't good enough. Even if we assume the caller has tried to move the
3448 gap out of our way, it might still be at start1 exactly, for example;
3449 and that places it `inside' the interval, for our purposes. The amount
3450 of adjustment is nontrivial if there's a `denormalized' marker whose
3451 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
3452 the dirty work to Fmarker_position, below. */
3454 /* The difference between the region's lengths */
3455 diff = (end2 - start2) - (end1 - start1);
3456 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
3458 /* For shifting each marker in a region by the length of the other
3459 region plus the distance between the regions. */
3460 amt1 = (end2 - start2) + (start2 - end1);
3461 amt2 = (end1 - start1) + (start2 - end1);
3462 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
3463 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
3465 for (marker = BUF_MARKERS (current_buffer); !NILP (marker);
3466 marker = XMARKER (marker)->chain)
3468 mpos = marker_byte_position (marker);
3469 if (mpos >= start1_byte && mpos < end2_byte)
3471 if (mpos < end1_byte)
3472 mpos += amt1_byte;
3473 else if (mpos < start2_byte)
3474 mpos += diff_byte;
3475 else
3476 mpos -= amt2_byte;
3477 XMARKER (marker)->bytepos = mpos;
3479 mpos = XMARKER (marker)->charpos;
3480 if (mpos >= start1 && mpos < end2)
3482 if (mpos < end1)
3483 mpos += amt1;
3484 else if (mpos < start2)
3485 mpos += diff;
3486 else
3487 mpos -= amt2;
3489 XMARKER (marker)->charpos = mpos;
3493 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
3494 "Transpose region START1 to END1 with START2 to END2.\n\
3495 The regions may not be overlapping, because the size of the buffer is\n\
3496 never changed in a transposition.\n\
3498 Optional fifth arg LEAVE_MARKERS, if non-nil, means don't update\n\
3499 any markers that happen to be located in the regions.\n\
3501 Transposing beyond buffer boundaries is an error.")
3502 (startr1, endr1, startr2, endr2, leave_markers)
3503 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
3505 register int start1, end1, start2, end2;
3506 int start1_byte, start2_byte, len1_byte, len2_byte;
3507 int gap, len1, len_mid, len2;
3508 unsigned char *start1_addr, *start2_addr, *temp;
3509 struct gcpro gcpro1, gcpro2;
3511 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
3512 cur_intv = BUF_INTERVALS (current_buffer);
3514 validate_region (&startr1, &endr1);
3515 validate_region (&startr2, &endr2);
3517 start1 = XFASTINT (startr1);
3518 end1 = XFASTINT (endr1);
3519 start2 = XFASTINT (startr2);
3520 end2 = XFASTINT (endr2);
3521 gap = GPT;
3523 /* Swap the regions if they're reversed. */
3524 if (start2 < end1)
3526 register int glumph = start1;
3527 start1 = start2;
3528 start2 = glumph;
3529 glumph = end1;
3530 end1 = end2;
3531 end2 = glumph;
3534 len1 = end1 - start1;
3535 len2 = end2 - start2;
3537 if (start2 < end1)
3538 error ("Transposed regions overlap");
3539 else if (start1 == end1 || start2 == end2)
3540 error ("Transposed region has length 0");
3542 /* The possibilities are:
3543 1. Adjacent (contiguous) regions, or separate but equal regions
3544 (no, really equal, in this case!), or
3545 2. Separate regions of unequal size.
3547 The worst case is usually No. 2. It means that (aside from
3548 potential need for getting the gap out of the way), there also
3549 needs to be a shifting of the text between the two regions. So
3550 if they are spread far apart, we are that much slower... sigh. */
3552 /* It must be pointed out that the really studly thing to do would
3553 be not to move the gap at all, but to leave it in place and work
3554 around it if necessary. This would be extremely efficient,
3555 especially considering that people are likely to do
3556 transpositions near where they are working interactively, which
3557 is exactly where the gap would be found. However, such code
3558 would be much harder to write and to read. So, if you are
3559 reading this comment and are feeling squirrely, by all means have
3560 a go! I just didn't feel like doing it, so I will simply move
3561 the gap the minimum distance to get it out of the way, and then
3562 deal with an unbroken array. */
3564 /* Make sure the gap won't interfere, by moving it out of the text
3565 we will operate on. */
3566 if (start1 < gap && gap < end2)
3568 if (gap - start1 < end2 - gap)
3569 move_gap (start1);
3570 else
3571 move_gap (end2);
3574 start1_byte = CHAR_TO_BYTE (start1);
3575 start2_byte = CHAR_TO_BYTE (start2);
3576 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
3577 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
3579 #ifdef BYTE_COMBINING_DEBUG
3580 if (end1 == start2)
3582 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3583 len2_byte, start1, start1_byte)
3584 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3585 len1_byte, end2, start2_byte + len2_byte)
3586 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3587 len1_byte, end2, start2_byte + len2_byte))
3588 abort ();
3590 else
3592 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3593 len2_byte, start1, start1_byte)
3594 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3595 len1_byte, start2, start2_byte)
3596 || count_combining_after (BYTE_POS_ADDR (start2_byte),
3597 len2_byte, end1, start1_byte + len1_byte)
3598 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3599 len1_byte, end2, start2_byte + len2_byte))
3600 abort ();
3602 #endif
3604 /* Hmmm... how about checking to see if the gap is large
3605 enough to use as the temporary storage? That would avoid an
3606 allocation... interesting. Later, don't fool with it now. */
3608 /* Working without memmove, for portability (sigh), so must be
3609 careful of overlapping subsections of the array... */
3611 if (end1 == start2) /* adjacent regions */
3613 modify_region (current_buffer, start1, end2);
3614 record_change (start1, len1 + len2);
3616 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3617 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3618 Fset_text_properties (make_number (start1), make_number (end2),
3619 Qnil, Qnil);
3621 /* First region smaller than second. */
3622 if (len1_byte < len2_byte)
3624 /* We use alloca only if it is small,
3625 because we want to avoid stack overflow. */
3626 if (len2_byte > 20000)
3627 temp = (unsigned char *) xmalloc (len2_byte);
3628 else
3629 temp = (unsigned char *) alloca (len2_byte);
3631 /* Don't precompute these addresses. We have to compute them
3632 at the last minute, because the relocating allocator might
3633 have moved the buffer around during the xmalloc. */
3634 start1_addr = BYTE_POS_ADDR (start1_byte);
3635 start2_addr = BYTE_POS_ADDR (start2_byte);
3637 bcopy (start2_addr, temp, len2_byte);
3638 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
3639 bcopy (temp, start1_addr, len2_byte);
3640 if (len2_byte > 20000)
3641 xfree (temp);
3643 else
3644 /* First region not smaller than second. */
3646 if (len1_byte > 20000)
3647 temp = (unsigned char *) xmalloc (len1_byte);
3648 else
3649 temp = (unsigned char *) alloca (len1_byte);
3650 start1_addr = BYTE_POS_ADDR (start1_byte);
3651 start2_addr = BYTE_POS_ADDR (start2_byte);
3652 bcopy (start1_addr, temp, len1_byte);
3653 bcopy (start2_addr, start1_addr, len2_byte);
3654 bcopy (temp, start1_addr + len2_byte, len1_byte);
3655 if (len1_byte > 20000)
3656 xfree (temp);
3658 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
3659 len1, current_buffer, 0);
3660 graft_intervals_into_buffer (tmp_interval2, start1,
3661 len2, current_buffer, 0);
3662 update_compositions (start1, start1 + len2, CHECK_BORDER);
3663 update_compositions (start1 + len2, end2, CHECK_TAIL);
3665 /* Non-adjacent regions, because end1 != start2, bleagh... */
3666 else
3668 len_mid = start2_byte - (start1_byte + len1_byte);
3670 if (len1_byte == len2_byte)
3671 /* Regions are same size, though, how nice. */
3673 modify_region (current_buffer, start1, end1);
3674 modify_region (current_buffer, start2, end2);
3675 record_change (start1, len1);
3676 record_change (start2, len2);
3677 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3678 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3679 Fset_text_properties (make_number (start1), make_number (end1),
3680 Qnil, Qnil);
3681 Fset_text_properties (make_number (start2), make_number (end2),
3682 Qnil, Qnil);
3684 if (len1_byte > 20000)
3685 temp = (unsigned char *) xmalloc (len1_byte);
3686 else
3687 temp = (unsigned char *) alloca (len1_byte);
3688 start1_addr = BYTE_POS_ADDR (start1_byte);
3689 start2_addr = BYTE_POS_ADDR (start2_byte);
3690 bcopy (start1_addr, temp, len1_byte);
3691 bcopy (start2_addr, start1_addr, len2_byte);
3692 bcopy (temp, start2_addr, len1_byte);
3693 if (len1_byte > 20000)
3694 xfree (temp);
3695 graft_intervals_into_buffer (tmp_interval1, start2,
3696 len1, current_buffer, 0);
3697 graft_intervals_into_buffer (tmp_interval2, start1,
3698 len2, current_buffer, 0);
3701 else if (len1_byte < len2_byte) /* Second region larger than first */
3702 /* Non-adjacent & unequal size, area between must also be shifted. */
3704 modify_region (current_buffer, start1, end2);
3705 record_change (start1, (end2 - start1));
3706 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3707 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3708 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3709 Fset_text_properties (make_number (start1), make_number (end2),
3710 Qnil, Qnil);
3712 /* holds region 2 */
3713 if (len2_byte > 20000)
3714 temp = (unsigned char *) xmalloc (len2_byte);
3715 else
3716 temp = (unsigned char *) alloca (len2_byte);
3717 start1_addr = BYTE_POS_ADDR (start1_byte);
3718 start2_addr = BYTE_POS_ADDR (start2_byte);
3719 bcopy (start2_addr, temp, len2_byte);
3720 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
3721 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3722 bcopy (temp, start1_addr, len2_byte);
3723 if (len2_byte > 20000)
3724 xfree (temp);
3725 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3726 len1, current_buffer, 0);
3727 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3728 len_mid, current_buffer, 0);
3729 graft_intervals_into_buffer (tmp_interval2, start1,
3730 len2, current_buffer, 0);
3732 else
3733 /* Second region smaller than first. */
3735 record_change (start1, (end2 - start1));
3736 modify_region (current_buffer, start1, end2);
3738 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3739 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3740 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3741 Fset_text_properties (make_number (start1), make_number (end2),
3742 Qnil, Qnil);
3744 /* holds region 1 */
3745 if (len1_byte > 20000)
3746 temp = (unsigned char *) xmalloc (len1_byte);
3747 else
3748 temp = (unsigned char *) alloca (len1_byte);
3749 start1_addr = BYTE_POS_ADDR (start1_byte);
3750 start2_addr = BYTE_POS_ADDR (start2_byte);
3751 bcopy (start1_addr, temp, len1_byte);
3752 bcopy (start2_addr, start1_addr, len2_byte);
3753 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3754 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
3755 if (len1_byte > 20000)
3756 xfree (temp);
3757 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3758 len1, current_buffer, 0);
3759 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3760 len_mid, current_buffer, 0);
3761 graft_intervals_into_buffer (tmp_interval2, start1,
3762 len2, current_buffer, 0);
3765 update_compositions (start1, start1 + len2, CHECK_BORDER);
3766 update_compositions (end2 - len1, end2, CHECK_BORDER);
3769 /* When doing multiple transpositions, it might be nice
3770 to optimize this. Perhaps the markers in any one buffer
3771 should be organized in some sorted data tree. */
3772 if (NILP (leave_markers))
3774 transpose_markers (start1, end1, start2, end2,
3775 start1_byte, start1_byte + len1_byte,
3776 start2_byte, start2_byte + len2_byte);
3777 fix_overlays_in_range (start1, end2);
3780 return Qnil;
3784 void
3785 syms_of_editfns ()
3787 environbuf = 0;
3789 Qbuffer_access_fontify_functions
3790 = intern ("buffer-access-fontify-functions");
3791 staticpro (&Qbuffer_access_fontify_functions);
3793 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
3794 "Non-nil means.text motion commands don't notice fields.");
3795 Vinhibit_field_text_motion = Qnil;
3797 DEFVAR_LISP ("buffer-access-fontify-functions",
3798 &Vbuffer_access_fontify_functions,
3799 "List of functions called by `buffer-substring' to fontify if necessary.\n\
3800 Each function is called with two arguments which specify the range\n\
3801 of the buffer being accessed.");
3802 Vbuffer_access_fontify_functions = Qnil;
3805 Lisp_Object obuf;
3806 extern Lisp_Object Vprin1_to_string_buffer;
3807 obuf = Fcurrent_buffer ();
3808 /* Do this here, because init_buffer_once is too early--it won't work. */
3809 Fset_buffer (Vprin1_to_string_buffer);
3810 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
3811 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
3812 Qnil);
3813 Fset_buffer (obuf);
3816 DEFVAR_LISP ("buffer-access-fontified-property",
3817 &Vbuffer_access_fontified_property,
3818 "Property which (if non-nil) indicates text has been fontified.\n\
3819 `buffer-substring' need not call the `buffer-access-fontify-functions'\n\
3820 functions if all the text being accessed has this property.");
3821 Vbuffer_access_fontified_property = Qnil;
3823 DEFVAR_LISP ("system-name", &Vsystem_name,
3824 "The name of the machine Emacs is running on.");
3826 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
3827 "The full name of the user logged in.");
3829 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
3830 "The user's name, taken from environment variables if possible.");
3832 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
3833 "The user's name, based upon the real uid only.");
3835 defsubr (&Spropertize);
3836 defsubr (&Schar_equal);
3837 defsubr (&Sgoto_char);
3838 defsubr (&Sstring_to_char);
3839 defsubr (&Schar_to_string);
3840 defsubr (&Sbuffer_substring);
3841 defsubr (&Sbuffer_substring_no_properties);
3842 defsubr (&Sbuffer_string);
3844 defsubr (&Spoint_marker);
3845 defsubr (&Smark_marker);
3846 defsubr (&Spoint);
3847 defsubr (&Sregion_beginning);
3848 defsubr (&Sregion_end);
3850 staticpro (&Qfield);
3851 Qfield = intern ("field");
3852 staticpro (&Qboundary);
3853 Qboundary = intern ("boundary");
3854 defsubr (&Sfield_beginning);
3855 defsubr (&Sfield_end);
3856 defsubr (&Sfield_string);
3857 defsubr (&Sfield_string_no_properties);
3858 defsubr (&Sdelete_field);
3859 defsubr (&Sconstrain_to_field);
3861 defsubr (&Sline_beginning_position);
3862 defsubr (&Sline_end_position);
3864 /* defsubr (&Smark); */
3865 /* defsubr (&Sset_mark); */
3866 defsubr (&Ssave_excursion);
3867 defsubr (&Ssave_current_buffer);
3869 defsubr (&Sbufsize);
3870 defsubr (&Spoint_max);
3871 defsubr (&Spoint_min);
3872 defsubr (&Spoint_min_marker);
3873 defsubr (&Spoint_max_marker);
3874 defsubr (&Sgap_position);
3875 defsubr (&Sgap_size);
3876 defsubr (&Sposition_bytes);
3877 defsubr (&Sbyte_to_position);
3879 defsubr (&Sbobp);
3880 defsubr (&Seobp);
3881 defsubr (&Sbolp);
3882 defsubr (&Seolp);
3883 defsubr (&Sfollowing_char);
3884 defsubr (&Sprevious_char);
3885 defsubr (&Schar_after);
3886 defsubr (&Schar_before);
3887 defsubr (&Sinsert);
3888 defsubr (&Sinsert_before_markers);
3889 defsubr (&Sinsert_and_inherit);
3890 defsubr (&Sinsert_and_inherit_before_markers);
3891 defsubr (&Sinsert_char);
3893 defsubr (&Suser_login_name);
3894 defsubr (&Suser_real_login_name);
3895 defsubr (&Suser_uid);
3896 defsubr (&Suser_real_uid);
3897 defsubr (&Suser_full_name);
3898 defsubr (&Semacs_pid);
3899 defsubr (&Scurrent_time);
3900 defsubr (&Sformat_time_string);
3901 defsubr (&Sfloat_time);
3902 defsubr (&Sdecode_time);
3903 defsubr (&Sencode_time);
3904 defsubr (&Scurrent_time_string);
3905 defsubr (&Scurrent_time_zone);
3906 defsubr (&Sset_time_zone_rule);
3907 defsubr (&Ssystem_name);
3908 defsubr (&Smessage);
3909 defsubr (&Smessage_box);
3910 defsubr (&Smessage_or_box);
3911 defsubr (&Scurrent_message);
3912 defsubr (&Sformat);
3914 defsubr (&Sinsert_buffer_substring);
3915 defsubr (&Scompare_buffer_substrings);
3916 defsubr (&Ssubst_char_in_region);
3917 defsubr (&Stranslate_region);
3918 defsubr (&Sdelete_region);
3919 defsubr (&Sdelete_and_extract_region);
3920 defsubr (&Swiden);
3921 defsubr (&Snarrow_to_region);
3922 defsubr (&Ssave_restriction);
3923 defsubr (&Stranspose_regions);