1 ;;; sort.el --- commands to sort text in an Emacs buffer
3 ;; Copyright (C) 1986-1987, 1994-1995, 2001-2011 Free Software Foundation, Inc.
9 ;; This file is part of GNU Emacs.
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.
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.
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/>.
26 ;; This package provides the sorting facilities documented in the Emacs
32 "Commands to sort text in an Emacs buffer."
35 (defcustom sort-fold-case nil
36 "Non-nil if the buffer sort functions should ignore case."
39 ;;;###autoload(put 'sort-fold-case 'safe-local-variable 'booleanp)
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.
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
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
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.
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
66 ENDRECFUN is called with point within the record.
67 It should move point to the end of the record.
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.
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
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)))
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))
91 (or reverse (setq sort-lists (nreverse sort-lists)))
92 (if messages (message "Sorting records..."))
96 `(lambda (a b) (,predicate (car a) (car b))))
97 ((numberp (car (car sort-lists)))
99 ((consp (car (car sort-lists)))
101 (> 0 (compare-buffer-substrings
102 nil (car (car a)) (cdr (car a))
103 nil (car (car b)) (cdr (car b))))))
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"))))
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.
117 ;; The records appear in the list lastmost first!
119 (defun sort-build-lists (nextrecfun endrecfun startkeyfun endkeyfun)
120 (let ((sort-lists ())
123 ;; Loop over sort records.
124 ;(goto-char (point-min)) -- it is the caller's responsibility to
125 ;arrange this if necessary
127 (setq start-rec (point)) ;save record start
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)))
143 ;; consing optimization in case in which key is same as record.
145 (equal (car key) start-rec)
146 (equal (cdr key) (point)))
148 (cons key (cons start-rec (point))))
150 (and (not done) nextrecfun (funcall nextrecfun)))
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)
160 (set-buffer-multibyte mb)
161 ;; Record the temporary buffer.
162 (setq temp-buffer (current-buffer))
164 ;; Copy the sorted text into the temporary buffer.
166 (goto-char (point-max))
167 (insert-buffer-substring old-buffer
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)
177 (goto-char (point-max))
178 (insert-buffer-substring old-buffer last max)
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))))))
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
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)))))
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
219 (narrow-to-region beg end)
220 (goto-char (point-min))
224 (while (and (not (eobp)) (looking-at paragraph-separate))
226 'forward-paragraph))))
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
238 (narrow-to-region beg end)
239 (goto-char (point-min))
241 (function (lambda () (skip-chars-forward "\n")))
244 (defvar sort-fields-syntax-table nil)
245 (if sort-fields-syntax-table nil
246 (let ((table (make-syntax-table))
249 (modify-syntax-entry i "w" table)
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)))
257 (defcustom sort-numeric-base 10
258 "The default base used by `sort-numeric-fields'."
261 ;;;###autoload(put 'sort-numeric-base 'safe-local-variable 'integerp)
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."
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
278 (sort-skip-fields field)
279 (let* ((case-fold-search t)
281 (if (looking-at "\\(0x\\)[0-9a-f]\\|\\(0\\)[0-7]")
282 (cond ((match-beginning 1)
283 (goto-char (match-end 1))
286 (goto-char (match-end 2))
289 (string-to-number (buffer-substring (point)
293 (or base sort-numeric-base))))
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
304 ;; (interactive "p\nr")
305 ;; (sort-fields-1 field beg end
306 ;; (function (lambda ()
307 ;; (sort-skip-fields field)
312 ;; (re-search-forward
313 ;; "[+-]?[0-9]*\.?[0-9]*\\([eE][+-]?[0-9]+\\)?")
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
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
331 (sort-skip-fields field)
333 (function (lambda () (skip-chars-forward "^ \t\n"))))))
335 (defun sort-fields-1 (field beg end startkeyfun endkeyfun)
336 (let ((tbl (syntax-table)))
337 (if (zerop field) (setq field 1))
341 (narrow-to-region beg end)
342 (goto-char (point-min))
343 (set-syntax-table sort-fields-syntax-table)
345 'forward-line 'end-of-line
346 startkeyfun endkeyfun)))
347 (set-syntax-table tbl))))
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)
353 ;; Skip across N - 1 fields.
356 (skip-chars-forward " \t")
357 (skip-chars-forward "^ \t\n")
359 (skip-chars-forward " \t")
361 (error "Line has too few fields: %s"
363 (line-beginning-position)
364 (line-end-position)))))
366 ;; Skip back across - N - 1 fields.
367 (let ((i (1- (- n))))
369 (skip-chars-backward " \t")
370 (skip-chars-backward "^ \t\n")
372 (skip-chars-backward " \t"))
374 (error "Line has too few fields: %s"
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")))
382 (defvar sort-regexp-fields-regexp)
383 (defvar sort-regexp-record-end)
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)
396 (re-search-forward sort-regexp-fields-regexp nil 'move)
397 (setq sort-regexp-record-end (match-end 0)))
399 (goto-char (match-beginning 0)))))
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.
414 With a negative prefix arg sorts in reverse order.
416 The variable `sort-fold-case' determines whether alphabetic case affects
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 "\\&"))
429 ((string-match "\\`\\\\[1-9]\\'" key-regexp)
430 (setq key-regexp (- (aref key-regexp 1) ?0))))
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))
441 'sort-regexp-fields-next-record
443 (goto-char sort-regexp-record-end)))
446 (cond ((numberp key-regexp)
449 key-regexp sort-regexp-record-end t)
451 (t (throw 'key nil)))
453 (cons (match-beginning n)
455 ;; if there was no such register
456 (error (throw 'key nil)))))))))))
459 (defvar sort-columns-subprocess t)
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
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."
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))
485 (goto-char (max beg end))
486 (setq col-end1 (current-column))
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)
497 (setq plist (text-properties-at pos))
498 (setq fontified (plist-get plist 'fontified))
500 (unless (or (eq (car plist) 'fontified)
501 (and (eq (car plist) 'face)
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"
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.
521 (narrow-to-region beg1 end1)
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))))))))
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."
533 (let (mid) (setq mid end end beg beg mid)))
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
538 (or (bolp) (forward-line 1))
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.
550 (setq ll (cons (buffer-substring (point) (progn (end-of-line) (point)))
552 (setq do (/= (point) end))
553 (delete-region beg (if do (1+ (point)) (point))))
555 (insert (car ll) "\n")
561 ;;; sort.el ends here