1 ;;; sort.el --- commands to sort text in an Emacs buffer.
3 ;; Copyright (C) 1986, 1987 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 2, or (at your option)
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; see the file COPYING. If not, write to
23 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
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.
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
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.
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.
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
49 ENDRECFUN is is called with point within the record.
50 It should move point to the end of the record.
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.
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
61 ;; Heuristically try to avoid messages if sorting a small amt of text.
62 (let ((messages (> (- (point-max) (point-min)) 50000)))
64 (if messages
(message "Finding sort keys..."))
65 (let* ((sort-lists (sort-build-lists nextrecfun endrecfun
66 startkeyfun endkeyfun
))
67 (old (reverse sort-lists
)))
70 (or reverse
(setq sort-lists
(nreverse sort-lists
)))
71 (if messages
(message "Sorting records..."))
73 (if (fboundp 'sortcar
)
75 (cond ((numberp (car (car sort-lists
)))
76 ;; This handles both ints and floats.
78 ((consp (car (car sort-lists
)))
79 'buffer-substring-lessp
)
83 (cond ((numberp (car (car sort-lists
)))
86 (< (car a
) (car b
)))))
87 ((consp (car (car sort-lists
)))
90 (buffer-substring-lessp (car a
) (car 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"))))
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.
106 ;; The records appear in the list lastmost first!
108 (defun sort-build-lists (nextrecfun endrecfun startkeyfun endkeyfun
)
109 (let ((sort-lists ())
112 ;; Loop over sort records.
113 ;(goto-char (point-min)) -- it is the caller's responsibility to
114 ;arrange this if necessary
116 (setq start-rec
(point)) ;save record start
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
)
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.
137 (equal (car key
) start-rec
)
138 (equal (cdr key
) (point)))
140 (cons key
(cons start-rec
(point))))
142 (and (not done
) nextrecfun
(funcall nextrecfun
)))
145 (defun sort-reorder-buffer (sort-lists old
)
146 (let ((inhibit-quit t
)
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)))
156 (goto-char (point-max))
157 (insert-buffer-substring (current-buffer)
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
)
167 (goto-char (point-max))
168 (insert-buffer-substring (current-buffer)
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)))))
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)."
186 (narrow-to-region beg end
)
187 (goto-char (point-min))
188 (sort-subr reverse
'forward-line
'end-of-line
))))
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)."
198 (narrow-to-region beg end
)
199 (goto-char (point-min))
201 (function (lambda () (skip-chars-forward "\n \t\f")))
202 'forward-paragraph
))))
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)."
212 (narrow-to-region beg end
)
213 (goto-char (point-min))
215 (function (lambda () (skip-chars-forward "\n")))
218 (defvar sort-fields-syntax-table nil
)
219 (if sort-fields-syntax-table nil
220 (let ((table (make-syntax-table))
223 (modify-syntax-entry i
"w" table
)
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
)))
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."
240 (sort-fields-1 field beg end
242 (sort-skip-fields (1- field
))
247 ;; This is just wrong! Even without floats...
248 ;; (skip-chars-forward "[0-9]")
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
261 (sort-fields-1 field beg end
263 (sort-skip-fields (1- field
))
269 "[+-]?[0-9]*\.?[0-9]*\\([eE][+-]?[0-9]+\\)?")
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."
281 (sort-fields-1 field beg end
283 (sort-skip-fields (1- field
))
285 (function (lambda () (skip-chars-forward "^ \t\n")))))
287 (defun sort-fields-1 (field beg end startkeyfun endkeyfun
)
288 (let ((tbl (syntax-table)))
289 (if (zerop field
) (setq field
1))
293 (narrow-to-region beg end
)
294 (goto-char (point-min))
295 (set-syntax-table sort-fields-syntax-table
)
297 'forward-line
'end-of-line
298 startkeyfun endkeyfun
)))
299 (set-syntax-table tbl
))))
301 (defun sort-skip-fields (n)
303 (eol (save-excursion (end-of-line 1) (point))))
304 (if (> n
0) (forward-word n
)
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")))
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.
330 With a negative prefix arg sorts in reverse order.
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
"\\&"))
342 ((string-match "\\`\\\\[1-9]\\'" key-regexp
)
343 (setq key-regexp
(- (aref key-regexp
1) ?
0))))
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))
354 (and (re-search-forward record-regexp nil
'move
)
355 (setq sort-regexp-record-end
(match-end 0))
356 (goto-char (match-beginning 0)))))
358 (goto-char sort-regexp-record-end
)))
361 (cond ((numberp key-regexp
)
364 key-regexp sort-regexp-record-end t
)
366 (t (throw 'key nil
)))
368 (if (fboundp 'buffer-substring-lessp
)
369 (cons (match-beginning n
)
371 (buffer-substring (match-beginning n
)
373 ;; if there was no such register
374 (error (throw 'key nil
)))))))))))
377 (defvar sort-columns-subprocess t
)
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.
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."
394 (let (beg1 end1 col-beg1 col-end1 col-start col-end
)
395 (goto-char (min beg end
))
396 (setq col-beg1
(current-column))
399 (goto-char (max beg end
))
400 (setq col-end1
(current-column))
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.
416 (narrow-to-region beg1 end1
)
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
)))))))))
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."
428 (let (mid) (setq mid end end beg beg mid
)))
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
433 (or (bolp) (forward-line 1))
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.
445 (setq ll
(cons (buffer-substring (point) (progn (end-of-line) (point)))
447 (setq do
(/= (point) end
))
448 (delete-region beg
(if do
(1+ (point)) (point))))
450 (insert (car ll
) "\n")
456 ;;; sort.el ends here