Search code examples
emacselisp

emacs save-excursion not restoring point?


I'm running this function (interactive and in a hook) to reformat source code

(defun a-style ()                                                                                                                                                                                         
  (interactive)                                                                                                                                                                                           
  (save-excursion                                                                                                                                                                                         
    (shell-command-on-region (point-min) (point-max) "/usr/local/bin/astyle -A10 -s4 -m0 -M40 -k1 -W0 -z2 -xd -CSKNLwYfpHjJcn" t t)))

but the save-excursion does not seem to work, the point always jumps to 1 (the shell command works though!). Am I missing something obvious here?

Thanks, Mario

EDIT:

So I finally did it the naive way:

(defun a-style ()                                                                                                                                                                                         
  (interactive)                                                                                                                                                                                           
  (setq temp-point (point))                                                                                                                                                                               
  (shell-command-on-region (point-min) (point-max) "/usr/local/bin/astyle -A10 -s4 -m0 -M40 -k1 -W0 -z2 -xd -CSKNLwYfpHjJcn" t t)                                                                         
  (goto-char temp-point))

Kinda stupid, but does what I want. If anyone knows of a better solution, I'd be grateful.


Solution

  • The documentation for shell-command-on-region says in part:

    If REPLACE, the optional fifth argument, is non-nil, that means insert the output in place of text from START to END, putting point and mark around it.

    Since you have REPLACE set to t, it replaces all the text and puts point and mark around it, and so point goes to point-min. Furthermore, I think when the spot previously saved by save-excursion is removed Emacs backs up to the beginning of the removed region which again is point-min.

    I think your solution is fine.