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