(rmail-reply): Don't forget to narrow header in
[emacs.git] / src / editfns.c
blob7efa75383ce9facad07db15d4bb740fdbd444cd9
1 /* Lisp functions pertaining to editing.
2 Copyright (C) 1985,86,87,89,93,94,95,96,97,98, 1999, 2000, 2001
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 "frame.h"
42 #include "window.h"
44 #include "systime.h"
46 #define min(a, b) ((a) < (b) ? (a) : (b))
47 #define max(a, b) ((a) > (b) ? (a) : (b))
49 #ifndef NULL
50 #define NULL 0
51 #endif
53 #ifndef USE_CRT_DLL
54 extern char **environ;
55 #endif
57 extern Lisp_Object make_time P_ ((time_t));
58 extern size_t emacs_strftimeu P_ ((char *, size_t, const char *,
59 const struct tm *, int));
60 static int tm_diff P_ ((struct tm *, struct tm *));
61 static void find_field P_ ((Lisp_Object, Lisp_Object, int *, int *));
62 static void update_buffer_properties P_ ((int, int));
63 static Lisp_Object region_limit P_ ((int));
64 static int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
65 static size_t emacs_memftimeu P_ ((char *, size_t, const char *,
66 size_t, const struct tm *, int));
67 static void general_insert_function P_ ((void (*) (unsigned char *, int),
68 void (*) (Lisp_Object, int, int, int,
69 int, int),
70 int, int, Lisp_Object *));
71 static Lisp_Object subst_char_in_region_unwind P_ ((Lisp_Object));
72 static Lisp_Object subst_char_in_region_unwind_1 P_ ((Lisp_Object));
73 static void transpose_markers P_ ((int, int, int, int, int, int, int, int));
75 #ifdef HAVE_INDEX
76 extern char *index P_ ((const char *, int));
77 #endif
79 Lisp_Object Vbuffer_access_fontify_functions;
80 Lisp_Object Qbuffer_access_fontify_functions;
81 Lisp_Object Vbuffer_access_fontified_property;
83 Lisp_Object Fuser_full_name P_ ((Lisp_Object));
85 /* Non-nil means don't stop at field boundary in text motion commands. */
87 Lisp_Object Vinhibit_field_text_motion;
89 /* Some static data, and a function to initialize it for each run */
91 Lisp_Object Vsystem_name;
92 Lisp_Object Vuser_real_login_name; /* login name of current user ID */
93 Lisp_Object Vuser_full_name; /* full name of current user */
94 Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
96 /* Symbol for the text property used to mark fields. */
98 Lisp_Object Qfield;
100 /* A special value for Qfield properties. */
102 Lisp_Object Qboundary;
105 void
106 init_editfns ()
108 char *user_name;
109 register unsigned char *p;
110 struct passwd *pw; /* password entry for the current user */
111 Lisp_Object tem;
113 /* Set up system_name even when dumping. */
114 init_system_name ();
116 #ifndef CANNOT_DUMP
117 /* Don't bother with this on initial start when just dumping out */
118 if (!initialized)
119 return;
120 #endif /* not CANNOT_DUMP */
122 pw = (struct passwd *) getpwuid (getuid ());
123 #ifdef MSDOS
124 /* We let the real user name default to "root" because that's quite
125 accurate on MSDOG and because it lets Emacs find the init file.
126 (The DVX libraries override the Djgpp libraries here.) */
127 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
128 #else
129 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
130 #endif
132 /* Get the effective user name, by consulting environment variables,
133 or the effective uid if those are unset. */
134 user_name = (char *) getenv ("LOGNAME");
135 if (!user_name)
136 #ifdef WINDOWSNT
137 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
138 #else /* WINDOWSNT */
139 user_name = (char *) getenv ("USER");
140 #endif /* WINDOWSNT */
141 if (!user_name)
143 pw = (struct passwd *) getpwuid (geteuid ());
144 user_name = (char *) (pw ? pw->pw_name : "unknown");
146 Vuser_login_name = build_string (user_name);
148 /* If the user name claimed in the environment vars differs from
149 the real uid, use the claimed name to find the full name. */
150 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
151 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
152 : Vuser_login_name);
154 p = (unsigned char *) getenv ("NAME");
155 if (p)
156 Vuser_full_name = build_string (p);
157 else if (NILP (Vuser_full_name))
158 Vuser_full_name = build_string ("unknown");
161 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
162 "Convert arg CHAR to a string containing that character.")
163 (character)
164 Lisp_Object character;
166 int len;
167 unsigned char str[MAX_MULTIBYTE_LENGTH];
169 CHECK_NUMBER (character, 0);
171 len = (SINGLE_BYTE_CHAR_P (XFASTINT (character))
172 ? (*str = (unsigned char)(XFASTINT (character)), 1)
173 : char_to_string (XFASTINT (character), str));
174 return make_string_from_bytes (str, 1, len);
177 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
178 "Convert arg STRING to a character, the first character of that string.\n\
179 A multibyte character is handled correctly.")
180 (string)
181 register Lisp_Object string;
183 register Lisp_Object val;
184 register struct Lisp_String *p;
185 CHECK_STRING (string, 0);
186 p = XSTRING (string);
187 if (p->size)
189 if (STRING_MULTIBYTE (string))
190 XSETFASTINT (val, STRING_CHAR (p->data, STRING_BYTES (p)));
191 else
192 XSETFASTINT (val, p->data[0]);
194 else
195 XSETFASTINT (val, 0);
196 return val;
199 static Lisp_Object
200 buildmark (charpos, bytepos)
201 int charpos, bytepos;
203 register Lisp_Object mark;
204 mark = Fmake_marker ();
205 set_marker_both (mark, Qnil, charpos, bytepos);
206 return mark;
209 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
210 "Return value of point, as an integer.\n\
211 Beginning of buffer is position (point-min)")
214 Lisp_Object temp;
215 XSETFASTINT (temp, PT);
216 return temp;
219 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
220 "Return value of point, as a marker object.")
223 return buildmark (PT, PT_BYTE);
227 clip_to_bounds (lower, num, upper)
228 int lower, num, upper;
230 if (num < lower)
231 return lower;
232 else if (num > upper)
233 return upper;
234 else
235 return num;
238 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
239 "Set point to POSITION, a number or marker.\n\
240 Beginning of buffer is position (point-min), end is (point-max).\n\
241 If the position is in the middle of a multibyte form,\n\
242 the actual point is set at the head of the multibyte form\n\
243 except in the case that `enable-multibyte-characters' is nil.")
244 (position)
245 register Lisp_Object position;
247 int pos;
249 if (MARKERP (position)
250 && current_buffer == XMARKER (position)->buffer)
252 pos = marker_position (position);
253 if (pos < BEGV)
254 SET_PT_BOTH (BEGV, BEGV_BYTE);
255 else if (pos > ZV)
256 SET_PT_BOTH (ZV, ZV_BYTE);
257 else
258 SET_PT_BOTH (pos, marker_byte_position (position));
260 return position;
263 CHECK_NUMBER_COERCE_MARKER (position, 0);
265 pos = clip_to_bounds (BEGV, XINT (position), ZV);
266 SET_PT (pos);
267 return position;
271 /* Return the start or end position of the region.
272 BEGINNINGP non-zero means return the start.
273 If there is no region active, signal an error. */
275 static Lisp_Object
276 region_limit (beginningp)
277 int beginningp;
279 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
280 Lisp_Object m;
282 if (!NILP (Vtransient_mark_mode)
283 && NILP (Vmark_even_if_inactive)
284 && NILP (current_buffer->mark_active))
285 Fsignal (Qmark_inactive, Qnil);
287 m = Fmarker_position (current_buffer->mark);
288 if (NILP (m))
289 error ("There is no region now");
291 if ((PT < XFASTINT (m)) == beginningp)
292 m = make_number (PT);
293 return m;
296 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
297 "Return position of beginning of region, as an integer.")
300 return region_limit (1);
303 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
304 "Return position of end of region, as an integer.")
307 return region_limit (0);
310 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
311 "Return this buffer's mark, as a marker object.\n\
312 Watch out! Moving this marker changes the mark position.\n\
313 If you set the marker not to point anywhere, the buffer will have no mark.")
316 return current_buffer->mark;
320 #if 0 /* Not used. */
322 /* Return nonzero if POS1 and POS2 have the same value
323 for the text property PROP. */
325 static int
326 char_property_eq (prop, pos1, pos2)
327 Lisp_Object prop;
328 Lisp_Object pos1, pos2;
330 Lisp_Object pval1, pval2;
332 pval1 = Fget_char_property (pos1, prop, Qnil);
333 pval2 = Fget_char_property (pos2, prop, Qnil);
335 return EQ (pval1, pval2);
338 #endif /* 0 */
340 /* Return the direction from which the text-property PROP would be
341 inherited by any new text inserted at POS: 1 if it would be
342 inherited from the char after POS, -1 if it would be inherited from
343 the char before POS, and 0 if from neither. */
345 static int
346 text_property_stickiness (prop, pos)
347 Lisp_Object prop;
348 Lisp_Object pos;
350 Lisp_Object front_sticky;
352 if (XINT (pos) > BEGV)
353 /* Consider previous character. */
355 Lisp_Object prev_pos, rear_non_sticky;
357 prev_pos = make_number (XINT (pos) - 1);
358 rear_non_sticky = Fget_text_property (prev_pos, Qrear_nonsticky, Qnil);
360 if (EQ (rear_non_sticky, Qnil)
361 || (CONSP (rear_non_sticky)
362 && NILP (Fmemq (prop, rear_non_sticky))))
363 /* PROP is not rear-non-sticky, and since this takes precedence over
364 any front-stickiness, PROP is inherited from before. */
365 return -1;
368 /* Consider following character. */
369 front_sticky = Fget_text_property (pos, Qfront_sticky, Qnil);
371 if (EQ (front_sticky, Qt)
372 || (CONSP (front_sticky)
373 && !NILP (Fmemq (prop, front_sticky))))
374 /* PROP is inherited from after. */
375 return 1;
377 /* PROP is not inherited from either side. */
378 return 0;
382 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
383 the value of point is used instead. If BEG or END null,
384 means don't store the beginning or end of the field.
386 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
387 position of a field, then the beginning of the previous field is
388 returned instead of the beginning of POS's field (since the end of a
389 field is actually also the beginning of the next input field, this
390 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
391 true case, if two fields are separated by a field with the special
392 value `boundary', and POS lies within it, then the two separated
393 fields are considered to be adjacent, and POS between them, when
394 finding the beginning and ending of the "merged" field.
396 Either BEG or END may be 0, in which case the corresponding value
397 is not stored. */
399 static void
400 find_field (pos, merge_at_boundary, beg, end)
401 Lisp_Object pos;
402 Lisp_Object merge_at_boundary;
403 int *beg, *end;
405 /* Fields right before and after the point. */
406 Lisp_Object before_field, after_field;
407 /* If the fields came from overlays, the associated overlays.
408 Qnil means they came from text-properties. */
409 Lisp_Object before_overlay = Qnil, after_overlay = Qnil;
410 /* 1 if POS counts as the start of a field. */
411 int at_field_start = 0;
412 /* 1 if POS counts as the end of a field. */
413 int at_field_end = 0;
415 if (NILP (pos))
416 XSETFASTINT (pos, PT);
417 else
418 CHECK_NUMBER_COERCE_MARKER (pos, 0);
420 after_field
421 = get_char_property_and_overlay (pos, Qfield, Qnil, &after_overlay);
422 before_field
423 = (XFASTINT (pos) > BEGV
424 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
425 Qfield, Qnil,
426 &before_overlay)
427 : Qnil);
429 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
430 and POS is at beginning of a field, which can also be interpreted
431 as the end of the previous field. Note that the case where if
432 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
433 more natural one; then we avoid treating the beginning of a field
434 specially. */
435 if (NILP (merge_at_boundary) && !EQ (after_field, before_field))
436 /* We are at a boundary, see which direction is inclusive. We
437 decide by seeing which field the `field' property sticks to. */
439 /* -1 means insertions go into before_field, 1 means they go
440 into after_field, 0 means neither. */
441 int stickiness;
442 /* Whether the before/after_field come from overlays. */
443 int bop = !NILP (before_overlay);
444 int aop = !NILP (after_overlay);
446 if (bop && XMARKER (OVERLAY_END (before_overlay))->insertion_type == 1)
447 /* before_field is from an overlay, which expands upon
448 end-insertions. Note that it's possible for after_overlay to
449 also eat insertions here, but then they will overlap, and
450 there's not much we can do. */
451 stickiness = -1;
452 else if (aop
453 && XMARKER (OVERLAY_START (after_overlay))->insertion_type == 0)
454 /* after_field is from an overlay, which expand to contain
455 start-insertions. */
456 stickiness = 1;
457 else if (bop && aop)
458 /* Both fields come from overlays, but neither will contain any
459 insertion here. */
460 stickiness = 0;
461 else if (bop)
462 /* before_field is an overlay that won't eat any insertion, but
463 after_field is from a text-property. Assume that the
464 text-property continues underneath the overlay, and so will
465 be inherited by any insertion, regardless of any stickiness
466 settings. */
467 stickiness = 1;
468 else if (aop)
469 /* Similarly, when after_field is the overlay. */
470 stickiness = -1;
471 else
472 /* Both fields come from text-properties. Look for explicit
473 stickiness properties. */
474 stickiness = text_property_stickiness (Qfield, pos);
476 if (stickiness > 0)
477 at_field_start = 1;
478 else if (stickiness < 0)
479 at_field_end = 1;
480 else
481 /* STICKINESS == 0 means that any inserted text will get a
482 `field' char-property of nil, so check to see if that
483 matches either of the adjacent characters (this being a
484 kind of "stickiness by default"). */
486 if (NILP (before_field))
487 at_field_end = 1; /* Sticks to the left. */
488 else if (NILP (after_field))
489 at_field_start = 1; /* Sticks to the right. */
493 /* Note about special `boundary' fields:
495 Consider the case where the point (`.') is between the fields `x' and `y':
497 xxxx.yyyy
499 In this situation, if merge_at_boundary is true, we consider the
500 `x' and `y' fields as forming one big merged field, and so the end
501 of the field is the end of `y'.
503 However, if `x' and `y' are separated by a special `boundary' field
504 (a field with a `field' char-property of 'boundary), then we ignore
505 this special field when merging adjacent fields. Here's the same
506 situation, but with a `boundary' field between the `x' and `y' fields:
508 xxx.BBBByyyy
510 Here, if point is at the end of `x', the beginning of `y', or
511 anywhere in-between (within the `boundary' field), we merge all
512 three fields and consider the beginning as being the beginning of
513 the `x' field, and the end as being the end of the `y' field. */
515 if (beg)
517 if (at_field_start)
518 /* POS is at the edge of a field, and we should consider it as
519 the beginning of the following field. */
520 *beg = XFASTINT (pos);
521 else
522 /* Find the previous field boundary. */
524 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
525 /* Skip a `boundary' field. */
526 pos = Fprevious_single_char_property_change (pos, Qfield, Qnil,Qnil);
528 pos = Fprevious_single_char_property_change (pos, Qfield, Qnil, Qnil);
529 *beg = NILP (pos) ? BEGV : XFASTINT (pos);
533 if (end)
535 if (at_field_end)
536 /* POS is at the edge of a field, and we should consider it as
537 the end of the previous field. */
538 *end = XFASTINT (pos);
539 else
540 /* Find the next field boundary. */
542 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
543 /* Skip a `boundary' field. */
544 pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
546 pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
547 *end = NILP (pos) ? ZV : XFASTINT (pos);
553 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
554 "Delete the field surrounding POS.\n\
555 A field is a region of text with the same `field' property.\n\
556 If POS is nil, the value of point is used for POS.")
557 (pos)
558 Lisp_Object pos;
560 int beg, end;
561 find_field (pos, Qnil, &beg, &end);
562 if (beg != end)
563 del_range (beg, end);
564 return Qnil;
567 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
568 "Return the contents of the field surrounding POS as a string.\n\
569 A field is a region of text with the same `field' property.\n\
570 If POS is nil, the value of point is used for POS.")
571 (pos)
572 Lisp_Object pos;
574 int beg, end;
575 find_field (pos, Qnil, &beg, &end);
576 return make_buffer_string (beg, end, 1);
579 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
580 "Return the contents of the field around POS, without text-properties.\n\
581 A field is a region of text with the same `field' property.\n\
582 If POS is nil, the value of point is used for POS.")
583 (pos)
584 Lisp_Object pos;
586 int beg, end;
587 find_field (pos, Qnil, &beg, &end);
588 return make_buffer_string (beg, end, 0);
591 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 2, 0,
592 "Return the beginning of the field surrounding POS.\n\
593 A field is a region of text with the same `field' property.\n\
594 If POS is nil, the value of point is used for POS.\n\
595 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its\n\
596 field, then the beginning of the *previous* field is returned.")
597 (pos, escape_from_edge)
598 Lisp_Object pos, escape_from_edge;
600 int beg;
601 find_field (pos, escape_from_edge, &beg, 0);
602 return make_number (beg);
605 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 2, 0,
606 "Return the end of the field surrounding POS.\n\
607 A field is a region of text with the same `field' property.\n\
608 If POS is nil, the value of point is used for POS.\n\
609 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,\n\
610 then the end of the *following* field is returned.")
611 (pos, escape_from_edge)
612 Lisp_Object pos, escape_from_edge;
614 int end;
615 find_field (pos, escape_from_edge, 0, &end);
616 return make_number (end);
619 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
620 "Return the position closest to NEW-POS that is in the same field as OLD-POS.\n\
622 A field is a region of text with the same `field' property.\n\
623 If NEW-POS is nil, then the current point is used instead, and set to the\n\
624 constrained position if that is different.\n\
626 If OLD-POS is at the boundary of two fields, then the allowable\n\
627 positions for NEW-POS depends on the value of the optional argument\n\
628 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is\n\
629 constrained to the field that has the same `field' char-property\n\
630 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE\n\
631 is non-nil, NEW-POS is constrained to the union of the two adjacent\n\
632 fields. Additionally, if two fields are separated by another field with\n\
633 the special value `boundary', then any point within this special field is\n\
634 also considered to be `on the boundary'.\n\
636 If the optional argument ONLY-IN-LINE is non-nil and constraining\n\
637 NEW-POS would move it to a different line, NEW-POS is returned\n\
638 unconstrained. This useful for commands that move by line, like\n\
639 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries\n\
640 only in the case where they can still move to the right line.\n\
642 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has\n\
643 a non-nil property of that name, then any field boundaries are ignored.\n\
645 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil.")
646 (new_pos, old_pos, escape_from_edge, only_in_line, inhibit_capture_property)
647 Lisp_Object new_pos, old_pos;
648 Lisp_Object escape_from_edge, only_in_line, inhibit_capture_property;
650 /* If non-zero, then the original point, before re-positioning. */
651 int orig_point = 0;
653 if (NILP (new_pos))
654 /* Use the current point, and afterwards, set it. */
656 orig_point = PT;
657 XSETFASTINT (new_pos, PT);
660 if (NILP (Vinhibit_field_text_motion)
661 && !EQ (new_pos, old_pos)
662 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
663 || !NILP (Fget_char_property (old_pos, Qfield, Qnil)))
664 && (NILP (inhibit_capture_property)
665 || NILP (Fget_char_property(old_pos, inhibit_capture_property, Qnil))))
666 /* NEW_POS is not within the same field as OLD_POS; try to
667 move NEW_POS so that it is. */
669 int fwd, shortage;
670 Lisp_Object field_bound;
672 CHECK_NUMBER_COERCE_MARKER (new_pos, 0);
673 CHECK_NUMBER_COERCE_MARKER (old_pos, 0);
675 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
677 if (fwd)
678 field_bound = Ffield_end (old_pos, escape_from_edge);
679 else
680 field_bound = Ffield_beginning (old_pos, escape_from_edge);
682 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
683 other side of NEW_POS, which would mean that NEW_POS is
684 already acceptable, and it's not necessary to constrain it
685 to FIELD_BOUND. */
686 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
687 /* NEW_POS should be constrained, but only if either
688 ONLY_IN_LINE is nil (in which case any constraint is OK),
689 or NEW_POS and FIELD_BOUND are on the same line (in which
690 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
691 && (NILP (only_in_line)
692 /* This is the ONLY_IN_LINE case, check that NEW_POS and
693 FIELD_BOUND are on the same line by seeing whether
694 there's an intervening newline or not. */
695 || (scan_buffer ('\n',
696 XFASTINT (new_pos), XFASTINT (field_bound),
697 fwd ? -1 : 1, &shortage, 1),
698 shortage != 0)))
699 /* Constrain NEW_POS to FIELD_BOUND. */
700 new_pos = field_bound;
702 if (orig_point && XFASTINT (new_pos) != orig_point)
703 /* The NEW_POS argument was originally nil, so automatically set PT. */
704 SET_PT (XFASTINT (new_pos));
707 return new_pos;
711 DEFUN ("line-beginning-position", Fline_beginning_position, Sline_beginning_position,
712 0, 1, 0,
713 "Return the character position of the first character on the current line.\n\
714 With argument N not nil or 1, move forward N - 1 lines first.\n\
715 If scan reaches end of buffer, return that position.\n\
716 The scan does not cross a field boundary unless it would move\n\
717 beyond there to a different line. Field boundaries are not noticed if\n\
718 `inhibit-field-text-motion' is non-nil. .And if N is nil or 1,\n\
719 and scan starts at a field boundary, the scan stops as soon as it starts.\n\
721 This function does not move point.")
723 Lisp_Object n;
725 int orig, orig_byte, end;
727 if (NILP (n))
728 XSETFASTINT (n, 1);
729 else
730 CHECK_NUMBER (n, 0);
732 orig = PT;
733 orig_byte = PT_BYTE;
734 Fforward_line (make_number (XINT (n) - 1));
735 end = PT;
737 SET_PT_BOTH (orig, orig_byte);
739 /* Return END constrained to the current input field. */
740 return Fconstrain_to_field (make_number (end), make_number (orig),
741 XINT (n) != 1 ? Qt : Qnil,
742 Qt, Qnil);
745 DEFUN ("line-end-position", Fline_end_position, Sline_end_position,
746 0, 1, 0,
747 "Return the character position of the last character on the current line.\n\
748 With argument N not nil or 1, move forward N - 1 lines first.\n\
749 If scan reaches end of buffer, return that position.\n\
750 This function does not move point.")
752 Lisp_Object n;
754 int end_pos;
755 int orig = PT;
757 if (NILP (n))
758 XSETFASTINT (n, 1);
759 else
760 CHECK_NUMBER (n, 0);
762 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
764 /* Return END_POS constrained to the current input field. */
765 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
766 Qnil, Qt, Qnil);
769 Lisp_Object
770 save_excursion_save ()
772 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
773 == current_buffer);
775 return Fcons (Fpoint_marker (),
776 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
777 Fcons (visible ? Qt : Qnil,
778 Fcons (current_buffer->mark_active,
779 selected_window))));
782 Lisp_Object
783 save_excursion_restore (info)
784 Lisp_Object info;
786 Lisp_Object tem, tem1, omark, nmark;
787 struct gcpro gcpro1, gcpro2, gcpro3;
788 int visible_p;
790 tem = Fmarker_buffer (XCAR (info));
791 /* If buffer being returned to is now deleted, avoid error */
792 /* Otherwise could get error here while unwinding to top level
793 and crash */
794 /* In that case, Fmarker_buffer returns nil now. */
795 if (NILP (tem))
796 return Qnil;
798 omark = nmark = Qnil;
799 GCPRO3 (info, omark, nmark);
801 Fset_buffer (tem);
803 /* Point marker. */
804 tem = XCAR (info);
805 Fgoto_char (tem);
806 unchain_marker (tem);
808 /* Mark marker. */
809 info = XCDR (info);
810 tem = XCAR (info);
811 omark = Fmarker_position (current_buffer->mark);
812 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
813 nmark = Fmarker_position (tem);
814 unchain_marker (tem);
816 /* visible */
817 info = XCDR (info);
818 visible_p = !NILP (XCAR (info));
820 #if 0 /* We used to make the current buffer visible in the selected window
821 if that was true previously. That avoids some anomalies.
822 But it creates others, and it wasn't documented, and it is simpler
823 and cleaner never to alter the window/buffer connections. */
824 tem1 = Fcar (tem);
825 if (!NILP (tem1)
826 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
827 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
828 #endif /* 0 */
830 /* Mark active */
831 info = XCDR (info);
832 tem = XCAR (info);
833 tem1 = current_buffer->mark_active;
834 current_buffer->mark_active = tem;
836 if (!NILP (Vrun_hooks))
838 /* If mark is active now, and either was not active
839 or was at a different place, run the activate hook. */
840 if (! NILP (current_buffer->mark_active))
842 if (! EQ (omark, nmark))
843 call1 (Vrun_hooks, intern ("activate-mark-hook"));
845 /* If mark has ceased to be active, run deactivate hook. */
846 else if (! NILP (tem1))
847 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
850 /* If buffer was visible in a window, and a different window was
851 selected, and the old selected window is still showing this
852 buffer, restore point in that window. */
853 tem = XCDR (info);
854 if (visible_p
855 && !EQ (tem, selected_window)
856 && (tem1 = XWINDOW (tem)->buffer,
857 (/* Window is live... */
858 BUFFERP (tem1)
859 /* ...and it shows the current buffer. */
860 && XBUFFER (tem1) == current_buffer)))
861 Fset_window_point (tem, make_number (PT));
863 UNGCPRO;
864 return Qnil;
867 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
868 "Save point, mark, and current buffer; execute BODY; restore those things.\n\
869 Executes BODY just like `progn'.\n\
870 The values of point, mark and the current buffer are restored\n\
871 even in case of abnormal exit (throw or error).\n\
872 The state of activation of the mark is also restored.\n\
874 This construct does not save `deactivate-mark', and therefore\n\
875 functions that change the buffer will still cause deactivation\n\
876 of the mark at the end of the command. To prevent that, bind\n\
877 `deactivate-mark' with `let'.")
878 (args)
879 Lisp_Object args;
881 register Lisp_Object val;
882 int count = specpdl_ptr - specpdl;
884 record_unwind_protect (save_excursion_restore, save_excursion_save ());
886 val = Fprogn (args);
887 return unbind_to (count, val);
890 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
891 "Save the current buffer; execute BODY; restore the current buffer.\n\
892 Executes BODY just like `progn'.")
893 (args)
894 Lisp_Object args;
896 Lisp_Object val;
897 int count = specpdl_ptr - specpdl;
899 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
901 val = Fprogn (args);
902 return unbind_to (count, val);
905 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
906 "Return the number of characters in the current buffer.\n\
907 If BUFFER, return the number of characters in that buffer instead.")
908 (buffer)
909 Lisp_Object buffer;
911 if (NILP (buffer))
912 return make_number (Z - BEG);
913 else
915 CHECK_BUFFER (buffer, 1);
916 return make_number (BUF_Z (XBUFFER (buffer))
917 - BUF_BEG (XBUFFER (buffer)));
921 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
922 "Return the minimum permissible value of point in the current buffer.\n\
923 This is 1, unless narrowing (a buffer restriction) is in effect.")
926 Lisp_Object temp;
927 XSETFASTINT (temp, BEGV);
928 return temp;
931 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
932 "Return a marker to the minimum permissible value of point in this buffer.\n\
933 This is the beginning, unless narrowing (a buffer restriction) is in effect.")
936 return buildmark (BEGV, BEGV_BYTE);
939 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
940 "Return the maximum permissible value of point in the current buffer.\n\
941 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
942 is in effect, in which case it is less.")
945 Lisp_Object temp;
946 XSETFASTINT (temp, ZV);
947 return temp;
950 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
951 "Return a marker to the maximum permissible value of point in this buffer.\n\
952 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
953 is in effect, in which case it is less.")
956 return buildmark (ZV, ZV_BYTE);
959 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
960 "Return the position of the gap, in the current buffer.\n\
961 See also `gap-size'.")
964 Lisp_Object temp;
965 XSETFASTINT (temp, GPT);
966 return temp;
969 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
970 "Return the size of the current buffer's gap.\n\
971 See also `gap-position'.")
974 Lisp_Object temp;
975 XSETFASTINT (temp, GAP_SIZE);
976 return temp;
979 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
980 "Return the byte position for character position POSITION.\n\
981 If POSITION is out of range, the value is nil.")
982 (position)
983 Lisp_Object position;
985 CHECK_NUMBER_COERCE_MARKER (position, 1);
986 if (XINT (position) < BEG || XINT (position) > Z)
987 return Qnil;
988 return make_number (CHAR_TO_BYTE (XINT (position)));
991 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
992 "Return the character position for byte position BYTEPOS.\n\
993 If BYTEPOS is out of range, the value is nil.")
994 (bytepos)
995 Lisp_Object bytepos;
997 CHECK_NUMBER (bytepos, 1);
998 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
999 return Qnil;
1000 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1003 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1004 "Return the character following point, as a number.\n\
1005 At the end of the buffer or accessible region, return 0.")
1008 Lisp_Object temp;
1009 if (PT >= ZV)
1010 XSETFASTINT (temp, 0);
1011 else
1012 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1013 return temp;
1016 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1017 "Return the character preceding point, as a number.\n\
1018 At the beginning of the buffer or accessible region, return 0.")
1021 Lisp_Object temp;
1022 if (PT <= BEGV)
1023 XSETFASTINT (temp, 0);
1024 else if (!NILP (current_buffer->enable_multibyte_characters))
1026 int pos = PT_BYTE;
1027 DEC_POS (pos);
1028 XSETFASTINT (temp, FETCH_CHAR (pos));
1030 else
1031 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1032 return temp;
1035 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1036 "Return t if point is at the beginning of the buffer.\n\
1037 If the buffer is narrowed, this means the beginning of the narrowed part.")
1040 if (PT == BEGV)
1041 return Qt;
1042 return Qnil;
1045 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1046 "Return t if point is at the end of the buffer.\n\
1047 If the buffer is narrowed, this means the end of the narrowed part.")
1050 if (PT == ZV)
1051 return Qt;
1052 return Qnil;
1055 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1056 "Return t if point is at the beginning of a line.")
1059 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1060 return Qt;
1061 return Qnil;
1064 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1065 "Return t if point is at the end of a line.\n\
1066 `End of a line' includes point being at the end of the buffer.")
1069 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1070 return Qt;
1071 return Qnil;
1074 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1075 "Return character in current buffer at position POS.\n\
1076 POS is an integer or a marker.\n\
1077 If POS is out of range, the value is nil.")
1078 (pos)
1079 Lisp_Object pos;
1081 register int pos_byte;
1083 if (NILP (pos))
1085 pos_byte = PT_BYTE;
1086 XSETFASTINT (pos, PT);
1089 if (MARKERP (pos))
1091 pos_byte = marker_byte_position (pos);
1092 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1093 return Qnil;
1095 else
1097 CHECK_NUMBER_COERCE_MARKER (pos, 0);
1098 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1099 return Qnil;
1101 pos_byte = CHAR_TO_BYTE (XINT (pos));
1104 return make_number (FETCH_CHAR (pos_byte));
1107 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1108 "Return character in current buffer preceding position POS.\n\
1109 POS is an integer or a marker.\n\
1110 If POS is out of range, the value is nil.")
1111 (pos)
1112 Lisp_Object pos;
1114 register Lisp_Object val;
1115 register int pos_byte;
1117 if (NILP (pos))
1119 pos_byte = PT_BYTE;
1120 XSETFASTINT (pos, PT);
1123 if (MARKERP (pos))
1125 pos_byte = marker_byte_position (pos);
1127 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1128 return Qnil;
1130 else
1132 CHECK_NUMBER_COERCE_MARKER (pos, 0);
1134 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1135 return Qnil;
1137 pos_byte = CHAR_TO_BYTE (XINT (pos));
1140 if (!NILP (current_buffer->enable_multibyte_characters))
1142 DEC_POS (pos_byte);
1143 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1145 else
1147 pos_byte--;
1148 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1150 return val;
1153 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1154 "Return the name under which the user logged in, as a string.\n\
1155 This is based on the effective uid, not the real uid.\n\
1156 Also, if the environment variable LOGNAME or USER is set,\n\
1157 that determines the value of this function.\n\n\
1158 If optional argument UID is an integer, return the login name of the user\n\
1159 with that uid, or nil if there is no such user.")
1160 (uid)
1161 Lisp_Object uid;
1163 struct passwd *pw;
1165 /* Set up the user name info if we didn't do it before.
1166 (That can happen if Emacs is dumpable
1167 but you decide to run `temacs -l loadup' and not dump. */
1168 if (INTEGERP (Vuser_login_name))
1169 init_editfns ();
1171 if (NILP (uid))
1172 return Vuser_login_name;
1174 CHECK_NUMBER (uid, 0);
1175 pw = (struct passwd *) getpwuid (XINT (uid));
1176 return (pw ? build_string (pw->pw_name) : Qnil);
1179 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1180 0, 0, 0,
1181 "Return the name of the user's real uid, as a string.\n\
1182 This ignores the environment variables LOGNAME and USER, so it differs from\n\
1183 `user-login-name' when running under `su'.")
1186 /* Set up the user name info if we didn't do it before.
1187 (That can happen if Emacs is dumpable
1188 but you decide to run `temacs -l loadup' and not dump. */
1189 if (INTEGERP (Vuser_login_name))
1190 init_editfns ();
1191 return Vuser_real_login_name;
1194 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1195 "Return the effective uid of Emacs, as an integer.")
1198 return make_number (geteuid ());
1201 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1202 "Return the real uid of Emacs, as an integer.")
1205 return make_number (getuid ());
1208 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1209 "Return the full name of the user logged in, as a string.\n\
1210 If the full name corresponding to Emacs's userid is not known,\n\
1211 return \"unknown\".\n\
1213 If optional argument UID is an integer, return the full name of the user\n\
1214 with that uid, or nil if there is no such user.\n\
1215 If UID is a string, return the full name of the user with that login\n\
1216 name, or nil if there is no such user.")
1217 (uid)
1218 Lisp_Object uid;
1220 struct passwd *pw;
1221 register unsigned char *p, *q;
1222 Lisp_Object full;
1224 if (NILP (uid))
1225 return Vuser_full_name;
1226 else if (NUMBERP (uid))
1227 pw = (struct passwd *) getpwuid (XINT (uid));
1228 else if (STRINGP (uid))
1229 pw = (struct passwd *) getpwnam (XSTRING (uid)->data);
1230 else
1231 error ("Invalid UID specification");
1233 if (!pw)
1234 return Qnil;
1236 p = (unsigned char *) USER_FULL_NAME;
1237 /* Chop off everything after the first comma. */
1238 q = (unsigned char *) index (p, ',');
1239 full = make_string (p, q ? q - p : strlen (p));
1241 #ifdef AMPERSAND_FULL_NAME
1242 p = XSTRING (full)->data;
1243 q = (unsigned char *) index (p, '&');
1244 /* Substitute the login name for the &, upcasing the first character. */
1245 if (q)
1247 register unsigned char *r;
1248 Lisp_Object login;
1250 login = Fuser_login_name (make_number (pw->pw_uid));
1251 r = (unsigned char *) alloca (strlen (p) + XSTRING (login)->size + 1);
1252 bcopy (p, r, q - p);
1253 r[q - p] = 0;
1254 strcat (r, XSTRING (login)->data);
1255 r[q - p] = UPCASE (r[q - p]);
1256 strcat (r, q + 1);
1257 full = build_string (r);
1259 #endif /* AMPERSAND_FULL_NAME */
1261 return full;
1264 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1265 "Return the name of the machine you are running on, as a string.")
1268 return Vsystem_name;
1271 /* For the benefit of callers who don't want to include lisp.h */
1273 char *
1274 get_system_name ()
1276 if (STRINGP (Vsystem_name))
1277 return (char *) XSTRING (Vsystem_name)->data;
1278 else
1279 return "";
1282 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1283 "Return the process ID of Emacs, as an integer.")
1286 return make_number (getpid ());
1289 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1290 "Return the current time, as the number of seconds since 1970-01-01 00:00:00.\n\
1291 The time is returned as a list of three integers. The first has the\n\
1292 most significant 16 bits of the seconds, while the second has the\n\
1293 least significant 16 bits. The third integer gives the microsecond\n\
1294 count.\n\
1296 The microsecond count is zero on systems that do not provide\n\
1297 resolution finer than a second.")
1300 EMACS_TIME t;
1301 Lisp_Object result[3];
1303 EMACS_GET_TIME (t);
1304 XSETINT (result[0], (EMACS_SECS (t) >> 16) & 0xffff);
1305 XSETINT (result[1], (EMACS_SECS (t) >> 0) & 0xffff);
1306 XSETINT (result[2], EMACS_USECS (t));
1308 return Flist (3, result);
1312 static int
1313 lisp_time_argument (specified_time, result, usec)
1314 Lisp_Object specified_time;
1315 time_t *result;
1316 int *usec;
1318 if (NILP (specified_time))
1320 if (usec)
1322 EMACS_TIME t;
1324 EMACS_GET_TIME (t);
1325 *usec = EMACS_USECS (t);
1326 *result = EMACS_SECS (t);
1327 return 1;
1329 else
1330 return time (result) != -1;
1332 else
1334 Lisp_Object high, low;
1335 high = Fcar (specified_time);
1336 CHECK_NUMBER (high, 0);
1337 low = Fcdr (specified_time);
1338 if (CONSP (low))
1340 if (usec)
1342 Lisp_Object usec_l = Fcdr (low);
1343 if (CONSP (usec_l))
1344 usec_l = Fcar (usec_l);
1345 if (NILP (usec_l))
1346 *usec = 0;
1347 else
1349 CHECK_NUMBER (usec_l, 0);
1350 *usec = XINT (usec_l);
1353 low = Fcar (low);
1355 else if (usec)
1356 *usec = 0;
1357 CHECK_NUMBER (low, 0);
1358 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1359 return *result >> 16 == XINT (high);
1363 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1364 "Return the current time, as a float number of seconds since the epoch.\n\
1365 If an argument is given, it specifies a time to convert to float\n\
1366 instead of the current time. The argument should have the forms:\n\
1367 (HIGH . LOW) or (HIGH LOW USEC) or (HIGH LOW . USEC).\n\
1368 Thus, you can use times obtained from `current-time'\n\
1369 and from `file-attributes'.\n\
1371 WARNING: Since the result is floating point, it may not be exact.\n\
1372 Do not use this function if precise time stamps are required.")
1373 (specified_time)
1374 Lisp_Object specified_time;
1376 time_t sec;
1377 int usec;
1379 if (! lisp_time_argument (specified_time, &sec, &usec))
1380 error ("Invalid time specification");
1382 return make_float ((sec * 1e6 + usec) / 1e6);
1385 /* Write information into buffer S of size MAXSIZE, according to the
1386 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1387 Default to Universal Time if UT is nonzero, local time otherwise.
1388 Return the number of bytes written, not including the terminating
1389 '\0'. If S is NULL, nothing will be written anywhere; so to
1390 determine how many bytes would be written, use NULL for S and
1391 ((size_t) -1) for MAXSIZE.
1393 This function behaves like emacs_strftimeu, except it allows null
1394 bytes in FORMAT. */
1395 static size_t
1396 emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
1397 char *s;
1398 size_t maxsize;
1399 const char *format;
1400 size_t format_len;
1401 const struct tm *tp;
1402 int ut;
1404 size_t total = 0;
1406 /* Loop through all the null-terminated strings in the format
1407 argument. Normally there's just one null-terminated string, but
1408 there can be arbitrarily many, concatenated together, if the
1409 format contains '\0' bytes. emacs_strftimeu stops at the first
1410 '\0' byte so we must invoke it separately for each such string. */
1411 for (;;)
1413 size_t len;
1414 size_t result;
1416 if (s)
1417 s[0] = '\1';
1419 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1421 if (s)
1423 if (result == 0 && s[0] != '\0')
1424 return 0;
1425 s += result + 1;
1428 maxsize -= result + 1;
1429 total += result;
1430 len = strlen (format);
1431 if (len == format_len)
1432 return total;
1433 total++;
1434 format += len + 1;
1435 format_len -= len + 1;
1440 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1441 "Use FORMAT-STRING to format the time TIME, or now if omitted.\n\
1442 TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as returned by\n\
1443 `current-time' or `file-attributes'.\n\
1444 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME\n\
1445 as Universal Time; nil means describe TIME in the local time zone.\n\
1446 The value is a copy of FORMAT-STRING, but with certain constructs replaced\n\
1447 by text that describes the specified date and time in TIME:\n\
1449 %Y is the year, %y within the century, %C the century.\n\
1450 %G is the year corresponding to the ISO week, %g within the century.\n\
1451 %m is the numeric month.\n\
1452 %b and %h are the locale's abbreviated month name, %B the full name.\n\
1453 %d is the day of the month, zero-padded, %e is blank-padded.\n\
1454 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.\n\
1455 %a is the locale's abbreviated name of the day of week, %A the full name.\n\
1456 %U is the week number starting on Sunday, %W starting on Monday,\n\
1457 %V according to ISO 8601.\n\
1458 %j is the day of the year.\n\
1460 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H\n\
1461 only blank-padded, %l is like %I blank-padded.\n\
1462 %p is the locale's equivalent of either AM or PM.\n\
1463 %M is the minute.\n\
1464 %S is the second.\n\
1465 %Z is the time zone name, %z is the numeric form.\n\
1466 %s is the number of seconds since 1970-01-01 00:00:00 +0000.\n\
1468 %c is the locale's date and time format.\n\
1469 %x is the locale's \"preferred\" date format.\n\
1470 %D is like \"%m/%d/%y\".\n\
1472 %R is like \"%H:%M\", %T is like \"%H:%M:%S\", %r is like \"%I:%M:%S %p\".\n\
1473 %X is the locale's \"preferred\" time format.\n\
1475 Finally, %n is a newline, %t is a tab, %% is a literal %.\n\
1477 Certain flags and modifiers are available with some format controls.\n\
1478 The flags are `_', `-', `^' and `#'. For certain characters X,\n\
1479 %_X is like %X, but padded with blanks; %-X is like %X,\n\
1480 ut without padding. %^X is like %X but with all textual\n\
1481 characters up-cased; %#X is like %X but with letter-case of\n\
1482 all textual characters reversed.\n\
1483 %NX (where N stands for an integer) is like %X,\n\
1484 but takes up at least N (a number) positions.\n\
1485 The modifiers are `E' and `O'. For certain characters X,\n\
1486 %EX is a locale's alternative version of %X;\n\
1487 %OX is like %X, but uses the locale's number symbols.\n\
1489 For example, to produce full ISO 8601 format, use \"%Y-%m-%dT%T%z\".")
1490 (format_string, time, universal)
1493 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1494 0 /* See immediately above */)
1495 (format_string, time, universal)
1496 Lisp_Object format_string, time, universal;
1498 time_t value;
1499 int size;
1500 struct tm *tm;
1501 int ut = ! NILP (universal);
1503 CHECK_STRING (format_string, 1);
1505 if (! lisp_time_argument (time, &value, NULL))
1506 error ("Invalid time specification");
1508 format_string = code_convert_string_norecord (format_string,
1509 Vlocale_coding_system, 1);
1511 /* This is probably enough. */
1512 size = STRING_BYTES (XSTRING (format_string)) * 6 + 50;
1514 tm = ut ? gmtime (&value) : localtime (&value);
1515 if (! tm)
1516 error ("Specified time is not representable");
1518 synchronize_system_time_locale ();
1520 while (1)
1522 char *buf = (char *) alloca (size + 1);
1523 int result;
1525 buf[0] = '\1';
1526 result = emacs_memftimeu (buf, size, XSTRING (format_string)->data,
1527 STRING_BYTES (XSTRING (format_string)),
1528 tm, ut);
1529 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1530 return code_convert_string_norecord (make_string (buf, result),
1531 Vlocale_coding_system, 0);
1533 /* If buffer was too small, make it bigger and try again. */
1534 result = emacs_memftimeu (NULL, (size_t) -1,
1535 XSTRING (format_string)->data,
1536 STRING_BYTES (XSTRING (format_string)),
1537 tm, ut);
1538 size = result + 1;
1542 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1543 "Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).\n\
1544 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED)\n\
1545 or (HIGH . LOW), as from `current-time' and `file-attributes', or `nil'\n\
1546 to use the current time. The list has the following nine members:\n\
1547 SEC is an integer between 0 and 60; SEC is 60 for a leap second, which\n\
1548 only some operating systems support. MINUTE is an integer between 0 and 59.\n\
1549 HOUR is an integer between 0 and 23. DAY is an integer between 1 and 31.\n\
1550 MONTH is an integer between 1 and 12. YEAR is an integer indicating the\n\
1551 four-digit year. DOW is the day of week, an integer between 0 and 6, where\n\
1552 0 is Sunday. DST is t if daylight savings time is effect, otherwise nil.\n\
1553 ZONE is an integer indicating the number of seconds east of Greenwich.\n\
1554 \(Note that Common Lisp has different meanings for DOW and ZONE.)")
1555 (specified_time)
1556 Lisp_Object specified_time;
1558 time_t time_spec;
1559 struct tm save_tm;
1560 struct tm *decoded_time;
1561 Lisp_Object list_args[9];
1563 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1564 error ("Invalid time specification");
1566 decoded_time = localtime (&time_spec);
1567 if (! decoded_time)
1568 error ("Specified time is not representable");
1569 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1570 XSETFASTINT (list_args[1], decoded_time->tm_min);
1571 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1572 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1573 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1574 XSETINT (list_args[5], decoded_time->tm_year + 1900);
1575 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1576 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1578 /* Make a copy, in case gmtime modifies the struct. */
1579 save_tm = *decoded_time;
1580 decoded_time = gmtime (&time_spec);
1581 if (decoded_time == 0)
1582 list_args[8] = Qnil;
1583 else
1584 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1585 return Flist (9, list_args);
1588 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1589 "Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.\n\
1590 This is the reverse operation of `decode-time', which see.\n\
1591 ZONE defaults to the current time zone rule. This can\n\
1592 be a string or t (as from `set-time-zone-rule'), or it can be a list\n\
1593 \(as from `current-time-zone') or an integer (as from `decode-time')\n\
1594 applied without consideration for daylight savings time.\n\
1596 You can pass more than 7 arguments; then the first six arguments\n\
1597 are used as SECOND through YEAR, and the *last* argument is used as ZONE.\n\
1598 The intervening arguments are ignored.\n\
1599 This feature lets (apply 'encode-time (decode-time ...)) work.\n\
1601 Out-of-range values for SEC, MINUTE, HOUR, DAY, or MONTH are allowed;\n\
1602 for example, a DAY of 0 means the day preceding the given month.\n\
1603 Year numbers less than 100 are treated just like other year numbers.\n\
1604 If you want them to stand for years in this century, you must do that yourself.")
1605 (nargs, args)
1606 int nargs;
1607 register Lisp_Object *args;
1609 time_t time;
1610 struct tm tm;
1611 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1613 CHECK_NUMBER (args[0], 0); /* second */
1614 CHECK_NUMBER (args[1], 1); /* minute */
1615 CHECK_NUMBER (args[2], 2); /* hour */
1616 CHECK_NUMBER (args[3], 3); /* day */
1617 CHECK_NUMBER (args[4], 4); /* month */
1618 CHECK_NUMBER (args[5], 5); /* year */
1620 tm.tm_sec = XINT (args[0]);
1621 tm.tm_min = XINT (args[1]);
1622 tm.tm_hour = XINT (args[2]);
1623 tm.tm_mday = XINT (args[3]);
1624 tm.tm_mon = XINT (args[4]) - 1;
1625 tm.tm_year = XINT (args[5]) - 1900;
1626 tm.tm_isdst = -1;
1628 if (CONSP (zone))
1629 zone = Fcar (zone);
1630 if (NILP (zone))
1631 time = mktime (&tm);
1632 else
1634 char tzbuf[100];
1635 char *tzstring;
1636 char **oldenv = environ, **newenv;
1638 if (EQ (zone, Qt))
1639 tzstring = "UTC0";
1640 else if (STRINGP (zone))
1641 tzstring = (char *) XSTRING (zone)->data;
1642 else if (INTEGERP (zone))
1644 int abszone = abs (XINT (zone));
1645 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1646 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1647 tzstring = tzbuf;
1649 else
1650 error ("Invalid time zone specification");
1652 /* Set TZ before calling mktime; merely adjusting mktime's returned
1653 value doesn't suffice, since that would mishandle leap seconds. */
1654 set_time_zone_rule (tzstring);
1656 time = mktime (&tm);
1658 /* Restore TZ to previous value. */
1659 newenv = environ;
1660 environ = oldenv;
1661 xfree (newenv);
1662 #ifdef LOCALTIME_CACHE
1663 tzset ();
1664 #endif
1667 if (time == (time_t) -1)
1668 error ("Specified time is not representable");
1670 return make_time (time);
1673 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1674 "Return the current time, as a human-readable string.\n\
1675 Programs can use this function to decode a time,\n\
1676 since the number of columns in each field is fixed.\n\
1677 The format is `Sun Sep 16 01:03:52 1973'.\n\
1678 However, see also the functions `decode-time' and `format-time-string'\n\
1679 which provide a much more powerful and general facility.\n\
1681 If an argument is given, it specifies a time to format\n\
1682 instead of the current time. The argument should have the form:\n\
1683 (HIGH . LOW)\n\
1684 or the form:\n\
1685 (HIGH LOW . IGNORED).\n\
1686 Thus, you can use times obtained from `current-time'\n\
1687 and from `file-attributes'.")
1688 (specified_time)
1689 Lisp_Object specified_time;
1691 time_t value;
1692 char buf[30];
1693 register char *tem;
1695 if (! lisp_time_argument (specified_time, &value, NULL))
1696 value = -1;
1697 tem = (char *) ctime (&value);
1699 strncpy (buf, tem, 24);
1700 buf[24] = 0;
1702 return build_string (buf);
1705 #define TM_YEAR_BASE 1900
1707 /* Yield A - B, measured in seconds.
1708 This function is copied from the GNU C Library. */
1709 static int
1710 tm_diff (a, b)
1711 struct tm *a, *b;
1713 /* Compute intervening leap days correctly even if year is negative.
1714 Take care to avoid int overflow in leap day calculations,
1715 but it's OK to assume that A and B are close to each other. */
1716 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1717 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1718 int a100 = a4 / 25 - (a4 % 25 < 0);
1719 int b100 = b4 / 25 - (b4 % 25 < 0);
1720 int a400 = a100 >> 2;
1721 int b400 = b100 >> 2;
1722 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1723 int years = a->tm_year - b->tm_year;
1724 int days = (365 * years + intervening_leap_days
1725 + (a->tm_yday - b->tm_yday));
1726 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1727 + (a->tm_min - b->tm_min))
1728 + (a->tm_sec - b->tm_sec));
1731 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1732 "Return the offset and name for the local time zone.\n\
1733 This returns a list of the form (OFFSET NAME).\n\
1734 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).\n\
1735 A negative value means west of Greenwich.\n\
1736 NAME is a string giving the name of the time zone.\n\
1737 If an argument is given, it specifies when the time zone offset is determined\n\
1738 instead of using the current time. The argument should have the form:\n\
1739 (HIGH . LOW)\n\
1740 or the form:\n\
1741 (HIGH LOW . IGNORED).\n\
1742 Thus, you can use times obtained from `current-time'\n\
1743 and from `file-attributes'.\n\
1745 Some operating systems cannot provide all this information to Emacs;\n\
1746 in this case, `current-time-zone' returns a list containing nil for\n\
1747 the data it can't find.")
1748 (specified_time)
1749 Lisp_Object specified_time;
1751 time_t value;
1752 struct tm *t;
1753 struct tm gmt;
1755 if (lisp_time_argument (specified_time, &value, NULL)
1756 && (t = gmtime (&value)) != 0
1757 && (gmt = *t, t = localtime (&value)) != 0)
1759 int offset = tm_diff (t, &gmt);
1760 char *s = 0;
1761 char buf[6];
1762 #ifdef HAVE_TM_ZONE
1763 if (t->tm_zone)
1764 s = (char *)t->tm_zone;
1765 #else /* not HAVE_TM_ZONE */
1766 #ifdef HAVE_TZNAME
1767 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1768 s = tzname[t->tm_isdst];
1769 #endif
1770 #endif /* not HAVE_TM_ZONE */
1772 #if defined HAVE_TM_ZONE || defined HAVE_TZNAME
1773 if (s)
1775 /* On Japanese w32, we can get a Japanese string as time
1776 zone name. Don't accept that. */
1777 char *p;
1778 for (p = s; *p && (isalnum (*p) || *p == ' '); ++p)
1780 if (p == s || *p)
1781 s = NULL;
1783 #endif
1785 if (!s)
1787 /* No local time zone name is available; use "+-NNNN" instead. */
1788 int am = (offset < 0 ? -offset : offset) / 60;
1789 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1790 s = buf;
1792 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
1794 else
1795 return Fmake_list (make_number (2), Qnil);
1798 /* This holds the value of `environ' produced by the previous
1799 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
1800 has never been called. */
1801 static char **environbuf;
1803 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
1804 "Set the local time zone using TZ, a string specifying a time zone rule.\n\
1805 If TZ is nil, use implementation-defined default time zone information.\n\
1806 If TZ is t, use Universal Time.")
1807 (tz)
1808 Lisp_Object tz;
1810 char *tzstring;
1812 if (NILP (tz))
1813 tzstring = 0;
1814 else if (EQ (tz, Qt))
1815 tzstring = "UTC0";
1816 else
1818 CHECK_STRING (tz, 0);
1819 tzstring = (char *) XSTRING (tz)->data;
1822 set_time_zone_rule (tzstring);
1823 if (environbuf)
1824 free (environbuf);
1825 environbuf = environ;
1827 return Qnil;
1830 #ifdef LOCALTIME_CACHE
1832 /* These two values are known to load tz files in buggy implementations,
1833 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1834 Their values shouldn't matter in non-buggy implementations.
1835 We don't use string literals for these strings,
1836 since if a string in the environment is in readonly
1837 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
1838 See Sun bugs 1113095 and 1114114, ``Timezone routines
1839 improperly modify environment''. */
1841 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
1842 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
1844 #endif
1846 /* Set the local time zone rule to TZSTRING.
1847 This allocates memory into `environ', which it is the caller's
1848 responsibility to free. */
1850 void
1851 set_time_zone_rule (tzstring)
1852 char *tzstring;
1854 int envptrs;
1855 char **from, **to, **newenv;
1857 /* Make the ENVIRON vector longer with room for TZSTRING. */
1858 for (from = environ; *from; from++)
1859 continue;
1860 envptrs = from - environ + 2;
1861 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
1862 + (tzstring ? strlen (tzstring) + 4 : 0));
1864 /* Add TZSTRING to the end of environ, as a value for TZ. */
1865 if (tzstring)
1867 char *t = (char *) (to + envptrs);
1868 strcpy (t, "TZ=");
1869 strcat (t, tzstring);
1870 *to++ = t;
1873 /* Copy the old environ vector elements into NEWENV,
1874 but don't copy the TZ variable.
1875 So we have only one definition of TZ, which came from TZSTRING. */
1876 for (from = environ; *from; from++)
1877 if (strncmp (*from, "TZ=", 3) != 0)
1878 *to++ = *from;
1879 *to = 0;
1881 environ = newenv;
1883 /* If we do have a TZSTRING, NEWENV points to the vector slot where
1884 the TZ variable is stored. If we do not have a TZSTRING,
1885 TO points to the vector slot which has the terminating null. */
1887 #ifdef LOCALTIME_CACHE
1889 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
1890 "US/Pacific" that loads a tz file, then changes to a value like
1891 "XXX0" that does not load a tz file, and then changes back to
1892 its original value, the last change is (incorrectly) ignored.
1893 Also, if TZ changes twice in succession to values that do
1894 not load a tz file, tzset can dump core (see Sun bug#1225179).
1895 The following code works around these bugs. */
1897 if (tzstring)
1899 /* Temporarily set TZ to a value that loads a tz file
1900 and that differs from tzstring. */
1901 char *tz = *newenv;
1902 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
1903 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
1904 tzset ();
1905 *newenv = tz;
1907 else
1909 /* The implied tzstring is unknown, so temporarily set TZ to
1910 two different values that each load a tz file. */
1911 *to = set_time_zone_rule_tz1;
1912 to[1] = 0;
1913 tzset ();
1914 *to = set_time_zone_rule_tz2;
1915 tzset ();
1916 *to = 0;
1919 /* Now TZ has the desired value, and tzset can be invoked safely. */
1922 tzset ();
1923 #endif
1926 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
1927 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
1928 type of object is Lisp_String). INHERIT is passed to
1929 INSERT_FROM_STRING_FUNC as the last argument. */
1931 static void
1932 general_insert_function (insert_func, insert_from_string_func,
1933 inherit, nargs, args)
1934 void (*insert_func) P_ ((unsigned char *, int));
1935 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
1936 int inherit, nargs;
1937 register Lisp_Object *args;
1939 register int argnum;
1940 register Lisp_Object val;
1942 for (argnum = 0; argnum < nargs; argnum++)
1944 val = args[argnum];
1945 retry:
1946 if (INTEGERP (val))
1948 unsigned char str[MAX_MULTIBYTE_LENGTH];
1949 int len;
1951 if (!NILP (current_buffer->enable_multibyte_characters))
1952 len = CHAR_STRING (XFASTINT (val), str);
1953 else
1955 str[0] = (SINGLE_BYTE_CHAR_P (XINT (val))
1956 ? XINT (val)
1957 : multibyte_char_to_unibyte (XINT (val), Qnil));
1958 len = 1;
1960 (*insert_func) (str, len);
1962 else if (STRINGP (val))
1964 (*insert_from_string_func) (val, 0, 0,
1965 XSTRING (val)->size,
1966 STRING_BYTES (XSTRING (val)),
1967 inherit);
1969 else
1971 val = wrong_type_argument (Qchar_or_string_p, val);
1972 goto retry;
1977 void
1978 insert1 (arg)
1979 Lisp_Object arg;
1981 Finsert (1, &arg);
1985 /* Callers passing one argument to Finsert need not gcpro the
1986 argument "array", since the only element of the array will
1987 not be used after calling insert or insert_from_string, so
1988 we don't care if it gets trashed. */
1990 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
1991 "Insert the arguments, either strings or characters, at point.\n\
1992 Point and before-insertion markers move forward to end up\n\
1993 after the inserted text.\n\
1994 Any other markers at the point of insertion remain before the text.\n\
1996 If the current buffer is multibyte, unibyte strings are converted\n\
1997 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
1998 If the current buffer is unibyte, multibyte strings are converted\n\
1999 to unibyte for insertion.")
2000 (nargs, args)
2001 int nargs;
2002 register Lisp_Object *args;
2004 general_insert_function (insert, insert_from_string, 0, nargs, args);
2005 return Qnil;
2008 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2009 0, MANY, 0,
2010 "Insert the arguments at point, inheriting properties from adjoining text.\n\
2011 Point and before-insertion markers move forward to end up\n\
2012 after the inserted text.\n\
2013 Any other markers at the point of insertion remain before the text.\n\
2015 If the current buffer is multibyte, unibyte strings are converted\n\
2016 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
2017 If the current buffer is unibyte, multibyte strings are converted\n\
2018 to unibyte for insertion.")
2019 (nargs, args)
2020 int nargs;
2021 register Lisp_Object *args;
2023 general_insert_function (insert_and_inherit, insert_from_string, 1,
2024 nargs, args);
2025 return Qnil;
2028 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2029 "Insert strings or characters at point, relocating markers after the text.\n\
2030 Point and markers move forward to end up after the inserted text.\n\
2032 If the current buffer is multibyte, unibyte strings are converted\n\
2033 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
2034 If the current buffer is unibyte, multibyte strings are converted\n\
2035 to unibyte for insertion.")
2036 (nargs, args)
2037 int nargs;
2038 register Lisp_Object *args;
2040 general_insert_function (insert_before_markers,
2041 insert_from_string_before_markers, 0,
2042 nargs, args);
2043 return Qnil;
2046 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2047 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2048 "Insert text at point, relocating markers and inheriting properties.\n\
2049 Point and markers move forward to end up after the inserted text.\n\
2051 If the current buffer is multibyte, unibyte strings are converted\n\
2052 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
2053 If the current buffer is unibyte, multibyte strings are converted\n\
2054 to unibyte for insertion.")
2055 (nargs, args)
2056 int nargs;
2057 register Lisp_Object *args;
2059 general_insert_function (insert_before_markers_and_inherit,
2060 insert_from_string_before_markers, 1,
2061 nargs, args);
2062 return Qnil;
2065 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2066 "Insert COUNT (second arg) copies of CHARACTER (first arg).\n\
2067 Both arguments are required.\n\
2068 Point, and before-insertion markers, are relocated as in the function `insert'.\n\
2069 The optional third arg INHERIT, if non-nil, says to inherit text properties\n\
2070 from adjoining text, if those properties are sticky.")
2071 (character, count, inherit)
2072 Lisp_Object character, count, inherit;
2074 register unsigned char *string;
2075 register int strlen;
2076 register int i, n;
2077 int len;
2078 unsigned char str[MAX_MULTIBYTE_LENGTH];
2080 CHECK_NUMBER (character, 0);
2081 CHECK_NUMBER (count, 1);
2083 if (!NILP (current_buffer->enable_multibyte_characters))
2084 len = CHAR_STRING (XFASTINT (character), str);
2085 else
2086 str[0] = XFASTINT (character), len = 1;
2087 n = XINT (count) * len;
2088 if (n <= 0)
2089 return Qnil;
2090 strlen = min (n, 256 * len);
2091 string = (unsigned char *) alloca (strlen);
2092 for (i = 0; i < strlen; i++)
2093 string[i] = str[i % len];
2094 while (n >= strlen)
2096 QUIT;
2097 if (!NILP (inherit))
2098 insert_and_inherit (string, strlen);
2099 else
2100 insert (string, strlen);
2101 n -= strlen;
2103 if (n > 0)
2105 if (!NILP (inherit))
2106 insert_and_inherit (string, n);
2107 else
2108 insert (string, n);
2110 return Qnil;
2114 /* Making strings from buffer contents. */
2116 /* Return a Lisp_String containing the text of the current buffer from
2117 START to END. If text properties are in use and the current buffer
2118 has properties in the range specified, the resulting string will also
2119 have them, if PROPS is nonzero.
2121 We don't want to use plain old make_string here, because it calls
2122 make_uninit_string, which can cause the buffer arena to be
2123 compacted. make_string has no way of knowing that the data has
2124 been moved, and thus copies the wrong data into the string. This
2125 doesn't effect most of the other users of make_string, so it should
2126 be left as is. But we should use this function when conjuring
2127 buffer substrings. */
2129 Lisp_Object
2130 make_buffer_string (start, end, props)
2131 int start, end;
2132 int props;
2134 int start_byte = CHAR_TO_BYTE (start);
2135 int end_byte = CHAR_TO_BYTE (end);
2137 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2140 /* Return a Lisp_String containing the text of the current buffer from
2141 START / START_BYTE to END / END_BYTE.
2143 If text properties are in use and the current buffer
2144 has properties in the range specified, the resulting string will also
2145 have them, if PROPS is nonzero.
2147 We don't want to use plain old make_string here, because it calls
2148 make_uninit_string, which can cause the buffer arena to be
2149 compacted. make_string has no way of knowing that the data has
2150 been moved, and thus copies the wrong data into the string. This
2151 doesn't effect most of the other users of make_string, so it should
2152 be left as is. But we should use this function when conjuring
2153 buffer substrings. */
2155 Lisp_Object
2156 make_buffer_string_both (start, start_byte, end, end_byte, props)
2157 int start, start_byte, end, end_byte;
2158 int props;
2160 Lisp_Object result, tem, tem1;
2162 if (start < GPT && GPT < end)
2163 move_gap (start);
2165 if (! NILP (current_buffer->enable_multibyte_characters))
2166 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2167 else
2168 result = make_uninit_string (end - start);
2169 bcopy (BYTE_POS_ADDR (start_byte), XSTRING (result)->data,
2170 end_byte - start_byte);
2172 /* If desired, update and copy the text properties. */
2173 if (props)
2175 update_buffer_properties (start, end);
2177 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2178 tem1 = Ftext_properties_at (make_number (start), Qnil);
2180 if (XINT (tem) != end || !NILP (tem1))
2181 copy_intervals_to_string (result, current_buffer, start,
2182 end - start);
2185 return result;
2188 /* Call Vbuffer_access_fontify_functions for the range START ... END
2189 in the current buffer, if necessary. */
2191 static void
2192 update_buffer_properties (start, end)
2193 int start, end;
2195 /* If this buffer has some access functions,
2196 call them, specifying the range of the buffer being accessed. */
2197 if (!NILP (Vbuffer_access_fontify_functions))
2199 Lisp_Object args[3];
2200 Lisp_Object tem;
2202 args[0] = Qbuffer_access_fontify_functions;
2203 XSETINT (args[1], start);
2204 XSETINT (args[2], end);
2206 /* But don't call them if we can tell that the work
2207 has already been done. */
2208 if (!NILP (Vbuffer_access_fontified_property))
2210 tem = Ftext_property_any (args[1], args[2],
2211 Vbuffer_access_fontified_property,
2212 Qnil, Qnil);
2213 if (! NILP (tem))
2214 Frun_hook_with_args (3, args);
2216 else
2217 Frun_hook_with_args (3, args);
2221 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2222 "Return the contents of part of the current buffer as a string.\n\
2223 The two arguments START and END are character positions;\n\
2224 they can be in either order.\n\
2225 The string returned is multibyte if the buffer is multibyte.\n\
2227 This function copies the text properties of that part of the buffer\n\
2228 into the result string; if you don't want the text properties,\n\
2229 use `buffer-substring-no-properties' instead.")
2230 (start, end)
2231 Lisp_Object start, end;
2233 register int b, e;
2235 validate_region (&start, &end);
2236 b = XINT (start);
2237 e = XINT (end);
2239 return make_buffer_string (b, e, 1);
2242 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2243 Sbuffer_substring_no_properties, 2, 2, 0,
2244 "Return the characters of part of the buffer, without the text properties.\n\
2245 The two arguments START and END are character positions;\n\
2246 they can be in either order.")
2247 (start, end)
2248 Lisp_Object start, end;
2250 register int b, e;
2252 validate_region (&start, &end);
2253 b = XINT (start);
2254 e = XINT (end);
2256 return make_buffer_string (b, e, 0);
2259 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2260 "Return the contents of the current buffer as a string.\n\
2261 If narrowing is in effect, this function returns only the visible part\n\
2262 of the buffer.")
2265 return make_buffer_string (BEGV, ZV, 1);
2268 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2269 1, 3, 0,
2270 "Insert before point a substring of the contents of buffer BUFFER.\n\
2271 BUFFER may be a buffer or a buffer name.\n\
2272 Arguments START and END are character numbers specifying the substring.\n\
2273 They default to the beginning and the end of BUFFER.")
2274 (buf, start, end)
2275 Lisp_Object buf, start, end;
2277 register int b, e, temp;
2278 register struct buffer *bp, *obuf;
2279 Lisp_Object buffer;
2281 buffer = Fget_buffer (buf);
2282 if (NILP (buffer))
2283 nsberror (buf);
2284 bp = XBUFFER (buffer);
2285 if (NILP (bp->name))
2286 error ("Selecting deleted buffer");
2288 if (NILP (start))
2289 b = BUF_BEGV (bp);
2290 else
2292 CHECK_NUMBER_COERCE_MARKER (start, 0);
2293 b = XINT (start);
2295 if (NILP (end))
2296 e = BUF_ZV (bp);
2297 else
2299 CHECK_NUMBER_COERCE_MARKER (end, 1);
2300 e = XINT (end);
2303 if (b > e)
2304 temp = b, b = e, e = temp;
2306 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2307 args_out_of_range (start, end);
2309 obuf = current_buffer;
2310 set_buffer_internal_1 (bp);
2311 update_buffer_properties (b, e);
2312 set_buffer_internal_1 (obuf);
2314 insert_from_buffer (bp, b, e - b, 0);
2315 return Qnil;
2318 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2319 6, 6, 0,
2320 "Compare two substrings of two buffers; return result as number.\n\
2321 the value is -N if first string is less after N-1 chars,\n\
2322 +N if first string is greater after N-1 chars, or 0 if strings match.\n\
2323 Each substring is represented as three arguments: BUFFER, START and END.\n\
2324 That makes six args in all, three for each substring.\n\n\
2325 The value of `case-fold-search' in the current buffer\n\
2326 determines whether case is significant or ignored.")
2327 (buffer1, start1, end1, buffer2, start2, end2)
2328 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2330 register int begp1, endp1, begp2, endp2, temp;
2331 register struct buffer *bp1, *bp2;
2332 register Lisp_Object *trt
2333 = (!NILP (current_buffer->case_fold_search)
2334 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents : 0);
2335 int chars = 0;
2336 int i1, i2, i1_byte, i2_byte;
2338 /* Find the first buffer and its substring. */
2340 if (NILP (buffer1))
2341 bp1 = current_buffer;
2342 else
2344 Lisp_Object buf1;
2345 buf1 = Fget_buffer (buffer1);
2346 if (NILP (buf1))
2347 nsberror (buffer1);
2348 bp1 = XBUFFER (buf1);
2349 if (NILP (bp1->name))
2350 error ("Selecting deleted buffer");
2353 if (NILP (start1))
2354 begp1 = BUF_BEGV (bp1);
2355 else
2357 CHECK_NUMBER_COERCE_MARKER (start1, 1);
2358 begp1 = XINT (start1);
2360 if (NILP (end1))
2361 endp1 = BUF_ZV (bp1);
2362 else
2364 CHECK_NUMBER_COERCE_MARKER (end1, 2);
2365 endp1 = XINT (end1);
2368 if (begp1 > endp1)
2369 temp = begp1, begp1 = endp1, endp1 = temp;
2371 if (!(BUF_BEGV (bp1) <= begp1
2372 && begp1 <= endp1
2373 && endp1 <= BUF_ZV (bp1)))
2374 args_out_of_range (start1, end1);
2376 /* Likewise for second substring. */
2378 if (NILP (buffer2))
2379 bp2 = current_buffer;
2380 else
2382 Lisp_Object buf2;
2383 buf2 = Fget_buffer (buffer2);
2384 if (NILP (buf2))
2385 nsberror (buffer2);
2386 bp2 = XBUFFER (buf2);
2387 if (NILP (bp2->name))
2388 error ("Selecting deleted buffer");
2391 if (NILP (start2))
2392 begp2 = BUF_BEGV (bp2);
2393 else
2395 CHECK_NUMBER_COERCE_MARKER (start2, 4);
2396 begp2 = XINT (start2);
2398 if (NILP (end2))
2399 endp2 = BUF_ZV (bp2);
2400 else
2402 CHECK_NUMBER_COERCE_MARKER (end2, 5);
2403 endp2 = XINT (end2);
2406 if (begp2 > endp2)
2407 temp = begp2, begp2 = endp2, endp2 = temp;
2409 if (!(BUF_BEGV (bp2) <= begp2
2410 && begp2 <= endp2
2411 && endp2 <= BUF_ZV (bp2)))
2412 args_out_of_range (start2, end2);
2414 i1 = begp1;
2415 i2 = begp2;
2416 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2417 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2419 while (i1 < endp1 && i2 < endp2)
2421 /* When we find a mismatch, we must compare the
2422 characters, not just the bytes. */
2423 int c1, c2;
2425 if (! NILP (bp1->enable_multibyte_characters))
2427 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2428 BUF_INC_POS (bp1, i1_byte);
2429 i1++;
2431 else
2433 c1 = BUF_FETCH_BYTE (bp1, i1);
2434 c1 = unibyte_char_to_multibyte (c1);
2435 i1++;
2438 if (! NILP (bp2->enable_multibyte_characters))
2440 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2441 BUF_INC_POS (bp2, i2_byte);
2442 i2++;
2444 else
2446 c2 = BUF_FETCH_BYTE (bp2, i2);
2447 c2 = unibyte_char_to_multibyte (c2);
2448 i2++;
2451 if (trt)
2453 c1 = XINT (trt[c1]);
2454 c2 = XINT (trt[c2]);
2456 if (c1 < c2)
2457 return make_number (- 1 - chars);
2458 if (c1 > c2)
2459 return make_number (chars + 1);
2461 chars++;
2464 /* The strings match as far as they go.
2465 If one is shorter, that one is less. */
2466 if (chars < endp1 - begp1)
2467 return make_number (chars + 1);
2468 else if (chars < endp2 - begp2)
2469 return make_number (- chars - 1);
2471 /* Same length too => they are equal. */
2472 return make_number (0);
2475 static Lisp_Object
2476 subst_char_in_region_unwind (arg)
2477 Lisp_Object arg;
2479 return current_buffer->undo_list = arg;
2482 static Lisp_Object
2483 subst_char_in_region_unwind_1 (arg)
2484 Lisp_Object arg;
2486 return current_buffer->filename = arg;
2489 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2490 Ssubst_char_in_region, 4, 5, 0,
2491 "From START to END, replace FROMCHAR with TOCHAR each time it occurs.\n\
2492 If optional arg NOUNDO is non-nil, don't record this change for undo\n\
2493 and don't mark the buffer as really changed.\n\
2494 Both characters must have the same length of multi-byte form.")
2495 (start, end, fromchar, tochar, noundo)
2496 Lisp_Object start, end, fromchar, tochar, noundo;
2498 register int pos, pos_byte, stop, i, len, end_byte;
2499 int changed = 0;
2500 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2501 unsigned char *p;
2502 int count = specpdl_ptr - specpdl;
2503 #define COMBINING_NO 0
2504 #define COMBINING_BEFORE 1
2505 #define COMBINING_AFTER 2
2506 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2507 int maybe_byte_combining = COMBINING_NO;
2508 int last_changed = 0;
2509 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
2511 validate_region (&start, &end);
2512 CHECK_NUMBER (fromchar, 2);
2513 CHECK_NUMBER (tochar, 3);
2515 if (multibyte_p)
2517 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2518 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2519 error ("Characters in subst-char-in-region have different byte-lengths");
2520 if (!ASCII_BYTE_P (*tostr))
2522 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2523 complete multibyte character, it may be combined with the
2524 after bytes. If it is in the range 0xA0..0xFF, it may be
2525 combined with the before and after bytes. */
2526 if (!CHAR_HEAD_P (*tostr))
2527 maybe_byte_combining = COMBINING_BOTH;
2528 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2529 maybe_byte_combining = COMBINING_AFTER;
2532 else
2534 len = 1;
2535 fromstr[0] = XFASTINT (fromchar);
2536 tostr[0] = XFASTINT (tochar);
2539 pos = XINT (start);
2540 pos_byte = CHAR_TO_BYTE (pos);
2541 stop = CHAR_TO_BYTE (XINT (end));
2542 end_byte = stop;
2544 /* If we don't want undo, turn off putting stuff on the list.
2545 That's faster than getting rid of things,
2546 and it prevents even the entry for a first change.
2547 Also inhibit locking the file. */
2548 if (!NILP (noundo))
2550 record_unwind_protect (subst_char_in_region_unwind,
2551 current_buffer->undo_list);
2552 current_buffer->undo_list = Qt;
2553 /* Don't do file-locking. */
2554 record_unwind_protect (subst_char_in_region_unwind_1,
2555 current_buffer->filename);
2556 current_buffer->filename = Qnil;
2559 if (pos_byte < GPT_BYTE)
2560 stop = min (stop, GPT_BYTE);
2561 while (1)
2563 int pos_byte_next = pos_byte;
2565 if (pos_byte >= stop)
2567 if (pos_byte >= end_byte) break;
2568 stop = end_byte;
2570 p = BYTE_POS_ADDR (pos_byte);
2571 if (multibyte_p)
2572 INC_POS (pos_byte_next);
2573 else
2574 ++pos_byte_next;
2575 if (pos_byte_next - pos_byte == len
2576 && p[0] == fromstr[0]
2577 && (len == 1
2578 || (p[1] == fromstr[1]
2579 && (len == 2 || (p[2] == fromstr[2]
2580 && (len == 3 || p[3] == fromstr[3]))))))
2582 if (! changed)
2584 changed = pos;
2585 modify_region (current_buffer, changed, XINT (end));
2587 if (! NILP (noundo))
2589 if (MODIFF - 1 == SAVE_MODIFF)
2590 SAVE_MODIFF++;
2591 if (MODIFF - 1 == current_buffer->auto_save_modified)
2592 current_buffer->auto_save_modified++;
2596 /* Take care of the case where the new character
2597 combines with neighboring bytes. */
2598 if (maybe_byte_combining
2599 && (maybe_byte_combining == COMBINING_AFTER
2600 ? (pos_byte_next < Z_BYTE
2601 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2602 : ((pos_byte_next < Z_BYTE
2603 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2604 || (pos_byte > BEG_BYTE
2605 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2607 Lisp_Object tem, string;
2609 struct gcpro gcpro1;
2611 tem = current_buffer->undo_list;
2612 GCPRO1 (tem);
2614 /* Make a multibyte string containing this single character. */
2615 string = make_multibyte_string (tostr, 1, len);
2616 /* replace_range is less efficient, because it moves the gap,
2617 but it handles combining correctly. */
2618 replace_range (pos, pos + 1, string,
2619 0, 0, 1);
2620 pos_byte_next = CHAR_TO_BYTE (pos);
2621 if (pos_byte_next > pos_byte)
2622 /* Before combining happened. We should not increment
2623 POS. So, to cancel the later increment of POS,
2624 decrease it now. */
2625 pos--;
2626 else
2627 INC_POS (pos_byte_next);
2629 if (! NILP (noundo))
2630 current_buffer->undo_list = tem;
2632 UNGCPRO;
2634 else
2636 if (NILP (noundo))
2637 record_change (pos, 1);
2638 for (i = 0; i < len; i++) *p++ = tostr[i];
2640 last_changed = pos + 1;
2642 pos_byte = pos_byte_next;
2643 pos++;
2646 if (changed)
2648 signal_after_change (changed,
2649 last_changed - changed, last_changed - changed);
2650 update_compositions (changed, last_changed, CHECK_ALL);
2653 unbind_to (count, Qnil);
2654 return Qnil;
2657 DEFUN ("translate-region", Ftranslate_region, Stranslate_region, 3, 3, 0,
2658 "From START to END, translate characters according to TABLE.\n\
2659 TABLE is a string; the Nth character in it is the mapping\n\
2660 for the character with code N.\n\
2661 This function does not alter multibyte characters.\n\
2662 It returns the number of characters changed.")
2663 (start, end, table)
2664 Lisp_Object start;
2665 Lisp_Object end;
2666 register Lisp_Object table;
2668 register int pos_byte, stop; /* Limits of the region. */
2669 register unsigned char *tt; /* Trans table. */
2670 register int nc; /* New character. */
2671 int cnt; /* Number of changes made. */
2672 int size; /* Size of translate table. */
2673 int pos;
2674 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
2676 validate_region (&start, &end);
2677 CHECK_STRING (table, 2);
2679 size = STRING_BYTES (XSTRING (table));
2680 tt = XSTRING (table)->data;
2682 pos_byte = CHAR_TO_BYTE (XINT (start));
2683 stop = CHAR_TO_BYTE (XINT (end));
2684 modify_region (current_buffer, XINT (start), XINT (end));
2685 pos = XINT (start);
2687 cnt = 0;
2688 for (; pos_byte < stop; )
2690 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
2691 int len;
2692 int oc;
2693 int pos_byte_next;
2695 if (multibyte)
2696 oc = STRING_CHAR_AND_LENGTH (p, stop - pos_byte, len);
2697 else
2698 oc = *p, len = 1;
2699 pos_byte_next = pos_byte + len;
2700 if (oc < size && len == 1)
2702 nc = tt[oc];
2703 if (nc != oc)
2705 /* Take care of the case where the new character
2706 combines with neighboring bytes. */
2707 if (!ASCII_BYTE_P (nc)
2708 && (CHAR_HEAD_P (nc)
2709 ? ! CHAR_HEAD_P (FETCH_BYTE (pos_byte + 1))
2710 : (pos_byte > BEG_BYTE
2711 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1)))))
2713 Lisp_Object string;
2715 string = make_multibyte_string (tt + oc, 1, 1);
2716 /* This is less efficient, because it moves the gap,
2717 but it handles combining correctly. */
2718 replace_range (pos, pos + 1, string,
2719 1, 0, 1);
2720 pos_byte_next = CHAR_TO_BYTE (pos);
2721 if (pos_byte_next > pos_byte)
2722 /* Before combining happened. We should not
2723 increment POS. So, to cancel the later
2724 increment of POS, we decrease it now. */
2725 pos--;
2726 else
2727 INC_POS (pos_byte_next);
2729 else
2731 record_change (pos, 1);
2732 *p = nc;
2733 signal_after_change (pos, 1, 1);
2734 update_compositions (pos, pos + 1, CHECK_BORDER);
2736 ++cnt;
2739 pos_byte = pos_byte_next;
2740 pos++;
2743 return make_number (cnt);
2746 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
2747 "Delete the text between point and mark.\n\
2748 When called from a program, expects two arguments,\n\
2749 positions (integers or markers) specifying the stretch to be deleted.")
2750 (start, end)
2751 Lisp_Object start, end;
2753 validate_region (&start, &end);
2754 del_range (XINT (start), XINT (end));
2755 return Qnil;
2758 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
2759 Sdelete_and_extract_region, 2, 2, 0,
2760 "Delete the text between START and END and return it.")
2761 (start, end)
2762 Lisp_Object start, end;
2764 validate_region (&start, &end);
2765 return del_range_1 (XINT (start), XINT (end), 1, 1);
2768 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
2769 "Remove restrictions (narrowing) from current buffer.\n\
2770 This allows the buffer's full text to be seen and edited.")
2773 if (BEG != BEGV || Z != ZV)
2774 current_buffer->clip_changed = 1;
2775 BEGV = BEG;
2776 BEGV_BYTE = BEG_BYTE;
2777 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
2778 /* Changing the buffer bounds invalidates any recorded current column. */
2779 invalidate_current_column ();
2780 return Qnil;
2783 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
2784 "Restrict editing in this buffer to the current region.\n\
2785 The rest of the text becomes temporarily invisible and untouchable\n\
2786 but is not deleted; if you save the buffer in a file, the invisible\n\
2787 text is included in the file. \\[widen] makes all visible again.\n\
2788 See also `save-restriction'.\n\
2790 When calling from a program, pass two arguments; positions (integers\n\
2791 or markers) bounding the text that should remain visible.")
2792 (start, end)
2793 register Lisp_Object start, end;
2795 CHECK_NUMBER_COERCE_MARKER (start, 0);
2796 CHECK_NUMBER_COERCE_MARKER (end, 1);
2798 if (XINT (start) > XINT (end))
2800 Lisp_Object tem;
2801 tem = start; start = end; end = tem;
2804 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
2805 args_out_of_range (start, end);
2807 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
2808 current_buffer->clip_changed = 1;
2810 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2811 SET_BUF_ZV (current_buffer, XFASTINT (end));
2812 if (PT < XFASTINT (start))
2813 SET_PT (XFASTINT (start));
2814 if (PT > XFASTINT (end))
2815 SET_PT (XFASTINT (end));
2816 /* Changing the buffer bounds invalidates any recorded current column. */
2817 invalidate_current_column ();
2818 return Qnil;
2821 Lisp_Object
2822 save_restriction_save ()
2824 if (BEGV == BEG && ZV == Z)
2825 /* The common case that the buffer isn't narrowed.
2826 We return just the buffer object, which save_restriction_restore
2827 recognizes as meaning `no restriction'. */
2828 return Fcurrent_buffer ();
2829 else
2830 /* We have to save a restriction, so return a pair of markers, one
2831 for the beginning and one for the end. */
2833 Lisp_Object beg, end;
2835 beg = buildmark (BEGV, BEGV_BYTE);
2836 end = buildmark (ZV, ZV_BYTE);
2838 /* END must move forward if text is inserted at its exact location. */
2839 XMARKER(end)->insertion_type = 1;
2841 return Fcons (beg, end);
2845 Lisp_Object
2846 save_restriction_restore (data)
2847 Lisp_Object data;
2849 if (CONSP (data))
2850 /* A pair of marks bounding a saved restriction. */
2852 struct Lisp_Marker *beg = XMARKER (XCAR (data));
2853 struct Lisp_Marker *end = XMARKER (XCDR (data));
2854 struct buffer *buf = beg->buffer; /* END should have the same buffer. */
2856 if (beg->charpos != BUF_BEGV(buf) || end->charpos != BUF_ZV(buf))
2857 /* The restriction has changed from the saved one, so restore
2858 the saved restriction. */
2860 int pt = BUF_PT (buf);
2862 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
2863 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
2865 if (pt < beg->charpos || pt > end->charpos)
2866 /* The point is outside the new visible range, move it inside. */
2867 SET_BUF_PT_BOTH (buf,
2868 clip_to_bounds (beg->charpos, pt, end->charpos),
2869 clip_to_bounds (beg->bytepos, BUF_PT_BYTE(buf),
2870 end->bytepos));
2872 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2875 else
2876 /* A buffer, which means that there was no old restriction. */
2878 struct buffer *buf = XBUFFER (data);
2880 if (BUF_BEGV(buf) != BUF_BEG(buf) || BUF_ZV(buf) != BUF_Z(buf))
2881 /* The buffer has been narrowed, get rid of the narrowing. */
2883 SET_BUF_BEGV_BOTH (buf, BUF_BEG(buf), BUF_BEG_BYTE(buf));
2884 SET_BUF_ZV_BOTH (buf, BUF_Z(buf), BUF_Z_BYTE(buf));
2886 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2890 return Qnil;
2893 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
2894 "Execute BODY, saving and restoring current buffer's restrictions.\n\
2895 The buffer's restrictions make parts of the beginning and end invisible.\n\
2896 \(They are set up with `narrow-to-region' and eliminated with `widen'.)\n\
2897 This special form, `save-restriction', saves the current buffer's restrictions\n\
2898 when it is entered, and restores them when it is exited.\n\
2899 So any `narrow-to-region' within BODY lasts only until the end of the form.\n\
2900 The old restrictions settings are restored\n\
2901 even in case of abnormal exit (throw or error).\n\
2903 The value returned is the value of the last form in BODY.\n\
2905 Note: if you are using both `save-excursion' and `save-restriction',\n\
2906 use `save-excursion' outermost:\n\
2907 (save-excursion (save-restriction ...))")
2908 (body)
2909 Lisp_Object body;
2911 register Lisp_Object val;
2912 int count = specpdl_ptr - specpdl;
2914 record_unwind_protect (save_restriction_restore, save_restriction_save ());
2915 val = Fprogn (body);
2916 return unbind_to (count, val);
2919 /* Buffer for the most recent text displayed by Fmessage_box. */
2920 static char *message_text;
2922 /* Allocated length of that buffer. */
2923 static int message_length;
2925 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
2926 "Print a one-line message at the bottom of the screen.\n\
2927 The first argument is a format control string, and the rest are data\n\
2928 to be formatted under control of the string. See `format' for details.\n\
2930 If the first argument is nil, clear any existing message; let the\n\
2931 minibuffer contents show.")
2932 (nargs, args)
2933 int nargs;
2934 Lisp_Object *args;
2936 if (NILP (args[0]))
2938 message (0);
2939 return Qnil;
2941 else
2943 register Lisp_Object val;
2944 val = Fformat (nargs, args);
2945 message3 (val, STRING_BYTES (XSTRING (val)), STRING_MULTIBYTE (val));
2946 return val;
2950 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
2951 "Display a message, in a dialog box if possible.\n\
2952 If a dialog box is not available, use the echo area.\n\
2953 The first argument is a format control string, and the rest are data\n\
2954 to be formatted under control of the string. See `format' for details.\n\
2956 If the first argument is nil, clear any existing message; let the\n\
2957 minibuffer contents show.")
2958 (nargs, args)
2959 int nargs;
2960 Lisp_Object *args;
2962 if (NILP (args[0]))
2964 message (0);
2965 return Qnil;
2967 else
2969 register Lisp_Object val;
2970 val = Fformat (nargs, args);
2971 #ifdef HAVE_MENUS
2972 /* The MS-DOS frames support popup menus even though they are
2973 not FRAME_WINDOW_P. */
2974 if (FRAME_WINDOW_P (XFRAME (selected_frame))
2975 || FRAME_MSDOS_P (XFRAME (selected_frame)))
2977 Lisp_Object pane, menu, obj;
2978 struct gcpro gcpro1;
2979 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
2980 GCPRO1 (pane);
2981 menu = Fcons (val, pane);
2982 obj = Fx_popup_dialog (Qt, menu);
2983 UNGCPRO;
2984 return val;
2986 #endif /* HAVE_MENUS */
2987 /* Copy the data so that it won't move when we GC. */
2988 if (! message_text)
2990 message_text = (char *)xmalloc (80);
2991 message_length = 80;
2993 if (STRING_BYTES (XSTRING (val)) > message_length)
2995 message_length = STRING_BYTES (XSTRING (val));
2996 message_text = (char *)xrealloc (message_text, message_length);
2998 bcopy (XSTRING (val)->data, message_text, STRING_BYTES (XSTRING (val)));
2999 message2 (message_text, STRING_BYTES (XSTRING (val)),
3000 STRING_MULTIBYTE (val));
3001 return val;
3004 #ifdef HAVE_MENUS
3005 extern Lisp_Object last_nonmenu_event;
3006 #endif
3008 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3009 "Display a message in a dialog box or in the echo area.\n\
3010 If this command was invoked with the mouse, use a dialog box if\n\
3011 `use-dialog-box' is non-nil.\n\
3012 Otherwise, use the echo area.\n\
3013 The first argument is a format control string, and the rest are data\n\
3014 to be formatted under control of the string. See `format' for details.\n\
3016 If the first argument is nil, clear any existing message; let the\n\
3017 minibuffer contents show.")
3018 (nargs, args)
3019 int nargs;
3020 Lisp_Object *args;
3022 #ifdef HAVE_MENUS
3023 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3024 && use_dialog_box)
3025 return Fmessage_box (nargs, args);
3026 #endif
3027 return Fmessage (nargs, args);
3030 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3031 "Return the string currently displayed in the echo area, or nil if none.")
3034 return current_message ();
3038 DEFUN ("propertize", Fpropertize, Spropertize, 3, MANY, 0,
3039 "Return a copy of STRING with text properties added.\n\
3040 First argument is the string to copy.\n\
3041 Remaining arguments form a sequence of PROPERTY VALUE pairs for text\n\
3042 properties to add to the result ")
3043 (nargs, args)
3044 int nargs;
3045 Lisp_Object *args;
3047 Lisp_Object properties, string;
3048 struct gcpro gcpro1, gcpro2;
3049 int i;
3051 /* Number of args must be odd. */
3052 if ((nargs & 1) == 0 || nargs < 3)
3053 error ("Wrong number of arguments");
3055 properties = string = Qnil;
3056 GCPRO2 (properties, string);
3058 /* First argument must be a string. */
3059 CHECK_STRING (args[0], 0);
3060 string = Fcopy_sequence (args[0]);
3062 for (i = 1; i < nargs; i += 2)
3064 CHECK_SYMBOL (args[i], i);
3065 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3068 Fadd_text_properties (make_number (0),
3069 make_number (XSTRING (string)->size),
3070 properties, string);
3071 RETURN_UNGCPRO (string);
3075 /* Number of bytes that STRING will occupy when put into the result.
3076 MULTIBYTE is nonzero if the result should be multibyte. */
3078 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3079 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3080 ? count_size_as_multibyte (XSTRING (STRING)->data, \
3081 STRING_BYTES (XSTRING (STRING))) \
3082 : STRING_BYTES (XSTRING (STRING)))
3084 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3085 "Format a string out of a control-string and arguments.\n\
3086 The first argument is a control string.\n\
3087 The other arguments are substituted into it to make the result, a string.\n\
3088 It may contain %-sequences meaning to substitute the next argument.\n\
3089 %s means print a string argument. Actually, prints any object, with `princ'.\n\
3090 %d means print as number in decimal (%o octal, %x hex).\n\
3091 %X is like %x, but uses upper case.\n\
3092 %e means print a number in exponential notation.\n\
3093 %f means print a number in decimal-point notation.\n\
3094 %g means print a number in exponential notation\n\
3095 or decimal-point notation, whichever uses fewer characters.\n\
3096 %c means print a number as a single character.\n\
3097 %S means print any object as an s-expression (using `prin1').\n\
3098 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.\n\
3099 Use %% to put a single % into the output.")
3100 (nargs, args)
3101 int nargs;
3102 register Lisp_Object *args;
3104 register int n; /* The number of the next arg to substitute */
3105 register int total; /* An estimate of the final length */
3106 char *buf, *p;
3107 register unsigned char *format, *end;
3108 int nchars;
3109 /* Nonzero if the output should be a multibyte string,
3110 which is true if any of the inputs is one. */
3111 int multibyte = 0;
3112 /* When we make a multibyte string, we must pay attention to the
3113 byte combining problem, i.e., a byte may be combined with a
3114 multibyte charcter of the previous string. This flag tells if we
3115 must consider such a situation or not. */
3116 int maybe_combine_byte;
3117 unsigned char *this_format;
3118 int longest_format;
3119 Lisp_Object val;
3120 struct info
3122 int start, end;
3123 } *info = 0;
3125 /* It should not be necessary to GCPRO ARGS, because
3126 the caller in the interpreter should take care of that. */
3128 /* Try to determine whether the result should be multibyte.
3129 This is not always right; sometimes the result needs to be multibyte
3130 because of an object that we will pass through prin1,
3131 and in that case, we won't know it here. */
3132 for (n = 0; n < nargs; n++)
3133 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3134 multibyte = 1;
3136 CHECK_STRING (args[0], 0);
3138 /* If we start out planning a unibyte result,
3139 and later find it has to be multibyte, we jump back to retry. */
3140 retry:
3142 format = XSTRING (args[0])->data;
3143 end = format + STRING_BYTES (XSTRING (args[0]));
3144 longest_format = 0;
3146 /* Make room in result for all the non-%-codes in the control string. */
3147 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]);
3149 /* Add to TOTAL enough space to hold the converted arguments. */
3151 n = 0;
3152 while (format != end)
3153 if (*format++ == '%')
3155 int thissize = 0;
3156 unsigned char *this_format_start = format - 1;
3157 int field_width, precision;
3159 /* General format specifications look like
3161 '%' [flags] [field-width] [precision] format
3163 where
3165 flags ::= [#-* 0]+
3166 field-width ::= [0-9]+
3167 precision ::= '.' [0-9]*
3169 If a field-width is specified, it specifies to which width
3170 the output should be padded with blanks, iff the output
3171 string is shorter than field-width.
3173 if precision is specified, it specifies the number of
3174 digits to print after the '.' for floats, or the max.
3175 number of chars to print from a string. */
3177 precision = field_width = 0;
3179 while (index ("-*# 0", *format))
3180 ++format;
3182 if (*format >= '0' && *format <= '9')
3184 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3185 field_width = 10 * field_width + *format - '0';
3188 if (*format == '.')
3190 ++format;
3191 for (precision = 0; *format >= '0' && *format <= '9'; ++format)
3192 precision = 10 * precision + *format - '0';
3195 if (format - this_format_start + 1 > longest_format)
3196 longest_format = format - this_format_start + 1;
3198 if (format == end)
3199 error ("Format string ends in middle of format specifier");
3200 if (*format == '%')
3201 format++;
3202 else if (++n >= nargs)
3203 error ("Not enough arguments for format string");
3204 else if (*format == 'S')
3206 /* For `S', prin1 the argument and then treat like a string. */
3207 register Lisp_Object tem;
3208 tem = Fprin1_to_string (args[n], Qnil);
3209 if (STRING_MULTIBYTE (tem) && ! multibyte)
3211 multibyte = 1;
3212 goto retry;
3214 args[n] = tem;
3215 goto string;
3217 else if (SYMBOLP (args[n]))
3219 /* Use a temp var to avoid problems when ENABLE_CHECKING
3220 is turned on. */
3221 struct Lisp_String *t = XSYMBOL (args[n])->name;
3222 XSETSTRING (args[n], t);
3223 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3225 multibyte = 1;
3226 goto retry;
3228 goto string;
3230 else if (STRINGP (args[n]))
3232 string:
3233 if (*format != 's' && *format != 'S')
3234 error ("Format specifier doesn't match argument type");
3235 thissize = CONVERTED_BYTE_SIZE (multibyte, args[n]);
3237 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3238 else if (INTEGERP (args[n]) && *format != 's')
3240 /* The following loop assumes the Lisp type indicates
3241 the proper way to pass the argument.
3242 So make sure we have a flonum if the argument should
3243 be a double. */
3244 if (*format == 'e' || *format == 'f' || *format == 'g')
3245 args[n] = Ffloat (args[n]);
3246 else
3247 if (*format != 'd' && *format != 'o' && *format != 'x'
3248 && *format != 'i' && *format != 'X' && *format != 'c')
3249 error ("Invalid format operation %%%c", *format);
3251 thissize = 30;
3252 if (*format == 'c'
3253 && (! SINGLE_BYTE_CHAR_P (XINT (args[n]))
3254 || XINT (args[n]) == 0))
3256 if (! multibyte)
3258 multibyte = 1;
3259 goto retry;
3261 args[n] = Fchar_to_string (args[n]);
3262 thissize = STRING_BYTES (XSTRING (args[n]));
3265 else if (FLOATP (args[n]) && *format != 's')
3267 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3268 args[n] = Ftruncate (args[n], Qnil);
3270 /* Note that we're using sprintf to print floats,
3271 so we have to take into account what that function
3272 prints. */
3273 thissize = 200 + precision;
3275 else
3277 /* Anything but a string, convert to a string using princ. */
3278 register Lisp_Object tem;
3279 tem = Fprin1_to_string (args[n], Qt);
3280 if (STRING_MULTIBYTE (tem) & ! multibyte)
3282 multibyte = 1;
3283 goto retry;
3285 args[n] = tem;
3286 goto string;
3289 thissize = max (field_width, thissize);
3290 total += thissize + 4;
3293 /* Now we can no longer jump to retry.
3294 TOTAL and LONGEST_FORMAT are known for certain. */
3296 this_format = (unsigned char *) alloca (longest_format + 1);
3298 /* Allocate the space for the result.
3299 Note that TOTAL is an overestimate. */
3300 if (total < 1000)
3301 buf = (char *) alloca (total + 1);
3302 else
3303 buf = (char *) xmalloc (total + 1);
3305 p = buf;
3306 nchars = 0;
3307 n = 0;
3309 /* Scan the format and store result in BUF. */
3310 format = XSTRING (args[0])->data;
3311 maybe_combine_byte = 0;
3312 while (format != end)
3314 if (*format == '%')
3316 int minlen;
3317 int negative = 0;
3318 unsigned char *this_format_start = format;
3320 format++;
3322 /* Process a numeric arg and skip it. */
3323 minlen = atoi (format);
3324 if (minlen < 0)
3325 minlen = - minlen, negative = 1;
3327 while ((*format >= '0' && *format <= '9')
3328 || *format == '-' || *format == ' ' || *format == '.')
3329 format++;
3331 if (*format++ == '%')
3333 *p++ = '%';
3334 nchars++;
3335 continue;
3338 ++n;
3340 if (STRINGP (args[n]))
3342 int padding, nbytes, start, end;
3343 int width = lisp_string_width (args[n], -1, NULL, NULL);
3345 /* If spec requires it, pad on right with spaces. */
3346 padding = minlen - width;
3347 if (! negative)
3348 while (padding-- > 0)
3350 *p++ = ' ';
3351 ++nchars;
3354 start = nchars;
3356 if (p > buf
3357 && multibyte
3358 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3359 && STRING_MULTIBYTE (args[n])
3360 && !CHAR_HEAD_P (XSTRING (args[n])->data[0]))
3361 maybe_combine_byte = 1;
3362 nbytes = copy_text (XSTRING (args[n])->data, p,
3363 STRING_BYTES (XSTRING (args[n])),
3364 STRING_MULTIBYTE (args[n]), multibyte);
3365 p += nbytes;
3366 nchars += XSTRING (args[n])->size;
3367 end = nchars;
3369 if (negative)
3370 while (padding-- > 0)
3372 *p++ = ' ';
3373 nchars++;
3376 /* If this argument has text properties, record where
3377 in the result string it appears. */
3378 if (XSTRING (args[n])->intervals)
3380 if (!info)
3382 int nbytes = nargs * sizeof *info;
3383 info = (struct info *) alloca (nbytes);
3384 bzero (info, nbytes);
3387 info[n].start = start;
3388 info[n].end = end;
3391 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3393 int this_nchars;
3395 bcopy (this_format_start, this_format,
3396 format - this_format_start);
3397 this_format[format - this_format_start] = 0;
3399 if (INTEGERP (args[n]))
3400 sprintf (p, this_format, XINT (args[n]));
3401 else
3402 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3404 if (p > buf
3405 && multibyte
3406 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3407 && !CHAR_HEAD_P (*((unsigned char *) p)))
3408 maybe_combine_byte = 1;
3409 this_nchars = strlen (p);
3410 if (multibyte)
3411 p += str_to_multibyte (p, buf + total - p, this_nchars);
3412 else
3413 p += this_nchars;
3414 nchars += this_nchars;
3417 else if (STRING_MULTIBYTE (args[0]))
3419 /* Copy a whole multibyte character. */
3420 if (p > buf
3421 && multibyte
3422 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3423 && !CHAR_HEAD_P (*format))
3424 maybe_combine_byte = 1;
3425 *p++ = *format++;
3426 while (! CHAR_HEAD_P (*format)) *p++ = *format++;
3427 nchars++;
3429 else if (multibyte)
3431 /* Convert a single-byte character to multibyte. */
3432 int len = copy_text (format, p, 1, 0, 1);
3434 p += len;
3435 format++;
3436 nchars++;
3438 else
3439 *p++ = *format++, nchars++;
3442 if (p > buf + total + 1)
3443 abort ();
3445 if (maybe_combine_byte)
3446 nchars = multibyte_chars_in_text (buf, p - buf);
3447 val = make_specified_string (buf, nchars, p - buf, multibyte);
3449 /* If we allocated BUF with malloc, free it too. */
3450 if (total >= 1000)
3451 xfree (buf);
3453 /* If the format string has text properties, or any of the string
3454 arguments has text properties, set up text properties of the
3455 result string. */
3457 if (XSTRING (args[0])->intervals || info)
3459 Lisp_Object len, new_len, props;
3460 struct gcpro gcpro1;
3462 /* Add text properties from the format string. */
3463 len = make_number (XSTRING (args[0])->size);
3464 props = text_property_list (args[0], make_number (0), len, Qnil);
3465 GCPRO1 (props);
3467 if (CONSP (props))
3469 new_len = make_number (XSTRING (val)->size);
3470 extend_property_ranges (props, len, new_len);
3471 add_text_properties_from_list (val, props, make_number (0));
3474 /* Add text properties from arguments. */
3475 if (info)
3476 for (n = 1; n < nargs; ++n)
3477 if (info[n].end)
3479 len = make_number (XSTRING (args[n])->size);
3480 new_len = make_number (info[n].end - info[n].start);
3481 props = text_property_list (args[n], make_number (0), len, Qnil);
3482 extend_property_ranges (props, len, new_len);
3483 /* If successive arguments have properites, be sure that
3484 the value of `composition' property be the copy. */
3485 if (n > 1 && info[n - 1].end)
3486 make_composition_value_copy (props);
3487 add_text_properties_from_list (val, props,
3488 make_number (info[n].start));
3491 UNGCPRO;
3494 return val;
3498 /* VARARGS 1 */
3499 Lisp_Object
3500 #ifdef NO_ARG_ARRAY
3501 format1 (string1, arg0, arg1, arg2, arg3, arg4)
3502 EMACS_INT arg0, arg1, arg2, arg3, arg4;
3503 #else
3504 format1 (string1)
3505 #endif
3506 char *string1;
3508 char buf[100];
3509 #ifdef NO_ARG_ARRAY
3510 EMACS_INT args[5];
3511 args[0] = arg0;
3512 args[1] = arg1;
3513 args[2] = arg2;
3514 args[3] = arg3;
3515 args[4] = arg4;
3516 doprnt (buf, sizeof buf, string1, (char *)0, 5, (char **) args);
3517 #else
3518 doprnt (buf, sizeof buf, string1, (char *)0, 5, &string1 + 1);
3519 #endif
3520 return build_string (buf);
3523 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
3524 "Return t if two characters match, optionally ignoring case.\n\
3525 Both arguments must be characters (i.e. integers).\n\
3526 Case is ignored if `case-fold-search' is non-nil in the current buffer.")
3527 (c1, c2)
3528 register Lisp_Object c1, c2;
3530 int i1, i2;
3531 CHECK_NUMBER (c1, 0);
3532 CHECK_NUMBER (c2, 1);
3534 if (XINT (c1) == XINT (c2))
3535 return Qt;
3536 if (NILP (current_buffer->case_fold_search))
3537 return Qnil;
3539 /* Do these in separate statements,
3540 then compare the variables.
3541 because of the way DOWNCASE uses temp variables. */
3542 i1 = DOWNCASE (XFASTINT (c1));
3543 i2 = DOWNCASE (XFASTINT (c2));
3544 return (i1 == i2 ? Qt : Qnil);
3547 /* Transpose the markers in two regions of the current buffer, and
3548 adjust the ones between them if necessary (i.e.: if the regions
3549 differ in size).
3551 START1, END1 are the character positions of the first region.
3552 START1_BYTE, END1_BYTE are the byte positions.
3553 START2, END2 are the character positions of the second region.
3554 START2_BYTE, END2_BYTE are the byte positions.
3556 Traverses the entire marker list of the buffer to do so, adding an
3557 appropriate amount to some, subtracting from some, and leaving the
3558 rest untouched. Most of this is copied from adjust_markers in insdel.c.
3560 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
3562 static void
3563 transpose_markers (start1, end1, start2, end2,
3564 start1_byte, end1_byte, start2_byte, end2_byte)
3565 register int start1, end1, start2, end2;
3566 register int start1_byte, end1_byte, start2_byte, end2_byte;
3568 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
3569 register Lisp_Object marker;
3571 /* Update point as if it were a marker. */
3572 if (PT < start1)
3574 else if (PT < end1)
3575 TEMP_SET_PT_BOTH (PT + (end2 - end1),
3576 PT_BYTE + (end2_byte - end1_byte));
3577 else if (PT < start2)
3578 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
3579 (PT_BYTE + (end2_byte - start2_byte)
3580 - (end1_byte - start1_byte)));
3581 else if (PT < end2)
3582 TEMP_SET_PT_BOTH (PT - (start2 - start1),
3583 PT_BYTE - (start2_byte - start1_byte));
3585 /* We used to adjust the endpoints here to account for the gap, but that
3586 isn't good enough. Even if we assume the caller has tried to move the
3587 gap out of our way, it might still be at start1 exactly, for example;
3588 and that places it `inside' the interval, for our purposes. The amount
3589 of adjustment is nontrivial if there's a `denormalized' marker whose
3590 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
3591 the dirty work to Fmarker_position, below. */
3593 /* The difference between the region's lengths */
3594 diff = (end2 - start2) - (end1 - start1);
3595 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
3597 /* For shifting each marker in a region by the length of the other
3598 region plus the distance between the regions. */
3599 amt1 = (end2 - start2) + (start2 - end1);
3600 amt2 = (end1 - start1) + (start2 - end1);
3601 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
3602 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
3604 for (marker = BUF_MARKERS (current_buffer); !NILP (marker);
3605 marker = XMARKER (marker)->chain)
3607 mpos = marker_byte_position (marker);
3608 if (mpos >= start1_byte && mpos < end2_byte)
3610 if (mpos < end1_byte)
3611 mpos += amt1_byte;
3612 else if (mpos < start2_byte)
3613 mpos += diff_byte;
3614 else
3615 mpos -= amt2_byte;
3616 XMARKER (marker)->bytepos = mpos;
3618 mpos = XMARKER (marker)->charpos;
3619 if (mpos >= start1 && mpos < end2)
3621 if (mpos < end1)
3622 mpos += amt1;
3623 else if (mpos < start2)
3624 mpos += diff;
3625 else
3626 mpos -= amt2;
3628 XMARKER (marker)->charpos = mpos;
3632 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
3633 "Transpose region START1 to END1 with START2 to END2.\n\
3634 The regions may not be overlapping, because the size of the buffer is\n\
3635 never changed in a transposition.\n\
3637 Optional fifth arg LEAVE_MARKERS, if non-nil, means don't update\n\
3638 any markers that happen to be located in the regions.\n\
3640 Transposing beyond buffer boundaries is an error.")
3641 (startr1, endr1, startr2, endr2, leave_markers)
3642 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
3644 register int start1, end1, start2, end2;
3645 int start1_byte, start2_byte, len1_byte, len2_byte;
3646 int gap, len1, len_mid, len2;
3647 unsigned char *start1_addr, *start2_addr, *temp;
3649 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
3650 cur_intv = BUF_INTERVALS (current_buffer);
3652 validate_region (&startr1, &endr1);
3653 validate_region (&startr2, &endr2);
3655 start1 = XFASTINT (startr1);
3656 end1 = XFASTINT (endr1);
3657 start2 = XFASTINT (startr2);
3658 end2 = XFASTINT (endr2);
3659 gap = GPT;
3661 /* Swap the regions if they're reversed. */
3662 if (start2 < end1)
3664 register int glumph = start1;
3665 start1 = start2;
3666 start2 = glumph;
3667 glumph = end1;
3668 end1 = end2;
3669 end2 = glumph;
3672 len1 = end1 - start1;
3673 len2 = end2 - start2;
3675 if (start2 < end1)
3676 error ("Transposed regions overlap");
3677 else if (start1 == end1 || start2 == end2)
3678 error ("Transposed region has length 0");
3680 /* The possibilities are:
3681 1. Adjacent (contiguous) regions, or separate but equal regions
3682 (no, really equal, in this case!), or
3683 2. Separate regions of unequal size.
3685 The worst case is usually No. 2. It means that (aside from
3686 potential need for getting the gap out of the way), there also
3687 needs to be a shifting of the text between the two regions. So
3688 if they are spread far apart, we are that much slower... sigh. */
3690 /* It must be pointed out that the really studly thing to do would
3691 be not to move the gap at all, but to leave it in place and work
3692 around it if necessary. This would be extremely efficient,
3693 especially considering that people are likely to do
3694 transpositions near where they are working interactively, which
3695 is exactly where the gap would be found. However, such code
3696 would be much harder to write and to read. So, if you are
3697 reading this comment and are feeling squirrely, by all means have
3698 a go! I just didn't feel like doing it, so I will simply move
3699 the gap the minimum distance to get it out of the way, and then
3700 deal with an unbroken array. */
3702 /* Make sure the gap won't interfere, by moving it out of the text
3703 we will operate on. */
3704 if (start1 < gap && gap < end2)
3706 if (gap - start1 < end2 - gap)
3707 move_gap (start1);
3708 else
3709 move_gap (end2);
3712 start1_byte = CHAR_TO_BYTE (start1);
3713 start2_byte = CHAR_TO_BYTE (start2);
3714 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
3715 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
3717 #ifdef BYTE_COMBINING_DEBUG
3718 if (end1 == start2)
3720 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3721 len2_byte, start1, start1_byte)
3722 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3723 len1_byte, end2, start2_byte + len2_byte)
3724 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3725 len1_byte, end2, start2_byte + len2_byte))
3726 abort ();
3728 else
3730 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3731 len2_byte, start1, start1_byte)
3732 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3733 len1_byte, start2, start2_byte)
3734 || count_combining_after (BYTE_POS_ADDR (start2_byte),
3735 len2_byte, end1, start1_byte + len1_byte)
3736 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3737 len1_byte, end2, start2_byte + len2_byte))
3738 abort ();
3740 #endif
3742 /* Hmmm... how about checking to see if the gap is large
3743 enough to use as the temporary storage? That would avoid an
3744 allocation... interesting. Later, don't fool with it now. */
3746 /* Working without memmove, for portability (sigh), so must be
3747 careful of overlapping subsections of the array... */
3749 if (end1 == start2) /* adjacent regions */
3751 modify_region (current_buffer, start1, end2);
3752 record_change (start1, len1 + len2);
3754 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3755 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3756 Fset_text_properties (make_number (start1), make_number (end2),
3757 Qnil, Qnil);
3759 /* First region smaller than second. */
3760 if (len1_byte < len2_byte)
3762 /* We use alloca only if it is small,
3763 because we want to avoid stack overflow. */
3764 if (len2_byte > 20000)
3765 temp = (unsigned char *) xmalloc (len2_byte);
3766 else
3767 temp = (unsigned char *) alloca (len2_byte);
3769 /* Don't precompute these addresses. We have to compute them
3770 at the last minute, because the relocating allocator might
3771 have moved the buffer around during the xmalloc. */
3772 start1_addr = BYTE_POS_ADDR (start1_byte);
3773 start2_addr = BYTE_POS_ADDR (start2_byte);
3775 bcopy (start2_addr, temp, len2_byte);
3776 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
3777 bcopy (temp, start1_addr, len2_byte);
3778 if (len2_byte > 20000)
3779 xfree (temp);
3781 else
3782 /* First region not smaller than second. */
3784 if (len1_byte > 20000)
3785 temp = (unsigned char *) xmalloc (len1_byte);
3786 else
3787 temp = (unsigned char *) alloca (len1_byte);
3788 start1_addr = BYTE_POS_ADDR (start1_byte);
3789 start2_addr = BYTE_POS_ADDR (start2_byte);
3790 bcopy (start1_addr, temp, len1_byte);
3791 bcopy (start2_addr, start1_addr, len2_byte);
3792 bcopy (temp, start1_addr + len2_byte, len1_byte);
3793 if (len1_byte > 20000)
3794 xfree (temp);
3796 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
3797 len1, current_buffer, 0);
3798 graft_intervals_into_buffer (tmp_interval2, start1,
3799 len2, current_buffer, 0);
3800 update_compositions (start1, start1 + len2, CHECK_BORDER);
3801 update_compositions (start1 + len2, end2, CHECK_TAIL);
3803 /* Non-adjacent regions, because end1 != start2, bleagh... */
3804 else
3806 len_mid = start2_byte - (start1_byte + len1_byte);
3808 if (len1_byte == len2_byte)
3809 /* Regions are same size, though, how nice. */
3811 modify_region (current_buffer, start1, end1);
3812 modify_region (current_buffer, start2, end2);
3813 record_change (start1, len1);
3814 record_change (start2, len2);
3815 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3816 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3817 Fset_text_properties (make_number (start1), make_number (end1),
3818 Qnil, Qnil);
3819 Fset_text_properties (make_number (start2), make_number (end2),
3820 Qnil, Qnil);
3822 if (len1_byte > 20000)
3823 temp = (unsigned char *) xmalloc (len1_byte);
3824 else
3825 temp = (unsigned char *) alloca (len1_byte);
3826 start1_addr = BYTE_POS_ADDR (start1_byte);
3827 start2_addr = BYTE_POS_ADDR (start2_byte);
3828 bcopy (start1_addr, temp, len1_byte);
3829 bcopy (start2_addr, start1_addr, len2_byte);
3830 bcopy (temp, start2_addr, len1_byte);
3831 if (len1_byte > 20000)
3832 xfree (temp);
3833 graft_intervals_into_buffer (tmp_interval1, start2,
3834 len1, current_buffer, 0);
3835 graft_intervals_into_buffer (tmp_interval2, start1,
3836 len2, current_buffer, 0);
3839 else if (len1_byte < len2_byte) /* Second region larger than first */
3840 /* Non-adjacent & unequal size, area between must also be shifted. */
3842 modify_region (current_buffer, start1, end2);
3843 record_change (start1, (end2 - start1));
3844 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3845 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3846 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3847 Fset_text_properties (make_number (start1), make_number (end2),
3848 Qnil, Qnil);
3850 /* holds region 2 */
3851 if (len2_byte > 20000)
3852 temp = (unsigned char *) xmalloc (len2_byte);
3853 else
3854 temp = (unsigned char *) alloca (len2_byte);
3855 start1_addr = BYTE_POS_ADDR (start1_byte);
3856 start2_addr = BYTE_POS_ADDR (start2_byte);
3857 bcopy (start2_addr, temp, len2_byte);
3858 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
3859 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3860 bcopy (temp, start1_addr, len2_byte);
3861 if (len2_byte > 20000)
3862 xfree (temp);
3863 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3864 len1, current_buffer, 0);
3865 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3866 len_mid, current_buffer, 0);
3867 graft_intervals_into_buffer (tmp_interval2, start1,
3868 len2, current_buffer, 0);
3870 else
3871 /* Second region smaller than first. */
3873 record_change (start1, (end2 - start1));
3874 modify_region (current_buffer, start1, end2);
3876 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3877 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3878 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3879 Fset_text_properties (make_number (start1), make_number (end2),
3880 Qnil, Qnil);
3882 /* holds region 1 */
3883 if (len1_byte > 20000)
3884 temp = (unsigned char *) xmalloc (len1_byte);
3885 else
3886 temp = (unsigned char *) alloca (len1_byte);
3887 start1_addr = BYTE_POS_ADDR (start1_byte);
3888 start2_addr = BYTE_POS_ADDR (start2_byte);
3889 bcopy (start1_addr, temp, len1_byte);
3890 bcopy (start2_addr, start1_addr, len2_byte);
3891 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3892 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
3893 if (len1_byte > 20000)
3894 xfree (temp);
3895 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3896 len1, current_buffer, 0);
3897 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3898 len_mid, current_buffer, 0);
3899 graft_intervals_into_buffer (tmp_interval2, start1,
3900 len2, current_buffer, 0);
3903 update_compositions (start1, start1 + len2, CHECK_BORDER);
3904 update_compositions (end2 - len1, end2, CHECK_BORDER);
3907 /* When doing multiple transpositions, it might be nice
3908 to optimize this. Perhaps the markers in any one buffer
3909 should be organized in some sorted data tree. */
3910 if (NILP (leave_markers))
3912 transpose_markers (start1, end1, start2, end2,
3913 start1_byte, start1_byte + len1_byte,
3914 start2_byte, start2_byte + len2_byte);
3915 fix_overlays_in_range (start1, end2);
3918 return Qnil;
3922 void
3923 syms_of_editfns ()
3925 environbuf = 0;
3927 Qbuffer_access_fontify_functions
3928 = intern ("buffer-access-fontify-functions");
3929 staticpro (&Qbuffer_access_fontify_functions);
3931 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
3932 "Non-nil means.text motion commands don't notice fields.");
3933 Vinhibit_field_text_motion = Qnil;
3935 DEFVAR_LISP ("buffer-access-fontify-functions",
3936 &Vbuffer_access_fontify_functions,
3937 "List of functions called by `buffer-substring' to fontify if necessary.\n\
3938 Each function is called with two arguments which specify the range\n\
3939 of the buffer being accessed.");
3940 Vbuffer_access_fontify_functions = Qnil;
3943 Lisp_Object obuf;
3944 extern Lisp_Object Vprin1_to_string_buffer;
3945 obuf = Fcurrent_buffer ();
3946 /* Do this here, because init_buffer_once is too early--it won't work. */
3947 Fset_buffer (Vprin1_to_string_buffer);
3948 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
3949 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
3950 Qnil);
3951 Fset_buffer (obuf);
3954 DEFVAR_LISP ("buffer-access-fontified-property",
3955 &Vbuffer_access_fontified_property,
3956 "Property which (if non-nil) indicates text has been fontified.\n\
3957 `buffer-substring' need not call the `buffer-access-fontify-functions'\n\
3958 functions if all the text being accessed has this property.");
3959 Vbuffer_access_fontified_property = Qnil;
3961 DEFVAR_LISP ("system-name", &Vsystem_name,
3962 "The name of the machine Emacs is running on.");
3964 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
3965 "The full name of the user logged in.");
3967 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
3968 "The user's name, taken from environment variables if possible.");
3970 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
3971 "The user's name, based upon the real uid only.");
3973 defsubr (&Spropertize);
3974 defsubr (&Schar_equal);
3975 defsubr (&Sgoto_char);
3976 defsubr (&Sstring_to_char);
3977 defsubr (&Schar_to_string);
3978 defsubr (&Sbuffer_substring);
3979 defsubr (&Sbuffer_substring_no_properties);
3980 defsubr (&Sbuffer_string);
3982 defsubr (&Spoint_marker);
3983 defsubr (&Smark_marker);
3984 defsubr (&Spoint);
3985 defsubr (&Sregion_beginning);
3986 defsubr (&Sregion_end);
3988 staticpro (&Qfield);
3989 Qfield = intern ("field");
3990 staticpro (&Qboundary);
3991 Qboundary = intern ("boundary");
3992 defsubr (&Sfield_beginning);
3993 defsubr (&Sfield_end);
3994 defsubr (&Sfield_string);
3995 defsubr (&Sfield_string_no_properties);
3996 defsubr (&Sdelete_field);
3997 defsubr (&Sconstrain_to_field);
3999 defsubr (&Sline_beginning_position);
4000 defsubr (&Sline_end_position);
4002 /* defsubr (&Smark); */
4003 /* defsubr (&Sset_mark); */
4004 defsubr (&Ssave_excursion);
4005 defsubr (&Ssave_current_buffer);
4007 defsubr (&Sbufsize);
4008 defsubr (&Spoint_max);
4009 defsubr (&Spoint_min);
4010 defsubr (&Spoint_min_marker);
4011 defsubr (&Spoint_max_marker);
4012 defsubr (&Sgap_position);
4013 defsubr (&Sgap_size);
4014 defsubr (&Sposition_bytes);
4015 defsubr (&Sbyte_to_position);
4017 defsubr (&Sbobp);
4018 defsubr (&Seobp);
4019 defsubr (&Sbolp);
4020 defsubr (&Seolp);
4021 defsubr (&Sfollowing_char);
4022 defsubr (&Sprevious_char);
4023 defsubr (&Schar_after);
4024 defsubr (&Schar_before);
4025 defsubr (&Sinsert);
4026 defsubr (&Sinsert_before_markers);
4027 defsubr (&Sinsert_and_inherit);
4028 defsubr (&Sinsert_and_inherit_before_markers);
4029 defsubr (&Sinsert_char);
4031 defsubr (&Suser_login_name);
4032 defsubr (&Suser_real_login_name);
4033 defsubr (&Suser_uid);
4034 defsubr (&Suser_real_uid);
4035 defsubr (&Suser_full_name);
4036 defsubr (&Semacs_pid);
4037 defsubr (&Scurrent_time);
4038 defsubr (&Sformat_time_string);
4039 defsubr (&Sfloat_time);
4040 defsubr (&Sdecode_time);
4041 defsubr (&Sencode_time);
4042 defsubr (&Scurrent_time_string);
4043 defsubr (&Scurrent_time_zone);
4044 defsubr (&Sset_time_zone_rule);
4045 defsubr (&Ssystem_name);
4046 defsubr (&Smessage);
4047 defsubr (&Smessage_box);
4048 defsubr (&Smessage_or_box);
4049 defsubr (&Scurrent_message);
4050 defsubr (&Sformat);
4052 defsubr (&Sinsert_buffer_substring);
4053 defsubr (&Scompare_buffer_substrings);
4054 defsubr (&Ssubst_char_in_region);
4055 defsubr (&Stranslate_region);
4056 defsubr (&Sdelete_region);
4057 defsubr (&Sdelete_and_extract_region);
4058 defsubr (&Swiden);
4059 defsubr (&Snarrow_to_region);
4060 defsubr (&Ssave_restriction);
4061 defsubr (&Stranspose_regions);