2

As suggested by the Org-mode Manual, I've customized org-link-abbrev-alist as follows:

(setq org-link-abbrev-alist
       '(;; Abbreviations for websites
         ("google"         . "https://www.google.com/#q=")
         ("github"         . "https://www.github.com/")))

This is convenient because I can easily insert a link with:

[[google:cat pictures][Google Search for cat pictures]]

This is useful because if the URL changes, I can just updated org-link-abbrev-alist. However, there are instances in the past where I've used the entire non-abbreviated link or decided, after visiting a website enough times, to create an abbreviation.

How would I write a function to use org-link-abbrev-alist to turn long form links in all org-mode files (say, all files in org-agenda-files to abbreviated links? For example,

[[https://www.google.com/#q=cat pictures][Google search for cat pictures]]

to:

[[google:cat pictures][Google search for cat pictures]]

I'd also like to integrate this function with org-mode-hook so that it happens automatically on either save or startup.

Lastly, I'd also like a function that does the reverse and replaces the abbreviation with the long form link.

1 Answer 1

5

After a bit of research, I encountered this answer and adopted it to answer my question above. The following function and hook will replace all links in an org-mode file with their corresponding abbreviations on save.

;; Create abbreviations
(defun my/create-org-link-abbreviations ()
  "Replace all long form links in current file with their corresponding abbreviations in `org-link-abbrev-alist'."
  (interactive)
  (dolist (pair org-link-abbrev-alist)
    (save-excursion
      (goto-char (point-min))
      (while (search-forward (concat "[[" (cdr pair)) nil t)
        (replace-match (concat "[[" (car pair) ":"))))))

(add-hook 'org-mode-hook
          (lambda ()
            (add-to-list 'write-file-functions 'my/create-org-link-abbreviations)))

;; Remove abbreviations
(defun my/remove-org-link-abbreviations ()
  "Replace all link abbreviations in current file with their long form counterparts in `org-link-abbrev-alist'."
  (interactive)
  (dolist (pair org-link-abbrev-alist)
    (save-excursion
      (goto-char (point-min))
      (while (search-forward (concat "[[" (car pair) ":") nil t)
        (replace-match (concat "[[" (cdr pair)))))))
1
  • Thanks @npostavs, I've update the answer to reflect your comment.
    – sk8ingdom
    May 12, 2016 at 0:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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