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