(Fformat_time_string): Doc fix.
[bpt/emacs.git] / src / editfns.c
1 /* Lisp functions pertaining to editing.
2 Copyright (C) 1985,86,87,89,93,94,95 Free Software Foundation, Inc.
3
4 This file is part of GNU Emacs.
5
6 GNU Emacs is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
9 any later version.
10
11 GNU Emacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs; see the file COPYING. If not, write to
18 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
20
21
22 #include <sys/types.h>
23
24 #include <config.h>
25
26 #ifdef VMS
27 #include "vms-pwd.h"
28 #else
29 #include <pwd.h>
30 #endif
31
32 #include "lisp.h"
33 #include "intervals.h"
34 #include "buffer.h"
35 #include "window.h"
36
37 #include "systime.h"
38
39 #define min(a, b) ((a) < (b) ? (a) : (b))
40 #define max(a, b) ((a) > (b) ? (a) : (b))
41
42 extern char **environ;
43 extern Lisp_Object make_time ();
44 extern void insert_from_buffer ();
45 static long difftm ();
46 static void update_buffer_properties ();
47 void set_time_zone_rule ();
48
49 Lisp_Object Vbuffer_access_fontify_functions;
50 Lisp_Object Qbuffer_access_fontify_functions;
51 Lisp_Object Vbuffer_access_fontified_property;
52
53 /* Some static data, and a function to initialize it for each run */
54
55 Lisp_Object Vsystem_name;
56 Lisp_Object Vuser_real_login_name; /* login name of current user ID */
57 Lisp_Object Vuser_full_name; /* full name of current user */
58 Lisp_Object Vuser_login_name; /* user name from LOGNAME or USER */
59
60 void
61 init_editfns ()
62 {
63 char *user_name;
64 register unsigned char *p, *q, *r;
65 struct passwd *pw; /* password entry for the current user */
66 extern char *index ();
67 Lisp_Object tem;
68
69 /* Set up system_name even when dumping. */
70 init_system_name ();
71
72 #ifndef CANNOT_DUMP
73 /* Don't bother with this on initial start when just dumping out */
74 if (!initialized)
75 return;
76 #endif /* not CANNOT_DUMP */
77
78 pw = (struct passwd *) getpwuid (getuid ());
79 #ifdef MSDOS
80 /* We let the real user name default to "root" because that's quite
81 accurate on MSDOG and because it lets Emacs find the init file.
82 (The DVX libraries override the Djgpp libraries here.) */
83 Vuser_real_login_name = build_string (pw ? pw->pw_name : "root");
84 #else
85 Vuser_real_login_name = build_string (pw ? pw->pw_name : "unknown");
86 #endif
87
88 /* Get the effective user name, by consulting environment variables,
89 or the effective uid if those are unset. */
90 user_name = (char *) getenv ("LOGNAME");
91 if (!user_name)
92 #ifdef WINDOWSNT
93 user_name = (char *) getenv ("USERNAME"); /* it's USERNAME on NT */
94 #else /* WINDOWSNT */
95 user_name = (char *) getenv ("USER");
96 #endif /* WINDOWSNT */
97 if (!user_name)
98 {
99 pw = (struct passwd *) getpwuid (geteuid ());
100 user_name = (char *) (pw ? pw->pw_name : "unknown");
101 }
102 Vuser_login_name = build_string (user_name);
103
104 /* If the user name claimed in the environment vars differs from
105 the real uid, use the claimed name to find the full name. */
106 tem = Fstring_equal (Vuser_login_name, Vuser_real_login_name);
107 if (NILP (tem))
108 pw = (struct passwd *) getpwnam (XSTRING (Vuser_login_name)->data);
109
110 p = (unsigned char *) (pw ? USER_FULL_NAME : "unknown");
111 q = (unsigned char *) index (p, ',');
112 Vuser_full_name = make_string (p, q ? q - p : strlen (p));
113
114 #ifdef AMPERSAND_FULL_NAME
115 p = XSTRING (Vuser_full_name)->data;
116 q = (unsigned char *) index (p, '&');
117 /* Substitute the login name for the &, upcasing the first character. */
118 if (q)
119 {
120 r = (unsigned char *) alloca (strlen (p)
121 + XSTRING (Vuser_login_name)->size + 1);
122 bcopy (p, r, q - p);
123 r[q - p] = 0;
124 strcat (r, XSTRING (Vuser_login_name)->data);
125 r[q - p] = UPCASE (r[q - p]);
126 strcat (r, q + 1);
127 Vuser_full_name = build_string (r);
128 }
129 #endif /* AMPERSAND_FULL_NAME */
130
131 p = (unsigned char *) getenv ("NAME");
132 if (p)
133 Vuser_full_name = build_string (p);
134 }
135 \f
136 DEFUN ("char-to-string", Fchar_to_string, Schar_to_string, 1, 1, 0,
137 "Convert arg CHARACTER to a one-character string containing that character.")
138 (character)
139 Lisp_Object character;
140 {
141 char c;
142 CHECK_NUMBER (character, 0);
143
144 c = XINT (character);
145 return make_string (&c, 1);
146 }
147
148 DEFUN ("string-to-char", Fstring_to_char, Sstring_to_char, 1, 1, 0,
149 "Convert arg STRING to a character, the first character of that string.")
150 (string)
151 register Lisp_Object string;
152 {
153 register Lisp_Object val;
154 register struct Lisp_String *p;
155 CHECK_STRING (string, 0);
156
157 p = XSTRING (string);
158 if (p->size)
159 XSETFASTINT (val, ((unsigned char *) p->data)[0]);
160 else
161 XSETFASTINT (val, 0);
162 return val;
163 }
164 \f
165 static Lisp_Object
166 buildmark (val)
167 int val;
168 {
169 register Lisp_Object mark;
170 mark = Fmake_marker ();
171 Fset_marker (mark, make_number (val), Qnil);
172 return mark;
173 }
174
175 DEFUN ("point", Fpoint, Spoint, 0, 0, 0,
176 "Return value of point, as an integer.\n\
177 Beginning of buffer is position (point-min)")
178 ()
179 {
180 Lisp_Object temp;
181 XSETFASTINT (temp, point);
182 return temp;
183 }
184
185 DEFUN ("point-marker", Fpoint_marker, Spoint_marker, 0, 0, 0,
186 "Return value of point, as a marker object.")
187 ()
188 {
189 return buildmark (point);
190 }
191
192 int
193 clip_to_bounds (lower, num, upper)
194 int lower, num, upper;
195 {
196 if (num < lower)
197 return lower;
198 else if (num > upper)
199 return upper;
200 else
201 return num;
202 }
203
204 DEFUN ("goto-char", Fgoto_char, Sgoto_char, 1, 1, "NGoto char: ",
205 "Set point to POSITION, a number or marker.\n\
206 Beginning of buffer is position (point-min), end is (point-max).")
207 (position)
208 register Lisp_Object position;
209 {
210 CHECK_NUMBER_COERCE_MARKER (position, 0);
211
212 SET_PT (clip_to_bounds (BEGV, XINT (position), ZV));
213 return position;
214 }
215
216 static Lisp_Object
217 region_limit (beginningp)
218 int beginningp;
219 {
220 extern Lisp_Object Vmark_even_if_inactive; /* Defined in callint.c. */
221 register Lisp_Object m;
222 if (!NILP (Vtransient_mark_mode) && NILP (Vmark_even_if_inactive)
223 && NILP (current_buffer->mark_active))
224 Fsignal (Qmark_inactive, Qnil);
225 m = Fmarker_position (current_buffer->mark);
226 if (NILP (m)) error ("There is no region now");
227 if ((point < XFASTINT (m)) == beginningp)
228 return (make_number (point));
229 else
230 return (m);
231 }
232
233 DEFUN ("region-beginning", Fregion_beginning, Sregion_beginning, 0, 0, 0,
234 "Return position of beginning of region, as an integer.")
235 ()
236 {
237 return (region_limit (1));
238 }
239
240 DEFUN ("region-end", Fregion_end, Sregion_end, 0, 0, 0,
241 "Return position of end of region, as an integer.")
242 ()
243 {
244 return (region_limit (0));
245 }
246
247 DEFUN ("mark-marker", Fmark_marker, Smark_marker, 0, 0, 0,
248 "Return this buffer's mark, as a marker object.\n\
249 Watch out! Moving this marker changes the mark position.\n\
250 If you set the marker not to point anywhere, the buffer will have no mark.")
251 ()
252 {
253 return current_buffer->mark;
254 }
255
256 Lisp_Object
257 save_excursion_save ()
258 {
259 register int visible = (XBUFFER (XWINDOW (selected_window)->buffer)
260 == current_buffer);
261
262 return Fcons (Fpoint_marker (),
263 Fcons (Fcopy_marker (current_buffer->mark, Qnil),
264 Fcons (visible ? Qt : Qnil,
265 current_buffer->mark_active)));
266 }
267
268 Lisp_Object
269 save_excursion_restore (info)
270 Lisp_Object info;
271 {
272 Lisp_Object tem, tem1, omark, nmark;
273 struct gcpro gcpro1, gcpro2, gcpro3;
274
275 tem = Fmarker_buffer (Fcar (info));
276 /* If buffer being returned to is now deleted, avoid error */
277 /* Otherwise could get error here while unwinding to top level
278 and crash */
279 /* In that case, Fmarker_buffer returns nil now. */
280 if (NILP (tem))
281 return Qnil;
282
283 omark = nmark = Qnil;
284 GCPRO3 (info, omark, nmark);
285
286 Fset_buffer (tem);
287 tem = Fcar (info);
288 Fgoto_char (tem);
289 unchain_marker (tem);
290 tem = Fcar (Fcdr (info));
291 omark = Fmarker_position (current_buffer->mark);
292 Fset_marker (current_buffer->mark, tem, Fcurrent_buffer ());
293 nmark = Fmarker_position (tem);
294 unchain_marker (tem);
295 tem = Fcdr (Fcdr (info));
296 #if 0 /* We used to make the current buffer visible in the selected window
297 if that was true previously. That avoids some anomalies.
298 But it creates others, and it wasn't documented, and it is simpler
299 and cleaner never to alter the window/buffer connections. */
300 tem1 = Fcar (tem);
301 if (!NILP (tem1)
302 && current_buffer != XBUFFER (XWINDOW (selected_window)->buffer))
303 Fswitch_to_buffer (Fcurrent_buffer (), Qnil);
304 #endif /* 0 */
305
306 tem1 = current_buffer->mark_active;
307 current_buffer->mark_active = Fcdr (tem);
308 if (!NILP (Vrun_hooks))
309 {
310 /* If mark is active now, and either was not active
311 or was at a different place, run the activate hook. */
312 if (! NILP (current_buffer->mark_active))
313 {
314 if (! EQ (omark, nmark))
315 call1 (Vrun_hooks, intern ("activate-mark-hook"));
316 }
317 /* If mark has ceased to be active, run deactivate hook. */
318 else if (! NILP (tem1))
319 call1 (Vrun_hooks, intern ("deactivate-mark-hook"));
320 }
321 UNGCPRO;
322 return Qnil;
323 }
324
325 DEFUN ("save-excursion", Fsave_excursion, Ssave_excursion, 0, UNEVALLED, 0,
326 "Save point, mark, and current buffer; execute BODY; restore those things.\n\
327 Executes BODY just like `progn'.\n\
328 The values of point, mark and the current buffer are restored\n\
329 even in case of abnormal exit (throw or error).\n\
330 The state of activation of the mark is also restored.")
331 (args)
332 Lisp_Object args;
333 {
334 register Lisp_Object val;
335 int count = specpdl_ptr - specpdl;
336
337 record_unwind_protect (save_excursion_restore, save_excursion_save ());
338
339 val = Fprogn (args);
340 return unbind_to (count, val);
341 }
342 \f
343 DEFUN ("buffer-size", Fbufsize, Sbufsize, 0, 0, 0,
344 "Return the number of characters in the current buffer.")
345 ()
346 {
347 Lisp_Object temp;
348 XSETFASTINT (temp, Z - BEG);
349 return temp;
350 }
351
352 DEFUN ("point-min", Fpoint_min, Spoint_min, 0, 0, 0,
353 "Return the minimum permissible value of point in the current buffer.\n\
354 This is 1, unless narrowing (a buffer restriction) is in effect.")
355 ()
356 {
357 Lisp_Object temp;
358 XSETFASTINT (temp, BEGV);
359 return temp;
360 }
361
362 DEFUN ("point-min-marker", Fpoint_min_marker, Spoint_min_marker, 0, 0, 0,
363 "Return a marker to the minimum permissible value of point in this buffer.\n\
364 This is the beginning, unless narrowing (a buffer restriction) is in effect.")
365 ()
366 {
367 return buildmark (BEGV);
368 }
369
370 DEFUN ("point-max", Fpoint_max, Spoint_max, 0, 0, 0,
371 "Return the maximum permissible value of point in the current buffer.\n\
372 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
373 is in effect, in which case it is less.")
374 ()
375 {
376 Lisp_Object temp;
377 XSETFASTINT (temp, ZV);
378 return temp;
379 }
380
381 DEFUN ("point-max-marker", Fpoint_max_marker, Spoint_max_marker, 0, 0, 0,
382 "Return a marker to the maximum permissible value of point in this buffer.\n\
383 This is (1+ (buffer-size)), unless narrowing (a buffer restriction)\n\
384 is in effect, in which case it is less.")
385 ()
386 {
387 return buildmark (ZV);
388 }
389
390 DEFUN ("following-char", Ffollowing_char, Sfollowing_char, 0, 0, 0,
391 "Return the character following point, as a number.\n\
392 At the end of the buffer or accessible region, return 0.")
393 ()
394 {
395 Lisp_Object temp;
396 if (point >= ZV)
397 XSETFASTINT (temp, 0);
398 else
399 XSETFASTINT (temp, FETCH_CHAR (point));
400 return temp;
401 }
402
403 DEFUN ("preceding-char", Fprevious_char, Sprevious_char, 0, 0, 0,
404 "Return the character preceding point, as a number.\n\
405 At the beginning of the buffer or accessible region, return 0.")
406 ()
407 {
408 Lisp_Object temp;
409 if (point <= BEGV)
410 XSETFASTINT (temp, 0);
411 else
412 XSETFASTINT (temp, FETCH_CHAR (point - 1));
413 return temp;
414 }
415
416 DEFUN ("bobp", Fbobp, Sbobp, 0, 0, 0,
417 "Return T if point is at the beginning of the buffer.\n\
418 If the buffer is narrowed, this means the beginning of the narrowed part.")
419 ()
420 {
421 if (point == BEGV)
422 return Qt;
423 return Qnil;
424 }
425
426 DEFUN ("eobp", Feobp, Seobp, 0, 0, 0,
427 "Return T if point is at the end of the buffer.\n\
428 If the buffer is narrowed, this means the end of the narrowed part.")
429 ()
430 {
431 if (point == ZV)
432 return Qt;
433 return Qnil;
434 }
435
436 DEFUN ("bolp", Fbolp, Sbolp, 0, 0, 0,
437 "Return T if point is at the beginning of a line.")
438 ()
439 {
440 if (point == BEGV || FETCH_CHAR (point - 1) == '\n')
441 return Qt;
442 return Qnil;
443 }
444
445 DEFUN ("eolp", Feolp, Seolp, 0, 0, 0,
446 "Return T if point is at the end of a line.\n\
447 `End of a line' includes point being at the end of the buffer.")
448 ()
449 {
450 if (point == ZV || FETCH_CHAR (point) == '\n')
451 return Qt;
452 return Qnil;
453 }
454
455 DEFUN ("char-after", Fchar_after, Schar_after, 1, 1, 0,
456 "Return character in current buffer at position POS.\n\
457 POS is an integer or a buffer pointer.\n\
458 If POS is out of range, the value is nil.")
459 (pos)
460 Lisp_Object pos;
461 {
462 register Lisp_Object val;
463 register int n;
464
465 CHECK_NUMBER_COERCE_MARKER (pos, 0);
466
467 n = XINT (pos);
468 if (n < BEGV || n >= ZV) return Qnil;
469
470 XSETFASTINT (val, FETCH_CHAR (n));
471 return val;
472 }
473 \f
474 DEFUN ("user-login-name", Fuser_login_name, Suser_login_name, 0, 1, 0,
475 "Return the name under which the user logged in, as a string.\n\
476 This is based on the effective uid, not the real uid.\n\
477 Also, if the environment variable LOGNAME or USER is set,\n\
478 that determines the value of this function.\n\n\
479 If optional argument UID is an integer, return the login name of the user\n\
480 with that uid, or nil if there is no such user.")
481 (uid)
482 Lisp_Object uid;
483 {
484 struct passwd *pw;
485
486 /* Set up the user name info if we didn't do it before.
487 (That can happen if Emacs is dumpable
488 but you decide to run `temacs -l loadup' and not dump. */
489 if (INTEGERP (Vuser_login_name))
490 init_editfns ();
491
492 if (NILP (uid))
493 return Vuser_login_name;
494
495 CHECK_NUMBER (uid, 0);
496 pw = (struct passwd *) getpwuid (XINT (uid));
497 return (pw ? build_string (pw->pw_name) : Qnil);
498 }
499
500 DEFUN ("user-real-login-name", Fuser_real_login_name, Suser_real_login_name,
501 0, 0, 0,
502 "Return the name of the user's real uid, as a string.\n\
503 This ignores the environment variables LOGNAME and USER, so it differs from\n\
504 `user-login-name' when running under `su'.")
505 ()
506 {
507 /* Set up the user name info if we didn't do it before.
508 (That can happen if Emacs is dumpable
509 but you decide to run `temacs -l loadup' and not dump. */
510 if (INTEGERP (Vuser_login_name))
511 init_editfns ();
512 return Vuser_real_login_name;
513 }
514
515 DEFUN ("user-uid", Fuser_uid, Suser_uid, 0, 0, 0,
516 "Return the effective uid of Emacs, as an integer.")
517 ()
518 {
519 return make_number (geteuid ());
520 }
521
522 DEFUN ("user-real-uid", Fuser_real_uid, Suser_real_uid, 0, 0, 0,
523 "Return the real uid of Emacs, as an integer.")
524 ()
525 {
526 return make_number (getuid ());
527 }
528
529 DEFUN ("user-full-name", Fuser_full_name, Suser_full_name, 0, 0, 0,
530 "Return the full name of the user logged in, as a string.")
531 ()
532 {
533 return Vuser_full_name;
534 }
535
536 DEFUN ("system-name", Fsystem_name, Ssystem_name, 0, 0, 0,
537 "Return the name of the machine you are running on, as a string.")
538 ()
539 {
540 return Vsystem_name;
541 }
542
543 /* For the benefit of callers who don't want to include lisp.h */
544 char *
545 get_system_name ()
546 {
547 return (char *) XSTRING (Vsystem_name)->data;
548 }
549
550 DEFUN ("emacs-pid", Femacs_pid, Semacs_pid, 0, 0, 0,
551 "Return the process ID of Emacs, as an integer.")
552 ()
553 {
554 return make_number (getpid ());
555 }
556
557 DEFUN ("current-time", Fcurrent_time, Scurrent_time, 0, 0, 0,
558 "Return the current time, as the number of seconds since 1970-01-01 00:00:00.\n\
559 The time is returned as a list of three integers. The first has the\n\
560 most significant 16 bits of the seconds, while the second has the\n\
561 least significant 16 bits. The third integer gives the microsecond\n\
562 count.\n\
563 \n\
564 The microsecond count is zero on systems that do not provide\n\
565 resolution finer than a second.")
566 ()
567 {
568 EMACS_TIME t;
569 Lisp_Object result[3];
570
571 EMACS_GET_TIME (t);
572 XSETINT (result[0], (EMACS_SECS (t) >> 16) & 0xffff);
573 XSETINT (result[1], (EMACS_SECS (t) >> 0) & 0xffff);
574 XSETINT (result[2], EMACS_USECS (t));
575
576 return Flist (3, result);
577 }
578 \f
579
580 static int
581 lisp_time_argument (specified_time, result)
582 Lisp_Object specified_time;
583 time_t *result;
584 {
585 if (NILP (specified_time))
586 return time (result) != -1;
587 else
588 {
589 Lisp_Object high, low;
590 high = Fcar (specified_time);
591 CHECK_NUMBER (high, 0);
592 low = Fcdr (specified_time);
593 if (CONSP (low))
594 low = Fcar (low);
595 CHECK_NUMBER (low, 0);
596 *result = (XINT (high) << 16) + (XINT (low) & 0xffff);
597 return *result >> 16 == XINT (high);
598 }
599 }
600
601 DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 2, 0,
602 "Use FORMAT-STRING to format the time TIME.\n\
603 TIME is specified as (HIGH LOW . IGNORED) or (HIGH . LOW), as from\n\
604 `current-time' and `file-attributes'.\n\
605 FORMAT-STRING may contain %-sequences to substitute parts of the time.\n\
606 %a is replaced by the abbreviated name of the day of week.\n\
607 %A is replaced by the full name of the day of week.\n\
608 %b is replaced by the abbreviated name of the month.\n\
609 %B is replaced by the full name of the month.\n\
610 %c stands for the preferred date/time format of the C locale.\n\
611 %d is replaced by the day of month, zero-padded.\n\
612 %D is a synonym for \"%m/%d/%y\".\n\
613 %e is replaced by the day of month, blank-padded.\n\
614 %h is a synonym for \"%b\".\n\
615 %H is replaced by the hour (00-23).\n\
616 %I is replaced by the hour (00-12).\n\
617 %j is replaced by the day of the year (001-366).\n\
618 %k is replaced by the hour (0-23), blank padded.\n\
619 %l is replaced by the hour (1-12), blank padded.\n\
620 %m is replaced by the month (01-12).\n\
621 %M is replaced by the minute (00-59).\n\
622 %n is a synonym for \"\\n\".\n\
623 %p is replaced by AM or PM, as appropriate.\n\
624 %r is a synonym for \"%I:%M:%S %p\".\n\
625 %R is a synonym for \"%H:%M\".\n\
626 %S is replaced by the second (00-60).\n\
627 %t is a synonym for \"\\t\".\n\
628 %T is a synonym for \"%H:%M:%S\".\n\
629 %U is replaced by the week of the year (00-53), first day of week is Sunday.\n\
630 %w is replaced by the day of week (0-6), Sunday is day 0.\n\
631 %W is replaced by the week of the year (00-53), first day of week is Monday.\n\
632 %x is a locale-specific synonym, which defaults to \"%D\" in the C locale.\n\
633 %X is a locale-specific synonym, which defaults to \"%T\" in the C locale.\n\
634 %y is replaced by the year without century (00-99).\n\
635 %Y is replaced by the year with century.\n\
636 %Z is replaced by the time zone abbreviation.\n\
637 \n\
638 The number of options reflects the `strftime' function.")
639 (format_string, time)
640 Lisp_Object format_string, time;
641 {
642 time_t value;
643 int size;
644
645 CHECK_STRING (format_string, 1);
646
647 if (! lisp_time_argument (time, &value))
648 error ("Invalid time specification");
649
650 /* This is probably enough. */
651 size = XSTRING (format_string)->size * 6 + 50;
652
653 while (1)
654 {
655 char *buf = (char *) alloca (size);
656 *buf = 1;
657 if (emacs_strftime (buf, size, XSTRING (format_string)->data,
658 localtime (&value))
659 || !*buf)
660 return build_string (buf);
661 /* If buffer was too small, make it bigger. */
662 size *= 2;
663 }
664 }
665
666 DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 1, 0,
667 "Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST ZONE).\n\
668 The optional SPECIFIED-TIME should be a list of (HIGH LOW . IGNORED)\n\
669 or (HIGH . LOW), as from `current-time' and `file-attributes', or `nil'\n\
670 to use the current time. The list has the following nine members:\n\
671 SEC is an integer between 0 and 60; SEC is 60 for a leap second, which\n\
672 only some operating systems support. MINUTE is an integer between 0 and 59.\n\
673 HOUR is an integer between 0 and 23. DAY is an integer between 1 and 31.\n\
674 MONTH is an integer between 1 and 12. YEAR is an integer indicating the\n\
675 four-digit year. DOW is the day of week, an integer between 0 and 6, where\n\
676 0 is Sunday. DST is t if daylight savings time is effect, otherwise nil.\n\
677 ZONE is an integer indicating the number of seconds east of Greenwich.\n\
678 \(Note that Common Lisp has different meanings for DOW and ZONE.)")
679 (specified_time)
680 Lisp_Object specified_time;
681 {
682 time_t time_spec;
683 struct tm save_tm;
684 struct tm *decoded_time;
685 Lisp_Object list_args[9];
686
687 if (! lisp_time_argument (specified_time, &time_spec))
688 error ("Invalid time specification");
689
690 decoded_time = localtime (&time_spec);
691 XSETFASTINT (list_args[0], decoded_time->tm_sec);
692 XSETFASTINT (list_args[1], decoded_time->tm_min);
693 XSETFASTINT (list_args[2], decoded_time->tm_hour);
694 XSETFASTINT (list_args[3], decoded_time->tm_mday);
695 XSETFASTINT (list_args[4], decoded_time->tm_mon + 1);
696 XSETFASTINT (list_args[5], decoded_time->tm_year + 1900);
697 XSETFASTINT (list_args[6], decoded_time->tm_wday);
698 list_args[7] = (decoded_time->tm_isdst)? Qt : Qnil;
699
700 /* Make a copy, in case gmtime modifies the struct. */
701 save_tm = *decoded_time;
702 decoded_time = gmtime (&time_spec);
703 if (decoded_time == 0)
704 list_args[8] = Qnil;
705 else
706 XSETINT (list_args[8], difftm (&save_tm, decoded_time));
707 return Flist (9, list_args);
708 }
709
710 DEFUN ("encode-time", Fencode_time, Sencode_time, 6, MANY, 0,
711 "Convert SECOND, MINUTE, HOUR, DAY, MONTH, YEAR and ZONE to internal time.\n\
712 This is the reverse operation of `decode-time', which see.\n\
713 ZONE defaults to the current time zone rule. This can\n\
714 be a string (as from `set-time-zone-rule'), or it can be a list\n\
715 (as from `current-time-zone') or an integer (as from `decode-time')\n\
716 applied without consideration for daylight savings time.\n\
717 \n\
718 You can pass more than 7 arguments; then the first six arguments\n\
719 are used as SECOND through YEAR, and the *last* argument is used as ZONE.\n\
720 The intervening arguments are ignored.\n\
721 This feature lets (apply 'encode-time (decode-time ...)) work.\n\
722 \n\
723 Out-of-range values for SEC, MINUTE, HOUR, DAY, or MONTH are allowed;\n\
724 for example, a DAY of 0 means the day preceding the given month.\n\
725 Year numbers less than 100 are treated just like other year numbers.\n\
726 If you want them to stand for years in this century, you must do that yourself.")
727 (nargs, args)
728 int nargs;
729 register Lisp_Object *args;
730 {
731 time_t time;
732 struct tm tm;
733 Lisp_Object zone = (nargs > 6)? args[nargs - 1] : Qnil;
734
735 CHECK_NUMBER (args[0], 0); /* second */
736 CHECK_NUMBER (args[1], 1); /* minute */
737 CHECK_NUMBER (args[2], 2); /* hour */
738 CHECK_NUMBER (args[3], 3); /* day */
739 CHECK_NUMBER (args[4], 4); /* month */
740 CHECK_NUMBER (args[5], 5); /* year */
741
742 tm.tm_sec = XINT (args[0]);
743 tm.tm_min = XINT (args[1]);
744 tm.tm_hour = XINT (args[2]);
745 tm.tm_mday = XINT (args[3]);
746 tm.tm_mon = XINT (args[4]) - 1;
747 tm.tm_year = XINT (args[5]) - 1900;
748 tm.tm_isdst = -1;
749
750 if (CONSP (zone))
751 zone = Fcar (zone);
752 if (NILP (zone))
753 time = mktime (&tm);
754 else
755 {
756 char tzbuf[100];
757 char *tzstring;
758 char **oldenv = environ, **newenv;
759
760 if (STRINGP (zone))
761 tzstring = (char *) XSTRING (zone)->data;
762 else if (INTEGERP (zone))
763 {
764 int abszone = abs (XINT (zone));
765 sprintf (tzbuf, "XXX%s%d:%02d:%02d", "-" + (XINT (zone) < 0),
766 abszone / (60*60), (abszone/60) % 60, abszone % 60);
767 tzstring = tzbuf;
768 }
769 else
770 error ("Invalid time zone specification");
771
772 /* Set TZ before calling mktime; merely adjusting mktime's returned
773 value doesn't suffice, since that would mishandle leap seconds. */
774 set_time_zone_rule (tzstring);
775
776 time = mktime (&tm);
777
778 /* Restore TZ to previous value. */
779 newenv = environ;
780 environ = oldenv;
781 free (newenv);
782 #ifdef LOCALTIME_CACHE
783 tzset ();
784 #endif
785 }
786
787 if (time == (time_t) -1)
788 error ("Specified time is not representable");
789
790 return make_time (time);
791 }
792
793 DEFUN ("current-time-string", Fcurrent_time_string, Scurrent_time_string, 0, 1, 0,
794 "Return the current time, as a human-readable string.\n\
795 Programs can use this function to decode a time,\n\
796 since the number of columns in each field is fixed.\n\
797 The format is `Sun Sep 16 01:03:52 1973'.\n\
798 If an argument is given, it specifies a time to format\n\
799 instead of the current time. The argument should have the form:\n\
800 (HIGH . LOW)\n\
801 or the form:\n\
802 (HIGH LOW . IGNORED).\n\
803 Thus, you can use times obtained from `current-time'\n\
804 and from `file-attributes'.")
805 (specified_time)
806 Lisp_Object specified_time;
807 {
808 time_t value;
809 char buf[30];
810 register char *tem;
811
812 if (! lisp_time_argument (specified_time, &value))
813 value = -1;
814 tem = (char *) ctime (&value);
815
816 strncpy (buf, tem, 24);
817 buf[24] = 0;
818
819 return build_string (buf);
820 }
821
822 #define TM_YEAR_ORIGIN 1900
823
824 /* Yield A - B, measured in seconds. */
825 static long
826 difftm (a, b)
827 struct tm *a, *b;
828 {
829 int ay = a->tm_year + (TM_YEAR_ORIGIN - 1);
830 int by = b->tm_year + (TM_YEAR_ORIGIN - 1);
831 /* Some compilers can't handle this as a single return statement. */
832 long days = (
833 /* difference in day of year */
834 a->tm_yday - b->tm_yday
835 /* + intervening leap days */
836 + ((ay >> 2) - (by >> 2))
837 - (ay/100 - by/100)
838 + ((ay/100 >> 2) - (by/100 >> 2))
839 /* + difference in years * 365 */
840 + (long)(ay-by) * 365
841 );
842 return (60*(60*(24*days + (a->tm_hour - b->tm_hour))
843 + (a->tm_min - b->tm_min))
844 + (a->tm_sec - b->tm_sec));
845 }
846
847 DEFUN ("current-time-zone", Fcurrent_time_zone, Scurrent_time_zone, 0, 1, 0,
848 "Return the offset and name for the local time zone.\n\
849 This returns a list of the form (OFFSET NAME).\n\
850 OFFSET is an integer number of seconds ahead of UTC (east of Greenwich).\n\
851 A negative value means west of Greenwich.\n\
852 NAME is a string giving the name of the time zone.\n\
853 If an argument is given, it specifies when the time zone offset is determined\n\
854 instead of using the current time. The argument should have the form:\n\
855 (HIGH . LOW)\n\
856 or the form:\n\
857 (HIGH LOW . IGNORED).\n\
858 Thus, you can use times obtained from `current-time'\n\
859 and from `file-attributes'.\n\
860 \n\
861 Some operating systems cannot provide all this information to Emacs;\n\
862 in this case, `current-time-zone' returns a list containing nil for\n\
863 the data it can't find.")
864 (specified_time)
865 Lisp_Object specified_time;
866 {
867 time_t value;
868 struct tm *t;
869
870 if (lisp_time_argument (specified_time, &value)
871 && (t = gmtime (&value)) != 0)
872 {
873 struct tm gmt;
874 long offset;
875 char *s, buf[6];
876
877 gmt = *t; /* Make a copy, in case localtime modifies *t. */
878 t = localtime (&value);
879 offset = difftm (t, &gmt);
880 s = 0;
881 #ifdef HAVE_TM_ZONE
882 if (t->tm_zone)
883 s = (char *)t->tm_zone;
884 #else /* not HAVE_TM_ZONE */
885 #ifdef HAVE_TZNAME
886 if (t->tm_isdst == 0 || t->tm_isdst == 1)
887 s = tzname[t->tm_isdst];
888 #endif
889 #endif /* not HAVE_TM_ZONE */
890 if (!s)
891 {
892 /* No local time zone name is available; use "+-NNNN" instead. */
893 int am = (offset < 0 ? -offset : offset) / 60;
894 sprintf (buf, "%c%02d%02d", (offset < 0 ? '-' : '+'), am/60, am%60);
895 s = buf;
896 }
897 return Fcons (make_number (offset), Fcons (build_string (s), Qnil));
898 }
899 else
900 return Fmake_list (2, Qnil);
901 }
902
903 /* This holds the value of `environ' produced by the previous
904 call to Fset_time_zone_rule, or 0 if Fset_time_zone_rule
905 has never been called. */
906 static char **environbuf;
907
908 DEFUN ("set-time-zone-rule", Fset_time_zone_rule, Sset_time_zone_rule, 1, 1, 0,
909 "Set the local time zone using TZ, a string specifying a time zone rule.\n\
910 If TZ is nil, use implementation-defined default time zone information.")
911 (tz)
912 Lisp_Object tz;
913 {
914 char *tzstring;
915
916 if (NILP (tz))
917 tzstring = 0;
918 else
919 {
920 CHECK_STRING (tz, 0);
921 tzstring = (char *) XSTRING (tz)->data;
922 }
923
924 set_time_zone_rule (tzstring);
925 if (environbuf)
926 free (environbuf);
927 environbuf = environ;
928
929 return Qnil;
930 }
931
932 /* Set the local time zone rule to TZSTRING.
933 This allocates memory into `environ', which it is the caller's
934 responsibility to free. */
935 void
936 set_time_zone_rule (tzstring)
937 char *tzstring;
938 {
939 int envptrs;
940 char **from, **to, **newenv;
941
942 for (from = environ; *from; from++)
943 continue;
944 envptrs = from - environ + 2;
945 newenv = to = (char **) xmalloc (envptrs * sizeof (char *)
946 + (tzstring ? strlen (tzstring) + 4 : 0));
947 if (tzstring)
948 {
949 char *t = (char *) (to + envptrs);
950 strcpy (t, "TZ=");
951 strcat (t, tzstring);
952 *to++ = t;
953 }
954
955 for (from = environ; *from; from++)
956 if (strncmp (*from, "TZ=", 3) != 0)
957 *to++ = *from;
958 *to = 0;
959
960 environ = newenv;
961
962 #ifdef LOCALTIME_CACHE
963 tzset ();
964 #endif
965 }
966 \f
967 void
968 insert1 (arg)
969 Lisp_Object arg;
970 {
971 Finsert (1, &arg);
972 }
973
974
975 /* Callers passing one argument to Finsert need not gcpro the
976 argument "array", since the only element of the array will
977 not be used after calling insert or insert_from_string, so
978 we don't care if it gets trashed. */
979
980 DEFUN ("insert", Finsert, Sinsert, 0, MANY, 0,
981 "Insert the arguments, either strings or characters, at point.\n\
982 Point moves forward so that it ends up after the inserted text.\n\
983 Any other markers at the point of insertion remain before the text.")
984 (nargs, args)
985 int nargs;
986 register Lisp_Object *args;
987 {
988 register int argnum;
989 register Lisp_Object tem;
990 char str[1];
991
992 for (argnum = 0; argnum < nargs; argnum++)
993 {
994 tem = args[argnum];
995 retry:
996 if (INTEGERP (tem))
997 {
998 str[0] = XINT (tem);
999 insert (str, 1);
1000 }
1001 else if (STRINGP (tem))
1002 {
1003 insert_from_string (tem, 0, XSTRING (tem)->size, 0);
1004 }
1005 else
1006 {
1007 tem = wrong_type_argument (Qchar_or_string_p, tem);
1008 goto retry;
1009 }
1010 }
1011
1012 return Qnil;
1013 }
1014
1015 DEFUN ("insert-and-inherit", Finsert_and_inherit, Sinsert_and_inherit,
1016 0, MANY, 0,
1017 "Insert the arguments at point, inheriting properties from adjoining text.\n\
1018 Point moves forward so that it ends up after the inserted text.\n\
1019 Any other markers at the point of insertion remain before the text.")
1020 (nargs, args)
1021 int nargs;
1022 register Lisp_Object *args;
1023 {
1024 register int argnum;
1025 register Lisp_Object tem;
1026 char str[1];
1027
1028 for (argnum = 0; argnum < nargs; argnum++)
1029 {
1030 tem = args[argnum];
1031 retry:
1032 if (INTEGERP (tem))
1033 {
1034 str[0] = XINT (tem);
1035 insert_and_inherit (str, 1);
1036 }
1037 else if (STRINGP (tem))
1038 {
1039 insert_from_string (tem, 0, XSTRING (tem)->size, 1);
1040 }
1041 else
1042 {
1043 tem = wrong_type_argument (Qchar_or_string_p, tem);
1044 goto retry;
1045 }
1046 }
1047
1048 return Qnil;
1049 }
1050
1051 DEFUN ("insert-before-markers", Finsert_before_markers, Sinsert_before_markers, 0, MANY, 0,
1052 "Insert strings or characters at point, relocating markers after the text.\n\
1053 Point moves forward so that it ends up after the inserted text.\n\
1054 Any other markers at the point of insertion also end up after the text.")
1055 (nargs, args)
1056 int nargs;
1057 register Lisp_Object *args;
1058 {
1059 register int argnum;
1060 register Lisp_Object tem;
1061 char str[1];
1062
1063 for (argnum = 0; argnum < nargs; argnum++)
1064 {
1065 tem = args[argnum];
1066 retry:
1067 if (INTEGERP (tem))
1068 {
1069 str[0] = XINT (tem);
1070 insert_before_markers (str, 1);
1071 }
1072 else if (STRINGP (tem))
1073 {
1074 insert_from_string_before_markers (tem, 0, XSTRING (tem)->size, 0);
1075 }
1076 else
1077 {
1078 tem = wrong_type_argument (Qchar_or_string_p, tem);
1079 goto retry;
1080 }
1081 }
1082
1083 return Qnil;
1084 }
1085
1086 DEFUN ("insert-before-markers-and-inherit",
1087 Finsert_and_inherit_before_markers, Sinsert_and_inherit_before_markers,
1088 0, MANY, 0,
1089 "Insert text at point, relocating markers and inheriting properties.\n\
1090 Point moves forward so that it ends up after the inserted text.\n\
1091 Any other markers at the point of insertion also end up after the text.")
1092 (nargs, args)
1093 int nargs;
1094 register Lisp_Object *args;
1095 {
1096 register int argnum;
1097 register Lisp_Object tem;
1098 char str[1];
1099
1100 for (argnum = 0; argnum < nargs; argnum++)
1101 {
1102 tem = args[argnum];
1103 retry:
1104 if (INTEGERP (tem))
1105 {
1106 str[0] = XINT (tem);
1107 insert_before_markers_and_inherit (str, 1);
1108 }
1109 else if (STRINGP (tem))
1110 {
1111 insert_from_string_before_markers (tem, 0, XSTRING (tem)->size, 1);
1112 }
1113 else
1114 {
1115 tem = wrong_type_argument (Qchar_or_string_p, tem);
1116 goto retry;
1117 }
1118 }
1119
1120 return Qnil;
1121 }
1122 \f
1123 DEFUN ("insert-char", Finsert_char, Sinsert_char, 2, 3, 0,
1124 "Insert COUNT (second arg) copies of CHARACTER (first arg).\n\
1125 Point and all markers are affected as in the function `insert'.\n\
1126 Both arguments are required.\n\
1127 The optional third arg INHERIT, if non-nil, says to inherit text properties\n\
1128 from adjoining text, if those properties are sticky.")
1129 (character, count, inherit)
1130 Lisp_Object character, count, inherit;
1131 {
1132 register unsigned char *string;
1133 register int strlen;
1134 register int i, n;
1135
1136 CHECK_NUMBER (character, 0);
1137 CHECK_NUMBER (count, 1);
1138
1139 n = XINT (count);
1140 if (n <= 0)
1141 return Qnil;
1142 strlen = min (n, 256);
1143 string = (unsigned char *) alloca (strlen);
1144 for (i = 0; i < strlen; i++)
1145 string[i] = XFASTINT (character);
1146 while (n >= strlen)
1147 {
1148 if (!NILP (inherit))
1149 insert_and_inherit (string, strlen);
1150 else
1151 insert (string, strlen);
1152 n -= strlen;
1153 }
1154 if (n > 0)
1155 {
1156 if (!NILP (inherit))
1157 insert_and_inherit (string, n);
1158 else
1159 insert (string, n);
1160 }
1161 return Qnil;
1162 }
1163
1164 \f
1165 /* Making strings from buffer contents. */
1166
1167 /* Return a Lisp_String containing the text of the current buffer from
1168 START to END. If text properties are in use and the current buffer
1169 has properties in the range specified, the resulting string will also
1170 have them, if PROPS is nonzero.
1171
1172 We don't want to use plain old make_string here, because it calls
1173 make_uninit_string, which can cause the buffer arena to be
1174 compacted. make_string has no way of knowing that the data has
1175 been moved, and thus copies the wrong data into the string. This
1176 doesn't effect most of the other users of make_string, so it should
1177 be left as is. But we should use this function when conjuring
1178 buffer substrings. */
1179
1180 Lisp_Object
1181 make_buffer_string (start, end, props)
1182 int start, end;
1183 int props;
1184 {
1185 Lisp_Object result, tem, tem1;
1186
1187 if (start < GPT && GPT < end)
1188 move_gap (start);
1189
1190 result = make_uninit_string (end - start);
1191 bcopy (&FETCH_CHAR (start), XSTRING (result)->data, end - start);
1192
1193 /* If desired, update and copy the text properties. */
1194 #ifdef USE_TEXT_PROPERTIES
1195 if (props)
1196 {
1197 update_buffer_properties (start, end);
1198
1199 tem = Fnext_property_change (make_number (start), Qnil, make_number (end));
1200 tem1 = Ftext_properties_at (make_number (start), Qnil);
1201
1202 if (XINT (tem) != end || !NILP (tem1))
1203 copy_intervals_to_string (result, current_buffer, start, end - start);
1204 }
1205 #endif
1206
1207 return result;
1208 }
1209
1210 /* Call Vbuffer_access_fontify_functions for the range START ... END
1211 in the current buffer, if necessary. */
1212
1213 static void
1214 update_buffer_properties (start, end)
1215 int start, end;
1216 {
1217 #ifdef USE_TEXT_PROPERTIES
1218 /* If this buffer has some access functions,
1219 call them, specifying the range of the buffer being accessed. */
1220 if (!NILP (Vbuffer_access_fontify_functions))
1221 {
1222 Lisp_Object args[3];
1223 Lisp_Object tem;
1224
1225 args[0] = Qbuffer_access_fontify_functions;
1226 XSETINT (args[1], start);
1227 XSETINT (args[2], end);
1228
1229 /* But don't call them if we can tell that the work
1230 has already been done. */
1231 if (!NILP (Vbuffer_access_fontified_property))
1232 {
1233 tem = Ftext_property_any (args[1], args[2],
1234 Vbuffer_access_fontified_property,
1235 Qnil, Qnil);
1236 if (! NILP (tem))
1237 Frun_hook_with_args (3, args);
1238 }
1239 else
1240 Frun_hook_with_args (3, args);
1241 }
1242 #endif
1243 }
1244
1245 DEFUN ("buffer-substring", Fbuffer_substring, Sbuffer_substring, 2, 2, 0,
1246 "Return the contents of part of the current buffer as a string.\n\
1247 The two arguments START and END are character positions;\n\
1248 they can be in either order.")
1249 (start, end)
1250 Lisp_Object start, end;
1251 {
1252 register int b, e;
1253
1254 validate_region (&start, &end);
1255 b = XINT (start);
1256 e = XINT (end);
1257
1258 return make_buffer_string (b, e, 1);
1259 }
1260
1261 DEFUN ("buffer-substring-no-properties", Fbuffer_substring_no_properties,
1262 Sbuffer_substring_no_properties, 2, 2, 0,
1263 "Return the characters of part of the buffer, without the text properties.\n\
1264 The two arguments START and END are character positions;\n\
1265 they can be in either order.")
1266 (start, end)
1267 Lisp_Object start, end;
1268 {
1269 register int b, e;
1270
1271 validate_region (&start, &end);
1272 b = XINT (start);
1273 e = XINT (end);
1274
1275 return make_buffer_string (b, e, 0);
1276 }
1277
1278 DEFUN ("buffer-string", Fbuffer_string, Sbuffer_string, 0, 0, 0,
1279 "Return the contents of the current buffer as a string.\n\
1280 If narrowing is in effect, this function returns only the visible part\n\
1281 of the buffer.")
1282 ()
1283 {
1284 return make_buffer_string (BEGV, ZV, 1);
1285 }
1286
1287 DEFUN ("insert-buffer-substring", Finsert_buffer_substring, Sinsert_buffer_substring,
1288 1, 3, 0,
1289 "Insert before point a substring of the contents of buffer BUFFER.\n\
1290 BUFFER may be a buffer or a buffer name.\n\
1291 Arguments START and END are character numbers specifying the substring.\n\
1292 They default to the beginning and the end of BUFFER.")
1293 (buf, start, end)
1294 Lisp_Object buf, start, end;
1295 {
1296 register int b, e, temp;
1297 register struct buffer *bp, *obuf;
1298 Lisp_Object buffer;
1299
1300 buffer = Fget_buffer (buf);
1301 if (NILP (buffer))
1302 nsberror (buf);
1303 bp = XBUFFER (buffer);
1304
1305 if (NILP (start))
1306 b = BUF_BEGV (bp);
1307 else
1308 {
1309 CHECK_NUMBER_COERCE_MARKER (start, 0);
1310 b = XINT (start);
1311 }
1312 if (NILP (end))
1313 e = BUF_ZV (bp);
1314 else
1315 {
1316 CHECK_NUMBER_COERCE_MARKER (end, 1);
1317 e = XINT (end);
1318 }
1319
1320 if (b > e)
1321 temp = b, b = e, e = temp;
1322
1323 if (!(BUF_BEGV (bp) <= b && e <= BUF_ZV (bp)))
1324 args_out_of_range (start, end);
1325
1326 obuf = current_buffer;
1327 set_buffer_internal_1 (bp);
1328 update_buffer_properties (b, e);
1329 set_buffer_internal_1 (obuf);
1330
1331 insert_from_buffer (bp, b, e - b, 0);
1332 return Qnil;
1333 }
1334
1335 DEFUN ("compare-buffer-substrings", Fcompare_buffer_substrings, Scompare_buffer_substrings,
1336 6, 6, 0,
1337 "Compare two substrings of two buffers; return result as number.\n\
1338 the value is -N if first string is less after N-1 chars,\n\
1339 +N if first string is greater after N-1 chars, or 0 if strings match.\n\
1340 Each substring is represented as three arguments: BUFFER, START and END.\n\
1341 That makes six args in all, three for each substring.\n\n\
1342 The value of `case-fold-search' in the current buffer\n\
1343 determines whether case is significant or ignored.")
1344 (buffer1, start1, end1, buffer2, start2, end2)
1345 Lisp_Object buffer1, start1, end1, buffer2, start2, end2;
1346 {
1347 register int begp1, endp1, begp2, endp2, temp, len1, len2, length, i;
1348 register struct buffer *bp1, *bp2;
1349 register Lisp_Object *trt
1350 = (!NILP (current_buffer->case_fold_search)
1351 ? XCHAR_TABLE (current_buffer->case_canon_table)->contents : 0);
1352
1353 /* Find the first buffer and its substring. */
1354
1355 if (NILP (buffer1))
1356 bp1 = current_buffer;
1357 else
1358 {
1359 Lisp_Object buf1;
1360 buf1 = Fget_buffer (buffer1);
1361 if (NILP (buf1))
1362 nsberror (buffer1);
1363 bp1 = XBUFFER (buf1);
1364 }
1365
1366 if (NILP (start1))
1367 begp1 = BUF_BEGV (bp1);
1368 else
1369 {
1370 CHECK_NUMBER_COERCE_MARKER (start1, 1);
1371 begp1 = XINT (start1);
1372 }
1373 if (NILP (end1))
1374 endp1 = BUF_ZV (bp1);
1375 else
1376 {
1377 CHECK_NUMBER_COERCE_MARKER (end1, 2);
1378 endp1 = XINT (end1);
1379 }
1380
1381 if (begp1 > endp1)
1382 temp = begp1, begp1 = endp1, endp1 = temp;
1383
1384 if (!(BUF_BEGV (bp1) <= begp1
1385 && begp1 <= endp1
1386 && endp1 <= BUF_ZV (bp1)))
1387 args_out_of_range (start1, end1);
1388
1389 /* Likewise for second substring. */
1390
1391 if (NILP (buffer2))
1392 bp2 = current_buffer;
1393 else
1394 {
1395 Lisp_Object buf2;
1396 buf2 = Fget_buffer (buffer2);
1397 if (NILP (buf2))
1398 nsberror (buffer2);
1399 bp2 = XBUFFER (buf2);
1400 }
1401
1402 if (NILP (start2))
1403 begp2 = BUF_BEGV (bp2);
1404 else
1405 {
1406 CHECK_NUMBER_COERCE_MARKER (start2, 4);
1407 begp2 = XINT (start2);
1408 }
1409 if (NILP (end2))
1410 endp2 = BUF_ZV (bp2);
1411 else
1412 {
1413 CHECK_NUMBER_COERCE_MARKER (end2, 5);
1414 endp2 = XINT (end2);
1415 }
1416
1417 if (begp2 > endp2)
1418 temp = begp2, begp2 = endp2, endp2 = temp;
1419
1420 if (!(BUF_BEGV (bp2) <= begp2
1421 && begp2 <= endp2
1422 && endp2 <= BUF_ZV (bp2)))
1423 args_out_of_range (start2, end2);
1424
1425 len1 = endp1 - begp1;
1426 len2 = endp2 - begp2;
1427 length = len1;
1428 if (len2 < length)
1429 length = len2;
1430
1431 for (i = 0; i < length; i++)
1432 {
1433 int c1 = *BUF_CHAR_ADDRESS (bp1, begp1 + i);
1434 int c2 = *BUF_CHAR_ADDRESS (bp2, begp2 + i);
1435 if (trt)
1436 {
1437 c1 = trt[c1];
1438 c2 = trt[c2];
1439 }
1440 if (c1 < c2)
1441 return make_number (- 1 - i);
1442 if (c1 > c2)
1443 return make_number (i + 1);
1444 }
1445
1446 /* The strings match as far as they go.
1447 If one is shorter, that one is less. */
1448 if (length < len1)
1449 return make_number (length + 1);
1450 else if (length < len2)
1451 return make_number (- length - 1);
1452
1453 /* Same length too => they are equal. */
1454 return make_number (0);
1455 }
1456 \f
1457 static Lisp_Object
1458 subst_char_in_region_unwind (arg)
1459 Lisp_Object arg;
1460 {
1461 return current_buffer->undo_list = arg;
1462 }
1463
1464 static Lisp_Object
1465 subst_char_in_region_unwind_1 (arg)
1466 Lisp_Object arg;
1467 {
1468 return current_buffer->filename = arg;
1469 }
1470
1471 DEFUN ("subst-char-in-region", Fsubst_char_in_region,
1472 Ssubst_char_in_region, 4, 5, 0,
1473 "From START to END, replace FROMCHAR with TOCHAR each time it occurs.\n\
1474 If optional arg NOUNDO is non-nil, don't record this change for undo\n\
1475 and don't mark the buffer as really changed.")
1476 (start, end, fromchar, tochar, noundo)
1477 Lisp_Object start, end, fromchar, tochar, noundo;
1478 {
1479 register int pos, stop, look;
1480 int changed = 0;
1481 int count = specpdl_ptr - specpdl;
1482
1483 validate_region (&start, &end);
1484 CHECK_NUMBER (fromchar, 2);
1485 CHECK_NUMBER (tochar, 3);
1486
1487 pos = XINT (start);
1488 stop = XINT (end);
1489 look = XINT (fromchar);
1490
1491 /* If we don't want undo, turn off putting stuff on the list.
1492 That's faster than getting rid of things,
1493 and it prevents even the entry for a first change.
1494 Also inhibit locking the file. */
1495 if (!NILP (noundo))
1496 {
1497 record_unwind_protect (subst_char_in_region_unwind,
1498 current_buffer->undo_list);
1499 current_buffer->undo_list = Qt;
1500 /* Don't do file-locking. */
1501 record_unwind_protect (subst_char_in_region_unwind_1,
1502 current_buffer->filename);
1503 current_buffer->filename = Qnil;
1504 }
1505
1506 while (pos < stop)
1507 {
1508 if (FETCH_CHAR (pos) == look)
1509 {
1510 if (! changed)
1511 {
1512 modify_region (current_buffer, XINT (start), stop);
1513
1514 if (! NILP (noundo))
1515 {
1516 if (MODIFF - 1 == SAVE_MODIFF)
1517 SAVE_MODIFF++;
1518 if (MODIFF - 1 == current_buffer->auto_save_modified)
1519 current_buffer->auto_save_modified++;
1520 }
1521
1522 changed = 1;
1523 }
1524
1525 if (NILP (noundo))
1526 record_change (pos, 1);
1527 FETCH_CHAR (pos) = XINT (tochar);
1528 }
1529 pos++;
1530 }
1531
1532 if (changed)
1533 signal_after_change (XINT (start),
1534 stop - XINT (start), stop - XINT (start));
1535
1536 unbind_to (count, Qnil);
1537 return Qnil;
1538 }
1539
1540 DEFUN ("translate-region", Ftranslate_region, Stranslate_region, 3, 3, 0,
1541 "From START to END, translate characters according to TABLE.\n\
1542 TABLE is a string; the Nth character in it is the mapping\n\
1543 for the character with code N. Returns the number of characters changed.")
1544 (start, end, table)
1545 Lisp_Object start;
1546 Lisp_Object end;
1547 register Lisp_Object table;
1548 {
1549 register int pos, stop; /* Limits of the region. */
1550 register unsigned char *tt; /* Trans table. */
1551 register int oc; /* Old character. */
1552 register int nc; /* New character. */
1553 int cnt; /* Number of changes made. */
1554 Lisp_Object z; /* Return. */
1555 int size; /* Size of translate table. */
1556
1557 validate_region (&start, &end);
1558 CHECK_STRING (table, 2);
1559
1560 size = XSTRING (table)->size;
1561 tt = XSTRING (table)->data;
1562
1563 pos = XINT (start);
1564 stop = XINT (end);
1565 modify_region (current_buffer, pos, stop);
1566
1567 cnt = 0;
1568 for (; pos < stop; ++pos)
1569 {
1570 oc = FETCH_CHAR (pos);
1571 if (oc < size)
1572 {
1573 nc = tt[oc];
1574 if (nc != oc)
1575 {
1576 record_change (pos, 1);
1577 FETCH_CHAR (pos) = nc;
1578 signal_after_change (pos, 1, 1);
1579 ++cnt;
1580 }
1581 }
1582 }
1583
1584 XSETFASTINT (z, cnt);
1585 return (z);
1586 }
1587
1588 DEFUN ("delete-region", Fdelete_region, Sdelete_region, 2, 2, "r",
1589 "Delete the text between point and mark.\n\
1590 When called from a program, expects two arguments,\n\
1591 positions (integers or markers) specifying the stretch to be deleted.")
1592 (start, end)
1593 Lisp_Object start, end;
1594 {
1595 validate_region (&start, &end);
1596 del_range (XINT (start), XINT (end));
1597 return Qnil;
1598 }
1599 \f
1600 DEFUN ("widen", Fwiden, Swiden, 0, 0, "",
1601 "Remove restrictions (narrowing) from current buffer.\n\
1602 This allows the buffer's full text to be seen and edited.")
1603 ()
1604 {
1605 BEGV = BEG;
1606 SET_BUF_ZV (current_buffer, Z);
1607 current_buffer->clip_changed = 1;
1608 /* Changing the buffer bounds invalidates any recorded current column. */
1609 invalidate_current_column ();
1610 return Qnil;
1611 }
1612
1613 DEFUN ("narrow-to-region", Fnarrow_to_region, Snarrow_to_region, 2, 2, "r",
1614 "Restrict editing in this buffer to the current region.\n\
1615 The rest of the text becomes temporarily invisible and untouchable\n\
1616 but is not deleted; if you save the buffer in a file, the invisible\n\
1617 text is included in the file. \\[widen] makes all visible again.\n\
1618 See also `save-restriction'.\n\
1619 \n\
1620 When calling from a program, pass two arguments; positions (integers\n\
1621 or markers) bounding the text that should remain visible.")
1622 (start, end)
1623 register Lisp_Object start, end;
1624 {
1625 CHECK_NUMBER_COERCE_MARKER (start, 0);
1626 CHECK_NUMBER_COERCE_MARKER (end, 1);
1627
1628 if (XINT (start) > XINT (end))
1629 {
1630 Lisp_Object tem;
1631 tem = start; start = end; end = tem;
1632 }
1633
1634 if (!(BEG <= XINT (start) && XINT (start) <= XINT (end) && XINT (end) <= Z))
1635 args_out_of_range (start, end);
1636
1637 BEGV = XFASTINT (start);
1638 SET_BUF_ZV (current_buffer, XFASTINT (end));
1639 if (point < XFASTINT (start))
1640 SET_PT (XFASTINT (start));
1641 if (point > XFASTINT (end))
1642 SET_PT (XFASTINT (end));
1643 current_buffer->clip_changed = 1;
1644 /* Changing the buffer bounds invalidates any recorded current column. */
1645 invalidate_current_column ();
1646 return Qnil;
1647 }
1648
1649 Lisp_Object
1650 save_restriction_save ()
1651 {
1652 register Lisp_Object bottom, top;
1653 /* Note: I tried using markers here, but it does not win
1654 because insertion at the end of the saved region
1655 does not advance mh and is considered "outside" the saved region. */
1656 XSETFASTINT (bottom, BEGV - BEG);
1657 XSETFASTINT (top, Z - ZV);
1658
1659 return Fcons (Fcurrent_buffer (), Fcons (bottom, top));
1660 }
1661
1662 Lisp_Object
1663 save_restriction_restore (data)
1664 Lisp_Object data;
1665 {
1666 register struct buffer *buf;
1667 register int newhead, newtail;
1668 register Lisp_Object tem;
1669
1670 buf = XBUFFER (XCONS (data)->car);
1671
1672 data = XCONS (data)->cdr;
1673
1674 tem = XCONS (data)->car;
1675 newhead = XINT (tem);
1676 tem = XCONS (data)->cdr;
1677 newtail = XINT (tem);
1678 if (newhead + newtail > BUF_Z (buf) - BUF_BEG (buf))
1679 {
1680 newhead = 0;
1681 newtail = 0;
1682 }
1683 BUF_BEGV (buf) = BUF_BEG (buf) + newhead;
1684 SET_BUF_ZV (buf, BUF_Z (buf) - newtail);
1685 current_buffer->clip_changed = 1;
1686
1687 /* If point is outside the new visible range, move it inside. */
1688 SET_BUF_PT (buf,
1689 clip_to_bounds (BUF_BEGV (buf), BUF_PT (buf), BUF_ZV (buf)));
1690
1691 return Qnil;
1692 }
1693
1694 DEFUN ("save-restriction", Fsave_restriction, Ssave_restriction, 0, UNEVALLED, 0,
1695 "Execute BODY, saving and restoring current buffer's restrictions.\n\
1696 The buffer's restrictions make parts of the beginning and end invisible.\n\
1697 \(They are set up with `narrow-to-region' and eliminated with `widen'.)\n\
1698 This special form, `save-restriction', saves the current buffer's restrictions\n\
1699 when it is entered, and restores them when it is exited.\n\
1700 So any `narrow-to-region' within BODY lasts only until the end of the form.\n\
1701 The old restrictions settings are restored\n\
1702 even in case of abnormal exit (throw or error).\n\
1703 \n\
1704 The value returned is the value of the last form in BODY.\n\
1705 \n\
1706 `save-restriction' can get confused if, within the BODY, you widen\n\
1707 and then make changes outside the area within the saved restrictions.\n\
1708 \n\
1709 Note: if you are using both `save-excursion' and `save-restriction',\n\
1710 use `save-excursion' outermost:\n\
1711 (save-excursion (save-restriction ...))")
1712 (body)
1713 Lisp_Object body;
1714 {
1715 register Lisp_Object val;
1716 int count = specpdl_ptr - specpdl;
1717
1718 record_unwind_protect (save_restriction_restore, save_restriction_save ());
1719 val = Fprogn (body);
1720 return unbind_to (count, val);
1721 }
1722 \f
1723 /* Buffer for the most recent text displayed by Fmessage. */
1724 static char *message_text;
1725
1726 /* Allocated length of that buffer. */
1727 static int message_length;
1728
1729 DEFUN ("message", Fmessage, Smessage, 1, MANY, 0,
1730 "Print a one-line message at the bottom of the screen.\n\
1731 The first argument is a format control string, and the rest are data\n\
1732 to be formatted under control of the string. See `format' for details.\n\
1733 \n\
1734 If the first argument is nil, clear any existing message; let the\n\
1735 minibuffer contents show.")
1736 (nargs, args)
1737 int nargs;
1738 Lisp_Object *args;
1739 {
1740 if (NILP (args[0]))
1741 {
1742 message (0);
1743 return Qnil;
1744 }
1745 else
1746 {
1747 register Lisp_Object val;
1748 val = Fformat (nargs, args);
1749 /* Copy the data so that it won't move when we GC. */
1750 if (! message_text)
1751 {
1752 message_text = (char *)xmalloc (80);
1753 message_length = 80;
1754 }
1755 if (XSTRING (val)->size > message_length)
1756 {
1757 message_length = XSTRING (val)->size;
1758 message_text = (char *)xrealloc (message_text, message_length);
1759 }
1760 bcopy (XSTRING (val)->data, message_text, XSTRING (val)->size);
1761 message2 (message_text, XSTRING (val)->size);
1762 return val;
1763 }
1764 }
1765
1766 DEFUN ("message-box", Fmessage_box, Smessage_box, 1, MANY, 0,
1767 "Display a message, in a dialog box if possible.\n\
1768 If a dialog box is not available, use the echo area.\n\
1769 The first argument is a format control string, and the rest are data\n\
1770 to be formatted under control of the string. See `format' for details.\n\
1771 \n\
1772 If the first argument is nil, clear any existing message; let the\n\
1773 minibuffer contents show.")
1774 (nargs, args)
1775 int nargs;
1776 Lisp_Object *args;
1777 {
1778 if (NILP (args[0]))
1779 {
1780 message (0);
1781 return Qnil;
1782 }
1783 else
1784 {
1785 register Lisp_Object val;
1786 val = Fformat (nargs, args);
1787 #ifdef HAVE_MENUS
1788 {
1789 Lisp_Object pane, menu, obj;
1790 struct gcpro gcpro1;
1791 pane = Fcons (Fcons (build_string ("OK"), Qt), Qnil);
1792 GCPRO1 (pane);
1793 menu = Fcons (val, pane);
1794 obj = Fx_popup_dialog (Qt, menu);
1795 UNGCPRO;
1796 return val;
1797 }
1798 #else /* not HAVE_MENUS */
1799 /* Copy the data so that it won't move when we GC. */
1800 if (! message_text)
1801 {
1802 message_text = (char *)xmalloc (80);
1803 message_length = 80;
1804 }
1805 if (XSTRING (val)->size > message_length)
1806 {
1807 message_length = XSTRING (val)->size;
1808 message_text = (char *)xrealloc (message_text, message_length);
1809 }
1810 bcopy (XSTRING (val)->data, message_text, XSTRING (val)->size);
1811 message2 (message_text, XSTRING (val)->size);
1812 return val;
1813 #endif /* not HAVE_MENUS */
1814 }
1815 }
1816 #ifdef HAVE_MENUS
1817 extern Lisp_Object last_nonmenu_event;
1818 #endif
1819
1820 DEFUN ("message-or-box", Fmessage_or_box, Smessage_or_box, 1, MANY, 0,
1821 "Display a message in a dialog box or in the echo area.\n\
1822 If this command was invoked with the mouse, use a dialog box.\n\
1823 Otherwise, use the echo area.\n\
1824 The first argument is a format control string, and the rest are data\n\
1825 to be formatted under control of the string. See `format' for details.\n\
1826 \n\
1827 If the first argument is nil, clear any existing message; let the\n\
1828 minibuffer contents show.")
1829 (nargs, args)
1830 int nargs;
1831 Lisp_Object *args;
1832 {
1833 #ifdef HAVE_MENUS
1834 if (NILP (last_nonmenu_event) || CONSP (last_nonmenu_event))
1835 return Fmessage_box (nargs, args);
1836 #endif
1837 return Fmessage (nargs, args);
1838 }
1839
1840 DEFUN ("format", Fformat, Sformat, 1, MANY, 0,
1841 "Format a string out of a control-string and arguments.\n\
1842 The first argument is a control string.\n\
1843 The other arguments are substituted into it to make the result, a string.\n\
1844 It may contain %-sequences meaning to substitute the next argument.\n\
1845 %s means print a string argument. Actually, prints any object, with `princ'.\n\
1846 %d means print as number in decimal (%o octal, %x hex).\n\
1847 %e means print a number in exponential notation.\n\
1848 %f means print a number in decimal-point notation.\n\
1849 %g means print a number in exponential notation\n\
1850 or decimal-point notation, whichever uses fewer characters.\n\
1851 %c means print a number as a single character.\n\
1852 %S means print any object as an s-expression (using prin1).\n\
1853 The argument used for %d, %o, %x, %e, %f, %g or %c must be a number.\n\
1854 Use %% to put a single % into the output.")
1855 (nargs, args)
1856 int nargs;
1857 register Lisp_Object *args;
1858 {
1859 register int n; /* The number of the next arg to substitute */
1860 register int total = 5; /* An estimate of the final length */
1861 char *buf;
1862 register unsigned char *format, *end;
1863 int length;
1864 extern char *index ();
1865 /* It should not be necessary to GCPRO ARGS, because
1866 the caller in the interpreter should take care of that. */
1867
1868 CHECK_STRING (args[0], 0);
1869 format = XSTRING (args[0])->data;
1870 end = format + XSTRING (args[0])->size;
1871
1872 n = 0;
1873 while (format != end)
1874 if (*format++ == '%')
1875 {
1876 int minlen;
1877
1878 /* Process a numeric arg and skip it. */
1879 minlen = atoi (format);
1880 if (minlen < 0)
1881 minlen = - minlen;
1882
1883 while ((*format >= '0' && *format <= '9')
1884 || *format == '-' || *format == ' ' || *format == '.')
1885 format++;
1886
1887 if (*format == '%')
1888 format++;
1889 else if (++n >= nargs)
1890 error ("Not enough arguments for format string");
1891 else if (*format == 'S')
1892 {
1893 /* For `S', prin1 the argument and then treat like a string. */
1894 register Lisp_Object tem;
1895 tem = Fprin1_to_string (args[n], Qnil);
1896 args[n] = tem;
1897 goto string;
1898 }
1899 else if (SYMBOLP (args[n]))
1900 {
1901 XSETSTRING (args[n], XSYMBOL (args[n])->name);
1902 goto string;
1903 }
1904 else if (STRINGP (args[n]))
1905 {
1906 string:
1907 if (*format != 's' && *format != 'S')
1908 error ("format specifier doesn't match argument type");
1909 total += XSTRING (args[n])->size;
1910 /* We have to put an arbitrary limit on minlen
1911 since otherwise it could make alloca fail. */
1912 if (minlen < XSTRING (args[n])->size + 1000)
1913 total += minlen;
1914 }
1915 /* Would get MPV otherwise, since Lisp_Int's `point' to low memory. */
1916 else if (INTEGERP (args[n]) && *format != 's')
1917 {
1918 #ifdef LISP_FLOAT_TYPE
1919 /* The following loop assumes the Lisp type indicates
1920 the proper way to pass the argument.
1921 So make sure we have a flonum if the argument should
1922 be a double. */
1923 if (*format == 'e' || *format == 'f' || *format == 'g')
1924 args[n] = Ffloat (args[n]);
1925 #endif
1926 total += 30;
1927 /* We have to put an arbitrary limit on minlen
1928 since otherwise it could make alloca fail. */
1929 if (minlen < 1000)
1930 total += minlen;
1931 }
1932 #ifdef LISP_FLOAT_TYPE
1933 else if (FLOATP (args[n]) && *format != 's')
1934 {
1935 if (! (*format == 'e' || *format == 'f' || *format == 'g'))
1936 args[n] = Ftruncate (args[n]);
1937 total += 30;
1938 /* We have to put an arbitrary limit on minlen
1939 since otherwise it could make alloca fail. */
1940 if (minlen < 1000)
1941 total += minlen;
1942 }
1943 #endif
1944 else
1945 {
1946 /* Anything but a string, convert to a string using princ. */
1947 register Lisp_Object tem;
1948 tem = Fprin1_to_string (args[n], Qt);
1949 args[n] = tem;
1950 goto string;
1951 }
1952 }
1953
1954 {
1955 register int nstrings = n + 1;
1956
1957 /* Allocate twice as many strings as we have %-escapes; floats occupy
1958 two slots, and we're not sure how many of those we have. */
1959 register unsigned char **strings
1960 = (unsigned char **) alloca (2 * nstrings * sizeof (unsigned char *));
1961 int i;
1962
1963 i = 0;
1964 for (n = 0; n < nstrings; n++)
1965 {
1966 if (n >= nargs)
1967 strings[i++] = (unsigned char *) "";
1968 else if (INTEGERP (args[n]))
1969 /* We checked above that the corresponding format effector
1970 isn't %s, which would cause MPV. */
1971 strings[i++] = (unsigned char *) XINT (args[n]);
1972 #ifdef LISP_FLOAT_TYPE
1973 else if (FLOATP (args[n]))
1974 {
1975 union { double d; char *half[2]; } u;
1976
1977 u.d = XFLOAT (args[n])->data;
1978 strings[i++] = (unsigned char *) u.half[0];
1979 strings[i++] = (unsigned char *) u.half[1];
1980 }
1981 #endif
1982 else if (i == 0)
1983 /* The first string is treated differently
1984 because it is the format string. */
1985 strings[i++] = XSTRING (args[n])->data;
1986 else
1987 strings[i++] = (unsigned char *) XFASTINT (args[n]);
1988 }
1989
1990 /* Make room in result for all the non-%-codes in the control string. */
1991 total += XSTRING (args[0])->size;
1992
1993 /* Format it in bigger and bigger buf's until it all fits. */
1994 while (1)
1995 {
1996 buf = (char *) alloca (total + 1);
1997 buf[total - 1] = 0;
1998
1999 length = doprnt_lisp (buf, total + 1, strings[0],
2000 end, i-1, strings + 1);
2001 if (buf[total - 1] == 0)
2002 break;
2003
2004 total *= 2;
2005 }
2006 }
2007
2008 /* UNGCPRO; */
2009 return make_string (buf, length);
2010 }
2011
2012 /* VARARGS 1 */
2013 Lisp_Object
2014 #ifdef NO_ARG_ARRAY
2015 format1 (string1, arg0, arg1, arg2, arg3, arg4)
2016 EMACS_INT arg0, arg1, arg2, arg3, arg4;
2017 #else
2018 format1 (string1)
2019 #endif
2020 char *string1;
2021 {
2022 char buf[100];
2023 #ifdef NO_ARG_ARRAY
2024 EMACS_INT args[5];
2025 args[0] = arg0;
2026 args[1] = arg1;
2027 args[2] = arg2;
2028 args[3] = arg3;
2029 args[4] = arg4;
2030 doprnt (buf, sizeof buf, string1, (char *)0, 5, args);
2031 #else
2032 doprnt (buf, sizeof buf, string1, (char *)0, 5, &string1 + 1);
2033 #endif
2034 return build_string (buf);
2035 }
2036 \f
2037 DEFUN ("char-equal", Fchar_equal, Schar_equal, 2, 2, 0,
2038 "Return t if two characters match, optionally ignoring case.\n\
2039 Both arguments must be characters (i.e. integers).\n\
2040 Case is ignored if `case-fold-search' is non-nil in the current buffer.")
2041 (c1, c2)
2042 register Lisp_Object c1, c2;
2043 {
2044 Lisp_Object *downcase = DOWNCASE_TABLE;
2045 CHECK_NUMBER (c1, 0);
2046 CHECK_NUMBER (c2, 1);
2047
2048 if (!NILP (current_buffer->case_fold_search)
2049 ? ((XINT (downcase[0xff & XFASTINT (c1)])
2050 == XINT (downcase[0xff & XFASTINT (c2)]))
2051 && (XFASTINT (c1) & ~0xff) == (XFASTINT (c2) & ~0xff))
2052 : XINT (c1) == XINT (c2))
2053 return Qt;
2054 return Qnil;
2055 }
2056 \f
2057 /* Transpose the markers in two regions of the current buffer, and
2058 adjust the ones between them if necessary (i.e.: if the regions
2059 differ in size).
2060
2061 Traverses the entire marker list of the buffer to do so, adding an
2062 appropriate amount to some, subtracting from some, and leaving the
2063 rest untouched. Most of this is copied from adjust_markers in insdel.c.
2064
2065 It's the caller's job to see that (start1 <= end1 <= start2 <= end2). */
2066
2067 void
2068 transpose_markers (start1, end1, start2, end2)
2069 register int start1, end1, start2, end2;
2070 {
2071 register int amt1, amt2, diff, mpos;
2072 register Lisp_Object marker;
2073
2074 /* Update point as if it were a marker. */
2075 if (PT < start1)
2076 ;
2077 else if (PT < end1)
2078 TEMP_SET_PT (PT + (end2 - end1));
2079 else if (PT < start2)
2080 TEMP_SET_PT (PT + (end2 - start2) - (end1 - start1));
2081 else if (PT < end2)
2082 TEMP_SET_PT (PT - (start2 - start1));
2083
2084 /* We used to adjust the endpoints here to account for the gap, but that
2085 isn't good enough. Even if we assume the caller has tried to move the
2086 gap out of our way, it might still be at start1 exactly, for example;
2087 and that places it `inside' the interval, for our purposes. The amount
2088 of adjustment is nontrivial if there's a `denormalized' marker whose
2089 position is between GPT and GPT + GAP_SIZE, so it's simpler to leave
2090 the dirty work to Fmarker_position, below. */
2091
2092 /* The difference between the region's lengths */
2093 diff = (end2 - start2) - (end1 - start1);
2094
2095 /* For shifting each marker in a region by the length of the other
2096 * region plus the distance between the regions.
2097 */
2098 amt1 = (end2 - start2) + (start2 - end1);
2099 amt2 = (end1 - start1) + (start2 - end1);
2100
2101 for (marker = BUF_MARKERS (current_buffer); !NILP (marker);
2102 marker = XMARKER (marker)->chain)
2103 {
2104 mpos = Fmarker_position (marker);
2105 if (mpos >= start1 && mpos < end2)
2106 {
2107 if (mpos < end1)
2108 mpos += amt1;
2109 else if (mpos < start2)
2110 mpos += diff;
2111 else
2112 mpos -= amt2;
2113 if (mpos > GPT) mpos += GAP_SIZE;
2114 XMARKER (marker)->bufpos = mpos;
2115 }
2116 }
2117 }
2118
2119 DEFUN ("transpose-regions", Ftranspose_regions, Stranspose_regions, 4, 5, 0,
2120 "Transpose region START1 to END1 with START2 to END2.\n\
2121 The regions may not be overlapping, because the size of the buffer is\n\
2122 never changed in a transposition.\n\
2123 \n\
2124 Optional fifth arg LEAVE_MARKERS, if non-nil, means don't transpose\n\
2125 any markers that happen to be located in the regions.\n\
2126 \n\
2127 Transposing beyond buffer boundaries is an error.")
2128 (startr1, endr1, startr2, endr2, leave_markers)
2129 Lisp_Object startr1, endr1, startr2, endr2, leave_markers;
2130 {
2131 register int start1, end1, start2, end2,
2132 gap, len1, len_mid, len2;
2133 unsigned char *start1_addr, *start2_addr, *temp;
2134
2135 #ifdef USE_TEXT_PROPERTIES
2136 INTERVAL cur_intv, tmp_interval1, tmp_interval_mid, tmp_interval2;
2137 cur_intv = BUF_INTERVALS (current_buffer);
2138 #endif /* USE_TEXT_PROPERTIES */
2139
2140 validate_region (&startr1, &endr1);
2141 validate_region (&startr2, &endr2);
2142
2143 start1 = XFASTINT (startr1);
2144 end1 = XFASTINT (endr1);
2145 start2 = XFASTINT (startr2);
2146 end2 = XFASTINT (endr2);
2147 gap = GPT;
2148
2149 /* Swap the regions if they're reversed. */
2150 if (start2 < end1)
2151 {
2152 register int glumph = start1;
2153 start1 = start2;
2154 start2 = glumph;
2155 glumph = end1;
2156 end1 = end2;
2157 end2 = glumph;
2158 }
2159
2160 len1 = end1 - start1;
2161 len2 = end2 - start2;
2162
2163 if (start2 < end1)
2164 error ("transposed regions not properly ordered");
2165 else if (start1 == end1 || start2 == end2)
2166 error ("transposed region may not be of length 0");
2167
2168 /* The possibilities are:
2169 1. Adjacent (contiguous) regions, or separate but equal regions
2170 (no, really equal, in this case!), or
2171 2. Separate regions of unequal size.
2172
2173 The worst case is usually No. 2. It means that (aside from
2174 potential need for getting the gap out of the way), there also
2175 needs to be a shifting of the text between the two regions. So
2176 if they are spread far apart, we are that much slower... sigh. */
2177
2178 /* It must be pointed out that the really studly thing to do would
2179 be not to move the gap at all, but to leave it in place and work
2180 around it if necessary. This would be extremely efficient,
2181 especially considering that people are likely to do
2182 transpositions near where they are working interactively, which
2183 is exactly where the gap would be found. However, such code
2184 would be much harder to write and to read. So, if you are
2185 reading this comment and are feeling squirrely, by all means have
2186 a go! I just didn't feel like doing it, so I will simply move
2187 the gap the minimum distance to get it out of the way, and then
2188 deal with an unbroken array. */
2189
2190 /* Make sure the gap won't interfere, by moving it out of the text
2191 we will operate on. */
2192 if (start1 < gap && gap < end2)
2193 {
2194 if (gap - start1 < end2 - gap)
2195 move_gap (start1);
2196 else
2197 move_gap (end2);
2198 }
2199
2200 /* Hmmm... how about checking to see if the gap is large
2201 enough to use as the temporary storage? That would avoid an
2202 allocation... interesting. Later, don't fool with it now. */
2203
2204 /* Working without memmove, for portability (sigh), so must be
2205 careful of overlapping subsections of the array... */
2206
2207 if (end1 == start2) /* adjacent regions */
2208 {
2209 modify_region (current_buffer, start1, end2);
2210 record_change (start1, len1 + len2);
2211
2212 #ifdef USE_TEXT_PROPERTIES
2213 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
2214 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
2215 Fset_text_properties (start1, end2, Qnil, Qnil);
2216 #endif /* USE_TEXT_PROPERTIES */
2217
2218 /* First region smaller than second. */
2219 if (len1 < len2)
2220 {
2221 /* We use alloca only if it is small,
2222 because we want to avoid stack overflow. */
2223 if (len2 > 20000)
2224 temp = (unsigned char *) xmalloc (len2);
2225 else
2226 temp = (unsigned char *) alloca (len2);
2227
2228 /* Don't precompute these addresses. We have to compute them
2229 at the last minute, because the relocating allocator might
2230 have moved the buffer around during the xmalloc. */
2231 start1_addr = BUF_CHAR_ADDRESS (current_buffer, start1);
2232 start2_addr = BUF_CHAR_ADDRESS (current_buffer, start2);
2233
2234 bcopy (start2_addr, temp, len2);
2235 bcopy (start1_addr, start1_addr + len2, len1);
2236 bcopy (temp, start1_addr, len2);
2237 if (len2 > 20000)
2238 free (temp);
2239 }
2240 else
2241 /* First region not smaller than second. */
2242 {
2243 if (len1 > 20000)
2244 temp = (unsigned char *) xmalloc (len1);
2245 else
2246 temp = (unsigned char *) alloca (len1);
2247 start1_addr = BUF_CHAR_ADDRESS (current_buffer, start1);
2248 start2_addr = BUF_CHAR_ADDRESS (current_buffer, start2);
2249 bcopy (start1_addr, temp, len1);
2250 bcopy (start2_addr, start1_addr, len2);
2251 bcopy (temp, start1_addr + len2, len1);
2252 if (len1 > 20000)
2253 free (temp);
2254 }
2255 #ifdef USE_TEXT_PROPERTIES
2256 graft_intervals_into_buffer (tmp_interval1, start1 + len2,
2257 len1, current_buffer, 0);
2258 graft_intervals_into_buffer (tmp_interval2, start1,
2259 len2, current_buffer, 0);
2260 #endif /* USE_TEXT_PROPERTIES */
2261 }
2262 /* Non-adjacent regions, because end1 != start2, bleagh... */
2263 else
2264 {
2265 if (len1 == len2)
2266 /* Regions are same size, though, how nice. */
2267 {
2268 modify_region (current_buffer, start1, end1);
2269 modify_region (current_buffer, start2, end2);
2270 record_change (start1, len1);
2271 record_change (start2, len2);
2272 #ifdef USE_TEXT_PROPERTIES
2273 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
2274 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
2275 Fset_text_properties (start1, end1, Qnil, Qnil);
2276 Fset_text_properties (start2, end2, Qnil, Qnil);
2277 #endif /* USE_TEXT_PROPERTIES */
2278
2279 if (len1 > 20000)
2280 temp = (unsigned char *) xmalloc (len1);
2281 else
2282 temp = (unsigned char *) alloca (len1);
2283 start1_addr = BUF_CHAR_ADDRESS (current_buffer, start1);
2284 start2_addr = BUF_CHAR_ADDRESS (current_buffer, start2);
2285 bcopy (start1_addr, temp, len1);
2286 bcopy (start2_addr, start1_addr, len2);
2287 bcopy (temp, start2_addr, len1);
2288 if (len1 > 20000)
2289 free (temp);
2290 #ifdef USE_TEXT_PROPERTIES
2291 graft_intervals_into_buffer (tmp_interval1, start2,
2292 len1, current_buffer, 0);
2293 graft_intervals_into_buffer (tmp_interval2, start1,
2294 len2, current_buffer, 0);
2295 #endif /* USE_TEXT_PROPERTIES */
2296 }
2297
2298 else if (len1 < len2) /* Second region larger than first */
2299 /* Non-adjacent & unequal size, area between must also be shifted. */
2300 {
2301 len_mid = start2 - end1;
2302 modify_region (current_buffer, start1, end2);
2303 record_change (start1, (end2 - start1));
2304 #ifdef USE_TEXT_PROPERTIES
2305 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
2306 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
2307 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
2308 Fset_text_properties (start1, end2, Qnil, Qnil);
2309 #endif /* USE_TEXT_PROPERTIES */
2310
2311 /* holds region 2 */
2312 if (len2 > 20000)
2313 temp = (unsigned char *) xmalloc (len2);
2314 else
2315 temp = (unsigned char *) alloca (len2);
2316 start1_addr = BUF_CHAR_ADDRESS (current_buffer, start1);
2317 start2_addr = BUF_CHAR_ADDRESS (current_buffer, start2);
2318 bcopy (start2_addr, temp, len2);
2319 bcopy (start1_addr, start1_addr + len_mid + len2, len1);
2320 safe_bcopy (start1_addr + len1, start1_addr + len2, len_mid);
2321 bcopy (temp, start1_addr, len2);
2322 if (len2 > 20000)
2323 free (temp);
2324 #ifdef USE_TEXT_PROPERTIES
2325 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
2326 len1, current_buffer, 0);
2327 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
2328 len_mid, current_buffer, 0);
2329 graft_intervals_into_buffer (tmp_interval2, start1,
2330 len2, current_buffer, 0);
2331 #endif /* USE_TEXT_PROPERTIES */
2332 }
2333 else
2334 /* Second region smaller than first. */
2335 {
2336 len_mid = start2 - end1;
2337 record_change (start1, (end2 - start1));
2338 modify_region (current_buffer, start1, end2);
2339
2340 #ifdef USE_TEXT_PROPERTIES
2341 tmp_interval1 = copy_intervals (cur_intv, start1, len1);
2342 tmp_interval_mid = copy_intervals (cur_intv, end1, len_mid);
2343 tmp_interval2 = copy_intervals (cur_intv, start2, len2);
2344 Fset_text_properties (start1, end2, Qnil, Qnil);
2345 #endif /* USE_TEXT_PROPERTIES */
2346
2347 /* holds region 1 */
2348 if (len1 > 20000)
2349 temp = (unsigned char *) xmalloc (len1);
2350 else
2351 temp = (unsigned char *) alloca (len1);
2352 start1_addr = BUF_CHAR_ADDRESS (current_buffer, start1);
2353 start2_addr = BUF_CHAR_ADDRESS (current_buffer, start2);
2354 bcopy (start1_addr, temp, len1);
2355 bcopy (start2_addr, start1_addr, len2);
2356 bcopy (start1_addr + len1, start1_addr + len2, len_mid);
2357 bcopy (temp, start1_addr + len2 + len_mid, len1);
2358 if (len1 > 20000)
2359 free (temp);
2360 #ifdef USE_TEXT_PROPERTIES
2361 graft_intervals_into_buffer (tmp_interval1, end2 - len1,
2362 len1, current_buffer, 0);
2363 graft_intervals_into_buffer (tmp_interval_mid, start1 + len2,
2364 len_mid, current_buffer, 0);
2365 graft_intervals_into_buffer (tmp_interval2, start1,
2366 len2, current_buffer, 0);
2367 #endif /* USE_TEXT_PROPERTIES */
2368 }
2369 }
2370
2371 /* todo: this will be slow, because for every transposition, we
2372 traverse the whole friggin marker list. Possible solutions:
2373 somehow get a list of *all* the markers across multiple
2374 transpositions and do it all in one swell phoop. Or maybe modify
2375 Emacs' marker code to keep an ordered list or tree. This might
2376 be nicer, and more beneficial in the long run, but would be a
2377 bunch of work. Plus the way they're arranged now is nice. */
2378 if (NILP (leave_markers))
2379 {
2380 transpose_markers (start1, end1, start2, end2);
2381 fix_overlays_in_range (start1, end2);
2382 }
2383
2384 return Qnil;
2385 }
2386
2387 \f
2388 void
2389 syms_of_editfns ()
2390 {
2391 environbuf = 0;
2392
2393 Qbuffer_access_fontify_functions
2394 = intern ("buffer-access-fontify-functions");
2395 staticpro (&Qbuffer_access_fontify_functions);
2396
2397 DEFVAR_LISP ("buffer-access-fontify-functions",
2398 &Vbuffer_access_fontify_functions,
2399 "List of functions called by `buffer-substring' to fontify if necessary.\n\
2400 Each function is called with two arguments which specify the range\n\
2401 of the buffer being accessed.");
2402 Vbuffer_access_fontify_functions = Qnil;
2403
2404 {
2405 Lisp_Object obuf;
2406 extern Lisp_Object Vprin1_to_string_buffer;
2407 obuf = Fcurrent_buffer ();
2408 /* Do this here, because init_buffer_once is too early--it won't work. */
2409 Fset_buffer (Vprin1_to_string_buffer);
2410 /* Make sure buffer-access-fontify-functions is nil in this buffer. */
2411 Fset (Fmake_local_variable (intern ("buffer-access-fontify-functions")),
2412 Qnil);
2413 Fset_buffer (obuf);
2414 }
2415
2416 DEFVAR_LISP ("buffer-access-fontified-property",
2417 &Vbuffer_access_fontified_property,
2418 "Property which (if non-nil) indicates text has been fontified.\n\
2419 `buffer-substring' need not call the `buffer-access-fontify-functions'\n\
2420 functions if all the text being accessed has this property.");
2421 Vbuffer_access_fontified_property = Qnil;
2422
2423 DEFVAR_LISP ("system-name", &Vsystem_name,
2424 "The name of the machine Emacs is running on.");
2425
2426 DEFVAR_LISP ("user-full-name", &Vuser_full_name,
2427 "The full name of the user logged in.");
2428
2429 DEFVAR_LISP ("user-login-name", &Vuser_login_name,
2430 "The user's name, taken from environment variables if possible.");
2431
2432 DEFVAR_LISP ("user-real-login-name", &Vuser_real_login_name,
2433 "The user's name, based upon the real uid only.");
2434
2435 defsubr (&Schar_equal);
2436 defsubr (&Sgoto_char);
2437 defsubr (&Sstring_to_char);
2438 defsubr (&Schar_to_string);
2439 defsubr (&Sbuffer_substring);
2440 defsubr (&Sbuffer_substring_no_properties);
2441 defsubr (&Sbuffer_string);
2442
2443 defsubr (&Spoint_marker);
2444 defsubr (&Smark_marker);
2445 defsubr (&Spoint);
2446 defsubr (&Sregion_beginning);
2447 defsubr (&Sregion_end);
2448 /* defsubr (&Smark); */
2449 /* defsubr (&Sset_mark); */
2450 defsubr (&Ssave_excursion);
2451
2452 defsubr (&Sbufsize);
2453 defsubr (&Spoint_max);
2454 defsubr (&Spoint_min);
2455 defsubr (&Spoint_min_marker);
2456 defsubr (&Spoint_max_marker);
2457
2458 defsubr (&Sbobp);
2459 defsubr (&Seobp);
2460 defsubr (&Sbolp);
2461 defsubr (&Seolp);
2462 defsubr (&Sfollowing_char);
2463 defsubr (&Sprevious_char);
2464 defsubr (&Schar_after);
2465 defsubr (&Sinsert);
2466 defsubr (&Sinsert_before_markers);
2467 defsubr (&Sinsert_and_inherit);
2468 defsubr (&Sinsert_and_inherit_before_markers);
2469 defsubr (&Sinsert_char);
2470
2471 defsubr (&Suser_login_name);
2472 defsubr (&Suser_real_login_name);
2473 defsubr (&Suser_uid);
2474 defsubr (&Suser_real_uid);
2475 defsubr (&Suser_full_name);
2476 defsubr (&Semacs_pid);
2477 defsubr (&Scurrent_time);
2478 defsubr (&Sformat_time_string);
2479 defsubr (&Sdecode_time);
2480 defsubr (&Sencode_time);
2481 defsubr (&Scurrent_time_string);
2482 defsubr (&Scurrent_time_zone);
2483 defsubr (&Sset_time_zone_rule);
2484 defsubr (&Ssystem_name);
2485 defsubr (&Smessage);
2486 defsubr (&Smessage_box);
2487 defsubr (&Smessage_or_box);
2488 defsubr (&Sformat);
2489
2490 defsubr (&Sinsert_buffer_substring);
2491 defsubr (&Scompare_buffer_substrings);
2492 defsubr (&Ssubst_char_in_region);
2493 defsubr (&Stranslate_region);
2494 defsubr (&Sdelete_region);
2495 defsubr (&Swiden);
2496 defsubr (&Snarrow_to_region);
2497 defsubr (&Ssave_restriction);
2498 defsubr (&Stranspose_regions);
2499 }