]> code.delx.au - gnu-emacs/blob - lisp/sort.el
(sort-build-lints): Add comment.
[gnu-emacs] / lisp / sort.el
1 ;;; sort.el --- commands to sort text in an Emacs buffer
2
3 ;; Copyright (C) 1986, 1987, 1994, 1995, 2002, 2003,
4 ;; 2004, 2005, 2006 Free Software Foundation, Inc.
5
6 ;; Author: Howie Kaye
7 ;; Maintainer: FSF
8 ;; Keywords: unix
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26
27 ;;; Commentary:
28
29 ;; This package provides the sorting facilities documented in the Emacs
30 ;; user's manual.
31
32 ;;; Code:
33
34 (defgroup sort nil
35 "Commands to sort text in an Emacs buffer."
36 :group 'data)
37
38 (defcustom sort-fold-case nil
39 "*Non-nil if the buffer sort functions should ignore case."
40 :group 'sort
41 :type 'boolean)
42
43 ;;;###autoload
44 (defun sort-subr (reverse nextrecfun endrecfun
45 &optional startkeyfun endkeyfun predicate)
46 "General text sorting routine to divide buffer into records and sort them.
47
48 We divide the accessible portion of the buffer into disjoint pieces
49 called sort records. A portion of each sort record (perhaps all of
50 it) is designated as the sort key. The records are rearranged in the
51 buffer in order by their sort keys. The records may or may not be
52 contiguous.
53
54 Usually the records are rearranged in order of ascending sort key.
55 If REVERSE is non-nil, they are rearranged in order of descending sort key.
56 The variable `sort-fold-case' determines whether alphabetic case affects
57 the sort order.
58
59 The next four arguments are functions to be called to move point
60 across a sort record. They will be called many times from within sort-subr.
61
62 NEXTRECFUN is called with point at the end of the previous record.
63 It moves point to the start of the next record.
64 It should move point to the end of the buffer if there are no more records.
65 The first record is assumed to start at the position of point when sort-subr
66 is called.
67
68 ENDRECFUN is called with point within the record.
69 It should move point to the end of the record.
70
71 STARTKEYFUN moves from the start of the record to the start of the key.
72 It may return either a non-nil value to be used as the key, or
73 else the key is the substring between the values of point after
74 STARTKEYFUN and ENDKEYFUN are called. If STARTKEYFUN is nil, the key
75 starts at the beginning of the record.
76
77 ENDKEYFUN moves from the start of the sort key to the end of the sort key.
78 ENDKEYFUN may be nil if STARTKEYFUN returns a value or if it would be the
79 same as ENDRECFUN.
80
81 PREDICATE is the function to use to compare keys. If keys are numbers,
82 it defaults to `<', otherwise it defaults to `string<'."
83 ;; Heuristically try to avoid messages if sorting a small amt of text.
84 (let ((messages (> (- (point-max) (point-min)) 50000)))
85 (save-excursion
86 (if messages (message "Finding sort keys..."))
87 (let* ((sort-lists (sort-build-lists nextrecfun endrecfun
88 startkeyfun endkeyfun))
89 (old (reverse sort-lists))
90 (case-fold-search sort-fold-case))
91 (if (null sort-lists)
92 ()
93 (or reverse (setq sort-lists (nreverse sort-lists)))
94 (if messages (message "Sorting records..."))
95 (setq sort-lists
96 (sort sort-lists
97 (cond (predicate
98 `(lambda (a b) (,predicate (car a) (car b))))
99 ((numberp (car (car sort-lists)))
100 'car-less-than-car)
101 ((consp (car (car sort-lists)))
102 (lambda (a b)
103 (> 0 (compare-buffer-substrings
104 nil (car (car a)) (cdr (car a))
105 nil (car (car b)) (cdr (car b))))))
106 (t
107 (lambda (a b) (string< (car a) (car b)))))))
108 (if reverse (setq sort-lists (nreverse sort-lists)))
109 (if messages (message "Reordering buffer..."))
110 (sort-reorder-buffer sort-lists old)))
111 (if messages (message "Reordering buffer... Done"))))
112 nil)
113
114 ;; Parse buffer into records using the arguments as Lisp expressions;
115 ;; return a list of records. Each record looks like (KEY STARTPOS . ENDPOS)
116 ;; where KEY is the sort key (a number or string),
117 ;; and STARTPOS and ENDPOS are the bounds of this record in the buffer.
118
119 ;; The records appear in the list lastmost first!
120
121 (defun sort-build-lists (nextrecfun endrecfun startkeyfun endkeyfun)
122 (let ((sort-lists ())
123 (start-rec nil)
124 ;; To avoid such functins as `end-of-line' being affected by
125 ;; fields.
126 (inhibit-field-text-motion t)
127 done key)
128 ;; Loop over sort records.
129 ;(goto-char (point-min)) -- it is the caller's responsibility to
130 ;arrange this if necessary
131 (while (not (eobp))
132 (setq start-rec (point)) ;save record start
133 (setq done nil)
134 ;; Get key value, or move to start of key.
135 (setq key (catch 'key
136 (or (and startkeyfun (funcall startkeyfun))
137 ;; If key was not returned as value,
138 ;; move to end of key and get key from the buffer.
139 (let ((start (point)))
140 (funcall (or endkeyfun
141 (prog1 endrecfun (setq done t))))
142 (cons start (point))))))
143 ;; Move to end of this record (start of next one, or end of buffer).
144 (cond ((prog1 done (setq done nil)))
145 (endrecfun (funcall endrecfun))
146 (nextrecfun (funcall nextrecfun) (setq done t)))
147 (if key (push
148 ;; consing optimization in case in which key is same as record.
149 (if (and (consp key)
150 (equal (car key) start-rec)
151 (equal (cdr key) (point)))
152 (cons key key)
153 (cons key (cons start-rec (point))))
154 sort-lists))
155 (and (not done) nextrecfun (funcall nextrecfun)))
156 sort-lists))
157
158 (defun sort-reorder-buffer (sort-lists old)
159 (let ((last (point-min))
160 (min (point-min)) (max (point-max))
161 (old-buffer (current-buffer))
162 temp-buffer)
163 (with-temp-buffer
164 ;; Record the temporary buffer.
165 (setq temp-buffer (current-buffer))
166
167 ;; Copy the sorted text into the temporary buffer.
168 (while sort-lists
169 (goto-char (point-max))
170 (insert-buffer-substring old-buffer
171 last
172 (nth 1 (car old)))
173 (goto-char (point-max))
174 (insert-buffer-substring old-buffer
175 (nth 1 (car sort-lists))
176 (cdr (cdr (car sort-lists))))
177 (setq last (cdr (cdr (car old)))
178 sort-lists (cdr sort-lists)
179 old (cdr old)))
180 (goto-char (point-max))
181 (insert-buffer-substring old-buffer last max)
182
183 ;; Copy the reordered text from the temporary buffer
184 ;; to the buffer we sorted (OLD-BUFFER).
185 (set-buffer old-buffer)
186 (let ((inhibit-quit t))
187 ;; Make sure insertions done for reordering
188 ;; saves any markers at the end of the sorted region,
189 ;; by leaving the last character of the region.
190 (delete-region min (1- max))
191 ;; Now replace the one remaining old character with the sorted text.
192 (goto-char (point-min))
193 (insert-buffer-substring temp-buffer)
194 (delete-region max (1+ max))))))
195
196 ;;;###autoload
197 (defun sort-lines (reverse beg end)
198 "Sort lines in region alphabetically; argument means descending order.
199 Called from a program, there are three arguments:
200 REVERSE (non-nil means reverse order), BEG and END (region to sort).
201 The variable `sort-fold-case' determines whether alphabetic case affects
202 the sort order."
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 'forward-line 'end-of-line))))
209
210 ;;;###autoload
211 (defun sort-paragraphs (reverse beg end)
212 "Sort paragraphs in region alphabetically; argument means descending order.
213 Called from a program, there are three arguments:
214 REVERSE (non-nil means reverse order), BEG and END (region to sort).
215 The variable `sort-fold-case' determines whether alphabetic case affects
216 the sort order."
217 (interactive "P\nr")
218 (save-excursion
219 (save-restriction
220 (narrow-to-region beg end)
221 (goto-char (point-min))
222 (sort-subr reverse
223 (function
224 (lambda ()
225 (while (and (not (eobp)) (looking-at paragraph-separate))
226 (forward-line 1))))
227 'forward-paragraph))))
228
229 ;;;###autoload
230 (defun sort-pages (reverse beg end)
231 "Sort pages in region alphabetically; argument means descending order.
232 Called from a program, there are three arguments:
233 REVERSE (non-nil means reverse order), BEG and END (region to sort).
234 The variable `sort-fold-case' determines whether alphabetic case affects
235 the sort order."
236 (interactive "P\nr")
237 (save-excursion
238 (save-restriction
239 (narrow-to-region beg end)
240 (goto-char (point-min))
241 (sort-subr reverse
242 (function (lambda () (skip-chars-forward "\n")))
243 'forward-page))))
244 \f
245 (defvar sort-fields-syntax-table nil)
246 (if sort-fields-syntax-table nil
247 (let ((table (make-syntax-table))
248 (i 0))
249 (while (< i 256)
250 (modify-syntax-entry i "w" table)
251 (setq i (1+ i)))
252 (modify-syntax-entry ?\ " " table)
253 (modify-syntax-entry ?\t " " table)
254 (modify-syntax-entry ?\n " " table)
255 (modify-syntax-entry ?\. "_" table) ; for floating pt. numbers. -wsr
256 (setq sort-fields-syntax-table table)))
257
258 (defcustom sort-numeric-base 10
259 "*The default base used by `sort-numeric-fields'."
260 :group 'sort
261 :type 'integer)
262
263 ;;;###autoload
264 (defun sort-numeric-fields (field beg end)
265 "Sort lines in region numerically by the ARGth field of each line.
266 Fields are separated by whitespace and numbered from 1 up.
267 Specified field must contain a number in each line of the region,
268 which may begin with \"0x\" or \"0\" for hexadecimal and octal values.
269 Otherwise, the number is interpreted according to sort-numeric-base.
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 (lambda ()
276 (sort-skip-fields field)
277 (let* ((case-fold-search t)
278 (base
279 (if (looking-at "\\(0x\\)[0-9a-f]\\|\\(0\\)[0-7]")
280 (cond ((match-beginning 1)
281 (goto-char (match-end 1))
282 16)
283 ((match-beginning 2)
284 (goto-char (match-end 2))
285 8)
286 (t nil)))))
287 (string-to-number (buffer-substring (point)
288 (save-excursion
289 (forward-sexp 1)
290 (point)))
291 (or base sort-numeric-base))))
292 nil))
293
294 ;;;;;###autoload
295 ;;(defun sort-float-fields (field beg end)
296 ;; "Sort lines in region numerically by the ARGth field of each line.
297 ;;Fields are separated by whitespace and numbered from 1 up. Specified field
298 ;;must contain a floating point number in each line of the region. With a
299 ;;negative arg, sorts by the ARGth field counted from the right. Called from a
300 ;;program, there are three arguments: FIELD, BEG and END. BEG and END specify
301 ;;region to sort."
302 ;; (interactive "p\nr")
303 ;; (sort-fields-1 field beg end
304 ;; (function (lambda ()
305 ;; (sort-skip-fields field)
306 ;; (string-to-number
307 ;; (buffer-substring
308 ;; (point)
309 ;; (save-excursion
310 ;; (re-search-forward
311 ;; "[+-]?[0-9]*\.?[0-9]*\\([eE][+-]?[0-9]+\\)?")
312 ;; (point))))))
313 ;; nil))
314
315 ;;;###autoload
316 (defun sort-fields (field beg end)
317 "Sort lines in region lexicographically by the ARGth field of each line.
318 Fields are separated by whitespace and numbered from 1 up.
319 With a negative arg, sorts by the ARGth field counted from the right.
320 Called from a program, there are three arguments:
321 FIELD, BEG and END. BEG and END specify region to sort.
322 The variable `sort-fold-case' determines whether alphabetic case affects
323 the sort order."
324 (interactive "p\nr")
325 (sort-fields-1 field beg end
326 (function (lambda ()
327 (sort-skip-fields field)
328 nil))
329 (function (lambda () (skip-chars-forward "^ \t\n")))))
330
331 (defun sort-fields-1 (field beg end startkeyfun endkeyfun)
332 (let ((tbl (syntax-table)))
333 (if (zerop field) (setq field 1))
334 (unwind-protect
335 (save-excursion
336 (save-restriction
337 (narrow-to-region beg end)
338 (goto-char (point-min))
339 (set-syntax-table sort-fields-syntax-table)
340 (sort-subr nil
341 'forward-line 'end-of-line
342 startkeyfun endkeyfun)))
343 (set-syntax-table tbl))))
344
345 ;; Position at the beginning of field N on the current line,
346 ;; assuming point is initially at the beginning of the line.
347 (defun sort-skip-fields (n)
348 (if (> n 0)
349 ;; Skip across N - 1 fields.
350 (let ((i (1- n)))
351 (while (> i 0)
352 (skip-chars-forward " \t")
353 (skip-chars-forward "^ \t\n")
354 (setq i (1- i)))
355 (skip-chars-forward " \t")
356 (if (eolp)
357 (error "Line has too few fields: %s"
358 (buffer-substring
359 (save-excursion (beginning-of-line) (point))
360 (save-excursion (end-of-line) (point))))))
361 (end-of-line)
362 ;; Skip back across - N - 1 fields.
363 (let ((i (1- (- n))))
364 (while (> i 0)
365 (skip-chars-backward " \t")
366 (skip-chars-backward "^ \t\n")
367 (setq i (1- i)))
368 (skip-chars-backward " \t"))
369 (if (bolp)
370 (error "Line has too few fields: %s"
371 (buffer-substring
372 (save-excursion (beginning-of-line) (point))
373 (save-excursion (end-of-line) (point)))))
374 ;; Position at the front of the field
375 ;; even if moving backwards.
376 (skip-chars-backward "^ \t\n")))
377 \f
378 (defvar sort-regexp-fields-regexp)
379 (defvar sort-regexp-record-end)
380
381 ;; Move to the beginning of the next match for record-regexp,
382 ;; and set sort-regexp-record-end to the end of that match.
383 ;; If the next match is empty and does not advance point,
384 ;; skip one character and try again.
385 (defun sort-regexp-fields-next-record ()
386 (let ((oldpos (point)))
387 (and (re-search-forward sort-regexp-fields-regexp nil 'move)
388 (setq sort-regexp-record-end (match-end 0))
389 (if (= sort-regexp-record-end oldpos)
390 (progn
391 (forward-char 1)
392 (re-search-forward sort-regexp-fields-regexp nil 'move)
393 (setq sort-regexp-record-end (match-end 0)))
394 t)
395 (goto-char (match-beginning 0)))))
396
397 ;;;###autoload
398 (defun sort-regexp-fields (reverse record-regexp key-regexp beg end)
399 "Sort the region lexicographically as specified by RECORD-REGEXP and KEY.
400 RECORD-REGEXP specifies the textual units which should be sorted.
401 For example, to sort lines RECORD-REGEXP would be \"^.*$\"
402 KEY specifies the part of each record (ie each match for RECORD-REGEXP)
403 is to be used for sorting.
404 If it is \"\\\\digit\" then the digit'th \"\\\\(...\\\\)\" match field from
405 RECORD-REGEXP is used.
406 If it is \"\\\\&\" then the whole record is used.
407 Otherwise, it is a regular-expression for which to search within the record.
408 If a match for KEY is not found within a record then that record is ignored.
409
410 With a negative prefix arg sorts in reverse order.
411
412 The variable `sort-fold-case' determines whether alphabetic case affects
413 the sort order.
414
415 For example: to sort lines in the region by the first word on each line
416 starting with the letter \"f\",
417 RECORD-REGEXP would be \"^.*$\" and KEY would be \"\\\\=\\<f\\\\w*\\\\>\""
418 ;; using negative prefix arg to mean "reverse" is now inconsistent with
419 ;; other sort-.*fields functions but then again this was before, since it
420 ;; didn't use the magnitude of the arg to specify anything.
421 (interactive "P\nsRegexp specifying records to sort:
422 sRegexp specifying key within record: \nr")
423 (cond ((or (equal key-regexp "") (equal key-regexp "\\&"))
424 (setq key-regexp 0))
425 ((string-match "\\`\\\\[1-9]\\'" key-regexp)
426 (setq key-regexp (- (aref key-regexp 1) ?0))))
427 (save-excursion
428 (save-restriction
429 (narrow-to-region beg end)
430 (goto-char (point-min))
431 (let (sort-regexp-record-end
432 (sort-regexp-fields-regexp record-regexp))
433 (re-search-forward sort-regexp-fields-regexp nil t)
434 (setq sort-regexp-record-end (point))
435 (goto-char (match-beginning 0))
436 (sort-subr reverse
437 'sort-regexp-fields-next-record
438 (function (lambda ()
439 (goto-char sort-regexp-record-end)))
440 (function (lambda ()
441 (let ((n 0))
442 (cond ((numberp key-regexp)
443 (setq n key-regexp))
444 ((re-search-forward
445 key-regexp sort-regexp-record-end t)
446 (setq n 0))
447 (t (throw 'key nil)))
448 (condition-case ()
449 (cons (match-beginning n)
450 (match-end n))
451 ;; if there was no such register
452 (error (throw 'key nil)))))))))))
453
454 \f
455 (defvar sort-columns-subprocess t)
456
457 ;;;###autoload
458 (defun sort-columns (reverse &optional beg end)
459 "Sort lines in region alphabetically by a certain range of columns.
460 For the purpose of this command, the region BEG...END includes
461 the entire line that point is in and the entire line the mark is in.
462 The column positions of point and mark bound the range of columns to sort on.
463 A prefix argument means sort into REVERSE order.
464 The variable `sort-fold-case' determines whether alphabetic case affects
465 the sort order.
466
467 Note that `sort-columns' rejects text that contains tabs,
468 because tabs could be split across the specified columns
469 and it doesn't know how to handle that. Also, when possible,
470 it uses the `sort' utility program, which doesn't understand tabs.
471 Use \\[untabify] to convert tabs to spaces before sorting."
472 (interactive "P\nr")
473 (save-excursion
474 (let (beg1 end1 col-beg1 col-end1 col-start col-end)
475 (goto-char (min beg end))
476 (setq col-beg1 (current-column))
477 (beginning-of-line)
478 (setq beg1 (point))
479 (goto-char (max beg end))
480 (setq col-end1 (current-column))
481 (forward-line)
482 (setq end1 (point))
483 (setq col-start (min col-beg1 col-end1))
484 (setq col-end (max col-beg1 col-end1))
485 (if (search-backward "\t" beg1 t)
486 (error "sort-columns does not work with tabs -- use M-x untabify"))
487 (if (not (or (memq system-type '(vax-vms windows-nt))
488 (let ((pos beg1) plist fontified)
489 (catch 'found
490 (while (< pos end1)
491 (setq plist (text-properties-at pos))
492 (setq fontified (plist-get plist 'fontified))
493 (while (consp plist)
494 (unless (or (eq (car plist) 'fontified)
495 (and (eq (car plist) 'face)
496 fontified))
497 (throw 'found t))
498 (setq plist (cddr plist)))
499 (setq pos (next-property-change pos nil end1)))))))
500 ;; Use the sort utility if we can; it is 4 times as fast.
501 ;; Do not use it if there are any non-font-lock properties
502 ;; in the region, since the sort utility would lose the
503 ;; properties.
504 (let ((sort-args (list (if reverse "-rt\n" "-t\n")
505 (format "-k1.%d,1.%d"
506 (1+ col-start)
507 (1+ col-end)))))
508 (when sort-fold-case
509 (push "-f" sort-args))
510 (apply #'call-process-region beg1 end1 "sort" t t nil sort-args))
511 ;; On VMS and ms-windows, use Emacs's own facilities.
512 (save-excursion
513 (save-restriction
514 (narrow-to-region beg1 end1)
515 (goto-char beg1)
516 (sort-subr reverse 'forward-line 'end-of-line
517 #'(lambda () (move-to-column col-start) nil)
518 #'(lambda () (move-to-column col-end) nil))))))))
519
520 ;;;###autoload
521 (defun reverse-region (beg end)
522 "Reverse the order of lines in a region.
523 From a program takes two point or marker arguments, BEG and END."
524 (interactive "r")
525 (if (> beg end)
526 (let (mid) (setq mid end end beg beg mid)))
527 (save-excursion
528 ;; put beg at the start of a line and end and the end of one --
529 ;; the largest possible region which fits this criteria
530 (goto-char beg)
531 (or (bolp) (forward-line 1))
532 (setq beg (point))
533 (goto-char end)
534 ;; the test for bolp is for those times when end is on an empty line;
535 ;; it is probably not the case that the line should be included in the
536 ;; reversal; it isn't difficult to add it afterward.
537 (or (and (eolp) (not (bolp))) (progn (forward-line -1) (end-of-line)))
538 (setq end (point-marker))
539 ;; the real work. this thing cranks through memory on large regions.
540 (let (ll (do t))
541 (while do
542 (goto-char beg)
543 (setq ll (cons (buffer-substring (point) (progn (end-of-line) (point)))
544 ll))
545 (setq do (/= (point) end))
546 (delete-region beg (if do (1+ (point)) (point))))
547 (while (cdr ll)
548 (insert (car ll) "\n")
549 (setq ll (cdr ll)))
550 (insert (car ll)))))
551
552 (provide 'sort)
553
554 ;;; arch-tag: fbac12be-2a7b-4c8a-9665-264d61f70bd9
555 ;;; sort.el ends here