(Search and Replace): Add description of
[emacs.git] / src / editfns.c
blob2cf10923b37fafbf5cdf465eef91f0ac6cbefc64
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 #ifdef STDC_HEADERS
47 #include <float.h>
48 #define MAX_10_EXP DBL_MAX_10_EXP
49 #else
50 #define MAX_10_EXP 310
51 #endif
53 #define min(a, b) ((a) < (b) ? (a) : (b))
54 #define max(a, b) ((a) > (b) ? (a) : (b))
56 #ifndef NULL
57 #define NULL 0
58 #endif
60 #ifndef USE_CRT_DLL
61 extern char **environ;
62 #endif
64 extern Lisp_Object make_time P_ ((time_t));
65 extern size_t emacs_strftimeu P_ ((char *, size_t, const char *,
66 const struct tm *, int));
67 static int tm_diff P_ ((struct tm *, struct tm *));
68 static void find_field P_ ((Lisp_Object, Lisp_Object, int *, int *));
69 static void update_buffer_properties P_ ((int, int));
70 static Lisp_Object region_limit P_ ((int));
71 static int lisp_time_argument P_ ((Lisp_Object, time_t *, int *));
72 static size_t emacs_memftimeu P_ ((char *, size_t, const char *,
73 size_t, const struct tm *, int));
74 static void general_insert_function P_ ((void (*) (unsigned char *, int),
75 void (*) (Lisp_Object, int, int, int,
76 int, int),
77 int, int, Lisp_Object *));
78 static Lisp_Object subst_char_in_region_unwind P_ ((Lisp_Object));
79 static Lisp_Object subst_char_in_region_unwind_1 P_ ((Lisp_Object));
80 static void transpose_markers P_ ((int, int, int, int, int, int, int, int));
82 #ifdef HAVE_INDEX
83 extern char *index P_ ((const char *, int));
84 #endif
86 Lisp_Object Vbuffer_access_fontify_functions;
87 Lisp_Object Qbuffer_access_fontify_functions;
88 Lisp_Object Vbuffer_access_fontified_property;
90 Lisp_Object Fuser_full_name P_ ((Lisp_Object));
92 /* Non-nil means don't stop at field boundary in text motion commands. */
94 Lisp_Object Vinhibit_field_text_motion;
96 /* Some static data, and a function to initialize it for each run */
98 Lisp_Object Vsystem_name;
99 Lisp_Object Vuser_real_login_name; /* login name of current user ID */
100 Lisp_Object Vuser_full_name; /* full name of current user */
101 Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
103 /* Symbol for the text property used to mark fields. */
105 Lisp_Object Qfield;
107 /* A special value for Qfield properties. */
109 Lisp_Object Qboundary;
112 void
113 init_editfns ()
115 char *user_name;
116 register unsigned char *p;
117 struct passwd *pw; /* password entry for the current user */
118 Lisp_Object tem;
120 /* Set up system_name even when dumping. */
121 init_system_name ();
123 #ifndef CANNOT_DUMP
124 /* Don't bother with this on initial start when just dumping out */
125 if (!initialized)
126 return;
127 #endif /* not CANNOT_DUMP */
129 pw = (struct passwd *) getpwuid (getuid ());
130 #ifdef MSDOS
131 /* We let the real user name default to "root" because that's quite
132 accurate on MSDOG and because it lets Emacs find the init file.
133 (The DVX libraries override the Djgpp libraries here.) */
134 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
135 #else
136 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
137 #endif
139 /* Get the effective user name, by consulting environment variables,
140 or the effective uid if those are unset. */
141 user_name = (char *) getenv ("LOGNAME");
142 if (!user_name)
143 #ifdef WINDOWSNT
144 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
145 #else /* WINDOWSNT */
146 user_name = (char *) getenv ("USER");
147 #endif /* WINDOWSNT */
148 if (!user_name)
150 pw = (struct passwd *) getpwuid (geteuid ());
151 user_name = (char *) (pw ? pw->pw_name : "unknown");
153 Vuser_login_name = build_string (user_name);
155 /* If the user name claimed in the environment vars differs from
156 the real uid, use the claimed name to find the full name. */
157 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
158 Vuser_full_name = Fuser_full_name (NILP (tem)? make_number (geteuid())
159 : Vuser_login_name);
161 p = (unsigned char *) getenv ("NAME");
162 if (p)
163 Vuser_full_name = build_string (p);
164 else if (NILP (Vuser_full_name))
165 Vuser_full_name = build_string ("unknown");
168 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
169 "Convert arg CHAR to a string containing that character.")
170 (character)
171 Lisp_Object character;
173 int len;
174 unsigned char str[MAX_MULTIBYTE_LENGTH];
176 CHECK_NUMBER (character, 0);
178 len = (SINGLE_BYTE_CHAR_P (XFASTINT (character))
179 ? (*str = (unsigned char)(XFASTINT (character)), 1)
180 : char_to_string (XFASTINT (character), str));
181 return make_string_from_bytes (str, 1, len);
184 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
185 "Convert arg STRING to a character, the first character of that string.\n\
186 A multibyte character is handled correctly.")
187 (string)
188 register Lisp_Object string;
190 register Lisp_Object val;
191 register struct Lisp_String *p;
192 CHECK_STRING (string, 0);
193 p = XSTRING (string);
194 if (p->size)
196 if (STRING_MULTIBYTE (string))
197 XSETFASTINT (val, STRING_CHAR (p->data, STRING_BYTES (p)));
198 else
199 XSETFASTINT (val, p->data[0]);
201 else
202 XSETFASTINT (val, 0);
203 return val;
206 static Lisp_Object
207 buildmark (charpos, bytepos)
208 int charpos, bytepos;
210 register Lisp_Object mark;
211 mark = Fmake_marker ();
212 set_marker_both (mark, Qnil, charpos, bytepos);
213 return mark;
216 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
217 "Return value of point, as an integer.\n\
218 Beginning of buffer is position (point-min)")
221 Lisp_Object temp;
222 XSETFASTINT (temp, PT);
223 return temp;
226 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
227 "Return value of point, as a marker object.")
230 return buildmark (PT, PT_BYTE);
234 clip_to_bounds (lower, num, upper)
235 int lower, num, upper;
237 if (num < lower)
238 return lower;
239 else if (num > upper)
240 return upper;
241 else
242 return num;
245 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
246 "Set point to POSITION, a number or marker.\n\
247 Beginning of buffer is position (point-min), end is (point-max).\n\
248 If the position is in the middle of a multibyte form,\n\
249 the actual point is set at the head of the multibyte form\n\
250 except in the case that `enable-multibyte-characters' is nil.")
251 (position)
252 register Lisp_Object position;
254 int pos;
256 if (MARKERP (position)
257 && current_buffer == XMARKER (position)->buffer)
259 pos = marker_position (position);
260 if (pos < BEGV)
261 SET_PT_BOTH (BEGV, BEGV_BYTE);
262 else if (pos > ZV)
263 SET_PT_BOTH (ZV, ZV_BYTE);
264 else
265 SET_PT_BOTH (pos, marker_byte_position (position));
267 return position;
270 CHECK_NUMBER_COERCE_MARKER (position, 0);
272 pos = clip_to_bounds (BEGV, XINT (position), ZV);
273 SET_PT (pos);
274 return position;
278 /* Return the start or end position of the region.
279 BEGINNINGP non-zero means return the start.
280 If there is no region active, signal an error. */
282 static Lisp_Object
283 region_limit (beginningp)
284 int beginningp;
286 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
287 Lisp_Object m;
289 if (!NILP (Vtransient_mark_mode)
290 && NILP (Vmark_even_if_inactive)
291 && NILP (current_buffer->mark_active))
292 Fsignal (Qmark_inactive, Qnil);
294 m = Fmarker_position (current_buffer->mark);
295 if (NILP (m))
296 error ("There is no region now");
298 if ((PT < XFASTINT (m)) == beginningp)
299 m = make_number (PT);
300 return m;
303 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
304 "Return position of beginning of region, as an integer.")
307 return region_limit (1);
310 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
311 "Return position of end of region, as an integer.")
314 return region_limit (0);
317 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
318 "Return this buffer's mark, as a marker object.\n\
319 Watch out! Moving this marker changes the mark position.\n\
320 If you set the marker not to point anywhere, the buffer will have no mark.")
323 return current_buffer->mark;
327 #if 0 /* Not used. */
329 /* Return nonzero if POS1 and POS2 have the same value
330 for the text property PROP. */
332 static int
333 char_property_eq (prop, pos1, pos2)
334 Lisp_Object prop;
335 Lisp_Object pos1, pos2;
337 Lisp_Object pval1, pval2;
339 pval1 = Fget_char_property (pos1, prop, Qnil);
340 pval2 = Fget_char_property (pos2, prop, Qnil);
342 return EQ (pval1, pval2);
345 #endif /* 0 */
347 /* Return the direction from which the text-property PROP would be
348 inherited by any new text inserted at POS: 1 if it would be
349 inherited from the char after POS, -1 if it would be inherited from
350 the char before POS, and 0 if from neither. */
352 static int
353 text_property_stickiness (prop, pos)
354 Lisp_Object prop;
355 Lisp_Object pos;
357 Lisp_Object front_sticky;
359 if (XINT (pos) > BEGV)
360 /* Consider previous character. */
362 Lisp_Object prev_pos, rear_non_sticky;
364 prev_pos = make_number (XINT (pos) - 1);
365 rear_non_sticky = Fget_text_property (prev_pos, Qrear_nonsticky, Qnil);
367 if (EQ (rear_non_sticky, Qnil)
368 || (CONSP (rear_non_sticky)
369 && NILP (Fmemq (prop, rear_non_sticky))))
370 /* PROP is not rear-non-sticky, and since this takes precedence over
371 any front-stickiness, PROP is inherited from before. */
372 return -1;
375 /* Consider following character. */
376 front_sticky = Fget_text_property (pos, Qfront_sticky, Qnil);
378 if (EQ (front_sticky, Qt)
379 || (CONSP (front_sticky)
380 && !NILP (Fmemq (prop, front_sticky))))
381 /* PROP is inherited from after. */
382 return 1;
384 /* PROP is not inherited from either side. */
385 return 0;
389 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
390 the value of point is used instead. If BEG or END null,
391 means don't store the beginning or end of the field.
393 If MERGE_AT_BOUNDARY is nonzero, then if POS is at the very first
394 position of a field, then the beginning of the previous field is
395 returned instead of the beginning of POS's field (since the end of a
396 field is actually also the beginning of the next input field, this
397 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
398 true case, if two fields are separated by a field with the special
399 value `boundary', and POS lies within it, then the two separated
400 fields are considered to be adjacent, and POS between them, when
401 finding the beginning and ending of the "merged" field.
403 Either BEG or END may be 0, in which case the corresponding value
404 is not stored. */
406 static void
407 find_field (pos, merge_at_boundary, beg, end)
408 Lisp_Object pos;
409 Lisp_Object merge_at_boundary;
410 int *beg, *end;
412 /* Fields right before and after the point. */
413 Lisp_Object before_field, after_field;
414 /* If the fields came from overlays, the associated overlays.
415 Qnil means they came from text-properties. */
416 Lisp_Object before_overlay = Qnil, after_overlay = Qnil;
417 /* 1 if POS counts as the start of a field. */
418 int at_field_start = 0;
419 /* 1 if POS counts as the end of a field. */
420 int at_field_end = 0;
422 if (NILP (pos))
423 XSETFASTINT (pos, PT);
424 else
425 CHECK_NUMBER_COERCE_MARKER (pos, 0);
427 after_field
428 = get_char_property_and_overlay (pos, Qfield, Qnil, &after_overlay);
429 before_field
430 = (XFASTINT (pos) > BEGV
431 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
432 Qfield, Qnil,
433 &before_overlay)
434 : Qnil);
436 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
437 and POS is at beginning of a field, which can also be interpreted
438 as the end of the previous field. Note that the case where if
439 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
440 more natural one; then we avoid treating the beginning of a field
441 specially. */
442 if (NILP (merge_at_boundary) && !EQ (after_field, before_field))
443 /* We are at a boundary, see which direction is inclusive. We
444 decide by seeing which field the `field' property sticks to. */
446 /* -1 means insertions go into before_field, 1 means they go
447 into after_field, 0 means neither. */
448 int stickiness;
449 /* Whether the before/after_field come from overlays. */
450 int bop = !NILP (before_overlay);
451 int aop = !NILP (after_overlay);
453 if (bop && XMARKER (OVERLAY_END (before_overlay))->insertion_type == 1)
454 /* before_field is from an overlay, which expands upon
455 end-insertions. Note that it's possible for after_overlay to
456 also eat insertions here, but then they will overlap, and
457 there's not much we can do. */
458 stickiness = -1;
459 else if (aop
460 && XMARKER (OVERLAY_START (after_overlay))->insertion_type == 0)
461 /* after_field is from an overlay, which expand to contain
462 start-insertions. */
463 stickiness = 1;
464 else if (bop && aop)
465 /* Both fields come from overlays, but neither will contain any
466 insertion here. */
467 stickiness = 0;
468 else if (bop)
469 /* before_field is an overlay that won't eat any insertion, but
470 after_field is from a text-property. Assume that the
471 text-property continues underneath the overlay, and so will
472 be inherited by any insertion, regardless of any stickiness
473 settings. */
474 stickiness = 1;
475 else if (aop)
476 /* Similarly, when after_field is the overlay. */
477 stickiness = -1;
478 else
479 /* Both fields come from text-properties. Look for explicit
480 stickiness properties. */
481 stickiness = text_property_stickiness (Qfield, pos);
483 if (stickiness > 0)
484 at_field_start = 1;
485 else if (stickiness < 0)
486 at_field_end = 1;
487 else
488 /* STICKINESS == 0 means that any inserted text will get a
489 `field' char-property of nil, so check to see if that
490 matches either of the adjacent characters (this being a
491 kind of "stickiness by default"). */
493 if (NILP (before_field))
494 at_field_end = 1; /* Sticks to the left. */
495 else if (NILP (after_field))
496 at_field_start = 1; /* Sticks to the right. */
500 /* Note about special `boundary' fields:
502 Consider the case where the point (`.') is between the fields `x' and `y':
504 xxxx.yyyy
506 In this situation, if merge_at_boundary is true, we consider the
507 `x' and `y' fields as forming one big merged field, and so the end
508 of the field is the end of `y'.
510 However, if `x' and `y' are separated by a special `boundary' field
511 (a field with a `field' char-property of 'boundary), then we ignore
512 this special field when merging adjacent fields. Here's the same
513 situation, but with a `boundary' field between the `x' and `y' fields:
515 xxx.BBBByyyy
517 Here, if point is at the end of `x', the beginning of `y', or
518 anywhere in-between (within the `boundary' field), we merge all
519 three fields and consider the beginning as being the beginning of
520 the `x' field, and the end as being the end of the `y' field. */
522 if (beg)
524 if (at_field_start)
525 /* POS is at the edge of a field, and we should consider it as
526 the beginning of the following field. */
527 *beg = XFASTINT (pos);
528 else
529 /* Find the previous field boundary. */
531 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
532 /* Skip a `boundary' field. */
533 pos = Fprevious_single_char_property_change (pos, Qfield, Qnil,Qnil);
535 pos = Fprevious_single_char_property_change (pos, Qfield, Qnil, Qnil);
536 *beg = NILP (pos) ? BEGV : XFASTINT (pos);
540 if (end)
542 if (at_field_end)
543 /* POS is at the edge of a field, and we should consider it as
544 the end of the previous field. */
545 *end = XFASTINT (pos);
546 else
547 /* Find the next field boundary. */
549 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
550 /* Skip a `boundary' field. */
551 pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
553 pos = Fnext_single_char_property_change (pos, Qfield, Qnil, Qnil);
554 *end = NILP (pos) ? ZV : XFASTINT (pos);
560 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
561 "Delete the field surrounding POS.\n\
562 A field is a region of text with the same `field' property.\n\
563 If POS is nil, the value of point is used for POS.")
564 (pos)
565 Lisp_Object pos;
567 int beg, end;
568 find_field (pos, Qnil, &beg, &end);
569 if (beg != end)
570 del_range (beg, end);
571 return Qnil;
574 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
575 "Return the contents of the field surrounding POS as a string.\n\
576 A field is a region of text with the same `field' property.\n\
577 If POS is nil, the value of point is used for POS.")
578 (pos)
579 Lisp_Object pos;
581 int beg, end;
582 find_field (pos, Qnil, &beg, &end);
583 return make_buffer_string (beg, end, 1);
586 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
587 "Return the contents of the field around POS, without text-properties.\n\
588 A field is a region of text with the same `field' property.\n\
589 If POS is nil, the value of point is used for POS.")
590 (pos)
591 Lisp_Object pos;
593 int beg, end;
594 find_field (pos, Qnil, &beg, &end);
595 return make_buffer_string (beg, end, 0);
598 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 2, 0,
599 "Return the beginning of the field surrounding POS.\n\
600 A field is a region of text with the same `field' property.\n\
601 If POS is nil, the value of point is used for POS.\n\
602 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its\n\
603 field, then the beginning of the *previous* field is returned.")
604 (pos, escape_from_edge)
605 Lisp_Object pos, escape_from_edge;
607 int beg;
608 find_field (pos, escape_from_edge, &beg, 0);
609 return make_number (beg);
612 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 2, 0,
613 "Return the end of the field surrounding POS.\n\
614 A field is a region of text with the same `field' property.\n\
615 If POS is nil, the value of point is used for POS.\n\
616 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,\n\
617 then the end of the *following* field is returned.")
618 (pos, escape_from_edge)
619 Lisp_Object pos, escape_from_edge;
621 int end;
622 find_field (pos, escape_from_edge, 0, &end);
623 return make_number (end);
626 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
627 "Return the position closest to NEW-POS that is in the same field as OLD-POS.\n\
629 A field is a region of text with the same `field' property.\n\
630 If NEW-POS is nil, then the current point is used instead, and set to the\n\
631 constrained position if that is different.\n\
633 If OLD-POS is at the boundary of two fields, then the allowable\n\
634 positions for NEW-POS depends on the value of the optional argument\n\
635 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is\n\
636 constrained to the field that has the same `field' char-property\n\
637 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE\n\
638 is non-nil, NEW-POS is constrained to the union of the two adjacent\n\
639 fields. Additionally, if two fields are separated by another field with\n\
640 the special value `boundary', then any point within this special field is\n\
641 also considered to be `on the boundary'.\n\
643 If the optional argument ONLY-IN-LINE is non-nil and constraining\n\
644 NEW-POS would move it to a different line, NEW-POS is returned\n\
645 unconstrained. This useful for commands that move by line, like\n\
646 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries\n\
647 only in the case where they can still move to the right line.\n\
649 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has\n\
650 a non-nil property of that name, then any field boundaries are ignored.\n\
652 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil.")
653 (new_pos, old_pos, escape_from_edge, only_in_line, inhibit_capture_property)
654 Lisp_Object new_pos, old_pos;
655 Lisp_Object escape_from_edge, only_in_line, inhibit_capture_property;
657 /* If non-zero, then the original point, before re-positioning. */
658 int orig_point = 0;
660 if (NILP (new_pos))
661 /* Use the current point, and afterwards, set it. */
663 orig_point = PT;
664 XSETFASTINT (new_pos, PT);
667 if (NILP (Vinhibit_field_text_motion)
668 && !EQ (new_pos, old_pos)
669 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
670 || !NILP (Fget_char_property (old_pos, Qfield, Qnil)))
671 && (NILP (inhibit_capture_property)
672 || NILP (Fget_char_property(old_pos, inhibit_capture_property, Qnil))))
673 /* NEW_POS is not within the same field as OLD_POS; try to
674 move NEW_POS so that it is. */
676 int fwd, shortage;
677 Lisp_Object field_bound;
679 CHECK_NUMBER_COERCE_MARKER (new_pos, 0);
680 CHECK_NUMBER_COERCE_MARKER (old_pos, 0);
682 fwd = (XFASTINT (new_pos) > XFASTINT (old_pos));
684 if (fwd)
685 field_bound = Ffield_end (old_pos, escape_from_edge);
686 else
687 field_bound = Ffield_beginning (old_pos, escape_from_edge);
689 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
690 other side of NEW_POS, which would mean that NEW_POS is
691 already acceptable, and it's not necessary to constrain it
692 to FIELD_BOUND. */
693 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
694 /* NEW_POS should be constrained, but only if either
695 ONLY_IN_LINE is nil (in which case any constraint is OK),
696 or NEW_POS and FIELD_BOUND are on the same line (in which
697 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
698 && (NILP (only_in_line)
699 /* This is the ONLY_IN_LINE case, check that NEW_POS and
700 FIELD_BOUND are on the same line by seeing whether
701 there's an intervening newline or not. */
702 || (scan_buffer ('\n',
703 XFASTINT (new_pos), XFASTINT (field_bound),
704 fwd ? -1 : 1, &shortage, 1),
705 shortage != 0)))
706 /* Constrain NEW_POS to FIELD_BOUND. */
707 new_pos = field_bound;
709 if (orig_point && XFASTINT (new_pos) != orig_point)
710 /* The NEW_POS argument was originally nil, so automatically set PT. */
711 SET_PT (XFASTINT (new_pos));
714 return new_pos;
718 DEFUN ("line-beginning-position", Fline_beginning_position, Sline_beginning_position,
719 0, 1, 0,
720 "Return the character position of the first character on the current line.\n\
721 With argument N not nil or 1, move forward N - 1 lines first.\n\
722 If scan reaches end of buffer, return that position.\n\
723 The scan does not cross a field boundary unless it would move\n\
724 beyond there to a different line. Field boundaries are not noticed if\n\
725 `inhibit-field-text-motion' is non-nil. .And if N is nil or 1,\n\
726 and scan starts at a field boundary, the scan stops as soon as it starts.\n\
728 This function does not move point.")
730 Lisp_Object n;
732 int orig, orig_byte, end;
734 if (NILP (n))
735 XSETFASTINT (n, 1);
736 else
737 CHECK_NUMBER (n, 0);
739 orig = PT;
740 orig_byte = PT_BYTE;
741 Fforward_line (make_number (XINT (n) - 1));
742 end = PT;
744 SET_PT_BOTH (orig, orig_byte);
746 /* Return END constrained to the current input field. */
747 return Fconstrain_to_field (make_number (end), make_number (orig),
748 XINT (n) != 1 ? Qt : Qnil,
749 Qt, Qnil);
752 DEFUN ("line-end-position", Fline_end_position, Sline_end_position,
753 0, 1, 0,
754 "Return the character position of the last character on the current line.\n\
755 With argument N not nil or 1, move forward N - 1 lines first.\n\
756 If scan reaches end of buffer, return that position.\n\
757 This function does not move point.")
759 Lisp_Object n;
761 int end_pos;
762 int orig = PT;
764 if (NILP (n))
765 XSETFASTINT (n, 1);
766 else
767 CHECK_NUMBER (n, 0);
769 end_pos = find_before_next_newline (orig, 0, XINT (n) - (XINT (n) <= 0));
771 /* Return END_POS constrained to the current input field. */
772 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
773 Qnil, Qt, Qnil);
776 Lisp_Object
777 save_excursion_save ()
779 int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
780 == current_buffer);
782 return Fcons (Fpoint_marker (),
783 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
784 Fcons (visible ? Qt : Qnil,
785 Fcons (current_buffer->mark_active,
786 selected_window))));
789 Lisp_Object
790 save_excursion_restore (info)
791 Lisp_Object info;
793 Lisp_Object tem, tem1, omark, nmark;
794 struct gcpro gcpro1, gcpro2, gcpro3;
795 int visible_p;
797 tem = Fmarker_buffer (XCAR (info));
798 /* If buffer being returned to is now deleted, avoid error */
799 /* Otherwise could get error here while unwinding to top level
800 and crash */
801 /* In that case, Fmarker_buffer returns nil now. */
802 if (NILP (tem))
803 return Qnil;
805 omark = nmark = Qnil;
806 GCPRO3 (info, omark, nmark);
808 Fset_buffer (tem);
810 /* Point marker. */
811 tem = XCAR (info);
812 Fgoto_char (tem);
813 unchain_marker (tem);
815 /* Mark marker. */
816 info = XCDR (info);
817 tem = XCAR (info);
818 omark = Fmarker_position (current_buffer->mark);
819 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
820 nmark = Fmarker_position (tem);
821 unchain_marker (tem);
823 /* visible */
824 info = XCDR (info);
825 visible_p = !NILP (XCAR (info));
827 #if 0 /* We used to make the current buffer visible in the selected window
828 if that was true previously. That avoids some anomalies.
829 But it creates others, and it wasn't documented, and it is simpler
830 and cleaner never to alter the window/buffer connections. */
831 tem1 = Fcar (tem);
832 if (!NILP (tem1)
833 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
834 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
835 #endif /* 0 */
837 /* Mark active */
838 info = XCDR (info);
839 tem = XCAR (info);
840 tem1 = current_buffer->mark_active;
841 current_buffer->mark_active = tem;
843 if (!NILP (Vrun_hooks))
845 /* If mark is active now, and either was not active
846 or was at a different place, run the activate hook. */
847 if (! NILP (current_buffer->mark_active))
849 if (! EQ (omark, nmark))
850 call1 (Vrun_hooks, intern ("activate-mark-hook"));
852 /* If mark has ceased to be active, run deactivate hook. */
853 else if (! NILP (tem1))
854 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
857 /* If buffer was visible in a window, and a different window was
858 selected, and the old selected window is still showing this
859 buffer, restore point in that window. */
860 tem = XCDR (info);
861 if (visible_p
862 && !EQ (tem, selected_window)
863 && (tem1 = XWINDOW (tem)->buffer,
864 (/* Window is live... */
865 BUFFERP (tem1)
866 /* ...and it shows the current buffer. */
867 && XBUFFER (tem1) == current_buffer)))
868 Fset_window_point (tem, make_number (PT));
870 UNGCPRO;
871 return Qnil;
874 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
875 "Save point, mark, and current buffer; execute BODY; restore those things.\n\
876 Executes BODY just like `progn'.\n\
877 The values of point, mark and the current buffer are restored\n\
878 even in case of abnormal exit (throw or error).\n\
879 The state of activation of the mark is also restored.\n\
881 This construct does not save `deactivate-mark', and therefore\n\
882 functions that change the buffer will still cause deactivation\n\
883 of the mark at the end of the command. To prevent that, bind\n\
884 `deactivate-mark' with `let'.")
885 (args)
886 Lisp_Object args;
888 register Lisp_Object val;
889 int count = specpdl_ptr - specpdl;
891 record_unwind_protect (save_excursion_restore, save_excursion_save ());
893 val = Fprogn (args);
894 return unbind_to (count, val);
897 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
898 "Save the current buffer; execute BODY; restore the current buffer.\n\
899 Executes BODY just like `progn'.")
900 (args)
901 Lisp_Object args;
903 Lisp_Object val;
904 int count = specpdl_ptr - specpdl;
906 record_unwind_protect (set_buffer_if_live, Fcurrent_buffer ());
908 val = Fprogn (args);
909 return unbind_to (count, val);
912 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 1, 0,
913 "Return the number of characters in the current buffer.\n\
914 If BUFFER, return the number of characters in that buffer instead.")
915 (buffer)
916 Lisp_Object buffer;
918 if (NILP (buffer))
919 return make_number (Z - BEG);
920 else
922 CHECK_BUFFER (buffer, 1);
923 return make_number (BUF_Z (XBUFFER (buffer))
924 - BUF_BEG (XBUFFER (buffer)));
928 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
929 "Return the minimum permissible value of point in the current buffer.\n\
930 This is 1, unless narrowing (a buffer restriction) is in effect.")
933 Lisp_Object temp;
934 XSETFASTINT (temp, BEGV);
935 return temp;
938 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
939 "Return a marker to the minimum permissible value of point in this buffer.\n\
940 This is the beginning, unless narrowing (a buffer restriction) is in effect.")
943 return buildmark (BEGV, BEGV_BYTE);
946 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
947 "Return the maximum permissible value of point in the current buffer.\n\
948 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
949 is in effect, in which case it is less.")
952 Lisp_Object temp;
953 XSETFASTINT (temp, ZV);
954 return temp;
957 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
958 "Return a marker to the maximum permissible value of point in this buffer.\n\
959 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
960 is in effect, in which case it is less.")
963 return buildmark (ZV, ZV_BYTE);
966 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
967 "Return the position of the gap, in the current buffer.\n\
968 See also `gap-size'.")
971 Lisp_Object temp;
972 XSETFASTINT (temp, GPT);
973 return temp;
976 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
977 "Return the size of the current buffer's gap.\n\
978 See also `gap-position'.")
981 Lisp_Object temp;
982 XSETFASTINT (temp, GAP_SIZE);
983 return temp;
986 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
987 "Return the byte position for character position POSITION.\n\
988 If POSITION is out of range, the value is nil.")
989 (position)
990 Lisp_Object position;
992 CHECK_NUMBER_COERCE_MARKER (position, 1);
993 if (XINT (position) < BEG || XINT (position) > Z)
994 return Qnil;
995 return make_number (CHAR_TO_BYTE (XINT (position)));
998 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
999 "Return the character position for byte position BYTEPOS.\n\
1000 If BYTEPOS is out of range, the value is nil.")
1001 (bytepos)
1002 Lisp_Object bytepos;
1004 CHECK_NUMBER (bytepos, 1);
1005 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1006 return Qnil;
1007 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1010 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1011 "Return the character following point, as a number.\n\
1012 At the end of the buffer or accessible region, return 0.")
1015 Lisp_Object temp;
1016 if (PT >= ZV)
1017 XSETFASTINT (temp, 0);
1018 else
1019 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1020 return temp;
1023 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1024 "Return the character preceding point, as a number.\n\
1025 At the beginning of the buffer or accessible region, return 0.")
1028 Lisp_Object temp;
1029 if (PT <= BEGV)
1030 XSETFASTINT (temp, 0);
1031 else if (!NILP (current_buffer->enable_multibyte_characters))
1033 int pos = PT_BYTE;
1034 DEC_POS (pos);
1035 XSETFASTINT (temp, FETCH_CHAR (pos));
1037 else
1038 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1039 return temp;
1042 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1043 "Return t if point is at the beginning of the buffer.\n\
1044 If the buffer is narrowed, this means the beginning of the narrowed part.")
1047 if (PT == BEGV)
1048 return Qt;
1049 return Qnil;
1052 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1053 "Return t if point is at the end of the buffer.\n\
1054 If the buffer is narrowed, this means the end of the narrowed part.")
1057 if (PT == ZV)
1058 return Qt;
1059 return Qnil;
1062 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1063 "Return t if point is at the beginning of a line.")
1066 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1067 return Qt;
1068 return Qnil;
1071 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1072 "Return t if point is at the end of a line.\n\
1073 `End of a line' includes point being at the end of the buffer.")
1076 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1077 return Qt;
1078 return Qnil;
1081 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1082 "Return character in current buffer at position POS.\n\
1083 POS is an integer or a marker.\n\
1084 If POS is out of range, the value is nil.")
1085 (pos)
1086 Lisp_Object pos;
1088 register int pos_byte;
1090 if (NILP (pos))
1092 pos_byte = PT_BYTE;
1093 XSETFASTINT (pos, PT);
1096 if (MARKERP (pos))
1098 pos_byte = marker_byte_position (pos);
1099 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1100 return Qnil;
1102 else
1104 CHECK_NUMBER_COERCE_MARKER (pos, 0);
1105 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1106 return Qnil;
1108 pos_byte = CHAR_TO_BYTE (XINT (pos));
1111 return make_number (FETCH_CHAR (pos_byte));
1114 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1115 "Return character in current buffer preceding position POS.\n\
1116 POS is an integer or a marker.\n\
1117 If POS is out of range, the value is nil.")
1118 (pos)
1119 Lisp_Object pos;
1121 register Lisp_Object val;
1122 register int pos_byte;
1124 if (NILP (pos))
1126 pos_byte = PT_BYTE;
1127 XSETFASTINT (pos, PT);
1130 if (MARKERP (pos))
1132 pos_byte = marker_byte_position (pos);
1134 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1135 return Qnil;
1137 else
1139 CHECK_NUMBER_COERCE_MARKER (pos, 0);
1141 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1142 return Qnil;
1144 pos_byte = CHAR_TO_BYTE (XINT (pos));
1147 if (!NILP (current_buffer->enable_multibyte_characters))
1149 DEC_POS (pos_byte);
1150 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1152 else
1154 pos_byte--;
1155 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1157 return val;
1160 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1161 "Return the name under which the user logged in, as a string.\n\
1162 This is based on the effective uid, not the real uid.\n\
1163 Also, if the environment variable LOGNAME or USER is set,\n\
1164 that determines the value of this function.\n\n\
1165 If optional argument UID is an integer, return the login name of the user\n\
1166 with that uid, or nil if there is no such user.")
1167 (uid)
1168 Lisp_Object uid;
1170 struct passwd *pw;
1172 /* Set up the user name info if we didn't do it before.
1173 (That can happen if Emacs is dumpable
1174 but you decide to run `temacs -l loadup' and not dump. */
1175 if (INTEGERP (Vuser_login_name))
1176 init_editfns ();
1178 if (NILP (uid))
1179 return Vuser_login_name;
1181 CHECK_NUMBER (uid, 0);
1182 pw = (struct passwd *) getpwuid (XINT (uid));
1183 return (pw ? build_string (pw->pw_name) : Qnil);
1186 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1187 0, 0, 0,
1188 "Return the name of the user's real uid, as a string.\n\
1189 This ignores the environment variables LOGNAME and USER, so it differs from\n\
1190 `user-login-name' when running under `su'.")
1193 /* Set up the user name info if we didn't do it before.
1194 (That can happen if Emacs is dumpable
1195 but you decide to run `temacs -l loadup' and not dump. */
1196 if (INTEGERP (Vuser_login_name))
1197 init_editfns ();
1198 return Vuser_real_login_name;
1201 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1202 "Return the effective uid of Emacs, as an integer.")
1205 return make_number (geteuid ());
1208 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1209 "Return the real uid of Emacs, as an integer.")
1212 return make_number (getuid ());
1215 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1216 "Return the full name of the user logged in, as a string.\n\
1217 If the full name corresponding to Emacs's userid is not known,\n\
1218 return \"unknown\".\n\
1220 If optional argument UID is an integer, return the full name of the user\n\
1221 with that uid, or nil if there is no such user.\n\
1222 If UID is a string, return the full name of the user with that login\n\
1223 name, or nil if there is no such user.")
1224 (uid)
1225 Lisp_Object uid;
1227 struct passwd *pw;
1228 register unsigned char *p, *q;
1229 Lisp_Object full;
1231 if (NILP (uid))
1232 return Vuser_full_name;
1233 else if (NUMBERP (uid))
1234 pw = (struct passwd *) getpwuid (XINT (uid));
1235 else if (STRINGP (uid))
1236 pw = (struct passwd *) getpwnam (XSTRING (uid)->data);
1237 else
1238 error ("Invalid UID specification");
1240 if (!pw)
1241 return Qnil;
1243 p = (unsigned char *) USER_FULL_NAME;
1244 /* Chop off everything after the first comma. */
1245 q = (unsigned char *) index (p, ',');
1246 full = make_string (p, q ? q - p : strlen (p));
1248 #ifdef AMPERSAND_FULL_NAME
1249 p = XSTRING (full)->data;
1250 q = (unsigned char *) index (p, '&');
1251 /* Substitute the login name for the &, upcasing the first character. */
1252 if (q)
1254 register unsigned char *r;
1255 Lisp_Object login;
1257 login = Fuser_login_name (make_number (pw->pw_uid));
1258 r = (unsigned char *) alloca (strlen (p) + XSTRING (login)->size + 1);
1259 bcopy (p, r, q - p);
1260 r[q - p] = 0;
1261 strcat (r, XSTRING (login)->data);
1262 r[q - p] = UPCASE (r[q - p]);
1263 strcat (r, q + 1);
1264 full = build_string (r);
1266 #endif /* AMPERSAND_FULL_NAME */
1268 return full;
1271 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1272 "Return the name of the machine you are running on, as a string.")
1275 return Vsystem_name;
1278 /* For the benefit of callers who don't want to include lisp.h */
1280 char *
1281 get_system_name ()
1283 if (STRINGP (Vsystem_name))
1284 return (char *) XSTRING (Vsystem_name)->data;
1285 else
1286 return "";
1289 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1290 "Return the process ID of Emacs, as an integer.")
1293 return make_number (getpid ());
1296 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1297 "Return the current time, as the number of seconds since 1970-01-01 00:00:00.\n\
1298 The time is returned as a list of three integers. The first has the\n\
1299 most significant 16 bits of the seconds, while the second has the\n\
1300 least significant 16 bits. The third integer gives the microsecond\n\
1301 count.\n\
1303 The microsecond count is zero on systems that do not provide\n\
1304 resolution finer than a second.")
1307 EMACS_TIME t;
1308 Lisp_Object result[3];
1310 EMACS_GET_TIME (t);
1311 XSETINT (result[0], (EMACS_SECS (t) >> 16) & 0xffff);
1312 XSETINT (result[1], (EMACS_SECS (t) >> 0) & 0xffff);
1313 XSETINT (result[2], EMACS_USECS (t));
1315 return Flist (3, result);
1319 static int
1320 lisp_time_argument (specified_time, result, usec)
1321 Lisp_Object specified_time;
1322 time_t *result;
1323 int *usec;
1325 if (NILP (specified_time))
1327 if (usec)
1329 EMACS_TIME t;
1331 EMACS_GET_TIME (t);
1332 *usec = EMACS_USECS (t);
1333 *result = EMACS_SECS (t);
1334 return 1;
1336 else
1337 return time (result) != -1;
1339 else
1341 Lisp_Object high, low;
1342 high = Fcar (specified_time);
1343 CHECK_NUMBER (high, 0);
1344 low = Fcdr (specified_time);
1345 if (CONSP (low))
1347 if (usec)
1349 Lisp_Object usec_l = Fcdr (low);
1350 if (CONSP (usec_l))
1351 usec_l = Fcar (usec_l);
1352 if (NILP (usec_l))
1353 *usec = 0;
1354 else
1356 CHECK_NUMBER (usec_l, 0);
1357 *usec = XINT (usec_l);
1360 low = Fcar (low);
1362 else if (usec)
1363 *usec = 0;
1364 CHECK_NUMBER (low, 0);
1365 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
1366 return *result >> 16 == XINT (high);
1370 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1371 "Return the current time, as a float number of seconds since the epoch.\n\
1372 If an argument is given, it specifies a time to convert to float\n\
1373 instead of the current time. The argument should have the forms:\n\
1374 (HIGH . LOW) or (HIGH LOW USEC) or (HIGH LOW . USEC).\n\
1375 Thus, you can use times obtained from `current-time'\n\
1376 and from `file-attributes'.\n\
1378 WARNING: Since the result is floating point, it may not be exact.\n\
1379 Do not use this function if precise time stamps are required.")
1380 (specified_time)
1381 Lisp_Object specified_time;
1383 time_t sec;
1384 int usec;
1386 if (! lisp_time_argument (specified_time, &sec, &usec))
1387 error ("Invalid time specification");
1389 return make_float ((sec * 1e6 + usec) / 1e6);
1392 /* Write information into buffer S of size MAXSIZE, according to the
1393 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1394 Default to Universal Time if UT is nonzero, local time otherwise.
1395 Return the number of bytes written, not including the terminating
1396 '\0'. If S is NULL, nothing will be written anywhere; so to
1397 determine how many bytes would be written, use NULL for S and
1398 ((size_t) -1) for MAXSIZE.
1400 This function behaves like emacs_strftimeu, except it allows null
1401 bytes in FORMAT. */
1402 static size_t
1403 emacs_memftimeu (s, maxsize, format, format_len, tp, ut)
1404 char *s;
1405 size_t maxsize;
1406 const char *format;
1407 size_t format_len;
1408 const struct tm *tp;
1409 int ut;
1411 size_t total = 0;
1413 /* Loop through all the null-terminated strings in the format
1414 argument. Normally there's just one null-terminated string, but
1415 there can be arbitrarily many, concatenated together, if the
1416 format contains '\0' bytes. emacs_strftimeu stops at the first
1417 '\0' byte so we must invoke it separately for each such string. */
1418 for (;;)
1420 size_t len;
1421 size_t result;
1423 if (s)
1424 s[0] = '\1';
1426 result = emacs_strftimeu (s, maxsize, format, tp, ut);
1428 if (s)
1430 if (result == 0 && s[0] != '\0')
1431 return 0;
1432 s += result + 1;
1435 maxsize -= result + 1;
1436 total += result;
1437 len = strlen (format);
1438 if (len == format_len)
1439 return total;
1440 total++;
1441 format += len + 1;
1442 format_len -= len + 1;
1447 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1448 "Use FORMAT-STRING to format the time TIME, or now if omitted.\n\
1449 TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as returned by\n\
1450 `current-time' or `file-attributes'.\n\
1451 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME\n\
1452 as Universal Time; nil means describe TIME in the local time zone.\n\
1453 The value is a copy of FORMAT-STRING, but with certain constructs replaced\n\
1454 by text that describes the specified date and time in TIME:\n\
1456 %Y is the year, %y within the century, %C the century.\n\
1457 %G is the year corresponding to the ISO week, %g within the century.\n\
1458 %m is the numeric month.\n\
1459 %b and %h are the locale's abbreviated month name, %B the full name.\n\
1460 %d is the day of the month, zero-padded, %e is blank-padded.\n\
1461 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.\n\
1462 %a is the locale's abbreviated name of the day of week, %A the full name.\n\
1463 %U is the week number starting on Sunday, %W starting on Monday,\n\
1464 %V according to ISO 8601.\n\
1465 %j is the day of the year.\n\
1467 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H\n\
1468 only blank-padded, %l is like %I blank-padded.\n\
1469 %p is the locale's equivalent of either AM or PM.\n\
1470 %M is the minute.\n\
1471 %S is the second.\n\
1472 %Z is the time zone name, %z is the numeric form.\n\
1473 %s is the number of seconds since 1970-01-01 00:00:00 +0000.\n\
1475 %c is the locale's date and time format.\n\
1476 %x is the locale's \"preferred\" date format.\n\
1477 %D is like \"%m/%d/%y\".\n\
1479 %R is like \"%H:%M\", %T is like \"%H:%M:%S\", %r is like \"%I:%M:%S %p\".\n\
1480 %X is the locale's \"preferred\" time format.\n\
1482 Finally, %n is a newline, %t is a tab, %% is a literal %.\n\
1484 Certain flags and modifiers are available with some format controls.\n\
1485 The flags are `_', `-', `^' and `#'. For certain characters X,\n\
1486 %_X is like %X, but padded with blanks; %-X is like %X,\n\
1487 ut without padding. %^X is like %X but with all textual\n\
1488 characters up-cased; %#X is like %X but with letter-case of\n\
1489 all textual characters reversed.\n\
1490 %NX (where N stands for an integer) is like %X,\n\
1491 but takes up at least N (a number) positions.\n\
1492 The modifiers are `E' and `O'. For certain characters X,\n\
1493 %EX is a locale's alternative version of %X;\n\
1494 %OX is like %X, but uses the locale's number symbols.\n\
1496 For example, to produce full ISO 8601 format, use \"%Y-%m-%dT%T%z\".")
1497 (format_string, time, universal)
1500 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1501 0 /* See immediately above */)
1502 (format_string, time, universal)
1503 Lisp_Object format_string, time, universal;
1505 time_t value;
1506 int size;
1507 struct tm *tm;
1508 int ut = ! NILP (universal);
1510 CHECK_STRING (format_string, 1);
1512 if (! lisp_time_argument (time, &value, NULL))
1513 error ("Invalid time specification");
1515 format_string = code_convert_string_norecord (format_string,
1516 Vlocale_coding_system, 1);
1518 /* This is probably enough. */
1519 size = STRING_BYTES (XSTRING (format_string)) * 6 + 50;
1521 tm = ut ? gmtime (&value) : localtime (&value);
1522 if (! tm)
1523 error ("Specified time is not representable");
1525 synchronize_system_time_locale ();
1527 while (1)
1529 char *buf = (char *) alloca (size + 1);
1530 int result;
1532 buf[0] = '\1';
1533 result = emacs_memftimeu (buf, size, XSTRING (format_string)->data,
1534 STRING_BYTES (XSTRING (format_string)),
1535 tm, ut);
1536 if ((result > 0 && result < size) || (result == 0 && buf[0] == '\0'))
1537 return code_convert_string_norecord (make_string (buf, result),
1538 Vlocale_coding_system, 0);
1540 /* If buffer was too small, make it bigger and try again. */
1541 result = emacs_memftimeu (NULL, (size_t) -1,
1542 XSTRING (format_string)->data,
1543 STRING_BYTES (XSTRING (format_string)),
1544 tm, ut);
1545 size = result + 1;
1549 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
1550 "Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).\n\
1551 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED)\n\
1552 or (HIGH . LOW), as from `current-time' and `file-attributes', or `nil'\n\
1553 to use the current time. The list has the following nine members:\n\
1554 SEC is an integer between 0 and 60; SEC is 60 for a leap second, which\n\
1555 only some operating systems support. MINUTE is an integer between 0 and 59.\n\
1556 HOUR is an integer between 0 and 23. DAY is an integer between 1 and 31.\n\
1557 MONTH is an integer between 1 and 12. YEAR is an integer indicating the\n\
1558 four-digit year. DOW is the day of week, an integer between 0 and 6, where\n\
1559 0 is Sunday. DST is t if daylight savings time is effect, otherwise nil.\n\
1560 ZONE is an integer indicating the number of seconds east of Greenwich.\n\
1561 \(Note that Common Lisp has different meanings for DOW and ZONE.)")
1562 (specified_time)
1563 Lisp_Object specified_time;
1565 time_t time_spec;
1566 struct tm save_tm;
1567 struct tm *decoded_time;
1568 Lisp_Object list_args[9];
1570 if (! lisp_time_argument (specified_time, &time_spec, NULL))
1571 error ("Invalid time specification");
1573 decoded_time = localtime (&time_spec);
1574 if (! decoded_time)
1575 error ("Specified time is not representable");
1576 XSETFASTINT (list_args[0], decoded_time->tm_sec);
1577 XSETFASTINT (list_args[1], decoded_time->tm_min);
1578 XSETFASTINT (list_args[2], decoded_time->tm_hour);
1579 XSETFASTINT (list_args[3], decoded_time->tm_mday);
1580 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
1581 XSETINT (list_args[5], decoded_time->tm_year + 1900);
1582 XSETFASTINT (list_args[6], decoded_time->tm_wday);
1583 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
1585 /* Make a copy, in case gmtime modifies the struct. */
1586 save_tm = *decoded_time;
1587 decoded_time = gmtime (&time_spec);
1588 if (decoded_time == 0)
1589 list_args[8] = Qnil;
1590 else
1591 XSETINT (list_args[8], tm_diff (&save_tm, decoded_time));
1592 return Flist (9, list_args);
1595 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
1596 "Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.\n\
1597 This is the reverse operation of `decode-time', which see.\n\
1598 ZONE defaults to the current time zone rule. This can\n\
1599 be a string or t (as from `set-time-zone-rule'), or it can be a list\n\
1600 \(as from `current-time-zone') or an integer (as from `decode-time')\n\
1601 applied without consideration for daylight savings time.\n\
1603 You can pass more than 7 arguments; then the first six arguments\n\
1604 are used as SECOND through YEAR, and the *last* argument is used as ZONE.\n\
1605 The intervening arguments are ignored.\n\
1606 This feature lets (apply 'encode-time (decode-time ...)) work.\n\
1608 Out-of-range values for SEC, MINUTE, HOUR, DAY, or MONTH are allowed;\n\
1609 for example, a DAY of 0 means the day preceding the given month.\n\
1610 Year numbers less than 100 are treated just like other year numbers.\n\
1611 If you want them to stand for years in this century, you must do that yourself.")
1612 (nargs, args)
1613 int nargs;
1614 register Lisp_Object *args;
1616 time_t time;
1617 struct tm tm;
1618 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
1620 CHECK_NUMBER (args[0], 0); /* second */
1621 CHECK_NUMBER (args[1], 1); /* minute */
1622 CHECK_NUMBER (args[2], 2); /* hour */
1623 CHECK_NUMBER (args[3], 3); /* day */
1624 CHECK_NUMBER (args[4], 4); /* month */
1625 CHECK_NUMBER (args[5], 5); /* year */
1627 tm.tm_sec = XINT (args[0]);
1628 tm.tm_min = XINT (args[1]);
1629 tm.tm_hour = XINT (args[2]);
1630 tm.tm_mday = XINT (args[3]);
1631 tm.tm_mon = XINT (args[4]) - 1;
1632 tm.tm_year = XINT (args[5]) - 1900;
1633 tm.tm_isdst = -1;
1635 if (CONSP (zone))
1636 zone = Fcar (zone);
1637 if (NILP (zone))
1638 time = mktime (&tm);
1639 else
1641 char tzbuf[100];
1642 char *tzstring;
1643 char **oldenv = environ, **newenv;
1645 if (EQ (zone, Qt))
1646 tzstring = "UTC0";
1647 else if (STRINGP (zone))
1648 tzstring = (char *) XSTRING (zone)->data;
1649 else if (INTEGERP (zone))
1651 int abszone = abs (XINT (zone));
1652 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
1653 abszone / (60*60), (abszone/60) % 60, abszone % 60);
1654 tzstring = tzbuf;
1656 else
1657 error ("Invalid time zone specification");
1659 /* Set TZ before calling mktime; merely adjusting mktime's returned
1660 value doesn't suffice, since that would mishandle leap seconds. */
1661 set_time_zone_rule (tzstring);
1663 time = mktime (&tm);
1665 /* Restore TZ to previous value. */
1666 newenv = environ;
1667 environ = oldenv;
1668 xfree (newenv);
1669 #ifdef LOCALTIME_CACHE
1670 tzset ();
1671 #endif
1674 if (time == (time_t) -1)
1675 error ("Specified time is not representable");
1677 return make_time (time);
1680 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
1681 "Return the current time, as a human-readable string.\n\
1682 Programs can use this function to decode a time,\n\
1683 since the number of columns in each field is fixed.\n\
1684 The format is `Sun Sep 16 01:03:52 1973'.\n\
1685 However, see also the functions `decode-time' and `format-time-string'\n\
1686 which provide a much more powerful and general facility.\n\
1688 If an argument is given, it specifies a time to format\n\
1689 instead of the current time. The argument should have the form:\n\
1690 (HIGH . LOW)\n\
1691 or the form:\n\
1692 (HIGH LOW . IGNORED).\n\
1693 Thus, you can use times obtained from `current-time'\n\
1694 and from `file-attributes'.")
1695 (specified_time)
1696 Lisp_Object specified_time;
1698 time_t value;
1699 char buf[30];
1700 register char *tem;
1702 if (! lisp_time_argument (specified_time, &value, NULL))
1703 value = -1;
1704 tem = (char *) ctime (&value);
1706 strncpy (buf, tem, 24);
1707 buf[24] = 0;
1709 return build_string (buf);
1712 #define TM_YEAR_BASE 1900
1714 /* Yield A - B, measured in seconds.
1715 This function is copied from the GNU C Library. */
1716 static int
1717 tm_diff (a, b)
1718 struct tm *a, *b;
1720 /* Compute intervening leap days correctly even if year is negative.
1721 Take care to avoid int overflow in leap day calculations,
1722 but it's OK to assume that A and B are close to each other. */
1723 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
1724 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
1725 int a100 = a4 / 25 - (a4 % 25 < 0);
1726 int b100 = b4 / 25 - (b4 % 25 < 0);
1727 int a400 = a100 >> 2;
1728 int b400 = b100 >> 2;
1729 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
1730 int years = a->tm_year - b->tm_year;
1731 int days = (365 * years + intervening_leap_days
1732 + (a->tm_yday - b->tm_yday));
1733 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
1734 + (a->tm_min - b->tm_min))
1735 + (a->tm_sec - b->tm_sec));
1738 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
1739 "Return the offset and name for the local time zone.\n\
1740 This returns a list of the form (OFFSET NAME).\n\
1741 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).\n\
1742 A negative value means west of Greenwich.\n\
1743 NAME is a string giving the name of the time zone.\n\
1744 If an argument is given, it specifies when the time zone offset is determined\n\
1745 instead of using the current time. The argument should have the form:\n\
1746 (HIGH . LOW)\n\
1747 or the form:\n\
1748 (HIGH LOW . IGNORED).\n\
1749 Thus, you can use times obtained from `current-time'\n\
1750 and from `file-attributes'.\n\
1752 Some operating systems cannot provide all this information to Emacs;\n\
1753 in this case, `current-time-zone' returns a list containing nil for\n\
1754 the data it can't find.")
1755 (specified_time)
1756 Lisp_Object specified_time;
1758 time_t value;
1759 struct tm *t;
1760 struct tm gmt;
1762 if (lisp_time_argument (specified_time, &value, NULL)
1763 && (t = gmtime (&value)) != 0
1764 && (gmt = *t, t = localtime (&value)) != 0)
1766 int offset = tm_diff (t, &gmt);
1767 char *s = 0;
1768 char buf[6];
1769 #ifdef HAVE_TM_ZONE
1770 if (t->tm_zone)
1771 s = (char *)t->tm_zone;
1772 #else /* not HAVE_TM_ZONE */
1773 #ifdef HAVE_TZNAME
1774 if (t->tm_isdst == 0 || t->tm_isdst == 1)
1775 s = tzname[t->tm_isdst];
1776 #endif
1777 #endif /* not HAVE_TM_ZONE */
1779 #if defined HAVE_TM_ZONE || defined HAVE_TZNAME
1780 if (s)
1782 /* On Japanese w32, we can get a Japanese string as time
1783 zone name. Don't accept that. */
1784 char *p;
1785 for (p = s; *p && (isalnum (*p) || *p == ' '); ++p)
1787 if (p == s || *p)
1788 s = NULL;
1790 #endif
1792 if (!s)
1794 /* No local time zone name is available; use "+-NNNN" instead. */
1795 int am = (offset < 0 ? -offset : offset) / 60;
1796 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
1797 s = buf;
1799 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
1801 else
1802 return Fmake_list (make_number (2), Qnil);
1805 /* This holds the value of `environ' produced by the previous
1806 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
1807 has never been called. */
1808 static char **environbuf;
1810 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
1811 "Set the local time zone using TZ, a string specifying a time zone rule.\n\
1812 If TZ is nil, use implementation-defined default time zone information.\n\
1813 If TZ is t, use Universal Time.")
1814 (tz)
1815 Lisp_Object tz;
1817 char *tzstring;
1819 if (NILP (tz))
1820 tzstring = 0;
1821 else if (EQ (tz, Qt))
1822 tzstring = "UTC0";
1823 else
1825 CHECK_STRING (tz, 0);
1826 tzstring = (char *) XSTRING (tz)->data;
1829 set_time_zone_rule (tzstring);
1830 if (environbuf)
1831 free (environbuf);
1832 environbuf = environ;
1834 return Qnil;
1837 #ifdef LOCALTIME_CACHE
1839 /* These two values are known to load tz files in buggy implementations,
1840 i.e. Solaris 1 executables running under either Solaris 1 or Solaris 2.
1841 Their values shouldn't matter in non-buggy implementations.
1842 We don't use string literals for these strings,
1843 since if a string in the environment is in readonly
1844 storage, it runs afoul of bugs in SVR4 and Solaris 2.3.
1845 See Sun bugs 1113095 and 1114114, ``Timezone routines
1846 improperly modify environment''. */
1848 static char set_time_zone_rule_tz1[] = "TZ=GMT+0";
1849 static char set_time_zone_rule_tz2[] = "TZ=GMT+1";
1851 #endif
1853 /* Set the local time zone rule to TZSTRING.
1854 This allocates memory into `environ', which it is the caller's
1855 responsibility to free. */
1857 void
1858 set_time_zone_rule (tzstring)
1859 char *tzstring;
1861 int envptrs;
1862 char **from, **to, **newenv;
1864 /* Make the ENVIRON vector longer with room for TZSTRING. */
1865 for (from = environ; *from; from++)
1866 continue;
1867 envptrs = from - environ + 2;
1868 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
1869 + (tzstring ? strlen (tzstring) + 4 : 0));
1871 /* Add TZSTRING to the end of environ, as a value for TZ. */
1872 if (tzstring)
1874 char *t = (char *) (to + envptrs);
1875 strcpy (t, "TZ=");
1876 strcat (t, tzstring);
1877 *to++ = t;
1880 /* Copy the old environ vector elements into NEWENV,
1881 but don't copy the TZ variable.
1882 So we have only one definition of TZ, which came from TZSTRING. */
1883 for (from = environ; *from; from++)
1884 if (strncmp (*from, "TZ=", 3) != 0)
1885 *to++ = *from;
1886 *to = 0;
1888 environ = newenv;
1890 /* If we do have a TZSTRING, NEWENV points to the vector slot where
1891 the TZ variable is stored. If we do not have a TZSTRING,
1892 TO points to the vector slot which has the terminating null. */
1894 #ifdef LOCALTIME_CACHE
1896 /* In SunOS 4.1.3_U1 and 4.1.4, if TZ has a value like
1897 "US/Pacific" that loads a tz file, then changes to a value like
1898 "XXX0" that does not load a tz file, and then changes back to
1899 its original value, the last change is (incorrectly) ignored.
1900 Also, if TZ changes twice in succession to values that do
1901 not load a tz file, tzset can dump core (see Sun bug#1225179).
1902 The following code works around these bugs. */
1904 if (tzstring)
1906 /* Temporarily set TZ to a value that loads a tz file
1907 and that differs from tzstring. */
1908 char *tz = *newenv;
1909 *newenv = (strcmp (tzstring, set_time_zone_rule_tz1 + 3) == 0
1910 ? set_time_zone_rule_tz2 : set_time_zone_rule_tz1);
1911 tzset ();
1912 *newenv = tz;
1914 else
1916 /* The implied tzstring is unknown, so temporarily set TZ to
1917 two different values that each load a tz file. */
1918 *to = set_time_zone_rule_tz1;
1919 to[1] = 0;
1920 tzset ();
1921 *to = set_time_zone_rule_tz2;
1922 tzset ();
1923 *to = 0;
1926 /* Now TZ has the desired value, and tzset can be invoked safely. */
1929 tzset ();
1930 #endif
1933 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
1934 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
1935 type of object is Lisp_String). INHERIT is passed to
1936 INSERT_FROM_STRING_FUNC as the last argument. */
1938 static void
1939 general_insert_function (insert_func, insert_from_string_func,
1940 inherit, nargs, args)
1941 void (*insert_func) P_ ((unsigned char *, int));
1942 void (*insert_from_string_func) P_ ((Lisp_Object, int, int, int, int, int));
1943 int inherit, nargs;
1944 register Lisp_Object *args;
1946 register int argnum;
1947 register Lisp_Object val;
1949 for (argnum = 0; argnum < nargs; argnum++)
1951 val = args[argnum];
1952 retry:
1953 if (INTEGERP (val))
1955 unsigned char str[MAX_MULTIBYTE_LENGTH];
1956 int len;
1958 if (!NILP (current_buffer->enable_multibyte_characters))
1959 len = CHAR_STRING (XFASTINT (val), str);
1960 else
1962 str[0] = (SINGLE_BYTE_CHAR_P (XINT (val))
1963 ? XINT (val)
1964 : multibyte_char_to_unibyte (XINT (val), Qnil));
1965 len = 1;
1967 (*insert_func) (str, len);
1969 else if (STRINGP (val))
1971 (*insert_from_string_func) (val, 0, 0,
1972 XSTRING (val)->size,
1973 STRING_BYTES (XSTRING (val)),
1974 inherit);
1976 else
1978 val = wrong_type_argument (Qchar_or_string_p, val);
1979 goto retry;
1984 void
1985 insert1 (arg)
1986 Lisp_Object arg;
1988 Finsert (1, &arg);
1992 /* Callers passing one argument to Finsert need not gcpro the
1993 argument "array", since the only element of the array will
1994 not be used after calling insert or insert_from_string, so
1995 we don't care if it gets trashed. */
1997 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
1998 "Insert the arguments, either strings or characters, at point.\n\
1999 Point and before-insertion markers move forward to end up\n\
2000 after the inserted text.\n\
2001 Any other markers at the point of insertion remain before the text.\n\
2003 If the current buffer is multibyte, unibyte strings are converted\n\
2004 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
2005 If the current buffer is unibyte, multibyte strings are converted\n\
2006 to unibyte for insertion.")
2007 (nargs, args)
2008 int nargs;
2009 register Lisp_Object *args;
2011 general_insert_function (insert, insert_from_string, 0, nargs, args);
2012 return Qnil;
2015 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2016 0, MANY, 0,
2017 "Insert the arguments at point, inheriting properties from adjoining text.\n\
2018 Point and before-insertion markers move forward to end up\n\
2019 after the inserted text.\n\
2020 Any other markers at the point of insertion remain before the text.\n\
2022 If the current buffer is multibyte, unibyte strings are converted\n\
2023 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
2024 If the current buffer is unibyte, multibyte strings are converted\n\
2025 to unibyte for insertion.")
2026 (nargs, args)
2027 int nargs;
2028 register Lisp_Object *args;
2030 general_insert_function (insert_and_inherit, insert_from_string, 1,
2031 nargs, args);
2032 return Qnil;
2035 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2036 "Insert strings or characters at point, relocating markers after the text.\n\
2037 Point and markers move forward to end up after the inserted text.\n\
2039 If the current buffer is multibyte, unibyte strings are converted\n\
2040 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
2041 If the current buffer is unibyte, multibyte strings are converted\n\
2042 to unibyte for insertion.")
2043 (nargs, args)
2044 int nargs;
2045 register Lisp_Object *args;
2047 general_insert_function (insert_before_markers,
2048 insert_from_string_before_markers, 0,
2049 nargs, args);
2050 return Qnil;
2053 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2054 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2055 "Insert text at point, relocating markers and inheriting properties.\n\
2056 Point and markers move forward to end up after the inserted text.\n\
2058 If the current buffer is multibyte, unibyte strings are converted\n\
2059 to multibyte for insertion (see `unibyte-char-to-multibyte').\n\
2060 If the current buffer is unibyte, multibyte strings are converted\n\
2061 to unibyte for insertion.")
2062 (nargs, args)
2063 int nargs;
2064 register Lisp_Object *args;
2066 general_insert_function (insert_before_markers_and_inherit,
2067 insert_from_string_before_markers, 1,
2068 nargs, args);
2069 return Qnil;
2072 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
2073 "Insert COUNT (second arg) copies of CHARACTER (first arg).\n\
2074 Both arguments are required.\n\
2075 Point, and before-insertion markers, are relocated as in the function `insert'.\n\
2076 The optional third arg INHERIT, if non-nil, says to inherit text properties\n\
2077 from adjoining text, if those properties are sticky.")
2078 (character, count, inherit)
2079 Lisp_Object character, count, inherit;
2081 register unsigned char *string;
2082 register int strlen;
2083 register int i, n;
2084 int len;
2085 unsigned char str[MAX_MULTIBYTE_LENGTH];
2087 CHECK_NUMBER (character, 0);
2088 CHECK_NUMBER (count, 1);
2090 if (!NILP (current_buffer->enable_multibyte_characters))
2091 len = CHAR_STRING (XFASTINT (character), str);
2092 else
2093 str[0] = XFASTINT (character), len = 1;
2094 n = XINT (count) * len;
2095 if (n <= 0)
2096 return Qnil;
2097 strlen = min (n, 256 * len);
2098 string = (unsigned char *) alloca (strlen);
2099 for (i = 0; i < strlen; i++)
2100 string[i] = str[i % len];
2101 while (n >= strlen)
2103 QUIT;
2104 if (!NILP (inherit))
2105 insert_and_inherit (string, strlen);
2106 else
2107 insert (string, strlen);
2108 n -= strlen;
2110 if (n > 0)
2112 if (!NILP (inherit))
2113 insert_and_inherit (string, n);
2114 else
2115 insert (string, n);
2117 return Qnil;
2121 /* Making strings from buffer contents. */
2123 /* Return a Lisp_String containing the text of the current buffer from
2124 START to END. If text properties are in use and the current buffer
2125 has properties in the range specified, the resulting string will also
2126 have them, if PROPS is nonzero.
2128 We don't want to use plain old make_string here, because it calls
2129 make_uninit_string, which can cause the buffer arena to be
2130 compacted. make_string has no way of knowing that the data has
2131 been moved, and thus copies the wrong data into the string. This
2132 doesn't effect most of the other users of make_string, so it should
2133 be left as is. But we should use this function when conjuring
2134 buffer substrings. */
2136 Lisp_Object
2137 make_buffer_string (start, end, props)
2138 int start, end;
2139 int props;
2141 int start_byte = CHAR_TO_BYTE (start);
2142 int end_byte = CHAR_TO_BYTE (end);
2144 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2147 /* Return a Lisp_String containing the text of the current buffer from
2148 START / START_BYTE to END / END_BYTE.
2150 If text properties are in use and the current buffer
2151 has properties in the range specified, the resulting string will also
2152 have them, if PROPS is nonzero.
2154 We don't want to use plain old make_string here, because it calls
2155 make_uninit_string, which can cause the buffer arena to be
2156 compacted. make_string has no way of knowing that the data has
2157 been moved, and thus copies the wrong data into the string. This
2158 doesn't effect most of the other users of make_string, so it should
2159 be left as is. But we should use this function when conjuring
2160 buffer substrings. */
2162 Lisp_Object
2163 make_buffer_string_both (start, start_byte, end, end_byte, props)
2164 int start, start_byte, end, end_byte;
2165 int props;
2167 Lisp_Object result, tem, tem1;
2169 if (start < GPT && GPT < end)
2170 move_gap (start);
2172 if (! NILP (current_buffer->enable_multibyte_characters))
2173 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2174 else
2175 result = make_uninit_string (end - start);
2176 bcopy (BYTE_POS_ADDR (start_byte), XSTRING (result)->data,
2177 end_byte - start_byte);
2179 /* If desired, update and copy the text properties. */
2180 if (props)
2182 update_buffer_properties (start, end);
2184 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2185 tem1 = Ftext_properties_at (make_number (start), Qnil);
2187 if (XINT (tem) != end || !NILP (tem1))
2188 copy_intervals_to_string (result, current_buffer, start,
2189 end - start);
2192 return result;
2195 /* Call Vbuffer_access_fontify_functions for the range START ... END
2196 in the current buffer, if necessary. */
2198 static void
2199 update_buffer_properties (start, end)
2200 int start, end;
2202 /* If this buffer has some access functions,
2203 call them, specifying the range of the buffer being accessed. */
2204 if (!NILP (Vbuffer_access_fontify_functions))
2206 Lisp_Object args[3];
2207 Lisp_Object tem;
2209 args[0] = Qbuffer_access_fontify_functions;
2210 XSETINT (args[1], start);
2211 XSETINT (args[2], end);
2213 /* But don't call them if we can tell that the work
2214 has already been done. */
2215 if (!NILP (Vbuffer_access_fontified_property))
2217 tem = Ftext_property_any (args[1], args[2],
2218 Vbuffer_access_fontified_property,
2219 Qnil, Qnil);
2220 if (! NILP (tem))
2221 Frun_hook_with_args (3, args);
2223 else
2224 Frun_hook_with_args (3, args);
2228 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2229 "Return the contents of part of the current buffer as a string.\n\
2230 The two arguments START and END are character positions;\n\
2231 they can be in either order.\n\
2232 The string returned is multibyte if the buffer is multibyte.\n\
2234 This function copies the text properties of that part of the buffer\n\
2235 into the result string; if you don't want the text properties,\n\
2236 use `buffer-substring-no-properties' instead.")
2237 (start, end)
2238 Lisp_Object start, end;
2240 register int b, e;
2242 validate_region (&start, &end);
2243 b = XINT (start);
2244 e = XINT (end);
2246 return make_buffer_string (b, e, 1);
2249 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2250 Sbuffer_substring_no_properties, 2, 2, 0,
2251 "Return the characters of part of the buffer, without the text properties.\n\
2252 The two arguments START and END are character positions;\n\
2253 they can be in either order.")
2254 (start, end)
2255 Lisp_Object start, end;
2257 register int b, e;
2259 validate_region (&start, &end);
2260 b = XINT (start);
2261 e = XINT (end);
2263 return make_buffer_string (b, e, 0);
2266 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2267 "Return the contents of the current buffer as a string.\n\
2268 If narrowing is in effect, this function returns only the visible part\n\
2269 of the buffer.")
2272 return make_buffer_string (BEGV, ZV, 1);
2275 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2276 1, 3, 0,
2277 "Insert before point a substring of the contents of buffer BUFFER.\n\
2278 BUFFER may be a buffer or a buffer name.\n\
2279 Arguments START and END are character numbers specifying the substring.\n\
2280 They default to the beginning and the end of BUFFER.")
2281 (buf, start, end)
2282 Lisp_Object buf, start, end;
2284 register int b, e, temp;
2285 register struct buffer *bp, *obuf;
2286 Lisp_Object buffer;
2288 buffer = Fget_buffer (buf);
2289 if (NILP (buffer))
2290 nsberror (buf);
2291 bp = XBUFFER (buffer);
2292 if (NILP (bp->name))
2293 error ("Selecting deleted buffer");
2295 if (NILP (start))
2296 b = BUF_BEGV (bp);
2297 else
2299 CHECK_NUMBER_COERCE_MARKER (start, 0);
2300 b = XINT (start);
2302 if (NILP (end))
2303 e = BUF_ZV (bp);
2304 else
2306 CHECK_NUMBER_COERCE_MARKER (end, 1);
2307 e = XINT (end);
2310 if (b > e)
2311 temp = b, b = e, e = temp;
2313 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2314 args_out_of_range (start, end);
2316 obuf = current_buffer;
2317 set_buffer_internal_1 (bp);
2318 update_buffer_properties (b, e);
2319 set_buffer_internal_1 (obuf);
2321 insert_from_buffer (bp, b, e - b, 0);
2322 return Qnil;
2325 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2326 6, 6, 0,
2327 "Compare two substrings of two buffers; return result as number.\n\
2328 the value is -N if first string is less after N-1 chars,\n\
2329 +N if first string is greater after N-1 chars, or 0 if strings match.\n\
2330 Each substring is represented as three arguments: BUFFER, START and END.\n\
2331 That makes six args in all, three for each substring.\n\n\
2332 The value of `case-fold-search' in the current buffer\n\
2333 determines whether case is significant or ignored.")
2334 (buffer1, start1, end1, buffer2, start2, end2)
2335 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
2337 register int begp1, endp1, begp2, endp2, temp;
2338 register struct buffer *bp1, *bp2;
2339 register Lisp_Object *trt
2340 = (!NILP (current_buffer->case_fold_search)
2341 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents : 0);
2342 int chars = 0;
2343 int i1, i2, i1_byte, i2_byte;
2345 /* Find the first buffer and its substring. */
2347 if (NILP (buffer1))
2348 bp1 = current_buffer;
2349 else
2351 Lisp_Object buf1;
2352 buf1 = Fget_buffer (buffer1);
2353 if (NILP (buf1))
2354 nsberror (buffer1);
2355 bp1 = XBUFFER (buf1);
2356 if (NILP (bp1->name))
2357 error ("Selecting deleted buffer");
2360 if (NILP (start1))
2361 begp1 = BUF_BEGV (bp1);
2362 else
2364 CHECK_NUMBER_COERCE_MARKER (start1, 1);
2365 begp1 = XINT (start1);
2367 if (NILP (end1))
2368 endp1 = BUF_ZV (bp1);
2369 else
2371 CHECK_NUMBER_COERCE_MARKER (end1, 2);
2372 endp1 = XINT (end1);
2375 if (begp1 > endp1)
2376 temp = begp1, begp1 = endp1, endp1 = temp;
2378 if (!(BUF_BEGV (bp1) <= begp1
2379 && begp1 <= endp1
2380 && endp1 <= BUF_ZV (bp1)))
2381 args_out_of_range (start1, end1);
2383 /* Likewise for second substring. */
2385 if (NILP (buffer2))
2386 bp2 = current_buffer;
2387 else
2389 Lisp_Object buf2;
2390 buf2 = Fget_buffer (buffer2);
2391 if (NILP (buf2))
2392 nsberror (buffer2);
2393 bp2 = XBUFFER (buf2);
2394 if (NILP (bp2->name))
2395 error ("Selecting deleted buffer");
2398 if (NILP (start2))
2399 begp2 = BUF_BEGV (bp2);
2400 else
2402 CHECK_NUMBER_COERCE_MARKER (start2, 4);
2403 begp2 = XINT (start2);
2405 if (NILP (end2))
2406 endp2 = BUF_ZV (bp2);
2407 else
2409 CHECK_NUMBER_COERCE_MARKER (end2, 5);
2410 endp2 = XINT (end2);
2413 if (begp2 > endp2)
2414 temp = begp2, begp2 = endp2, endp2 = temp;
2416 if (!(BUF_BEGV (bp2) <= begp2
2417 && begp2 <= endp2
2418 && endp2 <= BUF_ZV (bp2)))
2419 args_out_of_range (start2, end2);
2421 i1 = begp1;
2422 i2 = begp2;
2423 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2424 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2426 while (i1 < endp1 && i2 < endp2)
2428 /* When we find a mismatch, we must compare the
2429 characters, not just the bytes. */
2430 int c1, c2;
2432 if (! NILP (bp1->enable_multibyte_characters))
2434 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2435 BUF_INC_POS (bp1, i1_byte);
2436 i1++;
2438 else
2440 c1 = BUF_FETCH_BYTE (bp1, i1);
2441 c1 = unibyte_char_to_multibyte (c1);
2442 i1++;
2445 if (! NILP (bp2->enable_multibyte_characters))
2447 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2448 BUF_INC_POS (bp2, i2_byte);
2449 i2++;
2451 else
2453 c2 = BUF_FETCH_BYTE (bp2, i2);
2454 c2 = unibyte_char_to_multibyte (c2);
2455 i2++;
2458 if (trt)
2460 c1 = XINT (trt[c1]);
2461 c2 = XINT (trt[c2]);
2463 if (c1 < c2)
2464 return make_number (- 1 - chars);
2465 if (c1 > c2)
2466 return make_number (chars + 1);
2468 chars++;
2471 /* The strings match as far as they go.
2472 If one is shorter, that one is less. */
2473 if (chars < endp1 - begp1)
2474 return make_number (chars + 1);
2475 else if (chars < endp2 - begp2)
2476 return make_number (- chars - 1);
2478 /* Same length too => they are equal. */
2479 return make_number (0);
2482 static Lisp_Object
2483 subst_char_in_region_unwind (arg)
2484 Lisp_Object arg;
2486 return current_buffer->undo_list = arg;
2489 static Lisp_Object
2490 subst_char_in_region_unwind_1 (arg)
2491 Lisp_Object arg;
2493 return current_buffer->filename = arg;
2496 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2497 Ssubst_char_in_region, 4, 5, 0,
2498 "From START to END, replace FROMCHAR with TOCHAR each time it occurs.\n\
2499 If optional arg NOUNDO is non-nil, don't record this change for undo\n\
2500 and don't mark the buffer as really changed.\n\
2501 Both characters must have the same length of multi-byte form.")
2502 (start, end, fromchar, tochar, noundo)
2503 Lisp_Object start, end, fromchar, tochar, noundo;
2505 register int pos, pos_byte, stop, i, len, end_byte;
2506 int changed = 0;
2507 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2508 unsigned char *p;
2509 int count = specpdl_ptr - specpdl;
2510 #define COMBINING_NO 0
2511 #define COMBINING_BEFORE 1
2512 #define COMBINING_AFTER 2
2513 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2514 int maybe_byte_combining = COMBINING_NO;
2515 int last_changed = 0;
2516 int multibyte_p = !NILP (current_buffer->enable_multibyte_characters);
2518 validate_region (&start, &end);
2519 CHECK_NUMBER (fromchar, 2);
2520 CHECK_NUMBER (tochar, 3);
2522 if (multibyte_p)
2524 len = CHAR_STRING (XFASTINT (fromchar), fromstr);
2525 if (CHAR_STRING (XFASTINT (tochar), tostr) != len)
2526 error ("Characters in subst-char-in-region have different byte-lengths");
2527 if (!ASCII_BYTE_P (*tostr))
2529 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
2530 complete multibyte character, it may be combined with the
2531 after bytes. If it is in the range 0xA0..0xFF, it may be
2532 combined with the before and after bytes. */
2533 if (!CHAR_HEAD_P (*tostr))
2534 maybe_byte_combining = COMBINING_BOTH;
2535 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
2536 maybe_byte_combining = COMBINING_AFTER;
2539 else
2541 len = 1;
2542 fromstr[0] = XFASTINT (fromchar);
2543 tostr[0] = XFASTINT (tochar);
2546 pos = XINT (start);
2547 pos_byte = CHAR_TO_BYTE (pos);
2548 stop = CHAR_TO_BYTE (XINT (end));
2549 end_byte = stop;
2551 /* If we don't want undo, turn off putting stuff on the list.
2552 That's faster than getting rid of things,
2553 and it prevents even the entry for a first change.
2554 Also inhibit locking the file. */
2555 if (!NILP (noundo))
2557 record_unwind_protect (subst_char_in_region_unwind,
2558 current_buffer->undo_list);
2559 current_buffer->undo_list = Qt;
2560 /* Don't do file-locking. */
2561 record_unwind_protect (subst_char_in_region_unwind_1,
2562 current_buffer->filename);
2563 current_buffer->filename = Qnil;
2566 if (pos_byte < GPT_BYTE)
2567 stop = min (stop, GPT_BYTE);
2568 while (1)
2570 int pos_byte_next = pos_byte;
2572 if (pos_byte >= stop)
2574 if (pos_byte >= end_byte) break;
2575 stop = end_byte;
2577 p = BYTE_POS_ADDR (pos_byte);
2578 if (multibyte_p)
2579 INC_POS (pos_byte_next);
2580 else
2581 ++pos_byte_next;
2582 if (pos_byte_next - pos_byte == len
2583 && p[0] == fromstr[0]
2584 && (len == 1
2585 || (p[1] == fromstr[1]
2586 && (len == 2 || (p[2] == fromstr[2]
2587 && (len == 3 || p[3] == fromstr[3]))))))
2589 if (! changed)
2591 changed = pos;
2592 modify_region (current_buffer, changed, XINT (end));
2594 if (! NILP (noundo))
2596 if (MODIFF - 1 == SAVE_MODIFF)
2597 SAVE_MODIFF++;
2598 if (MODIFF - 1 == current_buffer->auto_save_modified)
2599 current_buffer->auto_save_modified++;
2603 /* Take care of the case where the new character
2604 combines with neighboring bytes. */
2605 if (maybe_byte_combining
2606 && (maybe_byte_combining == COMBINING_AFTER
2607 ? (pos_byte_next < Z_BYTE
2608 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2609 : ((pos_byte_next < Z_BYTE
2610 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
2611 || (pos_byte > BEG_BYTE
2612 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1))))))
2614 Lisp_Object tem, string;
2616 struct gcpro gcpro1;
2618 tem = current_buffer->undo_list;
2619 GCPRO1 (tem);
2621 /* Make a multibyte string containing this single character. */
2622 string = make_multibyte_string (tostr, 1, len);
2623 /* replace_range is less efficient, because it moves the gap,
2624 but it handles combining correctly. */
2625 replace_range (pos, pos + 1, string,
2626 0, 0, 1);
2627 pos_byte_next = CHAR_TO_BYTE (pos);
2628 if (pos_byte_next > pos_byte)
2629 /* Before combining happened. We should not increment
2630 POS. So, to cancel the later increment of POS,
2631 decrease it now. */
2632 pos--;
2633 else
2634 INC_POS (pos_byte_next);
2636 if (! NILP (noundo))
2637 current_buffer->undo_list = tem;
2639 UNGCPRO;
2641 else
2643 if (NILP (noundo))
2644 record_change (pos, 1);
2645 for (i = 0; i < len; i++) *p++ = tostr[i];
2647 last_changed = pos + 1;
2649 pos_byte = pos_byte_next;
2650 pos++;
2653 if (changed)
2655 signal_after_change (changed,
2656 last_changed - changed, last_changed - changed);
2657 update_compositions (changed, last_changed, CHECK_ALL);
2660 unbind_to (count, Qnil);
2661 return Qnil;
2664 DEFUN ("translate-region", Ftranslate_region, Stranslate_region, 3, 3, 0,
2665 "From START to END, translate characters according to TABLE.\n\
2666 TABLE is a string; the Nth character in it is the mapping\n\
2667 for the character with code N.\n\
2668 This function does not alter multibyte characters.\n\
2669 It returns the number of characters changed.")
2670 (start, end, table)
2671 Lisp_Object start;
2672 Lisp_Object end;
2673 register Lisp_Object table;
2675 register int pos_byte, stop; /* Limits of the region. */
2676 register unsigned char *tt; /* Trans table. */
2677 register int nc; /* New character. */
2678 int cnt; /* Number of changes made. */
2679 int size; /* Size of translate table. */
2680 int pos;
2681 int multibyte = !NILP (current_buffer->enable_multibyte_characters);
2683 validate_region (&start, &end);
2684 CHECK_STRING (table, 2);
2686 size = STRING_BYTES (XSTRING (table));
2687 tt = XSTRING (table)->data;
2689 pos_byte = CHAR_TO_BYTE (XINT (start));
2690 stop = CHAR_TO_BYTE (XINT (end));
2691 modify_region (current_buffer, XINT (start), XINT (end));
2692 pos = XINT (start);
2694 cnt = 0;
2695 for (; pos_byte < stop; )
2697 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
2698 int len;
2699 int oc;
2700 int pos_byte_next;
2702 if (multibyte)
2703 oc = STRING_CHAR_AND_LENGTH (p, stop - pos_byte, len);
2704 else
2705 oc = *p, len = 1;
2706 pos_byte_next = pos_byte + len;
2707 if (oc < size && len == 1)
2709 nc = tt[oc];
2710 if (nc != oc)
2712 /* Take care of the case where the new character
2713 combines with neighboring bytes. */
2714 if (!ASCII_BYTE_P (nc)
2715 && (CHAR_HEAD_P (nc)
2716 ? ! CHAR_HEAD_P (FETCH_BYTE (pos_byte + 1))
2717 : (pos_byte > BEG_BYTE
2718 && ! ASCII_BYTE_P (FETCH_BYTE (pos_byte - 1)))))
2720 Lisp_Object string;
2722 string = make_multibyte_string (tt + oc, 1, 1);
2723 /* This is less efficient, because it moves the gap,
2724 but it handles combining correctly. */
2725 replace_range (pos, pos + 1, string,
2726 1, 0, 1);
2727 pos_byte_next = CHAR_TO_BYTE (pos);
2728 if (pos_byte_next > pos_byte)
2729 /* Before combining happened. We should not
2730 increment POS. So, to cancel the later
2731 increment of POS, we decrease it now. */
2732 pos--;
2733 else
2734 INC_POS (pos_byte_next);
2736 else
2738 record_change (pos, 1);
2739 *p = nc;
2740 signal_after_change (pos, 1, 1);
2741 update_compositions (pos, pos + 1, CHECK_BORDER);
2743 ++cnt;
2746 pos_byte = pos_byte_next;
2747 pos++;
2750 return make_number (cnt);
2753 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
2754 "Delete the text between point and mark.\n\
2755 When called from a program, expects two arguments,\n\
2756 positions (integers or markers) specifying the stretch to be deleted.")
2757 (start, end)
2758 Lisp_Object start, end;
2760 validate_region (&start, &end);
2761 del_range (XINT (start), XINT (end));
2762 return Qnil;
2765 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
2766 Sdelete_and_extract_region, 2, 2, 0,
2767 "Delete the text between START and END and return it.")
2768 (start, end)
2769 Lisp_Object start, end;
2771 validate_region (&start, &end);
2772 return del_range_1 (XINT (start), XINT (end), 1, 1);
2775 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
2776 "Remove restrictions (narrowing) from current buffer.\n\
2777 This allows the buffer's full text to be seen and edited.")
2780 if (BEG != BEGV || Z != ZV)
2781 current_buffer->clip_changed = 1;
2782 BEGV = BEG;
2783 BEGV_BYTE = BEG_BYTE;
2784 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
2785 /* Changing the buffer bounds invalidates any recorded current column. */
2786 invalidate_current_column ();
2787 return Qnil;
2790 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
2791 "Restrict editing in this buffer to the current region.\n\
2792 The rest of the text becomes temporarily invisible and untouchable\n\
2793 but is not deleted; if you save the buffer in a file, the invisible\n\
2794 text is included in the file. \\[widen] makes all visible again.\n\
2795 See also `save-restriction'.\n\
2797 When calling from a program, pass two arguments; positions (integers\n\
2798 or markers) bounding the text that should remain visible.")
2799 (start, end)
2800 register Lisp_Object start, end;
2802 CHECK_NUMBER_COERCE_MARKER (start, 0);
2803 CHECK_NUMBER_COERCE_MARKER (end, 1);
2805 if (XINT (start) > XINT (end))
2807 Lisp_Object tem;
2808 tem = start; start = end; end = tem;
2811 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
2812 args_out_of_range (start, end);
2814 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
2815 current_buffer->clip_changed = 1;
2817 SET_BUF_BEGV (current_buffer, XFASTINT (start));
2818 SET_BUF_ZV (current_buffer, XFASTINT (end));
2819 if (PT < XFASTINT (start))
2820 SET_PT (XFASTINT (start));
2821 if (PT > XFASTINT (end))
2822 SET_PT (XFASTINT (end));
2823 /* Changing the buffer bounds invalidates any recorded current column. */
2824 invalidate_current_column ();
2825 return Qnil;
2828 Lisp_Object
2829 save_restriction_save ()
2831 if (BEGV == BEG && ZV == Z)
2832 /* The common case that the buffer isn't narrowed.
2833 We return just the buffer object, which save_restriction_restore
2834 recognizes as meaning `no restriction'. */
2835 return Fcurrent_buffer ();
2836 else
2837 /* We have to save a restriction, so return a pair of markers, one
2838 for the beginning and one for the end. */
2840 Lisp_Object beg, end;
2842 beg = buildmark (BEGV, BEGV_BYTE);
2843 end = buildmark (ZV, ZV_BYTE);
2845 /* END must move forward if text is inserted at its exact location. */
2846 XMARKER(end)->insertion_type = 1;
2848 return Fcons (beg, end);
2852 Lisp_Object
2853 save_restriction_restore (data)
2854 Lisp_Object data;
2856 if (CONSP (data))
2857 /* A pair of marks bounding a saved restriction. */
2859 struct Lisp_Marker *beg = XMARKER (XCAR (data));
2860 struct Lisp_Marker *end = XMARKER (XCDR (data));
2861 struct buffer *buf = beg->buffer; /* END should have the same buffer. */
2863 if (beg->charpos != BUF_BEGV(buf) || end->charpos != BUF_ZV(buf))
2864 /* The restriction has changed from the saved one, so restore
2865 the saved restriction. */
2867 int pt = BUF_PT (buf);
2869 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
2870 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
2872 if (pt < beg->charpos || pt > end->charpos)
2873 /* The point is outside the new visible range, move it inside. */
2874 SET_BUF_PT_BOTH (buf,
2875 clip_to_bounds (beg->charpos, pt, end->charpos),
2876 clip_to_bounds (beg->bytepos, BUF_PT_BYTE(buf),
2877 end->bytepos));
2879 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2882 else
2883 /* A buffer, which means that there was no old restriction. */
2885 struct buffer *buf = XBUFFER (data);
2887 if (BUF_BEGV(buf) != BUF_BEG(buf) || BUF_ZV(buf) != BUF_Z(buf))
2888 /* The buffer has been narrowed, get rid of the narrowing. */
2890 SET_BUF_BEGV_BOTH (buf, BUF_BEG(buf), BUF_BEG_BYTE(buf));
2891 SET_BUF_ZV_BOTH (buf, BUF_Z(buf), BUF_Z_BYTE(buf));
2893 buf->clip_changed = 1; /* Remember that the narrowing changed. */
2897 return Qnil;
2900 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
2901 "Execute BODY, saving and restoring current buffer's restrictions.\n\
2902 The buffer's restrictions make parts of the beginning and end invisible.\n\
2903 \(They are set up with `narrow-to-region' and eliminated with `widen'.)\n\
2904 This special form, `save-restriction', saves the current buffer's restrictions\n\
2905 when it is entered, and restores them when it is exited.\n\
2906 So any `narrow-to-region' within BODY lasts only until the end of the form.\n\
2907 The old restrictions settings are restored\n\
2908 even in case of abnormal exit (throw or error).\n\
2910 The value returned is the value of the last form in BODY.\n\
2912 Note: if you are using both `save-excursion' and `save-restriction',\n\
2913 use `save-excursion' outermost:\n\
2914 (save-excursion (save-restriction ...))")
2915 (body)
2916 Lisp_Object body;
2918 register Lisp_Object val;
2919 int count = specpdl_ptr - specpdl;
2921 record_unwind_protect (save_restriction_restore, save_restriction_save ());
2922 val = Fprogn (body);
2923 return unbind_to (count, val);
2926 /* Buffer for the most recent text displayed by Fmessage_box. */
2927 static char *message_text;
2929 /* Allocated length of that buffer. */
2930 static int message_length;
2932 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
2933 "Print a one-line message at the bottom of the screen.\n\
2934 The first argument is a format control string, and the rest are data\n\
2935 to be formatted under control of the string. See `format' for details.\n\
2937 If the first argument is nil, clear any existing message; let the\n\
2938 minibuffer contents show.")
2939 (nargs, args)
2940 int nargs;
2941 Lisp_Object *args;
2943 if (NILP (args[0]))
2945 message (0);
2946 return Qnil;
2948 else
2950 register Lisp_Object val;
2951 val = Fformat (nargs, args);
2952 message3 (val, STRING_BYTES (XSTRING (val)), STRING_MULTIBYTE (val));
2953 return val;
2957 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
2958 "Display a message, in a dialog box if possible.\n\
2959 If a dialog box is not available, use the echo area.\n\
2960 The first argument is a format control string, and the rest are data\n\
2961 to be formatted under control of the string. See `format' for details.\n\
2963 If the first argument is nil, clear any existing message; let the\n\
2964 minibuffer contents show.")
2965 (nargs, args)
2966 int nargs;
2967 Lisp_Object *args;
2969 if (NILP (args[0]))
2971 message (0);
2972 return Qnil;
2974 else
2976 register Lisp_Object val;
2977 val = Fformat (nargs, args);
2978 #ifdef HAVE_MENUS
2979 /* The MS-DOS frames support popup menus even though they are
2980 not FRAME_WINDOW_P. */
2981 if (FRAME_WINDOW_P (XFRAME (selected_frame))
2982 || FRAME_MSDOS_P (XFRAME (selected_frame)))
2984 Lisp_Object pane, menu, obj;
2985 struct gcpro gcpro1;
2986 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
2987 GCPRO1 (pane);
2988 menu = Fcons (val, pane);
2989 obj = Fx_popup_dialog (Qt, menu);
2990 UNGCPRO;
2991 return val;
2993 #endif /* HAVE_MENUS */
2994 /* Copy the data so that it won't move when we GC. */
2995 if (! message_text)
2997 message_text = (char *)xmalloc (80);
2998 message_length = 80;
3000 if (STRING_BYTES (XSTRING (val)) > message_length)
3002 message_length = STRING_BYTES (XSTRING (val));
3003 message_text = (char *)xrealloc (message_text, message_length);
3005 bcopy (XSTRING (val)->data, message_text, STRING_BYTES (XSTRING (val)));
3006 message2 (message_text, STRING_BYTES (XSTRING (val)),
3007 STRING_MULTIBYTE (val));
3008 return val;
3011 #ifdef HAVE_MENUS
3012 extern Lisp_Object last_nonmenu_event;
3013 #endif
3015 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3016 "Display a message in a dialog box or in the echo area.\n\
3017 If this command was invoked with the mouse, use a dialog box if\n\
3018 `use-dialog-box' is non-nil.\n\
3019 Otherwise, use the echo area.\n\
3020 The first argument is a format control string, and the rest are data\n\
3021 to be formatted under control of the string. See `format' for details.\n\
3023 If the first argument is nil, clear any existing message; let the\n\
3024 minibuffer contents show.")
3025 (nargs, args)
3026 int nargs;
3027 Lisp_Object *args;
3029 #ifdef HAVE_MENUS
3030 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3031 && use_dialog_box)
3032 return Fmessage_box (nargs, args);
3033 #endif
3034 return Fmessage (nargs, args);
3037 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3038 "Return the string currently displayed in the echo area, or nil if none.")
3041 return current_message ();
3045 DEFUN ("propertize", Fpropertize, Spropertize, 3, MANY, 0,
3046 "Return a copy of STRING with text properties added.\n\
3047 First argument is the string to copy.\n\
3048 Remaining arguments form a sequence of PROPERTY VALUE pairs for text\n\
3049 properties to add to the result ")
3050 (nargs, args)
3051 int nargs;
3052 Lisp_Object *args;
3054 Lisp_Object properties, string;
3055 struct gcpro gcpro1, gcpro2;
3056 int i;
3058 /* Number of args must be odd. */
3059 if ((nargs & 1) == 0 || nargs < 3)
3060 error ("Wrong number of arguments");
3062 properties = string = Qnil;
3063 GCPRO2 (properties, string);
3065 /* First argument must be a string. */
3066 CHECK_STRING (args[0], 0);
3067 string = Fcopy_sequence (args[0]);
3069 for (i = 1; i < nargs; i += 2)
3071 CHECK_SYMBOL (args[i], i);
3072 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3075 Fadd_text_properties (make_number (0),
3076 make_number (XSTRING (string)->size),
3077 properties, string);
3078 RETURN_UNGCPRO (string);
3082 /* Number of bytes that STRING will occupy when put into the result.
3083 MULTIBYTE is nonzero if the result should be multibyte. */
3085 #define CONVERTED_BYTE_SIZE(MULTIBYTE, STRING) \
3086 (((MULTIBYTE) && ! STRING_MULTIBYTE (STRING)) \
3087 ? count_size_as_multibyte (XSTRING (STRING)->data, \
3088 STRING_BYTES (XSTRING (STRING))) \
3089 : STRING_BYTES (XSTRING (STRING)))
3091 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3092 "Format a string out of a control-string and arguments.\n\
3093 The first argument is a control string.\n\
3094 The other arguments are substituted into it to make the result, a string.\n\
3095 It may contain %-sequences meaning to substitute the next argument.\n\
3096 %s means print a string argument. Actually, prints any object, with `princ'.\n\
3097 %d means print as number in decimal (%o octal, %x hex).\n\
3098 %X is like %x, but uses upper case.\n\
3099 %e means print a number in exponential notation.\n\
3100 %f means print a number in decimal-point notation.\n\
3101 %g means print a number in exponential notation\n\
3102 or decimal-point notation, whichever uses fewer characters.\n\
3103 %c means print a number as a single character.\n\
3104 %S means print any object as an s-expression (using `prin1').\n\
3105 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.\n\
3106 Use %% to put a single % into the output.")
3107 (nargs, args)
3108 int nargs;
3109 register Lisp_Object *args;
3111 register int n; /* The number of the next arg to substitute */
3112 register int total; /* An estimate of the final length */
3113 char *buf, *p;
3114 register unsigned char *format, *end;
3115 int nchars;
3116 /* Nonzero if the output should be a multibyte string,
3117 which is true if any of the inputs is one. */
3118 int multibyte = 0;
3119 /* When we make a multibyte string, we must pay attention to the
3120 byte combining problem, i.e., a byte may be combined with a
3121 multibyte charcter of the previous string. This flag tells if we
3122 must consider such a situation or not. */
3123 int maybe_combine_byte;
3124 unsigned char *this_format;
3125 int longest_format;
3126 Lisp_Object val;
3127 struct info
3129 int start, end;
3130 } *info = 0;
3132 /* It should not be necessary to GCPRO ARGS, because
3133 the caller in the interpreter should take care of that. */
3135 /* Try to determine whether the result should be multibyte.
3136 This is not always right; sometimes the result needs to be multibyte
3137 because of an object that we will pass through prin1,
3138 and in that case, we won't know it here. */
3139 for (n = 0; n < nargs; n++)
3140 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3141 multibyte = 1;
3143 CHECK_STRING (args[0], 0);
3145 /* If we start out planning a unibyte result,
3146 and later find it has to be multibyte, we jump back to retry. */
3147 retry:
3149 format = XSTRING (args[0])->data;
3150 end = format + STRING_BYTES (XSTRING (args[0]));
3151 longest_format = 0;
3153 /* Make room in result for all the non-%-codes in the control string. */
3154 total = 5 + CONVERTED_BYTE_SIZE (multibyte, args[0]);
3156 /* Add to TOTAL enough space to hold the converted arguments. */
3158 n = 0;
3159 while (format != end)
3160 if (*format++ == '%')
3162 int thissize = 0;
3163 unsigned char *this_format_start = format - 1;
3164 int field_width, precision;
3166 /* General format specifications look like
3168 '%' [flags] [field-width] [precision] format
3170 where
3172 flags ::= [#-* 0]+
3173 field-width ::= [0-9]+
3174 precision ::= '.' [0-9]*
3176 If a field-width is specified, it specifies to which width
3177 the output should be padded with blanks, iff the output
3178 string is shorter than field-width.
3180 if precision is specified, it specifies the number of
3181 digits to print after the '.' for floats, or the max.
3182 number of chars to print from a string. */
3184 precision = field_width = 0;
3186 while (index ("-*# 0", *format))
3187 ++format;
3189 if (*format >= '0' && *format <= '9')
3191 for (field_width = 0; *format >= '0' && *format <= '9'; ++format)
3192 field_width = 10 * field_width + *format - '0';
3195 if (*format == '.')
3197 ++format;
3198 for (precision = 0; *format >= '0' && *format <= '9'; ++format)
3199 precision = 10 * precision + *format - '0';
3202 if (format - this_format_start + 1 > longest_format)
3203 longest_format = format - this_format_start + 1;
3205 if (format == end)
3206 error ("Format string ends in middle of format specifier");
3207 if (*format == '%')
3208 format++;
3209 else if (++n >= nargs)
3210 error ("Not enough arguments for format string");
3211 else if (*format == 'S')
3213 /* For `S', prin1 the argument and then treat like a string. */
3214 register Lisp_Object tem;
3215 tem = Fprin1_to_string (args[n], Qnil);
3216 if (STRING_MULTIBYTE (tem) && ! multibyte)
3218 multibyte = 1;
3219 goto retry;
3221 args[n] = tem;
3222 goto string;
3224 else if (SYMBOLP (args[n]))
3226 /* Use a temp var to avoid problems when ENABLE_CHECKING
3227 is turned on. */
3228 struct Lisp_String *t = XSYMBOL (args[n])->name;
3229 XSETSTRING (args[n], t);
3230 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3232 multibyte = 1;
3233 goto retry;
3235 goto string;
3237 else if (STRINGP (args[n]))
3239 string:
3240 if (*format != 's' && *format != 'S')
3241 error ("Format specifier doesn't match argument type");
3242 thissize = CONVERTED_BYTE_SIZE (multibyte, args[n]);
3244 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
3245 else if (INTEGERP (args[n]) && *format != 's')
3247 /* The following loop assumes the Lisp type indicates
3248 the proper way to pass the argument.
3249 So make sure we have a flonum if the argument should
3250 be a double. */
3251 if (*format == 'e' || *format == 'f' || *format == 'g')
3252 args[n] = Ffloat (args[n]);
3253 else
3254 if (*format != 'd' && *format != 'o' && *format != 'x'
3255 && *format != 'i' && *format != 'X' && *format != 'c')
3256 error ("Invalid format operation %%%c", *format);
3258 thissize = 30;
3259 if (*format == 'c'
3260 && (! SINGLE_BYTE_CHAR_P (XINT (args[n]))
3261 || XINT (args[n]) == 0))
3263 if (! multibyte)
3265 multibyte = 1;
3266 goto retry;
3268 args[n] = Fchar_to_string (args[n]);
3269 thissize = STRING_BYTES (XSTRING (args[n]));
3272 else if (FLOATP (args[n]) && *format != 's')
3274 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
3275 args[n] = Ftruncate (args[n], Qnil);
3277 /* Note that we're using sprintf to print floats,
3278 so we have to take into account what that function
3279 prints. */
3280 thissize = MAX_10_EXP + 100 + precision;
3282 else
3284 /* Anything but a string, convert to a string using princ. */
3285 register Lisp_Object tem;
3286 tem = Fprin1_to_string (args[n], Qt);
3287 if (STRING_MULTIBYTE (tem) & ! multibyte)
3289 multibyte = 1;
3290 goto retry;
3292 args[n] = tem;
3293 goto string;
3296 thissize = max (field_width, thissize);
3297 total += thissize + 4;
3300 /* Now we can no longer jump to retry.
3301 TOTAL and LONGEST_FORMAT are known for certain. */
3303 this_format = (unsigned char *) alloca (longest_format + 1);
3305 /* Allocate the space for the result.
3306 Note that TOTAL is an overestimate. */
3307 if (total < 1000)
3308 buf = (char *) alloca (total + 1);
3309 else
3310 buf = (char *) xmalloc (total + 1);
3312 p = buf;
3313 nchars = 0;
3314 n = 0;
3316 /* Scan the format and store result in BUF. */
3317 format = XSTRING (args[0])->data;
3318 maybe_combine_byte = 0;
3319 while (format != end)
3321 if (*format == '%')
3323 int minlen;
3324 int negative = 0;
3325 unsigned char *this_format_start = format;
3327 format++;
3329 /* Process a numeric arg and skip it. */
3330 minlen = atoi (format);
3331 if (minlen < 0)
3332 minlen = - minlen, negative = 1;
3334 while ((*format >= '0' && *format <= '9')
3335 || *format == '-' || *format == ' ' || *format == '.')
3336 format++;
3338 if (*format++ == '%')
3340 *p++ = '%';
3341 nchars++;
3342 continue;
3345 ++n;
3347 if (STRINGP (args[n]))
3349 int padding, nbytes, start, end;
3350 int width = lisp_string_width (args[n], -1, NULL, NULL);
3352 /* If spec requires it, pad on right with spaces. */
3353 padding = minlen - width;
3354 if (! negative)
3355 while (padding-- > 0)
3357 *p++ = ' ';
3358 ++nchars;
3361 start = nchars;
3363 if (p > buf
3364 && multibyte
3365 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3366 && STRING_MULTIBYTE (args[n])
3367 && !CHAR_HEAD_P (XSTRING (args[n])->data[0]))
3368 maybe_combine_byte = 1;
3369 nbytes = copy_text (XSTRING (args[n])->data, p,
3370 STRING_BYTES (XSTRING (args[n])),
3371 STRING_MULTIBYTE (args[n]), multibyte);
3372 p += nbytes;
3373 nchars += XSTRING (args[n])->size;
3374 end = nchars;
3376 if (negative)
3377 while (padding-- > 0)
3379 *p++ = ' ';
3380 nchars++;
3383 /* If this argument has text properties, record where
3384 in the result string it appears. */
3385 if (XSTRING (args[n])->intervals)
3387 if (!info)
3389 int nbytes = nargs * sizeof *info;
3390 info = (struct info *) alloca (nbytes);
3391 bzero (info, nbytes);
3394 info[n].start = start;
3395 info[n].end = end;
3398 else if (INTEGERP (args[n]) || FLOATP (args[n]))
3400 int this_nchars;
3402 bcopy (this_format_start, this_format,
3403 format - this_format_start);
3404 this_format[format - this_format_start] = 0;
3406 if (INTEGERP (args[n]))
3407 sprintf (p, this_format, XINT (args[n]));
3408 else
3409 sprintf (p, this_format, XFLOAT_DATA (args[n]));
3411 if (p > buf
3412 && multibyte
3413 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3414 && !CHAR_HEAD_P (*((unsigned char *) p)))
3415 maybe_combine_byte = 1;
3416 this_nchars = strlen (p);
3417 if (multibyte)
3418 p += str_to_multibyte (p, buf + total - p, this_nchars);
3419 else
3420 p += this_nchars;
3421 nchars += this_nchars;
3424 else if (STRING_MULTIBYTE (args[0]))
3426 /* Copy a whole multibyte character. */
3427 if (p > buf
3428 && multibyte
3429 && !ASCII_BYTE_P (*((unsigned char *) p - 1))
3430 && !CHAR_HEAD_P (*format))
3431 maybe_combine_byte = 1;
3432 *p++ = *format++;
3433 while (! CHAR_HEAD_P (*format)) *p++ = *format++;
3434 nchars++;
3436 else if (multibyte)
3438 /* Convert a single-byte character to multibyte. */
3439 int len = copy_text (format, p, 1, 0, 1);
3441 p += len;
3442 format++;
3443 nchars++;
3445 else
3446 *p++ = *format++, nchars++;
3449 if (p > buf + total + 1)
3450 abort ();
3452 if (maybe_combine_byte)
3453 nchars = multibyte_chars_in_text (buf, p - buf);
3454 val = make_specified_string (buf, nchars, p - buf, multibyte);
3456 /* If we allocated BUF with malloc, free it too. */
3457 if (total >= 1000)
3458 xfree (buf);
3460 /* If the format string has text properties, or any of the string
3461 arguments has text properties, set up text properties of the
3462 result string. */
3464 if (XSTRING (args[0])->intervals || info)
3466 Lisp_Object len, new_len, props;
3467 struct gcpro gcpro1;
3469 /* Add text properties from the format string. */
3470 len = make_number (XSTRING (args[0])->size);
3471 props = text_property_list (args[0], make_number (0), len, Qnil);
3472 GCPRO1 (props);
3474 if (CONSP (props))
3476 new_len = make_number (XSTRING (val)->size);
3477 extend_property_ranges (props, len, new_len);
3478 add_text_properties_from_list (val, props, make_number (0));
3481 /* Add text properties from arguments. */
3482 if (info)
3483 for (n = 1; n < nargs; ++n)
3484 if (info[n].end)
3486 len = make_number (XSTRING (args[n])->size);
3487 new_len = make_number (info[n].end - info[n].start);
3488 props = text_property_list (args[n], make_number (0), len, Qnil);
3489 extend_property_ranges (props, len, new_len);
3490 /* If successive arguments have properites, be sure that
3491 the value of `composition' property be the copy. */
3492 if (n > 1 && info[n - 1].end)
3493 make_composition_value_copy (props);
3494 add_text_properties_from_list (val, props,
3495 make_number (info[n].start));
3498 UNGCPRO;
3501 return val;
3505 /* VARARGS 1 */
3506 Lisp_Object
3507 #ifdef NO_ARG_ARRAY
3508 format1 (string1, arg0, arg1, arg2, arg3, arg4)
3509 EMACS_INT arg0, arg1, arg2, arg3, arg4;
3510 #else
3511 format1 (string1)
3512 #endif
3513 char *string1;
3515 char buf[100];
3516 #ifdef NO_ARG_ARRAY
3517 EMACS_INT args[5];
3518 args[0] = arg0;
3519 args[1] = arg1;
3520 args[2] = arg2;
3521 args[3] = arg3;
3522 args[4] = arg4;
3523 doprnt (buf, sizeof buf, string1, (char *)0, 5, (char **) args);
3524 #else
3525 doprnt (buf, sizeof buf, string1, (char *)0, 5, &string1 + 1);
3526 #endif
3527 return build_string (buf);
3530 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
3531 "Return t if two characters match, optionally ignoring case.\n\
3532 Both arguments must be characters (i.e. integers).\n\
3533 Case is ignored if `case-fold-search' is non-nil in the current buffer.")
3534 (c1, c2)
3535 register Lisp_Object c1, c2;
3537 int i1, i2;
3538 CHECK_NUMBER (c1, 0);
3539 CHECK_NUMBER (c2, 1);
3541 if (XINT (c1) == XINT (c2))
3542 return Qt;
3543 if (NILP (current_buffer->case_fold_search))
3544 return Qnil;
3546 /* Do these in separate statements,
3547 then compare the variables.
3548 because of the way DOWNCASE uses temp variables. */
3549 i1 = DOWNCASE (XFASTINT (c1));
3550 i2 = DOWNCASE (XFASTINT (c2));
3551 return (i1 == i2 ? Qt : Qnil);
3554 /* Transpose the markers in two regions of the current buffer, and
3555 adjust the ones between them if necessary (i.e.: if the regions
3556 differ in size).
3558 START1, END1 are the character positions of the first region.
3559 START1_BYTE, END1_BYTE are the byte positions.
3560 START2, END2 are the character positions of the second region.
3561 START2_BYTE, END2_BYTE are the byte positions.
3563 Traverses the entire marker list of the buffer to do so, adding an
3564 appropriate amount to some, subtracting from some, and leaving the
3565 rest untouched. Most of this is copied from adjust_markers in insdel.c.
3567 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
3569 static void
3570 transpose_markers (start1, end1, start2, end2,
3571 start1_byte, end1_byte, start2_byte, end2_byte)
3572 register int start1, end1, start2, end2;
3573 register int start1_byte, end1_byte, start2_byte, end2_byte;
3575 register int amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
3576 register Lisp_Object marker;
3578 /* Update point as if it were a marker. */
3579 if (PT < start1)
3581 else if (PT < end1)
3582 TEMP_SET_PT_BOTH (PT + (end2 - end1),
3583 PT_BYTE + (end2_byte - end1_byte));
3584 else if (PT < start2)
3585 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
3586 (PT_BYTE + (end2_byte - start2_byte)
3587 - (end1_byte - start1_byte)));
3588 else if (PT < end2)
3589 TEMP_SET_PT_BOTH (PT - (start2 - start1),
3590 PT_BYTE - (start2_byte - start1_byte));
3592 /* We used to adjust the endpoints here to account for the gap, but that
3593 isn't good enough. Even if we assume the caller has tried to move the
3594 gap out of our way, it might still be at start1 exactly, for example;
3595 and that places it `inside' the interval, for our purposes. The amount
3596 of adjustment is nontrivial if there's a `denormalized' marker whose
3597 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
3598 the dirty work to Fmarker_position, below. */
3600 /* The difference between the region's lengths */
3601 diff = (end2 - start2) - (end1 - start1);
3602 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
3604 /* For shifting each marker in a region by the length of the other
3605 region plus the distance between the regions. */
3606 amt1 = (end2 - start2) + (start2 - end1);
3607 amt2 = (end1 - start1) + (start2 - end1);
3608 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
3609 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
3611 for (marker = BUF_MARKERS (current_buffer); !NILP (marker);
3612 marker = XMARKER (marker)->chain)
3614 mpos = marker_byte_position (marker);
3615 if (mpos >= start1_byte && mpos < end2_byte)
3617 if (mpos < end1_byte)
3618 mpos += amt1_byte;
3619 else if (mpos < start2_byte)
3620 mpos += diff_byte;
3621 else
3622 mpos -= amt2_byte;
3623 XMARKER (marker)->bytepos = mpos;
3625 mpos = XMARKER (marker)->charpos;
3626 if (mpos >= start1 && mpos < end2)
3628 if (mpos < end1)
3629 mpos += amt1;
3630 else if (mpos < start2)
3631 mpos += diff;
3632 else
3633 mpos -= amt2;
3635 XMARKER (marker)->charpos = mpos;
3639 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
3640 "Transpose region START1 to END1 with START2 to END2.\n\
3641 The regions may not be overlapping, because the size of the buffer is\n\
3642 never changed in a transposition.\n\
3644 Optional fifth arg LEAVE_MARKERS, if non-nil, means don't update\n\
3645 any markers that happen to be located in the regions.\n\
3647 Transposing beyond buffer boundaries is an error.")
3648 (startr1, endr1, startr2, endr2, leave_markers)
3649 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
3651 register int start1, end1, start2, end2;
3652 int start1_byte, start2_byte, len1_byte, len2_byte;
3653 int gap, len1, len_mid, len2;
3654 unsigned char *start1_addr, *start2_addr, *temp;
3656 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
3657 cur_intv = BUF_INTERVALS (current_buffer);
3659 validate_region (&startr1, &endr1);
3660 validate_region (&startr2, &endr2);
3662 start1 = XFASTINT (startr1);
3663 end1 = XFASTINT (endr1);
3664 start2 = XFASTINT (startr2);
3665 end2 = XFASTINT (endr2);
3666 gap = GPT;
3668 /* Swap the regions if they're reversed. */
3669 if (start2 < end1)
3671 register int glumph = start1;
3672 start1 = start2;
3673 start2 = glumph;
3674 glumph = end1;
3675 end1 = end2;
3676 end2 = glumph;
3679 len1 = end1 - start1;
3680 len2 = end2 - start2;
3682 if (start2 < end1)
3683 error ("Transposed regions overlap");
3684 else if (start1 == end1 || start2 == end2)
3685 error ("Transposed region has length 0");
3687 /* The possibilities are:
3688 1. Adjacent (contiguous) regions, or separate but equal regions
3689 (no, really equal, in this case!), or
3690 2. Separate regions of unequal size.
3692 The worst case is usually No. 2. It means that (aside from
3693 potential need for getting the gap out of the way), there also
3694 needs to be a shifting of the text between the two regions. So
3695 if they are spread far apart, we are that much slower... sigh. */
3697 /* It must be pointed out that the really studly thing to do would
3698 be not to move the gap at all, but to leave it in place and work
3699 around it if necessary. This would be extremely efficient,
3700 especially considering that people are likely to do
3701 transpositions near where they are working interactively, which
3702 is exactly where the gap would be found. However, such code
3703 would be much harder to write and to read. So, if you are
3704 reading this comment and are feeling squirrely, by all means have
3705 a go! I just didn't feel like doing it, so I will simply move
3706 the gap the minimum distance to get it out of the way, and then
3707 deal with an unbroken array. */
3709 /* Make sure the gap won't interfere, by moving it out of the text
3710 we will operate on. */
3711 if (start1 < gap && gap < end2)
3713 if (gap - start1 < end2 - gap)
3714 move_gap (start1);
3715 else
3716 move_gap (end2);
3719 start1_byte = CHAR_TO_BYTE (start1);
3720 start2_byte = CHAR_TO_BYTE (start2);
3721 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
3722 len2_byte = CHAR_TO_BYTE (end2) - start2_byte;
3724 #ifdef BYTE_COMBINING_DEBUG
3725 if (end1 == start2)
3727 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3728 len2_byte, start1, start1_byte)
3729 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3730 len1_byte, end2, start2_byte + len2_byte)
3731 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3732 len1_byte, end2, start2_byte + len2_byte))
3733 abort ();
3735 else
3737 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
3738 len2_byte, start1, start1_byte)
3739 || count_combining_before (BYTE_POS_ADDR (start1_byte),
3740 len1_byte, start2, start2_byte)
3741 || count_combining_after (BYTE_POS_ADDR (start2_byte),
3742 len2_byte, end1, start1_byte + len1_byte)
3743 || count_combining_after (BYTE_POS_ADDR (start1_byte),
3744 len1_byte, end2, start2_byte + len2_byte))
3745 abort ();
3747 #endif
3749 /* Hmmm... how about checking to see if the gap is large
3750 enough to use as the temporary storage? That would avoid an
3751 allocation... interesting. Later, don't fool with it now. */
3753 /* Working without memmove, for portability (sigh), so must be
3754 careful of overlapping subsections of the array... */
3756 if (end1 == start2) /* adjacent regions */
3758 modify_region (current_buffer, start1, end2);
3759 record_change (start1, len1 + len2);
3761 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3762 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3763 Fset_text_properties (make_number (start1), make_number (end2),
3764 Qnil, Qnil);
3766 /* First region smaller than second. */
3767 if (len1_byte < len2_byte)
3769 /* We use alloca only if it is small,
3770 because we want to avoid stack overflow. */
3771 if (len2_byte > 20000)
3772 temp = (unsigned char *) xmalloc (len2_byte);
3773 else
3774 temp = (unsigned char *) alloca (len2_byte);
3776 /* Don't precompute these addresses. We have to compute them
3777 at the last minute, because the relocating allocator might
3778 have moved the buffer around during the xmalloc. */
3779 start1_addr = BYTE_POS_ADDR (start1_byte);
3780 start2_addr = BYTE_POS_ADDR (start2_byte);
3782 bcopy (start2_addr, temp, len2_byte);
3783 bcopy (start1_addr, start1_addr + len2_byte, len1_byte);
3784 bcopy (temp, start1_addr, len2_byte);
3785 if (len2_byte > 20000)
3786 xfree (temp);
3788 else
3789 /* First region not smaller than second. */
3791 if (len1_byte > 20000)
3792 temp = (unsigned char *) xmalloc (len1_byte);
3793 else
3794 temp = (unsigned char *) alloca (len1_byte);
3795 start1_addr = BYTE_POS_ADDR (start1_byte);
3796 start2_addr = BYTE_POS_ADDR (start2_byte);
3797 bcopy (start1_addr, temp, len1_byte);
3798 bcopy (start2_addr, start1_addr, len2_byte);
3799 bcopy (temp, start1_addr + len2_byte, len1_byte);
3800 if (len1_byte > 20000)
3801 xfree (temp);
3803 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
3804 len1, current_buffer, 0);
3805 graft_intervals_into_buffer (tmp_interval2, start1,
3806 len2, current_buffer, 0);
3807 update_compositions (start1, start1 + len2, CHECK_BORDER);
3808 update_compositions (start1 + len2, end2, CHECK_TAIL);
3810 /* Non-adjacent regions, because end1 != start2, bleagh... */
3811 else
3813 len_mid = start2_byte - (start1_byte + len1_byte);
3815 if (len1_byte == len2_byte)
3816 /* Regions are same size, though, how nice. */
3818 modify_region (current_buffer, start1, end1);
3819 modify_region (current_buffer, start2, end2);
3820 record_change (start1, len1);
3821 record_change (start2, len2);
3822 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3823 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3824 Fset_text_properties (make_number (start1), make_number (end1),
3825 Qnil, Qnil);
3826 Fset_text_properties (make_number (start2), make_number (end2),
3827 Qnil, Qnil);
3829 if (len1_byte > 20000)
3830 temp = (unsigned char *) xmalloc (len1_byte);
3831 else
3832 temp = (unsigned char *) alloca (len1_byte);
3833 start1_addr = BYTE_POS_ADDR (start1_byte);
3834 start2_addr = BYTE_POS_ADDR (start2_byte);
3835 bcopy (start1_addr, temp, len1_byte);
3836 bcopy (start2_addr, start1_addr, len2_byte);
3837 bcopy (temp, start2_addr, len1_byte);
3838 if (len1_byte > 20000)
3839 xfree (temp);
3840 graft_intervals_into_buffer (tmp_interval1, start2,
3841 len1, current_buffer, 0);
3842 graft_intervals_into_buffer (tmp_interval2, start1,
3843 len2, current_buffer, 0);
3846 else if (len1_byte < len2_byte) /* Second region larger than first */
3847 /* Non-adjacent & unequal size, area between must also be shifted. */
3849 modify_region (current_buffer, start1, end2);
3850 record_change (start1, (end2 - start1));
3851 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3852 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3853 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3854 Fset_text_properties (make_number (start1), make_number (end2),
3855 Qnil, Qnil);
3857 /* holds region 2 */
3858 if (len2_byte > 20000)
3859 temp = (unsigned char *) xmalloc (len2_byte);
3860 else
3861 temp = (unsigned char *) alloca (len2_byte);
3862 start1_addr = BYTE_POS_ADDR (start1_byte);
3863 start2_addr = BYTE_POS_ADDR (start2_byte);
3864 bcopy (start2_addr, temp, len2_byte);
3865 bcopy (start1_addr, start1_addr + len_mid + len2_byte, len1_byte);
3866 safe_bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3867 bcopy (temp, start1_addr, len2_byte);
3868 if (len2_byte > 20000)
3869 xfree (temp);
3870 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3871 len1, current_buffer, 0);
3872 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3873 len_mid, current_buffer, 0);
3874 graft_intervals_into_buffer (tmp_interval2, start1,
3875 len2, current_buffer, 0);
3877 else
3878 /* Second region smaller than first. */
3880 record_change (start1, (end2 - start1));
3881 modify_region (current_buffer, start1, end2);
3883 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
3884 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
3885 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
3886 Fset_text_properties (make_number (start1), make_number (end2),
3887 Qnil, Qnil);
3889 /* holds region 1 */
3890 if (len1_byte > 20000)
3891 temp = (unsigned char *) xmalloc (len1_byte);
3892 else
3893 temp = (unsigned char *) alloca (len1_byte);
3894 start1_addr = BYTE_POS_ADDR (start1_byte);
3895 start2_addr = BYTE_POS_ADDR (start2_byte);
3896 bcopy (start1_addr, temp, len1_byte);
3897 bcopy (start2_addr, start1_addr, len2_byte);
3898 bcopy (start1_addr + len1_byte, start1_addr + len2_byte, len_mid);
3899 bcopy (temp, start1_addr + len2_byte + len_mid, len1_byte);
3900 if (len1_byte > 20000)
3901 xfree (temp);
3902 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
3903 len1, current_buffer, 0);
3904 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
3905 len_mid, current_buffer, 0);
3906 graft_intervals_into_buffer (tmp_interval2, start1,
3907 len2, current_buffer, 0);
3910 update_compositions (start1, start1 + len2, CHECK_BORDER);
3911 update_compositions (end2 - len1, end2, CHECK_BORDER);
3914 /* When doing multiple transpositions, it might be nice
3915 to optimize this. Perhaps the markers in any one buffer
3916 should be organized in some sorted data tree. */
3917 if (NILP (leave_markers))
3919 transpose_markers (start1, end1, start2, end2,
3920 start1_byte, start1_byte + len1_byte,
3921 start2_byte, start2_byte + len2_byte);
3922 fix_overlays_in_range (start1, end2);
3925 return Qnil;
3929 void
3930 syms_of_editfns ()
3932 environbuf = 0;
3934 Qbuffer_access_fontify_functions
3935 = intern ("buffer-access-fontify-functions");
3936 staticpro (&Qbuffer_access_fontify_functions);
3938 DEFVAR_LISP ("inhibit-field-text-motion", &Vinhibit_field_text_motion,
3939 "Non-nil means.text motion commands don't notice fields.");
3940 Vinhibit_field_text_motion = Qnil;
3942 DEFVAR_LISP ("buffer-access-fontify-functions",
3943 &Vbuffer_access_fontify_functions,
3944 "List of functions called by `buffer-substring' to fontify if necessary.\n\
3945 Each function is called with two arguments which specify the range\n\
3946 of the buffer being accessed.");
3947 Vbuffer_access_fontify_functions = Qnil;
3950 Lisp_Object obuf;
3951 extern Lisp_Object Vprin1_to_string_buffer;
3952 obuf = Fcurrent_buffer ();
3953 /* Do this here, because init_buffer_once is too early--it won't work. */
3954 Fset_buffer (Vprin1_to_string_buffer);
3955 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
3956 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
3957 Qnil);
3958 Fset_buffer (obuf);
3961 DEFVAR_LISP ("buffer-access-fontified-property",
3962 &Vbuffer_access_fontified_property,
3963 "Property which (if non-nil) indicates text has been fontified.\n\
3964 `buffer-substring' need not call the `buffer-access-fontify-functions'\n\
3965 functions if all the text being accessed has this property.");
3966 Vbuffer_access_fontified_property = Qnil;
3968 DEFVAR_LISP ("system-name", &Vsystem_name,
3969 "The name of the machine Emacs is running on.");
3971 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
3972 "The full name of the user logged in.");
3974 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
3975 "The user's name, taken from environment variables if possible.");
3977 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
3978 "The user's name, based upon the real uid only.");
3980 defsubr (&Spropertize);
3981 defsubr (&Schar_equal);
3982 defsubr (&Sgoto_char);
3983 defsubr (&Sstring_to_char);
3984 defsubr (&Schar_to_string);
3985 defsubr (&Sbuffer_substring);
3986 defsubr (&Sbuffer_substring_no_properties);
3987 defsubr (&Sbuffer_string);
3989 defsubr (&Spoint_marker);
3990 defsubr (&Smark_marker);
3991 defsubr (&Spoint);
3992 defsubr (&Sregion_beginning);
3993 defsubr (&Sregion_end);
3995 staticpro (&Qfield);
3996 Qfield = intern ("field");
3997 staticpro (&Qboundary);
3998 Qboundary = intern ("boundary");
3999 defsubr (&Sfield_beginning);
4000 defsubr (&Sfield_end);
4001 defsubr (&Sfield_string);
4002 defsubr (&Sfield_string_no_properties);
4003 defsubr (&Sdelete_field);
4004 defsubr (&Sconstrain_to_field);
4006 defsubr (&Sline_beginning_position);
4007 defsubr (&Sline_end_position);
4009 /* defsubr (&Smark); */
4010 /* defsubr (&Sset_mark); */
4011 defsubr (&Ssave_excursion);
4012 defsubr (&Ssave_current_buffer);
4014 defsubr (&Sbufsize);
4015 defsubr (&Spoint_max);
4016 defsubr (&Spoint_min);
4017 defsubr (&Spoint_min_marker);
4018 defsubr (&Spoint_max_marker);
4019 defsubr (&Sgap_position);
4020 defsubr (&Sgap_size);
4021 defsubr (&Sposition_bytes);
4022 defsubr (&Sbyte_to_position);
4024 defsubr (&Sbobp);
4025 defsubr (&Seobp);
4026 defsubr (&Sbolp);
4027 defsubr (&Seolp);
4028 defsubr (&Sfollowing_char);
4029 defsubr (&Sprevious_char);
4030 defsubr (&Schar_after);
4031 defsubr (&Schar_before);
4032 defsubr (&Sinsert);
4033 defsubr (&Sinsert_before_markers);
4034 defsubr (&Sinsert_and_inherit);
4035 defsubr (&Sinsert_and_inherit_before_markers);
4036 defsubr (&Sinsert_char);
4038 defsubr (&Suser_login_name);
4039 defsubr (&Suser_real_login_name);
4040 defsubr (&Suser_uid);
4041 defsubr (&Suser_real_uid);
4042 defsubr (&Suser_full_name);
4043 defsubr (&Semacs_pid);
4044 defsubr (&Scurrent_time);
4045 defsubr (&Sformat_time_string);
4046 defsubr (&Sfloat_time);
4047 defsubr (&Sdecode_time);
4048 defsubr (&Sencode_time);
4049 defsubr (&Scurrent_time_string);
4050 defsubr (&Scurrent_time_zone);
4051 defsubr (&Sset_time_zone_rule);
4052 defsubr (&Ssystem_name);
4053 defsubr (&Smessage);
4054 defsubr (&Smessage_box);
4055 defsubr (&Smessage_or_box);
4056 defsubr (&Scurrent_message);
4057 defsubr (&Sformat);
4059 defsubr (&Sinsert_buffer_substring);
4060 defsubr (&Scompare_buffer_substrings);
4061 defsubr (&Ssubst_char_in_region);
4062 defsubr (&Stranslate_region);
4063 defsubr (&Sdelete_region);
4064 defsubr (&Sdelete_and_extract_region);
4065 defsubr (&Swiden);
4066 defsubr (&Snarrow_to_region);
4067 defsubr (&Ssave_restriction);
4068 defsubr (&Stranspose_regions);