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