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