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