1 ;; Commands to sort text in an Emacs buffer.
2 ;; Copyright (C) 1986, 1987 Free Software Foundation, Inc.
4 ;; This file is part of GNU Emacs.
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 1, or (at your option)
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.
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.
22 ;; Original version of most of this contributed by Howie Kaye
24 (defun sort-subr (reverse nextrecfun endrecfun
&optional startkeyfun endkeyfun
)
25 "General text sorting routine to divide buffer into records and sort them.
26 Arguments are REVERSE NEXTRECFUN ENDRECFUN &optional STARTKEYFUN ENDKEYFUN.
28 We consider this portion of the buffer to be divided into disjoint pieces
29 called sort records. A portion of each sort record (perhaps all of it)
30 is designated as the sort key. The records are rearranged in the buffer
31 in order by their sort keys. The records may or may not be contiguous.
33 Usually the records are rearranged in order of ascending sort key.
34 If REVERSE is non-nil, they are rearranged in order of descending sort key.
36 The next four arguments are functions to be called to move point
37 across a sort record. They will be called many times from within sort-subr.
39 NEXTRECFUN is called with point at the end of the previous record.
40 It moves point to the start of the next record.
41 It should move point to the end of the buffer if there are no more records.
42 The first record is assumed to start at the position of point when sort-subr
45 ENDRECFUN is is called with point within the record.
46 It should move point to the end of the record.
48 STARTKEYFUN may moves from the start of the record to the start of the key.
49 It may return either return a non-nil value to be used as the key, or
50 else the key will be the substring between the values of point after
51 STARTKEYFUNC and ENDKEYFUN are called.
53 ENDKEYFUN moves from the start of the sort key to the end of the sort key.
54 ENDKEYFUN may be nil if STARTKEYFUN returns a value or if it would be the
57 (message "Finding sort keys...")
58 (let* ((sort-lists (sort-build-lists nextrecfun endrecfun
59 startkeyfun endkeyfun
))
60 (old (reverse sort-lists
)))
63 (or reverse
(setq sort-lists
(nreverse sort-lists
)))
64 (message "Sorting records...")
66 (if (fboundp 'sortcar
)
68 (cond ((floatp (car (car sort-lists
)))
70 ((numberp (car (car sort-lists
)))
72 ((consp (car (car sort-lists
)))
73 'buffer-substring-lessp
)
77 (cond ((floatp (car (car sort-lists
)))
80 (f< (car a
) (car b
)))))
81 ((numberp (car (car sort-lists
)))
84 (< (car a
) (car b
)))))
85 ((consp (car (car sort-lists
)))
88 (buffer-substring-lessp (car a
) (car b
)))))
92 (string< (car a
) (car b
)))))))))
93 (if reverse
(setq sort-lists
(nreverse sort-lists
)))
94 (message "Reordering buffer...")
95 (sort-reorder-buffer sort-lists old
)))
96 (message "Reordering buffer... Done"))
99 ;; Parse buffer into records using the arguments as Lisp expressions;
100 ;; return a list of records. Each record looks like (KEY STARTPOS ENDPOS)
101 ;; where KEY is the sort key (a number or string),
102 ;; and STARTPOS and ENDPOS are the bounds of this record in the buffer.
104 ;; The records appear in the list lastmost first!
106 (defun sort-build-lists (nextrecfun endrecfun startkeyfun endkeyfun
)
107 (let ((sort-lists ())
110 ;; Loop over sort records.
111 ;(goto-char (point-min)) -- it is the caller's responsibility to
112 ;arrange this if necessary
114 (setq start-rec
(point)) ;save record start
116 ;; Get key value, or move to start of key.
117 (setq key
(catch 'key
118 (or (and startkeyfun
(funcall startkeyfun
))
119 ;; If key was not returned as value,
120 ;; move to end of key and get key from the buffer.
121 (let ((start (point)))
122 (funcall (or endkeyfun
123 (prog1 endrecfun
(setq done t
))))
124 (if (fboundp 'buffer-substring-lessp
)
126 (buffer-substring start
(point)))))))
127 ;; Move to end of this record (start of next one, or end of buffer).
128 (cond ((prog1 done
(setq done nil
)))
129 (endrecfun (funcall endrecfun
))
130 (nextrecfun (funcall nextrecfun
) (setq done t
)))
131 (if key
(setq sort-lists
(cons
132 ;; consing optimization in case in which key
133 ;; is same as record.
135 (equal (car key
) start-rec
)
136 (equal (cdr key
) (point)))
138 (list key start-rec
(point)))
140 (and (not done
) nextrecfun
(funcall nextrecfun
)))
143 (defun sort-reorder-buffer (sort-lists old
)
144 (let ((inhibit-quit t
)
146 (min (point-min)) (max (point-max)))
147 ;; Make sure insertions done for reordering
148 ;; do not go after any markers at the end of the sorted region,
149 ;; by inserting a space to separate them.
150 (goto-char (point-max))
151 (insert-before-markers " ")
152 (narrow-to-region min
(1- (point-max)))
154 (goto-char (point-max))
155 (insert-buffer-substring (current-buffer)
158 (goto-char (point-max))
159 (insert-buffer-substring (current-buffer)
160 (nth 1 (car sort-lists
))
161 (nth 2 (car sort-lists
)))
162 (setq last
(nth 2 (car old
))
163 sort-lists
(cdr sort-lists
)
165 (goto-char (point-max))
166 (insert-buffer-substring (current-buffer)
169 ;; Delete the original copy of the text.
170 (delete-region min max
)
171 ;; Get rid of the separator " ".
172 (goto-char (point-max))
173 (narrow-to-region min
(1+ (point)))
174 (delete-region (point) (1+ (point)))))
176 (defun sort-lines (reverse beg end
)
177 "Sort lines in region alphabetically; argument means descending order.
178 Called from a program, there are three arguments:
179 REVERSE (non-nil means reverse order), BEG and END (region to sort)."
183 (narrow-to-region beg end
)
184 (goto-char (point-min))
185 (sort-subr reverse
'forward-line
'end-of-line
))))
187 (defun sort-paragraphs (reverse beg end
)
188 "Sort paragraphs in region alphabetically; argument means descending order.
189 Called from a program, there are three arguments:
190 REVERSE (non-nil means reverse order), BEG and END (region to sort)."
194 (narrow-to-region beg end
)
195 (goto-char (point-min))
197 (function (lambda () (skip-chars-forward "\n \t\f")))
198 'forward-paragraph
))))
200 (defun sort-pages (reverse beg end
)
201 "Sort pages in region alphabetically; argument means descending order.
202 Called from a program, there are three arguments:
203 REVERSE (non-nil means reverse order), BEG and END (region to sort)."
207 (narrow-to-region beg end
)
208 (goto-char (point-min))
210 (function (lambda () (skip-chars-forward "\n")))
213 (defvar sort-fields-syntax-table nil
)
214 (if sort-fields-syntax-table nil
215 (let ((table (make-syntax-table))
218 (modify-syntax-entry i
"w" table
)
220 (modify-syntax-entry ?\
" " table
)
221 (modify-syntax-entry ?
\t " " table
)
222 (modify-syntax-entry ?
\n " " table
)
223 (modify-syntax-entry ?\.
"_" table
) ; for floating pt. numbers. -wsr
224 (setq sort-fields-syntax-table table
)))
226 (defun sort-numeric-fields (field beg end
)
227 "Sort lines in region numerically by the ARGth field of each line.
228 Fields are separated by whitespace and numbered from 1 up.
229 Specified field must contain a number in each line of the region.
230 With a negative arg, sorts by the ARGth field counted from the right.
231 Called from a program, there are three arguments:
232 FIELD, BEG and END. BEG and END specify region to sort."
234 (sort-fields-1 field beg end
236 (sort-skip-fields (1- field
))
241 ;; This is just wrong! Even without floats...
242 ;; (skip-chars-forward "[0-9]")
247 (defun sort-float-fields (field beg end
)
248 "Sort lines in region numerically by the ARGth field of each line.
249 Fields are separated by whitespace and numbered from 1 up. Specified field
250 must contain a floating point number in each line of the region. With a
251 negative arg, sorts by the ARGth field counted from the right. Called from a
252 program, there are three arguments: FIELD, BEG and END. BEG and END specify
255 (sort-fields-1 field beg end
257 (sort-skip-fields (1- field
))
263 "[+-]?[0-9]*\.?[0-9]*\\([eE][+-]?[0-9]+\\)?")
267 (defun sort-fields (field beg end
)
268 "Sort lines in region lexicographically by the ARGth field of each line.
269 Fields are separated by whitespace and numbered from 1 up.
270 With a negative arg, sorts by the ARGth field counted from the right.
271 Called from a program, there are three arguments:
272 FIELD, BEG and END. BEG and END specify region to sort."
274 (sort-fields-1 field beg end
276 (sort-skip-fields (1- field
))
278 (function (lambda () (skip-chars-forward "^ \t\n")))))
280 (defun sort-fields-1 (field beg end startkeyfun endkeyfun
)
281 (let ((tbl (syntax-table)))
282 (if (zerop field
) (setq field
1))
286 (narrow-to-region beg end
)
287 (goto-char (point-min))
288 (set-syntax-table sort-fields-syntax-table
)
290 'forward-line
'end-of-line
291 startkeyfun endkeyfun
)))
292 (set-syntax-table tbl
))))
294 (defun sort-skip-fields (n)
296 (eol (save-excursion (end-of-line 1) (point))))
297 (if (> n
0) (forward-word n
)
299 (forward-word (1+ n
)))
300 (if (or (and (>= (point) eol
) (> n
0))
301 ;; this is marginally wrong; if the first line of the sort
302 ;; at bob has the wrong number of fields the error won't be
303 ;; reported until the next short line.
304 (and (< (point) bol
) (< n
0)))
305 (error "Line has too few fields: %s"
306 (buffer-substring bol eol
)))
307 (skip-chars-forward " \t")))
310 (defun sort-regexp-fields (reverse record-regexp key-regexp beg end
)
311 "Sort the region lexicographically as specifed by RECORD-REGEXP and KEY.
312 RECORD-REGEXP specifies the textual units which should be sorted.
313 For example, to sort lines RECORD-REGEXP would be \"^.*$\"
314 KEY specifies the part of each record (ie each match for RECORD-REGEXP)
315 is to be used for sorting.
316 If it is \"\\digit\" then the digit'th \"\\(...\\)\" match field from
317 RECORD-REGEXP is used.
318 If it is \"\\&\" then the whole record is used.
319 Otherwise, it is a regular-expression for which to search within the record.
320 If a match for KEY is not found within a record then that record is ignored.
322 With a negative prefix arg sorts in reverse order.
324 For example: to sort lines in the region by the first word on each line
325 starting with the letter \"f\",
326 RECORD-REGEXP would be \"^.*$\" and KEY would be \"\\=\\<f\\w*\\>\""
327 ;; using negative prefix arg to mean "reverse" is now inconsistent with
328 ;; other sort-.*fields functions but then again this was before, since it
329 ;; didn't use the magnitude of the arg to specify anything.
330 (interactive "P\nsRegexp specifying records to sort:
331 sRegexp specifying key within record: \nr")
332 (cond ((or (equal key-regexp
"") (equal key-regexp
"\\&"))
334 ((string-match "\\`\\\\[1-9]\\'" key-regexp
)
335 (setq key-regexp
(- (aref key-regexp
1) ?
0))))
338 (narrow-to-region beg end
)
339 (goto-char (point-min))
340 (let (sort-regexp-record-end) ;isn't dynamic scoping wonderful?
341 (re-search-forward record-regexp
)
342 (setq sort-regexp-record-end
(point))
343 (goto-char (match-beginning 0))
346 (and (re-search-forward record-regexp nil
'move
)
347 (setq sort-regexp-record-end
(match-end 0))
348 (goto-char (match-beginning 0)))))
350 (goto-char sort-regexp-record-end
)))
353 (cond ((numberp key-regexp
)
356 key-regexp sort-regexp-record-end t
)
358 (t (throw 'key nil
)))
360 (if (fboundp 'buffer-substring-lessp
)
361 (cons (match-beginning n
)
363 (buffer-substring (match-beginning n
)
365 ;; if there was no such register
366 (error (throw 'key nil
)))))))))))
369 (defvar sort-columns-subprocess t
)
371 (defun sort-columns (reverse &optional beg end
)
372 "Sort lines in region alphabetically by a certain range of columns.
373 For the purpose of this command, the region includes
374 the entire line that point is in and the entire line the mark is in.
375 The column positions of point and mark bound the range of columns to sort on.
376 A prefix argument means sort into reverse order.
378 Note that `sort-columns' rejects text that contains tabs,
379 because tabs could be split across the specified columns
380 and it doesn't know how to handle that. Also, when possible,
381 it uses the `sort' utility program, which doesn't understand tabs.
382 Use \\[untabify] to convert tabs to spaces before sorting."
385 (let (beg1 end1 col-beg1 col-end1 col-start col-end
)
386 (goto-char (min beg end
))
387 (setq col-beg1
(current-column))
390 (goto-char (max beg end
))
391 (setq col-end1
(current-column))
394 (setq col-start
(min col-beg1 col-end1
))
395 (setq col-end
(max col-beg1 col-end1
))
396 (if (search-backward "\t" beg1 t
)
397 (error "sort-columns does not work with tabs. Use M-x untabify."))
398 (if (not (eq system-type
'vax-vms
))
399 ;; Use the sort utility if we can; it is 4 times as fast.
400 (call-process-region beg1 end1
"sort" t t nil
401 (if reverse
"-rt\n" "-t\n")
402 (concat "+0." col-start
)
403 (concat "-0." col-end
))
404 ;; On VMS, use Emacs's own facilities.
407 (narrow-to-region beg1 end1
)
409 (sort-subr reverse
'forward-line
'end-of-line
410 (function (lambda () (move-to-column col-start
) nil
))
411 (function (lambda () (move-to-column col-end
) nil
)))))))))
413 (defun reverse-region (beg end
)
414 "Reverse the order of lines in a region.
415 From a program takes two point or marker arguments, BEG and END."
418 (let (mid) (setq mid end end beg beg mid
)))
420 ;; put beg at the start of a line and end and the end of one --
421 ;; the largest possible region which fits this criteria
423 (or (bolp) (forward-line 1))
426 ;; the test for bolp is for those times when end is on an empty line;
427 ;; it is probably not the case that the line should be included in the
428 ;; reversal; it isn't difficult to add it afterward.
429 (or (and (eolp) (not (bolp))) (progn (forward-line -
1) (end-of-line)))
430 (setq end
(point-marker))
431 ;; the real work. this thing cranks through memory on large regions.
435 (setq ll
(cons (buffer-substring (point) (progn (end-of-line) (point)))
437 (setq do
(/= (point) end
))
438 (delete-region beg
(if do
(1+ (point)) (point))))
440 (insert (car ll
) "\n")