org-modeのファイルパスをタイトル付きのリンクに置き換える

しむどん 2025-02-14

org-modeファイルのパスを、タイトル付きリンクに変換するEmacs Lispを書く事にした。

例えばこのような文字列があるとする。

/path/to/org-mode-file.org

このファイル内に指定されているタイトルを取得し、以下の文字列に変換する。

[[/path/to/org-mode-file.org][取得したタイトル]]

書いたLispは数行だけだ。ここに掲載しておく。

;;; our-org-insert-title-link --- org-mode-utility -*- lexical-binding: t -*-

;; Copyright (C) 2025 TakesxiSximada

;; Author: TakesxiSximada <[email protected]>
;; Maintainer: TakesxiSximada <[email protected]>
;; Repository:
;; Version: 1
;; Package-Version: 20250215.0000
;; Package-Requires: ((emacs "28.0")
;; Date: 2025-02-15

;; This file is not part of GNU Emacs.

;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

;;; Code:

(defun our-org-insert-title-link (beg end)
  "Replace org-mode file path with titled link"
  (interactive "r")
  (if-let* ((file-path (buffer-substring-no-properties beg end))
	    (title (org-get-title file-path)))
      (replace-string-in-region
       file-path
       (org-link-make-string file-path title)
       beg end)))

(provide 'our-org-insert-title-link)
;; our-org-insert-title-link.el ends here