1 /* Lisp functions pertaining to editing. -*- coding: utf-8 -*-
3 Copyright (C) 1985-1987, 1989, 1993-2018 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 3 of the License, or (at
10 your option) 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. If not, see <https://www.gnu.org/licenses/>. */
22 #include <sys/types.h>
32 #ifdef HAVE_SYS_UTSNAME_H
33 #include <sys/utsname.h>
38 /* systime.h includes <sys/time.h> which, on some systems, is required
39 for <sys/resource.h>; thus systime.h must be included before
43 #if defined HAVE_SYS_RESOURCE_H
44 #include <sys/resource.h>
57 #include "composite.h"
58 #include "intervals.h"
59 #include "ptr-bounds.h"
60 #include "character.h"
64 #include "blockinput.h"
66 #define TM_YEAR_BASE 1900
69 extern Lisp_Object
w32_get_internal_run_time (void);
72 static struct lisp_time
lisp_time_struct (Lisp_Object
, int *);
73 static Lisp_Object
format_time_string (char const *, ptrdiff_t, struct timespec
,
74 Lisp_Object
, struct tm
*);
75 static long int tm_gmtoff (struct tm
*);
76 static int tm_diff (struct tm
*, struct tm
*);
77 static void update_buffer_properties (ptrdiff_t, ptrdiff_t);
78 static Lisp_Object
styled_format (ptrdiff_t, Lisp_Object
*, bool);
80 #ifndef HAVE_TM_GMTOFF
81 # define HAVE_TM_GMTOFF false
84 enum { tzeqlen
= sizeof "TZ=" - 1 };
86 /* Time zones equivalent to current local time and to UTC, respectively. */
87 static timezone_t local_tz
;
88 static timezone_t
const utc_tz
= 0;
90 /* The cached value of Vsystem_name. This is used only to compare it
91 to Vsystem_name, so it need not be visible to the GC. */
92 static Lisp_Object cached_system_name
;
95 init_and_cache_system_name (void)
98 cached_system_name
= Vsystem_name
;
102 emacs_localtime_rz (timezone_t tz
, time_t const *t
, struct tm
*tm
)
104 tm
= localtime_rz (tz
, t
, tm
);
105 if (!tm
&& errno
== ENOMEM
)
106 memory_full (SIZE_MAX
);
111 emacs_mktime_z (timezone_t tz
, struct tm
*tm
)
114 time_t t
= mktime_z (tz
, tm
);
115 if (t
== (time_t) -1 && errno
== ENOMEM
)
116 memory_full (SIZE_MAX
);
120 static _Noreturn
void
121 invalid_time_zone_specification (Lisp_Object zone
)
123 xsignal2 (Qerror
, build_string ("Invalid time zone specification"), zone
);
126 /* Free a timezone, except do not free the time zone for local time.
127 Freeing utc_tz is also a no-op. */
129 xtzfree (timezone_t tz
)
135 /* Convert the Lisp time zone rule ZONE to a timezone_t object.
136 The returned value either is 0, or is LOCAL_TZ, or is newly allocated.
137 If SETTZ, set Emacs local time to the time zone rule; otherwise,
138 the caller should eventually pass the returned value to xtzfree. */
140 tzlookup (Lisp_Object zone
, bool settz
)
142 static char const tzbuf_format
[] = "<%+.*"pI
"d>%s%"pI
"d:%02d:%02d";
143 char const *trailing_tzbuf_format
= tzbuf_format
+ sizeof "<%+.*"pI
"d" - 1;
144 char tzbuf
[sizeof tzbuf_format
+ 2 * INT_STRLEN_BOUND (EMACS_INT
)];
145 char const *zone_string
;
150 else if (EQ (zone
, Qt
))
152 zone_string
= "UTC0";
157 bool plain_integer
= INTEGERP (zone
);
159 if (EQ (zone
, Qwall
))
161 else if (STRINGP (zone
))
162 zone_string
= SSDATA (ENCODE_SYSTEM (zone
));
163 else if (plain_integer
|| (CONSP (zone
) && INTEGERP (XCAR (zone
))
164 && CONSP (XCDR (zone
))))
169 abbr
= XCAR (XCDR (zone
));
173 EMACS_INT abszone
= eabs (XINT (zone
)), hour
= abszone
/ (60 * 60);
174 int hour_remainder
= abszone
% (60 * 60);
175 int min
= hour_remainder
/ 60, sec
= hour_remainder
% 60;
180 EMACS_INT numzone
= hour
;
181 if (hour_remainder
!= 0)
183 prec
+= 2, numzone
= 100 * numzone
+ min
;
185 prec
+= 2, numzone
= 100 * numzone
+ sec
;
187 sprintf (tzbuf
, tzbuf_format
, prec
,
188 XINT (zone
) < 0 ? -numzone
: numzone
,
189 &"-"[XINT (zone
) < 0], hour
, min
, sec
);
194 AUTO_STRING (leading
, "<");
195 AUTO_STRING_WITH_LEN (trailing
, tzbuf
,
196 sprintf (tzbuf
, trailing_tzbuf_format
,
197 &"-"[XINT (zone
) < 0],
199 zone_string
= SSDATA (concat3 (leading
, ENCODE_SYSTEM (abbr
),
204 invalid_time_zone_specification (zone
);
206 new_tz
= tzalloc (zone_string
);
210 memory_full (SIZE_MAX
);
211 invalid_time_zone_specification (zone
);
218 emacs_setenv_TZ (zone_string
);
220 timezone_t old_tz
= local_tz
;
230 init_editfns (bool dumping
)
232 #if !defined CANNOT_DUMP
233 /* A valid but unlikely setting for the TZ environment variable.
234 It is OK (though a bit slower) if the user chooses this value. */
235 static char dump_tz_string
[] = "TZ=UtC0";
238 const char *user_name
;
240 struct passwd
*pw
; /* password entry for the current user */
243 /* Set up system_name even when dumping. */
244 init_and_cache_system_name ();
247 /* When just dumping out, set the time zone to a known unlikely value
248 and skip the rest of this function. */
251 xputenv (dump_tz_string
);
257 char *tz
= getenv ("TZ");
259 #if !defined CANNOT_DUMP
260 /* If the execution TZ happens to be the same as the dump TZ,
261 change it to some other value and then change it back,
262 to force the underlying implementation to reload the TZ info.
263 This is needed on implementations that load TZ info from files,
264 since the TZ file contents may differ between dump and execution. */
265 if (tz
&& strcmp (tz
, &dump_tz_string
[tzeqlen
]) == 0)
273 /* Set the time zone rule now, so that the call to putenv is done
274 before multiple threads are active. */
275 tzlookup (tz
? build_string (tz
) : Qwall
, true);
277 pw
= getpwuid (getuid ());
279 /* We let the real user name default to "root" because that's quite
280 accurate on MS-DOS and because it lets Emacs find the init file.
281 (The DVX libraries override the Djgpp libraries here.) */
282 Vuser_real_login_name
= build_string (pw
? pw
->pw_name
: "root");
284 Vuser_real_login_name
= build_string (pw
? pw
->pw_name
: "unknown");
287 /* Get the effective user name, by consulting environment variables,
288 or the effective uid if those are unset. */
289 user_name
= getenv ("LOGNAME");
292 user_name
= getenv ("USERNAME"); /* it's USERNAME on NT */
293 #else /* WINDOWSNT */
294 user_name
= getenv ("USER");
295 #endif /* WINDOWSNT */
298 pw
= getpwuid (geteuid ());
299 user_name
= pw
? pw
->pw_name
: "unknown";
301 Vuser_login_name
= build_string (user_name
);
303 /* If the user name claimed in the environment vars differs from
304 the real uid, use the claimed name to find the full name. */
305 tem
= Fstring_equal (Vuser_login_name
, Vuser_real_login_name
);
307 tem
= Vuser_login_name
;
310 uid_t euid
= geteuid ();
311 tem
= make_fixnum_or_float (euid
);
313 Vuser_full_name
= Fuser_full_name (tem
);
317 Vuser_full_name
= build_string (p
);
318 else if (NILP (Vuser_full_name
))
319 Vuser_full_name
= build_string ("unknown");
321 #ifdef HAVE_SYS_UTSNAME_H
325 Voperating_system_release
= build_string (uts
.release
);
328 Voperating_system_release
= Qnil
;
332 DEFUN ("char-to-string", Fchar_to_string
, Schar_to_string
, 1, 1, 0,
333 doc
: /* Convert arg CHAR to a string containing that character.
334 usage: (char-to-string CHAR) */)
335 (Lisp_Object character
)
338 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
340 CHECK_CHARACTER (character
);
341 c
= XFASTINT (character
);
343 len
= CHAR_STRING (c
, str
);
344 return make_string_from_bytes ((char *) str
, 1, len
);
347 DEFUN ("byte-to-string", Fbyte_to_string
, Sbyte_to_string
, 1, 1, 0,
348 doc
: /* Convert arg BYTE to a unibyte string containing that byte. */)
353 if (XINT (byte
) < 0 || XINT (byte
) > 255)
354 error ("Invalid byte");
356 return make_string_from_bytes ((char *) &b
, 1, 1);
359 DEFUN ("string-to-char", Fstring_to_char
, Sstring_to_char
, 1, 1, 0,
360 doc
: /* Return the first character in STRING. */)
361 (register Lisp_Object string
)
363 register Lisp_Object val
;
364 CHECK_STRING (string
);
367 if (STRING_MULTIBYTE (string
))
368 XSETFASTINT (val
, STRING_CHAR (SDATA (string
)));
370 XSETFASTINT (val
, SREF (string
, 0));
373 XSETFASTINT (val
, 0);
377 DEFUN ("point", Fpoint
, Spoint
, 0, 0, 0,
378 doc
: /* Return value of point, as an integer.
379 Beginning of buffer is position (point-min). */)
383 XSETFASTINT (temp
, PT
);
387 DEFUN ("point-marker", Fpoint_marker
, Spoint_marker
, 0, 0, 0,
388 doc
: /* Return value of point, as a marker object. */)
391 return build_marker (current_buffer
, PT
, PT_BYTE
);
394 DEFUN ("goto-char", Fgoto_char
, Sgoto_char
, 1, 1, "NGoto char: ",
395 doc
: /* Set point to POSITION, a number or marker.
396 Beginning of buffer is position (point-min), end is (point-max).
398 The return value is POSITION. */)
399 (register Lisp_Object position
)
401 if (MARKERP (position
))
402 set_point_from_marker (position
);
403 else if (INTEGERP (position
))
404 SET_PT (clip_to_bounds (BEGV
, XINT (position
), ZV
));
406 wrong_type_argument (Qinteger_or_marker_p
, position
);
411 /* Return the start or end position of the region.
412 BEGINNINGP means return the start.
413 If there is no region active, signal an error. */
416 region_limit (bool beginningp
)
420 if (!NILP (Vtransient_mark_mode
)
421 && NILP (Vmark_even_if_inactive
)
422 && NILP (BVAR (current_buffer
, mark_active
)))
423 xsignal0 (Qmark_inactive
);
425 m
= Fmarker_position (BVAR (current_buffer
, mark
));
427 error ("The mark is not set now, so there is no region");
429 /* Clip to the current narrowing (bug#11770). */
430 return make_number ((PT
< XFASTINT (m
)) == beginningp
432 : clip_to_bounds (BEGV
, XFASTINT (m
), ZV
));
435 DEFUN ("region-beginning", Fregion_beginning
, Sregion_beginning
, 0, 0, 0,
436 doc
: /* Return the integer value of point or mark, whichever is smaller. */)
439 return region_limit (1);
442 DEFUN ("region-end", Fregion_end
, Sregion_end
, 0, 0, 0,
443 doc
: /* Return the integer value of point or mark, whichever is larger. */)
446 return region_limit (0);
449 DEFUN ("mark-marker", Fmark_marker
, Smark_marker
, 0, 0, 0,
450 doc
: /* Return this buffer's mark, as a marker object.
451 Watch out! Moving this marker changes the mark position.
452 If you set the marker not to point anywhere, the buffer will have no mark. */)
455 return BVAR (current_buffer
, mark
);
459 /* Find all the overlays in the current buffer that touch position POS.
460 Return the number found, and store them in a vector in VEC
464 overlays_around (EMACS_INT pos
, Lisp_Object
*vec
, ptrdiff_t len
)
466 Lisp_Object overlay
, start
, end
;
467 struct Lisp_Overlay
*tail
;
468 ptrdiff_t startpos
, endpos
;
471 for (tail
= current_buffer
->overlays_before
; tail
; tail
= tail
->next
)
473 XSETMISC (overlay
, tail
);
475 end
= OVERLAY_END (overlay
);
476 endpos
= OVERLAY_POSITION (end
);
479 start
= OVERLAY_START (overlay
);
480 startpos
= OVERLAY_POSITION (start
);
485 /* Keep counting overlays even if we can't return them all. */
490 for (tail
= current_buffer
->overlays_after
; tail
; tail
= tail
->next
)
492 XSETMISC (overlay
, tail
);
494 start
= OVERLAY_START (overlay
);
495 startpos
= OVERLAY_POSITION (start
);
498 end
= OVERLAY_END (overlay
);
499 endpos
= OVERLAY_POSITION (end
);
511 DEFUN ("get-pos-property", Fget_pos_property
, Sget_pos_property
, 2, 3, 0,
512 doc
: /* Return the value of POSITION's property PROP, in OBJECT.
513 Almost identical to `get-char-property' except for the following difference:
514 Whereas `get-char-property' returns the property of the char at (i.e. right
515 after) POSITION, this pays attention to properties's stickiness and overlays's
516 advancement settings, in order to find the property of POSITION itself,
517 i.e. the property that a char would inherit if it were inserted
519 (Lisp_Object position
, register Lisp_Object prop
, Lisp_Object object
)
521 CHECK_NUMBER_COERCE_MARKER (position
);
524 XSETBUFFER (object
, current_buffer
);
525 else if (WINDOWP (object
))
526 object
= XWINDOW (object
)->contents
;
528 if (!BUFFERP (object
))
529 /* pos-property only makes sense in buffers right now, since strings
530 have no overlays and no notion of insertion for which stickiness
532 return Fget_text_property (position
, prop
, object
);
535 EMACS_INT posn
= XINT (position
);
537 Lisp_Object
*overlay_vec
, tem
;
538 struct buffer
*obuf
= current_buffer
;
541 set_buffer_temp (XBUFFER (object
));
543 /* First try with room for 40 overlays. */
544 Lisp_Object overlay_vecbuf
[40];
545 noverlays
= ARRAYELTS (overlay_vecbuf
);
546 overlay_vec
= overlay_vecbuf
;
547 noverlays
= overlays_around (posn
, overlay_vec
, noverlays
);
549 /* If there are more than 40,
550 make enough space for all, and try again. */
551 if (ARRAYELTS (overlay_vecbuf
) < noverlays
)
553 SAFE_ALLOCA_LISP (overlay_vec
, noverlays
);
554 noverlays
= overlays_around (posn
, overlay_vec
, noverlays
);
556 noverlays
= sort_overlays (overlay_vec
, noverlays
, NULL
);
558 set_buffer_temp (obuf
);
560 /* Now check the overlays in order of decreasing priority. */
561 while (--noverlays
>= 0)
563 Lisp_Object ol
= overlay_vec
[noverlays
];
564 tem
= Foverlay_get (ol
, prop
);
567 /* Check the overlay is indeed active at point. */
568 Lisp_Object start
= OVERLAY_START (ol
), finish
= OVERLAY_END (ol
);
569 if ((OVERLAY_POSITION (start
) == posn
570 && XMARKER (start
)->insertion_type
== 1)
571 || (OVERLAY_POSITION (finish
) == posn
572 && XMARKER (finish
)->insertion_type
== 0))
573 ; /* The overlay will not cover a char inserted at point. */
583 { /* Now check the text properties. */
584 int stickiness
= text_property_stickiness (prop
, position
, object
);
586 return Fget_text_property (position
, prop
, object
);
587 else if (stickiness
< 0
588 && XINT (position
) > BUF_BEGV (XBUFFER (object
)))
589 return Fget_text_property (make_number (XINT (position
) - 1),
597 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
598 the value of point is used instead. If BEG or END is null,
599 means don't store the beginning or end of the field.
601 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
602 results; they do not effect boundary behavior.
604 If MERGE_AT_BOUNDARY is non-nil, then if POS is at the very first
605 position of a field, then the beginning of the previous field is
606 returned instead of the beginning of POS's field (since the end of a
607 field is actually also the beginning of the next input field, this
608 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
609 non-nil case, if two fields are separated by a field with the special
610 value `boundary', and POS lies within it, then the two separated
611 fields are considered to be adjacent, and POS between them, when
612 finding the beginning and ending of the "merged" field.
614 Either BEG or END may be 0, in which case the corresponding value
618 find_field (Lisp_Object pos
, Lisp_Object merge_at_boundary
,
619 Lisp_Object beg_limit
,
620 ptrdiff_t *beg
, Lisp_Object end_limit
, ptrdiff_t *end
)
622 /* Fields right before and after the point. */
623 Lisp_Object before_field
, after_field
;
624 /* True if POS counts as the start of a field. */
625 bool at_field_start
= 0;
626 /* True if POS counts as the end of a field. */
627 bool at_field_end
= 0;
630 XSETFASTINT (pos
, PT
);
632 CHECK_NUMBER_COERCE_MARKER (pos
);
635 = get_char_property_and_overlay (pos
, Qfield
, Qnil
, NULL
);
637 = (XFASTINT (pos
) > BEGV
638 ? get_char_property_and_overlay (make_number (XINT (pos
) - 1),
640 /* Using nil here would be a more obvious choice, but it would
641 fail when the buffer starts with a non-sticky field. */
644 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
645 and POS is at beginning of a field, which can also be interpreted
646 as the end of the previous field. Note that the case where if
647 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
648 more natural one; then we avoid treating the beginning of a field
650 if (NILP (merge_at_boundary
))
652 Lisp_Object field
= Fget_pos_property (pos
, Qfield
, Qnil
);
653 if (!EQ (field
, after_field
))
655 if (!EQ (field
, before_field
))
657 if (NILP (field
) && at_field_start
&& at_field_end
)
658 /* If an inserted char would have a nil field while the surrounding
659 text is non-nil, we're probably not looking at a
660 zero-length field, but instead at a non-nil field that's
661 not intended for editing (such as comint's prompts). */
662 at_field_end
= at_field_start
= 0;
665 /* Note about special `boundary' fields:
667 Consider the case where the point (`.') is between the fields `x' and `y':
671 In this situation, if merge_at_boundary is non-nil, consider the
672 `x' and `y' fields as forming one big merged field, and so the end
673 of the field is the end of `y'.
675 However, if `x' and `y' are separated by a special `boundary' field
676 (a field with a `field' char-property of 'boundary), then ignore
677 this special field when merging adjacent fields. Here's the same
678 situation, but with a `boundary' field between the `x' and `y' fields:
682 Here, if point is at the end of `x', the beginning of `y', or
683 anywhere in-between (within the `boundary' field), merge all
684 three fields and consider the beginning as being the beginning of
685 the `x' field, and the end as being the end of the `y' field. */
690 /* POS is at the edge of a field, and we should consider it as
691 the beginning of the following field. */
692 *beg
= XFASTINT (pos
);
694 /* Find the previous field boundary. */
697 if (!NILP (merge_at_boundary
) && EQ (before_field
, Qboundary
))
698 /* Skip a `boundary' field. */
699 p
= Fprevious_single_char_property_change (p
, Qfield
, Qnil
,
702 p
= Fprevious_single_char_property_change (p
, Qfield
, Qnil
,
704 *beg
= NILP (p
) ? BEGV
: XFASTINT (p
);
711 /* POS is at the edge of a field, and we should consider it as
712 the end of the previous field. */
713 *end
= XFASTINT (pos
);
715 /* Find the next field boundary. */
717 if (!NILP (merge_at_boundary
) && EQ (after_field
, Qboundary
))
718 /* Skip a `boundary' field. */
719 pos
= Fnext_single_char_property_change (pos
, Qfield
, Qnil
,
722 pos
= Fnext_single_char_property_change (pos
, Qfield
, Qnil
,
724 *end
= NILP (pos
) ? ZV
: XFASTINT (pos
);
730 DEFUN ("delete-field", Fdelete_field
, Sdelete_field
, 0, 1, 0,
731 doc
: /* Delete the field surrounding POS.
732 A field is a region of text with the same `field' property.
733 If POS is nil, the value of point is used for POS. */)
737 find_field (pos
, Qnil
, Qnil
, &beg
, Qnil
, &end
);
739 del_range (beg
, end
);
743 DEFUN ("field-string", Ffield_string
, Sfield_string
, 0, 1, 0,
744 doc
: /* Return the contents of the field surrounding POS as a string.
745 A field is a region of text with the same `field' property.
746 If POS is nil, the value of point is used for POS. */)
750 find_field (pos
, Qnil
, Qnil
, &beg
, Qnil
, &end
);
751 return make_buffer_string (beg
, end
, 1);
754 DEFUN ("field-string-no-properties", Ffield_string_no_properties
, Sfield_string_no_properties
, 0, 1, 0,
755 doc
: /* Return the contents of the field around POS, without text properties.
756 A field is a region of text with the same `field' property.
757 If POS is nil, the value of point is used for POS. */)
761 find_field (pos
, Qnil
, Qnil
, &beg
, Qnil
, &end
);
762 return make_buffer_string (beg
, end
, 0);
765 DEFUN ("field-beginning", Ffield_beginning
, Sfield_beginning
, 0, 3, 0,
766 doc
: /* Return the beginning of the field surrounding POS.
767 A field is a region of text with the same `field' property.
768 If POS is nil, the value of point is used for POS.
769 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
770 field, then the beginning of the *previous* field is returned.
771 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
772 is before LIMIT, then LIMIT will be returned instead. */)
773 (Lisp_Object pos
, Lisp_Object escape_from_edge
, Lisp_Object limit
)
776 find_field (pos
, escape_from_edge
, limit
, &beg
, Qnil
, 0);
777 return make_number (beg
);
780 DEFUN ("field-end", Ffield_end
, Sfield_end
, 0, 3, 0,
781 doc
: /* Return the end of the field surrounding POS.
782 A field is a region of text with the same `field' property.
783 If POS is nil, the value of point is used for POS.
784 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
785 then the end of the *following* field is returned.
786 If LIMIT is non-nil, it is a buffer position; if the end of the field
787 is after LIMIT, then LIMIT will be returned instead. */)
788 (Lisp_Object pos
, Lisp_Object escape_from_edge
, Lisp_Object limit
)
791 find_field (pos
, escape_from_edge
, Qnil
, 0, limit
, &end
);
792 return make_number (end
);
795 DEFUN ("constrain-to-field", Fconstrain_to_field
, Sconstrain_to_field
, 2, 5, 0,
796 doc
: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
797 A field is a region of text with the same `field' property.
799 If NEW-POS is nil, then use the current point instead, and move point
800 to the resulting constrained position, in addition to returning that
803 If OLD-POS is at the boundary of two fields, then the allowable
804 positions for NEW-POS depends on the value of the optional argument
805 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
806 constrained to the field that has the same `field' char-property
807 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
808 is non-nil, NEW-POS is constrained to the union of the two adjacent
809 fields. Additionally, if two fields are separated by another field with
810 the special value `boundary', then any point within this special field is
811 also considered to be `on the boundary'.
813 If the optional argument ONLY-IN-LINE is non-nil and constraining
814 NEW-POS would move it to a different line, NEW-POS is returned
815 unconstrained. This is useful for commands that move by line, like
816 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
817 only in the case where they can still move to the right line.
819 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
820 a non-nil property of that name, then any field boundaries are ignored.
822 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
823 (Lisp_Object new_pos
, Lisp_Object old_pos
, Lisp_Object escape_from_edge
,
824 Lisp_Object only_in_line
, Lisp_Object inhibit_capture_property
)
826 /* If non-zero, then the original point, before re-positioning. */
827 ptrdiff_t orig_point
= 0;
829 Lisp_Object prev_old
, prev_new
;
832 /* Use the current point, and afterwards, set it. */
835 XSETFASTINT (new_pos
, PT
);
838 CHECK_NUMBER_COERCE_MARKER (new_pos
);
839 CHECK_NUMBER_COERCE_MARKER (old_pos
);
841 fwd
= (XINT (new_pos
) > XINT (old_pos
));
843 prev_old
= make_number (XINT (old_pos
) - 1);
844 prev_new
= make_number (XINT (new_pos
) - 1);
846 if (NILP (Vinhibit_field_text_motion
)
847 && !EQ (new_pos
, old_pos
)
848 && (!NILP (Fget_char_property (new_pos
, Qfield
, Qnil
))
849 || !NILP (Fget_char_property (old_pos
, Qfield
, Qnil
))
850 /* To recognize field boundaries, we must also look at the
851 previous positions; we could use `Fget_pos_property'
852 instead, but in itself that would fail inside non-sticky
853 fields (like comint prompts). */
854 || (XFASTINT (new_pos
) > BEGV
855 && !NILP (Fget_char_property (prev_new
, Qfield
, Qnil
)))
856 || (XFASTINT (old_pos
) > BEGV
857 && !NILP (Fget_char_property (prev_old
, Qfield
, Qnil
))))
858 && (NILP (inhibit_capture_property
)
859 /* Field boundaries are again a problem; but now we must
860 decide the case exactly, so we need to call
861 `get_pos_property' as well. */
862 || (NILP (Fget_pos_property (old_pos
, inhibit_capture_property
, Qnil
))
863 && (XFASTINT (old_pos
) <= BEGV
864 || NILP (Fget_char_property
865 (old_pos
, inhibit_capture_property
, Qnil
))
866 || NILP (Fget_char_property
867 (prev_old
, inhibit_capture_property
, Qnil
))))))
868 /* It is possible that NEW_POS is not within the same field as
869 OLD_POS; try to move NEW_POS so that it is. */
872 Lisp_Object field_bound
;
875 field_bound
= Ffield_end (old_pos
, escape_from_edge
, new_pos
);
877 field_bound
= Ffield_beginning (old_pos
, escape_from_edge
, new_pos
);
879 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
880 other side of NEW_POS, which would mean that NEW_POS is
881 already acceptable, and it's not necessary to constrain it
883 ((XFASTINT (field_bound
) < XFASTINT (new_pos
)) ? fwd
: !fwd
)
884 /* NEW_POS should be constrained, but only if either
885 ONLY_IN_LINE is nil (in which case any constraint is OK),
886 or NEW_POS and FIELD_BOUND are on the same line (in which
887 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
888 && (NILP (only_in_line
)
889 /* This is the ONLY_IN_LINE case, check that NEW_POS and
890 FIELD_BOUND are on the same line by seeing whether
891 there's an intervening newline or not. */
892 || (find_newline (XFASTINT (new_pos
), -1,
893 XFASTINT (field_bound
), -1,
894 fwd
? -1 : 1, &shortage
, NULL
, 1),
896 /* Constrain NEW_POS to FIELD_BOUND. */
897 new_pos
= field_bound
;
899 if (orig_point
&& XFASTINT (new_pos
) != orig_point
)
900 /* The NEW_POS argument was originally nil, so automatically set PT. */
901 SET_PT (XFASTINT (new_pos
));
908 DEFUN ("line-beginning-position",
909 Fline_beginning_position
, Sline_beginning_position
, 0, 1, 0,
910 doc
: /* Return the character position of the first character on the current line.
911 With optional argument N, scan forward N - 1 lines first.
912 If the scan reaches the end of the buffer, return that position.
914 This function ignores text display directionality; it returns the
915 position of the first character in logical order, i.e. the smallest
916 character position on the line.
918 This function constrains the returned position to the current field
919 unless that position would be on a different line than the original,
920 unconstrained result. If N is nil or 1, and a front-sticky field
921 starts at point, the scan stops as soon as it starts. To ignore field
922 boundaries, bind `inhibit-field-text-motion' to t.
924 This function does not move point. */)
927 ptrdiff_t charpos
, bytepos
;
934 scan_newline_from_point (XINT (n
) - 1, &charpos
, &bytepos
);
936 /* Return END constrained to the current input field. */
937 return Fconstrain_to_field (make_number (charpos
), make_number (PT
),
938 XINT (n
) != 1 ? Qt
: Qnil
,
942 DEFUN ("line-end-position", Fline_end_position
, Sline_end_position
, 0, 1, 0,
943 doc
: /* Return the character position of the last character on the current line.
944 With argument N not nil or 1, move forward N - 1 lines first.
945 If scan reaches end of buffer, return that position.
947 This function ignores text display directionality; it returns the
948 position of the last character in logical order, i.e. the largest
949 character position on the line.
951 This function constrains the returned position to the current field
952 unless that would be on a different line than the original,
953 unconstrained result. If N is nil or 1, and a rear-sticky field ends
954 at point, the scan stops as soon as it starts. To ignore field
955 boundaries bind `inhibit-field-text-motion' to t.
957 This function does not move point. */)
969 clipped_n
= clip_to_bounds (PTRDIFF_MIN
+ 1, XINT (n
), PTRDIFF_MAX
);
970 end_pos
= find_before_next_newline (orig
, 0, clipped_n
- (clipped_n
<= 0),
973 /* Return END_POS constrained to the current input field. */
974 return Fconstrain_to_field (make_number (end_pos
), make_number (orig
),
978 /* Save current buffer state for `save-excursion' special form.
979 We (ab)use Lisp_Misc_Save_Value to allow explicit free and so
980 offload some work from GC. */
983 save_excursion_save (void)
985 return make_save_obj_obj_obj_obj
988 /* Selected window if current buffer is shown in it, nil otherwise. */
989 (EQ (XWINDOW (selected_window
)->contents
, Fcurrent_buffer ())
990 ? selected_window
: Qnil
),
994 /* Restore saved buffer before leaving `save-excursion' special form. */
997 save_excursion_restore (Lisp_Object info
)
999 Lisp_Object tem
, tem1
;
1001 tem
= Fmarker_buffer (XSAVE_OBJECT (info
, 0));
1002 /* If we're unwinding to top level, saved buffer may be deleted. This
1003 means that all of its markers are unchained and so tem is nil. */
1010 tem
= XSAVE_OBJECT (info
, 0);
1012 unchain_marker (XMARKER (tem
));
1014 /* If buffer was visible in a window, and a different window was
1015 selected, and the old selected window is still showing this
1016 buffer, restore point in that window. */
1017 tem
= XSAVE_OBJECT (info
, 2);
1019 && !EQ (tem
, selected_window
)
1020 && (tem1
= XWINDOW (tem
)->contents
,
1021 (/* Window is live... */
1023 /* ...and it shows the current buffer. */
1024 && XBUFFER (tem1
) == current_buffer
)))
1025 Fset_window_point (tem
, make_number (PT
));
1032 DEFUN ("save-excursion", Fsave_excursion
, Ssave_excursion
, 0, UNEVALLED
, 0,
1033 doc
: /* Save point, and current buffer; execute BODY; restore those things.
1034 Executes BODY just like `progn'.
1035 The values of point and the current buffer are restored
1036 even in case of abnormal exit (throw or error).
1038 If you only want to save the current buffer but not point,
1039 then just use `save-current-buffer', or even `with-current-buffer'.
1041 Before Emacs 25.1, `save-excursion' used to save the mark state.
1042 To save the mark state as well as point and the current buffer, use
1043 `save-mark-and-excursion'.
1045 usage: (save-excursion &rest BODY) */)
1048 register Lisp_Object val
;
1049 ptrdiff_t count
= SPECPDL_INDEX ();
1051 record_unwind_protect (save_excursion_restore
, save_excursion_save ());
1053 val
= Fprogn (args
);
1054 return unbind_to (count
, val
);
1057 DEFUN ("save-current-buffer", Fsave_current_buffer
, Ssave_current_buffer
, 0, UNEVALLED
, 0,
1058 doc
: /* Record which buffer is current; execute BODY; make that buffer current.
1059 BODY is executed just like `progn'.
1060 usage: (save-current-buffer &rest BODY) */)
1063 ptrdiff_t count
= SPECPDL_INDEX ();
1065 record_unwind_current_buffer ();
1066 return unbind_to (count
, Fprogn (args
));
1069 DEFUN ("buffer-size", Fbuffer_size
, Sbuffer_size
, 0, 1, 0,
1070 doc
: /* Return the number of characters in the current buffer.
1071 If BUFFER is not nil, return the number of characters in that buffer
1074 This does not take narrowing into account; to count the number of
1075 characters in the accessible portion of the current buffer, use
1076 `(- (point-max) (point-min))', and to count the number of characters
1077 in some other BUFFER, use
1078 `(with-current-buffer BUFFER (- (point-max) (point-min)))'. */)
1079 (Lisp_Object buffer
)
1082 return make_number (Z
- BEG
);
1085 CHECK_BUFFER (buffer
);
1086 return make_number (BUF_Z (XBUFFER (buffer
))
1087 - BUF_BEG (XBUFFER (buffer
)));
1091 DEFUN ("point-min", Fpoint_min
, Spoint_min
, 0, 0, 0,
1092 doc
: /* Return the minimum permissible value of point in the current buffer.
1093 This is 1, unless narrowing (a buffer restriction) is in effect. */)
1097 XSETFASTINT (temp
, BEGV
);
1101 DEFUN ("point-min-marker", Fpoint_min_marker
, Spoint_min_marker
, 0, 0, 0,
1102 doc
: /* Return a marker to the minimum permissible value of point in this buffer.
1103 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1106 return build_marker (current_buffer
, BEGV
, BEGV_BYTE
);
1109 DEFUN ("point-max", Fpoint_max
, Spoint_max
, 0, 0, 0,
1110 doc
: /* Return the maximum permissible value of point in the current buffer.
1111 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1112 is in effect, in which case it is less. */)
1116 XSETFASTINT (temp
, ZV
);
1120 DEFUN ("point-max-marker", Fpoint_max_marker
, Spoint_max_marker
, 0, 0, 0,
1121 doc
: /* Return a marker to the maximum permissible value of point in this buffer.
1122 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1123 is in effect, in which case it is less. */)
1126 return build_marker (current_buffer
, ZV
, ZV_BYTE
);
1129 DEFUN ("gap-position", Fgap_position
, Sgap_position
, 0, 0, 0,
1130 doc
: /* Return the position of the gap, in the current buffer.
1131 See also `gap-size'. */)
1135 XSETFASTINT (temp
, GPT
);
1139 DEFUN ("gap-size", Fgap_size
, Sgap_size
, 0, 0, 0,
1140 doc
: /* Return the size of the current buffer's gap.
1141 See also `gap-position'. */)
1145 XSETFASTINT (temp
, GAP_SIZE
);
1149 DEFUN ("position-bytes", Fposition_bytes
, Sposition_bytes
, 1, 1, 0,
1150 doc
: /* Return the byte position for character position POSITION.
1151 If POSITION is out of range, the value is nil. */)
1152 (Lisp_Object position
)
1154 CHECK_NUMBER_COERCE_MARKER (position
);
1155 if (XINT (position
) < BEG
|| XINT (position
) > Z
)
1157 return make_number (CHAR_TO_BYTE (XINT (position
)));
1160 DEFUN ("byte-to-position", Fbyte_to_position
, Sbyte_to_position
, 1, 1, 0,
1161 doc
: /* Return the character position for byte position BYTEPOS.
1162 If BYTEPOS is out of range, the value is nil. */)
1163 (Lisp_Object bytepos
)
1167 CHECK_NUMBER (bytepos
);
1168 pos_byte
= XINT (bytepos
);
1169 if (pos_byte
< BEG_BYTE
|| pos_byte
> Z_BYTE
)
1172 /* There are multibyte characters in the buffer.
1173 The argument of BYTE_TO_CHAR must be a byte position at
1174 a character boundary, so search for the start of the current
1176 while (!CHAR_HEAD_P (FETCH_BYTE (pos_byte
)))
1178 return make_number (BYTE_TO_CHAR (pos_byte
));
1181 DEFUN ("following-char", Ffollowing_char
, Sfollowing_char
, 0, 0, 0,
1182 doc
: /* Return the character following point, as a number.
1183 At the end of the buffer or accessible region, return 0. */)
1188 XSETFASTINT (temp
, 0);
1190 XSETFASTINT (temp
, FETCH_CHAR (PT_BYTE
));
1194 DEFUN ("preceding-char", Fprevious_char
, Sprevious_char
, 0, 0, 0,
1195 doc
: /* Return the character preceding point, as a number.
1196 At the beginning of the buffer or accessible region, return 0. */)
1201 XSETFASTINT (temp
, 0);
1202 else if (!NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
1204 ptrdiff_t pos
= PT_BYTE
;
1206 XSETFASTINT (temp
, FETCH_CHAR (pos
));
1209 XSETFASTINT (temp
, FETCH_BYTE (PT_BYTE
- 1));
1213 DEFUN ("bobp", Fbobp
, Sbobp
, 0, 0, 0,
1214 doc
: /* Return t if point is at the beginning of the buffer.
1215 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1223 DEFUN ("eobp", Feobp
, Seobp
, 0, 0, 0,
1224 doc
: /* Return t if point is at the end of the buffer.
1225 If the buffer is narrowed, this means the end of the narrowed part. */)
1233 DEFUN ("bolp", Fbolp
, Sbolp
, 0, 0, 0,
1234 doc
: /* Return t if point is at the beginning of a line. */)
1237 if (PT
== BEGV
|| FETCH_BYTE (PT_BYTE
- 1) == '\n')
1242 DEFUN ("eolp", Feolp
, Seolp
, 0, 0, 0,
1243 doc
: /* Return t if point is at the end of a line.
1244 `End of a line' includes point being at the end of the buffer. */)
1247 if (PT
== ZV
|| FETCH_BYTE (PT_BYTE
) == '\n')
1252 DEFUN ("char-after", Fchar_after
, Schar_after
, 0, 1, 0,
1253 doc
: /* Return character in current buffer at position POS.
1254 POS is an integer or a marker and defaults to point.
1255 If POS is out of range, the value is nil. */)
1258 register ptrdiff_t pos_byte
;
1263 if (pos_byte
< BEGV_BYTE
|| pos_byte
>= ZV_BYTE
)
1266 else if (MARKERP (pos
))
1268 pos_byte
= marker_byte_position (pos
);
1269 if (pos_byte
< BEGV_BYTE
|| pos_byte
>= ZV_BYTE
)
1274 CHECK_NUMBER_COERCE_MARKER (pos
);
1275 if (XINT (pos
) < BEGV
|| XINT (pos
) >= ZV
)
1278 pos_byte
= CHAR_TO_BYTE (XINT (pos
));
1281 return make_number (FETCH_CHAR (pos_byte
));
1284 DEFUN ("char-before", Fchar_before
, Schar_before
, 0, 1, 0,
1285 doc
: /* Return character in current buffer preceding position POS.
1286 POS is an integer or a marker and defaults to point.
1287 If POS is out of range, the value is nil. */)
1290 register Lisp_Object val
;
1291 register ptrdiff_t pos_byte
;
1296 XSETFASTINT (pos
, PT
);
1301 pos_byte
= marker_byte_position (pos
);
1303 if (pos_byte
<= BEGV_BYTE
|| pos_byte
> ZV_BYTE
)
1308 CHECK_NUMBER_COERCE_MARKER (pos
);
1310 if (XINT (pos
) <= BEGV
|| XINT (pos
) > ZV
)
1313 pos_byte
= CHAR_TO_BYTE (XINT (pos
));
1316 if (!NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
1319 XSETFASTINT (val
, FETCH_CHAR (pos_byte
));
1324 XSETFASTINT (val
, FETCH_BYTE (pos_byte
));
1329 DEFUN ("user-login-name", Fuser_login_name
, Suser_login_name
, 0, 1, 0,
1330 doc
: /* Return the name under which the user logged in, as a string.
1331 This is based on the effective uid, not the real uid.
1332 Also, if the environment variables LOGNAME or USER are set,
1333 that determines the value of this function.
1335 If optional argument UID is an integer or a float, return the login name
1336 of the user with that uid, or nil if there is no such user. */)
1342 /* Set up the user name info if we didn't do it before.
1343 (That can happen if Emacs is dumpable
1344 but you decide to run `temacs -l loadup' and not dump. */
1345 if (NILP (Vuser_login_name
))
1346 init_editfns (false);
1349 return Vuser_login_name
;
1351 CONS_TO_INTEGER (uid
, uid_t
, id
);
1355 return (pw
? build_string (pw
->pw_name
) : Qnil
);
1358 DEFUN ("user-real-login-name", Fuser_real_login_name
, Suser_real_login_name
,
1360 doc
: /* Return the name of the user's real uid, as a string.
1361 This ignores the environment variables LOGNAME and USER, so it differs from
1362 `user-login-name' when running under `su'. */)
1365 /* Set up the user name info if we didn't do it before.
1366 (That can happen if Emacs is dumpable
1367 but you decide to run `temacs -l loadup' and not dump. */
1368 if (NILP (Vuser_login_name
))
1369 init_editfns (false);
1370 return Vuser_real_login_name
;
1373 DEFUN ("user-uid", Fuser_uid
, Suser_uid
, 0, 0, 0,
1374 doc
: /* Return the effective uid of Emacs.
1375 Value is an integer or a float, depending on the value. */)
1378 uid_t euid
= geteuid ();
1379 return make_fixnum_or_float (euid
);
1382 DEFUN ("user-real-uid", Fuser_real_uid
, Suser_real_uid
, 0, 0, 0,
1383 doc
: /* Return the real uid of Emacs.
1384 Value is an integer or a float, depending on the value. */)
1387 uid_t uid
= getuid ();
1388 return make_fixnum_or_float (uid
);
1391 DEFUN ("group-gid", Fgroup_gid
, Sgroup_gid
, 0, 0, 0,
1392 doc
: /* Return the effective gid of Emacs.
1393 Value is an integer or a float, depending on the value. */)
1396 gid_t egid
= getegid ();
1397 return make_fixnum_or_float (egid
);
1400 DEFUN ("group-real-gid", Fgroup_real_gid
, Sgroup_real_gid
, 0, 0, 0,
1401 doc
: /* Return the real gid of Emacs.
1402 Value is an integer or a float, depending on the value. */)
1405 gid_t gid
= getgid ();
1406 return make_fixnum_or_float (gid
);
1409 DEFUN ("user-full-name", Fuser_full_name
, Suser_full_name
, 0, 1, 0,
1410 doc
: /* Return the full name of the user logged in, as a string.
1411 If the full name corresponding to Emacs's userid is not known,
1414 If optional argument UID is an integer or float, return the full name
1415 of the user with that uid, or nil if there is no such user.
1416 If UID is a string, return the full name of the user with that login
1417 name, or nil if there is no such user. */)
1421 register char *p
, *q
;
1425 return Vuser_full_name
;
1426 else if (NUMBERP (uid
))
1429 CONS_TO_INTEGER (uid
, uid_t
, u
);
1434 else if (STRINGP (uid
))
1437 pw
= getpwnam (SSDATA (uid
));
1441 error ("Invalid UID specification");
1447 /* Chop off everything after the first comma. */
1448 q
= strchr (p
, ',');
1449 full
= make_string (p
, q
? q
- p
: strlen (p
));
1451 #ifdef AMPERSAND_FULL_NAME
1453 q
= strchr (p
, '&');
1454 /* Substitute the login name for the &, upcasing the first character. */
1457 Lisp_Object login
= Fuser_login_name (make_number (pw
->pw_uid
));
1459 char *r
= SAFE_ALLOCA (strlen (p
) + SBYTES (login
) + 1);
1460 memcpy (r
, p
, q
- p
);
1461 char *s
= lispstpcpy (&r
[q
- p
], login
);
1462 r
[q
- p
] = upcase ((unsigned char) r
[q
- p
]);
1464 full
= build_string (r
);
1467 #endif /* AMPERSAND_FULL_NAME */
1472 DEFUN ("system-name", Fsystem_name
, Ssystem_name
, 0, 0, 0,
1473 doc
: /* Return the host name of the machine you are running on, as a string. */)
1476 if (EQ (Vsystem_name
, cached_system_name
))
1477 init_and_cache_system_name ();
1478 return Vsystem_name
;
1481 DEFUN ("emacs-pid", Femacs_pid
, Semacs_pid
, 0, 0, 0,
1482 doc
: /* Return the process ID of Emacs, as a number. */)
1485 pid_t pid
= getpid ();
1486 return make_fixnum_or_float (pid
);
1492 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1495 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1498 /* Report that a time value is out of range for Emacs. */
1500 time_overflow (void)
1502 error ("Specified time is not representable");
1505 static _Noreturn
void
1508 error ("Invalid time specification");
1511 /* Check a return value compatible with that of decode_time_components. */
1513 check_time_validity (int validity
)
1524 /* Return the upper part of the time T (everything but the bottom 16 bits). */
1528 time_t hi
= t
>> LO_TIME_BITS
;
1529 if (FIXNUM_OVERFLOW_P (hi
))
1534 /* Return the bottom bits of the time T. */
1538 return t
& ((1 << LO_TIME_BITS
) - 1);
1541 DEFUN ("current-time", Fcurrent_time
, Scurrent_time
, 0, 0, 0,
1542 doc
: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1543 The time is returned as a list of integers (HIGH LOW USEC PSEC).
1544 HIGH has the most significant bits of the seconds, while LOW has the
1545 least significant 16 bits. USEC and PSEC are the microsecond and
1546 picosecond counts. */)
1549 return make_lisp_time (current_timespec ());
1552 static struct lisp_time
1553 time_add (struct lisp_time ta
, struct lisp_time tb
)
1555 EMACS_INT hi
= ta
.hi
+ tb
.hi
;
1556 int lo
= ta
.lo
+ tb
.lo
;
1557 int us
= ta
.us
+ tb
.us
;
1558 int ps
= ta
.ps
+ tb
.ps
;
1559 us
+= (1000000 <= ps
);
1560 ps
-= (1000000 <= ps
) * 1000000;
1561 lo
+= (1000000 <= us
);
1562 us
-= (1000000 <= us
) * 1000000;
1563 hi
+= (1 << LO_TIME_BITS
<= lo
);
1564 lo
-= (1 << LO_TIME_BITS
<= lo
) << LO_TIME_BITS
;
1565 return (struct lisp_time
) { hi
, lo
, us
, ps
};
1568 static struct lisp_time
1569 time_subtract (struct lisp_time ta
, struct lisp_time tb
)
1571 EMACS_INT hi
= ta
.hi
- tb
.hi
;
1572 int lo
= ta
.lo
- tb
.lo
;
1573 int us
= ta
.us
- tb
.us
;
1574 int ps
= ta
.ps
- tb
.ps
;
1576 ps
+= (ps
< 0) * 1000000;
1578 us
+= (us
< 0) * 1000000;
1580 lo
+= (lo
< 0) << LO_TIME_BITS
;
1581 return (struct lisp_time
) { hi
, lo
, us
, ps
};
1585 time_arith (Lisp_Object a
, Lisp_Object b
,
1586 struct lisp_time (*op
) (struct lisp_time
, struct lisp_time
))
1589 struct lisp_time ta
= lisp_time_struct (a
, &alen
);
1590 struct lisp_time tb
= lisp_time_struct (b
, &blen
);
1591 struct lisp_time t
= op (ta
, tb
);
1592 if (FIXNUM_OVERFLOW_P (t
.hi
))
1594 Lisp_Object val
= Qnil
;
1596 switch (max (alen
, blen
))
1599 val
= Fcons (make_number (t
.ps
), val
);
1602 val
= Fcons (make_number (t
.us
), val
);
1605 val
= Fcons (make_number (t
.lo
), val
);
1606 val
= Fcons (make_number (t
.hi
), val
);
1613 DEFUN ("time-add", Ftime_add
, Stime_add
, 2, 2, 0,
1614 doc
: /* Return the sum of two time values A and B, as a time value.
1615 A nil value for either argument stands for the current time.
1616 See `current-time-string' for the various forms of a time value. */)
1617 (Lisp_Object a
, Lisp_Object b
)
1619 return time_arith (a
, b
, time_add
);
1622 DEFUN ("time-subtract", Ftime_subtract
, Stime_subtract
, 2, 2, 0,
1623 doc
: /* Return the difference between two time values A and B, as a time value.
1624 Use `float-time' to convert the difference into elapsed seconds.
1625 A nil value for either argument stands for the current time.
1626 See `current-time-string' for the various forms of a time value. */)
1627 (Lisp_Object a
, Lisp_Object b
)
1629 return time_arith (a
, b
, time_subtract
);
1632 DEFUN ("time-less-p", Ftime_less_p
, Stime_less_p
, 2, 2, 0,
1633 doc
: /* Return non-nil if time value T1 is earlier than time value T2.
1634 A nil value for either argument stands for the current time.
1635 See `current-time-string' for the various forms of a time value. */)
1636 (Lisp_Object t1
, Lisp_Object t2
)
1639 struct lisp_time a
= lisp_time_struct (t1
, &t1len
);
1640 struct lisp_time b
= lisp_time_struct (t2
, &t2len
);
1641 return ((a
.hi
!= b
.hi
? a
.hi
< b
.hi
1642 : a
.lo
!= b
.lo
? a
.lo
< b
.lo
1643 : a
.us
!= b
.us
? a
.us
< b
.us
1649 DEFUN ("get-internal-run-time", Fget_internal_run_time
, Sget_internal_run_time
,
1651 doc
: /* Return the current run time used by Emacs.
1652 The time is returned as a list (HIGH LOW USEC PSEC), using the same
1653 style as (current-time).
1655 On systems that can't determine the run time, `get-internal-run-time'
1656 does the same thing as `current-time'. */)
1659 #ifdef HAVE_GETRUSAGE
1660 struct rusage usage
;
1664 if (getrusage (RUSAGE_SELF
, &usage
) < 0)
1665 /* This shouldn't happen. What action is appropriate? */
1668 /* Sum up user time and system time. */
1669 secs
= usage
.ru_utime
.tv_sec
+ usage
.ru_stime
.tv_sec
;
1670 usecs
= usage
.ru_utime
.tv_usec
+ usage
.ru_stime
.tv_usec
;
1671 if (usecs
>= 1000000)
1676 return make_lisp_time (make_timespec (secs
, usecs
* 1000));
1677 #else /* ! HAVE_GETRUSAGE */
1679 return w32_get_internal_run_time ();
1680 #else /* ! WINDOWSNT */
1681 return Fcurrent_time ();
1682 #endif /* WINDOWSNT */
1683 #endif /* HAVE_GETRUSAGE */
1687 /* Make a Lisp list that represents the Emacs time T. T may be an
1688 invalid time, with a slightly negative tv_nsec value such as
1689 UNKNOWN_MODTIME_NSECS; in that case, the Lisp list contains a
1690 correspondingly negative picosecond count. */
1692 make_lisp_time (struct timespec t
)
1694 time_t s
= t
.tv_sec
;
1696 return list4i (hi_time (s
), lo_time (s
), ns
/ 1000, ns
% 1000 * 1000);
1699 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1700 Set *PHIGH, *PLOW, *PUSEC, *PPSEC to its parts; do not check their values.
1701 Return 2, 3, or 4 to indicate the effective length of SPECIFIED_TIME
1702 if successful, 0 if unsuccessful. */
1704 disassemble_lisp_time (Lisp_Object specified_time
, Lisp_Object
*phigh
,
1705 Lisp_Object
*plow
, Lisp_Object
*pusec
,
1708 Lisp_Object high
= make_number (0);
1709 Lisp_Object low
= specified_time
;
1710 Lisp_Object usec
= make_number (0);
1711 Lisp_Object psec
= make_number (0);
1714 if (CONSP (specified_time
))
1716 high
= XCAR (specified_time
);
1717 low
= XCDR (specified_time
);
1720 Lisp_Object low_tail
= XCDR (low
);
1722 if (CONSP (low_tail
))
1724 usec
= XCAR (low_tail
);
1725 low_tail
= XCDR (low_tail
);
1726 if (CONSP (low_tail
))
1727 psec
= XCAR (low_tail
);
1731 else if (!NILP (low_tail
))
1742 /* When combining components, require LOW to be an integer,
1743 as otherwise it would be a pain to add up times. */
1744 if (! INTEGERP (low
))
1747 else if (INTEGERP (specified_time
))
1757 /* Convert T into an Emacs time *RESULT, truncating toward minus infinity.
1758 Return true if T is in range, false otherwise. */
1760 decode_float_time (double t
, struct lisp_time
*result
)
1762 double lo_multiplier
= 1 << LO_TIME_BITS
;
1763 double emacs_time_min
= MOST_NEGATIVE_FIXNUM
* lo_multiplier
;
1764 if (! (emacs_time_min
<= t
&& t
< -emacs_time_min
))
1767 double small_t
= t
/ lo_multiplier
;
1768 EMACS_INT hi
= small_t
;
1769 double t_sans_hi
= t
- hi
* lo_multiplier
;
1771 long double fracps
= (t_sans_hi
- lo
) * 1e12L
;
1772 #ifdef INT_FAST64_MAX
1773 int_fast64_t ifracps
= fracps
;
1774 int us
= ifracps
/ 1000000;
1775 int ps
= ifracps
% 1000000;
1777 int us
= fracps
/ 1e6L
;
1778 int ps
= fracps
- us
* 1e6L
;
1781 ps
+= (ps
< 0) * 1000000;
1783 us
+= (us
< 0) * 1000000;
1785 lo
+= (lo
< 0) << LO_TIME_BITS
;
1793 /* From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
1794 list, generate the corresponding time value.
1795 If LOW is floating point, the other components should be zero.
1797 If RESULT is not null, store into *RESULT the converted time.
1798 If *DRESULT is not null, store into *DRESULT the number of
1799 seconds since the start of the POSIX Epoch.
1801 Return 1 if successful, 0 if the components are of the
1802 wrong type, and -1 if the time is out of range. */
1804 decode_time_components (Lisp_Object high
, Lisp_Object low
, Lisp_Object usec
,
1806 struct lisp_time
*result
, double *dresult
)
1808 EMACS_INT hi
, lo
, us
, ps
;
1809 if (! (INTEGERP (high
)
1810 && INTEGERP (usec
) && INTEGERP (psec
)))
1812 if (! INTEGERP (low
))
1816 double t
= XFLOAT_DATA (low
);
1817 if (result
&& ! decode_float_time (t
, result
))
1823 else if (NILP (low
))
1825 struct timespec now
= current_timespec ();
1828 result
->hi
= hi_time (now
.tv_sec
);
1829 result
->lo
= lo_time (now
.tv_sec
);
1830 result
->us
= now
.tv_nsec
/ 1000;
1831 result
->ps
= now
.tv_nsec
% 1000 * 1000;
1834 *dresult
= now
.tv_sec
+ now
.tv_nsec
/ 1e9
;
1846 /* Normalize out-of-range lower-order components by carrying
1847 each overflow into the next higher-order component. */
1848 us
+= ps
/ 1000000 - (ps
% 1000000 < 0);
1849 lo
+= us
/ 1000000 - (us
% 1000000 < 0);
1850 hi
+= lo
>> LO_TIME_BITS
;
1851 ps
= ps
% 1000000 + 1000000 * (ps
% 1000000 < 0);
1852 us
= us
% 1000000 + 1000000 * (us
% 1000000 < 0);
1853 lo
&= (1 << LO_TIME_BITS
) - 1;
1857 if (FIXNUM_OVERFLOW_P (hi
))
1868 *dresult
= (us
* 1e6
+ ps
) / 1e12
+ lo
+ dhi
* (1 << LO_TIME_BITS
);
1875 lisp_to_timespec (struct lisp_time t
)
1877 if (! ((TYPE_SIGNED (time_t) ? TIME_T_MIN
>> LO_TIME_BITS
<= t
.hi
: 0 <= t
.hi
)
1878 && t
.hi
<= TIME_T_MAX
>> LO_TIME_BITS
))
1879 return invalid_timespec ();
1880 time_t s
= (t
.hi
<< LO_TIME_BITS
) + t
.lo
;
1881 int ns
= t
.us
* 1000 + t
.ps
/ 1000;
1882 return make_timespec (s
, ns
);
1885 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1886 Store its effective length into *PLEN.
1887 If SPECIFIED_TIME is nil, use the current time.
1888 Signal an error if SPECIFIED_TIME does not represent a time. */
1889 static struct lisp_time
1890 lisp_time_struct (Lisp_Object specified_time
, int *plen
)
1892 Lisp_Object high
, low
, usec
, psec
;
1894 int len
= disassemble_lisp_time (specified_time
, &high
, &low
, &usec
, &psec
);
1897 int val
= decode_time_components (high
, low
, usec
, psec
, &t
, 0);
1898 check_time_validity (val
);
1903 /* Like lisp_time_struct, except return a struct timespec.
1904 Discard any low-order digits. */
1906 lisp_time_argument (Lisp_Object specified_time
)
1909 struct lisp_time lt
= lisp_time_struct (specified_time
, &len
);
1910 struct timespec t
= lisp_to_timespec (lt
);
1911 if (! timespec_valid_p (t
))
1916 /* Like lisp_time_argument, except decode only the seconds part,
1917 and do not check the subseconds part. */
1919 lisp_seconds_argument (Lisp_Object specified_time
)
1921 Lisp_Object high
, low
, usec
, psec
;
1924 int val
= disassemble_lisp_time (specified_time
, &high
, &low
, &usec
, &psec
);
1927 val
= decode_time_components (high
, low
, make_number (0),
1928 make_number (0), &t
, 0);
1930 && ! ((TYPE_SIGNED (time_t)
1931 ? TIME_T_MIN
>> LO_TIME_BITS
<= t
.hi
1933 && t
.hi
<= TIME_T_MAX
>> LO_TIME_BITS
))
1936 check_time_validity (val
);
1937 return (t
.hi
<< LO_TIME_BITS
) + t
.lo
;
1940 DEFUN ("float-time", Ffloat_time
, Sfloat_time
, 0, 1, 0,
1941 doc
: /* Return the current time, as a float number of seconds since the epoch.
1942 If SPECIFIED-TIME is given, it is the time to convert to float
1943 instead of the current time. The argument should have the form
1944 \(HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus,
1945 you can use times from `current-time' and from `file-attributes'.
1946 SPECIFIED-TIME can also have the form (HIGH . LOW), but this is
1947 considered obsolete.
1949 WARNING: Since the result is floating point, it may not be exact.
1950 If precise time stamps are required, use either `current-time',
1951 or (if you need time as a string) `format-time-string'. */)
1952 (Lisp_Object specified_time
)
1955 Lisp_Object high
, low
, usec
, psec
;
1956 if (! (disassemble_lisp_time (specified_time
, &high
, &low
, &usec
, &psec
)
1957 && decode_time_components (high
, low
, usec
, psec
, 0, &t
)))
1959 return make_float (t
);
1962 /* Write information into buffer S of size MAXSIZE, according to the
1963 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1964 Use the time zone specified by TZ.
1965 Use NS as the number of nanoseconds in the %N directive.
1966 Return the number of bytes written, not including the terminating
1967 '\0'. If S is NULL, nothing will be written anywhere; so to
1968 determine how many bytes would be written, use NULL for S and
1969 ((size_t) -1) for MAXSIZE.
1971 This function behaves like nstrftime, except it allows null
1972 bytes in FORMAT and it does not support nanoseconds. */
1974 emacs_nmemftime (char *s
, size_t maxsize
, const char *format
,
1975 size_t format_len
, const struct tm
*tp
, timezone_t tz
, int ns
)
1979 /* Loop through all the null-terminated strings in the format
1980 argument. Normally there's just one null-terminated string, but
1981 there can be arbitrarily many, concatenated together, if the
1982 format contains '\0' bytes. nstrftime stops at the first
1983 '\0' byte so we must invoke it separately for each such string. */
1992 result
= nstrftime (s
, maxsize
, format
, tp
, tz
, ns
);
1996 if (result
== 0 && s
[0] != '\0')
2001 maxsize
-= result
+ 1;
2003 len
= strlen (format
);
2004 if (len
== format_len
)
2008 format_len
-= len
+ 1;
2012 DEFUN ("format-time-string", Fformat_time_string
, Sformat_time_string
, 1, 3, 0,
2013 doc
: /* Use FORMAT-STRING to format the time TIME, or now if omitted or nil.
2014 TIME is specified as (HIGH LOW USEC PSEC), as returned by
2015 `current-time' or `file-attributes'. It can also be a single integer
2016 number of seconds since the epoch. The obsolete form (HIGH . LOW) is
2017 also still accepted.
2019 The optional ZONE is omitted or nil for Emacs local time, t for
2020 Universal Time, `wall' for system wall clock time, or a string as in
2021 the TZ environment variable. It can also be a list (as from
2022 `current-time-zone') or an integer (as from `decode-time') applied
2023 without consideration for daylight saving time.
2025 The value is a copy of FORMAT-STRING, but with certain constructs replaced
2026 by text that describes the specified date and time in TIME:
2028 %Y is the year, %y within the century, %C the century.
2029 %G is the year corresponding to the ISO week, %g within the century.
2030 %m is the numeric month.
2031 %b and %h are the locale's abbreviated month name, %B the full name.
2032 (%h is not supported on MS-Windows.)
2033 %d is the day of the month, zero-padded, %e is blank-padded.
2034 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
2035 %a is the locale's abbreviated name of the day of week, %A the full name.
2036 %U is the week number starting on Sunday, %W starting on Monday,
2037 %V according to ISO 8601.
2038 %j is the day of the year.
2040 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
2041 only blank-padded, %l is like %I blank-padded.
2042 %p is the locale's equivalent of either AM or PM.
2043 %q is the calendar quarter (1–4).
2044 %M is the minute (00-59).
2045 %S is the second (00-59; 00-60 on platforms with leap seconds)
2046 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
2047 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
2048 %Z is the time zone abbreviation, %z is the numeric form.
2050 %c is the locale's date and time format.
2051 %x is the locale's "preferred" date format.
2052 %D is like "%m/%d/%y".
2053 %F is the ISO 8601 date format (like "%Y-%m-%d").
2055 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
2056 %X is the locale's "preferred" time format.
2058 Finally, %n is a newline, %t is a tab, %% is a literal %, and
2059 unrecognized %-sequences stand for themselves.
2061 Certain flags and modifiers are available with some format controls.
2062 The flags are `_', `-', `^' and `#'. For certain characters X,
2063 %_X is like %X, but padded with blanks; %-X is like %X,
2064 but without padding. %^X is like %X, but with all textual
2065 characters up-cased; %#X is like %X, but with letter-case of
2066 all textual characters reversed.
2067 %NX (where N stands for an integer) is like %X,
2068 but takes up at least N (a number) positions.
2069 The modifiers are `E' and `O'. For certain characters X,
2070 %EX is a locale's alternative version of %X;
2071 %OX is like %X, but uses the locale's number symbols.
2073 For example, to produce full ISO 8601 format, use "%FT%T%z".
2075 usage: (format-time-string FORMAT-STRING &optional TIME ZONE) */)
2076 (Lisp_Object format_string
, Lisp_Object timeval
, Lisp_Object zone
)
2078 struct timespec t
= lisp_time_argument (timeval
);
2081 CHECK_STRING (format_string
);
2082 format_string
= code_convert_string_norecord (format_string
,
2083 Vlocale_coding_system
, 1);
2084 return format_time_string (SSDATA (format_string
), SBYTES (format_string
),
2089 format_time_string (char const *format
, ptrdiff_t formatlen
,
2090 struct timespec t
, Lisp_Object zone
, struct tm
*tmp
)
2094 ptrdiff_t size
= sizeof buffer
;
2099 timezone_t tz
= tzlookup (zone
, false);
2100 /* On some systems, like 32-bit MinGW, tv_sec of struct timespec is
2101 a 64-bit type, but time_t is a 32-bit type. emacs_localtime_rz
2102 expects a pointer to time_t value. */
2103 time_t tsec
= t
.tv_sec
;
2104 tmp
= emacs_localtime_rz (tz
, &tsec
, tmp
);
2110 synchronize_system_time_locale ();
2115 len
= emacs_nmemftime (buf
, size
, format
, formatlen
, tmp
, tz
, ns
);
2116 if ((0 < len
&& len
< size
) || (len
== 0 && buf
[0] == '\0'))
2119 /* Buffer was too small, so make it bigger and try again. */
2120 len
= emacs_nmemftime (NULL
, SIZE_MAX
, format
, formatlen
, tmp
, tz
, ns
);
2121 if (STRING_BYTES_BOUND
<= len
)
2127 buf
= SAFE_ALLOCA (size
);
2131 AUTO_STRING_WITH_LEN (bufstring
, buf
, len
);
2132 Lisp_Object result
= code_convert_string_norecord (bufstring
,
2133 Vlocale_coding_system
, 0);
2138 DEFUN ("decode-time", Fdecode_time
, Sdecode_time
, 0, 2, 0,
2139 doc
: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST UTCOFF).
2140 The optional TIME should be a list of (HIGH LOW . IGNORED),
2141 as from `current-time' and `file-attributes', or nil to use the
2142 current time. It can also be a single integer number of seconds since
2143 the epoch. The obsolete form (HIGH . LOW) is also still accepted.
2145 The optional ZONE is omitted or nil for Emacs local time, t for
2146 Universal Time, `wall' for system wall clock time, or a string as in
2147 the TZ environment variable. It can also be a list (as from
2148 `current-time-zone') or an integer (the UTC offset in seconds) applied
2149 without consideration for daylight saving time.
2151 The list has the following nine members: SEC is an integer between 0
2152 and 60; SEC is 60 for a leap second, which only some operating systems
2153 support. MINUTE is an integer between 0 and 59. HOUR is an integer
2154 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
2155 integer between 1 and 12. YEAR is an integer indicating the
2156 four-digit year. DOW is the day of week, an integer between 0 and 6,
2157 where 0 is Sunday. DST is t if daylight saving time is in effect,
2158 otherwise nil. UTCOFF is an integer indicating the UTC offset in
2159 seconds, i.e., the number of seconds east of Greenwich. (Note that
2160 Common Lisp has different meanings for DOW and UTCOFF.)
2162 usage: (decode-time &optional TIME ZONE) */)
2163 (Lisp_Object specified_time
, Lisp_Object zone
)
2165 time_t time_spec
= lisp_seconds_argument (specified_time
);
2166 struct tm local_tm
, gmt_tm
;
2167 timezone_t tz
= tzlookup (zone
, false);
2168 struct tm
*tm
= emacs_localtime_rz (tz
, &time_spec
, &local_tm
);
2172 && MOST_NEGATIVE_FIXNUM
- TM_YEAR_BASE
<= local_tm
.tm_year
2173 && local_tm
.tm_year
<= MOST_POSITIVE_FIXNUM
- TM_YEAR_BASE
))
2176 /* Avoid overflow when INT_MAX < EMACS_INT_MAX. */
2177 EMACS_INT tm_year_base
= TM_YEAR_BASE
;
2179 return CALLN (Flist
,
2180 make_number (local_tm
.tm_sec
),
2181 make_number (local_tm
.tm_min
),
2182 make_number (local_tm
.tm_hour
),
2183 make_number (local_tm
.tm_mday
),
2184 make_number (local_tm
.tm_mon
+ 1),
2185 make_number (local_tm
.tm_year
+ tm_year_base
),
2186 make_number (local_tm
.tm_wday
),
2187 local_tm
.tm_isdst
? Qt
: Qnil
,
2189 ? make_number (tm_gmtoff (&local_tm
))
2190 : gmtime_r (&time_spec
, &gmt_tm
)
2191 ? make_number (tm_diff (&local_tm
, &gmt_tm
))
2195 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
2196 the result is representable as an int. */
2198 check_tm_member (Lisp_Object obj
, int offset
)
2201 EMACS_INT n
= XINT (obj
);
2203 if (INT_SUBTRACT_WRAPV (n
, offset
, &result
))
2208 DEFUN ("encode-time", Fencode_time
, Sencode_time
, 6, MANY
, 0,
2209 doc
: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
2210 This is the reverse operation of `decode-time', which see.
2212 The optional ZONE is omitted or nil for Emacs local time, t for
2213 Universal Time, `wall' for system wall clock time, or a string as in
2214 the TZ environment variable. It can also be a list (as from
2215 `current-time-zone') or an integer (as from `decode-time') applied
2216 without consideration for daylight saving time.
2218 You can pass more than 7 arguments; then the first six arguments
2219 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
2220 The intervening arguments are ignored.
2221 This feature lets (apply \\='encode-time (decode-time ...)) work.
2223 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
2224 for example, a DAY of 0 means the day preceding the given month.
2225 Year numbers less than 100 are treated just like other year numbers.
2226 If you want them to stand for years in this century, you must do that yourself.
2228 Years before 1970 are not guaranteed to work. On some systems,
2229 year values as low as 1901 do work.
2231 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
2232 (ptrdiff_t nargs
, Lisp_Object
*args
)
2236 Lisp_Object zone
= (nargs
> 6 ? args
[nargs
- 1] : Qnil
);
2238 tm
.tm_sec
= check_tm_member (args
[0], 0);
2239 tm
.tm_min
= check_tm_member (args
[1], 0);
2240 tm
.tm_hour
= check_tm_member (args
[2], 0);
2241 tm
.tm_mday
= check_tm_member (args
[3], 0);
2242 tm
.tm_mon
= check_tm_member (args
[4], 1);
2243 tm
.tm_year
= check_tm_member (args
[5], TM_YEAR_BASE
);
2246 timezone_t tz
= tzlookup (zone
, false);
2247 value
= emacs_mktime_z (tz
, &tm
);
2250 if (value
== (time_t) -1)
2253 return list2i (hi_time (value
), lo_time (value
));
2256 DEFUN ("current-time-string", Fcurrent_time_string
, Scurrent_time_string
,
2258 doc
: /* Return the current local time, as a human-readable string.
2259 Programs can use this function to decode a time,
2260 since the number of columns in each field is fixed
2261 if the year is in the range 1000-9999.
2262 The format is `Sun Sep 16 01:03:52 1973'.
2263 However, see also the functions `decode-time' and `format-time-string'
2264 which provide a much more powerful and general facility.
2266 If SPECIFIED-TIME is given, it is a time to format instead of the
2267 current time. The argument should have the form (HIGH LOW . IGNORED).
2268 Thus, you can use times obtained from `current-time' and from
2269 `file-attributes'. SPECIFIED-TIME can also be a single integer number
2270 of seconds since the epoch. The obsolete form (HIGH . LOW) is also
2273 The optional ZONE is omitted or nil for Emacs local time, t for
2274 Universal Time, `wall' for system wall clock time, or a string as in
2275 the TZ environment variable. It can also be a list (as from
2276 `current-time-zone') or an integer (as from `decode-time') applied
2277 without consideration for daylight saving time. */)
2278 (Lisp_Object specified_time
, Lisp_Object zone
)
2280 time_t value
= lisp_seconds_argument (specified_time
);
2281 timezone_t tz
= tzlookup (zone
, false);
2283 /* Convert to a string in ctime format, except without the trailing
2284 newline, and without the 4-digit year limit. Don't use asctime
2285 or ctime, as they might dump core if the year is outside the
2286 range -999 .. 9999. */
2288 struct tm
*tmp
= emacs_localtime_rz (tz
, &value
, &tm
);
2293 static char const wday_name
[][4] =
2294 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
2295 static char const mon_name
[][4] =
2296 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2297 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
2298 printmax_t year_base
= TM_YEAR_BASE
;
2299 char buf
[sizeof "Mon Apr 30 12:49:17 " + INT_STRLEN_BOUND (int) + 1];
2300 int len
= sprintf (buf
, "%s %s%3d %02d:%02d:%02d %"pMd
,
2301 wday_name
[tm
.tm_wday
], mon_name
[tm
.tm_mon
], tm
.tm_mday
,
2302 tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
,
2303 tm
.tm_year
+ year_base
);
2305 return make_unibyte_string (buf
, len
);
2308 /* Yield A - B, measured in seconds.
2309 This function is copied from the GNU C Library. */
2311 tm_diff (struct tm
*a
, struct tm
*b
)
2313 /* Compute intervening leap days correctly even if year is negative.
2314 Take care to avoid int overflow in leap day calculations,
2315 but it's OK to assume that A and B are close to each other. */
2316 int a4
= (a
->tm_year
>> 2) + (TM_YEAR_BASE
>> 2) - ! (a
->tm_year
& 3);
2317 int b4
= (b
->tm_year
>> 2) + (TM_YEAR_BASE
>> 2) - ! (b
->tm_year
& 3);
2318 int a100
= a4
/ 25 - (a4
% 25 < 0);
2319 int b100
= b4
/ 25 - (b4
% 25 < 0);
2320 int a400
= a100
>> 2;
2321 int b400
= b100
>> 2;
2322 int intervening_leap_days
= (a4
- b4
) - (a100
- b100
) + (a400
- b400
);
2323 int years
= a
->tm_year
- b
->tm_year
;
2324 int days
= (365 * years
+ intervening_leap_days
2325 + (a
->tm_yday
- b
->tm_yday
));
2326 return (60 * (60 * (24 * days
+ (a
->tm_hour
- b
->tm_hour
))
2327 + (a
->tm_min
- b
->tm_min
))
2328 + (a
->tm_sec
- b
->tm_sec
));
2331 /* Yield A's UTC offset, or an unspecified value if unknown. */
2333 tm_gmtoff (struct tm
*a
)
2336 return a
->tm_gmtoff
;
2342 DEFUN ("current-time-zone", Fcurrent_time_zone
, Scurrent_time_zone
, 0, 2, 0,
2343 doc
: /* Return the offset and name for the local time zone.
2344 This returns a list of the form (OFFSET NAME).
2345 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
2346 A negative value means west of Greenwich.
2347 NAME is a string giving the name of the time zone.
2348 If SPECIFIED-TIME is given, the time zone offset is determined from it
2349 instead of using the current time. The argument should have the form
2350 \(HIGH LOW . IGNORED). Thus, you can use times obtained from
2351 `current-time' and from `file-attributes'. SPECIFIED-TIME can also be
2352 a single integer number of seconds since the epoch. The obsolete form
2353 (HIGH . LOW) is also still accepted.
2355 The optional ZONE is omitted or nil for Emacs local time, t for
2356 Universal Time, `wall' for system wall clock time, or a string as in
2357 the TZ environment variable. It can also be a list (as from
2358 `current-time-zone') or an integer (as from `decode-time') applied
2359 without consideration for daylight saving time.
2361 Some operating systems cannot provide all this information to Emacs;
2362 in this case, `current-time-zone' returns a list containing nil for
2363 the data it can't find. */)
2364 (Lisp_Object specified_time
, Lisp_Object zone
)
2366 struct timespec value
;
2367 struct tm local_tm
, gmt_tm
;
2368 Lisp_Object zone_offset
, zone_name
;
2371 value
= make_timespec (lisp_seconds_argument (specified_time
), 0);
2372 zone_name
= format_time_string ("%Z", sizeof "%Z" - 1, value
,
2375 /* gmtime_r expects a pointer to time_t, but tv_sec of struct
2376 timespec on some systems (MinGW) is a 64-bit field. */
2377 time_t tsec
= value
.tv_sec
;
2378 if (HAVE_TM_GMTOFF
|| gmtime_r (&tsec
, &gmt_tm
))
2380 long int offset
= (HAVE_TM_GMTOFF
2381 ? tm_gmtoff (&local_tm
)
2382 : tm_diff (&local_tm
, &gmt_tm
));
2383 zone_offset
= make_number (offset
);
2384 if (SCHARS (zone_name
) == 0)
2386 /* No local time zone name is available; use numeric zone instead. */
2387 long int hour
= offset
/ 3600;
2388 int min_sec
= offset
% 3600;
2389 int amin_sec
= min_sec
< 0 ? - min_sec
: min_sec
;
2390 int min
= amin_sec
/ 60;
2391 int sec
= amin_sec
% 60;
2392 int min_prec
= min_sec
? 2 : 0;
2393 int sec_prec
= sec
? 2 : 0;
2394 char buf
[sizeof "+0000" + INT_STRLEN_BOUND (long int)];
2395 zone_name
= make_formatted_string (buf
, "%c%.2ld%.*d%.*d",
2396 (offset
< 0 ? '-' : '+'),
2397 hour
, min_prec
, min
, sec_prec
, sec
);
2401 return list2 (zone_offset
, zone_name
);
2404 DEFUN ("set-time-zone-rule", Fset_time_zone_rule
, Sset_time_zone_rule
, 1, 1, 0,
2405 doc
: /* Set the Emacs local time zone using TZ, a string specifying a time zone rule.
2406 If TZ is nil or `wall', use system wall clock time; this differs from
2407 the usual Emacs convention where nil means current local time. If TZ
2408 is t, use Universal Time. If TZ is a list (as from
2409 `current-time-zone') or an integer (as from `decode-time'), use the
2410 specified time zone without consideration for daylight saving time.
2412 Instead of calling this function, you typically want something else.
2413 To temporarily use a different time zone rule for just one invocation
2414 of `decode-time', `encode-time', or `format-time-string', pass the
2415 function a ZONE argument. To change local time consistently
2416 throughout Emacs, call (setenv "TZ" TZ): this changes both the
2417 environment of the Emacs process and the variable
2418 `process-environment', whereas `set-time-zone-rule' affects only the
2422 tzlookup (NILP (tz
) ? Qwall
: tz
, true);
2426 /* A buffer holding a string of the form "TZ=value", intended
2427 to be part of the environment. If TZ is supposed to be unset,
2428 the buffer string is "tZ=". */
2429 static char *tzvalbuf
;
2431 /* Get the local time zone rule. */
2433 emacs_getenv_TZ (void)
2435 return tzvalbuf
[0] == 'T' ? tzvalbuf
+ tzeqlen
: 0;
2438 /* Set the local time zone rule to TZSTRING, which can be null to
2439 denote wall clock time. Do not record the setting in LOCAL_TZ.
2441 This function is not thread-safe, in theory because putenv is not,
2442 but mostly because of the static storage it updates. Other threads
2443 that invoke localtime etc. may be adversely affected while this
2444 function is executing. */
2447 emacs_setenv_TZ (const char *tzstring
)
2449 static ptrdiff_t tzvalbufsize
;
2450 ptrdiff_t tzstringlen
= tzstring
? strlen (tzstring
) : 0;
2451 char *tzval
= tzvalbuf
;
2452 bool new_tzvalbuf
= tzvalbufsize
<= tzeqlen
+ tzstringlen
;
2456 /* Do not attempt to free the old tzvalbuf, since another thread
2457 may be using it. In practice, the first allocation is large
2458 enough and memory does not leak. */
2459 tzval
= xpalloc (NULL
, &tzvalbufsize
,
2460 tzeqlen
+ tzstringlen
- tzvalbufsize
+ 1, -1, 1);
2468 /* Modify TZVAL in place. Although this is dicey in a
2469 multithreaded environment, we know of no portable alternative.
2470 Calling putenv or setenv could crash some other thread. */
2472 strcpy (tzval
+ tzeqlen
, tzstring
);
2476 /* Turn 'TZ=whatever' into an empty environment variable 'tZ='.
2477 Although this is also dicey, calling unsetenv here can crash Emacs.
2485 /* Modifying *TZVAL merely requires calling tzset (which is the
2486 caller's responsibility). However, modifying TZVAL requires
2487 calling putenv; although this is not thread-safe, in practice this
2488 runs only on startup when there is only one thread. */
2489 bool need_putenv
= new_tzvalbuf
;
2491 /* MS-Windows 'putenv' copies the argument string into a block it
2492 allocates, so modifying *TZVAL will not change the environment.
2493 However, the other threads run by Emacs on MS-Windows never call
2494 'xputenv' or 'putenv' or 'unsetenv', so the original cause for the
2495 dicey in-place modification technique doesn't exist there in the
2497 bool need_putenv
= true;
2505 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2506 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2507 type of object is Lisp_String). INHERIT is passed to
2508 INSERT_FROM_STRING_FUNC as the last argument. */
2511 general_insert_function (void (*insert_func
)
2512 (const char *, ptrdiff_t),
2513 void (*insert_from_string_func
)
2514 (Lisp_Object
, ptrdiff_t, ptrdiff_t,
2515 ptrdiff_t, ptrdiff_t, bool),
2516 bool inherit
, ptrdiff_t nargs
, Lisp_Object
*args
)
2521 for (argnum
= 0; argnum
< nargs
; argnum
++)
2524 if (CHARACTERP (val
))
2526 int c
= XFASTINT (val
);
2527 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2530 if (!NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2531 len
= CHAR_STRING (c
, str
);
2534 str
[0] = CHAR_TO_BYTE8 (c
);
2537 (*insert_func
) ((char *) str
, len
);
2539 else if (STRINGP (val
))
2541 (*insert_from_string_func
) (val
, 0, 0,
2547 wrong_type_argument (Qchar_or_string_p
, val
);
2552 insert1 (Lisp_Object arg
)
2558 DEFUN ("insert", Finsert
, Sinsert
, 0, MANY
, 0,
2559 doc
: /* Insert the arguments, either strings or characters, at point.
2560 Point and after-insertion markers move forward to end up
2561 after the inserted text.
2562 Any other markers at the point of insertion remain before the text.
2564 If the current buffer is multibyte, unibyte strings are converted
2565 to multibyte for insertion (see `string-make-multibyte').
2566 If the current buffer is unibyte, multibyte strings are converted
2567 to unibyte for insertion (see `string-make-unibyte').
2569 When operating on binary data, it may be necessary to preserve the
2570 original bytes of a unibyte string when inserting it into a multibyte
2571 buffer; to accomplish this, apply `string-as-multibyte' to the string
2572 and insert the result.
2574 usage: (insert &rest ARGS) */)
2575 (ptrdiff_t nargs
, Lisp_Object
*args
)
2577 general_insert_function (insert
, insert_from_string
, 0, nargs
, args
);
2581 DEFUN ("insert-and-inherit", Finsert_and_inherit
, Sinsert_and_inherit
,
2583 doc
: /* Insert the arguments at point, inheriting properties from adjoining text.
2584 Point and after-insertion markers move forward to end up
2585 after the inserted text.
2586 Any other markers at the point of insertion remain before the text.
2588 If the current buffer is multibyte, unibyte strings are converted
2589 to multibyte for insertion (see `unibyte-char-to-multibyte').
2590 If the current buffer is unibyte, multibyte strings are converted
2591 to unibyte for insertion.
2593 usage: (insert-and-inherit &rest ARGS) */)
2594 (ptrdiff_t nargs
, Lisp_Object
*args
)
2596 general_insert_function (insert_and_inherit
, insert_from_string
, 1,
2601 DEFUN ("insert-before-markers", Finsert_before_markers
, Sinsert_before_markers
, 0, MANY
, 0,
2602 doc
: /* Insert strings or characters at point, relocating markers after the text.
2603 Point and markers move forward to end up after the inserted text.
2605 If the current buffer is multibyte, unibyte strings are converted
2606 to multibyte for insertion (see `unibyte-char-to-multibyte').
2607 If the current buffer is unibyte, multibyte strings are converted
2608 to unibyte for insertion.
2610 If an overlay begins at the insertion point, the inserted text falls
2611 outside the overlay; if a nonempty overlay ends at the insertion
2612 point, the inserted text falls inside that overlay.
2614 usage: (insert-before-markers &rest ARGS) */)
2615 (ptrdiff_t nargs
, Lisp_Object
*args
)
2617 general_insert_function (insert_before_markers
,
2618 insert_from_string_before_markers
, 0,
2623 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers
,
2624 Sinsert_and_inherit_before_markers
, 0, MANY
, 0,
2625 doc
: /* Insert text at point, relocating markers and inheriting properties.
2626 Point and markers move forward to end up after the inserted text.
2628 If the current buffer is multibyte, unibyte strings are converted
2629 to multibyte for insertion (see `unibyte-char-to-multibyte').
2630 If the current buffer is unibyte, multibyte strings are converted
2631 to unibyte for insertion.
2633 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2634 (ptrdiff_t nargs
, Lisp_Object
*args
)
2636 general_insert_function (insert_before_markers_and_inherit
,
2637 insert_from_string_before_markers
, 1,
2642 DEFUN ("insert-char", Finsert_char
, Sinsert_char
, 1, 3,
2643 "(list (read-char-by-name \"Insert character (Unicode name or hex): \")\
2644 (prefix-numeric-value current-prefix-arg)\
2646 doc
: /* Insert COUNT copies of CHARACTER.
2647 Interactively, prompt for CHARACTER. You can specify CHARACTER in one
2650 - As its Unicode character name, e.g. \"LATIN SMALL LETTER A\".
2651 Completion is available; if you type a substring of the name
2652 preceded by an asterisk `*', Emacs shows all names which include
2653 that substring, not necessarily at the beginning of the name.
2655 - As a hexadecimal code point, e.g. 263A. Note that code points in
2656 Emacs are equivalent to Unicode up to 10FFFF (which is the limit of
2657 the Unicode code space).
2659 - As a code point with a radix specified with #, e.g. #o21430
2660 (octal), #x2318 (hex), or #10r8984 (decimal).
2662 If called interactively, COUNT is given by the prefix argument. If
2663 omitted or nil, it defaults to 1.
2665 Inserting the character(s) relocates point and before-insertion
2666 markers in the same ways as the function `insert'.
2668 The optional third argument INHERIT, if non-nil, says to inherit text
2669 properties from adjoining text, if those properties are sticky. If
2670 called interactively, INHERIT is t. */)
2671 (Lisp_Object character
, Lisp_Object count
, Lisp_Object inherit
)
2674 register ptrdiff_t n
;
2676 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
2679 CHECK_CHARACTER (character
);
2681 XSETFASTINT (count
, 1);
2682 CHECK_NUMBER (count
);
2683 c
= XFASTINT (character
);
2685 if (!NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2686 len
= CHAR_STRING (c
, str
);
2688 str
[0] = c
, len
= 1;
2689 if (XINT (count
) <= 0)
2691 if (BUF_BYTES_MAX
/ len
< XINT (count
))
2693 n
= XINT (count
) * len
;
2694 stringlen
= min (n
, sizeof string
- sizeof string
% len
);
2695 for (i
= 0; i
< stringlen
; i
++)
2696 string
[i
] = str
[i
% len
];
2697 while (n
> stringlen
)
2700 if (!NILP (inherit
))
2701 insert_and_inherit (string
, stringlen
);
2703 insert (string
, stringlen
);
2706 if (!NILP (inherit
))
2707 insert_and_inherit (string
, n
);
2713 DEFUN ("insert-byte", Finsert_byte
, Sinsert_byte
, 2, 3, 0,
2714 doc
: /* Insert COUNT (second arg) copies of BYTE (first arg).
2715 Both arguments are required.
2716 BYTE is a number of the range 0..255.
2718 If BYTE is 128..255 and the current buffer is multibyte, the
2719 corresponding eight-bit character is inserted.
2721 Point, and before-insertion markers, are relocated as in the function `insert'.
2722 The optional third arg INHERIT, if non-nil, says to inherit text properties
2723 from adjoining text, if those properties are sticky. */)
2724 (Lisp_Object byte
, Lisp_Object count
, Lisp_Object inherit
)
2726 CHECK_NUMBER (byte
);
2727 if (XINT (byte
) < 0 || XINT (byte
) > 255)
2728 args_out_of_range_3 (byte
, make_number (0), make_number (255));
2729 if (XINT (byte
) >= 128
2730 && ! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2731 XSETFASTINT (byte
, BYTE8_TO_CHAR (XINT (byte
)));
2732 return Finsert_char (byte
, count
, inherit
);
2736 /* Making strings from buffer contents. */
2738 /* Return a Lisp_String containing the text of the current buffer from
2739 START to END. If text properties are in use and the current buffer
2740 has properties in the range specified, the resulting string will also
2741 have them, if PROPS is true.
2743 We don't want to use plain old make_string here, because it calls
2744 make_uninit_string, which can cause the buffer arena to be
2745 compacted. make_string has no way of knowing that the data has
2746 been moved, and thus copies the wrong data into the string. This
2747 doesn't effect most of the other users of make_string, so it should
2748 be left as is. But we should use this function when conjuring
2749 buffer substrings. */
2752 make_buffer_string (ptrdiff_t start
, ptrdiff_t end
, bool props
)
2754 ptrdiff_t start_byte
= CHAR_TO_BYTE (start
);
2755 ptrdiff_t end_byte
= CHAR_TO_BYTE (end
);
2757 return make_buffer_string_both (start
, start_byte
, end
, end_byte
, props
);
2760 /* Return a Lisp_String containing the text of the current buffer from
2761 START / START_BYTE to END / END_BYTE.
2763 If text properties are in use and the current buffer
2764 has properties in the range specified, the resulting string will also
2765 have them, if PROPS is true.
2767 We don't want to use plain old make_string here, because it calls
2768 make_uninit_string, which can cause the buffer arena to be
2769 compacted. make_string has no way of knowing that the data has
2770 been moved, and thus copies the wrong data into the string. This
2771 doesn't effect most of the other users of make_string, so it should
2772 be left as is. But we should use this function when conjuring
2773 buffer substrings. */
2776 make_buffer_string_both (ptrdiff_t start
, ptrdiff_t start_byte
,
2777 ptrdiff_t end
, ptrdiff_t end_byte
, bool props
)
2779 Lisp_Object result
, tem
, tem1
;
2780 ptrdiff_t beg0
, end0
, beg1
, end1
, size
;
2782 if (start_byte
< GPT_BYTE
&& GPT_BYTE
< end_byte
)
2784 /* Two regions, before and after the gap. */
2787 beg1
= GPT_BYTE
+ GAP_SIZE
- BEG_BYTE
;
2788 end1
= end_byte
+ GAP_SIZE
- BEG_BYTE
;
2792 /* The only region. */
2799 if (! NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
2800 result
= make_uninit_multibyte_string (end
- start
, end_byte
- start_byte
);
2802 result
= make_uninit_string (end
- start
);
2805 memcpy (SDATA (result
), BYTE_POS_ADDR (beg0
), size
);
2807 memcpy (SDATA (result
) + size
, BEG_ADDR
+ beg1
, end1
- beg1
);
2809 /* If desired, update and copy the text properties. */
2812 update_buffer_properties (start
, end
);
2814 tem
= Fnext_property_change (make_number (start
), Qnil
, make_number (end
));
2815 tem1
= Ftext_properties_at (make_number (start
), Qnil
);
2817 if (XINT (tem
) != end
|| !NILP (tem1
))
2818 copy_intervals_to_string (result
, current_buffer
, start
,
2825 /* Call Vbuffer_access_fontify_functions for the range START ... END
2826 in the current buffer, if necessary. */
2829 update_buffer_properties (ptrdiff_t start
, ptrdiff_t end
)
2831 /* If this buffer has some access functions,
2832 call them, specifying the range of the buffer being accessed. */
2833 if (!NILP (Vbuffer_access_fontify_functions
))
2835 /* But don't call them if we can tell that the work
2836 has already been done. */
2837 if (!NILP (Vbuffer_access_fontified_property
))
2840 = Ftext_property_any (make_number (start
), make_number (end
),
2841 Vbuffer_access_fontified_property
,
2847 CALLN (Frun_hook_with_args
, Qbuffer_access_fontify_functions
,
2848 make_number (start
), make_number (end
));
2852 DEFUN ("buffer-substring", Fbuffer_substring
, Sbuffer_substring
, 2, 2, 0,
2853 doc
: /* Return the contents of part of the current buffer as a string.
2854 The two arguments START and END are character positions;
2855 they can be in either order.
2856 The string returned is multibyte if the buffer is multibyte.
2858 This function copies the text properties of that part of the buffer
2859 into the result string; if you don't want the text properties,
2860 use `buffer-substring-no-properties' instead. */)
2861 (Lisp_Object start
, Lisp_Object end
)
2863 register ptrdiff_t b
, e
;
2865 validate_region (&start
, &end
);
2869 return make_buffer_string (b
, e
, 1);
2872 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties
,
2873 Sbuffer_substring_no_properties
, 2, 2, 0,
2874 doc
: /* Return the characters of part of the buffer, without the text properties.
2875 The two arguments START and END are character positions;
2876 they can be in either order. */)
2877 (Lisp_Object start
, Lisp_Object end
)
2879 register ptrdiff_t b
, e
;
2881 validate_region (&start
, &end
);
2885 return make_buffer_string (b
, e
, 0);
2888 DEFUN ("buffer-string", Fbuffer_string
, Sbuffer_string
, 0, 0, 0,
2889 doc
: /* Return the contents of the current buffer as a string.
2890 If narrowing is in effect, this function returns only the visible part
2894 return make_buffer_string_both (BEGV
, BEGV_BYTE
, ZV
, ZV_BYTE
, 1);
2897 DEFUN ("insert-buffer-substring", Finsert_buffer_substring
, Sinsert_buffer_substring
,
2899 doc
: /* Insert before point a substring of the contents of BUFFER.
2900 BUFFER may be a buffer or a buffer name.
2901 Arguments START and END are character positions specifying the substring.
2902 They default to the values of (point-min) and (point-max) in BUFFER.
2904 Point and before-insertion markers move forward to end up after the
2906 Any other markers at the point of insertion remain before the text.
2908 If the current buffer is multibyte and BUFFER is unibyte, or vice
2909 versa, strings are converted from unibyte to multibyte or vice versa
2910 using `string-make-multibyte' or `string-make-unibyte', which see. */)
2911 (Lisp_Object buffer
, Lisp_Object start
, Lisp_Object end
)
2913 register EMACS_INT b
, e
, temp
;
2914 register struct buffer
*bp
, *obuf
;
2917 buf
= Fget_buffer (buffer
);
2921 if (!BUFFER_LIVE_P (bp
))
2922 error ("Selecting deleted buffer");
2928 CHECK_NUMBER_COERCE_MARKER (start
);
2935 CHECK_NUMBER_COERCE_MARKER (end
);
2940 temp
= b
, b
= e
, e
= temp
;
2942 if (!(BUF_BEGV (bp
) <= b
&& e
<= BUF_ZV (bp
)))
2943 args_out_of_range (start
, end
);
2945 obuf
= current_buffer
;
2946 set_buffer_internal_1 (bp
);
2947 update_buffer_properties (b
, e
);
2948 set_buffer_internal_1 (obuf
);
2950 insert_from_buffer (bp
, b
, e
- b
, 0);
2954 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings
, Scompare_buffer_substrings
,
2956 doc
: /* Compare two substrings of two buffers; return result as number.
2957 Return -N if first string is less after N-1 chars, +N if first string is
2958 greater after N-1 chars, or 0 if strings match.
2959 The first substring is in BUFFER1 from START1 to END1 and the second
2960 is in BUFFER2 from START2 to END2.
2961 All arguments may be nil. If BUFFER1 or BUFFER2 is nil, the current
2962 buffer is used. If START1 or START2 is nil, the value of `point-min'
2963 in the respective buffers is used. If END1 or END2 is nil, the value
2964 of `point-max' in the respective buffers is used.
2965 The value of `case-fold-search' in the current buffer
2966 determines whether case is significant or ignored. */)
2967 (Lisp_Object buffer1
, Lisp_Object start1
, Lisp_Object end1
, Lisp_Object buffer2
, Lisp_Object start2
, Lisp_Object end2
)
2969 register EMACS_INT begp1
, endp1
, begp2
, endp2
, temp
;
2970 register struct buffer
*bp1
, *bp2
;
2971 register Lisp_Object trt
2972 = (!NILP (BVAR (current_buffer
, case_fold_search
))
2973 ? BVAR (current_buffer
, case_canon_table
) : Qnil
);
2974 ptrdiff_t chars
= 0;
2975 ptrdiff_t i1
, i2
, i1_byte
, i2_byte
;
2977 /* Find the first buffer and its substring. */
2980 bp1
= current_buffer
;
2984 buf1
= Fget_buffer (buffer1
);
2987 bp1
= XBUFFER (buf1
);
2988 if (!BUFFER_LIVE_P (bp1
))
2989 error ("Selecting deleted buffer");
2993 begp1
= BUF_BEGV (bp1
);
2996 CHECK_NUMBER_COERCE_MARKER (start1
);
2997 begp1
= XINT (start1
);
3000 endp1
= BUF_ZV (bp1
);
3003 CHECK_NUMBER_COERCE_MARKER (end1
);
3004 endp1
= XINT (end1
);
3008 temp
= begp1
, begp1
= endp1
, endp1
= temp
;
3010 if (!(BUF_BEGV (bp1
) <= begp1
3012 && endp1
<= BUF_ZV (bp1
)))
3013 args_out_of_range (start1
, end1
);
3015 /* Likewise for second substring. */
3018 bp2
= current_buffer
;
3022 buf2
= Fget_buffer (buffer2
);
3025 bp2
= XBUFFER (buf2
);
3026 if (!BUFFER_LIVE_P (bp2
))
3027 error ("Selecting deleted buffer");
3031 begp2
= BUF_BEGV (bp2
);
3034 CHECK_NUMBER_COERCE_MARKER (start2
);
3035 begp2
= XINT (start2
);
3038 endp2
= BUF_ZV (bp2
);
3041 CHECK_NUMBER_COERCE_MARKER (end2
);
3042 endp2
= XINT (end2
);
3046 temp
= begp2
, begp2
= endp2
, endp2
= temp
;
3048 if (!(BUF_BEGV (bp2
) <= begp2
3050 && endp2
<= BUF_ZV (bp2
)))
3051 args_out_of_range (start2
, end2
);
3055 i1_byte
= buf_charpos_to_bytepos (bp1
, i1
);
3056 i2_byte
= buf_charpos_to_bytepos (bp2
, i2
);
3058 while (i1
< endp1
&& i2
< endp2
)
3060 /* When we find a mismatch, we must compare the
3061 characters, not just the bytes. */
3064 if (! NILP (BVAR (bp1
, enable_multibyte_characters
)))
3066 c1
= BUF_FETCH_MULTIBYTE_CHAR (bp1
, i1_byte
);
3067 BUF_INC_POS (bp1
, i1_byte
);
3072 c1
= BUF_FETCH_BYTE (bp1
, i1
);
3073 MAKE_CHAR_MULTIBYTE (c1
);
3077 if (! NILP (BVAR (bp2
, enable_multibyte_characters
)))
3079 c2
= BUF_FETCH_MULTIBYTE_CHAR (bp2
, i2_byte
);
3080 BUF_INC_POS (bp2
, i2_byte
);
3085 c2
= BUF_FETCH_BYTE (bp2
, i2
);
3086 MAKE_CHAR_MULTIBYTE (c2
);
3092 c1
= char_table_translate (trt
, c1
);
3093 c2
= char_table_translate (trt
, c2
);
3097 return make_number (c1
< c2
? -1 - chars
: chars
+ 1);
3100 rarely_quit (chars
);
3103 /* The strings match as far as they go.
3104 If one is shorter, that one is less. */
3105 if (chars
< endp1
- begp1
)
3106 return make_number (chars
+ 1);
3107 else if (chars
< endp2
- begp2
)
3108 return make_number (- chars
- 1);
3110 /* Same length too => they are equal. */
3111 return make_number (0);
3115 /* Set up necessary definitions for diffseq.h; see comments in
3116 diffseq.h for explanation. */
3121 #define XVECREF_YVECREF_EQUAL(ctx, xoff, yoff) \
3122 buffer_chars_equal ((ctx), (xoff), (yoff))
3124 #define OFFSET ptrdiff_t
3126 #define EXTRA_CONTEXT_FIELDS \
3127 /* Buffers to compare. */ \
3128 struct buffer *buffer_a; \
3129 struct buffer *buffer_b; \
3130 /* Bit vectors recording for each character whether it was deleted
3132 unsigned char *deletions; \
3133 unsigned char *insertions;
3135 #define NOTE_DELETE(ctx, xoff) set_bit ((ctx)->deletions, (xoff))
3136 #define NOTE_INSERT(ctx, yoff) set_bit ((ctx)->insertions, (yoff))
3139 static void set_bit (unsigned char *, OFFSET
);
3140 static bool bit_is_set (const unsigned char *, OFFSET
);
3141 static bool buffer_chars_equal (struct context
*, OFFSET
, OFFSET
);
3144 #include "diffseq.h"
3146 DEFUN ("replace-buffer-contents", Freplace_buffer_contents
,
3147 Sreplace_buffer_contents
, 1, 1, "bSource buffer: ",
3148 doc
: /* Replace accessible portion of current buffer with that of SOURCE.
3149 SOURCE can be a buffer or a string that names a buffer.
3150 Interactively, prompt for SOURCE.
3151 As far as possible the replacement is non-destructive, i.e. existing
3152 buffer contents, markers, properties, and overlays in the current
3153 buffer stay intact. */)
3154 (Lisp_Object source
)
3156 struct buffer
*a
= current_buffer
;
3157 Lisp_Object source_buffer
= Fget_buffer (source
);
3158 if (NILP (source_buffer
))
3160 struct buffer
*b
= XBUFFER (source_buffer
);
3161 if (! BUFFER_LIVE_P (b
))
3162 error ("Selecting deleted buffer");
3164 error ("Cannot replace a buffer with itself");
3166 ptrdiff_t min_a
= BEGV
;
3167 ptrdiff_t min_b
= BUF_BEGV (b
);
3168 ptrdiff_t size_a
= ZV
- min_a
;
3169 ptrdiff_t size_b
= BUF_ZV (b
) - min_b
;
3170 eassume (size_a
>= 0);
3171 eassume (size_b
>= 0);
3172 bool a_empty
= size_a
== 0;
3173 bool b_empty
= size_b
== 0;
3175 /* Handle trivial cases where at least one accessible portion is
3178 if (a_empty
&& b_empty
)
3182 return Finsert_buffer_substring (source
, Qnil
, Qnil
);
3186 del_range_both (BEGV
, BEGV_BYTE
, ZV
, ZV_BYTE
, true);
3190 /* FIXME: It is not documented how to initialize the contents of the
3191 context structure. This code cargo-cults from the existing
3192 caller in src/analyze.c of GNU Diffutils, which appears to
3195 ptrdiff_t diags
= size_a
+ size_b
+ 3;
3198 SAFE_NALLOCA (buffer
, 2, diags
);
3199 /* Micro-optimization: Casting to size_t generates much better
3201 ptrdiff_t del_bytes
= (size_t) size_a
/ CHAR_BIT
+ 1;
3202 ptrdiff_t ins_bytes
= (size_t) size_b
/ CHAR_BIT
+ 1;
3203 struct context ctx
= {
3206 .deletions
= SAFE_ALLOCA (del_bytes
),
3207 .insertions
= SAFE_ALLOCA (ins_bytes
),
3208 .fdiag
= buffer
+ size_b
+ 1,
3209 .bdiag
= buffer
+ diags
+ size_b
+ 1,
3210 /* FIXME: Find a good number for .too_expensive. */
3211 .too_expensive
= 1000000,
3213 memclear (ctx
.deletions
, del_bytes
);
3214 memclear (ctx
.insertions
, ins_bytes
);
3215 /* compareseq requires indices to be zero-based. We add BEGV back
3217 bool early_abort
= compareseq (0, size_a
, 0, size_b
, false, &ctx
);
3218 /* Since we didn’t define EARLY_ABORT, we should never abort
3220 eassert (! early_abort
);
3224 ptrdiff_t count
= SPECPDL_INDEX ();
3225 record_unwind_protect (save_excursion_restore
, save_excursion_save ());
3227 ptrdiff_t i
= size_a
;
3228 ptrdiff_t j
= size_b
;
3229 /* Walk backwards through the lists of changes. This was also
3230 cargo-culted from src/analyze.c in GNU Diffutils. Because we
3231 walk backwards, we don’t have to keep the positions in sync. */
3232 while (i
>= 0 || j
>= 0)
3234 /* Check whether there is a change (insertion or deletion)
3235 before the current position. */
3236 if ((i
> 0 && bit_is_set (ctx
.deletions
, i
- 1)) ||
3237 (j
> 0 && bit_is_set (ctx
.insertions
, j
- 1)))
3239 ptrdiff_t end_a
= min_a
+ i
;
3240 ptrdiff_t end_b
= min_b
+ j
;
3241 /* Find the beginning of the current change run. */
3242 while (i
> 0 && bit_is_set (ctx
.deletions
, i
- 1))
3244 while (j
> 0 && bit_is_set (ctx
.insertions
, j
- 1))
3246 ptrdiff_t beg_a
= min_a
+ i
;
3247 ptrdiff_t beg_b
= min_b
+ j
;
3248 eassert (beg_a
>= BEGV
);
3249 eassert (beg_b
>= BUF_BEGV (b
));
3250 eassert (beg_a
<= end_a
);
3251 eassert (beg_b
<= end_b
);
3252 eassert (end_a
<= ZV
);
3253 eassert (end_b
<= BUF_ZV (b
));
3254 eassert (beg_a
< end_a
|| beg_b
< end_b
);
3256 del_range (beg_a
, end_a
);
3260 Finsert_buffer_substring (source
, make_natnum (beg_b
),
3261 make_natnum (end_b
));
3268 return unbind_to (count
, Qnil
);
3272 set_bit (unsigned char *a
, ptrdiff_t i
)
3275 /* Micro-optimization: Casting to size_t generates much better
3278 a
[j
/ CHAR_BIT
] |= (1 << (j
% CHAR_BIT
));
3282 bit_is_set (const unsigned char *a
, ptrdiff_t i
)
3285 /* Micro-optimization: Casting to size_t generates much better
3288 return a
[j
/ CHAR_BIT
] & (1 << (j
% CHAR_BIT
));
3291 /* Return true if the characters at position POS_A of buffer
3292 CTX->buffer_a and at position POS_B of buffer CTX->buffer_b are
3293 equal. POS_A and POS_B are zero-based. Text properties are
3297 buffer_chars_equal (struct context
*ctx
,
3298 ptrdiff_t pos_a
, ptrdiff_t pos_b
)
3300 eassert (pos_a
>= 0);
3301 pos_a
+= BUF_BEGV (ctx
->buffer_a
);
3302 eassert (pos_a
>= BUF_BEGV (ctx
->buffer_a
));
3303 eassert (pos_a
< BUF_ZV (ctx
->buffer_a
));
3305 eassert (pos_b
>= 0);
3306 pos_b
+= BUF_BEGV (ctx
->buffer_b
);
3307 eassert (pos_b
>= BUF_BEGV (ctx
->buffer_b
));
3308 eassert (pos_b
< BUF_ZV (ctx
->buffer_b
));
3310 return BUF_FETCH_CHAR_AS_MULTIBYTE (ctx
->buffer_a
, pos_a
)
3311 == BUF_FETCH_CHAR_AS_MULTIBYTE (ctx
->buffer_b
, pos_b
);
3316 subst_char_in_region_unwind (Lisp_Object arg
)
3318 bset_undo_list (current_buffer
, arg
);
3322 subst_char_in_region_unwind_1 (Lisp_Object arg
)
3324 bset_filename (current_buffer
, arg
);
3327 DEFUN ("subst-char-in-region", Fsubst_char_in_region
,
3328 Ssubst_char_in_region
, 4, 5, 0,
3329 doc
: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
3330 If optional arg NOUNDO is non-nil, don't record this change for undo
3331 and don't mark the buffer as really changed.
3332 Both characters must have the same length of multi-byte form. */)
3333 (Lisp_Object start
, Lisp_Object end
, Lisp_Object fromchar
, Lisp_Object tochar
, Lisp_Object noundo
)
3335 register ptrdiff_t pos
, pos_byte
, stop
, i
, len
, end_byte
;
3336 /* Keep track of the first change in the buffer:
3337 if 0 we haven't found it yet.
3338 if < 0 we've found it and we've run the before-change-function.
3339 if > 0 we've actually performed it and the value is its position. */
3340 ptrdiff_t changed
= 0;
3341 unsigned char fromstr
[MAX_MULTIBYTE_LENGTH
], tostr
[MAX_MULTIBYTE_LENGTH
];
3343 ptrdiff_t count
= SPECPDL_INDEX ();
3344 #define COMBINING_NO 0
3345 #define COMBINING_BEFORE 1
3346 #define COMBINING_AFTER 2
3347 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
3348 int maybe_byte_combining
= COMBINING_NO
;
3349 ptrdiff_t last_changed
= 0;
3351 = !NILP (BVAR (current_buffer
, enable_multibyte_characters
));
3356 validate_region (&start
, &end
);
3357 CHECK_CHARACTER (fromchar
);
3358 CHECK_CHARACTER (tochar
);
3359 fromc
= XFASTINT (fromchar
);
3360 toc
= XFASTINT (tochar
);
3364 len
= CHAR_STRING (fromc
, fromstr
);
3365 if (CHAR_STRING (toc
, tostr
) != len
)
3366 error ("Characters in `subst-char-in-region' have different byte-lengths");
3367 if (!ASCII_CHAR_P (*tostr
))
3369 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
3370 complete multibyte character, it may be combined with the
3371 after bytes. If it is in the range 0xA0..0xFF, it may be
3372 combined with the before and after bytes. */
3373 if (!CHAR_HEAD_P (*tostr
))
3374 maybe_byte_combining
= COMBINING_BOTH
;
3375 else if (BYTES_BY_CHAR_HEAD (*tostr
) > len
)
3376 maybe_byte_combining
= COMBINING_AFTER
;
3387 pos_byte
= CHAR_TO_BYTE (pos
);
3388 stop
= CHAR_TO_BYTE (XINT (end
));
3391 /* If we don't want undo, turn off putting stuff on the list.
3392 That's faster than getting rid of things,
3393 and it prevents even the entry for a first change.
3394 Also inhibit locking the file. */
3395 if (!changed
&& !NILP (noundo
))
3397 record_unwind_protect (subst_char_in_region_unwind
,
3398 BVAR (current_buffer
, undo_list
));
3399 bset_undo_list (current_buffer
, Qt
);
3400 /* Don't do file-locking. */
3401 record_unwind_protect (subst_char_in_region_unwind_1
,
3402 BVAR (current_buffer
, filename
));
3403 bset_filename (current_buffer
, Qnil
);
3406 if (pos_byte
< GPT_BYTE
)
3407 stop
= min (stop
, GPT_BYTE
);
3410 ptrdiff_t pos_byte_next
= pos_byte
;
3412 if (pos_byte
>= stop
)
3414 if (pos_byte
>= end_byte
) break;
3417 p
= BYTE_POS_ADDR (pos_byte
);
3419 INC_POS (pos_byte_next
);
3422 if (pos_byte_next
- pos_byte
== len
3423 && p
[0] == fromstr
[0]
3425 || (p
[1] == fromstr
[1]
3426 && (len
== 2 || (p
[2] == fromstr
[2]
3427 && (len
== 3 || p
[3] == fromstr
[3]))))))
3430 /* We've already seen this and run the before-change-function;
3431 this time we only need to record the actual position. */
3436 modify_text (pos
, XINT (end
));
3438 if (! NILP (noundo
))
3440 if (MODIFF
- 1 == SAVE_MODIFF
)
3442 if (MODIFF
- 1 == BUF_AUTOSAVE_MODIFF (current_buffer
))
3443 BUF_AUTOSAVE_MODIFF (current_buffer
)++;
3446 /* The before-change-function may have moved the gap
3447 or even modified the buffer so we should start over. */
3451 /* Take care of the case where the new character
3452 combines with neighboring bytes. */
3453 if (maybe_byte_combining
3454 && (maybe_byte_combining
== COMBINING_AFTER
3455 ? (pos_byte_next
< Z_BYTE
3456 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next
)))
3457 : ((pos_byte_next
< Z_BYTE
3458 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next
)))
3459 || (pos_byte
> BEG_BYTE
3460 && ! ASCII_CHAR_P (FETCH_BYTE (pos_byte
- 1))))))
3462 Lisp_Object tem
, string
;
3464 tem
= BVAR (current_buffer
, undo_list
);
3466 /* Make a multibyte string containing this single character. */
3467 string
= make_multibyte_string ((char *) tostr
, 1, len
);
3468 /* replace_range is less efficient, because it moves the gap,
3469 but it handles combining correctly. */
3470 replace_range (pos
, pos
+ 1, string
,
3472 pos_byte_next
= CHAR_TO_BYTE (pos
);
3473 if (pos_byte_next
> pos_byte
)
3474 /* Before combining happened. We should not increment
3475 POS. So, to cancel the later increment of POS,
3479 INC_POS (pos_byte_next
);
3481 if (! NILP (noundo
))
3482 bset_undo_list (current_buffer
, tem
);
3487 record_change (pos
, 1);
3488 for (i
= 0; i
< len
; i
++) *p
++ = tostr
[i
];
3490 last_changed
= pos
+ 1;
3492 pos_byte
= pos_byte_next
;
3498 signal_after_change (changed
,
3499 last_changed
- changed
, last_changed
- changed
);
3500 update_compositions (changed
, last_changed
, CHECK_ALL
);
3503 unbind_to (count
, Qnil
);
3508 static Lisp_Object
check_translation (ptrdiff_t, ptrdiff_t, ptrdiff_t,
3511 /* Helper function for Ftranslate_region_internal.
3513 Check if a character sequence at POS (POS_BYTE) matches an element
3514 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
3515 element is found, return it. Otherwise return Qnil. */
3518 check_translation (ptrdiff_t pos
, ptrdiff_t pos_byte
, ptrdiff_t end
,
3521 int initial_buf
[16];
3522 int *buf
= initial_buf
;
3523 ptrdiff_t buf_size
= ARRAYELTS (initial_buf
);
3525 ptrdiff_t buf_used
= 0;
3526 Lisp_Object result
= Qnil
;
3528 for (; CONSP (val
); val
= XCDR (val
))
3537 if (! VECTORP (elt
))
3540 if (len
<= end
- pos
)
3542 for (i
= 0; i
< len
; i
++)
3546 unsigned char *p
= BYTE_POS_ADDR (pos_byte
);
3549 if (buf_used
== buf_size
)
3551 bufalloc
= xpalloc (bufalloc
, &buf_size
, 1, -1,
3553 if (buf
== initial_buf
)
3554 memcpy (bufalloc
, buf
, sizeof initial_buf
);
3557 buf
[buf_used
++] = STRING_CHAR_AND_LENGTH (p
, len1
);
3560 if (XINT (AREF (elt
, i
)) != buf
[i
])
3565 result
= XCAR (val
);
3576 DEFUN ("translate-region-internal", Ftranslate_region_internal
,
3577 Stranslate_region_internal
, 3, 3, 0,
3578 doc
: /* Internal use only.
3579 From START to END, translate characters according to TABLE.
3580 TABLE is a string or a char-table; the Nth character in it is the
3581 mapping for the character with code N.
3582 It returns the number of characters changed. */)
3583 (Lisp_Object start
, Lisp_Object end
, register Lisp_Object table
)
3585 register unsigned char *tt
; /* Trans table. */
3586 register int nc
; /* New character. */
3587 int cnt
; /* Number of changes made. */
3588 ptrdiff_t size
; /* Size of translate table. */
3589 ptrdiff_t pos
, pos_byte
, end_pos
;
3590 bool multibyte
= !NILP (BVAR (current_buffer
, enable_multibyte_characters
));
3591 bool string_multibyte UNINIT
;
3593 validate_region (&start
, &end
);
3594 if (CHAR_TABLE_P (table
))
3596 if (! EQ (XCHAR_TABLE (table
)->purpose
, Qtranslation_table
))
3597 error ("Not a translation table");
3603 CHECK_STRING (table
);
3605 if (! multibyte
&& (SCHARS (table
) < SBYTES (table
)))
3606 table
= string_make_unibyte (table
);
3607 string_multibyte
= SCHARS (table
) < SBYTES (table
);
3608 size
= SBYTES (table
);
3613 pos_byte
= CHAR_TO_BYTE (pos
);
3614 end_pos
= XINT (end
);
3615 modify_text (pos
, end_pos
);
3618 for (; pos
< end_pos
; )
3620 unsigned char *p
= BYTE_POS_ADDR (pos_byte
);
3621 unsigned char *str UNINIT
;
3622 unsigned char buf
[MAX_MULTIBYTE_LENGTH
];
3628 oc
= STRING_CHAR_AND_LENGTH (p
, len
);
3635 /* Reload as signal_after_change in last iteration may GC. */
3637 if (string_multibyte
)
3639 str
= tt
+ string_char_to_byte (table
, oc
);
3640 nc
= STRING_CHAR_AND_LENGTH (str
, str_len
);
3645 if (! ASCII_CHAR_P (nc
) && multibyte
)
3647 str_len
= BYTE8_STRING (nc
, buf
);
3660 val
= CHAR_TABLE_REF (table
, oc
);
3661 if (CHARACTERP (val
))
3663 nc
= XFASTINT (val
);
3664 str_len
= CHAR_STRING (nc
, buf
);
3667 else if (VECTORP (val
) || (CONSP (val
)))
3669 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3670 where TO is TO-CHAR or [TO-CHAR ...]. */
3675 if (nc
!= oc
&& nc
>= 0)
3677 /* Simple one char to one char translation. */
3682 /* This is less efficient, because it moves the gap,
3683 but it should handle multibyte characters correctly. */
3684 string
= make_multibyte_string ((char *) str
, 1, str_len
);
3685 replace_range (pos
, pos
+ 1, string
, 1, 0, 1, 0);
3690 record_change (pos
, 1);
3691 while (str_len
-- > 0)
3693 signal_after_change (pos
, 1, 1);
3694 update_compositions (pos
, pos
+ 1, CHECK_BORDER
);
3704 val
= check_translation (pos
, pos_byte
, end_pos
, val
);
3711 /* VAL is ([FROM-CHAR ...] . TO). */
3712 len
= ASIZE (XCAR (val
));
3720 string
= Fconcat (1, &val
);
3724 string
= Fmake_string (make_number (1), val
, Qnil
);
3726 replace_range (pos
, pos
+ len
, string
, 1, 0, 1, 0);
3727 pos_byte
+= SBYTES (string
);
3728 pos
+= SCHARS (string
);
3729 cnt
+= SCHARS (string
);
3730 end_pos
+= SCHARS (string
) - len
;
3738 return make_number (cnt
);
3741 DEFUN ("delete-region", Fdelete_region
, Sdelete_region
, 2, 2, "r",
3742 doc
: /* Delete the text between START and END.
3743 If called interactively, delete the region between point and mark.
3744 This command deletes buffer text without modifying the kill ring. */)
3745 (Lisp_Object start
, Lisp_Object end
)
3747 validate_region (&start
, &end
);
3748 del_range (XINT (start
), XINT (end
));
3752 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region
,
3753 Sdelete_and_extract_region
, 2, 2, 0,
3754 doc
: /* Delete the text between START and END and return it. */)
3755 (Lisp_Object start
, Lisp_Object end
)
3757 validate_region (&start
, &end
);
3758 if (XINT (start
) == XINT (end
))
3759 return empty_unibyte_string
;
3760 return del_range_1 (XINT (start
), XINT (end
), 1, 1);
3763 DEFUN ("widen", Fwiden
, Swiden
, 0, 0, "",
3764 doc
: /* Remove restrictions (narrowing) from current buffer.
3765 This allows the buffer's full text to be seen and edited. */)
3768 if (BEG
!= BEGV
|| Z
!= ZV
)
3769 current_buffer
->clip_changed
= 1;
3771 BEGV_BYTE
= BEG_BYTE
;
3772 SET_BUF_ZV_BOTH (current_buffer
, Z
, Z_BYTE
);
3773 /* Changing the buffer bounds invalidates any recorded current column. */
3774 invalidate_current_column ();
3778 DEFUN ("narrow-to-region", Fnarrow_to_region
, Snarrow_to_region
, 2, 2, "r",
3779 doc
: /* Restrict editing in this buffer to the current region.
3780 The rest of the text becomes temporarily invisible and untouchable
3781 but is not deleted; if you save the buffer in a file, the invisible
3782 text is included in the file. \\[widen] makes all visible again.
3783 See also `save-restriction'.
3785 When calling from a program, pass two arguments; positions (integers
3786 or markers) bounding the text that should remain visible. */)
3787 (register Lisp_Object start
, Lisp_Object end
)
3789 CHECK_NUMBER_COERCE_MARKER (start
);
3790 CHECK_NUMBER_COERCE_MARKER (end
);
3792 if (XINT (start
) > XINT (end
))
3795 tem
= start
; start
= end
; end
= tem
;
3798 if (!(BEG
<= XINT (start
) && XINT (start
) <= XINT (end
) && XINT (end
) <= Z
))
3799 args_out_of_range (start
, end
);
3801 if (BEGV
!= XFASTINT (start
) || ZV
!= XFASTINT (end
))
3802 current_buffer
->clip_changed
= 1;
3804 SET_BUF_BEGV (current_buffer
, XFASTINT (start
));
3805 SET_BUF_ZV (current_buffer
, XFASTINT (end
));
3806 if (PT
< XFASTINT (start
))
3807 SET_PT (XFASTINT (start
));
3808 if (PT
> XFASTINT (end
))
3809 SET_PT (XFASTINT (end
));
3810 /* Changing the buffer bounds invalidates any recorded current column. */
3811 invalidate_current_column ();
3816 save_restriction_save (void)
3818 if (BEGV
== BEG
&& ZV
== Z
)
3819 /* The common case that the buffer isn't narrowed.
3820 We return just the buffer object, which save_restriction_restore
3821 recognizes as meaning `no restriction'. */
3822 return Fcurrent_buffer ();
3824 /* We have to save a restriction, so return a pair of markers, one
3825 for the beginning and one for the end. */
3827 Lisp_Object beg
, end
;
3829 beg
= build_marker (current_buffer
, BEGV
, BEGV_BYTE
);
3830 end
= build_marker (current_buffer
, ZV
, ZV_BYTE
);
3832 /* END must move forward if text is inserted at its exact location. */
3833 XMARKER (end
)->insertion_type
= 1;
3835 return Fcons (beg
, end
);
3840 save_restriction_restore (Lisp_Object data
)
3842 struct buffer
*cur
= NULL
;
3843 struct buffer
*buf
= (CONSP (data
)
3844 ? XMARKER (XCAR (data
))->buffer
3847 if (buf
&& buf
!= current_buffer
&& !NILP (BVAR (buf
, pt_marker
)))
3848 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3849 is the case if it is or has an indirect buffer), then make
3850 sure it is current before we update BEGV, so
3851 set_buffer_internal takes care of managing those markers. */
3852 cur
= current_buffer
;
3853 set_buffer_internal (buf
);
3857 /* A pair of marks bounding a saved restriction. */
3859 struct Lisp_Marker
*beg
= XMARKER (XCAR (data
));
3860 struct Lisp_Marker
*end
= XMARKER (XCDR (data
));
3861 eassert (buf
== end
->buffer
);
3863 if (buf
/* Verify marker still points to a buffer. */
3864 && (beg
->charpos
!= BUF_BEGV (buf
) || end
->charpos
!= BUF_ZV (buf
)))
3865 /* The restriction has changed from the saved one, so restore
3866 the saved restriction. */
3868 ptrdiff_t pt
= BUF_PT (buf
);
3870 SET_BUF_BEGV_BOTH (buf
, beg
->charpos
, beg
->bytepos
);
3871 SET_BUF_ZV_BOTH (buf
, end
->charpos
, end
->bytepos
);
3873 if (pt
< beg
->charpos
|| pt
> end
->charpos
)
3874 /* The point is outside the new visible range, move it inside. */
3875 SET_BUF_PT_BOTH (buf
,
3876 clip_to_bounds (beg
->charpos
, pt
, end
->charpos
),
3877 clip_to_bounds (beg
->bytepos
, BUF_PT_BYTE (buf
),
3880 buf
->clip_changed
= 1; /* Remember that the narrowing changed. */
3882 /* These aren't needed anymore, so don't wait for GC. */
3883 free_marker (XCAR (data
));
3884 free_marker (XCDR (data
));
3885 free_cons (XCONS (data
));
3888 /* A buffer, which means that there was no old restriction. */
3890 if (buf
/* Verify marker still points to a buffer. */
3891 && (BUF_BEGV (buf
) != BUF_BEG (buf
) || BUF_ZV (buf
) != BUF_Z (buf
)))
3892 /* The buffer has been narrowed, get rid of the narrowing. */
3894 SET_BUF_BEGV_BOTH (buf
, BUF_BEG (buf
), BUF_BEG_BYTE (buf
));
3895 SET_BUF_ZV_BOTH (buf
, BUF_Z (buf
), BUF_Z_BYTE (buf
));
3897 buf
->clip_changed
= 1; /* Remember that the narrowing changed. */
3901 /* Changing the buffer bounds invalidates any recorded current column. */
3902 invalidate_current_column ();
3905 set_buffer_internal (cur
);
3908 DEFUN ("save-restriction", Fsave_restriction
, Ssave_restriction
, 0, UNEVALLED
, 0,
3909 doc
: /* Execute BODY, saving and restoring current buffer's restrictions.
3910 The buffer's restrictions make parts of the beginning and end invisible.
3911 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3912 This special form, `save-restriction', saves the current buffer's restrictions
3913 when it is entered, and restores them when it is exited.
3914 So any `narrow-to-region' within BODY lasts only until the end of the form.
3915 The old restrictions settings are restored
3916 even in case of abnormal exit (throw or error).
3918 The value returned is the value of the last form in BODY.
3920 Note: if you are using both `save-excursion' and `save-restriction',
3921 use `save-excursion' outermost:
3922 (save-excursion (save-restriction ...))
3924 usage: (save-restriction &rest BODY) */)
3927 register Lisp_Object val
;
3928 ptrdiff_t count
= SPECPDL_INDEX ();
3930 record_unwind_protect (save_restriction_restore
, save_restriction_save ());
3931 val
= Fprogn (body
);
3932 return unbind_to (count
, val
);
3935 DEFUN ("message", Fmessage
, Smessage
, 1, MANY
, 0,
3936 doc
: /* Display a message at the bottom of the screen.
3937 The message also goes into the `*Messages*' buffer, if `message-log-max'
3938 is non-nil. (In keyboard macros, that's all it does.)
3941 In batch mode, the message is printed to the standard error stream,
3942 followed by a newline.
3944 The first argument is a format control string, and the rest are data
3945 to be formatted under control of the string. Percent sign (%), grave
3946 accent (\\=`) and apostrophe (\\=') are special in the format; see
3947 `format-message' for details. To display STRING without special
3948 treatment, use (message "%s" STRING).
3950 If the first argument is nil or the empty string, the function clears
3951 any existing message; this lets the minibuffer contents show. See
3952 also `current-message'.
3954 usage: (message FORMAT-STRING &rest ARGS) */)
3955 (ptrdiff_t nargs
, Lisp_Object
*args
)
3958 || (STRINGP (args
[0])
3959 && SBYTES (args
[0]) == 0))
3966 Lisp_Object val
= Fformat_message (nargs
, args
);
3972 DEFUN ("message-box", Fmessage_box
, Smessage_box
, 1, MANY
, 0,
3973 doc
: /* Display a message, in a dialog box if possible.
3974 If a dialog box is not available, use the echo area.
3975 The first argument is a format control string, and the rest are data
3976 to be formatted under control of the string. See `format-message' for
3979 If the first argument is nil or the empty string, clear any existing
3980 message; let the minibuffer contents show.
3982 usage: (message-box FORMAT-STRING &rest ARGS) */)
3983 (ptrdiff_t nargs
, Lisp_Object
*args
)
3992 Lisp_Object val
= Fformat_message (nargs
, args
);
3993 Lisp_Object pane
, menu
;
3995 pane
= list1 (Fcons (build_string ("OK"), Qt
));
3996 menu
= Fcons (val
, pane
);
3997 Fx_popup_dialog (Qt
, menu
, Qt
);
4002 DEFUN ("message-or-box", Fmessage_or_box
, Smessage_or_box
, 1, MANY
, 0,
4003 doc
: /* Display a message in a dialog box or in the echo area.
4004 If this command was invoked with the mouse, use a dialog box if
4005 `use-dialog-box' is non-nil.
4006 Otherwise, use the echo area.
4007 The first argument is a format control string, and the rest are data
4008 to be formatted under control of the string. See `format-message' for
4011 If the first argument is nil or the empty string, clear any existing
4012 message; let the minibuffer contents show.
4014 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
4015 (ptrdiff_t nargs
, Lisp_Object
*args
)
4017 if ((NILP (last_nonmenu_event
) || CONSP (last_nonmenu_event
))
4019 return Fmessage_box (nargs
, args
);
4020 return Fmessage (nargs
, args
);
4023 DEFUN ("current-message", Fcurrent_message
, Scurrent_message
, 0, 0, 0,
4024 doc
: /* Return the string currently displayed in the echo area, or nil if none. */)
4027 return current_message ();
4031 DEFUN ("propertize", Fpropertize
, Spropertize
, 1, MANY
, 0,
4032 doc
: /* Return a copy of STRING with text properties added.
4033 First argument is the string to copy.
4034 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
4035 properties to add to the result.
4036 usage: (propertize STRING &rest PROPERTIES) */)
4037 (ptrdiff_t nargs
, Lisp_Object
*args
)
4039 Lisp_Object properties
, string
;
4042 /* Number of args must be odd. */
4043 if ((nargs
& 1) == 0)
4044 error ("Wrong number of arguments");
4046 properties
= string
= Qnil
;
4048 /* First argument must be a string. */
4049 CHECK_STRING (args
[0]);
4050 string
= Fcopy_sequence (args
[0]);
4052 for (i
= 1; i
< nargs
; i
+= 2)
4053 properties
= Fcons (args
[i
], Fcons (args
[i
+ 1], properties
));
4055 Fadd_text_properties (make_number (0),
4056 make_number (SCHARS (string
)),
4057 properties
, string
);
4061 /* Convert the prefix of STR from ASCII decimal digits to a number.
4062 Set *STR_END to the address of the first non-digit. Return the
4063 number, or PTRDIFF_MAX on overflow. Return 0 if there is no number.
4064 This is like strtol for ptrdiff_t and base 10 and C locale,
4065 except without negative numbers or errno. */
4068 str2num (char *str
, char **str_end
)
4071 for (; c_isdigit (*str
); str
++)
4072 if (INT_MULTIPLY_WRAPV (n
, 10, &n
) || INT_ADD_WRAPV (n
, *str
- '0', &n
))
4078 DEFUN ("format", Fformat
, Sformat
, 1, MANY
, 0,
4079 doc
: /* Format a string out of a format-string and arguments.
4080 The first argument is a format control string.
4081 The other arguments are substituted into it to make the result, a string.
4083 The format control string may contain %-sequences meaning to substitute
4084 the next available argument, or the argument explicitly specified:
4086 %s means print a string argument. Actually, prints any object, with `princ'.
4087 %d means print as signed number in decimal.
4088 %o means print as unsigned number in octal, %x as unsigned number in hex.
4089 %X is like %x, but uses upper case.
4090 %e means print a number in exponential notation.
4091 %f means print a number in decimal-point notation.
4092 %g means print a number in exponential notation if the exponent would be
4093 less than -4 or greater than or equal to the precision (default: 6);
4094 otherwise it prints in decimal-point notation.
4095 %c means print a number as a single character.
4096 %S means print any object as an s-expression (using `prin1').
4098 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
4099 Use %% to put a single % into the output.
4101 A %-sequence other than %% may contain optional field number, flag,
4102 width, and precision specifiers, as follows:
4104 %<field><flags><width><precision>character
4106 where field is [0-9]+ followed by a literal dollar "$", flags is
4107 [+ #-0]+, width is [0-9]+, and precision is a literal period "."
4110 If a %-sequence is numbered with a field with positive value N, the
4111 Nth argument is substituted instead of the next one. A format can
4112 contain either numbered or unnumbered %-sequences but not both, except
4113 that %% can be mixed with numbered %-sequences.
4115 The + flag character inserts a + before any positive number, while a
4116 space inserts a space before any positive number; these flags only
4117 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
4118 The - and 0 flags affect the width specifier, as described below.
4120 The # flag means to use an alternate display form for %o, %x, %X, %e,
4121 %f, and %g sequences: for %o, it ensures that the result begins with
4122 \"0\"; for %x and %X, it prefixes the result with \"0x\" or \"0X\";
4123 for %e and %f, it causes a decimal point to be included even if the
4124 precision is zero; for %g, it causes a decimal point to be
4125 included even if the precision is zero, and also forces trailing
4126 zeros after the decimal point to be left in place.
4128 The width specifier supplies a lower limit for the length of the
4129 printed representation. The padding, if any, normally goes on the
4130 left, but it goes on the right if the - flag is present. The padding
4131 character is normally a space, but it is 0 if the 0 flag is present.
4132 The 0 flag is ignored if the - flag is present, or the format sequence
4133 is something other than %d, %e, %f, and %g.
4135 For %e and %f sequences, the number after the "." in the precision
4136 specifier says how many decimal places to show; if zero, the decimal
4137 point itself is omitted. For %g, the precision specifies how many
4138 significant digits to print; zero or omitted are treated as 1.
4139 For %s and %S, the precision specifier truncates the string to the
4142 Text properties, if any, are copied from the format-string to the
4145 usage: (format STRING &rest OBJECTS) */)
4146 (ptrdiff_t nargs
, Lisp_Object
*args
)
4148 return styled_format (nargs
, args
, false);
4151 DEFUN ("format-message", Fformat_message
, Sformat_message
, 1, MANY
, 0,
4152 doc
: /* Format a string out of a format-string and arguments.
4153 The first argument is a format control string.
4154 The other arguments are substituted into it to make the result, a string.
4156 This acts like `format', except it also replaces each grave accent (\\=`)
4157 by a left quote, and each apostrophe (\\=') by a right quote. The left
4158 and right quote replacement characters are specified by
4159 `text-quoting-style'.
4161 usage: (format-message STRING &rest OBJECTS) */)
4162 (ptrdiff_t nargs
, Lisp_Object
*args
)
4164 return styled_format (nargs
, args
, true);
4167 /* Implement ‘format-message’ if MESSAGE is true, ‘format’ otherwise. */
4170 styled_format (ptrdiff_t nargs
, Lisp_Object
*args
, bool message
)
4172 ptrdiff_t n
; /* The number of the next arg to substitute. */
4173 char initial_buffer
[4000];
4174 char *buf
= initial_buffer
;
4175 ptrdiff_t bufsize
= sizeof initial_buffer
;
4176 ptrdiff_t max_bufsize
= STRING_BYTES_BOUND
+ 1;
4178 ptrdiff_t buf_save_value_index UNINIT
;
4181 /* When we make a multibyte string, we must pay attention to the
4182 byte combining problem, i.e., a byte may be combined with a
4183 multibyte character of the previous string. This flag tells if we
4184 must consider such a situation or not. */
4185 bool maybe_combine_byte
;
4187 bool arg_intervals
= false;
4189 sa_avail
-= sizeof initial_buffer
;
4191 /* Information recorded for each format spec. */
4194 /* The corresponding argument, converted to string if conversion
4196 Lisp_Object argument
;
4198 /* The start and end bytepos in the output string. */
4199 ptrdiff_t start
, end
;
4201 /* Whether the argument is a string with intervals. */
4202 bool_bf intervals
: 1;
4205 CHECK_STRING (args
[0]);
4206 char *format_start
= SSDATA (args
[0]);
4207 bool multibyte_format
= STRING_MULTIBYTE (args
[0]);
4208 ptrdiff_t formatlen
= SBYTES (args
[0]);
4210 /* Upper bound on number of format specs. Each uses at least 2 chars. */
4211 ptrdiff_t nspec_bound
= SCHARS (args
[0]) >> 1;
4213 /* Allocate the info and discarded tables. */
4214 ptrdiff_t info_size
, alloca_size
;
4215 if (INT_MULTIPLY_WRAPV (nspec_bound
, sizeof *info
, &info_size
)
4216 || INT_ADD_WRAPV (formatlen
, info_size
, &alloca_size
)
4217 || SIZE_MAX
< alloca_size
)
4218 memory_full (SIZE_MAX
);
4219 info
= SAFE_ALLOCA (alloca_size
);
4220 /* discarded[I] is 1 if byte I of the format
4221 string was not copied into the output.
4222 It is 2 if byte I was not the first byte of its character. */
4223 char *discarded
= (char *) &info
[nspec_bound
];
4224 info
= ptr_bounds_clip (info
, info_size
);
4225 discarded
= ptr_bounds_clip (discarded
, formatlen
);
4226 memset (discarded
, 0, formatlen
);
4228 /* Try to determine whether the result should be multibyte.
4229 This is not always right; sometimes the result needs to be multibyte
4230 because of an object that we will pass through prin1.
4231 or because a grave accent or apostrophe is requoted,
4232 and in that case, we won't know it here. */
4234 /* True if the output should be a multibyte string,
4235 which is true if any of the inputs is one. */
4236 bool multibyte
= multibyte_format
;
4237 for (ptrdiff_t i
= 1; !multibyte
&& i
< nargs
; i
++)
4238 if (STRINGP (args
[i
]) && STRING_MULTIBYTE (args
[i
]))
4241 int quoting_style
= message
? text_quoting_style () : -1;
4244 ptrdiff_t nspec
= 0;
4246 /* True if a string needs to be allocated to hold the result. */
4247 bool new_result
= false;
4249 /* If we start out planning a unibyte result,
4250 then discover it has to be multibyte, we jump back to retry. */
4256 /* N is the argument index, ISPEC is the specification index. */
4260 /* Scan the format and store result in BUF. */
4261 format
= format_start
;
4262 end
= format
+ formatlen
;
4263 maybe_combine_byte
= false;
4265 while (format
!= end
)
4267 /* The values of N, ISPEC, and FORMAT when the loop body is
4270 ptrdiff_t ispec0
= ispec
;
4271 char *format0
= format
;
4272 char const *convsrc
= format
;
4273 unsigned char format_char
= *format
++;
4275 /* Bytes needed to represent the output of this conversion. */
4276 ptrdiff_t convbytes
= 1;
4278 if (format_char
== '%')
4280 /* General format specifications look like
4282 '%' [field-number] [flags] [field-width] [precision] format
4286 field-number ::= [0-9]+ '$'
4288 field-width ::= [0-9]+
4289 precision ::= '.' [0-9]*
4291 If present, a field-number specifies the argument number
4292 to substitute. Otherwise, the next argument is taken.
4294 If a field-width is specified, it specifies to which width
4295 the output should be padded with blanks, if the output
4296 string is shorter than field-width.
4298 If precision is specified, it specifies the number of
4299 digits to print after the '.' for floats, or the max.
4300 number of chars to print from a string. */
4304 if (c_isdigit (*format
))
4306 num
= str2num (format
, &num_end
);
4307 if (*num_end
== '$')
4310 format
= num_end
+ 1;
4314 bool minus_flag
= false;
4315 bool plus_flag
= false;
4316 bool space_flag
= false;
4317 bool sharp_flag
= false;
4318 bool zero_flag
= false;
4324 case '-': minus_flag
= true; continue;
4325 case '+': plus_flag
= true; continue;
4326 case ' ': space_flag
= true; continue;
4327 case '#': sharp_flag
= true; continue;
4328 case '0': zero_flag
= true; continue;
4333 /* Ignore flags when sprintf ignores them. */
4334 space_flag
&= ! plus_flag
;
4335 zero_flag
&= ! minus_flag
;
4337 num
= str2num (format
, &num_end
);
4338 if (max_bufsize
<= num
)
4340 ptrdiff_t field_width
= num
;
4342 bool precision_given
= *num_end
== '.';
4343 ptrdiff_t precision
= (precision_given
4344 ? str2num (num_end
+ 1, &num_end
)
4349 error ("Format string ends in middle of format specifier");
4351 char conversion
= *format
++;
4352 memset (&discarded
[format0
- format_start
], 1,
4353 format
- format0
- (conversion
== '%'));
4354 if (conversion
== '%')
4362 error ("Not enough arguments for format string");
4364 struct info
*spec
= &info
[ispec
++];
4367 spec
->argument
= args
[n
];
4368 spec
->intervals
= false;
4371 Lisp_Object arg
= spec
->argument
;
4373 /* For 'S', prin1 the argument, and then treat like 's'.
4374 For 's', princ any argument that is not a string or
4375 symbol. But don't do this conversion twice, which might
4376 happen after retrying. */
4377 if ((conversion
== 'S'
4378 || (conversion
== 's'
4379 && ! STRINGP (arg
) && ! SYMBOLP (arg
))))
4381 if (EQ (arg
, args
[n
]))
4383 Lisp_Object noescape
= conversion
== 'S' ? Qnil
: Qt
;
4384 spec
->argument
= arg
= Fprin1_to_string (arg
, noescape
);
4385 if (STRING_MULTIBYTE (arg
) && ! multibyte
)
4393 else if (conversion
== 'c')
4395 if (INTEGERP (arg
) && ! ASCII_CHAR_P (XINT (arg
)))
4402 spec
->argument
= arg
= Fchar_to_string (arg
);
4405 if (!EQ (arg
, args
[n
]))
4412 spec
->argument
= arg
= SYMBOL_NAME (arg
);
4413 if (STRING_MULTIBYTE (arg
) && ! multibyte
)
4420 bool float_conversion
4421 = conversion
== 'e' || conversion
== 'f' || conversion
== 'g';
4423 if (conversion
== 's')
4425 if (format
== end
&& format
- format_start
== 2
4426 && ! string_intervals (args
[0]))
4432 /* handle case (precision[n] >= 0) */
4434 ptrdiff_t prec
= -1;
4435 if (precision_given
)
4438 /* lisp_string_width ignores a precision of 0, but GNU
4439 libc functions print 0 characters when the precision
4440 is 0. Imitate libc behavior here. Changing
4441 lisp_string_width is the right thing, and will be
4442 done, but meanwhile we work with it. */
4444 ptrdiff_t width
, nbytes
;
4445 ptrdiff_t nchars_string
;
4447 width
= nchars_string
= nbytes
= 0;
4451 width
= lisp_string_width (arg
, prec
, &nch
, &nby
);
4454 nchars_string
= SCHARS (arg
);
4455 nbytes
= SBYTES (arg
);
4459 nchars_string
= nch
;
4465 if (convbytes
&& multibyte
&& ! STRING_MULTIBYTE (arg
))
4466 convbytes
= count_size_as_multibyte (SDATA (arg
), nbytes
);
4469 = width
< field_width
? field_width
- width
: 0;
4471 if (max_bufsize
- padding
<= convbytes
)
4473 convbytes
+= padding
;
4474 if (convbytes
<= buf
+ bufsize
- p
)
4478 memset (p
, ' ', padding
);
4482 spec
->start
= nchars
;
4486 && !ASCII_CHAR_P (*((unsigned char *) p
- 1))
4487 && STRING_MULTIBYTE (arg
)
4488 && !CHAR_HEAD_P (SREF (arg
, 0)))
4489 maybe_combine_byte
= true;
4491 p
+= copy_text (SDATA (arg
), (unsigned char *) p
,
4493 STRING_MULTIBYTE (arg
), multibyte
);
4495 nchars
+= nchars_string
;
4499 memset (p
, ' ', padding
);
4505 /* If this argument has text properties, record where
4506 in the result string it appears. */
4507 if (string_intervals (arg
))
4508 spec
->intervals
= arg_intervals
= true;
4514 else if (! (conversion
== 'c' || conversion
== 'd'
4515 || float_conversion
|| conversion
== 'i'
4516 || conversion
== 'o' || conversion
== 'x'
4517 || conversion
== 'X'))
4518 error ("Invalid format operation %%%c",
4519 STRING_CHAR ((unsigned char *) format
- 1));
4520 else if (! (INTEGERP (arg
) || (FLOATP (arg
) && conversion
!= 'c')))
4521 error ("Format specifier doesn't match argument type");
4526 /* Lower bound on the number of bits per
4527 base-FLT_RADIX digit. */
4528 DIG_BITS_LBOUND
= FLT_RADIX
< 16 ? 1 : 4,
4530 /* 1 if integers should be formatted as long doubles,
4531 because they may be so large that there is a rounding
4532 error when converting them to double, and long doubles
4533 are wider than doubles. */
4534 INT_AS_LDBL
= (DIG_BITS_LBOUND
* DBL_MANT_DIG
< FIXNUM_BITS
- 1
4535 && DBL_MANT_DIG
< LDBL_MANT_DIG
),
4537 /* Maximum precision for a %f conversion such that the
4538 trailing output digit might be nonzero. Any precision
4539 larger than this will not yield useful information. */
4540 USEFUL_PRECISION_MAX
=
4542 * (FLT_RADIX
== 2 || FLT_RADIX
== 10 ? 1
4543 : FLT_RADIX
== 16 ? 4
4546 /* Maximum number of bytes generated by any format, if
4547 precision is no more than USEFUL_PRECISION_MAX.
4548 On all practical hosts, %f is the worst case. */
4550 sizeof "-." + (LDBL_MAX_10_EXP
+ 1) + USEFUL_PRECISION_MAX
,
4552 /* Length of pM (that is, of pMd without the
4554 pMlen
= sizeof pMd
- 2
4556 verify (USEFUL_PRECISION_MAX
> 0);
4558 /* Avoid undefined behavior in underlying sprintf. */
4559 if (conversion
== 'd' || conversion
== 'i')
4562 /* Create the copy of the conversion specification, with
4563 any width and precision removed, with ".*" inserted,
4564 with "L" possibly inserted for floating-point formats,
4565 and with pM inserted for integer formats.
4566 At most two flags F can be specified at once. */
4567 char convspec
[sizeof "%FF.*d" + max (INT_AS_LDBL
, pMlen
)];
4570 /* MINUS_FLAG and ZERO_FLAG are dealt with later. */
4571 *f
= '+'; f
+= plus_flag
;
4572 *f
= ' '; f
+= space_flag
;
4573 *f
= '#'; f
+= sharp_flag
;
4576 if (float_conversion
)
4581 f
+= INTEGERP (arg
);
4584 else if (conversion
!= 'c')
4586 memcpy (f
, pMd
, pMlen
);
4588 zero_flag
&= ! precision_given
;
4594 if (precision_given
)
4595 prec
= min (precision
, USEFUL_PRECISION_MAX
);
4597 /* Use sprintf to format this number into sprintf_buf. Omit
4598 padding and excess precision, though, because sprintf limits
4599 output length to INT_MAX.
4601 There are four types of conversion: double, unsigned
4602 char (passed as int), wide signed int, and wide
4603 unsigned int. Treat them separately because the
4604 sprintf ABI is sensitive to which type is passed. Be
4605 careful about integer overflow, NaNs, infinities, and
4606 conversions; for example, the min and max macros are
4607 not suitable here. */
4608 char sprintf_buf
[SPRINTF_BUFSIZE
];
4609 ptrdiff_t sprintf_bytes
;
4610 if (float_conversion
)
4612 if (INT_AS_LDBL
&& INTEGERP (arg
))
4614 /* Although long double may have a rounding error if
4615 DIG_BITS_LBOUND * LDBL_MANT_DIG < FIXNUM_BITS - 1,
4616 it is more accurate than plain 'double'. */
4617 long double x
= XINT (arg
);
4618 sprintf_bytes
= sprintf (sprintf_buf
, convspec
, prec
, x
);
4621 sprintf_bytes
= sprintf (sprintf_buf
, convspec
, prec
,
4624 else if (conversion
== 'c')
4626 /* Don't use sprintf here, as it might mishandle prec. */
4627 sprintf_buf
[0] = XINT (arg
);
4628 sprintf_bytes
= prec
!= 0;
4629 sprintf_buf
[sprintf_bytes
] = '\0';
4631 else if (conversion
== 'd' || conversion
== 'i')
4635 printmax_t x
= XINT (arg
);
4636 sprintf_bytes
= sprintf (sprintf_buf
, convspec
, prec
, x
);
4640 strcpy (f
- pMlen
- 1, "f");
4641 double x
= XFLOAT_DATA (arg
);
4642 sprintf_bytes
= sprintf (sprintf_buf
, convspec
, 0, x
);
4643 char c0
= sprintf_buf
[0];
4644 bool signedp
= ! ('0' <= c0
&& c0
<= '9');
4645 prec
= min (precision
, sprintf_bytes
- signedp
);
4650 /* Don't sign-extend for octal or hex printing. */
4656 double d
= XFLOAT_DATA (arg
);
4657 double uprintmax
= TYPE_MAXIMUM (uprintmax_t
);
4658 if (! (0 <= d
&& d
< uprintmax
+ 1))
4659 xsignal1 (Qoverflow_error
, arg
);
4662 sprintf_bytes
= sprintf (sprintf_buf
, convspec
, prec
, x
);
4665 /* Now the length of the formatted item is known, except it omits
4666 padding and excess precision. Deal with excess precision
4667 first. This happens when the format specifies ridiculously
4668 large precision, or when %d or %i formats a float that would
4669 ordinarily need fewer digits than a specified precision. */
4670 ptrdiff_t excess_precision
4671 = precision_given
? precision
- prec
: 0;
4672 ptrdiff_t leading_zeros
= 0, trailing_zeros
= 0;
4673 if (excess_precision
)
4675 if (float_conversion
)
4677 if ((conversion
== 'g' && ! sharp_flag
)
4678 || ! ('0' <= sprintf_buf
[sprintf_bytes
- 1]
4679 && sprintf_buf
[sprintf_bytes
- 1] <= '9'))
4680 excess_precision
= 0;
4683 if (conversion
== 'g')
4685 char *dot
= strchr (sprintf_buf
, '.');
4687 excess_precision
= 0;
4690 trailing_zeros
= excess_precision
;
4693 leading_zeros
= excess_precision
;
4696 /* Compute the total bytes needed for this item, including
4697 excess precision and padding. */
4699 if (INT_ADD_WRAPV (sprintf_bytes
, excess_precision
, &numwidth
))
4700 numwidth
= PTRDIFF_MAX
;
4702 = numwidth
< field_width
? field_width
- numwidth
: 0;
4703 if (max_bufsize
- sprintf_bytes
<= excess_precision
4704 || max_bufsize
- padding
<= numwidth
)
4706 convbytes
= numwidth
+ padding
;
4708 if (convbytes
<= buf
+ bufsize
- p
)
4710 /* Copy the formatted item from sprintf_buf into buf,
4711 inserting padding and excess-precision zeros. */
4713 char *src
= sprintf_buf
;
4715 int exponent_bytes
= 0;
4716 bool signedp
= src0
== '-' || src0
== '+' || src0
== ' ';
4717 int prefix_bytes
= (signedp
4718 + ((src
[signedp
] == '0'
4719 && (src
[signedp
+ 1] == 'x'
4720 || src
[signedp
+ 1] == 'X'))
4724 unsigned char after_prefix
= src
[prefix_bytes
];
4725 if (0 <= char_hexdigit (after_prefix
))
4727 leading_zeros
+= padding
;
4732 if (excess_precision
4733 && (conversion
== 'e' || conversion
== 'g'))
4735 char *e
= strchr (src
, 'e');
4737 exponent_bytes
= src
+ sprintf_bytes
- e
;
4740 spec
->start
= nchars
;
4743 memset (p
, ' ', padding
);
4748 memcpy (p
, src
, prefix_bytes
);
4750 src
+= prefix_bytes
;
4751 memset (p
, '0', leading_zeros
);
4753 int significand_bytes
4754 = sprintf_bytes
- prefix_bytes
- exponent_bytes
;
4755 memcpy (p
, src
, significand_bytes
);
4756 p
+= significand_bytes
;
4757 src
+= significand_bytes
;
4758 memset (p
, '0', trailing_zeros
);
4759 p
+= trailing_zeros
;
4760 memcpy (p
, src
, exponent_bytes
);
4761 p
+= exponent_bytes
;
4763 nchars
+= leading_zeros
+ sprintf_bytes
+ trailing_zeros
;
4767 memset (p
, ' ', padding
);
4780 unsigned char str
[MAX_MULTIBYTE_LENGTH
];
4782 if ((format_char
== '`' || format_char
== '\'')
4783 && quoting_style
== CURVE_QUOTING_STYLE
)
4790 convsrc
= format_char
== '`' ? uLSQM
: uRSQM
;
4794 else if (format_char
== '`' && quoting_style
== STRAIGHT_QUOTING_STYLE
)
4801 /* Copy a single character from format to buf. */
4802 if (multibyte_format
)
4804 /* Copy a whole multibyte character. */
4806 && !ASCII_CHAR_P (*((unsigned char *) p
- 1))
4807 && !CHAR_HEAD_P (format_char
))
4808 maybe_combine_byte
= true;
4810 while (! CHAR_HEAD_P (*format
))
4813 convbytes
= format
- format0
;
4814 memset (&discarded
[format0
+ 1 - format_start
], 2,
4817 else if (multibyte
&& !ASCII_CHAR_P (format_char
))
4819 int c
= BYTE8_TO_CHAR (format_char
);
4820 convbytes
= CHAR_STRING (c
, str
);
4821 convsrc
= (char *) str
;
4827 if (convbytes
<= buf
+ bufsize
- p
)
4829 memcpy (p
, convsrc
, convbytes
);
4836 /* There wasn't enough room to store this conversion or single
4837 character. CONVBYTES says how much room is needed. Allocate
4838 enough room (and then some) and do it again. */
4840 ptrdiff_t used
= p
- buf
;
4841 if (max_bufsize
- used
< convbytes
)
4843 bufsize
= used
+ convbytes
;
4844 bufsize
= bufsize
< max_bufsize
/ 2 ? bufsize
* 2 : max_bufsize
;
4846 if (buf
== initial_buffer
)
4848 buf
= xmalloc (bufsize
);
4849 sa_must_free
= true;
4850 buf_save_value_index
= SPECPDL_INDEX ();
4851 record_unwind_protect_ptr (xfree
, buf
);
4852 memcpy (buf
, initial_buffer
, used
);
4856 buf
= xrealloc (buf
, bufsize
);
4857 set_unwind_protect_ptr (buf_save_value_index
, xfree
, buf
);
4866 if (bufsize
< p
- buf
)
4875 if (maybe_combine_byte
)
4876 nchars
= multibyte_chars_in_text ((unsigned char *) buf
, p
- buf
);
4877 val
= make_specified_string (buf
, nchars
, p
- buf
, multibyte
);
4879 /* If the format string has text properties, or any of the string
4880 arguments has text properties, set up text properties of the
4883 if (string_intervals (args
[0]) || arg_intervals
)
4885 /* Add text properties from the format string. */
4886 Lisp_Object len
= make_number (SCHARS (args
[0]));
4887 Lisp_Object props
= text_property_list (args
[0], make_number (0),
4891 ptrdiff_t bytepos
= 0, position
= 0, translated
= 0;
4892 ptrdiff_t fieldn
= 0;
4894 /* Adjust the bounds of each text property
4895 to the proper start and end in the output string. */
4897 /* Put the positions in PROPS in increasing order, so that
4898 we can do (effectively) one scan through the position
4899 space of the format string. */
4900 props
= Fnreverse (props
);
4902 /* BYTEPOS is the byte position in the format string,
4903 POSITION is the untranslated char position in it,
4904 TRANSLATED is the translated char position in BUF,
4905 and ARGN is the number of the next arg we will come to. */
4906 for (Lisp_Object list
= props
; CONSP (list
); list
= XCDR (list
))
4908 Lisp_Object item
= XCAR (list
);
4910 /* First adjust the property start position. */
4911 ptrdiff_t pos
= XINT (XCAR (item
));
4913 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4914 up to this position. */
4915 for (; position
< pos
; bytepos
++)
4917 if (! discarded
[bytepos
])
4918 position
++, translated
++;
4919 else if (discarded
[bytepos
] == 1)
4922 if (fieldn
< nspec
&& translated
== info
[fieldn
].start
)
4924 translated
+= info
[fieldn
].end
- info
[fieldn
].start
;
4930 XSETCAR (item
, make_number (translated
));
4932 /* Likewise adjust the property end position. */
4933 pos
= XINT (XCAR (XCDR (item
)));
4935 for (; position
< pos
; bytepos
++)
4937 if (! discarded
[bytepos
])
4938 position
++, translated
++;
4939 else if (discarded
[bytepos
] == 1)
4942 if (fieldn
< nspec
&& translated
== info
[fieldn
].start
)
4944 translated
+= info
[fieldn
].end
- info
[fieldn
].start
;
4950 XSETCAR (XCDR (item
), make_number (translated
));
4953 add_text_properties_from_list (val
, props
, make_number (0));
4956 /* Add text properties from arguments. */
4958 for (ptrdiff_t i
= 0; i
< nspec
; i
++)
4959 if (info
[i
].intervals
)
4961 len
= make_number (SCHARS (info
[i
].argument
));
4962 Lisp_Object new_len
= make_number (info
[i
].end
- info
[i
].start
);
4963 props
= text_property_list (info
[i
].argument
,
4964 make_number (0), len
, Qnil
);
4965 props
= extend_property_ranges (props
, len
, new_len
);
4966 /* If successive arguments have properties, be sure that
4967 the value of `composition' property be the copy. */
4968 if (1 < i
&& info
[i
- 1].end
)
4969 make_composition_value_copy (props
);
4970 add_text_properties_from_list (val
, props
,
4971 make_number (info
[i
].start
));
4976 /* If we allocated BUF or INFO with malloc, free it too. */
4982 DEFUN ("char-equal", Fchar_equal
, Schar_equal
, 2, 2, 0,
4983 doc
: /* Return t if two characters match, optionally ignoring case.
4984 Both arguments must be characters (i.e. integers).
4985 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4986 (register Lisp_Object c1
, Lisp_Object c2
)
4989 /* Check they're chars, not just integers, otherwise we could get array
4990 bounds violations in downcase. */
4991 CHECK_CHARACTER (c1
);
4992 CHECK_CHARACTER (c2
);
4994 if (XINT (c1
) == XINT (c2
))
4996 if (NILP (BVAR (current_buffer
, case_fold_search
)))
5002 /* FIXME: It is possible to compare multibyte characters even when
5003 the current buffer is unibyte. Unfortunately this is ambiguous
5004 for characters between 128 and 255, as they could be either
5005 eight-bit raw bytes or Latin-1 characters. Assume the former for
5006 now. See Bug#17011, and also see casefiddle.c's casify_object,
5007 which has a similar problem. */
5008 if (NILP (BVAR (current_buffer
, enable_multibyte_characters
)))
5010 if (SINGLE_BYTE_CHAR_P (i1
))
5011 i1
= UNIBYTE_TO_CHAR (i1
);
5012 if (SINGLE_BYTE_CHAR_P (i2
))
5013 i2
= UNIBYTE_TO_CHAR (i2
);
5016 return (downcase (i1
) == downcase (i2
) ? Qt
: Qnil
);
5019 /* Transpose the markers in two regions of the current buffer, and
5020 adjust the ones between them if necessary (i.e.: if the regions
5023 START1, END1 are the character positions of the first region.
5024 START1_BYTE, END1_BYTE are the byte positions.
5025 START2, END2 are the character positions of the second region.
5026 START2_BYTE, END2_BYTE are the byte positions.
5028 Traverses the entire marker list of the buffer to do so, adding an
5029 appropriate amount to some, subtracting from some, and leaving the
5030 rest untouched. Most of this is copied from adjust_markers in insdel.c.
5032 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
5035 transpose_markers (ptrdiff_t start1
, ptrdiff_t end1
,
5036 ptrdiff_t start2
, ptrdiff_t end2
,
5037 ptrdiff_t start1_byte
, ptrdiff_t end1_byte
,
5038 ptrdiff_t start2_byte
, ptrdiff_t end2_byte
)
5040 register ptrdiff_t amt1
, amt1_byte
, amt2
, amt2_byte
, diff
, diff_byte
, mpos
;
5041 register struct Lisp_Marker
*marker
;
5043 /* Update point as if it were a marker. */
5047 TEMP_SET_PT_BOTH (PT
+ (end2
- end1
),
5048 PT_BYTE
+ (end2_byte
- end1_byte
));
5049 else if (PT
< start2
)
5050 TEMP_SET_PT_BOTH (PT
+ (end2
- start2
) - (end1
- start1
),
5051 (PT_BYTE
+ (end2_byte
- start2_byte
)
5052 - (end1_byte
- start1_byte
)));
5054 TEMP_SET_PT_BOTH (PT
- (start2
- start1
),
5055 PT_BYTE
- (start2_byte
- start1_byte
));
5057 /* We used to adjust the endpoints here to account for the gap, but that
5058 isn't good enough. Even if we assume the caller has tried to move the
5059 gap out of our way, it might still be at start1 exactly, for example;
5060 and that places it `inside' the interval, for our purposes. The amount
5061 of adjustment is nontrivial if there's a `denormalized' marker whose
5062 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
5063 the dirty work to Fmarker_position, below. */
5065 /* The difference between the region's lengths */
5066 diff
= (end2
- start2
) - (end1
- start1
);
5067 diff_byte
= (end2_byte
- start2_byte
) - (end1_byte
- start1_byte
);
5069 /* For shifting each marker in a region by the length of the other
5070 region plus the distance between the regions. */
5071 amt1
= (end2
- start2
) + (start2
- end1
);
5072 amt2
= (end1
- start1
) + (start2
- end1
);
5073 amt1_byte
= (end2_byte
- start2_byte
) + (start2_byte
- end1_byte
);
5074 amt2_byte
= (end1_byte
- start1_byte
) + (start2_byte
- end1_byte
);
5076 for (marker
= BUF_MARKERS (current_buffer
); marker
; marker
= marker
->next
)
5078 mpos
= marker
->bytepos
;
5079 if (mpos
>= start1_byte
&& mpos
< end2_byte
)
5081 if (mpos
< end1_byte
)
5083 else if (mpos
< start2_byte
)
5087 marker
->bytepos
= mpos
;
5089 mpos
= marker
->charpos
;
5090 if (mpos
>= start1
&& mpos
< end2
)
5094 else if (mpos
< start2
)
5099 marker
->charpos
= mpos
;
5103 DEFUN ("transpose-regions", Ftranspose_regions
, Stranspose_regions
, 4, 5,
5104 "(if (< (length mark-ring) 2)\
5105 (error \"Other region must be marked before transposing two regions\")\
5106 (let* ((num (if current-prefix-arg\
5107 (prefix-numeric-value current-prefix-arg)\
5109 (ring-length (length mark-ring))\
5110 (eltnum (mod num ring-length))\
5111 (eltnum2 (mod (1+ num) ring-length)))\
5112 (list (point) (mark) (elt mark-ring eltnum) (elt mark-ring eltnum2))))",
5113 doc
: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
5114 The regions should not be overlapping, because the size of the buffer is
5115 never changed in a transposition.
5117 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
5118 any markers that happen to be located in the regions.
5120 Transposing beyond buffer boundaries is an error.
5122 Interactively, STARTR1 and ENDR1 are point and mark; STARTR2 and ENDR2
5123 are the last two marks pushed to the mark ring; LEAVE-MARKERS is nil.
5124 If a prefix argument N is given, STARTR2 and ENDR2 are the two
5125 successive marks N entries back in the mark ring. A negative prefix
5126 argument instead counts forward from the oldest mark in the mark
5128 (Lisp_Object startr1
, Lisp_Object endr1
, Lisp_Object startr2
, Lisp_Object endr2
, Lisp_Object leave_markers
)
5130 register ptrdiff_t start1
, end1
, start2
, end2
;
5131 ptrdiff_t start1_byte
, start2_byte
, len1_byte
, len2_byte
, end2_byte
;
5132 ptrdiff_t gap
, len1
, len_mid
, len2
;
5133 unsigned char *start1_addr
, *start2_addr
, *temp
;
5135 INTERVAL cur_intv
, tmp_interval1
, tmp_interval_mid
, tmp_interval2
, tmp_interval3
;
5138 XSETBUFFER (buf
, current_buffer
);
5139 cur_intv
= buffer_intervals (current_buffer
);
5141 validate_region (&startr1
, &endr1
);
5142 validate_region (&startr2
, &endr2
);
5144 start1
= XFASTINT (startr1
);
5145 end1
= XFASTINT (endr1
);
5146 start2
= XFASTINT (startr2
);
5147 end2
= XFASTINT (endr2
);
5150 /* Swap the regions if they're reversed. */
5153 register ptrdiff_t glumph
= start1
;
5161 len1
= end1
- start1
;
5162 len2
= end2
- start2
;
5165 error ("Transposed regions overlap");
5166 /* Nothing to change for adjacent regions with one being empty */
5167 else if ((start1
== end1
|| start2
== end2
) && end1
== start2
)
5170 /* The possibilities are:
5171 1. Adjacent (contiguous) regions, or separate but equal regions
5172 (no, really equal, in this case!), or
5173 2. Separate regions of unequal size.
5175 The worst case is usually No. 2. It means that (aside from
5176 potential need for getting the gap out of the way), there also
5177 needs to be a shifting of the text between the two regions. So
5178 if they are spread far apart, we are that much slower... sigh. */
5180 /* It must be pointed out that the really studly thing to do would
5181 be not to move the gap at all, but to leave it in place and work
5182 around it if necessary. This would be extremely efficient,
5183 especially considering that people are likely to do
5184 transpositions near where they are working interactively, which
5185 is exactly where the gap would be found. However, such code
5186 would be much harder to write and to read. So, if you are
5187 reading this comment and are feeling squirrely, by all means have
5188 a go! I just didn't feel like doing it, so I will simply move
5189 the gap the minimum distance to get it out of the way, and then
5190 deal with an unbroken array. */
5192 start1_byte
= CHAR_TO_BYTE (start1
);
5193 end2_byte
= CHAR_TO_BYTE (end2
);
5195 /* Make sure the gap won't interfere, by moving it out of the text
5196 we will operate on. */
5197 if (start1
< gap
&& gap
< end2
)
5199 if (gap
- start1
< end2
- gap
)
5200 move_gap_both (start1
, start1_byte
);
5202 move_gap_both (end2
, end2_byte
);
5205 start2_byte
= CHAR_TO_BYTE (start2
);
5206 len1_byte
= CHAR_TO_BYTE (end1
) - start1_byte
;
5207 len2_byte
= end2_byte
- start2_byte
;
5209 #ifdef BYTE_COMBINING_DEBUG
5212 if (count_combining_before (BYTE_POS_ADDR (start2_byte
),
5213 len2_byte
, start1
, start1_byte
)
5214 || count_combining_before (BYTE_POS_ADDR (start1_byte
),
5215 len1_byte
, end2
, start2_byte
+ len2_byte
)
5216 || count_combining_after (BYTE_POS_ADDR (start1_byte
),
5217 len1_byte
, end2
, start2_byte
+ len2_byte
))
5222 if (count_combining_before (BYTE_POS_ADDR (start2_byte
),
5223 len2_byte
, start1
, start1_byte
)
5224 || count_combining_before (BYTE_POS_ADDR (start1_byte
),
5225 len1_byte
, start2
, start2_byte
)
5226 || count_combining_after (BYTE_POS_ADDR (start2_byte
),
5227 len2_byte
, end1
, start1_byte
+ len1_byte
)
5228 || count_combining_after (BYTE_POS_ADDR (start1_byte
),
5229 len1_byte
, end2
, start2_byte
+ len2_byte
))
5234 /* Hmmm... how about checking to see if the gap is large
5235 enough to use as the temporary storage? That would avoid an
5236 allocation... interesting. Later, don't fool with it now. */
5238 /* Working without memmove, for portability (sigh), so must be
5239 careful of overlapping subsections of the array... */
5241 if (end1
== start2
) /* adjacent regions */
5243 modify_text (start1
, end2
);
5244 record_change (start1
, len1
+ len2
);
5246 tmp_interval1
= copy_intervals (cur_intv
, start1
, len1
);
5247 tmp_interval2
= copy_intervals (cur_intv
, start2
, len2
);
5248 /* Don't use Fset_text_properties: that can cause GC, which can
5249 clobber objects stored in the tmp_intervals. */
5250 tmp_interval3
= validate_interval_range (buf
, &startr1
, &endr2
, 0);
5252 set_text_properties_1 (startr1
, endr2
, Qnil
, buf
, tmp_interval3
);
5256 /* First region smaller than second. */
5257 if (len1_byte
< len2_byte
)
5259 temp
= SAFE_ALLOCA (len2_byte
);
5261 /* Don't precompute these addresses. We have to compute them
5262 at the last minute, because the relocating allocator might
5263 have moved the buffer around during the xmalloc. */
5264 start1_addr
= BYTE_POS_ADDR (start1_byte
);
5265 start2_addr
= BYTE_POS_ADDR (start2_byte
);
5267 memcpy (temp
, start2_addr
, len2_byte
);
5268 memcpy (start1_addr
+ len2_byte
, start1_addr
, len1_byte
);
5269 memcpy (start1_addr
, temp
, len2_byte
);
5272 /* First region not smaller than second. */
5274 temp
= SAFE_ALLOCA (len1_byte
);
5275 start1_addr
= BYTE_POS_ADDR (start1_byte
);
5276 start2_addr
= BYTE_POS_ADDR (start2_byte
);
5277 memcpy (temp
, start1_addr
, len1_byte
);
5278 memcpy (start1_addr
, start2_addr
, len2_byte
);
5279 memcpy (start1_addr
+ len2_byte
, temp
, len1_byte
);
5283 graft_intervals_into_buffer (tmp_interval1
, start1
+ len2
,
5284 len1
, current_buffer
, 0);
5285 graft_intervals_into_buffer (tmp_interval2
, start1
,
5286 len2
, current_buffer
, 0);
5287 update_compositions (start1
, start1
+ len2
, CHECK_BORDER
);
5288 update_compositions (start1
+ len2
, end2
, CHECK_TAIL
);
5290 /* Non-adjacent regions, because end1 != start2, bleagh... */
5293 len_mid
= start2_byte
- (start1_byte
+ len1_byte
);
5295 if (len1_byte
== len2_byte
)
5296 /* Regions are same size, though, how nice. */
5300 modify_text (start1
, end2
);
5301 record_change (start1
, len1
);
5302 record_change (start2
, len2
);
5303 tmp_interval1
= copy_intervals (cur_intv
, start1
, len1
);
5304 tmp_interval2
= copy_intervals (cur_intv
, start2
, len2
);
5306 tmp_interval3
= validate_interval_range (buf
, &startr1
, &endr1
, 0);
5308 set_text_properties_1 (startr1
, endr1
, Qnil
, buf
, tmp_interval3
);
5310 tmp_interval3
= validate_interval_range (buf
, &startr2
, &endr2
, 0);
5312 set_text_properties_1 (startr2
, endr2
, Qnil
, buf
, tmp_interval3
);
5314 temp
= SAFE_ALLOCA (len1_byte
);
5315 start1_addr
= BYTE_POS_ADDR (start1_byte
);
5316 start2_addr
= BYTE_POS_ADDR (start2_byte
);
5317 memcpy (temp
, start1_addr
, len1_byte
);
5318 memcpy (start1_addr
, start2_addr
, len2_byte
);
5319 memcpy (start2_addr
, temp
, len1_byte
);
5322 graft_intervals_into_buffer (tmp_interval1
, start2
,
5323 len1
, current_buffer
, 0);
5324 graft_intervals_into_buffer (tmp_interval2
, start1
,
5325 len2
, current_buffer
, 0);
5328 else if (len1_byte
< len2_byte
) /* Second region larger than first */
5329 /* Non-adjacent & unequal size, area between must also be shifted. */
5333 modify_text (start1
, end2
);
5334 record_change (start1
, (end2
- start1
));
5335 tmp_interval1
= copy_intervals (cur_intv
, start1
, len1
);
5336 tmp_interval_mid
= copy_intervals (cur_intv
, end1
, len_mid
);
5337 tmp_interval2
= copy_intervals (cur_intv
, start2
, len2
);
5339 tmp_interval3
= validate_interval_range (buf
, &startr1
, &endr2
, 0);
5341 set_text_properties_1 (startr1
, endr2
, Qnil
, buf
, tmp_interval3
);
5343 /* holds region 2 */
5344 temp
= SAFE_ALLOCA (len2_byte
);
5345 start1_addr
= BYTE_POS_ADDR (start1_byte
);
5346 start2_addr
= BYTE_POS_ADDR (start2_byte
);
5347 memcpy (temp
, start2_addr
, len2_byte
);
5348 memcpy (start1_addr
+ len_mid
+ len2_byte
, start1_addr
, len1_byte
);
5349 memmove (start1_addr
+ len2_byte
, start1_addr
+ len1_byte
, len_mid
);
5350 memcpy (start1_addr
, temp
, len2_byte
);
5353 graft_intervals_into_buffer (tmp_interval1
, end2
- len1
,
5354 len1
, current_buffer
, 0);
5355 graft_intervals_into_buffer (tmp_interval_mid
, start1
+ len2
,
5356 len_mid
, current_buffer
, 0);
5357 graft_intervals_into_buffer (tmp_interval2
, start1
,
5358 len2
, current_buffer
, 0);
5361 /* Second region smaller than first. */
5365 record_change (start1
, (end2
- start1
));
5366 modify_text (start1
, end2
);
5368 tmp_interval1
= copy_intervals (cur_intv
, start1
, len1
);
5369 tmp_interval_mid
= copy_intervals (cur_intv
, end1
, len_mid
);
5370 tmp_interval2
= copy_intervals (cur_intv
, start2
, len2
);
5372 tmp_interval3
= validate_interval_range (buf
, &startr1
, &endr2
, 0);
5374 set_text_properties_1 (startr1
, endr2
, Qnil
, buf
, tmp_interval3
);
5376 /* holds region 1 */
5377 temp
= SAFE_ALLOCA (len1_byte
);
5378 start1_addr
= BYTE_POS_ADDR (start1_byte
);
5379 start2_addr
= BYTE_POS_ADDR (start2_byte
);
5380 memcpy (temp
, start1_addr
, len1_byte
);
5381 memcpy (start1_addr
, start2_addr
, len2_byte
);
5382 memmove (start1_addr
+ len2_byte
, start1_addr
+ len1_byte
, len_mid
);
5383 memcpy (start1_addr
+ len2_byte
+ len_mid
, temp
, len1_byte
);
5386 graft_intervals_into_buffer (tmp_interval1
, end2
- len1
,
5387 len1
, current_buffer
, 0);
5388 graft_intervals_into_buffer (tmp_interval_mid
, start1
+ len2
,
5389 len_mid
, current_buffer
, 0);
5390 graft_intervals_into_buffer (tmp_interval2
, start1
,
5391 len2
, current_buffer
, 0);
5394 update_compositions (start1
, start1
+ len2
, CHECK_BORDER
);
5395 update_compositions (end2
- len1
, end2
, CHECK_BORDER
);
5398 /* When doing multiple transpositions, it might be nice
5399 to optimize this. Perhaps the markers in any one buffer
5400 should be organized in some sorted data tree. */
5401 if (NILP (leave_markers
))
5403 transpose_markers (start1
, end1
, start2
, end2
,
5404 start1_byte
, start1_byte
+ len1_byte
,
5405 start2_byte
, start2_byte
+ len2_byte
);
5406 fix_start_end_in_overlays (start1
, end2
);
5410 /* The character positions of the markers remain intact, but we
5411 still need to update their byte positions, because the
5412 transposed regions might include multibyte sequences which
5413 make some original byte positions of the markers invalid. */
5414 adjust_markers_bytepos (start1
, start1_byte
, end2
, end2_byte
, 0);
5417 signal_after_change (start1
, end2
- start1
, end2
- start1
);
5423 syms_of_editfns (void)
5425 DEFSYM (Qbuffer_access_fontify_functions
, "buffer-access-fontify-functions");
5426 DEFSYM (Qwall
, "wall");
5428 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion
,
5429 doc
: /* Non-nil means text motion commands don't notice fields. */);
5430 Vinhibit_field_text_motion
= Qnil
;
5432 DEFVAR_LISP ("buffer-access-fontify-functions",
5433 Vbuffer_access_fontify_functions
,
5434 doc
: /* List of functions called by `buffer-substring' to fontify if necessary.
5435 Each function is called with two arguments which specify the range
5436 of the buffer being accessed. */);
5437 Vbuffer_access_fontify_functions
= Qnil
;
5441 obuf
= Fcurrent_buffer ();
5442 /* Do this here, because init_buffer_once is too early--it won't work. */
5443 Fset_buffer (Vprin1_to_string_buffer
);
5444 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
5445 Fset (Fmake_local_variable (Qbuffer_access_fontify_functions
), Qnil
);
5449 DEFVAR_LISP ("buffer-access-fontified-property",
5450 Vbuffer_access_fontified_property
,
5451 doc
: /* Property which (if non-nil) indicates text has been fontified.
5452 `buffer-substring' need not call the `buffer-access-fontify-functions'
5453 functions if all the text being accessed has this property. */);
5454 Vbuffer_access_fontified_property
= Qnil
;
5456 DEFVAR_LISP ("system-name", Vsystem_name
,
5457 doc
: /* The host name of the machine Emacs is running on. */);
5458 Vsystem_name
= cached_system_name
= Qnil
;
5460 DEFVAR_LISP ("user-full-name", Vuser_full_name
,
5461 doc
: /* The full name of the user logged in. */);
5463 DEFVAR_LISP ("user-login-name", Vuser_login_name
,
5464 doc
: /* The user's name, taken from environment variables if possible. */);
5465 Vuser_login_name
= Qnil
;
5467 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name
,
5468 doc
: /* The user's name, based upon the real uid only. */);
5470 DEFVAR_LISP ("operating-system-release", Voperating_system_release
,
5471 doc
: /* The release of the operating system Emacs is running on. */);
5473 defsubr (&Spropertize
);
5474 defsubr (&Schar_equal
);
5475 defsubr (&Sgoto_char
);
5476 defsubr (&Sstring_to_char
);
5477 defsubr (&Schar_to_string
);
5478 defsubr (&Sbyte_to_string
);
5479 defsubr (&Sbuffer_substring
);
5480 defsubr (&Sbuffer_substring_no_properties
);
5481 defsubr (&Sbuffer_string
);
5482 defsubr (&Sget_pos_property
);
5484 defsubr (&Spoint_marker
);
5485 defsubr (&Smark_marker
);
5487 defsubr (&Sregion_beginning
);
5488 defsubr (&Sregion_end
);
5490 /* Symbol for the text property used to mark fields. */
5491 DEFSYM (Qfield
, "field");
5493 /* A special value for Qfield properties. */
5494 DEFSYM (Qboundary
, "boundary");
5496 defsubr (&Sfield_beginning
);
5497 defsubr (&Sfield_end
);
5498 defsubr (&Sfield_string
);
5499 defsubr (&Sfield_string_no_properties
);
5500 defsubr (&Sdelete_field
);
5501 defsubr (&Sconstrain_to_field
);
5503 defsubr (&Sline_beginning_position
);
5504 defsubr (&Sline_end_position
);
5506 defsubr (&Ssave_excursion
);
5507 defsubr (&Ssave_current_buffer
);
5509 defsubr (&Sbuffer_size
);
5510 defsubr (&Spoint_max
);
5511 defsubr (&Spoint_min
);
5512 defsubr (&Spoint_min_marker
);
5513 defsubr (&Spoint_max_marker
);
5514 defsubr (&Sgap_position
);
5515 defsubr (&Sgap_size
);
5516 defsubr (&Sposition_bytes
);
5517 defsubr (&Sbyte_to_position
);
5523 defsubr (&Sfollowing_char
);
5524 defsubr (&Sprevious_char
);
5525 defsubr (&Schar_after
);
5526 defsubr (&Schar_before
);
5528 defsubr (&Sinsert_before_markers
);
5529 defsubr (&Sinsert_and_inherit
);
5530 defsubr (&Sinsert_and_inherit_before_markers
);
5531 defsubr (&Sinsert_char
);
5532 defsubr (&Sinsert_byte
);
5534 defsubr (&Suser_login_name
);
5535 defsubr (&Suser_real_login_name
);
5536 defsubr (&Suser_uid
);
5537 defsubr (&Suser_real_uid
);
5538 defsubr (&Sgroup_gid
);
5539 defsubr (&Sgroup_real_gid
);
5540 defsubr (&Suser_full_name
);
5541 defsubr (&Semacs_pid
);
5542 defsubr (&Scurrent_time
);
5543 defsubr (&Stime_add
);
5544 defsubr (&Stime_subtract
);
5545 defsubr (&Stime_less_p
);
5546 defsubr (&Sget_internal_run_time
);
5547 defsubr (&Sformat_time_string
);
5548 defsubr (&Sfloat_time
);
5549 defsubr (&Sdecode_time
);
5550 defsubr (&Sencode_time
);
5551 defsubr (&Scurrent_time_string
);
5552 defsubr (&Scurrent_time_zone
);
5553 defsubr (&Sset_time_zone_rule
);
5554 defsubr (&Ssystem_name
);
5555 defsubr (&Smessage
);
5556 defsubr (&Smessage_box
);
5557 defsubr (&Smessage_or_box
);
5558 defsubr (&Scurrent_message
);
5560 defsubr (&Sformat_message
);
5562 defsubr (&Sinsert_buffer_substring
);
5563 defsubr (&Scompare_buffer_substrings
);
5564 defsubr (&Sreplace_buffer_contents
);
5565 defsubr (&Ssubst_char_in_region
);
5566 defsubr (&Stranslate_region_internal
);
5567 defsubr (&Sdelete_region
);
5568 defsubr (&Sdelete_and_extract_region
);
5570 defsubr (&Snarrow_to_region
);
5571 defsubr (&Ssave_restriction
);
5572 defsubr (&Stranspose_regions
);