2008-10-15 6 views

Respuesta

100

puede seleccione una región y escriba `C-u M- | comando RET ', y reemplaza la región con el resultado del comando en el mismo búfer debido al argumento de prefijo interactivo de shell-command-on-region.

+2

Jurta por la victoria. Upvote. Juro que cada vez que pienso que estoy empezando a conocer este programa, alguien viene y me muestra que soy un principiante de rango. – dmckee

+0

Normalmente, cuando necesita una función en Emacs, lo más probable es que ya esté implementada hace mucho tiempo. Entonces, lo mejor que puede hacer primero es leer la documentación en lugar de comenzar a reinventar la rueda;) – link0ff

+1

Gracias jurta. Desafortunadamente no pude encontrar ninguna documentación para esta característica. – Rohit

7

Última edición: Por mucho que aprecio los votos por arriba, la respuesta de Jurta es el camino a seguir. Y el truco de Greg es más limpio que el mío.

dejaré el resto de esto aquí, ya que podría valer algo, pero ...


M-x shell-command-on-region, que parece estar ligado a por defecto.


Veo que esto no hace exactamente lo que pidió Rohit. El uso de C-h f shell-command-on-region revela que el comportamiento deseado está disponible en la versión no interactiva del comando (estableciendo el argumento replace en no nil). Deberíamos poder escribir un contenedor para hacer esto.

Prueba esto (cargarlo en *scratch* y ejecutar M-x eval-buffer, si funciona, copiarlo en el fichero .emacs):

(defun shell-command-on-region-replace (start end command) 
    "Run shell-command-on-region interactivly replacing the region in place" 
    (interactive (let (string) 
     (unless (mark) 
      (error "The mark is not set now, so there is no region")) 
     ;; Do this before calling region-beginning 
     ;; and region-end, in case subprocess output 
     ;; relocates them while we are in the minibuffer. 
     ;; call-interactively recognizes region-beginning and 
     ;; region-end specially, leaving them in the history. 
     (setq string (read-from-minibuffer "Shell command on region: " 
          nil nil nil 
          'shell-command-history)) 
     (list (region-beginning) (region-end) 
       string))) 
    (shell-command-on-region start end command t t) 
) 

y fichas como digo en los comentarios que esto no es una muy emacsy cosas que hacer. Pero creo que funciona


Para aquellos lectores que no saben cómo seleccionar una región:

  1. Mover el "punto" (posición actual del cursor) a un extremo de la región, y que utilizan para activar el C-space "marca"
  2. mover el punto al otro extremo de la región
  3. su hecho, invoque el comando
+0

Gracias, no sé de eso, sino que me da el texto filtrada en una memoria intermedia separada; no reemplaza el original. – Rohit

+0

Sé el comportamiento vi que desea. Sigue buscando. – dmckee

+0

Interesante que esto no es simplemente una pregunta frecuente. Utilizo esta funcionalidad en vi (o vim) todo el tiempo; un editor sin él se vuelve ... menos interesante. –

15

de escribir este hace unos años, podría ayudarle a:

(defun generalized-shell-command (command arg) 
    "Unifies `shell-command' and `shell-command-on-region'. If no region is 
selected, run a shell command just like M-x shell-command (M-!). If 
no region is selected and an argument is a passed, run a shell command 
and place its output after the mark as in C-u M-x `shell-command' (C-u 
M-!). If a region is selected pass the text of that region to the 
shell and replace the text in that region with the output of the shell 
command as in C-u M-x `shell-command-on-region' (C-u M-|). If a region 
is selected AND an argument is passed (via C-u) send output to another 
buffer instead of replacing the text in region." 
    (interactive (list (read-from-minibuffer "Shell command: " nil nil nil 'shell-command-history) 
        current-prefix-arg)) 
    (let ((p (if mark-active (region-beginning) 0)) 
     (m (if mark-active (region-end) 0))) 
    (if (= p m) 
     ;; No active region 
     (if (eq arg nil) 
      (shell-command command) 
      (shell-command command t)) 
     ;; Active region 
     (if (eq arg nil) 
      (shell-command-on-region p m command t t) 
     (shell-command-on-region p m command))))) 

que he encontrado esta función a ser muy útil. Si le resulta útil, así, sugiero asociarlos a una determinada tecla de función por conveniencia, en lo personal yo uso F3:

(global-set-key [f3] 'generalized-shell-command) 
+0

Excelente. Esto actúa igual que el conducto "C-k /" de joe a través del comando de shell. –

Cuestiones relacionadas