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