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