2

My goal is to use grep to find other Org files, use next-error to switch to those files, copy the link to the grep match, then go back and paste that link.

It worked for a long time as a macro, but when it finally broke I decided to write it as a proper function. But the buffer-switches that worked as macro don't seem to be working as a function. Why?

;; Can't use `with-current-buffer' because it's used in `next-error'
(let ((thisbuf  (current-buffer)))
  ;; Unless interactive, this doesn't change `current-buffer', at least not in time for `org-store-link'
  (next-error)
  ;; Message says thisbuf, not the one `next-error' takes me to
  (message (concat "Current buffer: " (current-buffer)))
  ;; Why does it store my link in `thisbuf' instead of the buffer `next-error' goes to?
  (org-store-link nil 1)
  (switch-to-buffer thisbuf))
1
  • (I removed the unnecessary progn and shortened comments.) – Drew Apr 2 at 15:51
2

This should do it.

(defun foo ()
  (interactive)
  (add-hook 'next-error-hook 'toto)
  (let ((thisbuf  (current-buffer)))
    (next-error)
    (switch-to-buffer thisbuf))
  (remove-hook 'next-error-hook 'toto))

(defun toto ()
  (message "Current buffer: %s" (current-buffer))
  (org-store-link nil))

It fixes three problems:

  1. (current-buffer) returns a buffer, not its name. You can't concat a buffer.

  2. org-store-link accepts only one argument.

  3. next-error puts you back in the original buffer. You need to use its hook if you want to do something in the source buffer that it moves to.

But this is really all you need for foo (see #3 above):

(defun foo ()
  (interactive)
  (add-hook 'next-error-hook 'toto)
  (next-error)
  (remove-hook 'next-error-hook 'toto))
1
  • Perfect! The hook emacs idiom is what I hadn't thought of. I discovered one more adjust necessary to make it work: (org-store-link nil t)) needs the second arg or else it wasn't actually storing anything... – Webdev Tory Apr 2 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.