创建一个elisp函数将URL转换为HTML链接?

1 emacs elisp

我想创建某种类型的elisp函数,并将其绑定到一个带有两种格式之一的URL的键,并生成一个HTML链接元素.

以下是两种输入格式:

http://developer.apple.com/safaridemos/
http://developer.apple.com/safaridemos|Safari Demos
Run Code Online (Sandbox Code Playgroud)

以下是两个所需的输出值:

<a href="http://developer.apple.com/safaridemos/">safaridemos</a>
<a href="http://developer.apple.com/safaridemos/">Safari Demos</a>
Run Code Online (Sandbox Code Playgroud)

理想情况下,这可以在一个区域上工作,但即使它只在一行上工作,它也会有所帮助.

jus*_*nhj 18

这是一种做法.此方法的工作原理是让用户选择应转换为链接的文本,然后替换它.

;;; http://developer.apple.com/safaridemos|Safari Demos
;;; becomes <a href="http://developer.apple.com/safaridemos">Safari Demos</a>
;;; http://developer.apple.com/safaridemos|Safari Demos
;;; <a href="http://developer.apple.com/safaridemos">Safari Demos</a>

  (defun url-to-html-link(input)
  "Convert INPUT url into a html link. The link text will be the text after the last slash or you can end the url with a | and add text after that"
  (let ((split-on-| (split-string input "|"))
    (split-on-/ (split-string input "/"))
    (fmt-string "<a href=\"%s\">%s</a>"))
    (if (> (length split-on-|) 1)
    (format fmt-string (first split-on-|) (second split-on-|))
      (format fmt-string input (first (last split-on-/))))))


(defun url-region-to-html-link(b e)
  (interactive "r")
  (let ((link 
     (url-to-html-link (buffer-substring-no-properties b e))))
    (delete-region b e)
    (insert link)))

(global-set-key (kbd "C-c j") 'url-region-to-html-link)
Run Code Online (Sandbox Code Playgroud)

编辑:您还可以结合使用第一个函数query-replace-regexp来制作交互式命令:

(defun query-replace-urls ()
  (interactive)
  (query-replace-regexp "http://.*"
                        (quote (replace-eval-replacement replace-quote (url-to-html-link (match-string 0))))
                        nil
                        (if (and transient-mark-mode mark-active) (region-beginning))
                        (if (and transient-mark-mode mark-active) (region-end))))
Run Code Online (Sandbox Code Playgroud)

  • 你可以在替换中使用"\,(...)"形式借用`query-replace-regexp`机器.看我的编辑. (2认同)

小智 8

或许更好的想法是使用一些代码片段引擎?例如,Yasnippet提供类似于填写样板文本的缩写机制.我不记得我到底在哪里得到了这个片段,但是想出一个像你这样的片段是微不足道的:

# contributor: Jimmy Wu <frozenthrone88 at gmail dot com>
# name: <a href="...">...</a>
# key: href
# --
<a href="$1">$2</a>
Run Code Online (Sandbox Code Playgroud)

Yasnippet还允许您在占位符中放置默认值,eLisp代码以交互方式查询用户,同时填充代码段或从系统状态读取某些值等.