Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Update the current region/buffer in Emacs via Perl

by laughingboy (Monk)
on Aug 09, 2002 at 16:24 UTC ( #188959=snippet: print w/replies, xml ) Need Help??
Description: For those who edit with emacs, here are a couple of functions that I find useful. The first one runs perl on the current region, replacing it with the results of the command. The second does the same for the current buffer.

Both functions attempt to preserve the current locations of point and mark as best they can. In the case of updating the entire buffer, the point and mark maintain the same line & column number, if possible.

I'm not an elisp guru; suggestions and improvements welcome!

Inspired by a one-liner in TPJ by Dominus.

; run perl on the current region, updating the region
(defun perl-replace-region (start end)     
  "Apply perl command to region"
  (interactive "r")
  (shell-command-on-region start end 
                           (read-from-minibuffer "Replace region comma
+nd: " '("perl -pe \"\"" . 11 ))
                           t
                           t
                           )
  (exchange-point-and-mark)
  )

; run perl on the current buffer, updating the buffer
(defun perl-replace-buffer ()    
  "Apply perl command to buffer"
  (interactive)
  (let ((ptline (count-lines (point-min) (point)))
        (ptcol (current-column))
        (markline 0)
        (markcol  0)
        (command (read-from-minibuffer "Replace buffer command: " '("p
+erl -pe \"\"" . 11 ))))
    (exchange-point-and-mark)
    (setq markline (count-lines (point-min) (point)))
    (setq markcol  (current-column))
    (mark-whole-buffer)
    (let ((new-start (region-beginning))
          (new-end   (region-end)))
      (shell-command-on-region  new-start new-end command t t )
      )
    (goto-line markline)
    (move-to-column markcol)
    (exchange-point-and-mark)
    (goto-line ptline)
    (move-to-column ptcol)
    )
  )

laughingboy

Replies are listed 'Best First'.
Re: Update the current region/buffer in Emacs via Perl
by hossman (Prior) on Aug 10, 2002 at 07:38 UTC
    Very cool. VERY cool. But some people may prefer changing the command to this...

    (read-from-minibuffer "Replace region command: " '("perl -ple \'\'" . +12 ))

    1. without the -l, you lose any newlines in your buffer
    2. shell-command-on-region seems to use a normal shell, which means the double quotes won't going to protect any variables in your region.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: snippet [id://188959]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2023-09-23 11:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?