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