* lisp/vc/vc-filewise.el: Comment fixes.
[emacs.git] / src / editfns.c
blob0a07886934c71c0a8f2fbe6f030d2245b71ff48b
1 /* Lisp functions pertaining to editing.
3 Copyright (C) 1985-1987, 1989, 1993-2014 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 static Lisp_Object Qbuffer_access_fontify_functions;
81 /* Symbol for the text property used to mark fields. */
83 Lisp_Object Qfield;
85 /* A special value for Qfield properties. */
87 static Lisp_Object Qboundary;
89 /* The startup value of the TZ environment variable; null if unset. */
90 static char const *initial_tz;
92 /* A valid but unlikely setting for the TZ environment variable.
93 It is OK (though a bit slower) if the user chooses this value. */
94 static char dump_tz_string[] = "TZ=UtC0";
96 void
97 init_editfns (void)
99 const char *user_name;
100 register char *p;
101 struct passwd *pw; /* password entry for the current user */
102 Lisp_Object tem;
104 /* Set up system_name even when dumping. */
105 init_system_name ();
107 #ifndef CANNOT_DUMP
108 /* When just dumping out, set the time zone to a known unlikely value
109 and skip the rest of this function. */
110 if (!initialized)
112 # ifdef HAVE_TZSET
113 xputenv (dump_tz_string);
114 tzset ();
115 # endif
116 return;
118 #endif
120 char *tz = getenv ("TZ");
121 initial_tz = tz;
123 #if !defined CANNOT_DUMP && defined HAVE_TZSET
124 /* If the execution TZ happens to be the same as the dump TZ,
125 change it to some other value and then change it back,
126 to force the underlying implementation to reload the TZ info.
127 This is needed on implementations that load TZ info from files,
128 since the TZ file contents may differ between dump and execution. */
129 if (tz && strcmp (tz, &dump_tz_string[sizeof "TZ=" - 1]) == 0)
131 ++*tz;
132 tzset ();
133 --*tz;
135 #endif
137 /* Call set_time_zone_rule now, so that its call to putenv is done
138 before multiple threads are active. */
139 set_time_zone_rule (tz);
141 pw = getpwuid (getuid ());
142 #ifdef MSDOS
143 /* We let the real user name default to "root" because that's quite
144 accurate on MS-DOS and because it lets Emacs find the init file.
145 (The DVX libraries override the Djgpp libraries here.) */
146 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
147 #else
148 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
149 #endif
151 /* Get the effective user name, by consulting environment variables,
152 or the effective uid if those are unset. */
153 user_name = getenv ("LOGNAME");
154 if (!user_name)
155 #ifdef WINDOWSNT
156 user_name = getenv ("USERNAME"); /* it's USERNAME on NT */
157 #else /* WINDOWSNT */
158 user_name = getenv ("USER");
159 #endif /* WINDOWSNT */
160 if (!user_name)
162 pw = getpwuid (geteuid ());
163 user_name = pw ? pw->pw_name : "unknown";
165 Vuser_login_name = build_string (user_name);
167 /* If the user name claimed in the environment vars differs from
168 the real uid, use the claimed name to find the full name. */
169 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
170 if (! NILP (tem))
171 tem = Vuser_login_name;
172 else
174 uid_t euid = geteuid ();
175 tem = make_fixnum_or_float (euid);
177 Vuser_full_name = Fuser_full_name (tem);
179 p = getenv ("NAME");
180 if (p)
181 Vuser_full_name = build_string (p);
182 else if (NILP (Vuser_full_name))
183 Vuser_full_name = build_string ("unknown");
185 #ifdef HAVE_SYS_UTSNAME_H
187 struct utsname uts;
188 uname (&uts);
189 Voperating_system_release = build_string (uts.release);
191 #else
192 Voperating_system_release = Qnil;
193 #endif
196 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
197 doc: /* Convert arg CHAR to a string containing that character.
198 usage: (char-to-string CHAR) */)
199 (Lisp_Object character)
201 int c, len;
202 unsigned char str[MAX_MULTIBYTE_LENGTH];
204 CHECK_CHARACTER (character);
205 c = XFASTINT (character);
207 len = CHAR_STRING (c, str);
208 return make_string_from_bytes ((char *) str, 1, len);
211 DEFUN ("byte-to-string", Fbyte_to_string, Sbyte_to_string, 1, 1, 0,
212 doc: /* Convert arg BYTE to a unibyte string containing that byte. */)
213 (Lisp_Object byte)
215 unsigned char b;
216 CHECK_NUMBER (byte);
217 if (XINT (byte) < 0 || XINT (byte) > 255)
218 error ("Invalid byte");
219 b = XINT (byte);
220 return make_string_from_bytes ((char *) &b, 1, 1);
223 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
224 doc: /* Return the first character in STRING. */)
225 (register Lisp_Object string)
227 register Lisp_Object val;
228 CHECK_STRING (string);
229 if (SCHARS (string))
231 if (STRING_MULTIBYTE (string))
232 XSETFASTINT (val, STRING_CHAR (SDATA (string)));
233 else
234 XSETFASTINT (val, SREF (string, 0));
236 else
237 XSETFASTINT (val, 0);
238 return val;
241 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
242 doc: /* Return value of point, as an integer.
243 Beginning of buffer is position (point-min). */)
244 (void)
246 Lisp_Object temp;
247 XSETFASTINT (temp, PT);
248 return temp;
251 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
252 doc: /* Return value of point, as a marker object. */)
253 (void)
255 return build_marker (current_buffer, PT, PT_BYTE);
258 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
259 doc: /* Set point to POSITION, a number or marker.
260 Beginning of buffer is position (point-min), end is (point-max).
262 The return value is POSITION. */)
263 (register Lisp_Object position)
265 if (MARKERP (position))
266 set_point_from_marker (position);
267 else if (INTEGERP (position))
268 SET_PT (clip_to_bounds (BEGV, XINT (position), ZV));
269 else
270 wrong_type_argument (Qinteger_or_marker_p, position);
271 return position;
275 /* Return the start or end position of the region.
276 BEGINNINGP means return the start.
277 If there is no region active, signal an error. */
279 static Lisp_Object
280 region_limit (bool beginningp)
282 Lisp_Object m;
284 if (!NILP (Vtransient_mark_mode)
285 && NILP (Vmark_even_if_inactive)
286 && NILP (BVAR (current_buffer, mark_active)))
287 xsignal0 (Qmark_inactive);
289 m = Fmarker_position (BVAR (current_buffer, mark));
290 if (NILP (m))
291 error ("The mark is not set now, so there is no region");
293 /* Clip to the current narrowing (bug#11770). */
294 return make_number ((PT < XFASTINT (m)) == beginningp
295 ? PT
296 : clip_to_bounds (BEGV, XFASTINT (m), ZV));
299 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
300 doc: /* Return the integer value of point or mark, whichever is smaller. */)
301 (void)
303 return region_limit (1);
306 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
307 doc: /* Return the integer value of point or mark, whichever is larger. */)
308 (void)
310 return region_limit (0);
313 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
314 doc: /* Return this buffer's mark, as a marker object.
315 Watch out! Moving this marker changes the mark position.
316 If you set the marker not to point anywhere, the buffer will have no mark. */)
317 (void)
319 return BVAR (current_buffer, mark);
323 /* Find all the overlays in the current buffer that touch position POS.
324 Return the number found, and store them in a vector in VEC
325 of length LEN. */
327 static ptrdiff_t
328 overlays_around (EMACS_INT pos, Lisp_Object *vec, ptrdiff_t len)
330 Lisp_Object overlay, start, end;
331 struct Lisp_Overlay *tail;
332 ptrdiff_t startpos, endpos;
333 ptrdiff_t idx = 0;
335 for (tail = current_buffer->overlays_before; tail; tail = tail->next)
337 XSETMISC (overlay, tail);
339 end = OVERLAY_END (overlay);
340 endpos = OVERLAY_POSITION (end);
341 if (endpos < pos)
342 break;
343 start = OVERLAY_START (overlay);
344 startpos = OVERLAY_POSITION (start);
345 if (startpos <= pos)
347 if (idx < len)
348 vec[idx] = overlay;
349 /* Keep counting overlays even if we can't return them all. */
350 idx++;
354 for (tail = current_buffer->overlays_after; tail; tail = tail->next)
356 XSETMISC (overlay, tail);
358 start = OVERLAY_START (overlay);
359 startpos = OVERLAY_POSITION (start);
360 if (pos < startpos)
361 break;
362 end = OVERLAY_END (overlay);
363 endpos = OVERLAY_POSITION (end);
364 if (pos <= endpos)
366 if (idx < len)
367 vec[idx] = overlay;
368 idx++;
372 return idx;
375 DEFUN ("get-pos-property", Fget_pos_property, Sget_pos_property, 2, 3, 0,
376 doc: /* Return the value of POSITION's property PROP, in OBJECT.
377 Almost identical to `get-char-property' except for the following difference:
378 Whereas `get-char-property' returns the property of the char at (i.e. right
379 after) POSITION, this pays attention to properties's stickiness and overlays's
380 advancement settings, in order to find the property of POSITION itself,
381 i.e. the property that a char would inherit if it were inserted
382 at POSITION. */)
383 (Lisp_Object position, register Lisp_Object prop, Lisp_Object object)
385 CHECK_NUMBER_COERCE_MARKER (position);
387 if (NILP (object))
388 XSETBUFFER (object, current_buffer);
389 else if (WINDOWP (object))
390 object = XWINDOW (object)->contents;
392 if (!BUFFERP (object))
393 /* pos-property only makes sense in buffers right now, since strings
394 have no overlays and no notion of insertion for which stickiness
395 could be obeyed. */
396 return Fget_text_property (position, prop, object);
397 else
399 EMACS_INT posn = XINT (position);
400 ptrdiff_t noverlays;
401 Lisp_Object *overlay_vec, tem;
402 struct buffer *obuf = current_buffer;
403 USE_SAFE_ALLOCA;
405 set_buffer_temp (XBUFFER (object));
407 /* First try with room for 40 overlays. */
408 Lisp_Object overlay_vecbuf[40];
409 noverlays = ARRAYELTS (overlay_vecbuf);
410 overlay_vec = overlay_vecbuf;
411 noverlays = overlays_around (posn, overlay_vec, noverlays);
413 /* If there are more than 40,
414 make enough space for all, and try again. */
415 if (ARRAYELTS (overlay_vecbuf) < noverlays)
417 SAFE_ALLOCA_LISP (overlay_vec, noverlays);
418 noverlays = overlays_around (posn, overlay_vec, noverlays);
420 noverlays = sort_overlays (overlay_vec, noverlays, NULL);
422 set_buffer_temp (obuf);
424 /* Now check the overlays in order of decreasing priority. */
425 while (--noverlays >= 0)
427 Lisp_Object ol = overlay_vec[noverlays];
428 tem = Foverlay_get (ol, prop);
429 if (!NILP (tem))
431 /* Check the overlay is indeed active at point. */
432 Lisp_Object start = OVERLAY_START (ol), finish = OVERLAY_END (ol);
433 if ((OVERLAY_POSITION (start) == posn
434 && XMARKER (start)->insertion_type == 1)
435 || (OVERLAY_POSITION (finish) == posn
436 && XMARKER (finish)->insertion_type == 0))
437 ; /* The overlay will not cover a char inserted at point. */
438 else
440 SAFE_FREE ();
441 return tem;
445 SAFE_FREE ();
447 { /* Now check the text properties. */
448 int stickiness = text_property_stickiness (prop, position, object);
449 if (stickiness > 0)
450 return Fget_text_property (position, prop, object);
451 else if (stickiness < 0
452 && XINT (position) > BUF_BEGV (XBUFFER (object)))
453 return Fget_text_property (make_number (XINT (position) - 1),
454 prop, object);
455 else
456 return Qnil;
461 /* Find the field surrounding POS in *BEG and *END. If POS is nil,
462 the value of point is used instead. If BEG or END is null,
463 means don't store the beginning or end of the field.
465 BEG_LIMIT and END_LIMIT serve to limit the ranged of the returned
466 results; they do not effect boundary behavior.
468 If MERGE_AT_BOUNDARY is non-nil, then if POS is at the very first
469 position of a field, then the beginning of the previous field is
470 returned instead of the beginning of POS's field (since the end of a
471 field is actually also the beginning of the next input field, this
472 behavior is sometimes useful). Additionally in the MERGE_AT_BOUNDARY
473 non-nil case, if two fields are separated by a field with the special
474 value `boundary', and POS lies within it, then the two separated
475 fields are considered to be adjacent, and POS between them, when
476 finding the beginning and ending of the "merged" field.
478 Either BEG or END may be 0, in which case the corresponding value
479 is not stored. */
481 static void
482 find_field (Lisp_Object pos, Lisp_Object merge_at_boundary,
483 Lisp_Object beg_limit,
484 ptrdiff_t *beg, Lisp_Object end_limit, ptrdiff_t *end)
486 /* Fields right before and after the point. */
487 Lisp_Object before_field, after_field;
488 /* True if POS counts as the start of a field. */
489 bool at_field_start = 0;
490 /* True if POS counts as the end of a field. */
491 bool at_field_end = 0;
493 if (NILP (pos))
494 XSETFASTINT (pos, PT);
495 else
496 CHECK_NUMBER_COERCE_MARKER (pos);
498 after_field
499 = get_char_property_and_overlay (pos, Qfield, Qnil, NULL);
500 before_field
501 = (XFASTINT (pos) > BEGV
502 ? get_char_property_and_overlay (make_number (XINT (pos) - 1),
503 Qfield, Qnil, NULL)
504 /* Using nil here would be a more obvious choice, but it would
505 fail when the buffer starts with a non-sticky field. */
506 : after_field);
508 /* See if we need to handle the case where MERGE_AT_BOUNDARY is nil
509 and POS is at beginning of a field, which can also be interpreted
510 as the end of the previous field. Note that the case where if
511 MERGE_AT_BOUNDARY is non-nil (see function comment) is actually the
512 more natural one; then we avoid treating the beginning of a field
513 specially. */
514 if (NILP (merge_at_boundary))
516 Lisp_Object field = Fget_pos_property (pos, Qfield, Qnil);
517 if (!EQ (field, after_field))
518 at_field_end = 1;
519 if (!EQ (field, before_field))
520 at_field_start = 1;
521 if (NILP (field) && at_field_start && at_field_end)
522 /* If an inserted char would have a nil field while the surrounding
523 text is non-nil, we're probably not looking at a
524 zero-length field, but instead at a non-nil field that's
525 not intended for editing (such as comint's prompts). */
526 at_field_end = at_field_start = 0;
529 /* Note about special `boundary' fields:
531 Consider the case where the point (`.') is between the fields `x' and `y':
533 xxxx.yyyy
535 In this situation, if merge_at_boundary is non-nil, consider the
536 `x' and `y' fields as forming one big merged field, and so the end
537 of the field is the end of `y'.
539 However, if `x' and `y' are separated by a special `boundary' field
540 (a field with a `field' char-property of 'boundary), then ignore
541 this special field when merging adjacent fields. Here's the same
542 situation, but with a `boundary' field between the `x' and `y' fields:
544 xxx.BBBByyyy
546 Here, if point is at the end of `x', the beginning of `y', or
547 anywhere in-between (within the `boundary' field), merge all
548 three fields and consider the beginning as being the beginning of
549 the `x' field, and the end as being the end of the `y' field. */
551 if (beg)
553 if (at_field_start)
554 /* POS is at the edge of a field, and we should consider it as
555 the beginning of the following field. */
556 *beg = XFASTINT (pos);
557 else
558 /* Find the previous field boundary. */
560 Lisp_Object p = pos;
561 if (!NILP (merge_at_boundary) && EQ (before_field, Qboundary))
562 /* Skip a `boundary' field. */
563 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
564 beg_limit);
566 p = Fprevious_single_char_property_change (p, Qfield, Qnil,
567 beg_limit);
568 *beg = NILP (p) ? BEGV : XFASTINT (p);
572 if (end)
574 if (at_field_end)
575 /* POS is at the edge of a field, and we should consider it as
576 the end of the previous field. */
577 *end = XFASTINT (pos);
578 else
579 /* Find the next field boundary. */
581 if (!NILP (merge_at_boundary) && EQ (after_field, Qboundary))
582 /* Skip a `boundary' field. */
583 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
584 end_limit);
586 pos = Fnext_single_char_property_change (pos, Qfield, Qnil,
587 end_limit);
588 *end = NILP (pos) ? ZV : XFASTINT (pos);
594 DEFUN ("delete-field", Fdelete_field, Sdelete_field, 0, 1, 0,
595 doc: /* Delete the field surrounding POS.
596 A field is a region of text with the same `field' property.
597 If POS is nil, the value of point is used for POS. */)
598 (Lisp_Object pos)
600 ptrdiff_t beg, end;
601 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
602 if (beg != end)
603 del_range (beg, end);
604 return Qnil;
607 DEFUN ("field-string", Ffield_string, Sfield_string, 0, 1, 0,
608 doc: /* Return the contents of the field surrounding POS as a string.
609 A field is a region of text with the same `field' property.
610 If POS is nil, the value of point is used for POS. */)
611 (Lisp_Object pos)
613 ptrdiff_t beg, end;
614 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
615 return make_buffer_string (beg, end, 1);
618 DEFUN ("field-string-no-properties", Ffield_string_no_properties, Sfield_string_no_properties, 0, 1, 0,
619 doc: /* Return the contents of the field around POS, without text properties.
620 A field is a region of text with the same `field' property.
621 If POS is nil, the value of point is used for POS. */)
622 (Lisp_Object pos)
624 ptrdiff_t beg, end;
625 find_field (pos, Qnil, Qnil, &beg, Qnil, &end);
626 return make_buffer_string (beg, end, 0);
629 DEFUN ("field-beginning", Ffield_beginning, Sfield_beginning, 0, 3, 0,
630 doc: /* Return the beginning of the field surrounding POS.
631 A field is a region of text with the same `field' property.
632 If POS is nil, the value of point is used for POS.
633 If ESCAPE-FROM-EDGE is non-nil and POS is at the beginning of its
634 field, then the beginning of the *previous* field is returned.
635 If LIMIT is non-nil, it is a buffer position; if the beginning of the field
636 is before LIMIT, then LIMIT will be returned instead. */)
637 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
639 ptrdiff_t beg;
640 find_field (pos, escape_from_edge, limit, &beg, Qnil, 0);
641 return make_number (beg);
644 DEFUN ("field-end", Ffield_end, Sfield_end, 0, 3, 0,
645 doc: /* Return the end of the field surrounding POS.
646 A field is a region of text with the same `field' property.
647 If POS is nil, the value of point is used for POS.
648 If ESCAPE-FROM-EDGE is non-nil and POS is at the end of its field,
649 then the end of the *following* field is returned.
650 If LIMIT is non-nil, it is a buffer position; if the end of the field
651 is after LIMIT, then LIMIT will be returned instead. */)
652 (Lisp_Object pos, Lisp_Object escape_from_edge, Lisp_Object limit)
654 ptrdiff_t end;
655 find_field (pos, escape_from_edge, Qnil, 0, limit, &end);
656 return make_number (end);
659 DEFUN ("constrain-to-field", Fconstrain_to_field, Sconstrain_to_field, 2, 5, 0,
660 doc: /* Return the position closest to NEW-POS that is in the same field as OLD-POS.
661 A field is a region of text with the same `field' property.
663 If NEW-POS is nil, then use the current point instead, and move point
664 to the resulting constrained position, in addition to returning that
665 position.
667 If OLD-POS is at the boundary of two fields, then the allowable
668 positions for NEW-POS depends on the value of the optional argument
669 ESCAPE-FROM-EDGE: If ESCAPE-FROM-EDGE is nil, then NEW-POS is
670 constrained to the field that has the same `field' char-property
671 as any new characters inserted at OLD-POS, whereas if ESCAPE-FROM-EDGE
672 is non-nil, NEW-POS is constrained to the union of the two adjacent
673 fields. Additionally, if two fields are separated by another field with
674 the special value `boundary', then any point within this special field is
675 also considered to be `on the boundary'.
677 If the optional argument ONLY-IN-LINE is non-nil and constraining
678 NEW-POS would move it to a different line, NEW-POS is returned
679 unconstrained. This is useful for commands that move by line, like
680 \\[next-line] or \\[beginning-of-line], which should generally respect field boundaries
681 only in the case where they can still move to the right line.
683 If the optional argument INHIBIT-CAPTURE-PROPERTY is non-nil, and OLD-POS has
684 a non-nil property of that name, then any field boundaries are ignored.
686 Field boundaries are not noticed if `inhibit-field-text-motion' is non-nil. */)
687 (Lisp_Object new_pos, Lisp_Object old_pos, Lisp_Object escape_from_edge,
688 Lisp_Object only_in_line, Lisp_Object inhibit_capture_property)
690 /* If non-zero, then the original point, before re-positioning. */
691 ptrdiff_t orig_point = 0;
692 bool fwd;
693 Lisp_Object prev_old, prev_new;
695 if (NILP (new_pos))
696 /* Use the current point, and afterwards, set it. */
698 orig_point = PT;
699 XSETFASTINT (new_pos, PT);
702 CHECK_NUMBER_COERCE_MARKER (new_pos);
703 CHECK_NUMBER_COERCE_MARKER (old_pos);
705 fwd = (XINT (new_pos) > XINT (old_pos));
707 prev_old = make_number (XINT (old_pos) - 1);
708 prev_new = make_number (XINT (new_pos) - 1);
710 if (NILP (Vinhibit_field_text_motion)
711 && !EQ (new_pos, old_pos)
712 && (!NILP (Fget_char_property (new_pos, Qfield, Qnil))
713 || !NILP (Fget_char_property (old_pos, Qfield, Qnil))
714 /* To recognize field boundaries, we must also look at the
715 previous positions; we could use `Fget_pos_property'
716 instead, but in itself that would fail inside non-sticky
717 fields (like comint prompts). */
718 || (XFASTINT (new_pos) > BEGV
719 && !NILP (Fget_char_property (prev_new, Qfield, Qnil)))
720 || (XFASTINT (old_pos) > BEGV
721 && !NILP (Fget_char_property (prev_old, Qfield, Qnil))))
722 && (NILP (inhibit_capture_property)
723 /* Field boundaries are again a problem; but now we must
724 decide the case exactly, so we need to call
725 `get_pos_property' as well. */
726 || (NILP (Fget_pos_property (old_pos, inhibit_capture_property, Qnil))
727 && (XFASTINT (old_pos) <= BEGV
728 || NILP (Fget_char_property
729 (old_pos, inhibit_capture_property, Qnil))
730 || NILP (Fget_char_property
731 (prev_old, inhibit_capture_property, Qnil))))))
732 /* It is possible that NEW_POS is not within the same field as
733 OLD_POS; try to move NEW_POS so that it is. */
735 ptrdiff_t shortage;
736 Lisp_Object field_bound;
738 if (fwd)
739 field_bound = Ffield_end (old_pos, escape_from_edge, new_pos);
740 else
741 field_bound = Ffield_beginning (old_pos, escape_from_edge, new_pos);
743 if (/* See if ESCAPE_FROM_EDGE caused FIELD_BOUND to jump to the
744 other side of NEW_POS, which would mean that NEW_POS is
745 already acceptable, and it's not necessary to constrain it
746 to FIELD_BOUND. */
747 ((XFASTINT (field_bound) < XFASTINT (new_pos)) ? fwd : !fwd)
748 /* NEW_POS should be constrained, but only if either
749 ONLY_IN_LINE is nil (in which case any constraint is OK),
750 or NEW_POS and FIELD_BOUND are on the same line (in which
751 case the constraint is OK even if ONLY_IN_LINE is non-nil). */
752 && (NILP (only_in_line)
753 /* This is the ONLY_IN_LINE case, check that NEW_POS and
754 FIELD_BOUND are on the same line by seeing whether
755 there's an intervening newline or not. */
756 || (find_newline (XFASTINT (new_pos), -1,
757 XFASTINT (field_bound), -1,
758 fwd ? -1 : 1, &shortage, NULL, 1),
759 shortage != 0)))
760 /* Constrain NEW_POS to FIELD_BOUND. */
761 new_pos = field_bound;
763 if (orig_point && XFASTINT (new_pos) != orig_point)
764 /* The NEW_POS argument was originally nil, so automatically set PT. */
765 SET_PT (XFASTINT (new_pos));
768 return new_pos;
772 DEFUN ("line-beginning-position",
773 Fline_beginning_position, Sline_beginning_position, 0, 1, 0,
774 doc: /* Return the character position of the first character on the current line.
775 With optional argument N, scan forward N - 1 lines first.
776 If the scan reaches the end of the buffer, return that position.
778 This function ignores text display directionality; it returns the
779 position of the first character in logical order, i.e. the smallest
780 character position on the line.
782 This function constrains the returned position to the current field
783 unless that position would be on a different line than the original,
784 unconstrained result. If N is nil or 1, and a front-sticky field
785 starts at point, the scan stops as soon as it starts. To ignore field
786 boundaries, bind `inhibit-field-text-motion' to t.
788 This function does not move point. */)
789 (Lisp_Object n)
791 ptrdiff_t charpos, bytepos;
793 if (NILP (n))
794 XSETFASTINT (n, 1);
795 else
796 CHECK_NUMBER (n);
798 scan_newline_from_point (XINT (n) - 1, &charpos, &bytepos);
800 /* Return END constrained to the current input field. */
801 return Fconstrain_to_field (make_number (charpos), make_number (PT),
802 XINT (n) != 1 ? Qt : Qnil,
803 Qt, Qnil);
806 DEFUN ("line-end-position", Fline_end_position, Sline_end_position, 0, 1, 0,
807 doc: /* Return the character position of the last character on the current line.
808 With argument N not nil or 1, move forward N - 1 lines first.
809 If scan reaches end of buffer, return that position.
811 This function ignores text display directionality; it returns the
812 position of the last character in logical order, i.e. the largest
813 character position on the line.
815 This function constrains the returned position to the current field
816 unless that would be on a different line than the original,
817 unconstrained result. If N is nil or 1, and a rear-sticky field ends
818 at point, the scan stops as soon as it starts. To ignore field
819 boundaries bind `inhibit-field-text-motion' to t.
821 This function does not move point. */)
822 (Lisp_Object n)
824 ptrdiff_t clipped_n;
825 ptrdiff_t end_pos;
826 ptrdiff_t orig = PT;
828 if (NILP (n))
829 XSETFASTINT (n, 1);
830 else
831 CHECK_NUMBER (n);
833 clipped_n = clip_to_bounds (PTRDIFF_MIN + 1, XINT (n), PTRDIFF_MAX);
834 end_pos = find_before_next_newline (orig, 0, clipped_n - (clipped_n <= 0),
835 NULL);
837 /* Return END_POS constrained to the current input field. */
838 return Fconstrain_to_field (make_number (end_pos), make_number (orig),
839 Qnil, Qt, Qnil);
842 /* Save current buffer state for `save-excursion' special form.
843 We (ab)use Lisp_Misc_Save_Value to allow explicit free and so
844 offload some work from GC. */
846 Lisp_Object
847 save_excursion_save (void)
849 return make_save_obj_obj_obj_obj
850 (Fpoint_marker (),
851 /* Do not copy the mark if it points to nowhere. */
852 (XMARKER (BVAR (current_buffer, mark))->buffer
853 ? Fcopy_marker (BVAR (current_buffer, mark), Qnil)
854 : Qnil),
855 /* Selected window if current buffer is shown in it, nil otherwise. */
856 (EQ (XWINDOW (selected_window)->contents, Fcurrent_buffer ())
857 ? selected_window : Qnil),
858 BVAR (current_buffer, mark_active));
861 /* Restore saved buffer before leaving `save-excursion' special form. */
863 void
864 save_excursion_restore (Lisp_Object info)
866 Lisp_Object tem, tem1, omark, nmark;
867 struct gcpro gcpro1, gcpro2, gcpro3;
869 tem = Fmarker_buffer (XSAVE_OBJECT (info, 0));
870 /* If we're unwinding to top level, saved buffer may be deleted. This
871 means that all of its markers are unchained and so tem is nil. */
872 if (NILP (tem))
873 goto out;
875 omark = nmark = Qnil;
876 GCPRO3 (info, omark, nmark);
878 Fset_buffer (tem);
880 /* Point marker. */
881 tem = XSAVE_OBJECT (info, 0);
882 Fgoto_char (tem);
883 unchain_marker (XMARKER (tem));
885 /* Mark marker. */
886 tem = XSAVE_OBJECT (info, 1);
887 omark = Fmarker_position (BVAR (current_buffer, mark));
888 if (NILP (tem))
889 unchain_marker (XMARKER (BVAR (current_buffer, mark)));
890 else
892 Fset_marker (BVAR (current_buffer, mark), tem, Fcurrent_buffer ());
893 nmark = Fmarker_position (tem);
894 unchain_marker (XMARKER (tem));
897 /* Mark active. */
898 tem = XSAVE_OBJECT (info, 3);
899 tem1 = BVAR (current_buffer, mark_active);
900 bset_mark_active (current_buffer, tem);
902 /* If mark is active now, and either was not active
903 or was at a different place, run the activate hook. */
904 if (! NILP (tem))
906 if (! EQ (omark, nmark))
908 tem = intern ("activate-mark-hook");
909 Frun_hooks (1, &tem);
912 /* If mark has ceased to be active, run deactivate hook. */
913 else if (! NILP (tem1))
915 tem = intern ("deactivate-mark-hook");
916 Frun_hooks (1, &tem);
919 /* If buffer was visible in a window, and a different window was
920 selected, and the old selected window is still showing this
921 buffer, restore point in that window. */
922 tem = XSAVE_OBJECT (info, 2);
923 if (WINDOWP (tem)
924 && !EQ (tem, selected_window)
925 && (tem1 = XWINDOW (tem)->contents,
926 (/* Window is live... */
927 BUFFERP (tem1)
928 /* ...and it shows the current buffer. */
929 && XBUFFER (tem1) == current_buffer)))
930 Fset_window_point (tem, make_number (PT));
932 UNGCPRO;
934 out:
936 free_misc (info);
939 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
940 doc: /* Save point, mark, and current buffer; execute BODY; restore those things.
941 Executes BODY just like `progn'.
942 The values of point, mark and the current buffer are restored
943 even in case of abnormal exit (throw or error).
944 The state of activation of the mark is also restored.
946 This construct does not save `deactivate-mark', and therefore
947 functions that change the buffer will still cause deactivation
948 of the mark at the end of the command. To prevent that, bind
949 `deactivate-mark' with `let'.
951 If you only want to save the current buffer but not point nor mark,
952 then just use `save-current-buffer', or even `with-current-buffer'.
954 usage: (save-excursion &rest BODY) */)
955 (Lisp_Object args)
957 register Lisp_Object val;
958 ptrdiff_t count = SPECPDL_INDEX ();
960 record_unwind_protect (save_excursion_restore, save_excursion_save ());
962 val = Fprogn (args);
963 return unbind_to (count, val);
966 DEFUN ("save-current-buffer", Fsave_current_buffer, Ssave_current_buffer, 0, UNEVALLED, 0,
967 doc: /* Record which buffer is current; execute BODY; make that buffer current.
968 BODY is executed just like `progn'.
969 usage: (save-current-buffer &rest BODY) */)
970 (Lisp_Object args)
972 ptrdiff_t count = SPECPDL_INDEX ();
974 record_unwind_current_buffer ();
975 return unbind_to (count, Fprogn (args));
978 DEFUN ("buffer-size", Fbuffer_size, Sbuffer_size, 0, 1, 0,
979 doc: /* Return the number of characters in the current buffer.
980 If BUFFER, return the number of characters in that buffer instead. */)
981 (Lisp_Object buffer)
983 if (NILP (buffer))
984 return make_number (Z - BEG);
985 else
987 CHECK_BUFFER (buffer);
988 return make_number (BUF_Z (XBUFFER (buffer))
989 - BUF_BEG (XBUFFER (buffer)));
993 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
994 doc: /* Return the minimum permissible value of point in the current buffer.
995 This is 1, unless narrowing (a buffer restriction) is in effect. */)
996 (void)
998 Lisp_Object temp;
999 XSETFASTINT (temp, BEGV);
1000 return temp;
1003 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
1004 doc: /* Return a marker to the minimum permissible value of point in this buffer.
1005 This is the beginning, unless narrowing (a buffer restriction) is in effect. */)
1006 (void)
1008 return build_marker (current_buffer, BEGV, BEGV_BYTE);
1011 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
1012 doc: /* Return the maximum permissible value of point in the current buffer.
1013 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1014 is in effect, in which case it is less. */)
1015 (void)
1017 Lisp_Object temp;
1018 XSETFASTINT (temp, ZV);
1019 return temp;
1022 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
1023 doc: /* Return a marker to the maximum permissible value of point in this buffer.
1024 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)
1025 is in effect, in which case it is less. */)
1026 (void)
1028 return build_marker (current_buffer, ZV, ZV_BYTE);
1031 DEFUN ("gap-position", Fgap_position, Sgap_position, 0, 0, 0,
1032 doc: /* Return the position of the gap, in the current buffer.
1033 See also `gap-size'. */)
1034 (void)
1036 Lisp_Object temp;
1037 XSETFASTINT (temp, GPT);
1038 return temp;
1041 DEFUN ("gap-size", Fgap_size, Sgap_size, 0, 0, 0,
1042 doc: /* Return the size of the current buffer's gap.
1043 See also `gap-position'. */)
1044 (void)
1046 Lisp_Object temp;
1047 XSETFASTINT (temp, GAP_SIZE);
1048 return temp;
1051 DEFUN ("position-bytes", Fposition_bytes, Sposition_bytes, 1, 1, 0,
1052 doc: /* Return the byte position for character position POSITION.
1053 If POSITION is out of range, the value is nil. */)
1054 (Lisp_Object position)
1056 CHECK_NUMBER_COERCE_MARKER (position);
1057 if (XINT (position) < BEG || XINT (position) > Z)
1058 return Qnil;
1059 return make_number (CHAR_TO_BYTE (XINT (position)));
1062 DEFUN ("byte-to-position", Fbyte_to_position, Sbyte_to_position, 1, 1, 0,
1063 doc: /* Return the character position for byte position BYTEPOS.
1064 If BYTEPOS is out of range, the value is nil. */)
1065 (Lisp_Object bytepos)
1067 CHECK_NUMBER (bytepos);
1068 if (XINT (bytepos) < BEG_BYTE || XINT (bytepos) > Z_BYTE)
1069 return Qnil;
1070 return make_number (BYTE_TO_CHAR (XINT (bytepos)));
1073 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
1074 doc: /* Return the character following point, as a number.
1075 At the end of the buffer or accessible region, return 0. */)
1076 (void)
1078 Lisp_Object temp;
1079 if (PT >= ZV)
1080 XSETFASTINT (temp, 0);
1081 else
1082 XSETFASTINT (temp, FETCH_CHAR (PT_BYTE));
1083 return temp;
1086 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
1087 doc: /* Return the character preceding point, as a number.
1088 At the beginning of the buffer or accessible region, return 0. */)
1089 (void)
1091 Lisp_Object temp;
1092 if (PT <= BEGV)
1093 XSETFASTINT (temp, 0);
1094 else if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1096 ptrdiff_t pos = PT_BYTE;
1097 DEC_POS (pos);
1098 XSETFASTINT (temp, FETCH_CHAR (pos));
1100 else
1101 XSETFASTINT (temp, FETCH_BYTE (PT_BYTE - 1));
1102 return temp;
1105 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
1106 doc: /* Return t if point is at the beginning of the buffer.
1107 If the buffer is narrowed, this means the beginning of the narrowed part. */)
1108 (void)
1110 if (PT == BEGV)
1111 return Qt;
1112 return Qnil;
1115 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
1116 doc: /* Return t if point is at the end of the buffer.
1117 If the buffer is narrowed, this means the end of the narrowed part. */)
1118 (void)
1120 if (PT == ZV)
1121 return Qt;
1122 return Qnil;
1125 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
1126 doc: /* Return t if point is at the beginning of a line. */)
1127 (void)
1129 if (PT == BEGV || FETCH_BYTE (PT_BYTE - 1) == '\n')
1130 return Qt;
1131 return Qnil;
1134 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
1135 doc: /* Return t if point is at the end of a line.
1136 `End of a line' includes point being at the end of the buffer. */)
1137 (void)
1139 if (PT == ZV || FETCH_BYTE (PT_BYTE) == '\n')
1140 return Qt;
1141 return Qnil;
1144 DEFUN ("char-after", Fchar_after, Schar_after, 0, 1, 0,
1145 doc: /* Return character in current buffer at position POS.
1146 POS is an integer or a marker and defaults to point.
1147 If POS is out of range, the value is nil. */)
1148 (Lisp_Object pos)
1150 register ptrdiff_t pos_byte;
1152 if (NILP (pos))
1154 pos_byte = PT_BYTE;
1155 XSETFASTINT (pos, PT);
1158 if (MARKERP (pos))
1160 pos_byte = marker_byte_position (pos);
1161 if (pos_byte < BEGV_BYTE || pos_byte >= ZV_BYTE)
1162 return Qnil;
1164 else
1166 CHECK_NUMBER_COERCE_MARKER (pos);
1167 if (XINT (pos) < BEGV || XINT (pos) >= ZV)
1168 return Qnil;
1170 pos_byte = CHAR_TO_BYTE (XINT (pos));
1173 return make_number (FETCH_CHAR (pos_byte));
1176 DEFUN ("char-before", Fchar_before, Schar_before, 0, 1, 0,
1177 doc: /* Return character in current buffer preceding position POS.
1178 POS is an integer or a marker and defaults to point.
1179 If POS is out of range, the value is nil. */)
1180 (Lisp_Object pos)
1182 register Lisp_Object val;
1183 register ptrdiff_t pos_byte;
1185 if (NILP (pos))
1187 pos_byte = PT_BYTE;
1188 XSETFASTINT (pos, PT);
1191 if (MARKERP (pos))
1193 pos_byte = marker_byte_position (pos);
1195 if (pos_byte <= BEGV_BYTE || pos_byte > ZV_BYTE)
1196 return Qnil;
1198 else
1200 CHECK_NUMBER_COERCE_MARKER (pos);
1202 if (XINT (pos) <= BEGV || XINT (pos) > ZV)
1203 return Qnil;
1205 pos_byte = CHAR_TO_BYTE (XINT (pos));
1208 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
1210 DEC_POS (pos_byte);
1211 XSETFASTINT (val, FETCH_CHAR (pos_byte));
1213 else
1215 pos_byte--;
1216 XSETFASTINT (val, FETCH_BYTE (pos_byte));
1218 return val;
1221 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
1222 doc: /* Return the name under which the user logged in, as a string.
1223 This is based on the effective uid, not the real uid.
1224 Also, if the environment variables LOGNAME or USER are set,
1225 that determines the value of this function.
1227 If optional argument UID is an integer or a float, return the login name
1228 of the user with that uid, or nil if there is no such user. */)
1229 (Lisp_Object uid)
1231 struct passwd *pw;
1232 uid_t id;
1234 /* Set up the user name info if we didn't do it before.
1235 (That can happen if Emacs is dumpable
1236 but you decide to run `temacs -l loadup' and not dump. */
1237 if (INTEGERP (Vuser_login_name))
1238 init_editfns ();
1240 if (NILP (uid))
1241 return Vuser_login_name;
1243 CONS_TO_INTEGER (uid, uid_t, id);
1244 block_input ();
1245 pw = getpwuid (id);
1246 unblock_input ();
1247 return (pw ? build_string (pw->pw_name) : Qnil);
1250 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
1251 0, 0, 0,
1252 doc: /* Return the name of the user's real uid, as a string.
1253 This ignores the environment variables LOGNAME and USER, so it differs from
1254 `user-login-name' when running under `su'. */)
1255 (void)
1257 /* Set up the user name info if we didn't do it before.
1258 (That can happen if Emacs is dumpable
1259 but you decide to run `temacs -l loadup' and not dump. */
1260 if (INTEGERP (Vuser_login_name))
1261 init_editfns ();
1262 return Vuser_real_login_name;
1265 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
1266 doc: /* Return the effective uid of Emacs.
1267 Value is an integer or a float, depending on the value. */)
1268 (void)
1270 uid_t euid = geteuid ();
1271 return make_fixnum_or_float (euid);
1274 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
1275 doc: /* Return the real uid of Emacs.
1276 Value is an integer or a float, depending on the value. */)
1277 (void)
1279 uid_t uid = getuid ();
1280 return make_fixnum_or_float (uid);
1283 DEFUN ("group-gid", Fgroup_gid, Sgroup_gid, 0, 0, 0,
1284 doc: /* Return the effective gid of Emacs.
1285 Value is an integer or a float, depending on the value. */)
1286 (void)
1288 gid_t egid = getegid ();
1289 return make_fixnum_or_float (egid);
1292 DEFUN ("group-real-gid", Fgroup_real_gid, Sgroup_real_gid, 0, 0, 0,
1293 doc: /* Return the real gid of Emacs.
1294 Value is an integer or a float, depending on the value. */)
1295 (void)
1297 gid_t gid = getgid ();
1298 return make_fixnum_or_float (gid);
1301 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 1, 0,
1302 doc: /* Return the full name of the user logged in, as a string.
1303 If the full name corresponding to Emacs's userid is not known,
1304 return "unknown".
1306 If optional argument UID is an integer or float, return the full name
1307 of the user with that uid, or nil if there is no such user.
1308 If UID is a string, return the full name of the user with that login
1309 name, or nil if there is no such user. */)
1310 (Lisp_Object uid)
1312 struct passwd *pw;
1313 register char *p, *q;
1314 Lisp_Object full;
1316 if (NILP (uid))
1317 return Vuser_full_name;
1318 else if (NUMBERP (uid))
1320 uid_t u;
1321 CONS_TO_INTEGER (uid, uid_t, u);
1322 block_input ();
1323 pw = getpwuid (u);
1324 unblock_input ();
1326 else if (STRINGP (uid))
1328 block_input ();
1329 pw = getpwnam (SSDATA (uid));
1330 unblock_input ();
1332 else
1333 error ("Invalid UID specification");
1335 if (!pw)
1336 return Qnil;
1338 p = USER_FULL_NAME;
1339 /* Chop off everything after the first comma. */
1340 q = strchr (p, ',');
1341 full = make_string (p, q ? q - p : strlen (p));
1343 #ifdef AMPERSAND_FULL_NAME
1344 p = SSDATA (full);
1345 q = strchr (p, '&');
1346 /* Substitute the login name for the &, upcasing the first character. */
1347 if (q)
1349 Lisp_Object login = Fuser_login_name (make_number (pw->pw_uid));
1350 USE_SAFE_ALLOCA;
1351 char *r = SAFE_ALLOCA (strlen (p) + SBYTES (login) + 1);
1352 memcpy (r, p, q - p);
1353 r[q - p] = 0;
1354 strcat (r, SSDATA (login));
1355 r[q - p] = upcase ((unsigned char) r[q - p]);
1356 strcat (r, q + 1);
1357 full = build_string (r);
1358 SAFE_FREE ();
1360 #endif /* AMPERSAND_FULL_NAME */
1362 return full;
1365 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
1366 doc: /* Return the host name of the machine you are running on, as a string. */)
1367 (void)
1369 return Vsystem_name;
1372 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
1373 doc: /* Return the process ID of Emacs, as a number. */)
1374 (void)
1376 pid_t pid = getpid ();
1377 return make_fixnum_or_float (pid);
1382 #ifndef TIME_T_MIN
1383 # define TIME_T_MIN TYPE_MINIMUM (time_t)
1384 #endif
1385 #ifndef TIME_T_MAX
1386 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
1387 #endif
1389 /* Report that a time value is out of range for Emacs. */
1390 void
1391 time_overflow (void)
1393 error ("Specified time is not representable");
1396 static void
1397 invalid_time (void)
1399 error ("Invalid time specification");
1402 /* A substitute for mktime_z on platforms that lack it. It's not
1403 thread-safe, but should be good enough for Emacs in typical use. */
1404 #ifndef HAVE_TZALLOC
1405 time_t
1406 mktime_z (timezone_t tz, struct tm *tm)
1408 char *oldtz = getenv ("TZ");
1409 USE_SAFE_ALLOCA;
1410 if (oldtz)
1412 size_t oldtzsize = strlen (oldtz) + 1;
1413 char *oldtzcopy = SAFE_ALLOCA (oldtzsize);
1414 oldtz = strcpy (oldtzcopy, oldtz);
1416 block_input ();
1417 set_time_zone_rule (tz);
1418 time_t t = mktime (tm);
1419 set_time_zone_rule (oldtz);
1420 unblock_input ();
1421 SAFE_FREE ();
1422 return t;
1424 #endif
1426 /* Return the upper part of the time T (everything but the bottom 16 bits). */
1427 static EMACS_INT
1428 hi_time (time_t t)
1430 time_t hi = t >> LO_TIME_BITS;
1432 /* Check for overflow, helping the compiler for common cases where
1433 no runtime check is needed, and taking care not to convert
1434 negative numbers to unsigned before comparing them. */
1435 if (! ((! TYPE_SIGNED (time_t)
1436 || MOST_NEGATIVE_FIXNUM <= TIME_T_MIN >> LO_TIME_BITS
1437 || MOST_NEGATIVE_FIXNUM <= hi)
1438 && (TIME_T_MAX >> LO_TIME_BITS <= MOST_POSITIVE_FIXNUM
1439 || hi <= MOST_POSITIVE_FIXNUM)))
1440 time_overflow ();
1442 return hi;
1445 /* Return the bottom bits of the time T. */
1446 static int
1447 lo_time (time_t t)
1449 return t & ((1 << LO_TIME_BITS) - 1);
1452 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
1453 doc: /* Return the current time, as the number of seconds since 1970-01-01 00:00:00.
1454 The time is returned as a list of integers (HIGH LOW USEC PSEC).
1455 HIGH has the most significant bits of the seconds, while LOW has the
1456 least significant 16 bits. USEC and PSEC are the microsecond and
1457 picosecond counts. */)
1458 (void)
1460 return make_lisp_time (current_timespec ());
1463 static struct lisp_time
1464 time_add (struct lisp_time ta, struct lisp_time tb)
1466 EMACS_INT hi = ta.hi + tb.hi;
1467 int lo = ta.lo + tb.lo;
1468 int us = ta.us + tb.us;
1469 int ps = ta.ps + tb.ps;
1470 us += (1000000 <= ps);
1471 ps -= (1000000 <= ps) * 1000000;
1472 lo += (1000000 <= us);
1473 us -= (1000000 <= us) * 1000000;
1474 hi += (1 << LO_TIME_BITS <= lo);
1475 lo -= (1 << LO_TIME_BITS <= lo) << LO_TIME_BITS;
1476 return (struct lisp_time) { hi, lo, us, ps };
1479 static struct lisp_time
1480 time_subtract (struct lisp_time ta, struct lisp_time tb)
1482 EMACS_INT hi = ta.hi - tb.hi;
1483 int lo = ta.lo - tb.lo;
1484 int us = ta.us - tb.us;
1485 int ps = ta.ps - tb.ps;
1486 us -= (ps < 0);
1487 ps += (ps < 0) * 1000000;
1488 lo -= (us < 0);
1489 us += (us < 0) * 1000000;
1490 hi -= (lo < 0);
1491 lo += (lo < 0) << LO_TIME_BITS;
1492 return (struct lisp_time) { hi, lo, us, ps };
1495 static Lisp_Object
1496 time_arith (Lisp_Object a, Lisp_Object b,
1497 struct lisp_time (*op) (struct lisp_time, struct lisp_time))
1499 int alen, blen;
1500 struct lisp_time ta = lisp_time_struct (a, &alen);
1501 struct lisp_time tb = lisp_time_struct (b, &blen);
1502 struct lisp_time t = op (ta, tb);
1503 if (! (MOST_NEGATIVE_FIXNUM <= t.hi && t.hi <= MOST_POSITIVE_FIXNUM))
1504 time_overflow ();
1505 Lisp_Object val = Qnil;
1507 switch (max (alen, blen))
1509 default:
1510 val = Fcons (make_number (t.ps), val);
1511 /* Fall through. */
1512 case 3:
1513 val = Fcons (make_number (t.us), val);
1514 /* Fall through. */
1515 case 2:
1516 val = Fcons (make_number (t.lo), val);
1517 val = Fcons (make_number (t.hi), val);
1518 break;
1521 return val;
1524 DEFUN ("time-add", Ftime_add, Stime_add, 2, 2, 0,
1525 doc: /* Return the sum of two time values A and B, as a time value. */)
1526 (Lisp_Object a, Lisp_Object b)
1528 return time_arith (a, b, time_add);
1531 DEFUN ("time-subtract", Ftime_subtract, Stime_subtract, 2, 2, 0,
1532 doc: /* Return the difference between two time values A and B, as a time value. */)
1533 (Lisp_Object a, Lisp_Object b)
1535 return time_arith (a, b, time_subtract);
1538 DEFUN ("time-less-p", Ftime_less_p, Stime_less_p, 2, 2, 0,
1539 doc: /* Return non-nil if time value T1 is earlier than time value T2. */)
1540 (Lisp_Object t1, Lisp_Object t2)
1542 int t1len, t2len;
1543 struct lisp_time a = lisp_time_struct (t1, &t1len);
1544 struct lisp_time b = lisp_time_struct (t2, &t2len);
1545 return ((a.hi != b.hi ? a.hi < b.hi
1546 : a.lo != b.lo ? a.lo < b.lo
1547 : a.us != b.us ? a.us < b.us
1548 : a.ps < b.ps)
1549 ? Qt : Qnil);
1553 DEFUN ("get-internal-run-time", Fget_internal_run_time, Sget_internal_run_time,
1554 0, 0, 0,
1555 doc: /* Return the current run time used by Emacs.
1556 The time is returned as a list (HIGH LOW USEC PSEC), using the same
1557 style as (current-time).
1559 On systems that can't determine the run time, `get-internal-run-time'
1560 does the same thing as `current-time'. */)
1561 (void)
1563 #ifdef HAVE_GETRUSAGE
1564 struct rusage usage;
1565 time_t secs;
1566 int usecs;
1568 if (getrusage (RUSAGE_SELF, &usage) < 0)
1569 /* This shouldn't happen. What action is appropriate? */
1570 xsignal0 (Qerror);
1572 /* Sum up user time and system time. */
1573 secs = usage.ru_utime.tv_sec + usage.ru_stime.tv_sec;
1574 usecs = usage.ru_utime.tv_usec + usage.ru_stime.tv_usec;
1575 if (usecs >= 1000000)
1577 usecs -= 1000000;
1578 secs++;
1580 return make_lisp_time (make_timespec (secs, usecs * 1000));
1581 #else /* ! HAVE_GETRUSAGE */
1582 #ifdef WINDOWSNT
1583 return w32_get_internal_run_time ();
1584 #else /* ! WINDOWSNT */
1585 return Fcurrent_time ();
1586 #endif /* WINDOWSNT */
1587 #endif /* HAVE_GETRUSAGE */
1591 /* Make a Lisp list that represents the Emacs time T. T may be an
1592 invalid time, with a slightly negative tv_nsec value such as
1593 UNKNOWN_MODTIME_NSECS; in that case, the Lisp list contains a
1594 correspondingly negative picosecond count. */
1595 Lisp_Object
1596 make_lisp_time (struct timespec t)
1598 time_t s = t.tv_sec;
1599 int ns = t.tv_nsec;
1600 return list4i (hi_time (s), lo_time (s), ns / 1000, ns % 1000 * 1000);
1603 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1604 Set *PHIGH, *PLOW, *PUSEC, *PPSEC to its parts; do not check their values.
1605 Return 2, 3, or 4 to indicate the effective length of SPECIFIED_TIME
1606 if successful, 0 if unsuccessful. */
1607 static int
1608 disassemble_lisp_time (Lisp_Object specified_time, Lisp_Object *phigh,
1609 Lisp_Object *plow, Lisp_Object *pusec,
1610 Lisp_Object *ppsec)
1612 Lisp_Object high = make_number (0);
1613 Lisp_Object low = specified_time;
1614 Lisp_Object usec = make_number (0);
1615 Lisp_Object psec = make_number (0);
1616 int len = 4;
1618 if (CONSP (specified_time))
1620 high = XCAR (specified_time);
1621 low = XCDR (specified_time);
1622 if (CONSP (low))
1624 Lisp_Object low_tail = XCDR (low);
1625 low = XCAR (low);
1626 if (CONSP (low_tail))
1628 usec = XCAR (low_tail);
1629 low_tail = XCDR (low_tail);
1630 if (CONSP (low_tail))
1631 psec = XCAR (low_tail);
1632 else
1633 len = 3;
1635 else if (!NILP (low_tail))
1637 usec = low_tail;
1638 len = 3;
1640 else
1641 len = 2;
1643 else
1644 len = 2;
1646 /* When combining components, require LOW to be an integer,
1647 as otherwise it would be a pain to add up times. */
1648 if (! INTEGERP (low))
1649 return 0;
1651 else if (INTEGERP (specified_time))
1652 len = 2;
1654 *phigh = high;
1655 *plow = low;
1656 *pusec = usec;
1657 *ppsec = psec;
1658 return len;
1661 /* Convert T into an Emacs time *RESULT, truncating toward minus infinity.
1662 Return true if T is in range, false otherwise. */
1663 static bool
1664 decode_float_time (double t, struct lisp_time *result)
1666 double lo_multiplier = 1 << LO_TIME_BITS;
1667 double emacs_time_min = MOST_NEGATIVE_FIXNUM * lo_multiplier;
1668 if (! (emacs_time_min <= t && t < -emacs_time_min))
1669 return false;
1671 double small_t = t / lo_multiplier;
1672 EMACS_INT hi = small_t;
1673 double t_sans_hi = t - hi * lo_multiplier;
1674 int lo = t_sans_hi;
1675 long double fracps = (t_sans_hi - lo) * 1e12L;
1676 #ifdef INT_FAST64_MAX
1677 int_fast64_t ifracps = fracps;
1678 int us = ifracps / 1000000;
1679 int ps = ifracps % 1000000;
1680 #else
1681 int us = fracps / 1e6L;
1682 int ps = fracps - us * 1e6L;
1683 #endif
1684 us -= (ps < 0);
1685 ps += (ps < 0) * 1000000;
1686 lo -= (us < 0);
1687 us += (us < 0) * 1000000;
1688 hi -= (lo < 0);
1689 lo += (lo < 0) << LO_TIME_BITS;
1690 result->hi = hi;
1691 result->lo = lo;
1692 result->us = us;
1693 result->ps = ps;
1694 return true;
1697 /* From the time components HIGH, LOW, USEC and PSEC taken from a Lisp
1698 list, generate the corresponding time value.
1699 If LOW is floating point, the other components should be zero.
1701 If RESULT is not null, store into *RESULT the converted time.
1702 If *DRESULT is not null, store into *DRESULT the number of
1703 seconds since the start of the POSIX Epoch.
1705 Return true if successful, false if the components are of the
1706 wrong type or represent a time out of range. */
1707 bool
1708 decode_time_components (Lisp_Object high, Lisp_Object low, Lisp_Object usec,
1709 Lisp_Object psec,
1710 struct lisp_time *result, double *dresult)
1712 EMACS_INT hi, lo, us, ps;
1713 if (! (INTEGERP (high)
1714 && INTEGERP (usec) && INTEGERP (psec)))
1715 return false;
1716 if (! INTEGERP (low))
1718 if (FLOATP (low))
1720 double t = XFLOAT_DATA (low);
1721 if (result && ! decode_float_time (t, result))
1722 return false;
1723 if (dresult)
1724 *dresult = t;
1725 return true;
1727 else if (NILP (low))
1729 struct timespec now = current_timespec ();
1730 if (result)
1732 result->hi = hi_time (now.tv_sec);
1733 result->lo = lo_time (now.tv_sec);
1734 result->us = now.tv_nsec / 1000;
1735 result->ps = now.tv_nsec % 1000 * 1000;
1737 if (dresult)
1738 *dresult = now.tv_sec + now.tv_nsec / 1e9;
1739 return true;
1741 else
1742 return false;
1745 hi = XINT (high);
1746 lo = XINT (low);
1747 us = XINT (usec);
1748 ps = XINT (psec);
1750 /* Normalize out-of-range lower-order components by carrying
1751 each overflow into the next higher-order component. */
1752 us += ps / 1000000 - (ps % 1000000 < 0);
1753 lo += us / 1000000 - (us % 1000000 < 0);
1754 hi += lo >> LO_TIME_BITS;
1755 ps = ps % 1000000 + 1000000 * (ps % 1000000 < 0);
1756 us = us % 1000000 + 1000000 * (us % 1000000 < 0);
1757 lo &= (1 << LO_TIME_BITS) - 1;
1759 if (result)
1761 if (! (MOST_NEGATIVE_FIXNUM <= hi && hi <= MOST_POSITIVE_FIXNUM))
1762 return false;
1763 result->hi = hi;
1764 result->lo = lo;
1765 result->us = us;
1766 result->ps = ps;
1769 if (dresult)
1771 double dhi = hi;
1772 *dresult = (us * 1e6 + ps) / 1e12 + lo + dhi * (1 << LO_TIME_BITS);
1775 return true;
1778 struct timespec
1779 lisp_to_timespec (struct lisp_time t)
1781 if (! ((TYPE_SIGNED (time_t) ? TIME_T_MIN >> LO_TIME_BITS <= t.hi : 0 <= t.hi)
1782 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1783 return invalid_timespec ();
1784 time_t s = (t.hi << LO_TIME_BITS) + t.lo;
1785 int ns = t.us * 1000 + t.ps / 1000;
1786 return make_timespec (s, ns);
1789 /* Decode a Lisp list SPECIFIED_TIME that represents a time.
1790 Store its effective length into *PLEN.
1791 If SPECIFIED_TIME is nil, use the current time.
1792 Signal an error if SPECIFIED_TIME does not represent a time. */
1793 static struct lisp_time
1794 lisp_time_struct (Lisp_Object specified_time, int *plen)
1796 Lisp_Object high, low, usec, psec;
1797 struct lisp_time t;
1798 int len = disassemble_lisp_time (specified_time, &high, &low, &usec, &psec);
1799 if (! (len && decode_time_components (high, low, usec, psec, &t, 0)))
1800 invalid_time ();
1801 *plen = len;
1802 return t;
1805 /* Like lisp_time_struct, except return a struct timespec.
1806 Discard any low-order digits. */
1807 struct timespec
1808 lisp_time_argument (Lisp_Object specified_time)
1810 int len;
1811 struct lisp_time lt = lisp_time_struct (specified_time, &len);
1812 struct timespec t = lisp_to_timespec (lt);
1813 if (! timespec_valid_p (t))
1814 time_overflow ();
1815 return t;
1818 /* Like lisp_time_argument, except decode only the seconds part,
1819 and do not check the subseconds part. */
1820 static time_t
1821 lisp_seconds_argument (Lisp_Object specified_time)
1823 Lisp_Object high, low, usec, psec;
1824 struct lisp_time t;
1825 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1826 && decode_time_components (high, low, make_number (0),
1827 make_number (0), &t, 0)))
1828 invalid_time ();
1829 if (! ((TYPE_SIGNED (time_t) ? TIME_T_MIN >> LO_TIME_BITS <= t.hi : 0 <= t.hi)
1830 && t.hi <= TIME_T_MAX >> LO_TIME_BITS))
1831 time_overflow ();
1832 return (t.hi << LO_TIME_BITS) + t.lo;
1835 DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
1836 doc: /* Return the current time, as a float number of seconds since the epoch.
1837 If SPECIFIED-TIME is given, it is the time to convert to float
1838 instead of the current time. The argument should have the form
1839 (HIGH LOW) or (HIGH LOW USEC) or (HIGH LOW USEC PSEC). Thus,
1840 you can use times from `current-time' and from `file-attributes'.
1841 SPECIFIED-TIME can also have the form (HIGH . LOW), but this is
1842 considered obsolete.
1844 WARNING: Since the result is floating point, it may not be exact.
1845 If precise time stamps are required, use either `current-time',
1846 or (if you need time as a string) `format-time-string'. */)
1847 (Lisp_Object specified_time)
1849 double t;
1850 Lisp_Object high, low, usec, psec;
1851 if (! (disassemble_lisp_time (specified_time, &high, &low, &usec, &psec)
1852 && decode_time_components (high, low, usec, psec, 0, &t)))
1853 invalid_time ();
1854 return make_float (t);
1857 /* Write information into buffer S of size MAXSIZE, according to the
1858 FORMAT of length FORMAT_LEN, using time information taken from *TP.
1859 Default to Universal Time if UT, local time otherwise.
1860 Use NS as the number of nanoseconds in the %N directive.
1861 Return the number of bytes written, not including the terminating
1862 '\0'. If S is NULL, nothing will be written anywhere; so to
1863 determine how many bytes would be written, use NULL for S and
1864 ((size_t) -1) for MAXSIZE.
1866 This function behaves like nstrftime, except it allows null
1867 bytes in FORMAT and it does not support nanoseconds. */
1868 static size_t
1869 emacs_nmemftime (char *s, size_t maxsize, const char *format,
1870 size_t format_len, const struct tm *tp, bool ut, int ns)
1872 size_t total = 0;
1874 /* Loop through all the null-terminated strings in the format
1875 argument. Normally there's just one null-terminated string, but
1876 there can be arbitrarily many, concatenated together, if the
1877 format contains '\0' bytes. nstrftime stops at the first
1878 '\0' byte so we must invoke it separately for each such string. */
1879 for (;;)
1881 size_t len;
1882 size_t result;
1884 if (s)
1885 s[0] = '\1';
1887 result = nstrftime (s, maxsize, format, tp, ut, ns);
1889 if (s)
1891 if (result == 0 && s[0] != '\0')
1892 return 0;
1893 s += result + 1;
1896 maxsize -= result + 1;
1897 total += result;
1898 len = strlen (format);
1899 if (len == format_len)
1900 return total;
1901 total++;
1902 format += len + 1;
1903 format_len -= len + 1;
1907 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
1908 doc: /* Use FORMAT-STRING to format the time TIME, or now if omitted.
1909 TIME is specified as (HIGH LOW USEC PSEC), as returned by
1910 `current-time' or `file-attributes'. The obsolete form (HIGH . LOW)
1911 is also still accepted.
1912 The third, optional, argument UNIVERSAL, if non-nil, means describe TIME
1913 as Universal Time; nil means describe TIME in the local time zone.
1914 The value is a copy of FORMAT-STRING, but with certain constructs replaced
1915 by text that describes the specified date and time in TIME:
1917 %Y is the year, %y within the century, %C the century.
1918 %G is the year corresponding to the ISO week, %g within the century.
1919 %m is the numeric month.
1920 %b and %h are the locale's abbreviated month name, %B the full name.
1921 (%h is not supported on MS-Windows.)
1922 %d is the day of the month, zero-padded, %e is blank-padded.
1923 %u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
1924 %a is the locale's abbreviated name of the day of week, %A the full name.
1925 %U is the week number starting on Sunday, %W starting on Monday,
1926 %V according to ISO 8601.
1927 %j is the day of the year.
1929 %H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
1930 only blank-padded, %l is like %I blank-padded.
1931 %p is the locale's equivalent of either AM or PM.
1932 %M is the minute.
1933 %S is the second.
1934 %N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
1935 %Z is the time zone name, %z is the numeric form.
1936 %s is the number of seconds since 1970-01-01 00:00:00 +0000.
1938 %c is the locale's date and time format.
1939 %x is the locale's "preferred" date format.
1940 %D is like "%m/%d/%y".
1941 %F is the ISO 8601 date format (like "%Y-%m-%d").
1943 %R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
1944 %X is the locale's "preferred" time format.
1946 Finally, %n is a newline, %t is a tab, %% is a literal %.
1948 Certain flags and modifiers are available with some format controls.
1949 The flags are `_', `-', `^' and `#'. For certain characters X,
1950 %_X is like %X, but padded with blanks; %-X is like %X,
1951 but without padding. %^X is like %X, but with all textual
1952 characters up-cased; %#X is like %X, but with letter-case of
1953 all textual characters reversed.
1954 %NX (where N stands for an integer) is like %X,
1955 but takes up at least N (a number) positions.
1956 The modifiers are `E' and `O'. For certain characters X,
1957 %EX is a locale's alternative version of %X;
1958 %OX is like %X, but uses the locale's number symbols.
1960 For example, to produce full ISO 8601 format, use "%FT%T%z".
1962 usage: (format-time-string FORMAT-STRING &optional TIME UNIVERSAL) */)
1963 (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object universal)
1965 struct timespec t = lisp_time_argument (timeval);
1966 struct tm tm;
1968 CHECK_STRING (format_string);
1969 format_string = code_convert_string_norecord (format_string,
1970 Vlocale_coding_system, 1);
1971 return format_time_string (SSDATA (format_string), SBYTES (format_string),
1972 t, ! NILP (universal), &tm);
1975 static Lisp_Object
1976 format_time_string (char const *format, ptrdiff_t formatlen,
1977 struct timespec t, bool ut, struct tm *tmp)
1979 char buffer[4000];
1980 char *buf = buffer;
1981 ptrdiff_t size = sizeof buffer;
1982 size_t len;
1983 Lisp_Object bufstring;
1984 int ns = t.tv_nsec;
1985 USE_SAFE_ALLOCA;
1987 tmp = ut ? gmtime_r (&t.tv_sec, tmp) : localtime_r (&t.tv_sec, tmp);
1988 if (! tmp)
1989 time_overflow ();
1990 synchronize_system_time_locale ();
1992 while (true)
1994 buf[0] = '\1';
1995 len = emacs_nmemftime (buf, size, format, formatlen, tmp, ut, ns);
1996 if ((0 < len && len < size) || (len == 0 && buf[0] == '\0'))
1997 break;
1999 /* Buffer was too small, so make it bigger and try again. */
2000 len = emacs_nmemftime (NULL, SIZE_MAX, format, formatlen, tmp, ut, ns);
2001 if (STRING_BYTES_BOUND <= len)
2002 string_overflow ();
2003 size = len + 1;
2004 buf = SAFE_ALLOCA (size);
2007 bufstring = make_unibyte_string (buf, len);
2008 SAFE_FREE ();
2009 return code_convert_string_norecord (bufstring, Vlocale_coding_system, 0);
2012 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
2013 doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).
2014 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED),
2015 as from `current-time' and `file-attributes', or nil to use the
2016 current time. The obsolete form (HIGH . LOW) is also still accepted.
2017 The list has the following nine members: SEC is an integer between 0
2018 and 60; SEC is 60 for a leap second, which only some operating systems
2019 support. MINUTE is an integer between 0 and 59. HOUR is an integer
2020 between 0 and 23. DAY is an integer between 1 and 31. MONTH is an
2021 integer between 1 and 12. YEAR is an integer indicating the
2022 four-digit year. DOW is the day of week, an integer between 0 and 6,
2023 where 0 is Sunday. DST is t if daylight saving time is in effect,
2024 otherwise nil. ZONE is an integer indicating the number of seconds
2025 east of Greenwich. (Note that Common Lisp has different meanings for
2026 DOW and ZONE.) */)
2027 (Lisp_Object specified_time)
2029 time_t time_spec = lisp_seconds_argument (specified_time);
2030 struct tm local_tm, gmt_tm;
2032 if (! (localtime_r (&time_spec, &local_tm)
2033 && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= local_tm.tm_year
2034 && local_tm.tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE))
2035 time_overflow ();
2037 /* Avoid overflow when INT_MAX < EMACS_INT_MAX. */
2038 EMACS_INT tm_year_base = TM_YEAR_BASE;
2040 return Flist (9, ((Lisp_Object [])
2041 {make_number (local_tm.tm_sec),
2042 make_number (local_tm.tm_min),
2043 make_number (local_tm.tm_hour),
2044 make_number (local_tm.tm_mday),
2045 make_number (local_tm.tm_mon + 1),
2046 make_number (local_tm.tm_year + tm_year_base),
2047 make_number (local_tm.tm_wday),
2048 local_tm.tm_isdst ? Qt : Qnil,
2049 (HAVE_TM_GMTOFF
2050 ? make_number (tm_gmtoff (&local_tm))
2051 : gmtime_r (&time_spec, &gmt_tm)
2052 ? make_number (tm_diff (&local_tm, &gmt_tm))
2053 : Qnil)}));
2056 /* Return OBJ - OFFSET, checking that OBJ is a valid fixnum and that
2057 the result is representable as an int. Assume OFFSET is small and
2058 nonnegative. */
2059 static int
2060 check_tm_member (Lisp_Object obj, int offset)
2062 EMACS_INT n;
2063 CHECK_NUMBER (obj);
2064 n = XINT (obj);
2065 if (! (INT_MIN + offset <= n && n - offset <= INT_MAX))
2066 time_overflow ();
2067 return n - offset;
2070 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
2071 doc: /* Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.
2072 This is the reverse operation of `decode-time', which see.
2073 ZONE defaults to the current time zone rule. This can
2074 be a string or t (as from `set-time-zone-rule'), or it can be a list
2075 \(as from `current-time-zone') or an integer (as from `decode-time')
2076 applied without consideration for daylight saving time.
2078 You can pass more than 7 arguments; then the first six arguments
2079 are used as SECOND through YEAR, and the *last* argument is used as ZONE.
2080 The intervening arguments are ignored.
2081 This feature lets (apply 'encode-time (decode-time ...)) work.
2083 Out-of-range values for SECOND, MINUTE, HOUR, DAY, or MONTH are allowed;
2084 for example, a DAY of 0 means the day preceding the given month.
2085 Year numbers less than 100 are treated just like other year numbers.
2086 If you want them to stand for years in this century, you must do that yourself.
2088 Years before 1970 are not guaranteed to work. On some systems,
2089 year values as low as 1901 do work.
2091 usage: (encode-time SECOND MINUTE HOUR DAY MONTH YEAR &optional ZONE) */)
2092 (ptrdiff_t nargs, Lisp_Object *args)
2094 time_t value;
2095 struct tm tm;
2096 Lisp_Object zone = (nargs > 6 ? args[nargs - 1] : Qnil);
2098 tm.tm_sec = check_tm_member (args[0], 0);
2099 tm.tm_min = check_tm_member (args[1], 0);
2100 tm.tm_hour = check_tm_member (args[2], 0);
2101 tm.tm_mday = check_tm_member (args[3], 0);
2102 tm.tm_mon = check_tm_member (args[4], 1);
2103 tm.tm_year = check_tm_member (args[5], TM_YEAR_BASE);
2104 tm.tm_isdst = -1;
2106 if (CONSP (zone))
2107 zone = XCAR (zone);
2108 if (NILP (zone))
2109 value = mktime (&tm);
2110 else
2112 static char const tzbuf_format[] = "XXX%s%"pI"d:%02d:%02d";
2113 char tzbuf[sizeof tzbuf_format + INT_STRLEN_BOUND (EMACS_INT)];
2114 const char *tzstring;
2116 if (EQ (zone, Qt))
2117 tzstring = "UTC0";
2118 else if (STRINGP (zone))
2119 tzstring = SSDATA (zone);
2120 else if (INTEGERP (zone))
2122 EMACS_INT abszone = eabs (XINT (zone));
2123 EMACS_INT zone_hr = abszone / (60*60);
2124 int zone_min = (abszone/60) % 60;
2125 int zone_sec = abszone % 60;
2126 sprintf (tzbuf, tzbuf_format, &"-"[XINT (zone) < 0],
2127 zone_hr, zone_min, zone_sec);
2128 tzstring = tzbuf;
2130 else
2131 tzstring = 0;
2133 timezone_t tz = tzstring ? tzalloc (tzstring) : 0;
2134 if (! tz)
2135 error ("Invalid time zone specification");
2136 value = mktime_z (tz, &tm);
2137 tzfree (tz);
2140 if (value == (time_t) -1)
2141 time_overflow ();
2143 return list2i (hi_time (value), lo_time (value));
2146 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
2147 doc: /* Return the current local time, as a human-readable string.
2148 Programs can use this function to decode a time,
2149 since the number of columns in each field is fixed
2150 if the year is in the range 1000-9999.
2151 The format is `Sun Sep 16 01:03:52 1973'.
2152 However, see also the functions `decode-time' and `format-time-string'
2153 which provide a much more powerful and general facility.
2155 If SPECIFIED-TIME is given, it is a time to format instead of the
2156 current time. The argument should have the form (HIGH LOW . IGNORED).
2157 Thus, you can use times obtained from `current-time' and from
2158 `file-attributes'. SPECIFIED-TIME can also have the form (HIGH . LOW),
2159 but this is considered obsolete. */)
2160 (Lisp_Object specified_time)
2162 time_t value = lisp_seconds_argument (specified_time);
2164 /* Convert to a string in ctime format, except without the trailing
2165 newline, and without the 4-digit year limit. Don't use asctime
2166 or ctime, as they might dump core if the year is outside the
2167 range -999 .. 9999. */
2168 struct tm tm;
2169 if (! localtime_r (&value, &tm))
2170 time_overflow ();
2172 static char const wday_name[][4] =
2173 { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
2174 static char const mon_name[][4] =
2175 { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2176 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
2177 printmax_t year_base = TM_YEAR_BASE;
2178 char buf[sizeof "Mon Apr 30 12:49:17 " + INT_STRLEN_BOUND (int) + 1];
2179 int len = sprintf (buf, "%s %s%3d %02d:%02d:%02d %"pMd,
2180 wday_name[tm.tm_wday], mon_name[tm.tm_mon], tm.tm_mday,
2181 tm.tm_hour, tm.tm_min, tm.tm_sec,
2182 tm.tm_year + year_base);
2184 return make_unibyte_string (buf, len);
2187 /* Yield A - B, measured in seconds.
2188 This function is copied from the GNU C Library. */
2189 static int
2190 tm_diff (struct tm *a, struct tm *b)
2192 /* Compute intervening leap days correctly even if year is negative.
2193 Take care to avoid int overflow in leap day calculations,
2194 but it's OK to assume that A and B are close to each other. */
2195 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2196 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2197 int a100 = a4 / 25 - (a4 % 25 < 0);
2198 int b100 = b4 / 25 - (b4 % 25 < 0);
2199 int a400 = a100 >> 2;
2200 int b400 = b100 >> 2;
2201 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2202 int years = a->tm_year - b->tm_year;
2203 int days = (365 * years + intervening_leap_days
2204 + (a->tm_yday - b->tm_yday));
2205 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2206 + (a->tm_min - b->tm_min))
2207 + (a->tm_sec - b->tm_sec));
2210 /* Yield A's UTC offset, or an unspecified value if unknown. */
2211 static long int
2212 tm_gmtoff (struct tm *a)
2214 #if HAVE_TM_GMTOFF
2215 return a->tm_gmtoff;
2216 #else
2217 return 0;
2218 #endif
2221 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
2222 doc: /* Return the offset and name for the local time zone.
2223 This returns a list of the form (OFFSET NAME).
2224 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).
2225 A negative value means west of Greenwich.
2226 NAME is a string giving the name of the time zone.
2227 If SPECIFIED-TIME is given, the time zone offset is determined from it
2228 instead of using the current time. The argument should have the form
2229 (HIGH LOW . IGNORED). Thus, you can use times obtained from
2230 `current-time' and from `file-attributes'. SPECIFIED-TIME can also
2231 have the form (HIGH . LOW), but this is considered obsolete.
2233 Some operating systems cannot provide all this information to Emacs;
2234 in this case, `current-time-zone' returns a list containing nil for
2235 the data it can't find. */)
2236 (Lisp_Object specified_time)
2238 struct timespec value;
2239 struct tm local_tm, gmt_tm;
2240 Lisp_Object zone_offset, zone_name;
2242 zone_offset = Qnil;
2243 value = make_timespec (lisp_seconds_argument (specified_time), 0);
2244 zone_name = format_time_string ("%Z", sizeof "%Z" - 1, value, 0, &local_tm);
2246 if (HAVE_TM_GMTOFF || gmtime_r (&value.tv_sec, &gmt_tm))
2248 long int offset = (HAVE_TM_GMTOFF
2249 ? tm_gmtoff (&local_tm)
2250 : tm_diff (&local_tm, &gmt_tm));
2251 zone_offset = make_number (offset);
2252 if (SCHARS (zone_name) == 0)
2254 /* No local time zone name is available; use "+-NNNN" instead. */
2255 long int m = offset / 60;
2256 long int am = offset < 0 ? - m : m;
2257 long int hour = am / 60;
2258 int min = am % 60;
2259 char buf[sizeof "+00" + INT_STRLEN_BOUND (long int)];
2260 zone_name = make_formatted_string (buf, "%c%02ld%02d",
2261 (offset < 0 ? '-' : '+'),
2262 hour, min);
2266 return list2 (zone_offset, zone_name);
2269 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
2270 doc: /* Set the local time zone using TZ, a string specifying a time zone rule.
2271 If TZ is nil, use implementation-defined default time zone information.
2272 If TZ is t, use Universal Time.
2274 Instead of calling this function, you typically want (setenv "TZ" TZ).
2275 That changes both the environment of the Emacs process and the
2276 variable `process-environment', whereas `set-time-zone-rule' affects
2277 only the former. */)
2278 (Lisp_Object tz)
2280 const char *tzstring;
2282 if (! (NILP (tz) || EQ (tz, Qt)))
2283 CHECK_STRING (tz);
2285 if (NILP (tz))
2286 tzstring = initial_tz;
2287 else if (EQ (tz, Qt))
2288 tzstring = "UTC0";
2289 else
2290 tzstring = SSDATA (tz);
2292 block_input ();
2293 set_time_zone_rule (tzstring);
2294 unblock_input ();
2296 return Qnil;
2299 /* Set the local time zone rule to TZSTRING.
2301 This function is not thread-safe, in theory because putenv is not,
2302 but mostly because of the static storage it updates. Other threads
2303 that invoke localtime etc. may be adversely affected while this
2304 function is executing. */
2306 static void
2307 set_time_zone_rule (const char *tzstring)
2309 /* A buffer holding a string of the form "TZ=value", intended
2310 to be part of the environment. */
2311 static char *tzvalbuf;
2312 static ptrdiff_t tzvalbufsize;
2314 int tzeqlen = sizeof "TZ=" - 1;
2315 ptrdiff_t tzstringlen = tzstring ? strlen (tzstring) : 0;
2316 char *tzval = tzvalbuf;
2317 bool new_tzvalbuf = tzvalbufsize <= tzeqlen + tzstringlen;
2319 if (new_tzvalbuf)
2321 /* Do not attempt to free the old tzvalbuf, since another thread
2322 may be using it. In practice, the first allocation is large
2323 enough and memory does not leak. */
2324 tzval = xpalloc (NULL, &tzvalbufsize,
2325 tzeqlen + tzstringlen - tzvalbufsize + 1, -1, 1);
2326 tzvalbuf = tzval;
2327 tzval[1] = 'Z';
2328 tzval[2] = '=';
2331 if (tzstring)
2333 /* Modify TZVAL in place. Although this is dicey in a
2334 multithreaded environment, we know of no portable alternative.
2335 Calling putenv or setenv could crash some other thread. */
2336 tzval[0] = 'T';
2337 strcpy (tzval + tzeqlen, tzstring);
2339 else
2341 /* Turn 'TZ=whatever' into an empty environment variable 'tZ='.
2342 Although this is also dicey, calling unsetenv here can crash Emacs.
2343 See Bug#8705. */
2344 tzval[0] = 't';
2345 tzval[tzeqlen] = 0;
2348 if (new_tzvalbuf)
2350 /* Although this is not thread-safe, in practice this runs only
2351 on startup when there is only one thread. */
2352 xputenv (tzval);
2355 #ifdef HAVE_TZSET
2356 tzset ();
2357 #endif
2360 /* Insert NARGS Lisp objects in the array ARGS by calling INSERT_FUNC
2361 (if a type of object is Lisp_Int) or INSERT_FROM_STRING_FUNC (if a
2362 type of object is Lisp_String). INHERIT is passed to
2363 INSERT_FROM_STRING_FUNC as the last argument. */
2365 static void
2366 general_insert_function (void (*insert_func)
2367 (const char *, ptrdiff_t),
2368 void (*insert_from_string_func)
2369 (Lisp_Object, ptrdiff_t, ptrdiff_t,
2370 ptrdiff_t, ptrdiff_t, bool),
2371 bool inherit, ptrdiff_t nargs, Lisp_Object *args)
2373 ptrdiff_t argnum;
2374 Lisp_Object val;
2376 for (argnum = 0; argnum < nargs; argnum++)
2378 val = args[argnum];
2379 if (CHARACTERP (val))
2381 int c = XFASTINT (val);
2382 unsigned char str[MAX_MULTIBYTE_LENGTH];
2383 int len;
2385 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2386 len = CHAR_STRING (c, str);
2387 else
2389 str[0] = CHAR_TO_BYTE8 (c);
2390 len = 1;
2392 (*insert_func) ((char *) str, len);
2394 else if (STRINGP (val))
2396 (*insert_from_string_func) (val, 0, 0,
2397 SCHARS (val),
2398 SBYTES (val),
2399 inherit);
2401 else
2402 wrong_type_argument (Qchar_or_string_p, val);
2406 void
2407 insert1 (Lisp_Object arg)
2409 Finsert (1, &arg);
2413 /* Callers passing one argument to Finsert need not gcpro the
2414 argument "array", since the only element of the array will
2415 not be used after calling insert or insert_from_string, so
2416 we don't care if it gets trashed. */
2418 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
2419 doc: /* Insert the arguments, either strings or characters, at point.
2420 Point and before-insertion markers move forward to end up
2421 after the inserted text.
2422 Any other markers at the point of insertion remain before the text.
2424 If the current buffer is multibyte, unibyte strings are converted
2425 to multibyte for insertion (see `string-make-multibyte').
2426 If the current buffer is unibyte, multibyte strings are converted
2427 to unibyte for insertion (see `string-make-unibyte').
2429 When operating on binary data, it may be necessary to preserve the
2430 original bytes of a unibyte string when inserting it into a multibyte
2431 buffer; to accomplish this, apply `string-as-multibyte' to the string
2432 and insert the result.
2434 usage: (insert &rest ARGS) */)
2435 (ptrdiff_t nargs, Lisp_Object *args)
2437 general_insert_function (insert, insert_from_string, 0, nargs, args);
2438 return Qnil;
2441 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
2442 0, MANY, 0,
2443 doc: /* Insert the arguments at point, inheriting properties from adjoining text.
2444 Point and before-insertion markers move forward to end up
2445 after the inserted text.
2446 Any other markers at the point of insertion remain before the text.
2448 If the current buffer is multibyte, unibyte strings are converted
2449 to multibyte for insertion (see `unibyte-char-to-multibyte').
2450 If the current buffer is unibyte, multibyte strings are converted
2451 to unibyte for insertion.
2453 usage: (insert-and-inherit &rest ARGS) */)
2454 (ptrdiff_t nargs, Lisp_Object *args)
2456 general_insert_function (insert_and_inherit, insert_from_string, 1,
2457 nargs, args);
2458 return Qnil;
2461 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
2462 doc: /* Insert strings or characters at point, relocating markers after the text.
2463 Point and markers move forward to end up after the inserted text.
2465 If the current buffer is multibyte, unibyte strings are converted
2466 to multibyte for insertion (see `unibyte-char-to-multibyte').
2467 If the current buffer is unibyte, multibyte strings are converted
2468 to unibyte for insertion.
2470 If an overlay begins at the insertion point, the inserted text falls
2471 outside the overlay; if a nonempty overlay ends at the insertion
2472 point, the inserted text falls inside that overlay.
2474 usage: (insert-before-markers &rest ARGS) */)
2475 (ptrdiff_t nargs, Lisp_Object *args)
2477 general_insert_function (insert_before_markers,
2478 insert_from_string_before_markers, 0,
2479 nargs, args);
2480 return Qnil;
2483 DEFUN ("insert-before-markers-and-inherit", Finsert_and_inherit_before_markers,
2484 Sinsert_and_inherit_before_markers, 0, MANY, 0,
2485 doc: /* Insert text at point, relocating markers and inheriting properties.
2486 Point and markers move forward to end up after the inserted text.
2488 If the current buffer is multibyte, unibyte strings are converted
2489 to multibyte for insertion (see `unibyte-char-to-multibyte').
2490 If the current buffer is unibyte, multibyte strings are converted
2491 to unibyte for insertion.
2493 usage: (insert-before-markers-and-inherit &rest ARGS) */)
2494 (ptrdiff_t nargs, Lisp_Object *args)
2496 general_insert_function (insert_before_markers_and_inherit,
2497 insert_from_string_before_markers, 1,
2498 nargs, args);
2499 return Qnil;
2502 DEFUN ("insert-char", Finsert_char, Sinsert_char, 1, 3,
2503 "(list (read-char-by-name \"Insert character (Unicode name or hex): \")\
2504 (prefix-numeric-value current-prefix-arg)\
2505 t))",
2506 doc: /* Insert COUNT copies of CHARACTER.
2507 Interactively, prompt for CHARACTER. You can specify CHARACTER in one
2508 of these ways:
2510 - As its Unicode character name, e.g. \"LATIN SMALL LETTER A\".
2511 Completion is available; if you type a substring of the name
2512 preceded by an asterisk `*', Emacs shows all names which include
2513 that substring, not necessarily at the beginning of the name.
2515 - As a hexadecimal code point, e.g. 263A. Note that code points in
2516 Emacs are equivalent to Unicode up to 10FFFF (which is the limit of
2517 the Unicode code space).
2519 - As a code point with a radix specified with #, e.g. #o21430
2520 (octal), #x2318 (hex), or #10r8984 (decimal).
2522 If called interactively, COUNT is given by the prefix argument. If
2523 omitted or nil, it defaults to 1.
2525 Inserting the character(s) relocates point and before-insertion
2526 markers in the same ways as the function `insert'.
2528 The optional third argument INHERIT, if non-nil, says to inherit text
2529 properties from adjoining text, if those properties are sticky. If
2530 called interactively, INHERIT is t. */)
2531 (Lisp_Object character, Lisp_Object count, Lisp_Object inherit)
2533 int i, stringlen;
2534 register ptrdiff_t n;
2535 int c, len;
2536 unsigned char str[MAX_MULTIBYTE_LENGTH];
2537 char string[4000];
2539 CHECK_CHARACTER (character);
2540 if (NILP (count))
2541 XSETFASTINT (count, 1);
2542 CHECK_NUMBER (count);
2543 c = XFASTINT (character);
2545 if (!NILP (BVAR (current_buffer, enable_multibyte_characters)))
2546 len = CHAR_STRING (c, str);
2547 else
2548 str[0] = c, len = 1;
2549 if (XINT (count) <= 0)
2550 return Qnil;
2551 if (BUF_BYTES_MAX / len < XINT (count))
2552 buffer_overflow ();
2553 n = XINT (count) * len;
2554 stringlen = min (n, sizeof string - sizeof string % len);
2555 for (i = 0; i < stringlen; i++)
2556 string[i] = str[i % len];
2557 while (n > stringlen)
2559 QUIT;
2560 if (!NILP (inherit))
2561 insert_and_inherit (string, stringlen);
2562 else
2563 insert (string, stringlen);
2564 n -= stringlen;
2566 if (!NILP (inherit))
2567 insert_and_inherit (string, n);
2568 else
2569 insert (string, n);
2570 return Qnil;
2573 DEFUN ("insert-byte", Finsert_byte, Sinsert_byte, 2, 3, 0,
2574 doc: /* Insert COUNT (second arg) copies of BYTE (first arg).
2575 Both arguments are required.
2576 BYTE is a number of the range 0..255.
2578 If BYTE is 128..255 and the current buffer is multibyte, the
2579 corresponding eight-bit character is inserted.
2581 Point, and before-insertion markers, are relocated as in the function `insert'.
2582 The optional third arg INHERIT, if non-nil, says to inherit text properties
2583 from adjoining text, if those properties are sticky. */)
2584 (Lisp_Object byte, Lisp_Object count, Lisp_Object inherit)
2586 CHECK_NUMBER (byte);
2587 if (XINT (byte) < 0 || XINT (byte) > 255)
2588 args_out_of_range_3 (byte, make_number (0), make_number (255));
2589 if (XINT (byte) >= 128
2590 && ! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2591 XSETFASTINT (byte, BYTE8_TO_CHAR (XINT (byte)));
2592 return Finsert_char (byte, count, inherit);
2596 /* Making strings from buffer contents. */
2598 /* Return a Lisp_String containing the text of the current buffer from
2599 START to END. If text properties are in use and the current buffer
2600 has properties in the range specified, the resulting string will also
2601 have them, if PROPS is true.
2603 We don't want to use plain old make_string here, because it calls
2604 make_uninit_string, which can cause the buffer arena to be
2605 compacted. make_string has no way of knowing that the data has
2606 been moved, and thus copies the wrong data into the string. This
2607 doesn't effect most of the other users of make_string, so it should
2608 be left as is. But we should use this function when conjuring
2609 buffer substrings. */
2611 Lisp_Object
2612 make_buffer_string (ptrdiff_t start, ptrdiff_t end, bool props)
2614 ptrdiff_t start_byte = CHAR_TO_BYTE (start);
2615 ptrdiff_t end_byte = CHAR_TO_BYTE (end);
2617 return make_buffer_string_both (start, start_byte, end, end_byte, props);
2620 /* Return a Lisp_String containing the text of the current buffer from
2621 START / START_BYTE to END / END_BYTE.
2623 If text properties are in use and the current buffer
2624 has properties in the range specified, the resulting string will also
2625 have them, if PROPS is true.
2627 We don't want to use plain old make_string here, because it calls
2628 make_uninit_string, which can cause the buffer arena to be
2629 compacted. make_string has no way of knowing that the data has
2630 been moved, and thus copies the wrong data into the string. This
2631 doesn't effect most of the other users of make_string, so it should
2632 be left as is. But we should use this function when conjuring
2633 buffer substrings. */
2635 Lisp_Object
2636 make_buffer_string_both (ptrdiff_t start, ptrdiff_t start_byte,
2637 ptrdiff_t end, ptrdiff_t end_byte, bool props)
2639 Lisp_Object result, tem, tem1;
2641 if (start < GPT && GPT < end)
2642 move_gap_both (start, start_byte);
2644 if (! NILP (BVAR (current_buffer, enable_multibyte_characters)))
2645 result = make_uninit_multibyte_string (end - start, end_byte - start_byte);
2646 else
2647 result = make_uninit_string (end - start);
2648 memcpy (SDATA (result), BYTE_POS_ADDR (start_byte), end_byte - start_byte);
2650 /* If desired, update and copy the text properties. */
2651 if (props)
2653 update_buffer_properties (start, end);
2655 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
2656 tem1 = Ftext_properties_at (make_number (start), Qnil);
2658 if (XINT (tem) != end || !NILP (tem1))
2659 copy_intervals_to_string (result, current_buffer, start,
2660 end - start);
2663 return result;
2666 /* Call Vbuffer_access_fontify_functions for the range START ... END
2667 in the current buffer, if necessary. */
2669 static void
2670 update_buffer_properties (ptrdiff_t start, ptrdiff_t end)
2672 /* If this buffer has some access functions,
2673 call them, specifying the range of the buffer being accessed. */
2674 if (!NILP (Vbuffer_access_fontify_functions))
2676 Lisp_Object args[3];
2677 Lisp_Object tem;
2679 args[0] = Qbuffer_access_fontify_functions;
2680 XSETINT (args[1], start);
2681 XSETINT (args[2], end);
2683 /* But don't call them if we can tell that the work
2684 has already been done. */
2685 if (!NILP (Vbuffer_access_fontified_property))
2687 tem = Ftext_property_any (args[1], args[2],
2688 Vbuffer_access_fontified_property,
2689 Qnil, Qnil);
2690 if (! NILP (tem))
2691 Frun_hook_with_args (3, args);
2693 else
2694 Frun_hook_with_args (3, args);
2698 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
2699 doc: /* Return the contents of part of the current buffer as a string.
2700 The two arguments START and END are character positions;
2701 they can be in either order.
2702 The string returned is multibyte if the buffer is multibyte.
2704 This function copies the text properties of that part of the buffer
2705 into the result string; if you don't want the text properties,
2706 use `buffer-substring-no-properties' instead. */)
2707 (Lisp_Object start, Lisp_Object end)
2709 register ptrdiff_t b, e;
2711 validate_region (&start, &end);
2712 b = XINT (start);
2713 e = XINT (end);
2715 return make_buffer_string (b, e, 1);
2718 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
2719 Sbuffer_substring_no_properties, 2, 2, 0,
2720 doc: /* Return the characters of part of the buffer, without the text properties.
2721 The two arguments START and END are character positions;
2722 they can be in either order. */)
2723 (Lisp_Object start, Lisp_Object end)
2725 register ptrdiff_t b, e;
2727 validate_region (&start, &end);
2728 b = XINT (start);
2729 e = XINT (end);
2731 return make_buffer_string (b, e, 0);
2734 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
2735 doc: /* Return the contents of the current buffer as a string.
2736 If narrowing is in effect, this function returns only the visible part
2737 of the buffer. */)
2738 (void)
2740 return make_buffer_string_both (BEGV, BEGV_BYTE, ZV, ZV_BYTE, 1);
2743 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
2744 1, 3, 0,
2745 doc: /* Insert before point a substring of the contents of BUFFER.
2746 BUFFER may be a buffer or a buffer name.
2747 Arguments START and END are character positions specifying the substring.
2748 They default to the values of (point-min) and (point-max) in BUFFER. */)
2749 (Lisp_Object buffer, Lisp_Object start, Lisp_Object end)
2751 register EMACS_INT b, e, temp;
2752 register struct buffer *bp, *obuf;
2753 Lisp_Object buf;
2755 buf = Fget_buffer (buffer);
2756 if (NILP (buf))
2757 nsberror (buffer);
2758 bp = XBUFFER (buf);
2759 if (!BUFFER_LIVE_P (bp))
2760 error ("Selecting deleted buffer");
2762 if (NILP (start))
2763 b = BUF_BEGV (bp);
2764 else
2766 CHECK_NUMBER_COERCE_MARKER (start);
2767 b = XINT (start);
2769 if (NILP (end))
2770 e = BUF_ZV (bp);
2771 else
2773 CHECK_NUMBER_COERCE_MARKER (end);
2774 e = XINT (end);
2777 if (b > e)
2778 temp = b, b = e, e = temp;
2780 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
2781 args_out_of_range (start, end);
2783 obuf = current_buffer;
2784 set_buffer_internal_1 (bp);
2785 update_buffer_properties (b, e);
2786 set_buffer_internal_1 (obuf);
2788 insert_from_buffer (bp, b, e - b, 0);
2789 return Qnil;
2792 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
2793 6, 6, 0,
2794 doc: /* Compare two substrings of two buffers; return result as number.
2795 Return -N if first string is less after N-1 chars, +N if first string is
2796 greater after N-1 chars, or 0 if strings match. Each substring is
2797 represented as three arguments: BUFFER, START and END. That makes six
2798 args in all, three for each substring.
2800 The value of `case-fold-search' in the current buffer
2801 determines whether case is significant or ignored. */)
2802 (Lisp_Object buffer1, Lisp_Object start1, Lisp_Object end1, Lisp_Object buffer2, Lisp_Object start2, Lisp_Object end2)
2804 register EMACS_INT begp1, endp1, begp2, endp2, temp;
2805 register struct buffer *bp1, *bp2;
2806 register Lisp_Object trt
2807 = (!NILP (BVAR (current_buffer, case_fold_search))
2808 ? BVAR (current_buffer, case_canon_table) : Qnil);
2809 ptrdiff_t chars = 0;
2810 ptrdiff_t i1, i2, i1_byte, i2_byte;
2812 /* Find the first buffer and its substring. */
2814 if (NILP (buffer1))
2815 bp1 = current_buffer;
2816 else
2818 Lisp_Object buf1;
2819 buf1 = Fget_buffer (buffer1);
2820 if (NILP (buf1))
2821 nsberror (buffer1);
2822 bp1 = XBUFFER (buf1);
2823 if (!BUFFER_LIVE_P (bp1))
2824 error ("Selecting deleted buffer");
2827 if (NILP (start1))
2828 begp1 = BUF_BEGV (bp1);
2829 else
2831 CHECK_NUMBER_COERCE_MARKER (start1);
2832 begp1 = XINT (start1);
2834 if (NILP (end1))
2835 endp1 = BUF_ZV (bp1);
2836 else
2838 CHECK_NUMBER_COERCE_MARKER (end1);
2839 endp1 = XINT (end1);
2842 if (begp1 > endp1)
2843 temp = begp1, begp1 = endp1, endp1 = temp;
2845 if (!(BUF_BEGV (bp1) <= begp1
2846 && begp1 <= endp1
2847 && endp1 <= BUF_ZV (bp1)))
2848 args_out_of_range (start1, end1);
2850 /* Likewise for second substring. */
2852 if (NILP (buffer2))
2853 bp2 = current_buffer;
2854 else
2856 Lisp_Object buf2;
2857 buf2 = Fget_buffer (buffer2);
2858 if (NILP (buf2))
2859 nsberror (buffer2);
2860 bp2 = XBUFFER (buf2);
2861 if (!BUFFER_LIVE_P (bp2))
2862 error ("Selecting deleted buffer");
2865 if (NILP (start2))
2866 begp2 = BUF_BEGV (bp2);
2867 else
2869 CHECK_NUMBER_COERCE_MARKER (start2);
2870 begp2 = XINT (start2);
2872 if (NILP (end2))
2873 endp2 = BUF_ZV (bp2);
2874 else
2876 CHECK_NUMBER_COERCE_MARKER (end2);
2877 endp2 = XINT (end2);
2880 if (begp2 > endp2)
2881 temp = begp2, begp2 = endp2, endp2 = temp;
2883 if (!(BUF_BEGV (bp2) <= begp2
2884 && begp2 <= endp2
2885 && endp2 <= BUF_ZV (bp2)))
2886 args_out_of_range (start2, end2);
2888 i1 = begp1;
2889 i2 = begp2;
2890 i1_byte = buf_charpos_to_bytepos (bp1, i1);
2891 i2_byte = buf_charpos_to_bytepos (bp2, i2);
2893 while (i1 < endp1 && i2 < endp2)
2895 /* When we find a mismatch, we must compare the
2896 characters, not just the bytes. */
2897 int c1, c2;
2899 QUIT;
2901 if (! NILP (BVAR (bp1, enable_multibyte_characters)))
2903 c1 = BUF_FETCH_MULTIBYTE_CHAR (bp1, i1_byte);
2904 BUF_INC_POS (bp1, i1_byte);
2905 i1++;
2907 else
2909 c1 = BUF_FETCH_BYTE (bp1, i1);
2910 MAKE_CHAR_MULTIBYTE (c1);
2911 i1++;
2914 if (! NILP (BVAR (bp2, enable_multibyte_characters)))
2916 c2 = BUF_FETCH_MULTIBYTE_CHAR (bp2, i2_byte);
2917 BUF_INC_POS (bp2, i2_byte);
2918 i2++;
2920 else
2922 c2 = BUF_FETCH_BYTE (bp2, i2);
2923 MAKE_CHAR_MULTIBYTE (c2);
2924 i2++;
2927 if (!NILP (trt))
2929 c1 = char_table_translate (trt, c1);
2930 c2 = char_table_translate (trt, c2);
2932 if (c1 < c2)
2933 return make_number (- 1 - chars);
2934 if (c1 > c2)
2935 return make_number (chars + 1);
2937 chars++;
2940 /* The strings match as far as they go.
2941 If one is shorter, that one is less. */
2942 if (chars < endp1 - begp1)
2943 return make_number (chars + 1);
2944 else if (chars < endp2 - begp2)
2945 return make_number (- chars - 1);
2947 /* Same length too => they are equal. */
2948 return make_number (0);
2951 static void
2952 subst_char_in_region_unwind (Lisp_Object arg)
2954 bset_undo_list (current_buffer, arg);
2957 static void
2958 subst_char_in_region_unwind_1 (Lisp_Object arg)
2960 bset_filename (current_buffer, arg);
2963 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
2964 Ssubst_char_in_region, 4, 5, 0,
2965 doc: /* From START to END, replace FROMCHAR with TOCHAR each time it occurs.
2966 If optional arg NOUNDO is non-nil, don't record this change for undo
2967 and don't mark the buffer as really changed.
2968 Both characters must have the same length of multi-byte form. */)
2969 (Lisp_Object start, Lisp_Object end, Lisp_Object fromchar, Lisp_Object tochar, Lisp_Object noundo)
2971 register ptrdiff_t pos, pos_byte, stop, i, len, end_byte;
2972 /* Keep track of the first change in the buffer:
2973 if 0 we haven't found it yet.
2974 if < 0 we've found it and we've run the before-change-function.
2975 if > 0 we've actually performed it and the value is its position. */
2976 ptrdiff_t changed = 0;
2977 unsigned char fromstr[MAX_MULTIBYTE_LENGTH], tostr[MAX_MULTIBYTE_LENGTH];
2978 unsigned char *p;
2979 ptrdiff_t count = SPECPDL_INDEX ();
2980 #define COMBINING_NO 0
2981 #define COMBINING_BEFORE 1
2982 #define COMBINING_AFTER 2
2983 #define COMBINING_BOTH (COMBINING_BEFORE | COMBINING_AFTER)
2984 int maybe_byte_combining = COMBINING_NO;
2985 ptrdiff_t last_changed = 0;
2986 bool multibyte_p
2987 = !NILP (BVAR (current_buffer, enable_multibyte_characters));
2988 int fromc, toc;
2990 restart:
2992 validate_region (&start, &end);
2993 CHECK_CHARACTER (fromchar);
2994 CHECK_CHARACTER (tochar);
2995 fromc = XFASTINT (fromchar);
2996 toc = XFASTINT (tochar);
2998 if (multibyte_p)
3000 len = CHAR_STRING (fromc, fromstr);
3001 if (CHAR_STRING (toc, tostr) != len)
3002 error ("Characters in `subst-char-in-region' have different byte-lengths");
3003 if (!ASCII_CHAR_P (*tostr))
3005 /* If *TOSTR is in the range 0x80..0x9F and TOCHAR is not a
3006 complete multibyte character, it may be combined with the
3007 after bytes. If it is in the range 0xA0..0xFF, it may be
3008 combined with the before and after bytes. */
3009 if (!CHAR_HEAD_P (*tostr))
3010 maybe_byte_combining = COMBINING_BOTH;
3011 else if (BYTES_BY_CHAR_HEAD (*tostr) > len)
3012 maybe_byte_combining = COMBINING_AFTER;
3015 else
3017 len = 1;
3018 fromstr[0] = fromc;
3019 tostr[0] = toc;
3022 pos = XINT (start);
3023 pos_byte = CHAR_TO_BYTE (pos);
3024 stop = CHAR_TO_BYTE (XINT (end));
3025 end_byte = stop;
3027 /* If we don't want undo, turn off putting stuff on the list.
3028 That's faster than getting rid of things,
3029 and it prevents even the entry for a first change.
3030 Also inhibit locking the file. */
3031 if (!changed && !NILP (noundo))
3033 record_unwind_protect (subst_char_in_region_unwind,
3034 BVAR (current_buffer, undo_list));
3035 bset_undo_list (current_buffer, Qt);
3036 /* Don't do file-locking. */
3037 record_unwind_protect (subst_char_in_region_unwind_1,
3038 BVAR (current_buffer, filename));
3039 bset_filename (current_buffer, Qnil);
3042 if (pos_byte < GPT_BYTE)
3043 stop = min (stop, GPT_BYTE);
3044 while (1)
3046 ptrdiff_t pos_byte_next = pos_byte;
3048 if (pos_byte >= stop)
3050 if (pos_byte >= end_byte) break;
3051 stop = end_byte;
3053 p = BYTE_POS_ADDR (pos_byte);
3054 if (multibyte_p)
3055 INC_POS (pos_byte_next);
3056 else
3057 ++pos_byte_next;
3058 if (pos_byte_next - pos_byte == len
3059 && p[0] == fromstr[0]
3060 && (len == 1
3061 || (p[1] == fromstr[1]
3062 && (len == 2 || (p[2] == fromstr[2]
3063 && (len == 3 || p[3] == fromstr[3]))))))
3065 if (changed < 0)
3066 /* We've already seen this and run the before-change-function;
3067 this time we only need to record the actual position. */
3068 changed = pos;
3069 else if (!changed)
3071 changed = -1;
3072 modify_text (pos, XINT (end));
3074 if (! NILP (noundo))
3076 if (MODIFF - 1 == SAVE_MODIFF)
3077 SAVE_MODIFF++;
3078 if (MODIFF - 1 == BUF_AUTOSAVE_MODIFF (current_buffer))
3079 BUF_AUTOSAVE_MODIFF (current_buffer)++;
3082 /* The before-change-function may have moved the gap
3083 or even modified the buffer so we should start over. */
3084 goto restart;
3087 /* Take care of the case where the new character
3088 combines with neighboring bytes. */
3089 if (maybe_byte_combining
3090 && (maybe_byte_combining == COMBINING_AFTER
3091 ? (pos_byte_next < Z_BYTE
3092 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3093 : ((pos_byte_next < Z_BYTE
3094 && ! CHAR_HEAD_P (FETCH_BYTE (pos_byte_next)))
3095 || (pos_byte > BEG_BYTE
3096 && ! ASCII_CHAR_P (FETCH_BYTE (pos_byte - 1))))))
3098 Lisp_Object tem, string;
3100 struct gcpro gcpro1;
3102 tem = BVAR (current_buffer, undo_list);
3103 GCPRO1 (tem);
3105 /* Make a multibyte string containing this single character. */
3106 string = make_multibyte_string ((char *) tostr, 1, len);
3107 /* replace_range is less efficient, because it moves the gap,
3108 but it handles combining correctly. */
3109 replace_range (pos, pos + 1, string,
3110 0, 0, 1);
3111 pos_byte_next = CHAR_TO_BYTE (pos);
3112 if (pos_byte_next > pos_byte)
3113 /* Before combining happened. We should not increment
3114 POS. So, to cancel the later increment of POS,
3115 decrease it now. */
3116 pos--;
3117 else
3118 INC_POS (pos_byte_next);
3120 if (! NILP (noundo))
3121 bset_undo_list (current_buffer, tem);
3123 UNGCPRO;
3125 else
3127 if (NILP (noundo))
3128 record_change (pos, 1);
3129 for (i = 0; i < len; i++) *p++ = tostr[i];
3131 last_changed = pos + 1;
3133 pos_byte = pos_byte_next;
3134 pos++;
3137 if (changed > 0)
3139 signal_after_change (changed,
3140 last_changed - changed, last_changed - changed);
3141 update_compositions (changed, last_changed, CHECK_ALL);
3144 unbind_to (count, Qnil);
3145 return Qnil;
3149 static Lisp_Object check_translation (ptrdiff_t, ptrdiff_t, ptrdiff_t,
3150 Lisp_Object);
3152 /* Helper function for Ftranslate_region_internal.
3154 Check if a character sequence at POS (POS_BYTE) matches an element
3155 of VAL. VAL is a list (([FROM-CHAR ...] . TO) ...). If a matching
3156 element is found, return it. Otherwise return Qnil. */
3158 static Lisp_Object
3159 check_translation (ptrdiff_t pos, ptrdiff_t pos_byte, ptrdiff_t end,
3160 Lisp_Object val)
3162 int initial_buf[16];
3163 int *buf = initial_buf;
3164 ptrdiff_t buf_size = ARRAYELTS (initial_buf);
3165 int *bufalloc = 0;
3166 ptrdiff_t buf_used = 0;
3167 Lisp_Object result = Qnil;
3169 for (; CONSP (val); val = XCDR (val))
3171 Lisp_Object elt;
3172 ptrdiff_t len, i;
3174 elt = XCAR (val);
3175 if (! CONSP (elt))
3176 continue;
3177 elt = XCAR (elt);
3178 if (! VECTORP (elt))
3179 continue;
3180 len = ASIZE (elt);
3181 if (len <= end - pos)
3183 for (i = 0; i < len; i++)
3185 if (buf_used <= i)
3187 unsigned char *p = BYTE_POS_ADDR (pos_byte);
3188 int len1;
3190 if (buf_used == buf_size)
3192 bufalloc = xpalloc (bufalloc, &buf_size, 1, -1,
3193 sizeof *bufalloc);
3194 if (buf == initial_buf)
3195 memcpy (bufalloc, buf, sizeof initial_buf);
3196 buf = bufalloc;
3198 buf[buf_used++] = STRING_CHAR_AND_LENGTH (p, len1);
3199 pos_byte += len1;
3201 if (XINT (AREF (elt, i)) != buf[i])
3202 break;
3204 if (i == len)
3206 result = XCAR (val);
3207 break;
3212 xfree (bufalloc);
3213 return result;
3217 DEFUN ("translate-region-internal", Ftranslate_region_internal,
3218 Stranslate_region_internal, 3, 3, 0,
3219 doc: /* Internal use only.
3220 From START to END, translate characters according to TABLE.
3221 TABLE is a string or a char-table; the Nth character in it is the
3222 mapping for the character with code N.
3223 It returns the number of characters changed. */)
3224 (Lisp_Object start, Lisp_Object end, register Lisp_Object table)
3226 register unsigned char *tt; /* Trans table. */
3227 register int nc; /* New character. */
3228 int cnt; /* Number of changes made. */
3229 ptrdiff_t size; /* Size of translate table. */
3230 ptrdiff_t pos, pos_byte, end_pos;
3231 bool multibyte = !NILP (BVAR (current_buffer, enable_multibyte_characters));
3232 bool string_multibyte IF_LINT (= 0);
3234 validate_region (&start, &end);
3235 if (CHAR_TABLE_P (table))
3237 if (! EQ (XCHAR_TABLE (table)->purpose, Qtranslation_table))
3238 error ("Not a translation table");
3239 size = MAX_CHAR;
3240 tt = NULL;
3242 else
3244 CHECK_STRING (table);
3246 if (! multibyte && (SCHARS (table) < SBYTES (table)))
3247 table = string_make_unibyte (table);
3248 string_multibyte = SCHARS (table) < SBYTES (table);
3249 size = SBYTES (table);
3250 tt = SDATA (table);
3253 pos = XINT (start);
3254 pos_byte = CHAR_TO_BYTE (pos);
3255 end_pos = XINT (end);
3256 modify_text (pos, end_pos);
3258 cnt = 0;
3259 for (; pos < end_pos; )
3261 register unsigned char *p = BYTE_POS_ADDR (pos_byte);
3262 unsigned char *str, buf[MAX_MULTIBYTE_LENGTH];
3263 int len, str_len;
3264 int oc;
3265 Lisp_Object val;
3267 if (multibyte)
3268 oc = STRING_CHAR_AND_LENGTH (p, len);
3269 else
3270 oc = *p, len = 1;
3271 if (oc < size)
3273 if (tt)
3275 /* Reload as signal_after_change in last iteration may GC. */
3276 tt = SDATA (table);
3277 if (string_multibyte)
3279 str = tt + string_char_to_byte (table, oc);
3280 nc = STRING_CHAR_AND_LENGTH (str, str_len);
3282 else
3284 nc = tt[oc];
3285 if (! ASCII_CHAR_P (nc) && multibyte)
3287 str_len = BYTE8_STRING (nc, buf);
3288 str = buf;
3290 else
3292 str_len = 1;
3293 str = tt + oc;
3297 else
3299 nc = oc;
3300 val = CHAR_TABLE_REF (table, oc);
3301 if (CHARACTERP (val))
3303 nc = XFASTINT (val);
3304 str_len = CHAR_STRING (nc, buf);
3305 str = buf;
3307 else if (VECTORP (val) || (CONSP (val)))
3309 /* VAL is [TO_CHAR ...] or (([FROM-CHAR ...] . TO) ...)
3310 where TO is TO-CHAR or [TO-CHAR ...]. */
3311 nc = -1;
3315 if (nc != oc && nc >= 0)
3317 /* Simple one char to one char translation. */
3318 if (len != str_len)
3320 Lisp_Object string;
3322 /* This is less efficient, because it moves the gap,
3323 but it should handle multibyte characters correctly. */
3324 string = make_multibyte_string ((char *) str, 1, str_len);
3325 replace_range (pos, pos + 1, string, 1, 0, 1);
3326 len = str_len;
3328 else
3330 record_change (pos, 1);
3331 while (str_len-- > 0)
3332 *p++ = *str++;
3333 signal_after_change (pos, 1, 1);
3334 update_compositions (pos, pos + 1, CHECK_BORDER);
3336 ++cnt;
3338 else if (nc < 0)
3340 Lisp_Object string;
3342 if (CONSP (val))
3344 val = check_translation (pos, pos_byte, end_pos, val);
3345 if (NILP (val))
3347 pos_byte += len;
3348 pos++;
3349 continue;
3351 /* VAL is ([FROM-CHAR ...] . TO). */
3352 len = ASIZE (XCAR (val));
3353 val = XCDR (val);
3355 else
3356 len = 1;
3358 if (VECTORP (val))
3360 string = Fconcat (1, &val);
3362 else
3364 string = Fmake_string (make_number (1), val);
3366 replace_range (pos, pos + len, string, 1, 0, 1);
3367 pos_byte += SBYTES (string);
3368 pos += SCHARS (string);
3369 cnt += SCHARS (string);
3370 end_pos += SCHARS (string) - len;
3371 continue;
3374 pos_byte += len;
3375 pos++;
3378 return make_number (cnt);
3381 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
3382 doc: /* Delete the text between START and END.
3383 If called interactively, delete the region between point and mark.
3384 This command deletes buffer text without modifying the kill ring. */)
3385 (Lisp_Object start, Lisp_Object end)
3387 validate_region (&start, &end);
3388 del_range (XINT (start), XINT (end));
3389 return Qnil;
3392 DEFUN ("delete-and-extract-region", Fdelete_and_extract_region,
3393 Sdelete_and_extract_region, 2, 2, 0,
3394 doc: /* Delete the text between START and END and return it. */)
3395 (Lisp_Object start, Lisp_Object end)
3397 validate_region (&start, &end);
3398 if (XINT (start) == XINT (end))
3399 return empty_unibyte_string;
3400 return del_range_1 (XINT (start), XINT (end), 1, 1);
3403 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
3404 doc: /* Remove restrictions (narrowing) from current buffer.
3405 This allows the buffer's full text to be seen and edited. */)
3406 (void)
3408 if (BEG != BEGV || Z != ZV)
3409 current_buffer->clip_changed = 1;
3410 BEGV = BEG;
3411 BEGV_BYTE = BEG_BYTE;
3412 SET_BUF_ZV_BOTH (current_buffer, Z, Z_BYTE);
3413 /* Changing the buffer bounds invalidates any recorded current column. */
3414 invalidate_current_column ();
3415 return Qnil;
3418 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
3419 doc: /* Restrict editing in this buffer to the current region.
3420 The rest of the text becomes temporarily invisible and untouchable
3421 but is not deleted; if you save the buffer in a file, the invisible
3422 text is included in the file. \\[widen] makes all visible again.
3423 See also `save-restriction'.
3425 When calling from a program, pass two arguments; positions (integers
3426 or markers) bounding the text that should remain visible. */)
3427 (register Lisp_Object start, Lisp_Object end)
3429 CHECK_NUMBER_COERCE_MARKER (start);
3430 CHECK_NUMBER_COERCE_MARKER (end);
3432 if (XINT (start) > XINT (end))
3434 Lisp_Object tem;
3435 tem = start; start = end; end = tem;
3438 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
3439 args_out_of_range (start, end);
3441 if (BEGV != XFASTINT (start) || ZV != XFASTINT (end))
3442 current_buffer->clip_changed = 1;
3444 SET_BUF_BEGV (current_buffer, XFASTINT (start));
3445 SET_BUF_ZV (current_buffer, XFASTINT (end));
3446 if (PT < XFASTINT (start))
3447 SET_PT (XFASTINT (start));
3448 if (PT > XFASTINT (end))
3449 SET_PT (XFASTINT (end));
3450 /* Changing the buffer bounds invalidates any recorded current column. */
3451 invalidate_current_column ();
3452 return Qnil;
3455 Lisp_Object
3456 save_restriction_save (void)
3458 if (BEGV == BEG && ZV == Z)
3459 /* The common case that the buffer isn't narrowed.
3460 We return just the buffer object, which save_restriction_restore
3461 recognizes as meaning `no restriction'. */
3462 return Fcurrent_buffer ();
3463 else
3464 /* We have to save a restriction, so return a pair of markers, one
3465 for the beginning and one for the end. */
3467 Lisp_Object beg, end;
3469 beg = build_marker (current_buffer, BEGV, BEGV_BYTE);
3470 end = build_marker (current_buffer, ZV, ZV_BYTE);
3472 /* END must move forward if text is inserted at its exact location. */
3473 XMARKER (end)->insertion_type = 1;
3475 return Fcons (beg, end);
3479 void
3480 save_restriction_restore (Lisp_Object data)
3482 struct buffer *cur = NULL;
3483 struct buffer *buf = (CONSP (data)
3484 ? XMARKER (XCAR (data))->buffer
3485 : XBUFFER (data));
3487 if (buf && buf != current_buffer && !NILP (BVAR (buf, pt_marker)))
3488 { /* If `buf' uses markers to keep track of PT, BEGV, and ZV (as
3489 is the case if it is or has an indirect buffer), then make
3490 sure it is current before we update BEGV, so
3491 set_buffer_internal takes care of managing those markers. */
3492 cur = current_buffer;
3493 set_buffer_internal (buf);
3496 if (CONSP (data))
3497 /* A pair of marks bounding a saved restriction. */
3499 struct Lisp_Marker *beg = XMARKER (XCAR (data));
3500 struct Lisp_Marker *end = XMARKER (XCDR (data));
3501 eassert (buf == end->buffer);
3503 if (buf /* Verify marker still points to a buffer. */
3504 && (beg->charpos != BUF_BEGV (buf) || end->charpos != BUF_ZV (buf)))
3505 /* The restriction has changed from the saved one, so restore
3506 the saved restriction. */
3508 ptrdiff_t pt = BUF_PT (buf);
3510 SET_BUF_BEGV_BOTH (buf, beg->charpos, beg->bytepos);
3511 SET_BUF_ZV_BOTH (buf, end->charpos, end->bytepos);
3513 if (pt < beg->charpos || pt > end->charpos)
3514 /* The point is outside the new visible range, move it inside. */
3515 SET_BUF_PT_BOTH (buf,
3516 clip_to_bounds (beg->charpos, pt, end->charpos),
3517 clip_to_bounds (beg->bytepos, BUF_PT_BYTE (buf),
3518 end->bytepos));
3520 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3522 /* These aren't needed anymore, so don't wait for GC. */
3523 free_marker (XCAR (data));
3524 free_marker (XCDR (data));
3525 free_cons (XCONS (data));
3527 else
3528 /* A buffer, which means that there was no old restriction. */
3530 if (buf /* Verify marker still points to a buffer. */
3531 && (BUF_BEGV (buf) != BUF_BEG (buf) || BUF_ZV (buf) != BUF_Z (buf)))
3532 /* The buffer has been narrowed, get rid of the narrowing. */
3534 SET_BUF_BEGV_BOTH (buf, BUF_BEG (buf), BUF_BEG_BYTE (buf));
3535 SET_BUF_ZV_BOTH (buf, BUF_Z (buf), BUF_Z_BYTE (buf));
3537 buf->clip_changed = 1; /* Remember that the narrowing changed. */
3541 /* Changing the buffer bounds invalidates any recorded current column. */
3542 invalidate_current_column ();
3544 if (cur)
3545 set_buffer_internal (cur);
3548 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
3549 doc: /* Execute BODY, saving and restoring current buffer's restrictions.
3550 The buffer's restrictions make parts of the beginning and end invisible.
3551 \(They are set up with `narrow-to-region' and eliminated with `widen'.)
3552 This special form, `save-restriction', saves the current buffer's restrictions
3553 when it is entered, and restores them when it is exited.
3554 So any `narrow-to-region' within BODY lasts only until the end of the form.
3555 The old restrictions settings are restored
3556 even in case of abnormal exit (throw or error).
3558 The value returned is the value of the last form in BODY.
3560 Note: if you are using both `save-excursion' and `save-restriction',
3561 use `save-excursion' outermost:
3562 (save-excursion (save-restriction ...))
3564 usage: (save-restriction &rest BODY) */)
3565 (Lisp_Object body)
3567 register Lisp_Object val;
3568 ptrdiff_t count = SPECPDL_INDEX ();
3570 record_unwind_protect (save_restriction_restore, save_restriction_save ());
3571 val = Fprogn (body);
3572 return unbind_to (count, val);
3575 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
3576 doc: /* Display a message at the bottom of the screen.
3577 The message also goes into the `*Messages*' buffer, if `message-log-max'
3578 is non-nil. (In keyboard macros, that's all it does.)
3579 Return the message.
3581 In batch mode, the message is printed to the standard error stream,
3582 followed by a newline.
3584 The first argument is a format control string, and the rest are data
3585 to be formatted under control of the string. See `format' for details.
3587 Note: Use (message "%s" VALUE) to print the value of expressions and
3588 variables to avoid accidentally interpreting `%' as format specifiers.
3590 If the first argument is nil or the empty string, the function clears
3591 any existing message; this lets the minibuffer contents show. See
3592 also `current-message'.
3594 usage: (message FORMAT-STRING &rest ARGS) */)
3595 (ptrdiff_t nargs, Lisp_Object *args)
3597 if (NILP (args[0])
3598 || (STRINGP (args[0])
3599 && SBYTES (args[0]) == 0))
3601 message1 (0);
3602 return args[0];
3604 else
3606 register Lisp_Object val;
3607 val = Fformat (nargs, args);
3608 message3 (val);
3609 return val;
3613 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
3614 doc: /* Display a message, in a dialog box if possible.
3615 If a dialog box is not available, use the echo area.
3616 The first argument is a format control string, and the rest are data
3617 to be formatted under control of the string. See `format' for details.
3619 If the first argument is nil or the empty string, clear any existing
3620 message; let the minibuffer contents show.
3622 usage: (message-box FORMAT-STRING &rest ARGS) */)
3623 (ptrdiff_t nargs, Lisp_Object *args)
3625 if (NILP (args[0]))
3627 message1 (0);
3628 return Qnil;
3630 else
3632 Lisp_Object val = Fformat (nargs, args);
3633 Lisp_Object pane, menu;
3634 struct gcpro gcpro1;
3636 pane = list1 (Fcons (build_string ("OK"), Qt));
3637 GCPRO1 (pane);
3638 menu = Fcons (val, pane);
3639 Fx_popup_dialog (Qt, menu, Qt);
3640 UNGCPRO;
3641 return val;
3645 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
3646 doc: /* Display a message in a dialog box or in the echo area.
3647 If this command was invoked with the mouse, use a dialog box if
3648 `use-dialog-box' is non-nil.
3649 Otherwise, use the echo area.
3650 The first argument is a format control string, and the rest are data
3651 to be formatted under control of the string. See `format' for details.
3653 If the first argument is nil or the empty string, clear any existing
3654 message; let the minibuffer contents show.
3656 usage: (message-or-box FORMAT-STRING &rest ARGS) */)
3657 (ptrdiff_t nargs, Lisp_Object *args)
3659 if ((NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
3660 && use_dialog_box)
3661 return Fmessage_box (nargs, args);
3662 return Fmessage (nargs, args);
3665 DEFUN ("current-message", Fcurrent_message, Scurrent_message, 0, 0, 0,
3666 doc: /* Return the string currently displayed in the echo area, or nil if none. */)
3667 (void)
3669 return current_message ();
3673 DEFUN ("propertize", Fpropertize, Spropertize, 1, MANY, 0,
3674 doc: /* Return a copy of STRING with text properties added.
3675 First argument is the string to copy.
3676 Remaining arguments form a sequence of PROPERTY VALUE pairs for text
3677 properties to add to the result.
3678 usage: (propertize STRING &rest PROPERTIES) */)
3679 (ptrdiff_t nargs, Lisp_Object *args)
3681 Lisp_Object properties, string;
3682 struct gcpro gcpro1, gcpro2;
3683 ptrdiff_t i;
3685 /* Number of args must be odd. */
3686 if ((nargs & 1) == 0)
3687 error ("Wrong number of arguments");
3689 properties = string = Qnil;
3690 GCPRO2 (properties, string);
3692 /* First argument must be a string. */
3693 CHECK_STRING (args[0]);
3694 string = Fcopy_sequence (args[0]);
3696 for (i = 1; i < nargs; i += 2)
3697 properties = Fcons (args[i], Fcons (args[i + 1], properties));
3699 Fadd_text_properties (make_number (0),
3700 make_number (SCHARS (string)),
3701 properties, string);
3702 RETURN_UNGCPRO (string);
3705 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
3706 doc: /* Format a string out of a format-string and arguments.
3707 The first argument is a format control string.
3708 The other arguments are substituted into it to make the result, a string.
3710 The format control string may contain %-sequences meaning to substitute
3711 the next available argument:
3713 %s means print a string argument. Actually, prints any object, with `princ'.
3714 %d means print as number in decimal (%o octal, %x hex).
3715 %X is like %x, but uses upper case.
3716 %e means print a number in exponential notation.
3717 %f means print a number in decimal-point notation.
3718 %g means print a number in exponential notation
3719 or decimal-point notation, whichever uses fewer characters.
3720 %c means print a number as a single character.
3721 %S means print any object as an s-expression (using `prin1').
3723 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.
3724 Use %% to put a single % into the output.
3726 A %-sequence may contain optional flag, width, and precision
3727 specifiers, as follows:
3729 %<flags><width><precision>character
3731 where flags is [+ #-0]+, width is [0-9]+, and precision is .[0-9]+
3733 The + flag character inserts a + before any positive number, while a
3734 space inserts a space before any positive number; these flags only
3735 affect %d, %e, %f, and %g sequences, and the + flag takes precedence.
3736 The - and 0 flags affect the width specifier, as described below.
3738 The # flag means to use an alternate display form for %o, %x, %X, %e,
3739 %f, and %g sequences: for %o, it ensures that the result begins with
3740 \"0\"; for %x and %X, it prefixes the result with \"0x\" or \"0X\";
3741 for %e, %f, and %g, it causes a decimal point to be included even if
3742 the precision is zero.
3744 The width specifier supplies a lower limit for the length of the
3745 printed representation. The padding, if any, normally goes on the
3746 left, but it goes on the right if the - flag is present. The padding
3747 character is normally a space, but it is 0 if the 0 flag is present.
3748 The 0 flag is ignored if the - flag is present, or the format sequence
3749 is something other than %d, %e, %f, and %g.
3751 For %e, %f, and %g sequences, the number after the "." in the
3752 precision specifier says how many decimal places to show; if zero, the
3753 decimal point itself is omitted. For %s and %S, the precision
3754 specifier truncates the string to the given width.
3756 usage: (format STRING &rest OBJECTS) */)
3757 (ptrdiff_t nargs, Lisp_Object *args)
3759 ptrdiff_t n; /* The number of the next arg to substitute. */
3760 char initial_buffer[4000];
3761 char *buf = initial_buffer;
3762 ptrdiff_t bufsize = sizeof initial_buffer;
3763 ptrdiff_t max_bufsize = STRING_BYTES_BOUND + 1;
3764 char *p;
3765 ptrdiff_t buf_save_value_index IF_LINT (= 0);
3766 char *format, *end, *format_start;
3767 ptrdiff_t formatlen, nchars;
3768 /* True if the format is multibyte. */
3769 bool multibyte_format = 0;
3770 /* True if the output should be a multibyte string,
3771 which is true if any of the inputs is one. */
3772 bool multibyte = 0;
3773 /* When we make a multibyte string, we must pay attention to the
3774 byte combining problem, i.e., a byte may be combined with a
3775 multibyte character of the previous string. This flag tells if we
3776 must consider such a situation or not. */
3777 bool maybe_combine_byte;
3778 Lisp_Object val;
3779 bool arg_intervals = 0;
3780 USE_SAFE_ALLOCA;
3782 /* discarded[I] is 1 if byte I of the format
3783 string was not copied into the output.
3784 It is 2 if byte I was not the first byte of its character. */
3785 char *discarded;
3787 /* Each element records, for one argument,
3788 the start and end bytepos in the output string,
3789 whether the argument has been converted to string (e.g., due to "%S"),
3790 and whether the argument is a string with intervals.
3791 info[0] is unused. Unused elements have -1 for start. */
3792 struct info
3794 ptrdiff_t start, end;
3795 bool_bf converted_to_string : 1;
3796 bool_bf intervals : 1;
3797 } *info = 0;
3799 /* It should not be necessary to GCPRO ARGS, because
3800 the caller in the interpreter should take care of that. */
3802 CHECK_STRING (args[0]);
3803 format_start = SSDATA (args[0]);
3804 formatlen = SBYTES (args[0]);
3806 /* Allocate the info and discarded tables. */
3808 ptrdiff_t i;
3809 if ((SIZE_MAX - formatlen) / sizeof (struct info) <= nargs)
3810 memory_full (SIZE_MAX);
3811 info = SAFE_ALLOCA ((nargs + 1) * sizeof *info + formatlen);
3812 discarded = (char *) &info[nargs + 1];
3813 for (i = 0; i < nargs + 1; i++)
3815 info[i].start = -1;
3816 info[i].intervals = info[i].converted_to_string = 0;
3818 memset (discarded, 0, formatlen);
3821 /* Try to determine whether the result should be multibyte.
3822 This is not always right; sometimes the result needs to be multibyte
3823 because of an object that we will pass through prin1,
3824 and in that case, we won't know it here. */
3825 multibyte_format = STRING_MULTIBYTE (args[0]);
3826 multibyte = multibyte_format;
3827 for (n = 1; !multibyte && n < nargs; n++)
3828 if (STRINGP (args[n]) && STRING_MULTIBYTE (args[n]))
3829 multibyte = 1;
3831 /* If we start out planning a unibyte result,
3832 then discover it has to be multibyte, we jump back to retry. */
3833 retry:
3835 p = buf;
3836 nchars = 0;
3837 n = 0;
3839 /* Scan the format and store result in BUF. */
3840 format = format_start;
3841 end = format + formatlen;
3842 maybe_combine_byte = 0;
3844 while (format != end)
3846 /* The values of N and FORMAT when the loop body is entered. */
3847 ptrdiff_t n0 = n;
3848 char *format0 = format;
3850 /* Bytes needed to represent the output of this conversion. */
3851 ptrdiff_t convbytes;
3853 if (*format == '%')
3855 /* General format specifications look like
3857 '%' [flags] [field-width] [precision] format
3859 where
3861 flags ::= [-+0# ]+
3862 field-width ::= [0-9]+
3863 precision ::= '.' [0-9]*
3865 If a field-width is specified, it specifies to which width
3866 the output should be padded with blanks, if the output
3867 string is shorter than field-width.
3869 If precision is specified, it specifies the number of
3870 digits to print after the '.' for floats, or the max.
3871 number of chars to print from a string. */
3873 bool minus_flag = 0;
3874 bool plus_flag = 0;
3875 bool space_flag = 0;
3876 bool sharp_flag = 0;
3877 bool zero_flag = 0;
3878 ptrdiff_t field_width;
3879 bool precision_given;
3880 uintmax_t precision = UINTMAX_MAX;
3881 char *num_end;
3882 char conversion;
3884 while (1)
3886 switch (*++format)
3888 case '-': minus_flag = 1; continue;
3889 case '+': plus_flag = 1; continue;
3890 case ' ': space_flag = 1; continue;
3891 case '#': sharp_flag = 1; continue;
3892 case '0': zero_flag = 1; continue;
3894 break;
3897 /* Ignore flags when sprintf ignores them. */
3898 space_flag &= ~ plus_flag;
3899 zero_flag &= ~ minus_flag;
3902 uintmax_t w = strtoumax (format, &num_end, 10);
3903 if (max_bufsize <= w)
3904 string_overflow ();
3905 field_width = w;
3907 precision_given = *num_end == '.';
3908 if (precision_given)
3909 precision = strtoumax (num_end + 1, &num_end, 10);
3910 format = num_end;
3912 if (format == end)
3913 error ("Format string ends in middle of format specifier");
3915 memset (&discarded[format0 - format_start], 1, format - format0);
3916 conversion = *format;
3917 if (conversion == '%')
3918 goto copy_char;
3919 discarded[format - format_start] = 1;
3920 format++;
3922 ++n;
3923 if (! (n < nargs))
3924 error ("Not enough arguments for format string");
3926 /* For 'S', prin1 the argument, and then treat like 's'.
3927 For 's', princ any argument that is not a string or
3928 symbol. But don't do this conversion twice, which might
3929 happen after retrying. */
3930 if ((conversion == 'S'
3931 || (conversion == 's'
3932 && ! STRINGP (args[n]) && ! SYMBOLP (args[n]))))
3934 if (! info[n].converted_to_string)
3936 Lisp_Object noescape = conversion == 'S' ? Qnil : Qt;
3937 args[n] = Fprin1_to_string (args[n], noescape);
3938 info[n].converted_to_string = 1;
3939 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3941 multibyte = 1;
3942 goto retry;
3945 conversion = 's';
3947 else if (conversion == 'c')
3949 if (FLOATP (args[n]))
3951 double d = XFLOAT_DATA (args[n]);
3952 args[n] = make_number (FIXNUM_OVERFLOW_P (d) ? -1 : d);
3955 if (INTEGERP (args[n]) && ! ASCII_CHAR_P (XINT (args[n])))
3957 if (!multibyte)
3959 multibyte = 1;
3960 goto retry;
3962 args[n] = Fchar_to_string (args[n]);
3963 info[n].converted_to_string = 1;
3966 if (info[n].converted_to_string)
3967 conversion = 's';
3968 zero_flag = 0;
3971 if (SYMBOLP (args[n]))
3973 args[n] = SYMBOL_NAME (args[n]);
3974 if (STRING_MULTIBYTE (args[n]) && ! multibyte)
3976 multibyte = 1;
3977 goto retry;
3981 if (conversion == 's')
3983 /* handle case (precision[n] >= 0) */
3985 ptrdiff_t width, padding, nbytes;
3986 ptrdiff_t nchars_string;
3988 ptrdiff_t prec = -1;
3989 if (precision_given && precision <= TYPE_MAXIMUM (ptrdiff_t))
3990 prec = precision;
3992 /* lisp_string_width ignores a precision of 0, but GNU
3993 libc functions print 0 characters when the precision
3994 is 0. Imitate libc behavior here. Changing
3995 lisp_string_width is the right thing, and will be
3996 done, but meanwhile we work with it. */
3998 if (prec == 0)
3999 width = nchars_string = nbytes = 0;
4000 else
4002 ptrdiff_t nch, nby;
4003 width = lisp_string_width (args[n], prec, &nch, &nby);
4004 if (prec < 0)
4006 nchars_string = SCHARS (args[n]);
4007 nbytes = SBYTES (args[n]);
4009 else
4011 nchars_string = nch;
4012 nbytes = nby;
4016 convbytes = nbytes;
4017 if (convbytes && multibyte && ! STRING_MULTIBYTE (args[n]))
4018 convbytes = count_size_as_multibyte (SDATA (args[n]), nbytes);
4020 padding = width < field_width ? field_width - width : 0;
4022 if (max_bufsize - padding <= convbytes)
4023 string_overflow ();
4024 convbytes += padding;
4025 if (convbytes <= buf + bufsize - p)
4027 if (! minus_flag)
4029 memset (p, ' ', padding);
4030 p += padding;
4031 nchars += padding;
4034 if (p > buf
4035 && multibyte
4036 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4037 && STRING_MULTIBYTE (args[n])
4038 && !CHAR_HEAD_P (SREF (args[n], 0)))
4039 maybe_combine_byte = 1;
4041 p += copy_text (SDATA (args[n]), (unsigned char *) p,
4042 nbytes,
4043 STRING_MULTIBYTE (args[n]), multibyte);
4045 info[n].start = nchars;
4046 nchars += nchars_string;
4047 info[n].end = nchars;
4049 if (minus_flag)
4051 memset (p, ' ', padding);
4052 p += padding;
4053 nchars += padding;
4056 /* If this argument has text properties, record where
4057 in the result string it appears. */
4058 if (string_intervals (args[n]))
4059 info[n].intervals = arg_intervals = 1;
4061 continue;
4064 else if (! (conversion == 'c' || conversion == 'd'
4065 || conversion == 'e' || conversion == 'f'
4066 || conversion == 'g' || conversion == 'i'
4067 || conversion == 'o' || conversion == 'x'
4068 || conversion == 'X'))
4069 error ("Invalid format operation %%%c",
4070 STRING_CHAR ((unsigned char *) format - 1));
4071 else if (! (INTEGERP (args[n]) || FLOATP (args[n])))
4072 error ("Format specifier doesn't match argument type");
4073 else
4075 enum
4077 /* Maximum precision for a %f conversion such that the
4078 trailing output digit might be nonzero. Any precision
4079 larger than this will not yield useful information. */
4080 USEFUL_PRECISION_MAX =
4081 ((1 - DBL_MIN_EXP)
4082 * (FLT_RADIX == 2 || FLT_RADIX == 10 ? 1
4083 : FLT_RADIX == 16 ? 4
4084 : -1)),
4086 /* Maximum number of bytes generated by any format, if
4087 precision is no more than USEFUL_PRECISION_MAX.
4088 On all practical hosts, %f is the worst case. */
4089 SPRINTF_BUFSIZE =
4090 sizeof "-." + (DBL_MAX_10_EXP + 1) + USEFUL_PRECISION_MAX,
4092 /* Length of pM (that is, of pMd without the
4093 trailing "d"). */
4094 pMlen = sizeof pMd - 2
4096 verify (USEFUL_PRECISION_MAX > 0);
4098 int prec;
4099 ptrdiff_t padding, sprintf_bytes;
4100 uintmax_t excess_precision, numwidth;
4101 uintmax_t leading_zeros = 0, trailing_zeros = 0;
4103 char sprintf_buf[SPRINTF_BUFSIZE];
4105 /* Copy of conversion specification, modified somewhat.
4106 At most three flags F can be specified at once. */
4107 char convspec[sizeof "%FFF.*d" + pMlen];
4109 /* Avoid undefined behavior in underlying sprintf. */
4110 if (conversion == 'd' || conversion == 'i')
4111 sharp_flag = 0;
4113 /* Create the copy of the conversion specification, with
4114 any width and precision removed, with ".*" inserted,
4115 and with pM inserted for integer formats. */
4117 char *f = convspec;
4118 *f++ = '%';
4119 *f = '-'; f += minus_flag;
4120 *f = '+'; f += plus_flag;
4121 *f = ' '; f += space_flag;
4122 *f = '#'; f += sharp_flag;
4123 *f = '0'; f += zero_flag;
4124 *f++ = '.';
4125 *f++ = '*';
4126 if (conversion == 'd' || conversion == 'i'
4127 || conversion == 'o' || conversion == 'x'
4128 || conversion == 'X')
4130 memcpy (f, pMd, pMlen);
4131 f += pMlen;
4132 zero_flag &= ~ precision_given;
4134 *f++ = conversion;
4135 *f = '\0';
4138 prec = -1;
4139 if (precision_given)
4140 prec = min (precision, USEFUL_PRECISION_MAX);
4142 /* Use sprintf to format this number into sprintf_buf. Omit
4143 padding and excess precision, though, because sprintf limits
4144 output length to INT_MAX.
4146 There are four types of conversion: double, unsigned
4147 char (passed as int), wide signed int, and wide
4148 unsigned int. Treat them separately because the
4149 sprintf ABI is sensitive to which type is passed. Be
4150 careful about integer overflow, NaNs, infinities, and
4151 conversions; for example, the min and max macros are
4152 not suitable here. */
4153 if (conversion == 'e' || conversion == 'f' || conversion == 'g')
4155 double x = (INTEGERP (args[n])
4156 ? XINT (args[n])
4157 : XFLOAT_DATA (args[n]));
4158 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4160 else if (conversion == 'c')
4162 /* Don't use sprintf here, as it might mishandle prec. */
4163 sprintf_buf[0] = XINT (args[n]);
4164 sprintf_bytes = prec != 0;
4166 else if (conversion == 'd')
4168 /* For float, maybe we should use "%1.0f"
4169 instead so it also works for values outside
4170 the integer range. */
4171 printmax_t x;
4172 if (INTEGERP (args[n]))
4173 x = XINT (args[n]);
4174 else
4176 double d = XFLOAT_DATA (args[n]);
4177 if (d < 0)
4179 x = TYPE_MINIMUM (printmax_t);
4180 if (x < d)
4181 x = d;
4183 else
4185 x = TYPE_MAXIMUM (printmax_t);
4186 if (d < x)
4187 x = d;
4190 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4192 else
4194 /* Don't sign-extend for octal or hex printing. */
4195 uprintmax_t x;
4196 if (INTEGERP (args[n]))
4197 x = XUINT (args[n]);
4198 else
4200 double d = XFLOAT_DATA (args[n]);
4201 if (d < 0)
4202 x = 0;
4203 else
4205 x = TYPE_MAXIMUM (uprintmax_t);
4206 if (d < x)
4207 x = d;
4210 sprintf_bytes = sprintf (sprintf_buf, convspec, prec, x);
4213 /* Now the length of the formatted item is known, except it omits
4214 padding and excess precision. Deal with excess precision
4215 first. This happens only when the format specifies
4216 ridiculously large precision. */
4217 excess_precision = precision - prec;
4218 if (excess_precision)
4220 if (conversion == 'e' || conversion == 'f'
4221 || conversion == 'g')
4223 if ((conversion == 'g' && ! sharp_flag)
4224 || ! ('0' <= sprintf_buf[sprintf_bytes - 1]
4225 && sprintf_buf[sprintf_bytes - 1] <= '9'))
4226 excess_precision = 0;
4227 else
4229 if (conversion == 'g')
4231 char *dot = strchr (sprintf_buf, '.');
4232 if (!dot)
4233 excess_precision = 0;
4236 trailing_zeros = excess_precision;
4238 else
4239 leading_zeros = excess_precision;
4242 /* Compute the total bytes needed for this item, including
4243 excess precision and padding. */
4244 numwidth = sprintf_bytes + excess_precision;
4245 padding = numwidth < field_width ? field_width - numwidth : 0;
4246 if (max_bufsize - sprintf_bytes <= excess_precision
4247 || max_bufsize - padding <= numwidth)
4248 string_overflow ();
4249 convbytes = numwidth + padding;
4251 if (convbytes <= buf + bufsize - p)
4253 /* Copy the formatted item from sprintf_buf into buf,
4254 inserting padding and excess-precision zeros. */
4256 char *src = sprintf_buf;
4257 char src0 = src[0];
4258 int exponent_bytes = 0;
4259 bool signedp = src0 == '-' || src0 == '+' || src0 == ' ';
4260 int significand_bytes;
4261 if (zero_flag
4262 && ((src[signedp] >= '0' && src[signedp] <= '9')
4263 || (src[signedp] >= 'a' && src[signedp] <= 'f')
4264 || (src[signedp] >= 'A' && src[signedp] <= 'F')))
4266 leading_zeros += padding;
4267 padding = 0;
4270 if (excess_precision
4271 && (conversion == 'e' || conversion == 'g'))
4273 char *e = strchr (src, 'e');
4274 if (e)
4275 exponent_bytes = src + sprintf_bytes - e;
4278 if (! minus_flag)
4280 memset (p, ' ', padding);
4281 p += padding;
4282 nchars += padding;
4285 *p = src0;
4286 src += signedp;
4287 p += signedp;
4288 memset (p, '0', leading_zeros);
4289 p += leading_zeros;
4290 significand_bytes = sprintf_bytes - signedp - exponent_bytes;
4291 memcpy (p, src, significand_bytes);
4292 p += significand_bytes;
4293 src += significand_bytes;
4294 memset (p, '0', trailing_zeros);
4295 p += trailing_zeros;
4296 memcpy (p, src, exponent_bytes);
4297 p += exponent_bytes;
4299 info[n].start = nchars;
4300 nchars += leading_zeros + sprintf_bytes + trailing_zeros;
4301 info[n].end = nchars;
4303 if (minus_flag)
4305 memset (p, ' ', padding);
4306 p += padding;
4307 nchars += padding;
4310 continue;
4314 else
4315 copy_char:
4317 /* Copy a single character from format to buf. */
4319 char *src = format;
4320 unsigned char str[MAX_MULTIBYTE_LENGTH];
4322 if (multibyte_format)
4324 /* Copy a whole multibyte character. */
4325 if (p > buf
4326 && !ASCII_CHAR_P (*((unsigned char *) p - 1))
4327 && !CHAR_HEAD_P (*format))
4328 maybe_combine_byte = 1;
4331 format++;
4332 while (! CHAR_HEAD_P (*format));
4334 convbytes = format - src;
4335 memset (&discarded[src + 1 - format_start], 2, convbytes - 1);
4337 else
4339 unsigned char uc = *format++;
4340 if (! multibyte || ASCII_CHAR_P (uc))
4341 convbytes = 1;
4342 else
4344 int c = BYTE8_TO_CHAR (uc);
4345 convbytes = CHAR_STRING (c, str);
4346 src = (char *) str;
4350 if (convbytes <= buf + bufsize - p)
4352 memcpy (p, src, convbytes);
4353 p += convbytes;
4354 nchars++;
4355 continue;
4359 /* There wasn't enough room to store this conversion or single
4360 character. CONVBYTES says how much room is needed. Allocate
4361 enough room (and then some) and do it again. */
4363 ptrdiff_t used = p - buf;
4365 if (max_bufsize - used < convbytes)
4366 string_overflow ();
4367 bufsize = used + convbytes;
4368 bufsize = bufsize < max_bufsize / 2 ? bufsize * 2 : max_bufsize;
4370 if (buf == initial_buffer)
4372 buf = xmalloc (bufsize);
4373 sa_must_free = true;
4374 buf_save_value_index = SPECPDL_INDEX ();
4375 record_unwind_protect_ptr (xfree, buf);
4376 memcpy (buf, initial_buffer, used);
4378 else
4380 buf = xrealloc (buf, bufsize);
4381 set_unwind_protect_ptr (buf_save_value_index, xfree, buf);
4384 p = buf + used;
4387 format = format0;
4388 n = n0;
4391 if (bufsize < p - buf)
4392 emacs_abort ();
4394 if (maybe_combine_byte)
4395 nchars = multibyte_chars_in_text ((unsigned char *) buf, p - buf);
4396 val = make_specified_string (buf, nchars, p - buf, multibyte);
4398 /* If we allocated BUF with malloc, free it too. */
4399 SAFE_FREE ();
4401 /* If the format string has text properties, or any of the string
4402 arguments has text properties, set up text properties of the
4403 result string. */
4405 if (string_intervals (args[0]) || arg_intervals)
4407 Lisp_Object len, new_len, props;
4408 struct gcpro gcpro1;
4410 /* Add text properties from the format string. */
4411 len = make_number (SCHARS (args[0]));
4412 props = text_property_list (args[0], make_number (0), len, Qnil);
4413 GCPRO1 (props);
4415 if (CONSP (props))
4417 ptrdiff_t bytepos = 0, position = 0, translated = 0;
4418 ptrdiff_t argn = 1;
4419 Lisp_Object list;
4421 /* Adjust the bounds of each text property
4422 to the proper start and end in the output string. */
4424 /* Put the positions in PROPS in increasing order, so that
4425 we can do (effectively) one scan through the position
4426 space of the format string. */
4427 props = Fnreverse (props);
4429 /* BYTEPOS is the byte position in the format string,
4430 POSITION is the untranslated char position in it,
4431 TRANSLATED is the translated char position in BUF,
4432 and ARGN is the number of the next arg we will come to. */
4433 for (list = props; CONSP (list); list = XCDR (list))
4435 Lisp_Object item;
4436 ptrdiff_t pos;
4438 item = XCAR (list);
4440 /* First adjust the property start position. */
4441 pos = XINT (XCAR (item));
4443 /* Advance BYTEPOS, POSITION, TRANSLATED and ARGN
4444 up to this position. */
4445 for (; position < pos; bytepos++)
4447 if (! discarded[bytepos])
4448 position++, translated++;
4449 else if (discarded[bytepos] == 1)
4451 position++;
4452 if (translated == info[argn].start)
4454 translated += info[argn].end - info[argn].start;
4455 argn++;
4460 XSETCAR (item, make_number (translated));
4462 /* Likewise adjust the property end position. */
4463 pos = XINT (XCAR (XCDR (item)));
4465 for (; position < pos; bytepos++)
4467 if (! discarded[bytepos])
4468 position++, translated++;
4469 else if (discarded[bytepos] == 1)
4471 position++;
4472 if (translated == info[argn].start)
4474 translated += info[argn].end - info[argn].start;
4475 argn++;
4480 XSETCAR (XCDR (item), make_number (translated));
4483 add_text_properties_from_list (val, props, make_number (0));
4486 /* Add text properties from arguments. */
4487 if (arg_intervals)
4488 for (n = 1; n < nargs; ++n)
4489 if (info[n].intervals)
4491 len = make_number (SCHARS (args[n]));
4492 new_len = make_number (info[n].end - info[n].start);
4493 props = text_property_list (args[n], make_number (0), len, Qnil);
4494 props = extend_property_ranges (props, new_len);
4495 /* If successive arguments have properties, be sure that
4496 the value of `composition' property be the copy. */
4497 if (n > 1 && info[n - 1].end)
4498 make_composition_value_copy (props);
4499 add_text_properties_from_list (val, props,
4500 make_number (info[n].start));
4503 UNGCPRO;
4506 return val;
4509 Lisp_Object
4510 format2 (const char *string1, Lisp_Object arg0, Lisp_Object arg1)
4512 AUTO_STRING (format, string1);
4513 return Fformat (3, (Lisp_Object []) {format, arg0, arg1});
4516 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
4517 doc: /* Return t if two characters match, optionally ignoring case.
4518 Both arguments must be characters (i.e. integers).
4519 Case is ignored if `case-fold-search' is non-nil in the current buffer. */)
4520 (register Lisp_Object c1, Lisp_Object c2)
4522 int i1, i2;
4523 /* Check they're chars, not just integers, otherwise we could get array
4524 bounds violations in downcase. */
4525 CHECK_CHARACTER (c1);
4526 CHECK_CHARACTER (c2);
4528 if (XINT (c1) == XINT (c2))
4529 return Qt;
4530 if (NILP (BVAR (current_buffer, case_fold_search)))
4531 return Qnil;
4533 i1 = XFASTINT (c1);
4534 i2 = XFASTINT (c2);
4536 /* FIXME: It is possible to compare multibyte characters even when
4537 the current buffer is unibyte. Unfortunately this is ambiguous
4538 for characters between 128 and 255, as they could be either
4539 eight-bit raw bytes or Latin-1 characters. Assume the former for
4540 now. See Bug#17011, and also see casefiddle.c's casify_object,
4541 which has a similar problem. */
4542 if (NILP (BVAR (current_buffer, enable_multibyte_characters)))
4544 if (SINGLE_BYTE_CHAR_P (i1))
4545 i1 = UNIBYTE_TO_CHAR (i1);
4546 if (SINGLE_BYTE_CHAR_P (i2))
4547 i2 = UNIBYTE_TO_CHAR (i2);
4550 return (downcase (i1) == downcase (i2) ? Qt : Qnil);
4553 /* Transpose the markers in two regions of the current buffer, and
4554 adjust the ones between them if necessary (i.e.: if the regions
4555 differ in size).
4557 START1, END1 are the character positions of the first region.
4558 START1_BYTE, END1_BYTE are the byte positions.
4559 START2, END2 are the character positions of the second region.
4560 START2_BYTE, END2_BYTE are the byte positions.
4562 Traverses the entire marker list of the buffer to do so, adding an
4563 appropriate amount to some, subtracting from some, and leaving the
4564 rest untouched. Most of this is copied from adjust_markers in insdel.c.
4566 It's the caller's job to ensure that START1 <= END1 <= START2 <= END2. */
4568 static void
4569 transpose_markers (ptrdiff_t start1, ptrdiff_t end1,
4570 ptrdiff_t start2, ptrdiff_t end2,
4571 ptrdiff_t start1_byte, ptrdiff_t end1_byte,
4572 ptrdiff_t start2_byte, ptrdiff_t end2_byte)
4574 register ptrdiff_t amt1, amt1_byte, amt2, amt2_byte, diff, diff_byte, mpos;
4575 register struct Lisp_Marker *marker;
4577 /* Update point as if it were a marker. */
4578 if (PT < start1)
4580 else if (PT < end1)
4581 TEMP_SET_PT_BOTH (PT + (end2 - end1),
4582 PT_BYTE + (end2_byte - end1_byte));
4583 else if (PT < start2)
4584 TEMP_SET_PT_BOTH (PT + (end2 - start2) - (end1 - start1),
4585 (PT_BYTE + (end2_byte - start2_byte)
4586 - (end1_byte - start1_byte)));
4587 else if (PT < end2)
4588 TEMP_SET_PT_BOTH (PT - (start2 - start1),
4589 PT_BYTE - (start2_byte - start1_byte));
4591 /* We used to adjust the endpoints here to account for the gap, but that
4592 isn't good enough. Even if we assume the caller has tried to move the
4593 gap out of our way, it might still be at start1 exactly, for example;
4594 and that places it `inside' the interval, for our purposes. The amount
4595 of adjustment is nontrivial if there's a `denormalized' marker whose
4596 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
4597 the dirty work to Fmarker_position, below. */
4599 /* The difference between the region's lengths */
4600 diff = (end2 - start2) - (end1 - start1);
4601 diff_byte = (end2_byte - start2_byte) - (end1_byte - start1_byte);
4603 /* For shifting each marker in a region by the length of the other
4604 region plus the distance between the regions. */
4605 amt1 = (end2 - start2) + (start2 - end1);
4606 amt2 = (end1 - start1) + (start2 - end1);
4607 amt1_byte = (end2_byte - start2_byte) + (start2_byte - end1_byte);
4608 amt2_byte = (end1_byte - start1_byte) + (start2_byte - end1_byte);
4610 for (marker = BUF_MARKERS (current_buffer); marker; marker = marker->next)
4612 mpos = marker->bytepos;
4613 if (mpos >= start1_byte && mpos < end2_byte)
4615 if (mpos < end1_byte)
4616 mpos += amt1_byte;
4617 else if (mpos < start2_byte)
4618 mpos += diff_byte;
4619 else
4620 mpos -= amt2_byte;
4621 marker->bytepos = mpos;
4623 mpos = marker->charpos;
4624 if (mpos >= start1 && mpos < end2)
4626 if (mpos < end1)
4627 mpos += amt1;
4628 else if (mpos < start2)
4629 mpos += diff;
4630 else
4631 mpos -= amt2;
4633 marker->charpos = mpos;
4637 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
4638 doc: /* Transpose region STARTR1 to ENDR1 with STARTR2 to ENDR2.
4639 The regions should not be overlapping, because the size of the buffer is
4640 never changed in a transposition.
4642 Optional fifth arg LEAVE-MARKERS, if non-nil, means don't update
4643 any markers that happen to be located in the regions.
4645 Transposing beyond buffer boundaries is an error. */)
4646 (Lisp_Object startr1, Lisp_Object endr1, Lisp_Object startr2, Lisp_Object endr2, Lisp_Object leave_markers)
4648 register ptrdiff_t start1, end1, start2, end2;
4649 ptrdiff_t start1_byte, start2_byte, len1_byte, len2_byte, end2_byte;
4650 ptrdiff_t gap, len1, len_mid, len2;
4651 unsigned char *start1_addr, *start2_addr, *temp;
4653 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2, tmp_interval3;
4654 Lisp_Object buf;
4656 XSETBUFFER (buf, current_buffer);
4657 cur_intv = buffer_intervals (current_buffer);
4659 validate_region (&startr1, &endr1);
4660 validate_region (&startr2, &endr2);
4662 start1 = XFASTINT (startr1);
4663 end1 = XFASTINT (endr1);
4664 start2 = XFASTINT (startr2);
4665 end2 = XFASTINT (endr2);
4666 gap = GPT;
4668 /* Swap the regions if they're reversed. */
4669 if (start2 < end1)
4671 register ptrdiff_t glumph = start1;
4672 start1 = start2;
4673 start2 = glumph;
4674 glumph = end1;
4675 end1 = end2;
4676 end2 = glumph;
4679 len1 = end1 - start1;
4680 len2 = end2 - start2;
4682 if (start2 < end1)
4683 error ("Transposed regions overlap");
4684 /* Nothing to change for adjacent regions with one being empty */
4685 else if ((start1 == end1 || start2 == end2) && end1 == start2)
4686 return Qnil;
4688 /* The possibilities are:
4689 1. Adjacent (contiguous) regions, or separate but equal regions
4690 (no, really equal, in this case!), or
4691 2. Separate regions of unequal size.
4693 The worst case is usually No. 2. It means that (aside from
4694 potential need for getting the gap out of the way), there also
4695 needs to be a shifting of the text between the two regions. So
4696 if they are spread far apart, we are that much slower... sigh. */
4698 /* It must be pointed out that the really studly thing to do would
4699 be not to move the gap at all, but to leave it in place and work
4700 around it if necessary. This would be extremely efficient,
4701 especially considering that people are likely to do
4702 transpositions near where they are working interactively, which
4703 is exactly where the gap would be found. However, such code
4704 would be much harder to write and to read. So, if you are
4705 reading this comment and are feeling squirrely, by all means have
4706 a go! I just didn't feel like doing it, so I will simply move
4707 the gap the minimum distance to get it out of the way, and then
4708 deal with an unbroken array. */
4710 start1_byte = CHAR_TO_BYTE (start1);
4711 end2_byte = CHAR_TO_BYTE (end2);
4713 /* Make sure the gap won't interfere, by moving it out of the text
4714 we will operate on. */
4715 if (start1 < gap && gap < end2)
4717 if (gap - start1 < end2 - gap)
4718 move_gap_both (start1, start1_byte);
4719 else
4720 move_gap_both (end2, end2_byte);
4723 start2_byte = CHAR_TO_BYTE (start2);
4724 len1_byte = CHAR_TO_BYTE (end1) - start1_byte;
4725 len2_byte = end2_byte - start2_byte;
4727 #ifdef BYTE_COMBINING_DEBUG
4728 if (end1 == start2)
4730 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4731 len2_byte, start1, start1_byte)
4732 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4733 len1_byte, end2, start2_byte + len2_byte)
4734 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4735 len1_byte, end2, start2_byte + len2_byte))
4736 emacs_abort ();
4738 else
4740 if (count_combining_before (BYTE_POS_ADDR (start2_byte),
4741 len2_byte, start1, start1_byte)
4742 || count_combining_before (BYTE_POS_ADDR (start1_byte),
4743 len1_byte, start2, start2_byte)
4744 || count_combining_after (BYTE_POS_ADDR (start2_byte),
4745 len2_byte, end1, start1_byte + len1_byte)
4746 || count_combining_after (BYTE_POS_ADDR (start1_byte),
4747 len1_byte, end2, start2_byte + len2_byte))
4748 emacs_abort ();
4750 #endif
4752 /* Hmmm... how about checking to see if the gap is large
4753 enough to use as the temporary storage? That would avoid an
4754 allocation... interesting. Later, don't fool with it now. */
4756 /* Working without memmove, for portability (sigh), so must be
4757 careful of overlapping subsections of the array... */
4759 if (end1 == start2) /* adjacent regions */
4761 modify_text (start1, end2);
4762 record_change (start1, len1 + len2);
4764 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4765 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4766 /* Don't use Fset_text_properties: that can cause GC, which can
4767 clobber objects stored in the tmp_intervals. */
4768 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4769 if (tmp_interval3)
4770 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4772 USE_SAFE_ALLOCA;
4774 /* First region smaller than second. */
4775 if (len1_byte < len2_byte)
4777 temp = SAFE_ALLOCA (len2_byte);
4779 /* Don't precompute these addresses. We have to compute them
4780 at the last minute, because the relocating allocator might
4781 have moved the buffer around during the xmalloc. */
4782 start1_addr = BYTE_POS_ADDR (start1_byte);
4783 start2_addr = BYTE_POS_ADDR (start2_byte);
4785 memcpy (temp, start2_addr, len2_byte);
4786 memcpy (start1_addr + len2_byte, start1_addr, len1_byte);
4787 memcpy (start1_addr, temp, len2_byte);
4789 else
4790 /* First region not smaller than second. */
4792 temp = SAFE_ALLOCA (len1_byte);
4793 start1_addr = BYTE_POS_ADDR (start1_byte);
4794 start2_addr = BYTE_POS_ADDR (start2_byte);
4795 memcpy (temp, start1_addr, len1_byte);
4796 memcpy (start1_addr, start2_addr, len2_byte);
4797 memcpy (start1_addr + len2_byte, temp, len1_byte);
4800 SAFE_FREE ();
4801 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
4802 len1, current_buffer, 0);
4803 graft_intervals_into_buffer (tmp_interval2, start1,
4804 len2, current_buffer, 0);
4805 update_compositions (start1, start1 + len2, CHECK_BORDER);
4806 update_compositions (start1 + len2, end2, CHECK_TAIL);
4808 /* Non-adjacent regions, because end1 != start2, bleagh... */
4809 else
4811 len_mid = start2_byte - (start1_byte + len1_byte);
4813 if (len1_byte == len2_byte)
4814 /* Regions are same size, though, how nice. */
4816 USE_SAFE_ALLOCA;
4818 modify_text (start1, end1);
4819 modify_text (start2, end2);
4820 record_change (start1, len1);
4821 record_change (start2, len2);
4822 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4823 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4825 tmp_interval3 = validate_interval_range (buf, &startr1, &endr1, 0);
4826 if (tmp_interval3)
4827 set_text_properties_1 (startr1, endr1, Qnil, buf, tmp_interval3);
4829 tmp_interval3 = validate_interval_range (buf, &startr2, &endr2, 0);
4830 if (tmp_interval3)
4831 set_text_properties_1 (startr2, endr2, Qnil, buf, tmp_interval3);
4833 temp = SAFE_ALLOCA (len1_byte);
4834 start1_addr = BYTE_POS_ADDR (start1_byte);
4835 start2_addr = BYTE_POS_ADDR (start2_byte);
4836 memcpy (temp, start1_addr, len1_byte);
4837 memcpy (start1_addr, start2_addr, len2_byte);
4838 memcpy (start2_addr, temp, len1_byte);
4839 SAFE_FREE ();
4841 graft_intervals_into_buffer (tmp_interval1, start2,
4842 len1, current_buffer, 0);
4843 graft_intervals_into_buffer (tmp_interval2, start1,
4844 len2, current_buffer, 0);
4847 else if (len1_byte < len2_byte) /* Second region larger than first */
4848 /* Non-adjacent & unequal size, area between must also be shifted. */
4850 USE_SAFE_ALLOCA;
4852 modify_text (start1, end2);
4853 record_change (start1, (end2 - start1));
4854 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4855 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4856 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4858 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4859 if (tmp_interval3)
4860 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4862 /* holds region 2 */
4863 temp = SAFE_ALLOCA (len2_byte);
4864 start1_addr = BYTE_POS_ADDR (start1_byte);
4865 start2_addr = BYTE_POS_ADDR (start2_byte);
4866 memcpy (temp, start2_addr, len2_byte);
4867 memcpy (start1_addr + len_mid + len2_byte, start1_addr, len1_byte);
4868 memmove (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4869 memcpy (start1_addr, temp, len2_byte);
4870 SAFE_FREE ();
4872 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4873 len1, current_buffer, 0);
4874 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4875 len_mid, current_buffer, 0);
4876 graft_intervals_into_buffer (tmp_interval2, start1,
4877 len2, current_buffer, 0);
4879 else
4880 /* Second region smaller than first. */
4882 USE_SAFE_ALLOCA;
4884 record_change (start1, (end2 - start1));
4885 modify_text (start1, end2);
4887 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
4888 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
4889 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
4891 tmp_interval3 = validate_interval_range (buf, &startr1, &endr2, 0);
4892 if (tmp_interval3)
4893 set_text_properties_1 (startr1, endr2, Qnil, buf, tmp_interval3);
4895 /* holds region 1 */
4896 temp = SAFE_ALLOCA (len1_byte);
4897 start1_addr = BYTE_POS_ADDR (start1_byte);
4898 start2_addr = BYTE_POS_ADDR (start2_byte);
4899 memcpy (temp, start1_addr, len1_byte);
4900 memcpy (start1_addr, start2_addr, len2_byte);
4901 memcpy (start1_addr + len2_byte, start1_addr + len1_byte, len_mid);
4902 memcpy (start1_addr + len2_byte + len_mid, temp, len1_byte);
4903 SAFE_FREE ();
4905 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
4906 len1, current_buffer, 0);
4907 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
4908 len_mid, current_buffer, 0);
4909 graft_intervals_into_buffer (tmp_interval2, start1,
4910 len2, current_buffer, 0);
4913 update_compositions (start1, start1 + len2, CHECK_BORDER);
4914 update_compositions (end2 - len1, end2, CHECK_BORDER);
4917 /* When doing multiple transpositions, it might be nice
4918 to optimize this. Perhaps the markers in any one buffer
4919 should be organized in some sorted data tree. */
4920 if (NILP (leave_markers))
4922 transpose_markers (start1, end1, start2, end2,
4923 start1_byte, start1_byte + len1_byte,
4924 start2_byte, start2_byte + len2_byte);
4925 fix_start_end_in_overlays (start1, end2);
4928 signal_after_change (start1, end2 - start1, end2 - start1);
4929 return Qnil;
4933 void
4934 syms_of_editfns (void)
4936 DEFSYM (Qbuffer_access_fontify_functions, "buffer-access-fontify-functions");
4938 DEFVAR_LISP ("inhibit-field-text-motion", Vinhibit_field_text_motion,
4939 doc: /* Non-nil means text motion commands don't notice fields. */);
4940 Vinhibit_field_text_motion = Qnil;
4942 DEFVAR_LISP ("buffer-access-fontify-functions",
4943 Vbuffer_access_fontify_functions,
4944 doc: /* List of functions called by `buffer-substring' to fontify if necessary.
4945 Each function is called with two arguments which specify the range
4946 of the buffer being accessed. */);
4947 Vbuffer_access_fontify_functions = Qnil;
4950 Lisp_Object obuf;
4951 obuf = Fcurrent_buffer ();
4952 /* Do this here, because init_buffer_once is too early--it won't work. */
4953 Fset_buffer (Vprin1_to_string_buffer);
4954 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
4955 Fset (Fmake_local_variable (intern_c_string ("buffer-access-fontify-functions")),
4956 Qnil);
4957 Fset_buffer (obuf);
4960 DEFVAR_LISP ("buffer-access-fontified-property",
4961 Vbuffer_access_fontified_property,
4962 doc: /* Property which (if non-nil) indicates text has been fontified.
4963 `buffer-substring' need not call the `buffer-access-fontify-functions'
4964 functions if all the text being accessed has this property. */);
4965 Vbuffer_access_fontified_property = Qnil;
4967 DEFVAR_LISP ("system-name", Vsystem_name,
4968 doc: /* The host name of the machine Emacs is running on. */);
4970 DEFVAR_LISP ("user-full-name", Vuser_full_name,
4971 doc: /* The full name of the user logged in. */);
4973 DEFVAR_LISP ("user-login-name", Vuser_login_name,
4974 doc: /* The user's name, taken from environment variables if possible. */);
4976 DEFVAR_LISP ("user-real-login-name", Vuser_real_login_name,
4977 doc: /* The user's name, based upon the real uid only. */);
4979 DEFVAR_LISP ("operating-system-release", Voperating_system_release,
4980 doc: /* The release of the operating system Emacs is running on. */);
4982 defsubr (&Spropertize);
4983 defsubr (&Schar_equal);
4984 defsubr (&Sgoto_char);
4985 defsubr (&Sstring_to_char);
4986 defsubr (&Schar_to_string);
4987 defsubr (&Sbyte_to_string);
4988 defsubr (&Sbuffer_substring);
4989 defsubr (&Sbuffer_substring_no_properties);
4990 defsubr (&Sbuffer_string);
4991 defsubr (&Sget_pos_property);
4993 defsubr (&Spoint_marker);
4994 defsubr (&Smark_marker);
4995 defsubr (&Spoint);
4996 defsubr (&Sregion_beginning);
4997 defsubr (&Sregion_end);
4999 DEFSYM (Qfield, "field");
5000 DEFSYM (Qboundary, "boundary");
5001 defsubr (&Sfield_beginning);
5002 defsubr (&Sfield_end);
5003 defsubr (&Sfield_string);
5004 defsubr (&Sfield_string_no_properties);
5005 defsubr (&Sdelete_field);
5006 defsubr (&Sconstrain_to_field);
5008 defsubr (&Sline_beginning_position);
5009 defsubr (&Sline_end_position);
5011 defsubr (&Ssave_excursion);
5012 defsubr (&Ssave_current_buffer);
5014 defsubr (&Sbuffer_size);
5015 defsubr (&Spoint_max);
5016 defsubr (&Spoint_min);
5017 defsubr (&Spoint_min_marker);
5018 defsubr (&Spoint_max_marker);
5019 defsubr (&Sgap_position);
5020 defsubr (&Sgap_size);
5021 defsubr (&Sposition_bytes);
5022 defsubr (&Sbyte_to_position);
5024 defsubr (&Sbobp);
5025 defsubr (&Seobp);
5026 defsubr (&Sbolp);
5027 defsubr (&Seolp);
5028 defsubr (&Sfollowing_char);
5029 defsubr (&Sprevious_char);
5030 defsubr (&Schar_after);
5031 defsubr (&Schar_before);
5032 defsubr (&Sinsert);
5033 defsubr (&Sinsert_before_markers);
5034 defsubr (&Sinsert_and_inherit);
5035 defsubr (&Sinsert_and_inherit_before_markers);
5036 defsubr (&Sinsert_char);
5037 defsubr (&Sinsert_byte);
5039 defsubr (&Suser_login_name);
5040 defsubr (&Suser_real_login_name);
5041 defsubr (&Suser_uid);
5042 defsubr (&Suser_real_uid);
5043 defsubr (&Sgroup_gid);
5044 defsubr (&Sgroup_real_gid);
5045 defsubr (&Suser_full_name);
5046 defsubr (&Semacs_pid);
5047 defsubr (&Scurrent_time);
5048 defsubr (&Stime_add);
5049 defsubr (&Stime_subtract);
5050 defsubr (&Stime_less_p);
5051 defsubr (&Sget_internal_run_time);
5052 defsubr (&Sformat_time_string);
5053 defsubr (&Sfloat_time);
5054 defsubr (&Sdecode_time);
5055 defsubr (&Sencode_time);
5056 defsubr (&Scurrent_time_string);
5057 defsubr (&Scurrent_time_zone);
5058 defsubr (&Sset_time_zone_rule);
5059 defsubr (&Ssystem_name);
5060 defsubr (&Smessage);
5061 defsubr (&Smessage_box);
5062 defsubr (&Smessage_or_box);
5063 defsubr (&Scurrent_message);
5064 defsubr (&Sformat);
5066 defsubr (&Sinsert_buffer_substring);
5067 defsubr (&Scompare_buffer_substrings);
5068 defsubr (&Ssubst_char_in_region);
5069 defsubr (&Stranslate_region_internal);
5070 defsubr (&Sdelete_region);
5071 defsubr (&Sdelete_and_extract_region);
5072 defsubr (&Swiden);
5073 defsubr (&Snarrow_to_region);
5074 defsubr (&Ssave_restriction);
5075 defsubr (&Stranspose_regions);