Based on a Reddit thread:

https://www.reddit.com/r/emacs/comments/10xhvd8/a_little_readstring_utility_using_an_org_mode/j7xziao/?context=3

I did a small experiment to see if I can re-use org-capture, to just capture a
string from a buffer, without actually writing to any file.

My plan was to just let-bind org-capture-finalize with cl-letf:

#+begin_src emacs-lisp
(defun my-read-string ()
  (cl-letf (((symbol-function 'org-capture-finalize) ;; C-c C-c
             (lambda (&optional _) (interactive "P") (buffer-string)))
            ((symbol-function 'org-kill-note-or-show-branches) #'kill-buffer)) 
;; C-c C-k
    (let ((org-capture-templates '(("s" "string" plain (function ignore)))))
      (org-capture nil "s"))))
#+end_src

Unfortunately, that does not work. Regardless of binding, and if I used cl-letf
or cl-flet or cl-labels, or old let, or something brewed on the internet, the
binding org-capture see for org-capture-finalize, is the original one from
org-capture.el.

My second experiment was to abstract the finalize function into a funcallable
fariable in org-capture.el (I have patched org-capture.el with this):

#+begin_src emacs-lisp
(defvar org-capture-finalizer #'org-capture--default-finalize)

(defun org-capture-finalize (&optional stay-with-capture)
  "Finalize the capture process.
With prefix argument STAY-WITH-CAPTURE, jump to the location of the
captured item after finalizing."
  (interactive "P")
  (funcall org-capture-finalizer stay-with-capture))


(defun org-capture--default-finalize (&optional stay-with-capture)
  "Default implementation for org-capture finalizer function."

;; this is the original org-capture-finalize just renamed to "default-finalize"
)
#+end_src

So I could then have something like this (never mind C-c C-k function being
removed):

#+begin_src emacs-lisp
(defun my-read-string ()
  (let ((org-capture-templates '(("s" "string" plain (function ignore))))
        (org-capture-finalizer
         (lambda (&optional _) (interactive "P") (buffer-string))))
    (org-capture nil "s")))
#+end_src

However I see that the binding for the org-capture-finalizer, in capture buffer,
is still the default 'org-capture--default-finalize' and not my lambda.

I am really not an expert on emacs lisp; and I do understand that this is
somewhat "creative" use of org-capture (to put it nicely :-)), but I would like
to understand what is going on here.

I don't understand why let-binding here does not work? If I take (symbol-functon
'org-capture) I see it is a closure. I am not sure if it has something with the
problem to do? I have tested to disable lexical binding, re-eval things, but
the let-binding seems rock stable :). Nothing makes org-capture to reconsider
using my local let-binding.

I would really like to understand this, so please if someone can explain it, I
will appreciate to hear.

Thanks in advance
/arthur

Reply via email to