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