sort.el 23 KB

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