Initial revision
[emacs.git] / lisp / sort.el
blob235f53e57bac08ab0587fd8317ccc4d79d7e6d12
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)
9 ;; any later version.
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.
20 (provide 'sort)
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
43 is called.
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
55 same as ENDRECFUN."
56 (save-excursion
57 (message "Finding sort keys...")
58 (let* ((sort-lists (sort-build-lists nextrecfun endrecfun
59 startkeyfun endkeyfun))
60 (old (reverse sort-lists)))
61 (if (null sort-lists)
63 (or reverse (setq sort-lists (nreverse sort-lists)))
64 (message "Sorting records...")
65 (setq sort-lists
66 (if (fboundp 'sortcar)
67 (sortcar sort-lists
68 (cond ((floatp (car (car sort-lists)))
69 'f<)
70 ((numberp (car (car sort-lists)))
71 '<)
72 ((consp (car (car sort-lists)))
73 'buffer-substring-lessp)
75 'string<)))
76 (sort sort-lists
77 (cond ((floatp (car (car sort-lists)))
78 (function
79 (lambda (a b)
80 (f< (car a) (car b)))))
81 ((numberp (car (car sort-lists)))
82 (function
83 (lambda (a b)
84 (< (car a) (car b)))))
85 ((consp (car (car sort-lists)))
86 (function
87 (lambda (a b)
88 (buffer-substring-lessp (car a) (car b)))))
90 (function
91 (lambda (a 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"))
97 nil)
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 ())
108 (start-rec nil)
109 done key)
110 ;; Loop over sort records.
111 ;(goto-char (point-min)) -- it is the caller's responsibility to
112 ;arrange this if necessary
113 (while (not (eobp))
114 (setq start-rec (point)) ;save record start
115 (setq done nil)
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)
125 (cons start (point))
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.
134 (if (and (consp key)
135 (equal (car key) start-rec)
136 (equal (cdr key) (point)))
137 (cons key key)
138 (list key start-rec (point)))
139 sort-lists)))
140 (and (not done) nextrecfun (funcall nextrecfun)))
141 sort-lists))
143 (defun sort-reorder-buffer (sort-lists old)
144 (let ((inhibit-quit t)
145 (last (point-min))
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)))
153 (while sort-lists
154 (goto-char (point-max))
155 (insert-buffer-substring (current-buffer)
156 last
157 (nth 1 (car old)))
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)
164 old (cdr old)))
165 (goto-char (point-max))
166 (insert-buffer-substring (current-buffer)
167 last
168 max)
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)."
180 (interactive "P\nr")
181 (save-excursion
182 (save-restriction
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)."
191 (interactive "P\nr")
192 (save-excursion
193 (save-restriction
194 (narrow-to-region beg end)
195 (goto-char (point-min))
196 (sort-subr reverse
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)."
204 (interactive "P\nr")
205 (save-excursion
206 (save-restriction
207 (narrow-to-region beg end)
208 (goto-char (point-min))
209 (sort-subr reverse
210 (function (lambda () (skip-chars-forward "\n")))
211 'forward-page))))
213 (defvar sort-fields-syntax-table nil)
214 (if sort-fields-syntax-table nil
215 (let ((table (make-syntax-table))
216 (i 0))
217 (while (< i 256)
218 (modify-syntax-entry i "w" table)
219 (setq i (1+ i)))
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."
233 (interactive "p\nr")
234 (sort-fields-1 field beg end
235 (function (lambda ()
236 (sort-skip-fields (1- field))
237 (string-to-int
238 (buffer-substring
239 (point)
240 (save-excursion
241 ;; This is just wrong! Even without floats...
242 ;; (skip-chars-forward "[0-9]")
243 (forward-sexp 1)
244 (point))))))
245 nil))
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
253 region to sort."
254 (interactive "p\nr")
255 (sort-fields-1 field beg end
256 (function (lambda ()
257 (sort-skip-fields (1- field))
258 (string-to-float
259 (buffer-substring
260 (point)
261 (save-excursion
262 (re-search-forward
263 "[+-]?[0-9]*\.?[0-9]*\\([eE][+-]?[0-9]+\\)?")
264 (point))))))
265 nil))
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."
273 (interactive "p\nr")
274 (sort-fields-1 field beg end
275 (function (lambda ()
276 (sort-skip-fields (1- field))
277 nil))
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))
283 (unwind-protect
284 (save-excursion
285 (save-restriction
286 (narrow-to-region beg end)
287 (goto-char (point-min))
288 (set-syntax-table sort-fields-syntax-table)
289 (sort-subr nil
290 'forward-line 'end-of-line
291 startkeyfun endkeyfun)))
292 (set-syntax-table tbl))))
294 (defun sort-skip-fields (n)
295 (let ((bol (point))
296 (eol (save-excursion (end-of-line 1) (point))))
297 (if (> n 0) (forward-word n)
298 (end-of-line)
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 "\\&"))
333 (setq key-regexp 0))
334 ((string-match "\\`\\\\[1-9]\\'" key-regexp)
335 (setq key-regexp (- (aref key-regexp 1) ?0))))
336 (save-excursion
337 (save-restriction
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))
344 (sort-subr reverse
345 (function (lambda ()
346 (and (re-search-forward record-regexp nil 'move)
347 (setq sort-regexp-record-end (match-end 0))
348 (goto-char (match-beginning 0)))))
349 (function (lambda ()
350 (goto-char sort-regexp-record-end)))
351 (function (lambda ()
352 (let ((n 0))
353 (cond ((numberp key-regexp)
354 (setq n key-regexp))
355 ((re-search-forward
356 key-regexp sort-regexp-record-end t)
357 (setq n 0))
358 (t (throw 'key nil)))
359 (condition-case ()
360 (if (fboundp 'buffer-substring-lessp)
361 (cons (match-beginning n)
362 (match-end n))
363 (buffer-substring (match-beginning n)
364 (match-end 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."
383 (interactive "P\nr")
384 (save-excursion
385 (let (beg1 end1 col-beg1 col-end1 col-start col-end)
386 (goto-char (min beg end))
387 (setq col-beg1 (current-column))
388 (beginning-of-line)
389 (setq beg1 (point))
390 (goto-char (max beg end))
391 (setq col-end1 (current-column))
392 (forward-line)
393 (setq end1 (point))
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.
405 (save-excursion
406 (save-restriction
407 (narrow-to-region beg1 end1)
408 (goto-char beg1)
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."
416 (interactive "r")
417 (if (> beg end)
418 (let (mid) (setq mid end end beg beg mid)))
419 (save-excursion
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
422 (goto-char beg)
423 (or (bolp) (forward-line 1))
424 (setq beg (point))
425 (goto-char end)
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.
432 (let (ll (do t))
433 (while do
434 (goto-char beg)
435 (setq ll (cons (buffer-substring (point) (progn (end-of-line) (point)))
436 ll))
437 (setq do (/= (point) end))
438 (delete-region beg (if do (1+ (point)) (point))))
439 (while (cdr ll)
440 (insert (car ll) "\n")
441 (setq ll (cdr ll)))
442 (insert (car ll)))))