I have a hook function config as bellowing to auto insert attached file
link and auto toggle link previewing.

#+begin_src emacs-lisp :eval no
;; Use `org-attach-store-link-p' as condition.
;; So the hook is not executed at correct position.
(defun my/org-attach/after/org-link-preview (attach-dir)
  "Preview file: / attach: link with `org-link-preview' after `org-attach'
in ATTACH-DIR."
  (org-insert-last-stored-link 1)
  (when (eq org-attach-store-link-p 'file)
    (org-link-preview-region
     :include-linked :refresh
     (org-element-begin (org-element-context)) (org-element-end
(org-element-context)))))

(add-hook 'org-attach-after-change-hook
#'my/org-attach/after/org-link-preview 95)
#+end_src

But I found the link inserted before the heading instead of original point
position.

Here is the reproduce workflow:

1. Evaluate hook function config for Minimal Emacs Config

  #+begin_src emacs-lisp
  (setq org-attach-method 'mv)
  (setq org-attach-store-link-p 'file)
  (setq org-attach-dir-relative t)
  (setq org-attach-auto-tag nil)

  (defun my/org-attach/after/insert-org-link-preview (&optional args)
    "Auto insert & preview file: / attach: link with `org-link-preview'
after `org-attach'."
    (save-excursion
      (save-window-excursion
        ;; FIXME: the position is drifted. TODO: debug `org-attach'.
        (org-insert-last-stored-link 1)
        (when (eq org-attach-store-link-p 'file)
          (org-link-preview-region
           :include-linked :refresh
           (org-element-begin (org-element-context)) (org-element-end
(org-element-context)))))))

  (add-hook 'org-attach-after-change-hook
#'my/org-attach/after/insert-org-link-preview 95)
  #+end_src

2. Move point to the position indicator (point). Then execute `org-attach`
command to move a file into current org heading.

   #+begin_src org
   ,* heading 1

   ,* heading 2
   (point)
   ,* heading 3
   #+end_src

3. The result

   #+begin_src org
   ,* heading 1

   [[link of moved file]]
   ,* heading 2
   :PROPERTIES:
   :ID:       3bec8113-0d0b-407e-a88f-76984f2a5698
   :END:
   (point)
   ,* heading 3
   #+end_src

But the correct result should be:

   #+begin_src org
   ,* heading 1

   ,* heading 2
   :PROPERTIES:
   :ID:       3bec8113-0d0b-407e-a88f-76984f2a5698
   :END:
   [[link of moved file]](point)
   ,* heading 3
   #+end_src

I tried this config with a Minimal Emacs Config that can reproduce this
problem.

I tried Edebug on the command `org-attach`, `org-attach-attach`.
Found the reason, so I created the attached patch to solve this problem.

[stardiviner]           <Hack this world!>      GPG key ID: 47C32433
IRC(freeenode): stardiviner                     Twitter:  @numbchild
Key fingerprint = 9BAA 92BC CDDD B9EF 3B36  CB99 B8C4 B8E5 47C3 2433
Blog: http://stardiviner.github.io/

Attachment: 0001-org-attach-Avoid-point-moving-around-in-org-attach-a.patch
Description: Binary data

Reply via email to