help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

use Elisp to improve your Elisp - some code issues


From: Emanuel Berg
Subject: use Elisp to improve your Elisp - some code issues
Date: Fri, 31 Jul 2015 02:22:29 +0200
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.4 (gnu/linux)

I just wrote some Elisp which can be used on a set of
files to identify for example the construct

    (if a a b)

if you want to replace those for

    (or a b)

See the comments for the issues!

Issue one is how to best create a temporary buffer to
display the results.

Issue two is to not kill buffers that were already
open at invocation - I can solve that by checking if
there is such a buffer, but I suspect there is
a better way to do these kind of things all in the
background, rather than the `find-file' and then
conditionally `kill-buffer' combo.

Third (minor) issue is the annoying message that
`downcase' does. Isn't there a (shut-up (do-stuff))?

Other comments also appreciated, as always.

;; This file: 
http://user.it.uu.se/~embe8573/conf/emacs-init/search-regexp-in-files.el

(defun files-as-list (file-regexp)
  (split-string
   (with-temp-buffer
     (call-process-shell-command
      (format "ls %s" file-regexp) nil t) ; no INFILE, temp BUFFER
     (buffer-substring (point-min) (point-max)) )))

(defun search-regexp-in-files (file-regexp regexp)
  (let ((paths       (files-as-list file-regexp))
        (regexp-hits "regexp-hits") ; unlikely, but if there is another such 
buffer
        (hits        nil))
    (with-current-buffer regexp-hits (erase-buffer)) ; then we can't have this
    (dolist (p paths)
      (let ((buffer (find-file p)))
        (with-current-buffer buffer
          (goto-char (point-min))
          (while (re-search-forward regexp nil t) ; no BOUND, NOERROR
            (setq hits t)
            (let ((hit-line (downcase (what-line))))
              (with-current-buffer regexp-hits
                (insert (format "file: %s (%s)\n" p hit-line)))))
          (kill-buffer buffer) ))) ; what if the buffer was open already?
                                   ; we only want to kill buffers that we opened
    (if hits (switch-to-buffer regexp-hits)
      (message "No hits!") )))

;; use this to test
(when nil

  ;; find "kill" - should be some hits even for pacifists
  (search-regexp-in-files "~/.emacs.d/emacs-init/*.el" "kill")

  ;; find the construct (if a a b) if you want to replace it with (or a b)
  ;; if it works, when applied to this file, it should find the example above!
  (search-regexp-in-files (buffer-file-name)
   
"([[:space:]\n]*if[[:space:]\n]+\\(.*\\)[[:space:]\n]+\\1[[:space:]\n]+\\(.*\\))"
   )
  )

(provide 'search-regexp-in-files)

-- 
underground experts united
http://user.it.uu.se/~embe8573




reply via email to

[Prev in Thread] Current Thread [Next in Thread]