Have `x-show-tip' handle `right' and `bottom' frame parameters.
[emacs.git] / src / editfns.c
blobe39eed6e870838507b97f1ccbd7260a93fec0aba
1 /* Lisp functions pertaining to editing.
3 Copyright (C) 1985-1987, 1989, 1993-2015 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
10 (at 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 <http://www.gnu.org/licenses/>. */
21 #include <config.h>
22 #include <sys/types.h>
23 #include <stdio.h>
25 #ifdef HAVE_PWD_H
26 #include <pwd.h>
27 #include <grp.h>
28 #endif
30 #include <unistd.h>
32 #ifdef HAVE_SYS_UTSNAME_H
33 #include <sys/utsname.h>
34 #endif
36 #include "lisp.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
40 <sys/resource.h> */
41 #include "systime.h"
43 #if defined HAVE_SYS_RESOURCE_H
44 #include <sys/resource.h>
45 #endif
47 #include <float.h>
48 #include <limits.h>
49 #include <intprops.h>
50 #include <strftime.h>
51 #include <verify.h>
53 #include "intervals.h"
54 #include "character.h"
55 #include "buffer.h"
56 #include "coding.h"
57 #include "frame.h"
58 #include "window.h"
59 #include "blockinput.h"
61 #define TM_YEAR_BASE 1900
63 #ifdef WINDOWSNT
64 extern Lisp_Object w32_get_internal_run_time (void);
65 #endif
67 static struct lisp_time lisp_time_struct (Lisp_Object, int *);
68 static void set_time_zone_rule (char const *);
69 static Lisp_Object format_time_string (char const *, ptrdiff_t, struct timespec,
70 bool, struct tm *);
71 static long int tm_gmtoff (struct tm *);
72 static int tm_diff (struct tm *, struct tm *);
73 static void update_buffer_properties (ptrdiff_t, ptrdiff_t);
75 #ifndef HAVE_TM_GMTOFF
76 # define HAVE_TM_GMTOFF false
77 #endif
79 /* The startup value of the TZ environment variable; null if unset. */
80 static char const *initial_tz;
82 /* A valid but unlikely setting for the TZ environment variable.
83 It is OK (though a bit slower) if the user chooses this value. */
84 static char dump_tz_string[] = "TZ=UtC0";
86 /* The cached value of Vsystem_name. This is used only to compare it
87 to Vsystem_name, so it need not be visible to the GC. */
88 static Lisp_Object cached_system_name;
90 static void
91 init_and_cache_system_name (void)
93 init_system_name ();
94 cached_system_name = Vsystem_name;
97 void
98 init_editfns (void)
100 const char *user_name;
101 register char *p;
102 struct passwd *pw; /* password entry for the current user */
103 Lisp_Object tem;
105 /* Set up system_name even when dumping. */
106 init_and_cache_system_name ();
108 #ifndef CANNOT_DUMP
109 /* When just dumping out, set the time zone to a known unlikely value
110 and skip the rest of this function. */
111 if (!initialized)
113 # ifdef HAVE_TZSET
114 xputenv (dump_tz_string);
115 tzset ();
116 # endif
117 return;
119 #endif
121 char *tz = getenv ("TZ");
122 initial_tz = tz;
124 #if !defined CANNOT_DUMP && defined HAVE_TZSET
125 /* If the execution TZ happens to be the same as the dump TZ,
126 change it to some other value and then change it back,
127 to force the underlying implementation to reload the TZ info.
128 This is needed on implementations that load TZ info from files,
129 since the TZ file contents may differ between dump and execution. */
130 if (tz && strcmp (tz, &dump_tz_string[sizeof "TZ=" - 1]) == 0)
132 ++*tz;
133 tzset ();
134 --*tz;
136 #endif
138 /* Call set_time_zone_rule now, so that its call to putenv is done
139 before multiple threads are active. */
140 set_time_zone_rule (tz);
142 pw = getpwuid (getuid ());
143 #ifdef MSDOS
144 /* We let the real user name default to "root" because that's quite
145 accurate on MS-DOS and because it lets Emacs find the init file.
146 (The DVX libraries override the Djgpp libraries here.) */
147 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
148 #else
149 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
150 #endif
152 /* Get the effective user name, by consulting environment variables,
153 or the effective uid if those are unset. */
154 user_name = getenv ("LOGNAME");
155 if (!user_name)
156 #ifdef WINDOWSNT
157 user_name = getenv ("USERNAME"); /* it's USERNAME on NT */
158 #else /* WINDOWSNT */
159 user_name = getenv ("USER");
160 #endif /* WINDOWSNT */
161 if (!user_name)
163 pw = getpwuid (geteuid ());
164 user_name = pw ? pw->pw_name : "unknown";
166 Vuser_login_name = build_string (user_name);
168 /* If the user name claimed in the environment vars differs from
169 the real uid, use the claimed name to find the full name. */
170 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
171 if (! NILP (tem))
172 tem = Vuser_login_name;
173 else
175 uid_t euid = geteuid ();
176 tem = make_fixnum_or_float (euid);
178 Vuser_full_name = Fuser_full_name (tem);
180 p = getenv ("NAME");
181 if (p)
182 Vuser_full_name = build_string (p);
183 else if (NILP (Vuser_full_name))
184 Vuser_full_name = build_string ("unknown");
186 #ifdef HAVE_SYS_UTSNAME_H
188 struct utsname uts;
189 uname (&uts);
190 Voperating_system_release = build_string (uts.release);
192 #else
193 Voperating_system_release = Qnil;
194 #endif
197 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
198 doc: /* Convert arg CHAR to a string containing that character.
199 usage: (char-to-string CHAR) */)
200 (Lisp_Object character)
202 int c, len;
203 unsigned char str[MAX_MULTIBYTE_LENGTH];
205 CHECK_CHARACTER (character);
206 c = XFASTINT (character);
208 len = CHAR_STRING (c, str);
209 return make_string_from_bytes ((char *) str, 1, len);
212 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
213 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
214 (Lisp_Object byte)
216 unsigned char b;
217 CHECK_NUMBER (byte);
218 if (XINT (byte) < 0 || XINT (byte) > 255)
219 error ("Invalid byte");
220 b = XINT (byte);
221 return make_string_from_bytes ((char *) &b, 1, 1);
224 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
225 doc: /* Return the first character in STRING. */)
226 (register Lisp_Object string)
228 register Lisp_Object val;
229 CHECK_STRING (string);
230 if (SCHARS (string))
232 if (STRING_MULTIBYTE (string))
233 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
234 else
235 XSETFASTINT (val, SREF (string, 0));
237 else
238 XSETFASTINT (val, 0);
239 return val;
242 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
243 doc: /* Return value of point, as an integer.
244 Beginning of buffer is position (point-min). */)
245 (void)
247 Lisp_Object temp;
248 XSETFASTINT (temp, PT);
249 return temp;
252 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
253 doc: /* Return value of point, as a marker object. */)
254 (void)
256 return build_marker (current_buffer, PT, PT_BYTE);
259 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
260 doc: /* Set point to POSITION, a number or marker.
261 Beginning of buffer is position (point-min), end is (point-max).
263 The return value is POSITION. */)
264 (register Lisp_Object position)
266 if (MARKERP (position))
267 set_point_from_marker (position);
268 else if (INTEGERP (position))
269 SET_PT (clip_to_bounds (BEGV, XINT (position), ZV));
270 else
271 wrong_type_argument (Qinteger_or_marker_p, position);
272 return position;
276 /* Return the start or end position of the region.
277 BEGINNINGP means return the start.
278 If there is no region active, signal an error. */
280 static Lisp_Object
281 region_limit (bool beginningp)
283 Lisp_Object m;
285 if (!NILP (Vtransient_mark_mode)
286 && NILP (Vmark_even_if_inactive)
287 && NILP (BVAR (current_buffer, mark_active)))
288 xsignal0 (Qmark_inactive);
290 m = Fmarker_position (BVAR (current_buffer, mark));
291 if (NILP (m))
292 error ("The mark is not set now, so there is no region");
294 /* Clip to the current narrowing (bug#11770). */
295 return make_number ((PT < XFASTINT (m)) == beginningp
296 ? PT
297 : clip_to_bounds (BEGV, XFASTINT (m), ZV));
300 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
301 doc: /* Return the integer value of point or mark, whichever is smaller. */)
302 (void)
304 return region_limit (1);
307 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
308 doc: /* Return the integer value of point or mark, whichever is larger. */)
309 (void)
311 return region_limit (0);
314 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
315 doc: /* Return this buffer's mark, as a marker object.
316 Watch out! Moving this marker changes the mark position.
317 If you set the marker not to point anywhere, the buffer will have no mark. */)
318 (void)
320 return BVAR (current_buffer, mark);
324 /* Find all the overlays in the current buffer that touch position POS.
325 Return the number found, and store them in a vector in VEC
326 of length LEN. */
328 static ptrdiff_t
329 overlays_around (EMACS_INT pos, Lisp_Object *vec, ptrdiff_t len)
331 Lisp_Object overlay, start, end;
332 struct Lisp_Overlay *tail;
333 ptrdiff_t startpos, endpos;
334 ptrdiff_t idx = 0;
336 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
338 XSETMISC (overlay, tail);
340 end = OVERLAY_END (overlay);
341 endpos = OVERLAY_POSITION (end);
342 if (endpos < pos)
343 break;
344 start = OVERLAY_START (overlay);
345 startpos = OVERLAY_POSITION (start);
346 if (startpos <= pos)
348 if (idx < len)
349 vec[idx] = overlay;
350 /* Keep counting overlays even if we can't return them all. */
351 idx++;
355 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
357 XSETMISC (overlay, tail);
359 start = OVERLAY_START (overlay);
360 startpos = OVERLAY_POSITION (start);
361 if (pos < startpos)
362 break;
363 end = OVERLAY_END (overlay);
364 endpos = OVERLAY_POSITION (end);
365 if (pos <= endpos)
367 if (idx < len)
368 vec[idx] = overlay;
369 idx++;
373 return idx;
376 DEFUN ("get-pos-property", Fget_pos_property, Sget_pos_property, 2, 3, 0,
377 doc: /* Return the value of POSITION's property PROP, in OBJECT.
378 Almost identical to `get-char-property' except for the following difference:
379 Whereas `get-char-property' returns the property of the char at (i.e. right
380 after) POSITION, this pays attention to properties's stickiness and overlays's
381 advancement settings, in order to find the property of POSITION itself,
382 i.e. the property that a char would inherit if it were inserted
383 at POSITION. */)
384 (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
386 CHECK_NUMBER_COERCE_MARKER (position);
388 if (NILP (object))
389 XSETBUFFER (object, current_buffer);
390 else if (WINDOWP (object))
391 object = XWINDOW (object)->contents;
393 if (!BUFFERP (object))
394 /* pos-property only makes sense in buffers right now, since strings
395 have no overlays and no notion of insertion for which stickiness
396 could be obeyed. */
397 return Fget_text_property (position, prop, object);
398 else
400 EMACS_INT posn = XINT (position);
401 ptrdiff_t noverlays;
402 Lisp_Object *overlay_vec, tem;
403 struct buffer *obuf = current_buffer;
404 USE_SAFE_ALLOCA;
406 set_buffer_temp (XBUFFER (object));
408 /* First try with room for 40 overlays. */
409 Lisp_Object overlay_vecbuf[40];
410 noverlays = ARRAYELTS (overlay_vecbuf);
411 overlay_vec = overlay_vecbuf;
412 noverlays = overlays_around (posn, overlay_vec, noverlays);
414 /* If there are more than 40,
415 make enough space for all, and try again. */
416 if (ARRAYELTS (overlay_vecbuf) < noverlays)
418 SAFE_ALLOCA_LISP (overlay_vec, noverlays);
419 noverlays = overlays_around (posn, overlay_vec, noverlays);
421 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
423 set_buffer_temp (obuf);
425 /* Now check the overlays in order of decreasing priority. */
426 while (--noverlays >= 0)
428 Lisp_Object ol = overlay_vec[noverlays];
429 tem = Foverlay_get (ol, prop);
430 if (!NILP (tem))
432 /* Check the overlay is indeed active at point. */
433 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
434 if ((OVERLAY_POSITION (start) == posn
435 && XMARKER (start)->insertion_type == 1)
436 || (OVERLAY_POSITION (finish) == posn
437 && XMARKER (finish)->insertion_type == 0))
438 ; /* The overlay will not cover a char inserted at point. */
439 else
441 SAFE_FREE ();
442 return tem;
446 SAFE_FREE ();
448 { /* Now check the text properties. */
449 int stickiness = text_property_stickiness (prop, position, object);
450 if (stickiness > 0)
451 return Fget_text_property (position, prop, object);
452 else if (stickiness < 0
453 && XINT (position) > BUF_BEGV (XBUFFER (object)))
454 return Fget_text_property (make_number (XINT (position) - 1),
455 prop, object);
456 else
457 return Qnil;
462 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
463 the value of point is used instead. If BEG or END is null,
464 means don't store the beginning or end of the field.
466 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
467 results; they do not effect boundary behavior.
469 If MERGE_AT_BOUNDARY is non-nil, then if POS is at the very first
470 position of a field, then the beginning of the previous field is
471 returned instead of the beginning of POS's field (since the end of a
472 field is actually also the beginning of the next input field, this
473 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
474 non-nil case, if two fields are separated by a field with the special
475 value `boundary', and POS lies within it, then the two separated
476 fields are considered to be adjacent, and POS between them, when
477 finding the beginning and ending of the "merged" field.
479 Either BEG or END may be 0, in which case the corresponding value
480 is not stored. */
482 static void
483 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
484 Lisp_Object beg_limit,
485 ptrdiff_t *beg, Lisp_Object end_limit, ptrdiff_t *end)
487 /* Fields right before and after the point. */
488 Lisp_Object before_field, after_field;
489 /* True if POS counts as the start of a field. */
490 bool at_field_start = 0;
491 /* True if POS counts as the end of a field. */
492 bool at_field_end = 0;
494 if (NILP (pos))
495 XSETFASTINT (pos, PT);
496 else
497 CHECK_NUMBER_COERCE_MARKER (pos);
499 after_field
500 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
501 before_field
502 = (XFASTINT (pos) > BEGV
503 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
504 Qfield, Qnil, NULL)
505 /* Using nil here would be a more obvious choice, but it would
506 fail when the buffer starts with a non-sticky field. */
507 : after_field);
509 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
510 and POS is at beginning of a field, which can also be interpreted
511 as the end of the previous field. Note that the case where if
512 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
513 more natural one; then we avoid treating the beginning of a field
514 specially. */
515 if (NILP (merge_at_boundary))
517 Lisp_Object field = Fget_pos_property (pos, Qfield, Qnil);
518 if (!EQ (field, after_field))
519 at_field_end = 1;
520 if (!EQ (field, before_field))
521 at_field_start = 1;
522 if (NILP (field) && at_field_start && at_field_end)
523 /* If an inserted char would have a nil field while the surrounding
524 text is non-nil, we're probably not looking at a
525 zero-length field, but instead at a non-nil field that's
526 not intended for editing (such as comint's prompts). */
527 at_field_end = at_field_start = 0;
530 /* Note about special `boundary' fields:
532 Consider the case where the point (`.') is between the fields `x' and `y':
534 xxxx.yyyy
536 In this situation, if merge_at_boundary is non-nil, consider the
537 `x' and `y' fields as forming one big merged field, and so the end
538 of the field is the end of `y'.
540 However, if `x' and `y' are separated by a special `boundary' field
541 (a field with a `field' char-property of 'boundary), then ignore
542 this special field when merging adjacent fields. Here's the same
543 situation, but with a `boundary' field between the `x' and `y' fields:
545 xxx.BBBByyyy
547 Here, if point is at the end of `x', the beginning of `y', or
548 anywhere in-between (within the `boundary' field), merge all
549 three fields and consider the beginning as being the beginning of
550 the `x' field, and the end as being the end of the `y' field. */
552 if (beg)
554 if (at_field_start)
555 /* POS is at the edge of a field, and we should consider it as
556 the beginning of the following field. */
557 *beg = XFASTINT (pos);
558 else
559 /* Find the previous field boundary. */
561 Lisp_Object p = pos;
562 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
563 /* Skip a `boundary' field. */
564 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
565 beg_limit);
567 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
568 beg_limit);
569 *beg = NILP (p) ? BEGV : XFASTINT (p);
573 if (end)
575 if (at_field_end)
576 /* POS is at the edge of a field, and we should consider it as
577 the end of the previous field. */
578 *end = XFASTINT (pos);
579 else
580 /* Find the next field boundary. */
582 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
583 /* Skip a `boundary' field. */
584 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
585 end_limit);
587 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
588 end_limit);
589 *end = NILP (pos) ? ZV : XFASTINT (pos);
595 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
596 doc: /* Delete the field surrounding POS.
597 A field is a region of text with the same `field' property.
598 If POS is nil, the value of point is used for POS. */)
599 (Lisp_Object pos)
601 ptrdiff_t beg, end;
602 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
603 if (beg != end)
604 del_range (beg, end);
605 return Qnil;
608 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
609 doc: /* Return the contents of the field surrounding POS as a string.
610 A field is a region of text with the same `field' property.
611 If POS is nil, the value of point is used for POS. */)
612 (Lisp_Object pos)
614 ptrdiff_t beg, end;
615 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
616 return make_buffer_string (beg, end, 1);
619 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
620 doc: /* Return the contents of the field around POS, without text properties.
621 A field is a region of text with the same `field' property.
622 If POS is nil, the value of point is used for POS. */)
623 (Lisp_Object pos)
625 ptrdiff_t beg, end;
626 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
627 return make_buffer_string (beg, end, 0);
630 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
631 doc: /* Return the beginning of the field surrounding POS.
632 A field is a region of text with the same `field' property.
633 If POS is nil, the value of point is used for POS.
634 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
635 field, then the beginning of the *previous* field is returned.
636 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
637 is before LIMIT, then LIMIT will be returned instead. */)
638 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
640 ptrdiff_t beg;
641 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
642 return make_number (beg);
645 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
646 doc: /* Return the end of the field surrounding POS.
647 A field is a region of text with the same `field' property.
648 If POS is nil, the value of point is used for POS.
649 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
650 then the end of the *following* field is returned.
651 If LIMIT is non-nil, it is a buffer position; if the end of the field
652 is after LIMIT, then LIMIT will be returned instead. */)
653 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
655 ptrdiff_t end;
656 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
657 return make_number (end);
660 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
661 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
662 A field is a region of text with the same `field' property.
664 If NEW-POS is nil, then use the current point instead, and move point
665 to the resulting constrained position, in addition to returning that
666 position.
668 If OLD-POS is at the boundary of two fields, then the allowable
669 positions for NEW-POS depends on the value of the optional argument
670 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
671 constrained to the field that has the same `field' char-property
672 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
673 is non-nil, NEW-POS is constrained to the union of the two adjacent
674 fields. Additionally, if two fields are separated by another field with
675 the special value `boundary', then any point within this special field is
676 also considered to be `on the boundary'.
678 If the optional argument ONLY-IN-LINE is non-nil and constraining
679 NEW-POS would move it to a different line, NEW-POS is returned
680 unconstrained. This is useful for commands that move by line, like
681 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
682 only in the case where they can still move to the right line.
684 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
685 a non-nil property of that name, then any field boundaries are ignored.
687 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
688 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge,
689 Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
691 /* If non-zero, then the original point, before re-positioning. */
692 ptrdiff_t orig_point = 0;
693 bool fwd;
694 Lisp_Object prev_old, prev_new;
696 if (NILP (new_pos))
697 /* Use the current point, and afterwards, set it. */
699 orig_point = PT;
700 XSETFASTINT (new_pos, PT);
703 CHECK_NUMBER_COERCE_MARKER (new_pos);
704 CHECK_NUMBER_COERCE_MARKER (old_pos);
706 fwd = (XINT (new_pos) > XINT (old_pos));
708 prev_old = make_number (XINT (old_pos) - 1);
709 prev_new = make_number (XINT (new_pos) - 1);
711 if (NILP (Vinhibit_field_text_motion)
712 && !EQ (new_pos, old_pos)
713 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
714 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
715 /* To recognize field boundaries, we must also look at the
716 previous positions; we could use `Fget_pos_property'
717 instead, but in itself that would fail inside non-sticky
718 fields (like comint prompts). */
719 || (XFASTINT (new_pos) > BEGV
720 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
721 || (XFASTINT (old_pos) > BEGV
722 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
723 && (NILP (inhibit_capture_property)
724 /* Field boundaries are again a problem; but now we must
725 decide the case exactly, so we need to call
726 `get_pos_property' as well. */
727 || (NILP (Fget_pos_property (old_pos, inhibit_capture_property, Qnil))
728 && (XFASTINT (old_pos) <= BEGV
729 || NILP (Fget_char_property
730 (old_pos, inhibit_capture_property, Qnil))
731 || NILP (Fget_char_property
732 (prev_old, inhibit_capture_property, Qnil))))))
733 /* It is possible that NEW_POS is not within the same field as
734 OLD_POS; try to move NEW_POS so that it is. */
736 ptrdiff_t shortage;
737 Lisp_Object field_bound;
739 if (fwd)
740 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
741 else
742 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
744 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
745 other side of NEW_POS, which would mean that NEW_POS is
746 already acceptable, and it's not necessary to constrain it
747 to FIELD_BOUND. */
748 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
749 /* NEW_POS should be constrained, but only if either
750 ONLY_IN_LINE is nil (in which case any constraint is OK),
751 or NEW_POS and FIELD_BOUND are on the same line (in which
752 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
753 && (NILP (only_in_line)
754 /* This is the ONLY_IN_LINE case, check that NEW_POS and
755 FIELD_BOUND are on the same line by seeing whether
756 there's an intervening newline or not. */
757 || (find_newline (XFASTINT (new_pos), -1,
758 XFASTINT (field_bound), -1,
759 fwd ? -1 : 1, &shortage, NULL, 1),
760 shortage != 0)))
761 /* Constrain NEW_POS to FIELD_BOUND. */
762 new_pos = field_bound;
764 if (orig_point && XFASTINT (new_pos) != orig_point)
765 /* The NEW_POS argument was originally nil, so automatically set PT. */
766 SET_PT (XFASTINT (new_pos));
769 return new_pos;
773 DEFUN ("line-beginning-position",
774 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
775 doc: /* Return the character position of the first character on the current line.
776 With optional argument N, scan forward N - 1 lines first.
777 If the scan reaches the end of the buffer, return that position.
779 This function ignores text display directionality; it returns the
780 position of the first character in logical order, i.e. the smallest
781 character position on the line.
783 This function constrains the returned position to the current field
784 unless that position would be on a different line than the original,
785 unconstrained result. If N is nil or 1, and a front-sticky field
786 starts at point, the scan stops as soon as it starts. To ignore field
787 boundaries, bind `inhibit-field-text-motion' to t.
789 This function does not move point. */)
790 (Lisp_Object n)
792 ptrdiff_t charpos, bytepos;
794 if (NILP (n))
795 XSETFASTINT (n, 1);
796 else
797 CHECK_NUMBER (n);
799 scan_newline_from_point (XINT (n) - 1, &charpos, &bytepos);
801 /* Return END constrained to the current input field. */
802 return Fconstrain_to_field (make_number (charpos), make_number (PT),
803 XINT (n) != 1 ? Qt : Qnil,
804 Qt, Qnil);
807 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
808 doc: /* Return the character position of the last character on the current line.
809 With argument N not nil or 1, move forward N - 1 lines first.
810 If scan reaches end of buffer, return that position.
812 This function ignores text display directionality; it returns the
813 position of the last character in logical order, i.e. the largest
814 character position on the line.
816 This function constrains the returned position to the current field
817 unless that would be on a different line than the original,
818 unconstrained result. If N is nil or 1, and a rear-sticky field ends
819 at point, the scan stops as soon as it starts. To ignore field
820 boundaries bind `inhibit-field-text-motion' to t.
822 This function does not move point. */)
823 (Lisp_Object n)
825 ptrdiff_t clipped_n;
826 ptrdiff_t end_pos;
827 ptrdiff_t orig = PT;
829 if (NILP (n))
830 XSETFASTINT (n, 1);
831 else
832 CHECK_NUMBER (n);
834 clipped_n = clip_to_bounds (PTRDIFF_MIN + 1, XINT (n), PTRDIFF_MAX);
835 end_pos = find_before_next_newline (orig, 0, clipped_n - (clipped_n <= 0),
836 NULL);
838 /* Return END_POS constrained to the current input field. */
839 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
840 Qnil, Qt, Qnil);
843 /* Save current buffer state for `save-excursion' special form.
844 We (ab)use Lisp_Misc_Save_Value to allow explicit free and so
845 offload some work from GC. */
847 Lisp_Object
848 save_excursion_save (void)
850 return make_save_obj_obj_obj_obj
851 (Fpoint_marker (),
852 Qnil,
853 /* Selected window if current buffer is shown in it, nil otherwise. */
854 (EQ (XWINDOW (selected_window)->contents, Fcurrent_buffer ())
855 ? selected_window : Qnil),
856 Qnil);
859 /* Restore saved buffer before leaving `save-excursion' special form. */
861 void
862 save_excursion_restore (Lisp_Object info)
864 Lisp_Object tem, tem1;
865 struct gcpro gcpro1;
867 tem = Fmarker_buffer (XSAVE_OBJECT (info, 0));
868 /* If we're unwinding to top level, saved buffer may be deleted. This
869 means that all of its markers are unchained and so tem is nil. */
870 if (NILP (tem))
871 goto out;
873 GCPRO1 (info);
875 Fset_buffer (tem);
877 /* Point marker. */
878 tem = XSAVE_OBJECT (info, 0);
879 Fgoto_char (tem);
880 unchain_marker (XMARKER (tem));
882 /* If buffer was visible in a window, and a different window was
883 selected, and the old selected window is still showing this
884 buffer, restore point in that window. */
885 tem = XSAVE_OBJECT (info, 2);
886 if (WINDOWP (tem)
887 && !EQ (tem, selected_window)
888 && (tem1 = XWINDOW (tem)->contents,
889 (/* Window is live... */
890 BUFFERP (tem1)
891 /* ...and it shows the current buffer. */
892 && XBUFFER (tem1) == current_buffer)))
893 Fset_window_point (tem, make_number (PT));
895 UNGCPRO;
897 out:
899 free_misc (info);
902 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
903 doc: /* Save point, and current buffer; execute BODY; restore those things.
904 Executes BODY just like `progn'.
905 The values of point and the current buffer are restored
906 even in case of abnormal exit (throw or error).
908 If you only want to save the current buffer but not point,
909 then just use `save-current-buffer', or even `with-current-buffer'.
911 Before Emacs 25.1, `save-excursion' used to save the mark state.
912 To save the marker state as well as the point and buffer, use
913 `save-mark-and-excursion'.
915 usage: (save-excursion &rest BODY) */)
916 (Lisp_Object args)
918 register Lisp_Object val;
919 ptrdiff_t count = SPECPDL_INDEX ();
921 record_unwind_protect (save_excursion_restore, save_excursion_save ());
923 val = Fprogn (args);
924 return unbind_to (count, val);
927 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
928 doc: /* Record which buffer is current; execute BODY; make that buffer current.
929 BODY is executed just like `progn'.
930 usage: (save-current-buffer &rest BODY) */)
931 (Lisp_Object args)
933 ptrdiff_t count = SPECPDL_INDEX ();
935 record_unwind_current_buffer ();
936 return unbind_to (count, Fprogn (args));
939 DEFUN ("buffer-size", Fbuffer_size, Sbuffer_size, 0, 1, 0,
940 doc: /* Return the number of characters in the current buffer.
941 If BUFFER, return the number of characters in that buffer instead. */)
942 (Lisp_Object buffer)
944 if (NILP (buffer))
945 return make_number (Z - BEG);
946 else
948 CHECK_BUFFER (buffer);
949 return make_number (BUF_Z (XBUFFER (buffer))
950 - BUF_BEG (XBUFFER (buffer)));
954 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
955 doc: /* Return the minimum permissible value of point in the current buffer.
956 This is 1, unless narrowing (a buffer restriction) is in effect. */)
957 (void)
959 Lisp_Object temp;
960 XSETFASTINT (temp, BEGV);
961 return temp;
964 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
965 doc: /* Return a marker to the minimum permissible value of point in this buffer.
966 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
967 (void)
969 return build_marker (current_buffer, BEGV, BEGV_BYTE);
972 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
973 doc: /* Return the maximum permissible value of point in the current buffer.
974 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
975 is in effect, in which case it is less. */)
976 (void)
978 Lisp_Object temp;
979 XSETFASTINT (temp, ZV);
980 return temp;
983 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
984 doc: /* Return a marker to the maximum permissible value of point in this buffer.
985 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
986 is in effect, in which case it is less. */)
987 (void)
989 return build_marker (current_buffer, ZV, ZV_BYTE);
992 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
993 doc: /* Return the position of the gap, in the current buffer.
994 See also `gap-size'. */)
995 (void)
997 Lisp_Object temp;
998 XSETFASTINT (temp, GPT);
999 return temp;
1002 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1003 doc: /* Return the size of the current buffer's gap.
1004 See also `gap-position'. */)
1005 (void)
1007 Lisp_Object temp;
1008 XSETFASTINT (temp, GAP_SIZE);
1009 return temp;
1012 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1013 doc: /* Return the byte position for character position POSITION.
1014 If POSITION is out of range, the value is nil. */)
1015 (Lisp_Object position)
1017 CHECK_NUMBER_COERCE_MARKER (position);
1018 if (XINT (position) < BEG || XINT (position) > Z)
1019 return Qnil;
1020 return make_number (CHAR_TO_BYTE (XINT (position)));
1023 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1024 doc: /* Return the character position for byte position BYTEPOS.
1025 If BYTEPOS is out of range, the value is nil. */)
1026 (Lisp_Object bytepos)
1028 ptrdiff_t pos_byte;
1030 CHECK_NUMBER (bytepos);
1031 pos_byte = XINT (bytepos);
1032 if (pos_byte < BEG_BYTE || pos_byte > Z_BYTE)
1033 return Qnil;
1034 if (Z != Z_BYTE)
1035 /* There are multibyte characters in the buffer.
1036 The argument of BYTE_TO_CHAR must be a byte position at
1037 a character boundary, so search for the start of the current
1038 character. */
1039 while (!CHAR_HEAD_P (FETCH_BYTE (pos_byte)))
1040 pos_byte--;
1041 return make_number (BYTE_TO_CHAR (pos_byte));
1044 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1045 doc: /* Return the character following point, as a number.
1046 At the end of the buffer or accessible region, return 0. */)
1047 (void)
1049 Lisp_Object temp;
1050 if (PT >= ZV)
1051 XSETFASTINT (temp, 0);
1052 else
1053 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1054 return temp;
1057 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1058 doc: /* Return the character preceding point, as a number.
1059 At the beginning of the buffer or accessible region, return 0. */)
1060 (void)
1062 Lisp_Object temp;
1063 if (PT <= BEGV)
1064 XSETFASTINT (temp, 0);
1065 else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1067 ptrdiff_t pos = PT_BYTE;
1068 DEC_POS (pos);
1069 XSETFASTINT (temp, FETCH_CHAR (pos));
1071 else
1072 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1073 return temp;
1076 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1077 doc: /* Return t if point is at the beginning of the buffer.
1078 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1079 (void)
1081 if (PT == BEGV)
1082 return Qt;
1083 return Qnil;
1086 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1087 doc: /* Return t if point is at the end of the buffer.
1088 If the buffer is narrowed, this means the end of the narrowed part. */)
1089 (void)
1091 if (PT == ZV)
1092 return Qt;
1093 return Qnil;
1096 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1097 doc: /* Return t if point is at the beginning of a line. */)
1098 (void)
1100 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1101 return Qt;
1102 return Qnil;
1105 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1106 doc: /* Return t if point is at the end of a line.
1107 `End of a line' includes point being at the end of the buffer. */)
1108 (void)
1110 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1111 return Qt;
1112 return Qnil;
1115 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1116 doc: /* Return character in current buffer at position POS.
1117 POS is an integer or a marker and defaults to point.
1118 If POS is out of range, the value is nil. */)
1119 (Lisp_Object pos)
1121 register ptrdiff_t pos_byte;
1123 if (NILP (pos))
1125 pos_byte = PT_BYTE;
1126 XSETFASTINT (pos, PT);
1129 if (MARKERP (pos))
1131 pos_byte = marker_byte_position (pos);
1132 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1133 return Qnil;
1135 else
1137 CHECK_NUMBER_COERCE_MARKER (pos);
1138 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1139 return Qnil;
1141 pos_byte = CHAR_TO_BYTE (XINT (pos));
1144 return make_number (FETCH_CHAR (pos_byte));
1147 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1148 doc: /* Return character in current buffer preceding position POS.
1149 POS is an integer or a marker and defaults to point.
1150 If POS is out of range, the value is nil. */)
1151 (Lisp_Object pos)
1153 register Lisp_Object val;
1154 register ptrdiff_t pos_byte;
1156 if (NILP (pos))
1158 pos_byte = PT_BYTE;
1159 XSETFASTINT (pos, PT);
1162 if (MARKERP (pos))
1164 pos_byte = marker_byte_position (pos);
1166 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1167 return Qnil;
1169 else
1171 CHECK_NUMBER_COERCE_MARKER (pos);
1173 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1174 return Qnil;
1176 pos_byte = CHAR_TO_BYTE (XINT (pos));
1179 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1181 DEC_POS (pos_byte);
1182 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1184 else
1186 pos_byte--;
1187 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1189 return val;
1192 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1193 doc: /* Return the name under which the user logged in, as a string.
1194 This is based on the effective uid, not the real uid.
1195 Also, if the environment variables LOGNAME or USER are set,
1196 that determines the value of this function.
1198 If optional argument UID is an integer or a float, return the login name
1199 of the user with that uid, or nil if there is no such user. */)
1200 (Lisp_Object uid)
1202 struct passwd *pw;
1203 uid_t id;
1205 /* Set up the user name info if we didn't do it before.
1206 (That can happen if Emacs is dumpable
1207 but you decide to run `temacs -l loadup' and not dump. */
1208 if (NILP (Vuser_login_name))
1209 init_editfns ();
1211 if (NILP (uid))
1212 return Vuser_login_name;
1214 CONS_TO_INTEGER (uid, uid_t, id);
1215 block_input ();
1216 pw = getpwuid (id);
1217 unblock_input ();
1218 return (pw ? build_string (pw->pw_name) : Qnil);
1221 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1222 0, 0, 0,
1223 doc: /* Return the name of the user's real uid, as a string.
1224 This ignores the environment variables LOGNAME and USER, so it differs from
1225 `user-login-name' when running under `su'. */)
1226 (void)
1228 /* Set up the user name info if we didn't do it before.
1229 (That can happen if Emacs is dumpable
1230 but you decide to run `temacs -l loadup' and not dump. */
1231 if (NILP (Vuser_login_name))
1232 init_editfns ();
1233 return Vuser_real_login_name;
1236 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1237 doc: /* Return the effective uid of Emacs.
1238 Value is an integer or a float, depending on the value. */)
1239 (void)
1241 uid_t euid = geteuid ();
1242 return make_fixnum_or_float (euid);
1245 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1246 doc: /* Return the real uid of Emacs.
1247 Value is an integer or a float, depending on the value. */)
1248 (void)
1250 uid_t uid = getuid ();
1251 return make_fixnum_or_float (uid);
1254 DEFUN ("group-gid", Fgroup_gid, Sgroup_gid, 0, 0, 0,
1255 doc: /* Return the effective gid of Emacs.
1256 Value is an integer or a float, depending on the value. */)
1257 (void)
1259 gid_t egid = getegid ();
1260 return make_fixnum_or_float (egid);
1263 DEFUN ("group-real-gid", Fgroup_real_gid, Sgroup_real_gid, 0, 0, 0,
1264 doc: /* Return the real gid of Emacs.
1265 Value is an integer or a float, depending on the value. */)
1266 (void)
1268 gid_t gid = getgid ();
1269 return make_fixnum_or_float (gid);
1272 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1273 doc: /* Return the full name of the user logged in, as a string.
1274 If the full name corresponding to Emacs's userid is not known,
1275 return "unknown".
1277 If optional argument UID is an integer or float, return the full name
1278 of the user with that uid, or nil if there is no such user.
1279 If UID is a string, return the full name of the user with that login
1280 name, or nil if there is no such user. */)
1281 (Lisp_Object uid)
1283 struct passwd *pw;
1284 register char *p, *q;
1285 Lisp_Object full;
1287 if (NILP (uid))
1288 return Vuser_full_name;
1289 else if (NUMBERP (uid))
1291 uid_t u;
1292 CONS_TO_INTEGER (uid, uid_t, u);
1293 block_input ();
1294 pw = getpwuid (u);
1295 unblock_input ();
1297 else if (STRINGP (uid))
1299 block_input ();
1300 pw = getpwnam (SSDATA (uid));
1301 unblock_input ();
1303 else
1304 error ("Invalid UID specification");
1306 if (!pw)
1307 return Qnil;
1309 p = USER_FULL_NAME;
1310 /* Chop off everything after the first comma. */
1311 q = strchr (p, ',');
1312 full = make_string (p, q ? q - p : strlen (p));
1314 #ifdef AMPERSAND_FULL_NAME
1315 p = SSDATA (full);
1316 q = strchr (p, '&');
1317 /* Substitute the login name for the &, upcasing the first character. */
1318 if (q)
1320 Lisp_Object login = Fuser_login_name (make_number (pw->pw_uid));
1321 USE_SAFE_ALLOCA;
1322 char *r = SAFE_ALLOCA (strlen (p) + SBYTES (login) + 1);
1323 memcpy (r, p, q - p);
1324 char *s = lispstpcpy (&r[q - p], login);
1325 r[q - p] = upcase ((unsigned char) r[q - p]);
1326 strcpy (s, q + 1);
1327 full = build_string (r);
1328 SAFE_FREE ();
1330 #endif /* AMPERSAND_FULL_NAME */
1332 return full;
1335 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1336 doc: /* Return the host name of the machine you are running on, as a string. */)
1337 (void)
1339 if (EQ (Vsystem_name, cached_system_name))
1340 init_and_cache_system_name ();
1341 return Vsystem_name;
1344 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1345 doc: /* Return the process ID of Emacs, as a number. */)
1346 (void)
1348 pid_t pid = getpid ();
1349 return make_fixnum_or_float (pid);
1354 #ifndef TIME_T_MIN
1355 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1356 #endif
1357 #ifndef TIME_T_MAX
1358 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1359 #endif
1361 /* Report that a time value is out of range for Emacs. */
1362 void
1363 time_overflow (void)
1365 error ("Specified time is not representable");
1368 static void
1369 invalid_time (void)
1371 error ("Invalid time specification");
1374 /* Check a return value compatible with that of decode_time_components. */
1375 static void
1376 check_time_validity (int validity)
1378 if (validity <= 0)
1380 if (validity < 0)
1381 time_overflow ();
1382 else
1383 invalid_time ();
1387 /* A substitute for mktime_z on platforms that lack it. It's not
1388 thread-safe, but should be good enough for Emacs in typical use. */
1389 #ifndef HAVE_TZALLOC
1390 static time_t
1391 mktime_z (timezone_t tz, struct tm *tm)
1393 char *oldtz = getenv ("TZ");
1394 USE_SAFE_ALLOCA;
1395 if (oldtz)
1397 size_t oldtzsize = strlen (oldtz) + 1;
1398 char *oldtzcopy = SAFE_ALLOCA (oldtzsize);
1399 oldtz = strcpy (oldtzcopy, oldtz);
1401 block_input ();
1402 set_time_zone_rule (tz);
1403 time_t t = mktime (tm);
1404 set_time_zone_rule (oldtz);
1405 unblock_input ();
1406 SAFE_FREE ();
1407 return t;
1409 #endif
1411 /* Return the upper part of the time T (everything but the bottom 16 bits). */
1412 static EMACS_INT
1413 hi_time (time_t t)
1415 time_t hi = t >> LO_TIME_BITS;
1417 /* Check for overflow, helping the compiler for common cases where
1418 no runtime check is needed, and taking care not to convert
1419 negative numbers to unsigned before comparing them. */
1420 if (! ((! TYPE_SIGNED (time_t)
1421 || MOST_NEGATIVE_FIXNUM <= TIME_T_MIN >> LO_TIME_BITS
1422 || MOST_NEGATIVE_FIXNUM <= hi)
1423 && (TIME_T_MAX >> LO_TIME_BITS <= MOST_POSITIVE_FIXNUM
1424 || hi <= MOST_POSITIVE_FIXNUM)))
1425 time_overflow ();
1427 return hi;
1430 /* Return the bottom bits of the time T. */
1431 static int
1432 lo_time (time_t t)
1434 return t & ((1 << LO_TIME_BITS) - 1);
1437 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1438 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1439 The time is returned as a list of integers (HIGH LOW USEC PSEC).
1440 HIGH has the most significant bits of the seconds, while LOW has the
1441 least significant 16 bits. USEC and PSEC are the microsecond and
1442 picosecond counts. */)
1443 (void)
1445 return make_lisp_time (current_timespec ());
1448 static struct lisp_time
1449 time_add (struct lisp_time ta, struct lisp_time tb)
1451 EMACS_INT hi = ta.hi + tb.hi;
1452 int lo = ta.lo + tb.lo;
1453 int us = ta.us + tb.us;
1454 int ps = ta.ps + tb.ps;
1455 us += (1000000 <= ps);
1456 ps -= (1000000 <= ps) * 1000000;
1457 lo += (1000000 <= us);
1458 us -= (1000000 <= us) * 1000000;
1459 hi += (1 << LO_TIME_BITS <= lo);
1460 lo -= (1 << LO_TIME_BITS <= lo) << LO_TIME_BITS;
1461 return (struct lisp_time) { hi, lo, us, ps };
1464 static struct lisp_time
1465 time_subtract (struct lisp_time ta, struct lisp_time tb)
1467 EMACS_INT hi = ta.hi - tb.hi;
1468 int lo = ta.lo - tb.lo;
1469 int us = ta.us - tb.us;
1470 int ps = ta.ps - tb.ps;
1471 us -= (ps < 0);
1472 ps += (ps < 0) * 1000000;
1473 lo -= (us < 0);
1474 us += (us < 0) * 1000000;
1475 hi -= (lo < 0);
1476 lo += (lo < 0) << LO_TIME_BITS;
1477 return (struct lisp_time) { hi, lo, us, ps };
1480 static Lisp_Object
1481 time_arith (Lisp_Object a, Lisp_Object b,
1482 struct lisp_time (*op) (struct lisp_time, struct lisp_time))
1484 int alen, blen;
1485 struct lisp_time ta = lisp_time_struct (a, &alen);
1486 struct lisp_time tb = lisp_time_struct (b, &blen);
1487 struct lisp_time t = op (ta, tb);
1488 if (! (MOST_NEGATIVE_FIXNUM <= t.hi && t.hi <= MOST_POSITIVE_FIXNUM))
1489 time_overflow ();
1490 Lisp_Object val = Qnil;
1492 switch (max (alen, blen))
1494 default:
1495 val = Fcons (make_number (t.ps), val);
1496 /* Fall through. */
1497 case 3:
1498 val = Fcons (make_number (t.us), val);
1499 /* Fall through. */
1500 case 2:
1501 val = Fcons (make_number (t.lo), val);
1502 val = Fcons (make_number (t.hi), val);
1503 break;
1506 return val;
1509 DEFUN ("time-add", Ftime_add, Stime_add, 2, 2, 0,
1510 doc: /* Return the sum of two time values A and B, as a time value. */)
1511 (Lisp_Object a, Lisp_Object b)
1513 return time_arith (a, b, time_add);
1516 DEFUN ("time-subtract", Ftime_subtract, Stime_subtract, 2, 2, 0,
1517 doc: /* Return the difference between two time values A and B, as a time value. */)
1518 (Lisp_Object a, Lisp_Object b)
1520 return time_arith (a, b, time_subtract);
1523 DEFUN ("time-less-p", Ftime_less_p, Stime_less_p, 2, 2, 0,
1524 doc: /* Return non-nil if time value T1 is earlier than time value T2. */)
1525 (Lisp_Object t1, Lisp_Object t2)
1527 int t1len, t2len;
1528 struct lisp_time a = lisp_time_struct (t1, &t1len);
1529 struct lisp_time b = lisp_time_struct (t2, &t2len);
1530 return ((a.hi != b.hi ? a.hi < b.hi
1531 : a.lo != b.lo ? a.lo < b.lo
1532 : a.us != b.us ? a.us < b.us
1533 : a.ps < b.ps)
1534 ? Qt : Qnil);
1538 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1539 0, 0, 0,
1540 doc: /* Return the current run time used by Emacs.
1541 The time is returned as a list (HIGH LOW USEC PSEC), using the same
1542 style as (current-time).
1544 On systems that can't determine the run time, `get-internal-run-time'
1545 does the same thing as `current-time'. */)
1546 (void)
1548 #ifdef HAVE_GETRUSAGE
1549 struct rusage usage;
1550 time_t secs;
1551 int usecs;
1553 if (getrusage (RUSAGE_SELF, &usage) < 0)
1554 /* This shouldn't happen. What action is appropriate? */
1555 xsignal0 (Qerror);
1557 /* Sum up user time and system time. */
1558 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1559 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1560 if (usecs >= 1000000)
1562 usecs -= 1000000;
1563 secs++;
1565 return make_lisp_time (make_timespec (secs, usecs * 1000));
1566 #else /* ! HAVE_GETRUSAGE */
1567 #ifdef WINDOWSNT
1568 return w32_get_internal_run_time ();
1569 #else /* ! WINDOWSNT */
1570 return Fcurrent_time ();
1571 #endif /* WINDOWSNT */
1572 #endif /* HAVE_GETRUSAGE */
1576 /* Make a Lisp list that represents the Emacs time T. T may be an
1577 invalid time, with a slightly negative tv_nsec value such as
1578 UNKNOWN_MODTIME_NSECS; in that case, the Lisp list contains a
1579 correspondingly negative picosecond count. */
1580 Lisp_Object
1581 make_lisp_time (struct timespec t)
1583 time_t s = t.tv_sec;
1584 int ns = t.tv_nsec;
1585 return list4i (hi_time (s), lo_time (s), ns / 1000, ns % 1000 * 1000);
1588 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1589 Set *PHIGH, *PLOW, *PUSEC, *PPSEC to its parts; do not check their values.
1590 Return 2, 3, or 4 to indicate the effective length of SPECIFIED_TIME
1591 if successful, 0 if unsuccessful. */
1592 static int
1593 disassemble_lisp_time (Lisp_Object specified_time, Lisp_Object *phigh,
1594 Lisp_Object *plow, Lisp_Object *pusec,
1595 Lisp_Object *ppsec)
1597 Lisp_Object high = make_number (0);
1598 Lisp_Object low = specified_time;
1599 Lisp_Object usec = make_number (0);
1600 Lisp_Object psec = make_number (0);
1601 int len = 4;
1603 if (CONSP (specified_time))
1605 high = XCAR (specified_time);
1606 low = XCDR (specified_time);
1607 if (CONSP (low))
1609 Lisp_Object low_tail = XCDR (low);
1610 low = XCAR (low);
1611 if (CONSP (low_tail))
1613 usec = XCAR (low_tail);
1614 low_tail = XCDR (low_tail);
1615 if (CONSP (low_tail))
1616 psec = XCAR (low_tail);
1617 else
1618 len = 3;
1620 else if (!NILP (low_tail))
1622 usec = low_tail;
1623 len = 3;
1625 else
1626 len = 2;
1628 else
1629 len = 2;
1631 /* When combining components, require LOW to be an integer,
1632 as otherwise it would be a pain to add up times. */
1633 if (! INTEGERP (low))
1634 return 0;
1636 else if (INTEGERP (specified_time))
1637 len = 2;
1639 *phigh = high;
1640 *plow = low;
1641 *pusec = usec;
1642 *ppsec = psec;
1643 return len;
1646 /* Convert T into an Emacs time *RESULT, truncating toward minus infinity.
1647 Return true if T is in range, false otherwise. */
1648 static bool
1649 decode_float_time (double t, struct lisp_time *result)
1651 double lo_multiplier = 1 << LO_TIME_BITS;
1652 double emacs_time_min = MOST_NEGATIVE_FIXNUM * lo_multiplier;
1653 if (! (emacs_time_min <= t && t < -emacs_time_min))
1654 return false;
1656 double small_t = t / lo_multiplier;
1657 EMACS_INT hi = small_t;
1658 double t_sans_hi = t - hi * lo_multiplier;
1659 int lo = t_sans_hi;
1660 long double fracps = (t_sans_hi - lo) * 1e12L;
1661 #ifdef INT_FAST64_MAX
1662 int_fast64_t ifracps = fracps;
1663 int us = ifracps / 1000000;
1664 int ps = ifracps % 1000000;
1665 #else
1666 int us = fracps / 1e6L;
1667 int ps = fracps - us * 1e6L;
1668 #endif
1669 us -= (ps < 0);
1670 ps += (ps < 0) * 1000000;
1671 lo -= (us < 0);
1672 us += (us < 0) * 1000000;
1673 hi -= (lo < 0);
1674 lo += (lo < 0) << LO_TIME_BITS;
1675 result->hi = hi;
1676 result->lo = lo;
1677 result->us = us;
1678 result->ps = ps;
1679 return true;
1682 /* From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
1683 list, generate the corresponding time value.
1684 If LOW is floating point, the other components should be zero.
1686 If RESULT is not null, store into *RESULT the converted time.
1687 If *DRESULT is not null, store into *DRESULT the number of
1688 seconds since the start of the POSIX Epoch.
1690 Return 1 if successful, 0 if the components are of the
1691 wrong type, and -1 if the time is out of range. */
1693 decode_time_components (Lisp_Object high, Lisp_Object low, Lisp_Object usec,
1694 Lisp_Object psec,
1695 struct lisp_time *result, double *dresult)
1697 EMACS_INT hi, lo, us, ps;
1698 if (! (INTEGERP (high)
1699 && INTEGERP (usec) && INTEGERP (psec)))
1700 return 0;
1701 if (! INTEGERP (low))
1703 if (FLOATP (low))
1705 double t = XFLOAT_DATA (low);
1706 if (result && ! decode_float_time (t, result))
1707 return -1;
1708 if (dresult)
1709 *dresult = t;
1710 return 1;
1712 else if (NILP (low))
1714 struct timespec now = current_timespec ();
1715 if (result)
1717 result->hi = hi_time (now.tv_sec);
1718 result->lo = lo_time (now.tv_sec);
1719 result->us = now.tv_nsec / 1000;
1720 result->ps = now.tv_nsec % 1000 * 1000;
1722 if (dresult)
1723 *dresult = now.tv_sec + now.tv_nsec / 1e9;
1724 return 1;
1726 else
1727 return 0;
1730 hi = XINT (high);
1731 lo = XINT (low);
1732 us = XINT (usec);
1733 ps = XINT (psec);
1735 /* Normalize out-of-range lower-order components by carrying
1736 each overflow into the next higher-order component. */
1737 us += ps / 1000000 - (ps % 1000000 < 0);
1738 lo += us / 1000000 - (us % 1000000 < 0);
1739 hi += lo >> LO_TIME_BITS;
1740 ps = ps % 1000000 + 1000000 * (ps % 1000000 < 0);
1741 us = us % 1000000 + 1000000 * (us % 1000000 < 0);
1742 lo &= (1 << LO_TIME_BITS) - 1;
1744 if (result)
1746 if (! (MOST_NEGATIVE_FIXNUM <= hi && hi <= MOST_POSITIVE_FIXNUM))
1747 return -1;
1748 result->hi = hi;
1749 result->lo = lo;
1750 result->us = us;
1751 result->ps = ps;
1754 if (dresult)
1756 double dhi = hi;
1757 *dresult = (us * 1e6 + ps) / 1e12 + lo + dhi * (1 << LO_TIME_BITS);
1760 return 1;
1763 struct timespec
1764 lisp_to_timespec (struct lisp_time t)
1766 if (! ((TYPE_SIGNED (time_t) ? TIME_T_MIN >> LO_TIME_BITS <= t.hi : 0 <= t.hi)
1767 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1768 return invalid_timespec ();
1769 time_t s = (t.hi << LO_TIME_BITS) + t.lo;
1770 int ns = t.us * 1000 + t.ps / 1000;
1771 return make_timespec (s, ns);
1774 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1775 Store its effective length into *PLEN.
1776 If SPECIFIED_TIME is nil, use the current time.
1777 Signal an error if SPECIFIED_TIME does not represent a time. */
1778 static struct lisp_time
1779 lisp_time_struct (Lisp_Object specified_time, int *plen)
1781 Lisp_Object high, low, usec, psec;
1782 struct lisp_time t;
1783 int len = disassemble_lisp_time (specified_time, &high, &low, &usec, &psec);
1784 int val = len ? decode_time_components (high, low, usec, psec, &t, 0) : 0;
1785 check_time_validity (val);
1786 *plen = len;
1787 return t;
1790 /* Like lisp_time_struct, except return a struct timespec.
1791 Discard any low-order digits. */
1792 struct timespec
1793 lisp_time_argument (Lisp_Object specified_time)
1795 int len;
1796 struct lisp_time lt = lisp_time_struct (specified_time, &len);
1797 struct timespec t = lisp_to_timespec (lt);
1798 if (! timespec_valid_p (t))
1799 time_overflow ();
1800 return t;
1803 /* Like lisp_time_argument, except decode only the seconds part,
1804 and do not check the subseconds part. */
1805 static time_t
1806 lisp_seconds_argument (Lisp_Object specified_time)
1808 Lisp_Object high, low, usec, psec;
1809 struct lisp_time t;
1811 int val = disassemble_lisp_time (specified_time, &high, &low, &usec, &psec);
1812 if (val != 0)
1814 val = decode_time_components (high, low, make_number (0),
1815 make_number (0), &t, 0);
1816 if (0 < val
1817 && ! ((TYPE_SIGNED (time_t)
1818 ? TIME_T_MIN >> LO_TIME_BITS <= t.hi
1819 : 0 <= t.hi)
1820 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1821 val = -1;
1823 check_time_validity (val);
1824 return (t.hi << LO_TIME_BITS) + t.lo;
1827 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1828 doc: /* Return the current time, as a float number of seconds since the epoch.
1829 If SPECIFIED-TIME is given, it is the time to convert to float
1830 instead of the current time. The argument should have the form
1831 (HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus,
1832 you can use times from `current-time' and from `file-attributes'.
1833 SPECIFIED-TIME can also have the form (HIGH . LOW), but this is
1834 considered obsolete.
1836 WARNING: Since the result is floating point, it may not be exact.
1837 If precise time stamps are required, use either `current-time',
1838 or (if you need time as a string) `format-time-string'. */)
1839 (Lisp_Object specified_time)
1841 double t;
1842 Lisp_Object high, low, usec, psec;
1843 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1844 && decode_time_components (high, low, usec, psec, 0, &t)))
1845 invalid_time ();
1846 return make_float (t);
1849 /* Write information into buffer S of size MAXSIZE, according to the
1850 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1851 Default to Universal Time if UT, local time otherwise.
1852 Use NS as the number of nanoseconds in the %N directive.
1853 Return the number of bytes written, not including the terminating
1854 '\0'. If S is NULL, nothing will be written anywhere; so to
1855 determine how many bytes would be written, use NULL for S and
1856 ((size_t) -1) for MAXSIZE.
1858 This function behaves like nstrftime, except it allows null
1859 bytes in FORMAT and it does not support nanoseconds. */
1860 static size_t
1861 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1862 size_t format_len, const struct tm *tp, bool ut, int ns)
1864 size_t total = 0;
1866 /* Loop through all the null-terminated strings in the format
1867 argument. Normally there's just one null-terminated string, but
1868 there can be arbitrarily many, concatenated together, if the
1869 format contains '\0' bytes. nstrftime stops at the first
1870 '\0' byte so we must invoke it separately for each such string. */
1871 for (;;)
1873 size_t len;
1874 size_t result;
1876 if (s)
1877 s[0] = '\1';
1879 result = nstrftime (s, maxsize, format, tp, ut, ns);
1881 if (s)
1883 if (result == 0 && s[0] != '\0')
1884 return 0;
1885 s += result + 1;
1888 maxsize -= result + 1;
1889 total += result;
1890 len = strlen (format);
1891 if (len == format_len)
1892 return total;
1893 total++;
1894 format += len + 1;
1895 format_len -= len + 1;
1899 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1900 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1901 TIME is specified as (HIGH LOW USEC PSEC), as returned by
1902 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1903 is also still accepted.
1904 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1905 as Universal Time; nil means describe TIME in the local time zone.
1906 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1907 by text that describes the specified date and time in TIME:
1909 %Y is the year, %y within the century, %C the century.
1910 %G is the year corresponding to the ISO week, %g within the century.
1911 %m is the numeric month.
1912 %b and %h are the locale's abbreviated month name, %B the full name.
1913 (%h is not supported on MS-Windows.)
1914 %d is the day of the month, zero-padded, %e is blank-padded.
1915 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1916 %a is the locale's abbreviated name of the day of week, %A the full name.
1917 %U is the week number starting on Sunday, %W starting on Monday,
1918 %V according to ISO 8601.
1919 %j is the day of the year.
1921 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1922 only blank-padded, %l is like %I blank-padded.
1923 %p is the locale's equivalent of either AM or PM.
1924 %M is the minute.
1925 %S is the second.
1926 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
1927 %Z is the time zone name, %z is the numeric form.
1928 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1930 %c is the locale's date and time format.
1931 %x is the locale's "preferred" date format.
1932 %D is like "%m/%d/%y".
1933 %F is the ISO 8601 date format (like "%Y-%m-%d").
1935 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1936 %X is the locale's "preferred" time format.
1938 Finally, %n is a newline, %t is a tab, %% is a literal %.
1940 Certain flags and modifiers are available with some format controls.
1941 The flags are `_', `-', `^' and `#'. For certain characters X,
1942 %_X is like %X, but padded with blanks; %-X is like %X,
1943 but without padding. %^X is like %X, but with all textual
1944 characters up-cased; %#X is like %X, but with letter-case of
1945 all textual characters reversed.
1946 %NX (where N stands for an integer) is like %X,
1947 but takes up at least N (a number) positions.
1948 The modifiers are `E' and `O'. For certain characters X,
1949 %EX is a locale's alternative version of %X;
1950 %OX is like %X, but uses the locale's number symbols.
1952 For example, to produce full ISO 8601 format, use "%FT%T%z".
1954 usage: (format-time-string FORMAT-STRING &optional TIME UNIVERSAL) */)
1955 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object universal)
1957 struct timespec t = lisp_time_argument (timeval);
1958 struct tm tm;
1960 CHECK_STRING (format_string);
1961 format_string = code_convert_string_norecord (format_string,
1962 Vlocale_coding_system, 1);
1963 return format_time_string (SSDATA (format_string), SBYTES (format_string),
1964 t, ! NILP (universal), &tm);
1967 static Lisp_Object
1968 format_time_string (char const *format, ptrdiff_t formatlen,
1969 struct timespec t, bool ut, struct tm *tmp)
1971 char buffer[4000];
1972 char *buf = buffer;
1973 ptrdiff_t size = sizeof buffer;
1974 size_t len;
1975 Lisp_Object bufstring;
1976 int ns = t.tv_nsec;
1977 USE_SAFE_ALLOCA;
1979 tmp = ut ? gmtime_r (&t.tv_sec, tmp) : localtime_r (&t.tv_sec, tmp);
1980 if (! tmp)
1981 time_overflow ();
1982 synchronize_system_time_locale ();
1984 while (true)
1986 buf[0] = '\1';
1987 len = emacs_nmemftime (buf, size, format, formatlen, tmp, ut, ns);
1988 if ((0 < len && len < size) || (len == 0 && buf[0] == '\0'))
1989 break;
1991 /* Buffer was too small, so make it bigger and try again. */
1992 len = emacs_nmemftime (NULL, SIZE_MAX, format, formatlen, tmp, ut, ns);
1993 if (STRING_BYTES_BOUND <= len)
1994 string_overflow ();
1995 size = len + 1;
1996 buf = SAFE_ALLOCA (size);
1999 bufstring = make_unibyte_string (buf, len);
2000 SAFE_FREE ();
2001 return code_convert_string_norecord (bufstring, Vlocale_coding_system, 0);
2004 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
2005 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
2006 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
2007 as from `current-time' and `file-attributes', or nil to use the
2008 current time. The obsolete form (HIGH . LOW) is also still accepted.
2009 The list has the following nine members: SEC is an integer between 0
2010 and 60; SEC is 60 for a leap second, which only some operating systems
2011 support. MINUTE is an integer between 0 and 59. HOUR is an integer
2012 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
2013 integer between 1 and 12. YEAR is an integer indicating the
2014 four-digit year. DOW is the day of week, an integer between 0 and 6,
2015 where 0 is Sunday. DST is t if daylight saving time is in effect,
2016 otherwise nil. ZONE is an integer indicating the number of seconds
2017 east of Greenwich. (Note that Common Lisp has different meanings for
2018 DOW and ZONE.) */)
2019 (Lisp_Object specified_time)
2021 time_t time_spec = lisp_seconds_argument (specified_time);
2022 struct tm local_tm, gmt_tm;
2024 if (! (localtime_r (&time_spec, &local_tm)
2025 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= local_tm.tm_year
2026 && local_tm.tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
2027 time_overflow ();
2029 /* Avoid overflow when INT_MAX < EMACS_INT_MAX. */
2030 EMACS_INT tm_year_base = TM_YEAR_BASE;
2032 return CALLN (Flist,
2033 make_number (local_tm.tm_sec),
2034 make_number (local_tm.tm_min),
2035 make_number (local_tm.tm_hour),
2036 make_number (local_tm.tm_mday),
2037 make_number (local_tm.tm_mon + 1),
2038 make_number (local_tm.tm_year + tm_year_base),
2039 make_number (local_tm.tm_wday),
2040 local_tm.tm_isdst ? Qt : Qnil,
2041 (HAVE_TM_GMTOFF
2042 ? make_number (tm_gmtoff (&local_tm))
2043 : gmtime_r (&time_spec, &gmt_tm)
2044 ? make_number (tm_diff (&local_tm, &gmt_tm))
2045 : Qnil));
2048 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
2049 the result is representable as an int. Assume OFFSET is small and
2050 nonnegative. */
2051 static int
2052 check_tm_member (Lisp_Object obj, int offset)
2054 EMACS_INT n;
2055 CHECK_NUMBER (obj);
2056 n = XINT (obj);
2057 if (! (INT_MIN + offset <= n && n - offset <= INT_MAX))
2058 time_overflow ();
2059 return n - offset;
2062 /* Decode ZONE as a time zone specification. */
2064 static Lisp_Object
2065 decode_time_zone (Lisp_Object zone)
2067 if (EQ (zone, Qt))
2068 return build_string ("UTC0");
2069 else if (STRINGP (zone))
2070 return zone;
2071 else if (INTEGERP (zone))
2073 static char const tzbuf_format[] = "XXX%s%"pI"d:%02d:%02d";
2074 char tzbuf[sizeof tzbuf_format + INT_STRLEN_BOUND (EMACS_INT)];
2075 EMACS_INT abszone = eabs (XINT (zone)), zone_hr = abszone / (60 * 60);
2076 int zone_min = (abszone / 60) % 60, zone_sec = abszone % 60;
2078 return make_formatted_string (tzbuf, tzbuf_format, &"-"[XINT (zone) < 0],
2079 zone_hr, zone_min, zone_sec);
2081 else
2082 xsignal2 (Qerror, build_string ("Invalid time zone specification"), zone);
2085 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
2086 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
2087 This is the reverse operation of `decode-time', which see.
2088 ZONE defaults to the current time zone rule. This can
2089 be a string or t (as from `set-time-zone-rule'), or it can be a list
2090 \(as from `current-time-zone') or an integer (as from `decode-time')
2091 applied without consideration for daylight saving time.
2093 You can pass more than 7 arguments; then the first six arguments
2094 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
2095 The intervening arguments are ignored.
2096 This feature lets (apply 'encode-time (decode-time ...)) work.
2098 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
2099 for example, a DAY of 0 means the day preceding the given month.
2100 Year numbers less than 100 are treated just like other year numbers.
2101 If you want them to stand for years in this century, you must do that yourself.
2103 Years before 1970 are not guaranteed to work. On some systems,
2104 year values as low as 1901 do work.
2106 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
2107 (ptrdiff_t nargs, Lisp_Object *args)
2109 time_t value;
2110 struct tm tm;
2111 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
2113 tm.tm_sec = check_tm_member (args[0], 0);
2114 tm.tm_min = check_tm_member (args[1], 0);
2115 tm.tm_hour = check_tm_member (args[2], 0);
2116 tm.tm_mday = check_tm_member (args[3], 0);
2117 tm.tm_mon = check_tm_member (args[4], 1);
2118 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
2119 tm.tm_isdst = -1;
2121 if (CONSP (zone))
2122 zone = XCAR (zone);
2123 if (NILP (zone))
2124 value = mktime (&tm);
2125 else
2127 timezone_t tz = tzalloc (SSDATA (decode_time_zone (zone)));
2128 value = mktime_z (tz, &tm);
2129 tzfree (tz);
2132 if (value == (time_t) -1)
2133 time_overflow ();
2135 return list2i (hi_time (value), lo_time (value));
2138 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
2139 doc: /* Return the current local time, as a human-readable string.
2140 Programs can use this function to decode a time,
2141 since the number of columns in each field is fixed
2142 if the year is in the range 1000-9999.
2143 The format is `Sun Sep 16 01:03:52 1973'.
2144 However, see also the functions `decode-time' and `format-time-string'
2145 which provide a much more powerful and general facility.
2147 If SPECIFIED-TIME is given, it is a time to format instead of the
2148 current time. The argument should have the form (HIGH LOW . IGNORED).
2149 Thus, you can use times obtained from `current-time' and from
2150 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
2151 but this is considered obsolete. */)
2152 (Lisp_Object specified_time)
2154 time_t value = lisp_seconds_argument (specified_time);
2156 /* Convert to a string in ctime format, except without the trailing
2157 newline, and without the 4-digit year limit. Don't use asctime
2158 or ctime, as they might dump core if the year is outside the
2159 range -999 .. 9999. */
2160 struct tm tm;
2161 if (! localtime_r (&value, &tm))
2162 time_overflow ();
2164 static char const wday_name[][4] =
2165 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
2166 static char const mon_name[][4] =
2167 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2168 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
2169 printmax_t year_base = TM_YEAR_BASE;
2170 char buf[sizeof "Mon Apr 30 12:49:17 " + INT_STRLEN_BOUND (int) + 1];
2171 int len = sprintf (buf, "%s %s%3d %02d:%02d:%02d %"pMd,
2172 wday_name[tm.tm_wday], mon_name[tm.tm_mon], tm.tm_mday,
2173 tm.tm_hour, tm.tm_min, tm.tm_sec,
2174 tm.tm_year + year_base);
2176 return make_unibyte_string (buf, len);
2179 /* Yield A - B, measured in seconds.
2180 This function is copied from the GNU C Library. */
2181 static int
2182 tm_diff (struct tm *a, struct tm *b)
2184 /* Compute intervening leap days correctly even if year is negative.
2185 Take care to avoid int overflow in leap day calculations,
2186 but it's OK to assume that A and B are close to each other. */
2187 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2188 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2189 int a100 = a4 / 25 - (a4 % 25 < 0);
2190 int b100 = b4 / 25 - (b4 % 25 < 0);
2191 int a400 = a100 >> 2;
2192 int b400 = b100 >> 2;
2193 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2194 int years = a->tm_year - b->tm_year;
2195 int days = (365 * years + intervening_leap_days
2196 + (a->tm_yday - b->tm_yday));
2197 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2198 + (a->tm_min - b->tm_min))
2199 + (a->tm_sec - b->tm_sec));
2202 /* Yield A's UTC offset, or an unspecified value if unknown. */
2203 static long int
2204 tm_gmtoff (struct tm *a)
2206 #if HAVE_TM_GMTOFF
2207 return a->tm_gmtoff;
2208 #else
2209 return 0;
2210 #endif
2213 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
2214 doc: /* Return the offset and name for the local time zone.
2215 This returns a list of the form (OFFSET NAME).
2216 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
2217 A negative value means west of Greenwich.
2218 NAME is a string giving the name of the time zone.
2219 If SPECIFIED-TIME is given, the time zone offset is determined from it
2220 instead of using the current time. The argument should have the form
2221 (HIGH LOW . IGNORED). Thus, you can use times obtained from
2222 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
2223 have the form (HIGH . LOW), but this is considered obsolete.
2225 Some operating systems cannot provide all this information to Emacs;
2226 in this case, `current-time-zone' returns a list containing nil for
2227 the data it can't find. */)
2228 (Lisp_Object specified_time)
2230 struct timespec value;
2231 struct tm local_tm, gmt_tm;
2232 Lisp_Object zone_offset, zone_name;
2234 zone_offset = Qnil;
2235 value = make_timespec (lisp_seconds_argument (specified_time), 0);
2236 zone_name = format_time_string ("%Z", sizeof "%Z" - 1, value, 0, &local_tm);
2238 if (HAVE_TM_GMTOFF || gmtime_r (&value.tv_sec, &gmt_tm))
2240 long int offset = (HAVE_TM_GMTOFF
2241 ? tm_gmtoff (&local_tm)
2242 : tm_diff (&local_tm, &gmt_tm));
2243 zone_offset = make_number (offset);
2244 if (SCHARS (zone_name) == 0)
2246 /* No local time zone name is available; use "+-NNNN" instead. */
2247 long int m = offset / 60;
2248 long int am = offset < 0 ? - m : m;
2249 long int hour = am / 60;
2250 int min = am % 60;
2251 char buf[sizeof "+00" + INT_STRLEN_BOUND (long int)];
2252 zone_name = make_formatted_string (buf, "%c%02ld%02d",
2253 (offset < 0 ? '-' : '+'),
2254 hour, min);
2258 return list2 (zone_offset, zone_name);
2261 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2262 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
2263 If TZ is nil, use implementation-defined default time zone information.
2264 If TZ is t, use Universal Time. If TZ is an integer, it is treated as in
2265 `encode-time'.
2267 Instead of calling this function, you typically want (setenv "TZ" TZ).
2268 That changes both the environment of the Emacs process and the
2269 variable `process-environment', whereas `set-time-zone-rule' affects
2270 only the former. */)
2271 (Lisp_Object tz)
2273 const char *tzstring = NILP (tz) ? initial_tz : SSDATA (decode_time_zone (tz));
2275 block_input ();
2276 set_time_zone_rule (tzstring);
2277 unblock_input ();
2279 return Qnil;
2282 /* Set the local time zone rule to TZSTRING.
2284 This function is not thread-safe, in theory because putenv is not,
2285 but mostly because of the static storage it updates. Other threads
2286 that invoke localtime etc. may be adversely affected while this
2287 function is executing. */
2289 static void
2290 set_time_zone_rule (const char *tzstring)
2292 /* A buffer holding a string of the form "TZ=value", intended
2293 to be part of the environment. */
2294 static char *tzvalbuf;
2295 static ptrdiff_t tzvalbufsize;
2297 int tzeqlen = sizeof "TZ=" - 1;
2298 ptrdiff_t tzstringlen = tzstring ? strlen (tzstring) : 0;
2299 char *tzval = tzvalbuf;
2300 bool new_tzvalbuf = tzvalbufsize <= tzeqlen + tzstringlen;
2302 if (new_tzvalbuf)
2304 /* Do not attempt to free the old tzvalbuf, since another thread
2305 may be using it. In practice, the first allocation is large
2306 enough and memory does not leak. */
2307 tzval = xpalloc (NULL, &tzvalbufsize,
2308 tzeqlen + tzstringlen - tzvalbufsize + 1, -1, 1);
2309 tzvalbuf = tzval;
2310 tzval[1] = 'Z';
2311 tzval[2] = '=';
2314 if (tzstring)
2316 /* Modify TZVAL in place. Although this is dicey in a
2317 multithreaded environment, we know of no portable alternative.
2318 Calling putenv or setenv could crash some other thread. */
2319 tzval[0] = 'T';
2320 strcpy (tzval + tzeqlen, tzstring);
2322 else
2324 /* Turn 'TZ=whatever' into an empty environment variable 'tZ='.
2325 Although this is also dicey, calling unsetenv here can crash Emacs.
2326 See Bug#8705. */
2327 tzval[0] = 't';
2328 tzval[tzeqlen] = 0;
2331 if (new_tzvalbuf
2332 #ifdef WINDOWSNT
2333 /* MS-Windows implementation of 'putenv' copies the argument
2334 string into a block it allocates, so modifying tzval string
2335 does not change the environment. OTOH, the other threads run
2336 by Emacs on MS-Windows never call 'xputenv' or 'putenv' or
2337 'unsetenv', so the original cause for the dicey in-place
2338 modification technique doesn't exist there in the first
2339 place. */
2340 || 1
2341 #endif
2344 /* Although this is not thread-safe, in practice this runs only
2345 on startup when there is only one thread. */
2346 xputenv (tzval);
2349 #ifdef HAVE_TZSET
2350 tzset ();
2351 #endif
2354 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2355 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2356 type of object is Lisp_String). INHERIT is passed to
2357 INSERT_FROM_STRING_FUNC as the last argument. */
2359 static void
2360 general_insert_function (void (*insert_func)
2361 (const char *, ptrdiff_t),
2362 void (*insert_from_string_func)
2363 (Lisp_Object, ptrdiff_t, ptrdiff_t,
2364 ptrdiff_t, ptrdiff_t, bool),
2365 bool inherit, ptrdiff_t nargs, Lisp_Object *args)
2367 ptrdiff_t argnum;
2368 Lisp_Object val;
2370 for (argnum = 0; argnum < nargs; argnum++)
2372 val = args[argnum];
2373 if (CHARACTERP (val))
2375 int c = XFASTINT (val);
2376 unsigned char str[MAX_MULTIBYTE_LENGTH];
2377 int len;
2379 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2380 len = CHAR_STRING (c, str);
2381 else
2383 str[0] = CHAR_TO_BYTE8 (c);
2384 len = 1;
2386 (*insert_func) ((char *) str, len);
2388 else if (STRINGP (val))
2390 (*insert_from_string_func) (val, 0, 0,
2391 SCHARS (val),
2392 SBYTES (val),
2393 inherit);
2395 else
2396 wrong_type_argument (Qchar_or_string_p, val);
2400 void
2401 insert1 (Lisp_Object arg)
2403 Finsert (1, &arg);
2407 /* Callers passing one argument to Finsert need not gcpro the
2408 argument "array", since the only element of the array will
2409 not be used after calling insert or insert_from_string, so
2410 we don't care if it gets trashed. */
2412 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2413 doc: /* Insert the arguments, either strings or characters, at point.
2414 Point and before-insertion markers move forward to end up
2415 after the inserted text.
2416 Any other markers at the point of insertion remain before the text.
2418 If the current buffer is multibyte, unibyte strings are converted
2419 to multibyte for insertion (see `string-make-multibyte').
2420 If the current buffer is unibyte, multibyte strings are converted
2421 to unibyte for insertion (see `string-make-unibyte').
2423 When operating on binary data, it may be necessary to preserve the
2424 original bytes of a unibyte string when inserting it into a multibyte
2425 buffer; to accomplish this, apply `string-as-multibyte' to the string
2426 and insert the result.
2428 usage: (insert &rest ARGS) */)
2429 (ptrdiff_t nargs, Lisp_Object *args)
2431 general_insert_function (insert, insert_from_string, 0, nargs, args);
2432 return Qnil;
2435 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2436 0, MANY, 0,
2437 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2438 Point and before-insertion markers move forward to end up
2439 after the inserted text.
2440 Any other markers at the point of insertion remain before the text.
2442 If the current buffer is multibyte, unibyte strings are converted
2443 to multibyte for insertion (see `unibyte-char-to-multibyte').
2444 If the current buffer is unibyte, multibyte strings are converted
2445 to unibyte for insertion.
2447 usage: (insert-and-inherit &rest ARGS) */)
2448 (ptrdiff_t nargs, Lisp_Object *args)
2450 general_insert_function (insert_and_inherit, insert_from_string, 1,
2451 nargs, args);
2452 return Qnil;
2455 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2456 doc: /* Insert strings or characters at point, relocating markers after the text.
2457 Point and markers move forward to end up after the inserted text.
2459 If the current buffer is multibyte, unibyte strings are converted
2460 to multibyte for insertion (see `unibyte-char-to-multibyte').
2461 If the current buffer is unibyte, multibyte strings are converted
2462 to unibyte for insertion.
2464 If an overlay begins at the insertion point, the inserted text falls
2465 outside the overlay; if a nonempty overlay ends at the insertion
2466 point, the inserted text falls inside that overlay.
2468 usage: (insert-before-markers &rest ARGS) */)
2469 (ptrdiff_t nargs, Lisp_Object *args)
2471 general_insert_function (insert_before_markers,
2472 insert_from_string_before_markers, 0,
2473 nargs, args);
2474 return Qnil;
2477 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2478 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2479 doc: /* Insert text at point, relocating markers and inheriting properties.
2480 Point and markers move forward to end up after the inserted text.
2482 If the current buffer is multibyte, unibyte strings are converted
2483 to multibyte for insertion (see `unibyte-char-to-multibyte').
2484 If the current buffer is unibyte, multibyte strings are converted
2485 to unibyte for insertion.
2487 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2488 (ptrdiff_t nargs, Lisp_Object *args)
2490 general_insert_function (insert_before_markers_and_inherit,
2491 insert_from_string_before_markers, 1,
2492 nargs, args);
2493 return Qnil;
2496 DEFUN ("insert-char", Finsert_char, Sinsert_char, 1, 3,
2497 "(list (read-char-by-name \"Insert character (Unicode name or hex): \")\
2498 (prefix-numeric-value current-prefix-arg)\
2499 t))",
2500 doc: /* Insert COUNT copies of CHARACTER.
2501 Interactively, prompt for CHARACTER. You can specify CHARACTER in one
2502 of these ways:
2504 - As its Unicode character name, e.g. \"LATIN SMALL LETTER A\".
2505 Completion is available; if you type a substring of the name
2506 preceded by an asterisk `*', Emacs shows all names which include
2507 that substring, not necessarily at the beginning of the name.
2509 - As a hexadecimal code point, e.g. 263A. Note that code points in
2510 Emacs are equivalent to Unicode up to 10FFFF (which is the limit of
2511 the Unicode code space).
2513 - As a code point with a radix specified with #, e.g. #o21430
2514 (octal), #x2318 (hex), or #10r8984 (decimal).
2516 If called interactively, COUNT is given by the prefix argument. If
2517 omitted or nil, it defaults to 1.
2519 Inserting the character(s) relocates point and before-insertion
2520 markers in the same ways as the function `insert'.
2522 The optional third argument INHERIT, if non-nil, says to inherit text
2523 properties from adjoining text, if those properties are sticky. If
2524 called interactively, INHERIT is t. */)
2525 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2527 int i, stringlen;
2528 register ptrdiff_t n;
2529 int c, len;
2530 unsigned char str[MAX_MULTIBYTE_LENGTH];
2531 char string[4000];
2533 CHECK_CHARACTER (character);
2534 if (NILP (count))
2535 XSETFASTINT (count, 1);
2536 CHECK_NUMBER (count);
2537 c = XFASTINT (character);
2539 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2540 len = CHAR_STRING (c, str);
2541 else
2542 str[0] = c, len = 1;
2543 if (XINT (count) <= 0)
2544 return Qnil;
2545 if (BUF_BYTES_MAX / len < XINT (count))
2546 buffer_overflow ();
2547 n = XINT (count) * len;
2548 stringlen = min (n, sizeof string - sizeof string % len);
2549 for (i = 0; i < stringlen; i++)
2550 string[i] = str[i % len];
2551 while (n > stringlen)
2553 QUIT;
2554 if (!NILP (inherit))
2555 insert_and_inherit (string, stringlen);
2556 else
2557 insert (string, stringlen);
2558 n -= stringlen;
2560 if (!NILP (inherit))
2561 insert_and_inherit (string, n);
2562 else
2563 insert (string, n);
2564 return Qnil;
2567 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2568 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2569 Both arguments are required.
2570 BYTE is a number of the range 0..255.
2572 If BYTE is 128..255 and the current buffer is multibyte, the
2573 corresponding eight-bit character is inserted.
2575 Point, and before-insertion markers, are relocated as in the function `insert'.
2576 The optional third arg INHERIT, if non-nil, says to inherit text properties
2577 from adjoining text, if those properties are sticky. */)
2578 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2580 CHECK_NUMBER (byte);
2581 if (XINT (byte) < 0 || XINT (byte) > 255)
2582 args_out_of_range_3 (byte, make_number (0), make_number (255));
2583 if (XINT (byte) >= 128
2584 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2585 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2586 return Finsert_char (byte, count, inherit);
2590 /* Making strings from buffer contents. */
2592 /* Return a Lisp_String containing the text of the current buffer from
2593 START to END. If text properties are in use and the current buffer
2594 has properties in the range specified, the resulting string will also
2595 have them, if PROPS is true.
2597 We don't want to use plain old make_string here, because it calls
2598 make_uninit_string, which can cause the buffer arena to be
2599 compacted. make_string has no way of knowing that the data has
2600 been moved, and thus copies the wrong data into the string. This
2601 doesn't effect most of the other users of make_string, so it should
2602 be left as is. But we should use this function when conjuring
2603 buffer substrings. */
2605 Lisp_Object
2606 make_buffer_string (ptrdiff_t start, ptrdiff_t end, bool props)
2608 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
2609 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
2611 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2614 /* Return a Lisp_String containing the text of the current buffer from
2615 START / START_BYTE to END / END_BYTE.
2617 If text properties are in use and the current buffer
2618 has properties in the range specified, the resulting string will also
2619 have them, if PROPS is true.
2621 We don't want to use plain old make_string here, because it calls
2622 make_uninit_string, which can cause the buffer arena to be
2623 compacted. make_string has no way of knowing that the data has
2624 been moved, and thus copies the wrong data into the string. This
2625 doesn't effect most of the other users of make_string, so it should
2626 be left as is. But we should use this function when conjuring
2627 buffer substrings. */
2629 Lisp_Object
2630 make_buffer_string_both (ptrdiff_t start, ptrdiff_t start_byte,
2631 ptrdiff_t end, ptrdiff_t end_byte, bool props)
2633 Lisp_Object result, tem, tem1;
2634 ptrdiff_t beg0, end0, beg1, end1, size;
2636 if (start_byte < GPT_BYTE && GPT_BYTE < end_byte)
2638 /* Two regions, before and after the gap. */
2639 beg0 = start_byte;
2640 end0 = GPT_BYTE;
2641 beg1 = GPT_BYTE + GAP_SIZE - BEG_BYTE;
2642 end1 = end_byte + GAP_SIZE - BEG_BYTE;
2644 else
2646 /* The only region. */
2647 beg0 = start_byte;
2648 end0 = end_byte;
2649 beg1 = -1;
2650 end1 = -1;
2653 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2654 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2655 else
2656 result = make_uninit_string (end - start);
2658 size = end0 - beg0;
2659 memcpy (SDATA (result), BYTE_POS_ADDR (beg0), size);
2660 if (beg1 != -1)
2661 memcpy (SDATA (result) + size, BEG_ADDR + beg1, end1 - beg1);
2663 /* If desired, update and copy the text properties. */
2664 if (props)
2666 update_buffer_properties (start, end);
2668 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2669 tem1 = Ftext_properties_at (make_number (start), Qnil);
2671 if (XINT (tem) != end || !NILP (tem1))
2672 copy_intervals_to_string (result, current_buffer, start,
2673 end - start);
2676 return result;
2679 /* Call Vbuffer_access_fontify_functions for the range START ... END
2680 in the current buffer, if necessary. */
2682 static void
2683 update_buffer_properties (ptrdiff_t start, ptrdiff_t end)
2685 /* If this buffer has some access functions,
2686 call them, specifying the range of the buffer being accessed. */
2687 if (!NILP (Vbuffer_access_fontify_functions))
2689 /* But don't call them if we can tell that the work
2690 has already been done. */
2691 if (!NILP (Vbuffer_access_fontified_property))
2693 Lisp_Object tem
2694 = Ftext_property_any (make_number (start), make_number (end),
2695 Vbuffer_access_fontified_property,
2696 Qnil, Qnil);
2697 if (NILP (tem))
2698 return;
2701 CALLN (Frun_hook_with_args, Qbuffer_access_fontify_functions,
2702 make_number (start), make_number (end));
2706 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2707 doc: /* Return the contents of part of the current buffer as a string.
2708 The two arguments START and END are character positions;
2709 they can be in either order.
2710 The string returned is multibyte if the buffer is multibyte.
2712 This function copies the text properties of that part of the buffer
2713 into the result string; if you don't want the text properties,
2714 use `buffer-substring-no-properties' instead. */)
2715 (Lisp_Object start, Lisp_Object end)
2717 register ptrdiff_t b, e;
2719 validate_region (&start, &end);
2720 b = XINT (start);
2721 e = XINT (end);
2723 return make_buffer_string (b, e, 1);
2726 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2727 Sbuffer_substring_no_properties, 2, 2, 0,
2728 doc: /* Return the characters of part of the buffer, without the text properties.
2729 The two arguments START and END are character positions;
2730 they can be in either order. */)
2731 (Lisp_Object start, Lisp_Object end)
2733 register ptrdiff_t b, e;
2735 validate_region (&start, &end);
2736 b = XINT (start);
2737 e = XINT (end);
2739 return make_buffer_string (b, e, 0);
2742 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2743 doc: /* Return the contents of the current buffer as a string.
2744 If narrowing is in effect, this function returns only the visible part
2745 of the buffer. */)
2746 (void)
2748 return make_buffer_string_both (BEGV, BEGV_BYTE, ZV, ZV_BYTE, 1);
2751 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2752 1, 3, 0,
2753 doc: /* Insert before point a substring of the contents of BUFFER.
2754 BUFFER may be a buffer or a buffer name.
2755 Arguments START and END are character positions specifying the substring.
2756 They default to the values of (point-min) and (point-max) in BUFFER.
2758 Point and before-insertion markers move forward to end up after the
2759 inserted text.
2760 Any other markers at the point of insertion remain before the text.
2762 If the current buffer is multibyte and BUFFER is unibyte, or vice
2763 versa, strings are converted from unibyte to multibyte or vice versa
2764 using `string-make-multibyte' or `string-make-unibyte', which see. */)
2765 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2767 register EMACS_INT b, e, temp;
2768 register struct buffer *bp, *obuf;
2769 Lisp_Object buf;
2771 buf = Fget_buffer (buffer);
2772 if (NILP (buf))
2773 nsberror (buffer);
2774 bp = XBUFFER (buf);
2775 if (!BUFFER_LIVE_P (bp))
2776 error ("Selecting deleted buffer");
2778 if (NILP (start))
2779 b = BUF_BEGV (bp);
2780 else
2782 CHECK_NUMBER_COERCE_MARKER (start);
2783 b = XINT (start);
2785 if (NILP (end))
2786 e = BUF_ZV (bp);
2787 else
2789 CHECK_NUMBER_COERCE_MARKER (end);
2790 e = XINT (end);
2793 if (b > e)
2794 temp = b, b = e, e = temp;
2796 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2797 args_out_of_range (start, end);
2799 obuf = current_buffer;
2800 set_buffer_internal_1 (bp);
2801 update_buffer_properties (b, e);
2802 set_buffer_internal_1 (obuf);
2804 insert_from_buffer (bp, b, e - b, 0);
2805 return Qnil;
2808 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2809 6, 6, 0,
2810 doc: /* Compare two substrings of two buffers; return result as number.
2811 Return -N if first string is less after N-1 chars, +N if first string is
2812 greater after N-1 chars, or 0 if strings match. Each substring is
2813 represented as three arguments: BUFFER, START and END. That makes six
2814 args in all, three for each substring.
2816 The value of `case-fold-search' in the current buffer
2817 determines whether case is significant or ignored. */)
2818 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2820 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2821 register struct buffer *bp1, *bp2;
2822 register Lisp_Object trt
2823 = (!NILP (BVAR (current_buffer, case_fold_search))
2824 ? BVAR (current_buffer, case_canon_table) : Qnil);
2825 ptrdiff_t chars = 0;
2826 ptrdiff_t i1, i2, i1_byte, i2_byte;
2828 /* Find the first buffer and its substring. */
2830 if (NILP (buffer1))
2831 bp1 = current_buffer;
2832 else
2834 Lisp_Object buf1;
2835 buf1 = Fget_buffer (buffer1);
2836 if (NILP (buf1))
2837 nsberror (buffer1);
2838 bp1 = XBUFFER (buf1);
2839 if (!BUFFER_LIVE_P (bp1))
2840 error ("Selecting deleted buffer");
2843 if (NILP (start1))
2844 begp1 = BUF_BEGV (bp1);
2845 else
2847 CHECK_NUMBER_COERCE_MARKER (start1);
2848 begp1 = XINT (start1);
2850 if (NILP (end1))
2851 endp1 = BUF_ZV (bp1);
2852 else
2854 CHECK_NUMBER_COERCE_MARKER (end1);
2855 endp1 = XINT (end1);
2858 if (begp1 > endp1)
2859 temp = begp1, begp1 = endp1, endp1 = temp;
2861 if (!(BUF_BEGV (bp1) <= begp1
2862 && begp1 <= endp1
2863 && endp1 <= BUF_ZV (bp1)))
2864 args_out_of_range (start1, end1);
2866 /* Likewise for second substring. */
2868 if (NILP (buffer2))
2869 bp2 = current_buffer;
2870 else
2872 Lisp_Object buf2;
2873 buf2 = Fget_buffer (buffer2);
2874 if (NILP (buf2))
2875 nsberror (buffer2);
2876 bp2 = XBUFFER (buf2);
2877 if (!BUFFER_LIVE_P (bp2))
2878 error ("Selecting deleted buffer");
2881 if (NILP (start2))
2882 begp2 = BUF_BEGV (bp2);
2883 else
2885 CHECK_NUMBER_COERCE_MARKER (start2);
2886 begp2 = XINT (start2);
2888 if (NILP (end2))
2889 endp2 = BUF_ZV (bp2);
2890 else
2892 CHECK_NUMBER_COERCE_MARKER (end2);
2893 endp2 = XINT (end2);
2896 if (begp2 > endp2)
2897 temp = begp2, begp2 = endp2, endp2 = temp;
2899 if (!(BUF_BEGV (bp2) <= begp2
2900 && begp2 <= endp2
2901 && endp2 <= BUF_ZV (bp2)))
2902 args_out_of_range (start2, end2);
2904 i1 = begp1;
2905 i2 = begp2;
2906 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2907 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2909 while (i1 < endp1 && i2 < endp2)
2911 /* When we find a mismatch, we must compare the
2912 characters, not just the bytes. */
2913 int c1, c2;
2915 QUIT;
2917 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
2919 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2920 BUF_INC_POS (bp1, i1_byte);
2921 i1++;
2923 else
2925 c1 = BUF_FETCH_BYTE (bp1, i1);
2926 MAKE_CHAR_MULTIBYTE (c1);
2927 i1++;
2930 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
2932 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2933 BUF_INC_POS (bp2, i2_byte);
2934 i2++;
2936 else
2938 c2 = BUF_FETCH_BYTE (bp2, i2);
2939 MAKE_CHAR_MULTIBYTE (c2);
2940 i2++;
2943 if (!NILP (trt))
2945 c1 = char_table_translate (trt, c1);
2946 c2 = char_table_translate (trt, c2);
2948 if (c1 < c2)
2949 return make_number (- 1 - chars);
2950 if (c1 > c2)
2951 return make_number (chars + 1);
2953 chars++;
2956 /* The strings match as far as they go.
2957 If one is shorter, that one is less. */
2958 if (chars < endp1 - begp1)
2959 return make_number (chars + 1);
2960 else if (chars < endp2 - begp2)
2961 return make_number (- chars - 1);
2963 /* Same length too => they are equal. */
2964 return make_number (0);
2967 static void
2968 subst_char_in_region_unwind (Lisp_Object arg)
2970 bset_undo_list (current_buffer, arg);
2973 static void
2974 subst_char_in_region_unwind_1 (Lisp_Object arg)
2976 bset_filename (current_buffer, arg);
2979 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2980 Ssubst_char_in_region, 4, 5, 0,
2981 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2982 If optional arg NOUNDO is non-nil, don't record this change for undo
2983 and don't mark the buffer as really changed.
2984 Both characters must have the same length of multi-byte form. */)
2985 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
2987 register ptrdiff_t pos, pos_byte, stop, i, len, end_byte;
2988 /* Keep track of the first change in the buffer:
2989 if 0 we haven't found it yet.
2990 if < 0 we've found it and we've run the before-change-function.
2991 if > 0 we've actually performed it and the value is its position. */
2992 ptrdiff_t changed = 0;
2993 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2994 unsigned char *p;
2995 ptrdiff_t count = SPECPDL_INDEX ();
2996 #define COMBINING_NO 0
2997 #define COMBINING_BEFORE 1
2998 #define COMBINING_AFTER 2
2999 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
3000 int maybe_byte_combining = COMBINING_NO;
3001 ptrdiff_t last_changed = 0;
3002 bool multibyte_p
3003 = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3004 int fromc, toc;
3006 restart:
3008 validate_region (&start, &end);
3009 CHECK_CHARACTER (fromchar);
3010 CHECK_CHARACTER (tochar);
3011 fromc = XFASTINT (fromchar);
3012 toc = XFASTINT (tochar);
3014 if (multibyte_p)
3016 len = CHAR_STRING (fromc, fromstr);
3017 if (CHAR_STRING (toc, tostr) != len)
3018 error ("Characters in `subst-char-in-region' have different byte-lengths");
3019 if (!ASCII_CHAR_P (*tostr))
3021 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
3022 complete multibyte character, it may be combined with the
3023 after bytes. If it is in the range 0xA0..0xFF, it may be
3024 combined with the before and after bytes. */
3025 if (!CHAR_HEAD_P (*tostr))
3026 maybe_byte_combining = COMBINING_BOTH;
3027 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
3028 maybe_byte_combining = COMBINING_AFTER;
3031 else
3033 len = 1;
3034 fromstr[0] = fromc;
3035 tostr[0] = toc;
3038 pos = XINT (start);
3039 pos_byte = CHAR_TO_BYTE (pos);
3040 stop = CHAR_TO_BYTE (XINT (end));
3041 end_byte = stop;
3043 /* If we don't want undo, turn off putting stuff on the list.
3044 That's faster than getting rid of things,
3045 and it prevents even the entry for a first change.
3046 Also inhibit locking the file. */
3047 if (!changed && !NILP (noundo))
3049 record_unwind_protect (subst_char_in_region_unwind,
3050 BVAR (current_buffer, undo_list));
3051 bset_undo_list (current_buffer, Qt);
3052 /* Don't do file-locking. */
3053 record_unwind_protect (subst_char_in_region_unwind_1,
3054 BVAR (current_buffer, filename));
3055 bset_filename (current_buffer, Qnil);
3058 if (pos_byte < GPT_BYTE)
3059 stop = min (stop, GPT_BYTE);
3060 while (1)
3062 ptrdiff_t pos_byte_next = pos_byte;
3064 if (pos_byte >= stop)
3066 if (pos_byte >= end_byte) break;
3067 stop = end_byte;
3069 p = BYTE_POS_ADDR (pos_byte);
3070 if (multibyte_p)
3071 INC_POS (pos_byte_next);
3072 else
3073 ++pos_byte_next;
3074 if (pos_byte_next - pos_byte == len
3075 && p[0] == fromstr[0]
3076 && (len == 1
3077 || (p[1] == fromstr[1]
3078 && (len == 2 || (p[2] == fromstr[2]
3079 && (len == 3 || p[3] == fromstr[3]))))))
3081 if (changed < 0)
3082 /* We've already seen this and run the before-change-function;
3083 this time we only need to record the actual position. */
3084 changed = pos;
3085 else if (!changed)
3087 changed = -1;
3088 modify_text (pos, XINT (end));
3090 if (! NILP (noundo))
3092 if (MODIFF - 1 == SAVE_MODIFF)
3093 SAVE_MODIFF++;
3094 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
3095 BUF_AUTOSAVE_MODIFF (current_buffer)++;
3098 /* The before-change-function may have moved the gap
3099 or even modified the buffer so we should start over. */
3100 goto restart;
3103 /* Take care of the case where the new character
3104 combines with neighboring bytes. */
3105 if (maybe_byte_combining
3106 && (maybe_byte_combining == COMBINING_AFTER
3107 ? (pos_byte_next < Z_BYTE
3108 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3109 : ((pos_byte_next < Z_BYTE
3110 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3111 || (pos_byte > BEG_BYTE
3112 && ! ASCII_CHAR_P (FETCH_BYTE (pos_byte - 1))))))
3114 Lisp_Object tem, string;
3116 struct gcpro gcpro1;
3118 tem = BVAR (current_buffer, undo_list);
3119 GCPRO1 (tem);
3121 /* Make a multibyte string containing this single character. */
3122 string = make_multibyte_string ((char *) tostr, 1, len);
3123 /* replace_range is less efficient, because it moves the gap,
3124 but it handles combining correctly. */
3125 replace_range (pos, pos + 1, string,
3126 0, 0, 1);
3127 pos_byte_next = CHAR_TO_BYTE (pos);
3128 if (pos_byte_next > pos_byte)
3129 /* Before combining happened. We should not increment
3130 POS. So, to cancel the later increment of POS,
3131 decrease it now. */
3132 pos--;
3133 else
3134 INC_POS (pos_byte_next);
3136 if (! NILP (noundo))
3137 bset_undo_list (current_buffer, tem);
3139 UNGCPRO;
3141 else
3143 if (NILP (noundo))
3144 record_change (pos, 1);
3145 for (i = 0; i < len; i++) *p++ = tostr[i];
3147 last_changed = pos + 1;
3149 pos_byte = pos_byte_next;
3150 pos++;
3153 if (changed > 0)
3155 signal_after_change (changed,
3156 last_changed - changed, last_changed - changed);
3157 update_compositions (changed, last_changed, CHECK_ALL);
3160 unbind_to (count, Qnil);
3161 return Qnil;
3165 static Lisp_Object check_translation (ptrdiff_t, ptrdiff_t, ptrdiff_t,
3166 Lisp_Object);
3168 /* Helper function for Ftranslate_region_internal.
3170 Check if a character sequence at POS (POS_BYTE) matches an element
3171 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
3172 element is found, return it. Otherwise return Qnil. */
3174 static Lisp_Object
3175 check_translation (ptrdiff_t pos, ptrdiff_t pos_byte, ptrdiff_t end,
3176 Lisp_Object val)
3178 int initial_buf[16];
3179 int *buf = initial_buf;
3180 ptrdiff_t buf_size = ARRAYELTS (initial_buf);
3181 int *bufalloc = 0;
3182 ptrdiff_t buf_used = 0;
3183 Lisp_Object result = Qnil;
3185 for (; CONSP (val); val = XCDR (val))
3187 Lisp_Object elt;
3188 ptrdiff_t len, i;
3190 elt = XCAR (val);
3191 if (! CONSP (elt))
3192 continue;
3193 elt = XCAR (elt);
3194 if (! VECTORP (elt))
3195 continue;
3196 len = ASIZE (elt);
3197 if (len <= end - pos)
3199 for (i = 0; i < len; i++)
3201 if (buf_used <= i)
3203 unsigned char *p = BYTE_POS_ADDR (pos_byte);
3204 int len1;
3206 if (buf_used == buf_size)
3208 bufalloc = xpalloc (bufalloc, &buf_size, 1, -1,
3209 sizeof *bufalloc);
3210 if (buf == initial_buf)
3211 memcpy (bufalloc, buf, sizeof initial_buf);
3212 buf = bufalloc;
3214 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
3215 pos_byte += len1;
3217 if (XINT (AREF (elt, i)) != buf[i])
3218 break;
3220 if (i == len)
3222 result = XCAR (val);
3223 break;
3228 xfree (bufalloc);
3229 return result;
3233 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3234 Stranslate_region_internal, 3, 3, 0,
3235 doc: /* Internal use only.
3236 From START to END, translate characters according to TABLE.
3237 TABLE is a string or a char-table; the Nth character in it is the
3238 mapping for the character with code N.
3239 It returns the number of characters changed. */)
3240 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
3242 register unsigned char *tt; /* Trans table. */
3243 register int nc; /* New character. */
3244 int cnt; /* Number of changes made. */
3245 ptrdiff_t size; /* Size of translate table. */
3246 ptrdiff_t pos, pos_byte, end_pos;
3247 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3248 bool string_multibyte IF_LINT (= 0);
3250 validate_region (&start, &end);
3251 if (CHAR_TABLE_P (table))
3253 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3254 error ("Not a translation table");
3255 size = MAX_CHAR;
3256 tt = NULL;
3258 else
3260 CHECK_STRING (table);
3262 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3263 table = string_make_unibyte (table);
3264 string_multibyte = SCHARS (table) < SBYTES (table);
3265 size = SBYTES (table);
3266 tt = SDATA (table);
3269 pos = XINT (start);
3270 pos_byte = CHAR_TO_BYTE (pos);
3271 end_pos = XINT (end);
3272 modify_text (pos, end_pos);
3274 cnt = 0;
3275 for (; pos < end_pos; )
3277 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3278 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3279 int len, str_len;
3280 int oc;
3281 Lisp_Object val;
3283 if (multibyte)
3284 oc = STRING_CHAR_AND_LENGTH (p, len);
3285 else
3286 oc = *p, len = 1;
3287 if (oc < size)
3289 if (tt)
3291 /* Reload as signal_after_change in last iteration may GC. */
3292 tt = SDATA (table);
3293 if (string_multibyte)
3295 str = tt + string_char_to_byte (table, oc);
3296 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3298 else
3300 nc = tt[oc];
3301 if (! ASCII_CHAR_P (nc) && multibyte)
3303 str_len = BYTE8_STRING (nc, buf);
3304 str = buf;
3306 else
3308 str_len = 1;
3309 str = tt + oc;
3313 else
3315 nc = oc;
3316 val = CHAR_TABLE_REF (table, oc);
3317 if (CHARACTERP (val))
3319 nc = XFASTINT (val);
3320 str_len = CHAR_STRING (nc, buf);
3321 str = buf;
3323 else if (VECTORP (val) || (CONSP (val)))
3325 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3326 where TO is TO-CHAR or [TO-CHAR ...]. */
3327 nc = -1;
3331 if (nc != oc && nc >= 0)
3333 /* Simple one char to one char translation. */
3334 if (len != str_len)
3336 Lisp_Object string;
3338 /* This is less efficient, because it moves the gap,
3339 but it should handle multibyte characters correctly. */
3340 string = make_multibyte_string ((char *) str, 1, str_len);
3341 replace_range (pos, pos + 1, string, 1, 0, 1);
3342 len = str_len;
3344 else
3346 record_change (pos, 1);
3347 while (str_len-- > 0)
3348 *p++ = *str++;
3349 signal_after_change (pos, 1, 1);
3350 update_compositions (pos, pos + 1, CHECK_BORDER);
3352 ++cnt;
3354 else if (nc < 0)
3356 Lisp_Object string;
3358 if (CONSP (val))
3360 val = check_translation (pos, pos_byte, end_pos, val);
3361 if (NILP (val))
3363 pos_byte += len;
3364 pos++;
3365 continue;
3367 /* VAL is ([FROM-CHAR ...] . TO). */
3368 len = ASIZE (XCAR (val));
3369 val = XCDR (val);
3371 else
3372 len = 1;
3374 if (VECTORP (val))
3376 string = Fconcat (1, &val);
3378 else
3380 string = Fmake_string (make_number (1), val);
3382 replace_range (pos, pos + len, string, 1, 0, 1);
3383 pos_byte += SBYTES (string);
3384 pos += SCHARS (string);
3385 cnt += SCHARS (string);
3386 end_pos += SCHARS (string) - len;
3387 continue;
3390 pos_byte += len;
3391 pos++;
3394 return make_number (cnt);
3397 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3398 doc: /* Delete the text between START and END.
3399 If called interactively, delete the region between point and mark.
3400 This command deletes buffer text without modifying the kill ring. */)
3401 (Lisp_Object start, Lisp_Object end)
3403 validate_region (&start, &end);
3404 del_range (XINT (start), XINT (end));
3405 return Qnil;
3408 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3409 Sdelete_and_extract_region, 2, 2, 0,
3410 doc: /* Delete the text between START and END and return it. */)
3411 (Lisp_Object start, Lisp_Object end)
3413 validate_region (&start, &end);
3414 if (XINT (start) == XINT (end))
3415 return empty_unibyte_string;
3416 return del_range_1 (XINT (start), XINT (end), 1, 1);
3419 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3420 doc: /* Remove restrictions (narrowing) from current buffer.
3421 This allows the buffer's full text to be seen and edited. */)
3422 (void)
3424 if (BEG != BEGV || Z != ZV)
3425 current_buffer->clip_changed = 1;
3426 BEGV = BEG;
3427 BEGV_BYTE = BEG_BYTE;
3428 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3429 /* Changing the buffer bounds invalidates any recorded current column. */
3430 invalidate_current_column ();
3431 return Qnil;
3434 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3435 doc: /* Restrict editing in this buffer to the current region.
3436 The rest of the text becomes temporarily invisible and untouchable
3437 but is not deleted; if you save the buffer in a file, the invisible
3438 text is included in the file. \\[widen] makes all visible again.
3439 See also `save-restriction'.
3441 When calling from a program, pass two arguments; positions (integers
3442 or markers) bounding the text that should remain visible. */)
3443 (register Lisp_Object start, Lisp_Object end)
3445 CHECK_NUMBER_COERCE_MARKER (start);
3446 CHECK_NUMBER_COERCE_MARKER (end);
3448 if (XINT (start) > XINT (end))
3450 Lisp_Object tem;
3451 tem = start; start = end; end = tem;
3454 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3455 args_out_of_range (start, end);
3457 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3458 current_buffer->clip_changed = 1;
3460 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3461 SET_BUF_ZV (current_buffer, XFASTINT (end));
3462 if (PT < XFASTINT (start))
3463 SET_PT (XFASTINT (start));
3464 if (PT > XFASTINT (end))
3465 SET_PT (XFASTINT (end));
3466 /* Changing the buffer bounds invalidates any recorded current column. */
3467 invalidate_current_column ();
3468 return Qnil;
3471 Lisp_Object
3472 save_restriction_save (void)
3474 if (BEGV == BEG && ZV == Z)
3475 /* The common case that the buffer isn't narrowed.
3476 We return just the buffer object, which save_restriction_restore
3477 recognizes as meaning `no restriction'. */
3478 return Fcurrent_buffer ();
3479 else
3480 /* We have to save a restriction, so return a pair of markers, one
3481 for the beginning and one for the end. */
3483 Lisp_Object beg, end;
3485 beg = build_marker (current_buffer, BEGV, BEGV_BYTE);
3486 end = build_marker (current_buffer, ZV, ZV_BYTE);
3488 /* END must move forward if text is inserted at its exact location. */
3489 XMARKER (end)->insertion_type = 1;
3491 return Fcons (beg, end);
3495 void
3496 save_restriction_restore (Lisp_Object data)
3498 struct buffer *cur = NULL;
3499 struct buffer *buf = (CONSP (data)
3500 ? XMARKER (XCAR (data))->buffer
3501 : XBUFFER (data));
3503 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3504 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3505 is the case if it is or has an indirect buffer), then make
3506 sure it is current before we update BEGV, so
3507 set_buffer_internal takes care of managing those markers. */
3508 cur = current_buffer;
3509 set_buffer_internal (buf);
3512 if (CONSP (data))
3513 /* A pair of marks bounding a saved restriction. */
3515 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3516 struct Lisp_Marker *end = XMARKER (XCDR (data));
3517 eassert (buf == end->buffer);
3519 if (buf /* Verify marker still points to a buffer. */
3520 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3521 /* The restriction has changed from the saved one, so restore
3522 the saved restriction. */
3524 ptrdiff_t pt = BUF_PT (buf);
3526 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3527 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3529 if (pt < beg->charpos || pt > end->charpos)
3530 /* The point is outside the new visible range, move it inside. */
3531 SET_BUF_PT_BOTH (buf,
3532 clip_to_bounds (beg->charpos, pt, end->charpos),
3533 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3534 end->bytepos));
3536 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3538 /* These aren't needed anymore, so don't wait for GC. */
3539 free_marker (XCAR (data));
3540 free_marker (XCDR (data));
3541 free_cons (XCONS (data));
3543 else
3544 /* A buffer, which means that there was no old restriction. */
3546 if (buf /* Verify marker still points to a buffer. */
3547 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3548 /* The buffer has been narrowed, get rid of the narrowing. */
3550 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3551 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3553 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3557 /* Changing the buffer bounds invalidates any recorded current column. */
3558 invalidate_current_column ();
3560 if (cur)
3561 set_buffer_internal (cur);
3564 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3565 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3566 The buffer's restrictions make parts of the beginning and end invisible.
3567 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3568 This special form, `save-restriction', saves the current buffer's restrictions
3569 when it is entered, and restores them when it is exited.
3570 So any `narrow-to-region' within BODY lasts only until the end of the form.
3571 The old restrictions settings are restored
3572 even in case of abnormal exit (throw or error).
3574 The value returned is the value of the last form in BODY.
3576 Note: if you are using both `save-excursion' and `save-restriction',
3577 use `save-excursion' outermost:
3578 (save-excursion (save-restriction ...))
3580 usage: (save-restriction &rest BODY) */)
3581 (Lisp_Object body)
3583 register Lisp_Object val;
3584 ptrdiff_t count = SPECPDL_INDEX ();
3586 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3587 val = Fprogn (body);
3588 return unbind_to (count, val);
3591 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3592 doc: /* Display a message at the bottom of the screen.
3593 The message also goes into the `*Messages*' buffer, if `message-log-max'
3594 is non-nil. (In keyboard macros, that's all it does.)
3595 Return the message.
3597 In batch mode, the message is printed to the standard error stream,
3598 followed by a newline.
3600 The first argument is a format control string, and the rest are data
3601 to be formatted under control of the string. See `format' for details.
3603 Note: Use (message "%s" VALUE) to print the value of expressions and
3604 variables to avoid accidentally interpreting `%' as format specifiers.
3606 If the first argument is nil or the empty string, the function clears
3607 any existing message; this lets the minibuffer contents show. See
3608 also `current-message'.
3610 usage: (message FORMAT-STRING &rest ARGS) */)
3611 (ptrdiff_t nargs, Lisp_Object *args)
3613 if (NILP (args[0])
3614 || (STRINGP (args[0])
3615 && SBYTES (args[0]) == 0))
3617 message1 (0);
3618 return args[0];
3620 else
3622 register Lisp_Object val;
3623 val = Fformat (nargs, args);
3624 message3 (val);
3625 return val;
3629 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3630 doc: /* Display a message, in a dialog box if possible.
3631 If a dialog box is not available, use the echo area.
3632 The first argument is a format control string, and the rest are data
3633 to be formatted under control of the string. See `format' for details.
3635 If the first argument is nil or the empty string, clear any existing
3636 message; let the minibuffer contents show.
3638 usage: (message-box FORMAT-STRING &rest ARGS) */)
3639 (ptrdiff_t nargs, Lisp_Object *args)
3641 if (NILP (args[0]))
3643 message1 (0);
3644 return Qnil;
3646 else
3648 Lisp_Object val = Fformat (nargs, args);
3649 Lisp_Object pane, menu;
3650 struct gcpro gcpro1;
3652 pane = list1 (Fcons (build_string ("OK"), Qt));
3653 GCPRO1 (pane);
3654 menu = Fcons (val, pane);
3655 Fx_popup_dialog (Qt, menu, Qt);
3656 UNGCPRO;
3657 return val;
3661 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3662 doc: /* Display a message in a dialog box or in the echo area.
3663 If this command was invoked with the mouse, use a dialog box if
3664 `use-dialog-box' is non-nil.
3665 Otherwise, use the echo area.
3666 The first argument is a format control string, and the rest are data
3667 to be formatted under control of the string. See `format' for details.
3669 If the first argument is nil or the empty string, clear any existing
3670 message; let the minibuffer contents show.
3672 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3673 (ptrdiff_t nargs, Lisp_Object *args)
3675 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3676 && use_dialog_box)
3677 return Fmessage_box (nargs, args);
3678 return Fmessage (nargs, args);
3681 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3682 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3683 (void)
3685 return current_message ();
3689 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3690 doc: /* Return a copy of STRING with text properties added.
3691 First argument is the string to copy.
3692 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3693 properties to add to the result.
3694 usage: (propertize STRING &rest PROPERTIES) */)
3695 (ptrdiff_t nargs, Lisp_Object *args)
3697 Lisp_Object properties, string;
3698 struct gcpro gcpro1, gcpro2;
3699 ptrdiff_t i;
3701 /* Number of args must be odd. */
3702 if ((nargs & 1) == 0)
3703 error ("Wrong number of arguments");
3705 properties = string = Qnil;
3706 GCPRO2 (properties, string);
3708 /* First argument must be a string. */
3709 CHECK_STRING (args[0]);
3710 string = Fcopy_sequence (args[0]);
3712 for (i = 1; i < nargs; i += 2)
3713 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3715 Fadd_text_properties (make_number (0),
3716 make_number (SCHARS (string)),
3717 properties, string);
3718 RETURN_UNGCPRO (string);
3721 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3722 doc: /* Format a string out of a format-string and arguments.
3723 The first argument is a format control string.
3724 The other arguments are substituted into it to make the result, a string.
3726 The format control string may contain %-sequences meaning to substitute
3727 the next available argument:
3729 %s means print a string argument. Actually, prints any object, with `princ'.
3730 %d means print as number in decimal (%o octal, %x hex).
3731 %X is like %x, but uses upper case.
3732 %e means print a number in exponential notation.
3733 %f means print a number in decimal-point notation.
3734 %g means print a number in exponential notation
3735 or decimal-point notation, whichever uses fewer characters.
3736 %c means print a number as a single character.
3737 %S means print any object as an s-expression (using `prin1').
3739 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3740 Use %% to put a single % into the output.
3742 A %-sequence may contain optional flag, width, and precision
3743 specifiers, as follows:
3745 %<flags><width><precision>character
3747 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3749 The + flag character inserts a + before any positive number, while a
3750 space inserts a space before any positive number; these flags only
3751 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3752 The - and 0 flags affect the width specifier, as described below.
3754 The # flag means to use an alternate display form for %o, %x, %X, %e,
3755 %f, and %g sequences: for %o, it ensures that the result begins with
3756 \"0\"; for %x and %X, it prefixes the result with \"0x\" or \"0X\";
3757 for %e, %f, and %g, it causes a decimal point to be included even if
3758 the precision is zero.
3760 The width specifier supplies a lower limit for the length of the
3761 printed representation. The padding, if any, normally goes on the
3762 left, but it goes on the right if the - flag is present. The padding
3763 character is normally a space, but it is 0 if the 0 flag is present.
3764 The 0 flag is ignored if the - flag is present, or the format sequence
3765 is something other than %d, %e, %f, and %g.
3767 For %e, %f, and %g sequences, the number after the "." in the
3768 precision specifier says how many decimal places to show; if zero, the
3769 decimal point itself is omitted. For %s and %S, the precision
3770 specifier truncates the string to the given width.
3772 usage: (format STRING &rest OBJECTS) */)
3773 (ptrdiff_t nargs, Lisp_Object *args)
3775 ptrdiff_t n; /* The number of the next arg to substitute. */
3776 char initial_buffer[4000];
3777 char *buf = initial_buffer;
3778 ptrdiff_t bufsize = sizeof initial_buffer;
3779 ptrdiff_t max_bufsize = STRING_BYTES_BOUND + 1;
3780 char *p;
3781 ptrdiff_t buf_save_value_index IF_LINT (= 0);
3782 char *format, *end, *format_start;
3783 ptrdiff_t formatlen, nchars;
3784 /* True if the format is multibyte. */
3785 bool multibyte_format = 0;
3786 /* True if the output should be a multibyte string,
3787 which is true if any of the inputs is one. */
3788 bool multibyte = 0;
3789 /* When we make a multibyte string, we must pay attention to the
3790 byte combining problem, i.e., a byte may be combined with a
3791 multibyte character of the previous string. This flag tells if we
3792 must consider such a situation or not. */
3793 bool maybe_combine_byte;
3794 Lisp_Object val;
3795 bool arg_intervals = 0;
3796 USE_SAFE_ALLOCA;
3798 /* discarded[I] is 1 if byte I of the format
3799 string was not copied into the output.
3800 It is 2 if byte I was not the first byte of its character. */
3801 char *discarded;
3803 /* Each element records, for one argument,
3804 the start and end bytepos in the output string,
3805 whether the argument has been converted to string (e.g., due to "%S"),
3806 and whether the argument is a string with intervals.
3807 info[0] is unused. Unused elements have -1 for start. */
3808 struct info
3810 ptrdiff_t start, end;
3811 bool_bf converted_to_string : 1;
3812 bool_bf intervals : 1;
3813 } *info = 0;
3815 /* It should not be necessary to GCPRO ARGS, because
3816 the caller in the interpreter should take care of that. */
3818 CHECK_STRING (args[0]);
3819 format_start = SSDATA (args[0]);
3820 formatlen = SBYTES (args[0]);
3822 /* Allocate the info and discarded tables. */
3824 ptrdiff_t i;
3825 if ((SIZE_MAX - formatlen) / sizeof (struct info) <= nargs)
3826 memory_full (SIZE_MAX);
3827 info = SAFE_ALLOCA ((nargs + 1) * sizeof *info + formatlen);
3828 discarded = (char *) &info[nargs + 1];
3829 for (i = 0; i < nargs + 1; i++)
3831 info[i].start = -1;
3832 info[i].intervals = info[i].converted_to_string = 0;
3834 memset (discarded, 0, formatlen);
3837 /* Try to determine whether the result should be multibyte.
3838 This is not always right; sometimes the result needs to be multibyte
3839 because of an object that we will pass through prin1,
3840 and in that case, we won't know it here. */
3841 multibyte_format = STRING_MULTIBYTE (args[0]);
3842 multibyte = multibyte_format;
3843 for (n = 1; !multibyte && n < nargs; n++)
3844 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3845 multibyte = 1;
3847 /* If we start out planning a unibyte result,
3848 then discover it has to be multibyte, we jump back to retry. */
3849 retry:
3851 p = buf;
3852 nchars = 0;
3853 n = 0;
3855 /* Scan the format and store result in BUF. */
3856 format = format_start;
3857 end = format + formatlen;
3858 maybe_combine_byte = 0;
3860 while (format != end)
3862 /* The values of N and FORMAT when the loop body is entered. */
3863 ptrdiff_t n0 = n;
3864 char *format0 = format;
3866 /* Bytes needed to represent the output of this conversion. */
3867 ptrdiff_t convbytes;
3869 if (*format == '%')
3871 /* General format specifications look like
3873 '%' [flags] [field-width] [precision] format
3875 where
3877 flags ::= [-+0# ]+
3878 field-width ::= [0-9]+
3879 precision ::= '.' [0-9]*
3881 If a field-width is specified, it specifies to which width
3882 the output should be padded with blanks, if the output
3883 string is shorter than field-width.
3885 If precision is specified, it specifies the number of
3886 digits to print after the '.' for floats, or the max.
3887 number of chars to print from a string. */
3889 bool minus_flag = 0;
3890 bool plus_flag = 0;
3891 bool space_flag = 0;
3892 bool sharp_flag = 0;
3893 bool zero_flag = 0;
3894 ptrdiff_t field_width;
3895 bool precision_given;
3896 uintmax_t precision = UINTMAX_MAX;
3897 char *num_end;
3898 char conversion;
3900 while (1)
3902 switch (*++format)
3904 case '-': minus_flag = 1; continue;
3905 case '+': plus_flag = 1; continue;
3906 case ' ': space_flag = 1; continue;
3907 case '#': sharp_flag = 1; continue;
3908 case '0': zero_flag = 1; continue;
3910 break;
3913 /* Ignore flags when sprintf ignores them. */
3914 space_flag &= ~ plus_flag;
3915 zero_flag &= ~ minus_flag;
3918 uintmax_t w = strtoumax (format, &num_end, 10);
3919 if (max_bufsize <= w)
3920 string_overflow ();
3921 field_width = w;
3923 precision_given = *num_end == '.';
3924 if (precision_given)
3925 precision = strtoumax (num_end + 1, &num_end, 10);
3926 format = num_end;
3928 if (format == end)
3929 error ("Format string ends in middle of format specifier");
3931 memset (&discarded[format0 - format_start], 1, format - format0);
3932 conversion = *format;
3933 if (conversion == '%')
3934 goto copy_char;
3935 discarded[format - format_start] = 1;
3936 format++;
3938 ++n;
3939 if (! (n < nargs))
3940 error ("Not enough arguments for format string");
3942 /* For 'S', prin1 the argument, and then treat like 's'.
3943 For 's', princ any argument that is not a string or
3944 symbol. But don't do this conversion twice, which might
3945 happen after retrying. */
3946 if ((conversion == 'S'
3947 || (conversion == 's'
3948 && ! STRINGP (args[n]) && ! SYMBOLP (args[n]))))
3950 if (! info[n].converted_to_string)
3952 Lisp_Object noescape = conversion == 'S' ? Qnil : Qt;
3953 args[n] = Fprin1_to_string (args[n], noescape);
3954 info[n].converted_to_string = 1;
3955 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3957 multibyte = 1;
3958 goto retry;
3961 conversion = 's';
3963 else if (conversion == 'c')
3965 if (FLOATP (args[n]))
3967 double d = XFLOAT_DATA (args[n]);
3968 args[n] = make_number (FIXNUM_OVERFLOW_P (d) ? -1 : d);
3971 if (INTEGERP (args[n]) && ! ASCII_CHAR_P (XINT (args[n])))
3973 if (!multibyte)
3975 multibyte = 1;
3976 goto retry;
3978 args[n] = Fchar_to_string (args[n]);
3979 info[n].converted_to_string = 1;
3982 if (info[n].converted_to_string)
3983 conversion = 's';
3984 zero_flag = 0;
3987 if (SYMBOLP (args[n]))
3989 args[n] = SYMBOL_NAME (args[n]);
3990 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3992 multibyte = 1;
3993 goto retry;
3997 if (conversion == 's')
3999 /* handle case (precision[n] >= 0) */
4001 ptrdiff_t width, padding, nbytes;
4002 ptrdiff_t nchars_string;
4004 ptrdiff_t prec = -1;
4005 if (precision_given && precision <= TYPE_MAXIMUM (ptrdiff_t))
4006 prec = precision;
4008 /* lisp_string_width ignores a precision of 0, but GNU
4009 libc functions print 0 characters when the precision
4010 is 0. Imitate libc behavior here. Changing
4011 lisp_string_width is the right thing, and will be
4012 done, but meanwhile we work with it. */
4014 if (prec == 0)
4015 width = nchars_string = nbytes = 0;
4016 else
4018 ptrdiff_t nch, nby;
4019 width = lisp_string_width (args[n], prec, &nch, &nby);
4020 if (prec < 0)
4022 nchars_string = SCHARS (args[n]);
4023 nbytes = SBYTES (args[n]);
4025 else
4027 nchars_string = nch;
4028 nbytes = nby;
4032 convbytes = nbytes;
4033 if (convbytes && multibyte && ! STRING_MULTIBYTE (args[n]))
4034 convbytes = count_size_as_multibyte (SDATA (args[n]), nbytes);
4036 padding = width < field_width ? field_width - width : 0;
4038 if (max_bufsize - padding <= convbytes)
4039 string_overflow ();
4040 convbytes += padding;
4041 if (convbytes <= buf + bufsize - p)
4043 if (! minus_flag)
4045 memset (p, ' ', padding);
4046 p += padding;
4047 nchars += padding;
4050 if (p > buf
4051 && multibyte
4052 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4053 && STRING_MULTIBYTE (args[n])
4054 && !CHAR_HEAD_P (SREF (args[n], 0)))
4055 maybe_combine_byte = 1;
4057 p += copy_text (SDATA (args[n]), (unsigned char *) p,
4058 nbytes,
4059 STRING_MULTIBYTE (args[n]), multibyte);
4061 info[n].start = nchars;
4062 nchars += nchars_string;
4063 info[n].end = nchars;
4065 if (minus_flag)
4067 memset (p, ' ', padding);
4068 p += padding;
4069 nchars += padding;
4072 /* If this argument has text properties, record where
4073 in the result string it appears. */
4074 if (string_intervals (args[n]))
4075 info[n].intervals = arg_intervals = 1;
4077 continue;
4080 else if (! (conversion == 'c' || conversion == 'd'
4081 || conversion == 'e' || conversion == 'f'
4082 || conversion == 'g' || conversion == 'i'
4083 || conversion == 'o' || conversion == 'x'
4084 || conversion == 'X'))
4085 error ("Invalid format operation %%%c",
4086 STRING_CHAR ((unsigned char *) format - 1));
4087 else if (! (INTEGERP (args[n]) || FLOATP (args[n])))
4088 error ("Format specifier doesn't match argument type");
4089 else
4091 enum
4093 /* Maximum precision for a %f conversion such that the
4094 trailing output digit might be nonzero. Any precision
4095 larger than this will not yield useful information. */
4096 USEFUL_PRECISION_MAX =
4097 ((1 - DBL_MIN_EXP)
4098 * (FLT_RADIX == 2 || FLT_RADIX == 10 ? 1
4099 : FLT_RADIX == 16 ? 4
4100 : -1)),
4102 /* Maximum number of bytes generated by any format, if
4103 precision is no more than USEFUL_PRECISION_MAX.
4104 On all practical hosts, %f is the worst case. */
4105 SPRINTF_BUFSIZE =
4106 sizeof "-." + (DBL_MAX_10_EXP + 1) + USEFUL_PRECISION_MAX,
4108 /* Length of pM (that is, of pMd without the
4109 trailing "d"). */
4110 pMlen = sizeof pMd - 2
4112 verify (USEFUL_PRECISION_MAX > 0);
4114 int prec;
4115 ptrdiff_t padding, sprintf_bytes;
4116 uintmax_t excess_precision, numwidth;
4117 uintmax_t leading_zeros = 0, trailing_zeros = 0;
4119 char sprintf_buf[SPRINTF_BUFSIZE];
4121 /* Copy of conversion specification, modified somewhat.
4122 At most three flags F can be specified at once. */
4123 char convspec[sizeof "%FFF.*d" + pMlen];
4125 /* Avoid undefined behavior in underlying sprintf. */
4126 if (conversion == 'd' || conversion == 'i')
4127 sharp_flag = 0;
4129 /* Create the copy of the conversion specification, with
4130 any width and precision removed, with ".*" inserted,
4131 and with pM inserted for integer formats. */
4133 char *f = convspec;
4134 *f++ = '%';
4135 *f = '-'; f += minus_flag;
4136 *f = '+'; f += plus_flag;
4137 *f = ' '; f += space_flag;
4138 *f = '#'; f += sharp_flag;
4139 *f = '0'; f += zero_flag;
4140 *f++ = '.';
4141 *f++ = '*';
4142 if (conversion == 'd' || conversion == 'i'
4143 || conversion == 'o' || conversion == 'x'
4144 || conversion == 'X')
4146 memcpy (f, pMd, pMlen);
4147 f += pMlen;
4148 zero_flag &= ~ precision_given;
4150 *f++ = conversion;
4151 *f = '\0';
4154 prec = -1;
4155 if (precision_given)
4156 prec = min (precision, USEFUL_PRECISION_MAX);
4158 /* Use sprintf to format this number into sprintf_buf. Omit
4159 padding and excess precision, though, because sprintf limits
4160 output length to INT_MAX.
4162 There are four types of conversion: double, unsigned
4163 char (passed as int), wide signed int, and wide
4164 unsigned int. Treat them separately because the
4165 sprintf ABI is sensitive to which type is passed. Be
4166 careful about integer overflow, NaNs, infinities, and
4167 conversions; for example, the min and max macros are
4168 not suitable here. */
4169 if (conversion == 'e' || conversion == 'f' || conversion == 'g')
4171 double x = (INTEGERP (args[n])
4172 ? XINT (args[n])
4173 : XFLOAT_DATA (args[n]));
4174 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4176 else if (conversion == 'c')
4178 /* Don't use sprintf here, as it might mishandle prec. */
4179 sprintf_buf[0] = XINT (args[n]);
4180 sprintf_bytes = prec != 0;
4182 else if (conversion == 'd')
4184 /* For float, maybe we should use "%1.0f"
4185 instead so it also works for values outside
4186 the integer range. */
4187 printmax_t x;
4188 if (INTEGERP (args[n]))
4189 x = XINT (args[n]);
4190 else
4192 double d = XFLOAT_DATA (args[n]);
4193 if (d < 0)
4195 x = TYPE_MINIMUM (printmax_t);
4196 if (x < d)
4197 x = d;
4199 else
4201 x = TYPE_MAXIMUM (printmax_t);
4202 if (d < x)
4203 x = d;
4206 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4208 else
4210 /* Don't sign-extend for octal or hex printing. */
4211 uprintmax_t x;
4212 if (INTEGERP (args[n]))
4213 x = XUINT (args[n]);
4214 else
4216 double d = XFLOAT_DATA (args[n]);
4217 if (d < 0)
4218 x = 0;
4219 else
4221 x = TYPE_MAXIMUM (uprintmax_t);
4222 if (d < x)
4223 x = d;
4226 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4229 /* Now the length of the formatted item is known, except it omits
4230 padding and excess precision. Deal with excess precision
4231 first. This happens only when the format specifies
4232 ridiculously large precision. */
4233 excess_precision = precision - prec;
4234 if (excess_precision)
4236 if (conversion == 'e' || conversion == 'f'
4237 || conversion == 'g')
4239 if ((conversion == 'g' && ! sharp_flag)
4240 || ! ('0' <= sprintf_buf[sprintf_bytes - 1]
4241 && sprintf_buf[sprintf_bytes - 1] <= '9'))
4242 excess_precision = 0;
4243 else
4245 if (conversion == 'g')
4247 char *dot = strchr (sprintf_buf, '.');
4248 if (!dot)
4249 excess_precision = 0;
4252 trailing_zeros = excess_precision;
4254 else
4255 leading_zeros = excess_precision;
4258 /* Compute the total bytes needed for this item, including
4259 excess precision and padding. */
4260 numwidth = sprintf_bytes + excess_precision;
4261 padding = numwidth < field_width ? field_width - numwidth : 0;
4262 if (max_bufsize - sprintf_bytes <= excess_precision
4263 || max_bufsize - padding <= numwidth)
4264 string_overflow ();
4265 convbytes = numwidth + padding;
4267 if (convbytes <= buf + bufsize - p)
4269 /* Copy the formatted item from sprintf_buf into buf,
4270 inserting padding and excess-precision zeros. */
4272 char *src = sprintf_buf;
4273 char src0 = src[0];
4274 int exponent_bytes = 0;
4275 bool signedp = src0 == '-' || src0 == '+' || src0 == ' ';
4276 int significand_bytes;
4277 if (zero_flag
4278 && ((src[signedp] >= '0' && src[signedp] <= '9')
4279 || (src[signedp] >= 'a' && src[signedp] <= 'f')
4280 || (src[signedp] >= 'A' && src[signedp] <= 'F')))
4282 leading_zeros += padding;
4283 padding = 0;
4286 if (excess_precision
4287 && (conversion == 'e' || conversion == 'g'))
4289 char *e = strchr (src, 'e');
4290 if (e)
4291 exponent_bytes = src + sprintf_bytes - e;
4294 if (! minus_flag)
4296 memset (p, ' ', padding);
4297 p += padding;
4298 nchars += padding;
4301 *p = src0;
4302 src += signedp;
4303 p += signedp;
4304 memset (p, '0', leading_zeros);
4305 p += leading_zeros;
4306 significand_bytes = sprintf_bytes - signedp - exponent_bytes;
4307 memcpy (p, src, significand_bytes);
4308 p += significand_bytes;
4309 src += significand_bytes;
4310 memset (p, '0', trailing_zeros);
4311 p += trailing_zeros;
4312 memcpy (p, src, exponent_bytes);
4313 p += exponent_bytes;
4315 info[n].start = nchars;
4316 nchars += leading_zeros + sprintf_bytes + trailing_zeros;
4317 info[n].end = nchars;
4319 if (minus_flag)
4321 memset (p, ' ', padding);
4322 p += padding;
4323 nchars += padding;
4326 continue;
4330 else
4331 copy_char:
4333 /* Copy a single character from format to buf. */
4335 char *src = format;
4336 unsigned char str[MAX_MULTIBYTE_LENGTH];
4338 if (multibyte_format)
4340 /* Copy a whole multibyte character. */
4341 if (p > buf
4342 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4343 && !CHAR_HEAD_P (*format))
4344 maybe_combine_byte = 1;
4347 format++;
4348 while (! CHAR_HEAD_P (*format));
4350 convbytes = format - src;
4351 memset (&discarded[src + 1 - format_start], 2, convbytes - 1);
4353 else
4355 unsigned char uc = *format++;
4356 if (! multibyte || ASCII_CHAR_P (uc))
4357 convbytes = 1;
4358 else
4360 int c = BYTE8_TO_CHAR (uc);
4361 convbytes = CHAR_STRING (c, str);
4362 src = (char *) str;
4366 if (convbytes <= buf + bufsize - p)
4368 memcpy (p, src, convbytes);
4369 p += convbytes;
4370 nchars++;
4371 continue;
4375 /* There wasn't enough room to store this conversion or single
4376 character. CONVBYTES says how much room is needed. Allocate
4377 enough room (and then some) and do it again. */
4379 ptrdiff_t used = p - buf;
4381 if (max_bufsize - used < convbytes)
4382 string_overflow ();
4383 bufsize = used + convbytes;
4384 bufsize = bufsize < max_bufsize / 2 ? bufsize * 2 : max_bufsize;
4386 if (buf == initial_buffer)
4388 buf = xmalloc (bufsize);
4389 sa_must_free = true;
4390 buf_save_value_index = SPECPDL_INDEX ();
4391 record_unwind_protect_ptr (xfree, buf);
4392 memcpy (buf, initial_buffer, used);
4394 else
4396 buf = xrealloc (buf, bufsize);
4397 set_unwind_protect_ptr (buf_save_value_index, xfree, buf);
4400 p = buf + used;
4403 format = format0;
4404 n = n0;
4407 if (bufsize < p - buf)
4408 emacs_abort ();
4410 if (maybe_combine_byte)
4411 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4412 val = make_specified_string (buf, nchars, p - buf, multibyte);
4414 /* If the format string has text properties, or any of the string
4415 arguments has text properties, set up text properties of the
4416 result string. */
4418 if (string_intervals (args[0]) || arg_intervals)
4420 Lisp_Object len, new_len, props;
4421 struct gcpro gcpro1;
4423 /* Add text properties from the format string. */
4424 len = make_number (SCHARS (args[0]));
4425 props = text_property_list (args[0], make_number (0), len, Qnil);
4426 GCPRO1 (props);
4428 if (CONSP (props))
4430 ptrdiff_t bytepos = 0, position = 0, translated = 0;
4431 ptrdiff_t argn = 1;
4432 Lisp_Object list;
4434 /* Adjust the bounds of each text property
4435 to the proper start and end in the output string. */
4437 /* Put the positions in PROPS in increasing order, so that
4438 we can do (effectively) one scan through the position
4439 space of the format string. */
4440 props = Fnreverse (props);
4442 /* BYTEPOS is the byte position in the format string,
4443 POSITION is the untranslated char position in it,
4444 TRANSLATED is the translated char position in BUF,
4445 and ARGN is the number of the next arg we will come to. */
4446 for (list = props; CONSP (list); list = XCDR (list))
4448 Lisp_Object item;
4449 ptrdiff_t pos;
4451 item = XCAR (list);
4453 /* First adjust the property start position. */
4454 pos = XINT (XCAR (item));
4456 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4457 up to this position. */
4458 for (; position < pos; bytepos++)
4460 if (! discarded[bytepos])
4461 position++, translated++;
4462 else if (discarded[bytepos] == 1)
4464 position++;
4465 if (translated == info[argn].start)
4467 translated += info[argn].end - info[argn].start;
4468 argn++;
4473 XSETCAR (item, make_number (translated));
4475 /* Likewise adjust the property end position. */
4476 pos = XINT (XCAR (XCDR (item)));
4478 for (; position < pos; bytepos++)
4480 if (! discarded[bytepos])
4481 position++, translated++;
4482 else if (discarded[bytepos] == 1)
4484 position++;
4485 if (translated == info[argn].start)
4487 translated += info[argn].end - info[argn].start;
4488 argn++;
4493 XSETCAR (XCDR (item), make_number (translated));
4496 add_text_properties_from_list (val, props, make_number (0));
4499 /* Add text properties from arguments. */
4500 if (arg_intervals)
4501 for (n = 1; n < nargs; ++n)
4502 if (info[n].intervals)
4504 len = make_number (SCHARS (args[n]));
4505 new_len = make_number (info[n].end - info[n].start);
4506 props = text_property_list (args[n], make_number (0), len, Qnil);
4507 props = extend_property_ranges (props, new_len);
4508 /* If successive arguments have properties, be sure that
4509 the value of `composition' property be the copy. */
4510 if (n > 1 && info[n - 1].end)
4511 make_composition_value_copy (props);
4512 add_text_properties_from_list (val, props,
4513 make_number (info[n].start));
4516 UNGCPRO;
4519 /* If we allocated BUF or INFO with malloc, free it too. */
4520 SAFE_FREE ();
4522 return val;
4525 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4526 doc: /* Return t if two characters match, optionally ignoring case.
4527 Both arguments must be characters (i.e. integers).
4528 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4529 (register Lisp_Object c1, Lisp_Object c2)
4531 int i1, i2;
4532 /* Check they're chars, not just integers, otherwise we could get array
4533 bounds violations in downcase. */
4534 CHECK_CHARACTER (c1);
4535 CHECK_CHARACTER (c2);
4537 if (XINT (c1) == XINT (c2))
4538 return Qt;
4539 if (NILP (BVAR (current_buffer, case_fold_search)))
4540 return Qnil;
4542 i1 = XFASTINT (c1);
4543 i2 = XFASTINT (c2);
4545 /* FIXME: It is possible to compare multibyte characters even when
4546 the current buffer is unibyte. Unfortunately this is ambiguous
4547 for characters between 128 and 255, as they could be either
4548 eight-bit raw bytes or Latin-1 characters. Assume the former for
4549 now. See Bug#17011, and also see casefiddle.c's casify_object,
4550 which has a similar problem. */
4551 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4553 if (SINGLE_BYTE_CHAR_P (i1))
4554 i1 = UNIBYTE_TO_CHAR (i1);
4555 if (SINGLE_BYTE_CHAR_P (i2))
4556 i2 = UNIBYTE_TO_CHAR (i2);
4559 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
4562 /* Transpose the markers in two regions of the current buffer, and
4563 adjust the ones between them if necessary (i.e.: if the regions
4564 differ in size).
4566 START1, END1 are the character positions of the first region.
4567 START1_BYTE, END1_BYTE are the byte positions.
4568 START2, END2 are the character positions of the second region.
4569 START2_BYTE, END2_BYTE are the byte positions.
4571 Traverses the entire marker list of the buffer to do so, adding an
4572 appropriate amount to some, subtracting from some, and leaving the
4573 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4575 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4577 static void
4578 transpose_markers (ptrdiff_t start1, ptrdiff_t end1,
4579 ptrdiff_t start2, ptrdiff_t end2,
4580 ptrdiff_t start1_byte, ptrdiff_t end1_byte,
4581 ptrdiff_t start2_byte, ptrdiff_t end2_byte)
4583 register ptrdiff_t amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4584 register struct Lisp_Marker *marker;
4586 /* Update point as if it were a marker. */
4587 if (PT < start1)
4589 else if (PT < end1)
4590 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4591 PT_BYTE + (end2_byte - end1_byte));
4592 else if (PT < start2)
4593 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4594 (PT_BYTE + (end2_byte - start2_byte)
4595 - (end1_byte - start1_byte)));
4596 else if (PT < end2)
4597 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4598 PT_BYTE - (start2_byte - start1_byte));
4600 /* We used to adjust the endpoints here to account for the gap, but that
4601 isn't good enough. Even if we assume the caller has tried to move the
4602 gap out of our way, it might still be at start1 exactly, for example;
4603 and that places it `inside' the interval, for our purposes. The amount
4604 of adjustment is nontrivial if there's a `denormalized' marker whose
4605 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4606 the dirty work to Fmarker_position, below. */
4608 /* The difference between the region's lengths */
4609 diff = (end2 - start2) - (end1 - start1);
4610 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4612 /* For shifting each marker in a region by the length of the other
4613 region plus the distance between the regions. */
4614 amt1 = (end2 - start2) + (start2 - end1);
4615 amt2 = (end1 - start1) + (start2 - end1);
4616 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4617 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4619 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4621 mpos = marker->bytepos;
4622 if (mpos >= start1_byte && mpos < end2_byte)
4624 if (mpos < end1_byte)
4625 mpos += amt1_byte;
4626 else if (mpos < start2_byte)
4627 mpos += diff_byte;
4628 else
4629 mpos -= amt2_byte;
4630 marker->bytepos = mpos;
4632 mpos = marker->charpos;
4633 if (mpos >= start1 && mpos < end2)
4635 if (mpos < end1)
4636 mpos += amt1;
4637 else if (mpos < start2)
4638 mpos += diff;
4639 else
4640 mpos -= amt2;
4642 marker->charpos = mpos;
4646 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4647 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4648 The regions should not be overlapping, because the size of the buffer is
4649 never changed in a transposition.
4651 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4652 any markers that happen to be located in the regions.
4654 Transposing beyond buffer boundaries is an error. */)
4655 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
4657 register ptrdiff_t start1, end1, start2, end2;
4658 ptrdiff_t start1_byte, start2_byte, len1_byte, len2_byte, end2_byte;
4659 ptrdiff_t gap, len1, len_mid, len2;
4660 unsigned char *start1_addr, *start2_addr, *temp;
4662 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4663 Lisp_Object buf;
4665 XSETBUFFER (buf, current_buffer);
4666 cur_intv = buffer_intervals (current_buffer);
4668 validate_region (&startr1, &endr1);
4669 validate_region (&startr2, &endr2);
4671 start1 = XFASTINT (startr1);
4672 end1 = XFASTINT (endr1);
4673 start2 = XFASTINT (startr2);
4674 end2 = XFASTINT (endr2);
4675 gap = GPT;
4677 /* Swap the regions if they're reversed. */
4678 if (start2 < end1)
4680 register ptrdiff_t glumph = start1;
4681 start1 = start2;
4682 start2 = glumph;
4683 glumph = end1;
4684 end1 = end2;
4685 end2 = glumph;
4688 len1 = end1 - start1;
4689 len2 = end2 - start2;
4691 if (start2 < end1)
4692 error ("Transposed regions overlap");
4693 /* Nothing to change for adjacent regions with one being empty */
4694 else if ((start1 == end1 || start2 == end2) && end1 == start2)
4695 return Qnil;
4697 /* The possibilities are:
4698 1. Adjacent (contiguous) regions, or separate but equal regions
4699 (no, really equal, in this case!), or
4700 2. Separate regions of unequal size.
4702 The worst case is usually No. 2. It means that (aside from
4703 potential need for getting the gap out of the way), there also
4704 needs to be a shifting of the text between the two regions. So
4705 if they are spread far apart, we are that much slower... sigh. */
4707 /* It must be pointed out that the really studly thing to do would
4708 be not to move the gap at all, but to leave it in place and work
4709 around it if necessary. This would be extremely efficient,
4710 especially considering that people are likely to do
4711 transpositions near where they are working interactively, which
4712 is exactly where the gap would be found. However, such code
4713 would be much harder to write and to read. So, if you are
4714 reading this comment and are feeling squirrely, by all means have
4715 a go! I just didn't feel like doing it, so I will simply move
4716 the gap the minimum distance to get it out of the way, and then
4717 deal with an unbroken array. */
4719 start1_byte = CHAR_TO_BYTE (start1);
4720 end2_byte = CHAR_TO_BYTE (end2);
4722 /* Make sure the gap won't interfere, by moving it out of the text
4723 we will operate on. */
4724 if (start1 < gap && gap < end2)
4726 if (gap - start1 < end2 - gap)
4727 move_gap_both (start1, start1_byte);
4728 else
4729 move_gap_both (end2, end2_byte);
4732 start2_byte = CHAR_TO_BYTE (start2);
4733 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4734 len2_byte = end2_byte - start2_byte;
4736 #ifdef BYTE_COMBINING_DEBUG
4737 if (end1 == start2)
4739 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4740 len2_byte, start1, start1_byte)
4741 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4742 len1_byte, end2, start2_byte + len2_byte)
4743 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4744 len1_byte, end2, start2_byte + len2_byte))
4745 emacs_abort ();
4747 else
4749 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4750 len2_byte, start1, start1_byte)
4751 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4752 len1_byte, start2, start2_byte)
4753 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4754 len2_byte, end1, start1_byte + len1_byte)
4755 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4756 len1_byte, end2, start2_byte + len2_byte))
4757 emacs_abort ();
4759 #endif
4761 /* Hmmm... how about checking to see if the gap is large
4762 enough to use as the temporary storage? That would avoid an
4763 allocation... interesting. Later, don't fool with it now. */
4765 /* Working without memmove, for portability (sigh), so must be
4766 careful of overlapping subsections of the array... */
4768 if (end1 == start2) /* adjacent regions */
4770 modify_text (start1, end2);
4771 record_change (start1, len1 + len2);
4773 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4774 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4775 /* Don't use Fset_text_properties: that can cause GC, which can
4776 clobber objects stored in the tmp_intervals. */
4777 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4778 if (tmp_interval3)
4779 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4781 USE_SAFE_ALLOCA;
4783 /* First region smaller than second. */
4784 if (len1_byte < len2_byte)
4786 temp = SAFE_ALLOCA (len2_byte);
4788 /* Don't precompute these addresses. We have to compute them
4789 at the last minute, because the relocating allocator might
4790 have moved the buffer around during the xmalloc. */
4791 start1_addr = BYTE_POS_ADDR (start1_byte);
4792 start2_addr = BYTE_POS_ADDR (start2_byte);
4794 memcpy (temp, start2_addr, len2_byte);
4795 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
4796 memcpy (start1_addr, temp, len2_byte);
4798 else
4799 /* First region not smaller than second. */
4801 temp = SAFE_ALLOCA (len1_byte);
4802 start1_addr = BYTE_POS_ADDR (start1_byte);
4803 start2_addr = BYTE_POS_ADDR (start2_byte);
4804 memcpy (temp, start1_addr, len1_byte);
4805 memcpy (start1_addr, start2_addr, len2_byte);
4806 memcpy (start1_addr + len2_byte, temp, len1_byte);
4809 SAFE_FREE ();
4810 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4811 len1, current_buffer, 0);
4812 graft_intervals_into_buffer (tmp_interval2, start1,
4813 len2, current_buffer, 0);
4814 update_compositions (start1, start1 + len2, CHECK_BORDER);
4815 update_compositions (start1 + len2, end2, CHECK_TAIL);
4817 /* Non-adjacent regions, because end1 != start2, bleagh... */
4818 else
4820 len_mid = start2_byte - (start1_byte + len1_byte);
4822 if (len1_byte == len2_byte)
4823 /* Regions are same size, though, how nice. */
4825 USE_SAFE_ALLOCA;
4827 modify_text (start1, end1);
4828 modify_text (start2, end2);
4829 record_change (start1, len1);
4830 record_change (start2, len2);
4831 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4832 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4834 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4835 if (tmp_interval3)
4836 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4838 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4839 if (tmp_interval3)
4840 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4842 temp = SAFE_ALLOCA (len1_byte);
4843 start1_addr = BYTE_POS_ADDR (start1_byte);
4844 start2_addr = BYTE_POS_ADDR (start2_byte);
4845 memcpy (temp, start1_addr, len1_byte);
4846 memcpy (start1_addr, start2_addr, len2_byte);
4847 memcpy (start2_addr, temp, len1_byte);
4848 SAFE_FREE ();
4850 graft_intervals_into_buffer (tmp_interval1, start2,
4851 len1, current_buffer, 0);
4852 graft_intervals_into_buffer (tmp_interval2, start1,
4853 len2, current_buffer, 0);
4856 else if (len1_byte < len2_byte) /* Second region larger than first */
4857 /* Non-adjacent & unequal size, area between must also be shifted. */
4859 USE_SAFE_ALLOCA;
4861 modify_text (start1, end2);
4862 record_change (start1, (end2 - start1));
4863 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4864 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4865 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4867 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4868 if (tmp_interval3)
4869 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4871 /* holds region 2 */
4872 temp = SAFE_ALLOCA (len2_byte);
4873 start1_addr = BYTE_POS_ADDR (start1_byte);
4874 start2_addr = BYTE_POS_ADDR (start2_byte);
4875 memcpy (temp, start2_addr, len2_byte);
4876 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
4877 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4878 memcpy (start1_addr, temp, len2_byte);
4879 SAFE_FREE ();
4881 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4882 len1, current_buffer, 0);
4883 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4884 len_mid, current_buffer, 0);
4885 graft_intervals_into_buffer (tmp_interval2, start1,
4886 len2, current_buffer, 0);
4888 else
4889 /* Second region smaller than first. */
4891 USE_SAFE_ALLOCA;
4893 record_change (start1, (end2 - start1));
4894 modify_text (start1, end2);
4896 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4897 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4898 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4900 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4901 if (tmp_interval3)
4902 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4904 /* holds region 1 */
4905 temp = SAFE_ALLOCA (len1_byte);
4906 start1_addr = BYTE_POS_ADDR (start1_byte);
4907 start2_addr = BYTE_POS_ADDR (start2_byte);
4908 memcpy (temp, start1_addr, len1_byte);
4909 memcpy (start1_addr, start2_addr, len2_byte);
4910 memcpy (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4911 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
4912 SAFE_FREE ();
4914 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4915 len1, current_buffer, 0);
4916 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4917 len_mid, current_buffer, 0);
4918 graft_intervals_into_buffer (tmp_interval2, start1,
4919 len2, current_buffer, 0);
4922 update_compositions (start1, start1 + len2, CHECK_BORDER);
4923 update_compositions (end2 - len1, end2, CHECK_BORDER);
4926 /* When doing multiple transpositions, it might be nice
4927 to optimize this. Perhaps the markers in any one buffer
4928 should be organized in some sorted data tree. */
4929 if (NILP (leave_markers))
4931 transpose_markers (start1, end1, start2, end2,
4932 start1_byte, start1_byte + len1_byte,
4933 start2_byte, start2_byte + len2_byte);
4934 fix_start_end_in_overlays (start1, end2);
4937 signal_after_change (start1, end2 - start1, end2 - start1);
4938 return Qnil;
4942 void
4943 syms_of_editfns (void)
4945 DEFSYM (Qbuffer_access_fontify_functions, "buffer-access-fontify-functions");
4947 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
4948 doc: /* Non-nil means text motion commands don't notice fields. */);
4949 Vinhibit_field_text_motion = Qnil;
4951 DEFVAR_LISP ("buffer-access-fontify-functions",
4952 Vbuffer_access_fontify_functions,
4953 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4954 Each function is called with two arguments which specify the range
4955 of the buffer being accessed. */);
4956 Vbuffer_access_fontify_functions = Qnil;
4959 Lisp_Object obuf;
4960 obuf = Fcurrent_buffer ();
4961 /* Do this here, because init_buffer_once is too early--it won't work. */
4962 Fset_buffer (Vprin1_to_string_buffer);
4963 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4964 Fset (Fmake_local_variable (Qbuffer_access_fontify_functions), Qnil);
4965 Fset_buffer (obuf);
4968 DEFVAR_LISP ("buffer-access-fontified-property",
4969 Vbuffer_access_fontified_property,
4970 doc: /* Property which (if non-nil) indicates text has been fontified.
4971 `buffer-substring' need not call the `buffer-access-fontify-functions'
4972 functions if all the text being accessed has this property. */);
4973 Vbuffer_access_fontified_property = Qnil;
4975 DEFVAR_LISP ("system-name", Vsystem_name,
4976 doc: /* The host name of the machine Emacs is running on. */);
4977 Vsystem_name = cached_system_name = Qnil;
4979 DEFVAR_LISP ("user-full-name", Vuser_full_name,
4980 doc: /* The full name of the user logged in. */);
4982 DEFVAR_LISP ("user-login-name", Vuser_login_name,
4983 doc: /* The user's name, taken from environment variables if possible. */);
4984 Vuser_login_name = Qnil;
4986 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
4987 doc: /* The user's name, based upon the real uid only. */);
4989 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
4990 doc: /* The release of the operating system Emacs is running on. */);
4992 defsubr (&Spropertize);
4993 defsubr (&Schar_equal);
4994 defsubr (&Sgoto_char);
4995 defsubr (&Sstring_to_char);
4996 defsubr (&Schar_to_string);
4997 defsubr (&Sbyte_to_string);
4998 defsubr (&Sbuffer_substring);
4999 defsubr (&Sbuffer_substring_no_properties);
5000 defsubr (&Sbuffer_string);
5001 defsubr (&Sget_pos_property);
5003 defsubr (&Spoint_marker);
5004 defsubr (&Smark_marker);
5005 defsubr (&Spoint);
5006 defsubr (&Sregion_beginning);
5007 defsubr (&Sregion_end);
5009 /* Symbol for the text property used to mark fields. */
5010 DEFSYM (Qfield, "field");
5012 /* A special value for Qfield properties. */
5013 DEFSYM (Qboundary, "boundary");
5015 defsubr (&Sfield_beginning);
5016 defsubr (&Sfield_end);
5017 defsubr (&Sfield_string);
5018 defsubr (&Sfield_string_no_properties);
5019 defsubr (&Sdelete_field);
5020 defsubr (&Sconstrain_to_field);
5022 defsubr (&Sline_beginning_position);
5023 defsubr (&Sline_end_position);
5025 defsubr (&Ssave_excursion);
5026 defsubr (&Ssave_current_buffer);
5028 defsubr (&Sbuffer_size);
5029 defsubr (&Spoint_max);
5030 defsubr (&Spoint_min);
5031 defsubr (&Spoint_min_marker);
5032 defsubr (&Spoint_max_marker);
5033 defsubr (&Sgap_position);
5034 defsubr (&Sgap_size);
5035 defsubr (&Sposition_bytes);
5036 defsubr (&Sbyte_to_position);
5038 defsubr (&Sbobp);
5039 defsubr (&Seobp);
5040 defsubr (&Sbolp);
5041 defsubr (&Seolp);
5042 defsubr (&Sfollowing_char);
5043 defsubr (&Sprevious_char);
5044 defsubr (&Schar_after);
5045 defsubr (&Schar_before);
5046 defsubr (&Sinsert);
5047 defsubr (&Sinsert_before_markers);
5048 defsubr (&Sinsert_and_inherit);
5049 defsubr (&Sinsert_and_inherit_before_markers);
5050 defsubr (&Sinsert_char);
5051 defsubr (&Sinsert_byte);
5053 defsubr (&Suser_login_name);
5054 defsubr (&Suser_real_login_name);
5055 defsubr (&Suser_uid);
5056 defsubr (&Suser_real_uid);
5057 defsubr (&Sgroup_gid);
5058 defsubr (&Sgroup_real_gid);
5059 defsubr (&Suser_full_name);
5060 defsubr (&Semacs_pid);
5061 defsubr (&Scurrent_time);
5062 defsubr (&Stime_add);
5063 defsubr (&Stime_subtract);
5064 defsubr (&Stime_less_p);
5065 defsubr (&Sget_internal_run_time);
5066 defsubr (&Sformat_time_string);
5067 defsubr (&Sfloat_time);
5068 defsubr (&Sdecode_time);
5069 defsubr (&Sencode_time);
5070 defsubr (&Scurrent_time_string);
5071 defsubr (&Scurrent_time_zone);
5072 defsubr (&Sset_time_zone_rule);
5073 defsubr (&Ssystem_name);
5074 defsubr (&Smessage);
5075 defsubr (&Smessage_box);
5076 defsubr (&Smessage_or_box);
5077 defsubr (&Scurrent_message);
5078 defsubr (&Sformat);
5080 defsubr (&Sinsert_buffer_substring);
5081 defsubr (&Scompare_buffer_substrings);
5082 defsubr (&Ssubst_char_in_region);
5083 defsubr (&Stranslate_region_internal);
5084 defsubr (&Sdelete_region);
5085 defsubr (&Sdelete_and_extract_region);
5086 defsubr (&Swiden);
5087 defsubr (&Snarrow_to_region);
5088 defsubr (&Ssave_restriction);
5089 defsubr (&Stranspose_regions);