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