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