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