Gnus -- Minor tweak define #'time-to-seconds
[packages] / xemacs-packages / xemacs-base / sort.el
1 ;;; sort.el --- commands to sort text in an XEmacs buffer
2
3 ;; Copyright (C) 1986, 1987, 1994, 1995, 2003 Free Software Foundation, Inc.
4
5 ;; Author: Howie Kaye
6 ;; Maintainer: XEmacs Development Team
7 ;; Keywords: unix
8
9 ;; This file is part of XEmacs.
10
11 ;; XEmacs is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; XEmacs is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
23 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
24 ;; 02111-1307, USA.
25
26 ;;; Synched up with: FSF 21.3.
27
28 ;;; Commentary:
29
30 ;;; This package provides the sorting facilities documented in the XEmacs
31 ;;; Reference Manual.
32
33 ;;; Code:
34
35 (defgroup sort nil
36   "Commands to sort text in an Emacs buffer."
37   :group 'data)
38
39 (defcustom sort-fold-case nil
40   "*Non-nil if the buffer sort functions should ignore case."
41   :group 'sort
42   :type 'boolean)
43
44 ;;;###autoload
45 (defun sort-subr (reverse nextrecfun endrecfun &optional startkeyfun endkeyfun
46                           comparefun)
47   "General text sorting routine to divide buffer into records and sort them.
48
49 We divide the accessible portion of the buffer into disjoint pieces
50 called sort records.  A portion of each sort record (perhaps all of
51 it) is designated as the sort key.  The records are rearranged in the
52 buffer in order by their sort keys.  The records may or may not be
53 contiguous.
54
55 Usually the records are rearranged in order of ascending sort key.
56 If REVERSE is non-nil, they are rearranged in order of descending sort key.
57 The variable `sort-fold-case' determines whether alphabetic case affects
58 the sort order.
59
60 The next four arguments are functions to be called to move point
61 across a sort record.  They will be called many times from within sort-subr.
62
63 NEXTRECFUN is called with point at the end of the previous record.
64 It moves point to the start of the next record.
65 It should move point to the end of the buffer if there are no more records.
66 The first record is assumed to start at the position of point when sort-subr
67 is called.
68
69 ENDRECFUN is called with point within the record.
70 It should move point to the end of the record.
71
72 STARTKEYFUN moves from the start of the record to the start of the key.
73 It may return either a non-nil value to be used as the key, or
74 else the key is the substring between the values of point after
75 STARTKEYFUN and ENDKEYFUN are called.  If STARTKEYFUN is nil, the key
76 starts at the beginning of the record.
77
78 ENDKEYFUN moves from the start of the sort key to the end of the sort key.
79 ENDKEYFUN may be nil if STARTKEYFUN returns a value or if it would be the
80 same as ENDRECFUN.
81
82 COMPAREFUN compares the two keys.  It is called with two strings and
83 should return true if the first is \"less\" than the second, just as
84 for `sort'.  If nil or omitted, the default function accepts keys that
85 are numbers (compared numerically) or strings (compared lexicographically)."
86   ;; Heuristically try to avoid messages if sorting a small amt of text.
87   (let ((messages (> (- (point-max) (point-min)) 50000)))
88     (save-excursion
89       (if messages (message "Finding sort keys..."))
90       (let* ((sort-lists (sort-build-lists nextrecfun endrecfun
91                                            startkeyfun endkeyfun))
92              (old (reverse sort-lists))
93              (case-fold-search sort-fold-case))
94         (if (null sort-lists)
95             ()
96           (or reverse (setq sort-lists (nreverse sort-lists)))
97           (if messages (message "Sorting records..."))
98           (setq sort-lists
99                 (sort sort-lists
100                       (cond ((and (consp (car (car sort-lists)))
101                                   comparefun)
102                              (function
103                               (lambda (a b)
104                                 (funcall comparefun
105                                          (buffer-substring (car (car a))
106                                                            (cdr (car a)))
107                                          (buffer-substring (car (car b))
108                                                            (cdr (car b)))))))
109                             ((consp (car (car sort-lists)))
110                              (function
111                               (lambda (a b)
112                                 (> 0 (compare-buffer-substrings
113                                       nil (car (car a)) (cdr (car a))
114                                       nil (car (car b)) (cdr (car b)))))))
115                             (comparefun
116                              (function
117                               (lambda (a b)
118                                 (funcall comparefun (car a) (car b)))))
119                             ((numberp (car (car sort-lists)))
120                              'car-less-than-car)
121                             (t
122                              (function
123                               (lambda (a b)
124                                 (string< (car a) (car b))))))))
125           (if reverse (setq sort-lists (nreverse sort-lists)))
126           (if messages (message "Reordering buffer..."))
127           (sort-reorder-buffer sort-lists old)))
128       (if messages (message "Reordering buffer... Done"))))
129   nil)
130
131 ;; Parse buffer into records using the arguments as Lisp expressions;
132 ;; return a list of records.  Each record looks like (KEY STARTPOS . ENDPOS)
133 ;; where KEY is the sort key (a number or string),
134 ;; and STARTPOS and ENDPOS are the bounds of this record in the buffer.
135
136 ;; The records appear in the list lastmost first!
137
138 (defun sort-build-lists (nextrecfun endrecfun startkeyfun endkeyfun)
139   (let ((sort-lists ())
140         (start-rec nil)
141         done key)
142     ;; Loop over sort records.
143     ;(goto-char (point-min)) -- it is the caller's responsibility to
144     ;arrange this if necessary
145     (while (not (eobp))
146       (setq start-rec (point))          ;save record start
147       (setq done nil)
148       ;; Get key value, or move to start of key.
149       (setq key (catch 'key
150                   (or (and startkeyfun (funcall startkeyfun))
151                       ;; If key was not returned as value,
152                       ;; move to end of key and get key from the buffer.
153                       (let ((start (point)))
154                         (funcall (or endkeyfun
155                                      (prog1 endrecfun (setq done t))))
156                         (cons start (point))))))
157       ;; Move to end of this record (start of next one, or end of buffer).
158       (cond ((prog1 done (setq done nil)))
159             (endrecfun (funcall endrecfun))
160             (nextrecfun (funcall nextrecfun) (setq done t)))
161       (if key (setq sort-lists (cons
162                                  ;; consing optimization in case in which key
163                                  ;; is same as record.
164                                  (if (and (consp key)
165                                           (equal (car key) start-rec)
166                                           (equal (cdr key) (point)))
167                                      (cons key key)
168                                      (cons key (cons start-rec (point))))
169                                 sort-lists)))
170       (and (not done) nextrecfun (funcall nextrecfun)))
171     sort-lists))
172
173 (defun sort-reorder-buffer (sort-lists old)
174   (let ((last (point-min))
175         (min (point-min)) (max (point-max))
176         (old-buffer (current-buffer))
177         temp-buffer)
178     (with-temp-buffer
179       ;; Record the temporary buffer.
180       (setq temp-buffer (current-buffer))
181
182       ;; Copy the sorted text into the temporary buffer.
183       (while sort-lists
184         (goto-char (point-max))
185         (insert-buffer-substring old-buffer
186                                  last
187                                  (nth 1 (car old)))
188         (goto-char (point-max))
189         (insert-buffer-substring old-buffer
190                                  (nth 1 (car sort-lists))
191                                  (cdr (cdr (car sort-lists))))
192         (setq last (cdr (cdr (car old)))
193               sort-lists (cdr sort-lists)
194               old (cdr old)))
195       (goto-char (point-max))
196       (insert-buffer-substring old-buffer last max)
197
198       ;; Copy the reordered text from the temporary buffer
199       ;; to the buffer we sorted (OLD-BUFFER).
200       (set-buffer old-buffer)
201       (let ((inhibit-quit t))
202         ;; Make sure insertions done for reordering
203         ;; do not go after any markers at the end of the sorted region,
204         ;; by inserting a space to separate them.
205         (goto-char max)
206         (insert-before-markers " ")
207         ;; Delete the original copy of the text.
208         (delete-region min max)
209         ;; Now replace the separator " " with the sorted text.
210         (goto-char (point-max))
211         (insert-buffer-substring temp-buffer)
212         (delete-region min (1+ min))))))
213
214 ;;;###autoload
215 (defun sort-lines (reverse beg end)
216   "Sort lines in region alphabetically; argument means descending order.
217 Called from a program, there are three arguments:
218 REVERSE (non-nil means reverse order), BEG and END (region to sort).
219 The variable `sort-fold-case' determines whether alphabetic case affects
220 the sort order."
221   (interactive "P\nr")
222   (save-excursion
223     (save-restriction
224       (narrow-to-region beg end)
225       (goto-char (point-min))
226       (sort-subr reverse 'forward-line 'end-of-line))))
227
228 ;;;###autoload
229 (defun sort-paragraphs (reverse beg end)
230   "Sort paragraphs in region alphabetically; argument means descending order.
231 Called from a program, there are three arguments:
232 REVERSE (non-nil means reverse order), BEG and END (region to sort).
233 The variable `sort-fold-case' determines whether alphabetic case affects
234 the sort order."
235   (interactive "P\nr")
236   (save-excursion
237     (save-restriction
238       (narrow-to-region beg end)
239       (goto-char (point-min))
240       (sort-subr reverse
241                  (function
242                   (lambda ()
243                     (while (and (not (eobp)) (looking-at paragraph-separate))
244                       (forward-line 1))))
245                  'forward-paragraph))))
246
247 ;;;###autoload
248 (defun sort-pages (reverse beg end)
249   "Sort pages in region alphabetically; argument means descending order.
250 Called from a program, there are three arguments:
251 REVERSE (non-nil means reverse order), BEG and END (region to sort).
252 The variable `sort-fold-case' determines whether alphabetic case affects
253 the sort order."
254   (interactive "P\nr")
255   (save-excursion
256     (save-restriction
257       (narrow-to-region beg end)
258       (goto-char (point-min))
259       (sort-subr reverse
260                  (function (lambda () (skip-chars-forward "\n")))
261                  'forward-page))))
262 \f
263 (defvar sort-fields-syntax-table nil)
264 (if sort-fields-syntax-table nil
265   (let ((table (make-syntax-table))
266         (i 0))
267     (while (< i 256)
268       (modify-syntax-entry i "w" table)
269       (setq i (1+ i)))
270     (modify-syntax-entry ?\  " " table)
271     (modify-syntax-entry ?\t " " table)
272     (modify-syntax-entry ?\n " " table)
273     (modify-syntax-entry ?\. "_" table) ; for floating pt. numbers. -wsr
274     (setq sort-fields-syntax-table table)))
275
276 (defcustom sort-numeric-base 10
277   "*Fallback base for `sort-numeric-fields', `sort-regexp-fields-numerically'."
278   :group 'sort
279   :type 'integer)
280
281 ;;;###autoload
282 (defun sort-numeric-fields (field beg end)
283   "Sort lines in region numerically by the ARGth field of each line.
284 Fields are separated by whitespace and numbered from 1 up.
285 Specified field must contain a number in each line of the region,
286 which may begin with \"0x\" or \"0\" for hexadecimal and octal values.
287 Otherwise, the number is interpreted according to sort-numeric-base.
288 With a negative arg, sorts by the ARGth field counted from the right.
289 Called from a program, there are three arguments:
290 FIELD, BEG and END.  BEG and END specify region to sort.
291 The variable `sort-fold-case' determines whether alphabetic case affects
292 the sort order.
293 If you want to sort floating-point numbers, try `sort-float-fields'."
294   (interactive "p\nr")
295   (sort-fields-1 field beg end
296                  (lambda ()
297                    (sort-skip-fields field)
298                    (let* ((case-fold-search t)
299                           (base
300                            (if (looking-at "\\(0x\\)[0-9a-f]\\|\\(0\\)[0-7]")
301                                (cond ((match-beginning 1)
302                                       (goto-char (match-end 1))
303                                       16)
304                                      ((match-beginning 2)
305                                       (goto-char (match-end 2))
306                                       8)
307                                      (t nil)))))
308                      (string-to-number (buffer-substring (point)
309                                                          (save-excursion
310                                                            (forward-sexp 1)
311                                                            (point)))
312                                        (or base sort-numeric-base))))
313                  nil))
314
315 ;; This function is commented out of 19.34.
316 ;;;###autoload
317 (defun sort-float-fields (field beg end)
318   "Sort lines in region numerically by the ARGth field of each line.
319 Fields are separated by whitespace and numbered from 1 up.  Specified field
320 must contain a floating point number in each line of the region.  With a
321 negative arg, sorts by the ARGth field counted from the right.  Called from a
322 program, there are three arguments: FIELD, BEG and END.  BEG and END specify
323 region to sort."
324   (interactive "p\nr")
325   (sort-fields-1 field beg end
326                  (function (lambda ()
327                              (sort-skip-fields field)
328                              (string-to-number
329                               (buffer-substring
330                                (point)
331                                (save-excursion
332                                  (re-search-forward
333                                   "[+-]?[0-9]*\.?[0-9]*\\([eE][+-]?[0-9]+\\)?")
334                                  (point))))))
335                  nil))
336
337 ;;;###autoload
338 (defun sort-fields (field beg end)
339   "Sort lines in region lexicographically by the ARGth field of each line.
340 Fields are separated by whitespace and numbered from 1 up.
341 With a negative arg, sorts by the ARGth field counted from the right.
342 Called from a program, there are three arguments:
343 FIELD, BEG and END.  BEG and END specify region to sort.
344 The variable `sort-fold-case' determines whether alphabetic case affects
345 the sort order."
346   (interactive "p\nr")
347   (sort-fields-1 field beg end
348                  (function (lambda ()
349                              (sort-skip-fields field)
350                              nil))
351                  (function (lambda () (skip-chars-forward "^ \t\n")))))
352
353 (defun sort-fields-1 (field beg end startkeyfun endkeyfun)
354   (let ((tbl (syntax-table)))
355     (if (zerop field) (setq field 1))
356     (unwind-protect
357         (save-excursion
358           (save-restriction
359             (narrow-to-region beg end)
360             (goto-char (point-min))
361             (set-syntax-table sort-fields-syntax-table)
362             (sort-subr nil
363                        'forward-line 'end-of-line
364                        startkeyfun endkeyfun)))
365       (set-syntax-table tbl))))
366
367 ;; Position at the beginning of field N on the current line,
368 ;; assuming point is initially at the beginning of the line.
369 (defun sort-skip-fields (n)
370   (if (> n 0)
371       ;; Skip across N - 1 fields.
372       (let ((i (1- n)))
373         (while (> i 0)
374           (skip-chars-forward " \t")
375           (skip-chars-forward "^ \t\n")
376           (setq i (1- i)))
377         (skip-chars-forward " \t")
378         (if (eolp)
379             (error "Line has too few fields: %s"
380                    (buffer-substring
381                     (save-excursion (beginning-of-line) (point))
382                     (save-excursion (end-of-line) (point))))))
383     (end-of-line)
384     ;; Skip back across - N - 1 fields.
385     (let ((i (1- (- n))))
386       (while (> i 0)
387         (skip-chars-backward " \t")
388         (skip-chars-backward "^ \t\n")
389         (setq i (1- i)))
390       (skip-chars-backward " \t"))
391     (if (bolp)
392         (error "Line has too few fields: %s"
393                (buffer-substring
394                 (save-excursion (beginning-of-line) (point))
395                 (save-excursion (end-of-line) (point)))))
396     ;; Position at the front of the field
397     ;; even if moving backwards.
398     (skip-chars-backward "^ \t\n")))
399 \f
400 (defvar sort-regexp-fields-regexp)
401 (defvar sort-regexp-record-end)
402
403 ;; Move to the beginning of the next match for record-regexp,
404 ;; and set sort-regexp-record-end to the end of that match.
405 ;; If the next match is empty and does not advance point,
406 ;; skip one character and try again.
407 (defun sort-regexp-fields-next-record ()
408   (let ((oldpos (point)))
409     (and (re-search-forward sort-regexp-fields-regexp nil 'move)
410          (setq sort-regexp-record-end (match-end 0))
411          (if (= sort-regexp-record-end oldpos)
412              (progn
413                (forward-char 1)
414                (re-search-forward sort-regexp-fields-regexp nil 'move)
415                (setq sort-regexp-record-end (match-end 0)))
416            t)
417          (goto-char (match-beginning 0)))))
418
419 ;; History used for sort regexps.
420 (defvar sort-regexp-history nil)
421
422 ;;;###autoload
423 (defun sort-regexp-fields (reverse record-regexp key-regexp beg end
424                                    &optional comparefun)
425   "Sort the region as specified by RECORD-REGEXP and KEY.
426 RECORD-REGEXP specifies the textual units which should be sorted.
427   For example, to sort lines RECORD-REGEXP would be \"^.*$\"
428 KEY specifies the part of each record (ie each match for RECORD-REGEXP)
429   is to be used for sorting.
430   If it is \"\\\\digit\" then the digit'th \"\\\\(...\\\\)\" match field from
431   RECORD-REGEXP is used.
432   If it is \"\\\\&\" then the whole record is used.
433   Otherwise, it is a regular-expression for which to search within the record.
434 If a match for KEY is not found within a record then that record is ignored.
435
436 With a negative prefix arg sorts in reverse order.
437
438 The variable `sort-fold-case' determines whether alphabetic case affects
439 the sort order.
440
441 COMPAREFUN, if specified, should be a function of two arguments; it
442 will be passed the keys (as strings), and should return true if the
443 first is \"less\" than the second.  Otherwise the keys will be
444 compared lexicographically.
445
446 For example: to sort lines in the region by the first word on each line
447  starting with the letter \"f\",
448  RECORD-REGEXP would be \"^.*$\" and KEY would be \"\\\\=\\<f\\\\w*\\\\>\""
449   ;; using negative prefix arg to mean "reverse" is now inconsistent with
450   ;; other sort-.*fields functions but then again this was before, since it
451   ;; didn't use the magnitude of the arg to specify anything.
452   (interactive
453    ;; retrieve the region first, since pasting into the minibuffer will
454    ;; deactivate it. (YUCK! should have per-buffer regions.)
455    (let ((beg (region-beginning))
456          (end (region-end)))
457      (list current-prefix-arg
458            (read-string "Regexp specifying records to sort: "
459                         nil 'sort-regexp-history)
460            (read-string "Regexp specifying key within record: "
461                         nil 'sort-regexp-history)
462            beg end)))
463   (cond ((or (equal key-regexp "") (equal key-regexp "\\&"))
464          (setq key-regexp 0))
465         ((string-match "\\`\\\\[1-9]\\'" key-regexp)
466          (setq key-regexp (- (aref key-regexp 1) ?0))))
467   (save-excursion
468     (save-restriction
469       (narrow-to-region beg end)
470       (goto-char (point-min))
471       (let (sort-regexp-record-end
472             (sort-regexp-fields-regexp record-regexp))
473         (re-search-forward sort-regexp-fields-regexp nil t)
474         (setq sort-regexp-record-end (point))
475         (goto-char (match-beginning 0))
476         (sort-subr reverse
477                    'sort-regexp-fields-next-record
478                    (function (lambda ()
479                                (goto-char sort-regexp-record-end)))
480                    (function (lambda ()
481                                (let ((n 0))
482                                  (cond ((numberp key-regexp)
483                                         (setq n key-regexp))
484                                        ((re-search-forward
485                                           key-regexp sort-regexp-record-end t)
486                                         (setq n 0))
487                                        (t (throw 'key nil)))
488                                  (condition-case ()
489                                      (cons (match-beginning n)
490                                            (match-end n))
491                                    ;; if there was no such register
492                                    (error (throw 'key nil))))))
493                    nil
494                    comparefun)))))
495
496 ;;;###autoload
497 (defun sort-regexp-fields-numerically (reverse record-regexp key-regexp
498                                                beg end)
499   "Sort the region numerically as specified by RECORD-REGEXP and KEY.
500 RECORD-REGEXP specifies the textual units which should be sorted.
501   For example, to sort lines RECORD-REGEXP would be \"^.*$\"
502 KEY specifies the part of each record (ie each match for RECORD-REGEXP)
503   which is to be used for sorting.
504   If it is \"\\\\digit\" then the digit'th \"\\\\(...\\\\)\" match field from
505   RECORD-REGEXP is used.
506   If it is \"\\\\&\" then the whole record is used.
507   Otherwise, it is a regular-expression for which to search within the record.
508 If a match for KEY is not found within a record then that record is ignored.
509
510 If the match for KEY starts with \"0x\", it specifies hexadecimal as the
511 conversion base.  A match for KEY starting with \"0\" is interpreted as
512 octal; otherwise `sort-numeric-base' is consulted for the conversion base to
513 use.  You can avoid the automatic detection of a field's base by specifying
514 RECORD-REGEXP appropriately; \"0*\" before the start of the KEY will prevent
515 detection as octal, and including \"[^xX]\" in the group corresponding to
516 KEY will prevent detection as hex.
517
518 With a negative prefix arg sorts in reverse order.
519
520 For example: to sort lines in the region by the numerical value of the first
521  C hexadecimal constant,
522  RECORD-REGEXP would be \"^.*$\" and KEY would be \"0[xX][0-9A-Fa-f]+\""
523   ;; using negative prefix arg to mean "reverse" is now inconsistent with
524   ;; other sort-.*fields functions but then again this was before, since it
525   ;; didn't use the magnitude of the arg to specify anything.
526   (interactive
527    ;; retrieve the region first, since pasting into the minibuffer will
528    ;; deactivate it. (YUCK! should have per-buffer regions.)
529    (let ((beg (region-beginning))
530          (end (region-end)))
531      (list current-prefix-arg
532            (read-string "Regexp specifying records to sort: "
533                         nil 'sort-regexp-history)
534            (read-string "Regexp specifying key within record: "
535                         nil 'sort-regexp-history)
536            beg end)))
537   (let ((base-sniff-regexp "\\(0[xX]\\)[0-9a-fA-F]\\|\\(0\\)[0-7]"))
538     (sort-regexp-fields reverse record-regexp key-regexp beg end
539                         #'(lambda (a b)
540                             ;; If I replace #'< with #'max, the warning
541                             ;; 
542                             ;; ** variable base-sniff-regexp bound but not
543                             ;; referenced
544                             ;;
545                             ;; goes away. Byte compiler bug. 
546                             (< (string-to-number a
547                                 (if (string-match base-sniff-regexp a)
548                                     (cond ((match-beginning 1) 16)
549                                           ((match-beginning 2) 8)
550                                           (t sort-numeric-base))
551                                   sort-numeric-base))
552                                (string-to-number b
553                                 (if (string-match base-sniff-regexp b)
554                                     (cond ((match-beginning 1) 16)
555                                           ((match-beginning 2) 8)
556                                           (t sort-numeric-base))
557                                   sort-numeric-base)))))))
558
559 \f
560 (defvar sort-columns-subprocess t)
561
562 ;;;###autoload
563 (defun sort-columns (reverse &optional beg end)
564   "Sort lines in region alphabetically by a certain range of columns.
565 For the purpose of this command, the region BEG...END includes
566 the entire line that point is in and the entire line the mark is in.
567 The column positions of point and mark bound the range of columns to sort on.
568 A prefix argument means sort into REVERSE order.
569 The variable `sort-fold-case' determines whether alphabetic case affects
570 the sort order.
571
572 Note that `sort-columns' rejects text that contains tabs,
573 because tabs could be split across the specified columns
574 and it doesn't know how to handle that.  Also, when possible,
575 it uses the `sort' utility program, which doesn't understand tabs.
576 Use \\[untabify] to convert tabs to spaces before sorting."
577   (interactive "P\nr")
578   (save-excursion
579     (let (beg1 end1 col-beg1 col-end1 col-start col-end)
580       (goto-char (min beg end))
581       (setq col-beg1 (current-column))
582       (beginning-of-line)
583       (setq beg1 (point))
584       (goto-char (max beg end))
585       (setq col-end1 (current-column))
586       (forward-line)
587       (setq end1 (point))
588       (setq col-start (min col-beg1 col-end1))
589       (setq col-end (max col-beg1 col-end1))
590       (if (search-backward "\t" beg1 t)
591           (error "sort-columns does not work with tabs -- use M-x untabify"))
592       (if (not (or (eq system-type 'vax-vms)
593                    (text-properties-at beg1)
594                    (< (next-property-change beg1 nil end1) end1)))
595           ;; Use the sort utility if we can; it is 4 times as fast.
596           ;; Do not use it if there are any properties in the region,
597           ;; since the sort utility would lose the properties.
598           (let ((sort-args (list (if reverse "-rt\n" "-t\n")
599                                  (concat "+0." (int-to-string col-start))
600                                  (concat "-0." (int-to-string col-end)))))
601             (when sort-fold-case
602               (push "-f" sort-args))
603             (apply #'call-process-region beg1 end1 "sort" t t nil sort-args))
604         ;; On VMS, use Emacs's own facilities.
605         (save-excursion
606           (save-restriction
607             (narrow-to-region beg1 end1)
608             (goto-char beg1)
609             (sort-subr reverse 'forward-line 'end-of-line
610                        #'(lambda () (move-to-column col-start) nil)
611                        #'(lambda () (move-to-column col-end) nil))))))))
612
613 ;;;###autoload
614 (defun reverse-region (beg end)
615   "Reverse the order of lines in a region.
616 From a program takes two point or marker arguments, BEG and END."
617   (interactive "r")
618   (if (> beg end)
619       (let (mid) (setq mid end end beg beg mid)))
620   (save-excursion
621     ;; put beg at the start of a line and end and the end of one --
622     ;; the largest possible region which fits this criteria
623     (goto-char beg)
624     (or (bolp) (forward-line 1))
625     (setq beg (point))
626     (goto-char end)
627     ;; the test for bolp is for those times when end is on an empty line;
628     ;; it is probably not the case that the line should be included in the
629     ;; reversal; it isn't difficult to add it afterward.
630     (or (and (eolp) (not (bolp))) (progn (forward-line -1) (end-of-line)))
631     (setq end (point-marker))
632     ;; the real work.  this thing cranks through memory on large regions.
633     (let (ll (do t))
634       (while do
635         (goto-char beg)
636         (setq ll (cons (buffer-substring (point) (progn (end-of-line) (point)))
637                        ll))
638         (setq do (/= (point) end))
639         (delete-region beg (if do (1+ (point)) (point))))
640       (while (cdr ll)
641         (insert (car ll) "\n")
642         (setq ll (cdr ll)))
643       (insert (car ll)))))
644
645 (provide 'sort)
646
647 ;;; sort.el ends here