[glug-t] Re: removing blank lines in emacs

Vimal Joseph <vimalekm@xxxxxxxxx> writes:

> On Sat, 2005-04-09 at 14:08 +0530, Vignesh Waran wrote:
> >              There is a  'C' program which has many blank lines in it,
> > how to remove all the blank lines with query-replace in emacs ?
> 
> M-x flush-lines RET ^$
> 
> flush-lines deletes all lines that matches the regular expression. and
> the reg exp ^$ matches empty lines ie lines with only RET.


I guess, our friend wants to be asked before deleting a line. I don't
think there is a function that does that! Anyway I have modified
flush-lines to ask y/n before flushing.(Boy! I love cut/copy/paste
programming!) Add the following function to your .emacs file.

;----------- START -------------

(defun query-flush-lines (regexp &optional rstart rend)
  "Similar to flush-lines, but queries before flushing."
  (interactive
   (keep-lines-read-args "Flush lines (containing match for regexp): "))
  (if rstart
      (goto-char (min rstart rend))
    (if (and transient-mark-mode mark-active)
        (setq rstart (region-beginning)
              rend (copy-marker (region-end)))
      (setq rstart (point)
            rend (point-max-marker)))
    (goto-char rstart))
  (let ((case-fold-search (and case-fold-search
                               (isearch-no-upper-case-p regexp t))))
    (save-excursion
      (while (and (< (point) rend)
                  (re-search-forward regexp rend t))
        (if (not (y-or-n-p "Flush? "))
            (forward-line 1)
            (delete-region (save-excursion (goto-char (match-beginning 0))
                                           (beginning-of-line)
                                           (point))
                           (progn (forward-line 1) (point))))))))

;----------- END -------------

To query replace empty lines do,

M-x query-flush-lines RET ^[[:space:]]*$ RET

Answer 'y' when you want to flush a line.
 
> BTW what is the regexp to match a blank line? 

I guess ^[[:space:]]*$ will do.

Regards,
Vijay
---------------------------------------------------------------
To unsubscribe send a mail to glug_t-request@xxxxxxxxxxxxx with 
'unsubscribe' as subject.

Website: http://glugt.linuxisle.com

Other related posts: