; ; unix-like-commands.l ; ; Nov 10, 2010 by FUJIWARA Teruyoshi ; ; Copyright: Copyright (c) 2010 FUJIWARA Teruyoshi ; License: Distributes under the same terms as xyzzy ; ; Installation: ; 1. Copy this file into /path/to/xyzzy/site-lisp. ; 2. Add "(load-library "unix-like-commands") in your .xyzzy. ; 3. (optional) Byte compile makes these functions faster. ; ; Usage: ; M-x uniq-buffer: Remove duplicate lines in current buffer. ; M-x sort-buffer: Sort current buffer. ; M-x wc-buffer: Show line, word and character counts in the message line. ; M-x grep-buffer: Filter buffer with a regular expression. ; ; uniq (defun uniq-buffer () "Remove duplicate lines in current buffer." (interactive) (let ((s (make-buffer-stream (selected-buffer))) (stack nil) (prev nil) line) (while (setq line (read-line s nil)) (unless (equal line prev) (push line stack)) (setq prev line)) (delete-region (point-min) (point-max)) (insert (format nil "~{~A~%~}" (reverse stack))))) ; sort (defun sort-buffer () "Sort current buffer. This function doesn't depend on sort.exe and can handle any charset that xyzzy supports." (interactive) (let ((s (make-buffer-stream (selected-buffer))) (stack nil) line) (while (setq line (read-line s nil)) (push line stack)) (delete-region (point-min) (point-max)) (insert (format nil "~{~A~%~}" (sort stack #'string<))))) ;(defun sort-buffer () ; "Sort current buffer using 'sort.exe' command." ; (interactive) ; (filter-buffer "sort.exe")) ; wc (defun wc-buffer () "Count newline, word and character counts for current buffer." (interactive) (message (format nil "Line: ~D, Word: ~D, Char: ~D" (wc-l) (wc-w) (wc-c)))) (defun wc-l () (save-excursion (goto-char (point-min)) (count-matches "\n"))) (defun wc-w () ; xyzzy's next-word recognizes some words (like "won't" "end." or "ex-president") as two words. ; So we should process input before counting words. (let ((s (buffer-substring (point-min) (point-max))) (buf (create-new-buffer "*wc*")) result) (set-buffer buf) (erase-buffer buf) (insert s) (goto-char (point-min)) (replace-regexp "[\"']" "" t) (goto-char (point-min)) (replace-regexp "[ \t,\.!\-]+$" "" t) (goto-char (point-min)) (replace-regexp "^[ \t,\.!\-]+" "" t) (goto-char (point-min)) (replace-regexp "[ \t,\.!\-][ \t,\.!\-]+" " " t) (goto-char (point-min)) (setq result (count-matches "\\W")) (and buf (delete-buffer buf)) result)) (defun wc-c () ; NOTE: ; This function counts newlines(like "wc -c"), but "\r\n" is counted as just one word. ; Handling of newlines depends on xyzzy. (save-excursion (goto-char (point-min)) (count-matches ".\\|\n"))) (defun grep-buffer (regexp) "Filter buffer with a regular expression. This command edits current buffer directly." (interactive "sRegular Expression: ") (let ((s (make-buffer-stream (selected-buffer))) (stack nil) line) (while (setq line (read-line s nil)) (if (string-match regexp line) (push line stack))) (delete-region (point-min) (point-max)) (insert (format nil "~{~A~%~}" (reverse stack)))))