Search code examples
emacslisporg-modebookmarks

Emacs org-mode: textual reference to a file:line


I am using org-mode in Emacs to document my development activities. One of the tasks which I must continuously do by hand is to describe areas of code. Emacs has a very nice Bookmark List: create a bookmark with CTRL-x r m, list them with CTRL-x r l. This is very useful, but is not quite what I need.

Org-mode has the concept of link, and the command org-store-link will record a link to the current position in any file, which can be pasted to the org-file. The problem with this is two-fold:

  • It is stored as an org-link, and the linked position is not directly visible (just the description).
  • It is stored in the format file/search, which is not what I want.

I need to have the bookmark in textual form, so that I can copy paste it into org-mode, end edit it if needed, with a simple format like this:

absolute-file-path:line

And this must be obtained from the current point position. The workflow would be as simple as:

  • Go to the position which I want to record
  • Call a function: position-to-kill-ring (I would bind this to a keyboard shortcut)
  • Go to the org-mode buffer.
  • Yank the position.
  • Edit if needed (sometimes I need to change absolute paths by relative paths, since my code is in a different location in different machines)

Unfortunately my lisp is non-existent, so I do not know how to do this. Is there a simple solution to my problem?


Solution

  • (defun position-to-kill-ring ()
      "Copy to the kill ring a string in the format \"file-name:line-number\"
    for the current buffer's file name, and the line number at point."
      (interactive)
      (kill-new
       (format "%s:%d" (buffer-file-name) (save-restriction
                                            (widen) (line-number-at-pos)))))