1 ;; Commands to sort text in an Emacs buffer.
2 ;; Copyright (C) 1986, 1987 Free Software Foundation, Inc.
4 ;; This file is part of GNU Emacs.
6 ;; GNU Emacs is free software; you can redistribute it and/or modify
7 ;; it under the terms of the GNU General Public License as published by
8 ;; the Free Software Foundation; either version 1, or (at your option)
11 ;; GNU Emacs is distributed in the hope that it will be useful,
12 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ;; GNU General Public License for more details.
16 ;; You should have received a copy of the GNU General Public License
17 ;; along with GNU Emacs; see the file COPYING. If not, write to
18 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
22 ;; Original version of most of this contributed by Howie Kaye
24 (defun sort-subr (reverse nextrecfun endrecfun &optional startkeyfun endkeyfun)
25 "General text sorting routine to divide buffer into records and sort them.
26 Arguments are REVERSE NEXTRECFUN ENDRECFUN &optional STARTKEYFUN ENDKEYFUN.
28 We consider this portion of the buffer to be divided into disjoint pieces
29 called sort records. A portion of each sort record (perhaps all of it)
30 is designated as the sort key. The records are rearranged in the buffer
31 in order by their sort keys. The records may or may not be contiguous.
33 Usually the records are rearranged in order of ascending sort key.
34 If REVERSE is non-nil, they are rearranged in order of descending sort key.
36 The next four arguments are functions to be called to move point
37 across a sort record. They will be called many times from within sort-subr.
39 NEXTRECFUN is called with point at the end of the previous record.
40 It moves point to the start of the next record.
41 It should move point to the end of the buffer if there are no more records.
42 The first record is assumed to start at the position of point when sort-subr
45 ENDRECFUN is is called with point within the record.
46 It should move point to the end of the record.
48 STARTKEYFUN may moves from the start of the record to the start of the key.
49 It may return either return a non-nil value to be used as the key, or
50 else the key will be the substring between the values of point after
51 STARTKEYFUN and ENDKEYFUN are called. If STARTKEYFUN is nil, the key
52 starts at the beginning of the record.
54 ENDKEYFUN moves from the start of the sort key to the end of the sort key.
55 ENDKEYFUN may be nil if STARTKEYFUN returns a value or if it would be the
58 (message "Finding sort keys...")
59 (let* ((sort-lists (sort-build-lists nextrecfun endrecfun
60 startkeyfun endkeyfun))
61 (old (reverse sort-lists)))
64 (or reverse (setq sort-lists (nreverse sort-lists)))
65 (message "Sorting records...")
67 (if (fboundp 'sortcar)
69 (cond ((numberp (car (car sort-lists)))
70 ;; This handles both ints and floats.
72 ((consp (car (car sort-lists)))
73 'buffer-substring-lessp)
77 (cond ((numberp (car (car sort-lists)))
80 (< (car a) (car b)))))
81 ((consp (car (car sort-lists)))
84 (buffer-substring-lessp (car a) (car b)))))
88 (string< (car a) (car b)))))))))
89 (if reverse (setq sort-lists (nreverse sort-lists)))
90 (message "Reordering buffer...")
91 (sort-reorder-buffer sort-lists old)))
92 (message "Reordering buffer... Done"))
95 ;; Parse buffer into records using the arguments as Lisp expressions;
96 ;; return a list of records. Each record looks like (KEY STARTPOS ENDPOS)
97 ;; where KEY is the sort key (a number or string),
98 ;; and STARTPOS and ENDPOS are the bounds of this record in the buffer.
100 ;; The records appear in the list lastmost first!
102 (defun sort-build-lists (nextrecfun endrecfun startkeyfun endkeyfun)
103 (let ((sort-lists ())
106 ;; Loop over sort records.
107 ;(goto-char (point-min)) -- it is the caller's responsibility to
108 ;arrange this if necessary
110 (setq start-rec (point)) ;save record start
112 ;; Get key value, or move to start of key.
113 (setq key (catch 'key
114 (or (and startkeyfun (funcall startkeyfun))
115 ;; If key was not returned as value,
116 ;; move to end of key and get key from the buffer.
117 (let ((start (point)))
118 (funcall (or endkeyfun
119 (prog1 endrecfun (setq done t))))
120 (if (fboundp 'buffer-substring-lessp)
122 (buffer-substring start (point)))))))
123 ;; Move to end of this record (start of next one, or end of buffer).
124 (cond ((prog1 done (setq done nil)))
125 (endrecfun (funcall endrecfun))
126 (nextrecfun (funcall nextrecfun) (setq done t)))
127 (if key (setq sort-lists (cons
128 ;; consing optimization in case in which key
129 ;; is same as record.
131 (equal (car key) start-rec)
132 (equal (cdr key) (point)))
134 (cons key (cons start-rec (point))))
136 (and (not done) nextrecfun (funcall nextrecfun)))
139 (defun sort-reorder-buffer (sort-lists old)
140 (let ((inhibit-quit t)
142 (min (point-min)) (max (point-max)))
143 ;; Make sure insertions done for reordering
144 ;; do not go after any markers at the end of the sorted region,
145 ;; by inserting a space to separate them.
146 (goto-char (point-max))
147 (insert-before-markers " ")
148 (narrow-to-region min (1- (point-max)))
150 (goto-char (point-max))
151 (insert-buffer-substring (current-buffer)
154 (goto-char (point-max))
155 (insert-buffer-substring (current-buffer)
156 (nth 1 (car sort-lists))
157 (cdr (cdr (car sort-lists))))
158 (setq last (cdr (cdr (car old)))
159 sort-lists (cdr sort-lists)
161 (goto-char (point-max))
162 (insert-buffer-substring (current-buffer)
165 ;; Delete the original copy of the text.
166 (delete-region min max)
167 ;; Get rid of the separator " ".
168 (goto-char (point-max))
169 (narrow-to-region min (1+ (point)))
170 (delete-region (point) (1+ (point)))))
172 (defun sort-lines (reverse beg end)
173 "Sort lines in region alphabetically; argument means descending order.
174 Called from a program, there are three arguments:
175 REVERSE (non-nil means reverse order), BEG and END (region to sort)."
179 (narrow-to-region beg end)
180 (goto-char (point-min))
181 (sort-subr reverse 'forward-line 'end-of-line))))
183 (defun sort-paragraphs (reverse beg end)
184 "Sort paragraphs in region alphabetically; argument means descending order.
185 Called from a program, there are three arguments:
186 REVERSE (non-nil means reverse order), BEG and END (region to sort)."
190 (narrow-to-region beg end)
191 (goto-char (point-min))
193 (function (lambda () (skip-chars-forward "\n \t\f")))
194 'forward-paragraph))))
196 (defun sort-pages (reverse beg end)
197 "Sort pages in region alphabetically; argument means descending order.
198 Called from a program, there are three arguments:
199 REVERSE (non-nil means reverse order), BEG and END (region to sort)."
203 (narrow-to-region beg end)
204 (goto-char (point-min))
206 (function (lambda () (skip-chars-forward "\n")))
209 (defvar sort-fields-syntax-table nil)
210 (if sort-fields-syntax-table nil
211 (let ((table (make-syntax-table))
214 (modify-syntax-entry i "w" table)
216 (modify-syntax-entry ?\ " " table)
217 (modify-syntax-entry ?\t " " table)
218 (modify-syntax-entry ?\n " " table)
219 (modify-syntax-entry ?\. "_" table) ; for floating pt. numbers. -wsr
220 (setq sort-fields-syntax-table table)))
222 (defun sort-numeric-fields (field beg end)
223 "Sort lines in region numerically by the ARGth field of each line.
224 Fields are separated by whitespace and numbered from 1 up.
225 Specified field must contain a number in each line of the region.
226 With a negative arg, sorts by the ARGth field counted from the right.
227 Called from a program, there are three arguments:
228 FIELD, BEG and END. BEG and END specify region to sort."
230 (sort-fields-1 field beg end
232 (sort-skip-fields (1- field))
237 ;; This is just wrong! Even without floats...
238 ;; (skip-chars-forward "[0-9]")
243 (defun sort-float-fields (field beg end)
244 "Sort lines in region numerically by the ARGth field of each line.
245 Fields are separated by whitespace and numbered from 1 up. Specified field
246 must contain a floating point number in each line of the region. With a
247 negative arg, sorts by the ARGth field counted from the right. Called from a
248 program, there are three arguments: FIELD, BEG and END. BEG and END specify
251 (sort-fields-1 field beg end
253 (sort-skip-fields (1- field))
259 "[+-]?[0-9]*\.?[0-9]*\\([eE][+-]?[0-9]+\\)?")
263 (defun sort-fields (field beg end)
264 "Sort lines in region lexicographically by the ARGth field of each line.
265 Fields are separated by whitespace and numbered from 1 up.
266 With a negative arg, sorts by the ARGth field counted from the right.
267 Called from a program, there are three arguments:
268 FIELD, BEG and END. BEG and END specify region to sort."
270 (sort-fields-1 field beg end
272 (sort-skip-fields (1- field))
274 (function (lambda () (skip-chars-forward "^ \t\n")))))
276 (defun sort-fields-1 (field beg end startkeyfun endkeyfun)
277 (let ((tbl (syntax-table)))
278 (if (zerop field) (setq field 1))
282 (narrow-to-region beg end)
283 (goto-char (point-min))
284 (set-syntax-table sort-fields-syntax-table)
286 'forward-line 'end-of-line
287 startkeyfun endkeyfun)))
288 (set-syntax-table tbl))))
290 (defun sort-skip-fields (n)
292 (eol (save-excursion (end-of-line 1) (point))))
293 (if (> n 0) (forward-word n)
295 (forward-word (1+ n)))
296 (if (or (and (>= (point) eol) (> n 0))
297 ;; this is marginally wrong; if the first line of the sort
298 ;; at bob has the wrong number of fields the error won't be
299 ;; reported until the next short line.
300 (and (< (point) bol) (< n 0)))
301 (error "Line has too few fields: %s"
302 (buffer-substring bol eol)))
303 (skip-chars-forward " \t")))
306 (defun sort-regexp-fields (reverse record-regexp key-regexp beg end)
307 "Sort the region lexicographically as specifed by RECORD-REGEXP and KEY.
308 RECORD-REGEXP specifies the textual units which should be sorted.
309 For example, to sort lines RECORD-REGEXP would be \"^.*$\"
310 KEY specifies the part of each record (ie each match for RECORD-REGEXP)
311 is to be used for sorting.
312 If it is \"\\digit\" then the digit'th \"\\(...\\)\" match field from
313 RECORD-REGEXP is used.
314 If it is \"\\&\" then the whole record is used.
315 Otherwise, it is a regular-expression for which to search within the record.
316 If a match for KEY is not found within a record then that record is ignored.
318 With a negative prefix arg sorts in reverse order.
320 For example: to sort lines in the region by the first word on each line
321 starting with the letter \"f\",
322 RECORD-REGEXP would be \"^.*$\" and KEY would be \"\\=\\<f\\w*\\>\""
323 ;; using negative prefix arg to mean "reverse" is now inconsistent with
324 ;; other sort-.*fields functions but then again this was before, since it
325 ;; didn't use the magnitude of the arg to specify anything.
326 (interactive "P\nsRegexp specifying records to sort:
327 sRegexp specifying key within record: \nr")
328 (cond ((or (equal key-regexp "") (equal key-regexp "\\&"))
330 ((string-match "\\`\\\\[1-9]\\'" key-regexp)
331 (setq key-regexp (- (aref key-regexp 1) ?0))))
334 (narrow-to-region beg end)
335 (goto-char (point-min))
336 (let (sort-regexp-record-end) ;isn't dynamic scoping wonderful?
337 (re-search-forward record-regexp)
338 (setq sort-regexp-record-end (point))
339 (goto-char (match-beginning 0))
342 (and (re-search-forward record-regexp nil 'move)
343 (setq sort-regexp-record-end (match-end 0))
344 (goto-char (match-beginning 0)))))
346 (goto-char sort-regexp-record-end)))
349 (cond ((numberp key-regexp)
352 key-regexp sort-regexp-record-end t)
354 (t (throw 'key nil)))
356 (if (fboundp 'buffer-substring-lessp)
357 (cons (match-beginning n)
359 (buffer-substring (match-beginning n)
361 ;; if there was no such register
362 (error (throw 'key nil)))))))))))
365 (defvar sort-columns-subprocess t)
367 (defun sort-columns (reverse &optional beg end)
368 "Sort lines in region alphabetically by a certain range of columns.
369 For the purpose of this command, the region includes
370 the entire line that point is in and the entire line the mark is in.
371 The column positions of point and mark bound the range of columns to sort on.
372 A prefix argument means sort into reverse order.
374 Note that `sort-columns' rejects text that contains tabs,
375 because tabs could be split across the specified columns
376 and it doesn't know how to handle that. Also, when possible,
377 it uses the `sort' utility program, which doesn't understand tabs.
378 Use \\[untabify] to convert tabs to spaces before sorting."
381 (let (beg1 end1 col-beg1 col-end1 col-start col-end)
382 (goto-char (min beg end))
383 (setq col-beg1 (current-column))
386 (goto-char (max beg end))
387 (setq col-end1 (current-column))
390 (setq col-start (min col-beg1 col-end1))
391 (setq col-end (max col-beg1 col-end1))
392 (if (search-backward "\t" beg1 t)
393 (error "sort-columns does not work with tabs. Use M-x untabify."))
394 (if (not (eq system-type 'vax-vms))
395 ;; Use the sort utility if we can; it is 4 times as fast.
396 (call-process-region beg1 end1 "sort" t t nil
397 (if reverse "-rt\n" "-t\n")
398 (concat "+0." col-start)
399 (concat "-0." col-end))
400 ;; On VMS, use Emacs's own facilities.
403 (narrow-to-region beg1 end1)
405 (sort-subr reverse 'forward-line 'end-of-line
406 (function (lambda () (move-to-column col-start) nil))
407 (function (lambda () (move-to-column col-end) nil)))))))))
409 (defun reverse-region (beg end)
410 "Reverse the order of lines in a region.
411 From a program takes two point or marker arguments, BEG and END."
414 (let (mid) (setq mid end end beg beg mid)))
416 ;; put beg at the start of a line and end and the end of one --
417 ;; the largest possible region which fits this criteria
419 (or (bolp) (forward-line 1))
422 ;; the test for bolp is for those times when end is on an empty line;
423 ;; it is probably not the case that the line should be included in the
424 ;; reversal; it isn't difficult to add it afterward.
425 (or (and (eolp) (not (bolp))) (progn (forward-line -1) (end-of-line)))
426 (setq end (point-marker))
427 ;; the real work. this thing cranks through memory on large regions.
431 (setq ll (cons (buffer-substring (point) (progn (end-of-line) (point)))
433 (setq do (/= (point) end))
434 (delete-region beg (if do (1+ (point)) (point))))
436 (insert (car ll) "\n")