]> code.delx.au - gnu-emacs/blob - lisp/sort.el
Initial revision
[gnu-emacs] / lisp / sort.el
1 ;; Commands to sort text in an Emacs buffer.
2 ;; Copyright (C) 1986, 1987 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 1, 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 (provide 'sort)
21
22 ;; Original version of most of this contributed by Howie Kaye
23
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.
27
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.
32
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.
35
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.
38
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.
44
45 ENDRECFUN is is called with point within the record.
46 It should move point to the end of the record.
47
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 STARTKEYFUN and ENDKEYFUN are called. If STARTKEYFUN is nil, the key
52 starts at the beginning of the record.
53
54 ENDKEYFUN moves from the start of the sort key to the end of the sort key.
55 ENDKEYFUN may be nil if STARTKEYFUN returns a value or if it would be the
56 same as ENDRECFUN."
57 (save-excursion
58 (message "Finding sort keys...")
59 (let* ((sort-lists (sort-build-lists nextrecfun endrecfun
60 startkeyfun endkeyfun))
61 (old (reverse sort-lists)))
62 (if (null sort-lists)
63 ()
64 (or reverse (setq sort-lists (nreverse sort-lists)))
65 (message "Sorting records...")
66 (setq sort-lists
67 (if (fboundp 'sortcar)
68 (sortcar sort-lists
69 (cond ((numberp (car (car sort-lists)))
70 ;; This handles both ints and floats.
71 '<)
72 ((consp (car (car sort-lists)))
73 'buffer-substring-lessp)
74 (t
75 'string<)))
76 (sort sort-lists
77 (cond ((numberp (car (car sort-lists)))
78 (function
79 (lambda (a b)
80 (< (car a) (car b)))))
81 ((consp (car (car sort-lists)))
82 (function
83 (lambda (a b)
84 (buffer-substring-lessp (car a) (car b)))))
85 (t
86 (function
87 (lambda (a b)
88 (string< (car a) (car b)))))))))
89 (if reverse (setq sort-lists (nreverse sort-lists)))
90 (message "Reordering buffer...")
91 (sort-reorder-buffer sort-lists old)))
92 (message "Reordering buffer... Done"))
93 nil)
94
95 ;; Parse buffer into records using the arguments as Lisp expressions;
96 ;; return a list of records. Each record looks like (KEY STARTPOS . ENDPOS)
97 ;; where KEY is the sort key (a number or string),
98 ;; and STARTPOS and ENDPOS are the bounds of this record in the buffer.
99
100 ;; The records appear in the list lastmost first!
101
102 (defun sort-build-lists (nextrecfun endrecfun startkeyfun endkeyfun)
103 (let ((sort-lists ())
104 (start-rec nil)
105 done key)
106 ;; Loop over sort records.
107 ;(goto-char (point-min)) -- it is the caller's responsibility to
108 ;arrange this if necessary
109 (while (not (eobp))
110 (setq start-rec (point)) ;save record start
111 (setq done nil)
112 ;; Get key value, or move to start of key.
113 (setq key (catch 'key
114 (or (and startkeyfun (funcall startkeyfun))
115 ;; If key was not returned as value,
116 ;; move to end of key and get key from the buffer.
117 (let ((start (point)))
118 (funcall (or endkeyfun
119 (prog1 endrecfun (setq done t))))
120 (if (fboundp 'buffer-substring-lessp)
121 (cons start (point))
122 (buffer-substring start (point)))))))
123 ;; Move to end of this record (start of next one, or end of buffer).
124 (cond ((prog1 done (setq done nil)))
125 (endrecfun (funcall endrecfun))
126 (nextrecfun (funcall nextrecfun) (setq done t)))
127 (if key (setq sort-lists (cons
128 ;; consing optimization in case in which key
129 ;; is same as record.
130 (if (and (consp key)
131 (equal (car key) start-rec)
132 (equal (cdr key) (point)))
133 (cons key key)
134 (cons key (cons start-rec (point))))
135 sort-lists)))
136 (and (not done) nextrecfun (funcall nextrecfun)))
137 sort-lists))
138
139 (defun sort-reorder-buffer (sort-lists old)
140 (let ((inhibit-quit t)
141 (last (point-min))
142 (min (point-min)) (max (point-max)))
143 ;; Make sure insertions done for reordering
144 ;; do not go after any markers at the end of the sorted region,
145 ;; by inserting a space to separate them.
146 (goto-char (point-max))
147 (insert-before-markers " ")
148 (narrow-to-region min (1- (point-max)))
149 (while sort-lists
150 (goto-char (point-max))
151 (insert-buffer-substring (current-buffer)
152 last
153 (nth 1 (car old)))
154 (goto-char (point-max))
155 (insert-buffer-substring (current-buffer)
156 (nth 1 (car sort-lists))
157 (cdr (cdr (car sort-lists))))
158 (setq last (cdr (cdr (car old)))
159 sort-lists (cdr sort-lists)
160 old (cdr old)))
161 (goto-char (point-max))
162 (insert-buffer-substring (current-buffer)
163 last
164 max)
165 ;; Delete the original copy of the text.
166 (delete-region min max)
167 ;; Get rid of the separator " ".
168 (goto-char (point-max))
169 (narrow-to-region min (1+ (point)))
170 (delete-region (point) (1+ (point)))))
171
172 ;;;###autoload
173 (defun sort-lines (reverse beg end)
174 "Sort lines in region alphabetically; argument means descending order.
175 Called from a program, there are three arguments:
176 REVERSE (non-nil means reverse order), BEG and END (region to sort)."
177 (interactive "P\nr")
178 (save-excursion
179 (save-restriction
180 (narrow-to-region beg end)
181 (goto-char (point-min))
182 (sort-subr reverse 'forward-line 'end-of-line))))
183
184 ;;;###autoload
185 (defun sort-paragraphs (reverse beg end)
186 "Sort paragraphs in region alphabetically; argument means descending order.
187 Called from a program, there are three arguments:
188 REVERSE (non-nil means reverse order), BEG and END (region to sort)."
189 (interactive "P\nr")
190 (save-excursion
191 (save-restriction
192 (narrow-to-region beg end)
193 (goto-char (point-min))
194 (sort-subr reverse
195 (function (lambda () (skip-chars-forward "\n \t\f")))
196 'forward-paragraph))))
197
198 ;;;###autoload
199 (defun sort-pages (reverse beg end)
200 "Sort pages in region alphabetically; argument means descending order.
201 Called from a program, there are three arguments:
202 REVERSE (non-nil means reverse order), BEG and END (region to sort)."
203 (interactive "P\nr")
204 (save-excursion
205 (save-restriction
206 (narrow-to-region beg end)
207 (goto-char (point-min))
208 (sort-subr reverse
209 (function (lambda () (skip-chars-forward "\n")))
210 'forward-page))))
211 \f
212 (defvar sort-fields-syntax-table nil)
213 (if sort-fields-syntax-table nil
214 (let ((table (make-syntax-table))
215 (i 0))
216 (while (< i 256)
217 (modify-syntax-entry i "w" table)
218 (setq i (1+ i)))
219 (modify-syntax-entry ?\ " " table)
220 (modify-syntax-entry ?\t " " table)
221 (modify-syntax-entry ?\n " " table)
222 (modify-syntax-entry ?\. "_" table) ; for floating pt. numbers. -wsr
223 (setq sort-fields-syntax-table table)))
224
225 ;;;###autoload
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))
246
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))
266
267 ;;;###autoload
268 (defun sort-fields (field beg end)
269 "Sort lines in region lexicographically by the ARGth field of each line.
270 Fields are separated by whitespace and numbered from 1 up.
271 With a negative arg, sorts by the ARGth field counted from the right.
272 Called from a program, there are three arguments:
273 FIELD, BEG and END. BEG and END specify region to sort."
274 (interactive "p\nr")
275 (sort-fields-1 field beg end
276 (function (lambda ()
277 (sort-skip-fields (1- field))
278 nil))
279 (function (lambda () (skip-chars-forward "^ \t\n")))))
280
281 (defun sort-fields-1 (field beg end startkeyfun endkeyfun)
282 (let ((tbl (syntax-table)))
283 (if (zerop field) (setq field 1))
284 (unwind-protect
285 (save-excursion
286 (save-restriction
287 (narrow-to-region beg end)
288 (goto-char (point-min))
289 (set-syntax-table sort-fields-syntax-table)
290 (sort-subr nil
291 'forward-line 'end-of-line
292 startkeyfun endkeyfun)))
293 (set-syntax-table tbl))))
294
295 (defun sort-skip-fields (n)
296 (let ((bol (point))
297 (eol (save-excursion (end-of-line 1) (point))))
298 (if (> n 0) (forward-word n)
299 (end-of-line)
300 (forward-word (1+ n)))
301 (if (or (and (>= (point) eol) (> n 0))
302 ;; this is marginally wrong; if the first line of the sort
303 ;; at bob has the wrong number of fields the error won't be
304 ;; reported until the next short line.
305 (and (< (point) bol) (< n 0)))
306 (error "Line has too few fields: %s"
307 (buffer-substring bol eol)))
308 (skip-chars-forward " \t")))
309
310 \f
311 ;;;###autoload
312 (defun sort-regexp-fields (reverse record-regexp key-regexp beg end)
313 "Sort the region lexicographically as specifed by RECORD-REGEXP and KEY.
314 RECORD-REGEXP specifies the textual units which should be sorted.
315 For example, to sort lines RECORD-REGEXP would be \"^.*$\"
316 KEY specifies the part of each record (ie each match for RECORD-REGEXP)
317 is to be used for sorting.
318 If it is \"\\digit\" then the digit'th \"\\(...\\)\" match field from
319 RECORD-REGEXP is used.
320 If it is \"\\&\" then the whole record is used.
321 Otherwise, it is a regular-expression for which to search within the record.
322 If a match for KEY is not found within a record then that record is ignored.
323
324 With a negative prefix arg sorts in reverse order.
325
326 For example: to sort lines in the region by the first word on each line
327 starting with the letter \"f\",
328 RECORD-REGEXP would be \"^.*$\" and KEY would be \"\\=\\<f\\w*\\>\""
329 ;; using negative prefix arg to mean "reverse" is now inconsistent with
330 ;; other sort-.*fields functions but then again this was before, since it
331 ;; didn't use the magnitude of the arg to specify anything.
332 (interactive "P\nsRegexp specifying records to sort:
333 sRegexp specifying key within record: \nr")
334 (cond ((or (equal key-regexp "") (equal key-regexp "\\&"))
335 (setq key-regexp 0))
336 ((string-match "\\`\\\\[1-9]\\'" key-regexp)
337 (setq key-regexp (- (aref key-regexp 1) ?0))))
338 (save-excursion
339 (save-restriction
340 (narrow-to-region beg end)
341 (goto-char (point-min))
342 (let (sort-regexp-record-end) ;isn't dynamic scoping wonderful?
343 (re-search-forward record-regexp)
344 (setq sort-regexp-record-end (point))
345 (goto-char (match-beginning 0))
346 (sort-subr reverse
347 (function (lambda ()
348 (and (re-search-forward record-regexp nil 'move)
349 (setq sort-regexp-record-end (match-end 0))
350 (goto-char (match-beginning 0)))))
351 (function (lambda ()
352 (goto-char sort-regexp-record-end)))
353 (function (lambda ()
354 (let ((n 0))
355 (cond ((numberp key-regexp)
356 (setq n key-regexp))
357 ((re-search-forward
358 key-regexp sort-regexp-record-end t)
359 (setq n 0))
360 (t (throw 'key nil)))
361 (condition-case ()
362 (if (fboundp 'buffer-substring-lessp)
363 (cons (match-beginning n)
364 (match-end n))
365 (buffer-substring (match-beginning n)
366 (match-end n)))
367 ;; if there was no such register
368 (error (throw 'key nil)))))))))))
369
370 \f
371 (defvar sort-columns-subprocess t)
372
373 ;;;###autoload
374 (defun sort-columns (reverse &optional beg end)
375 "Sort lines in region alphabetically by a certain range of columns.
376 For the purpose of this command, the region includes
377 the entire line that point is in and the entire line the mark is in.
378 The column positions of point and mark bound the range of columns to sort on.
379 A prefix argument means sort into reverse order.
380
381 Note that `sort-columns' rejects text that contains tabs,
382 because tabs could be split across the specified columns
383 and it doesn't know how to handle that. Also, when possible,
384 it uses the `sort' utility program, which doesn't understand tabs.
385 Use \\[untabify] to convert tabs to spaces before sorting."
386 (interactive "P\nr")
387 (save-excursion
388 (let (beg1 end1 col-beg1 col-end1 col-start col-end)
389 (goto-char (min beg end))
390 (setq col-beg1 (current-column))
391 (beginning-of-line)
392 (setq beg1 (point))
393 (goto-char (max beg end))
394 (setq col-end1 (current-column))
395 (forward-line)
396 (setq end1 (point))
397 (setq col-start (min col-beg1 col-end1))
398 (setq col-end (max col-beg1 col-end1))
399 (if (search-backward "\t" beg1 t)
400 (error "sort-columns does not work with tabs. Use M-x untabify."))
401 (if (not (eq system-type 'vax-vms))
402 ;; Use the sort utility if we can; it is 4 times as fast.
403 (call-process-region beg1 end1 "sort" t t nil
404 (if reverse "-rt\n" "-t\n")
405 (concat "+0." col-start)
406 (concat "-0." col-end))
407 ;; On VMS, use Emacs's own facilities.
408 (save-excursion
409 (save-restriction
410 (narrow-to-region beg1 end1)
411 (goto-char beg1)
412 (sort-subr reverse 'forward-line 'end-of-line
413 (function (lambda () (move-to-column col-start) nil))
414 (function (lambda () (move-to-column col-end) nil)))))))))
415
416 ;;;###autoload
417 (defun reverse-region (beg end)
418 "Reverse the order of lines in a region.
419 From a program takes two point or marker arguments, BEG and END."
420 (interactive "r")
421 (if (> beg end)
422 (let (mid) (setq mid end end beg beg mid)))
423 (save-excursion
424 ;; put beg at the start of a line and end and the end of one --
425 ;; the largest possible region which fits this criteria
426 (goto-char beg)
427 (or (bolp) (forward-line 1))
428 (setq beg (point))
429 (goto-char end)
430 ;; the test for bolp is for those times when end is on an empty line;
431 ;; it is probably not the case that the line should be included in the
432 ;; reversal; it isn't difficult to add it afterward.
433 (or (and (eolp) (not (bolp))) (progn (forward-line -1) (end-of-line)))
434 (setq end (point-marker))
435 ;; the real work. this thing cranks through memory on large regions.
436 (let (ll (do t))
437 (while do
438 (goto-char beg)
439 (setq ll (cons (buffer-substring (point) (progn (end-of-line) (point)))
440 ll))
441 (setq do (/= (point) end))
442 (delete-region beg (if do (1+ (point)) (point))))
443 (while (cdr ll)
444 (insert (car ll) "\n")
445 (setq ll (cdr ll)))
446 (insert (car ll)))))