刚刚发现了一个自动刷新 Chrome 当前 Tab 的 AppleScript 代码(Gist):
tell application "Chrome" to tell the active tab of its first window to reload
利用它能“实时”地预览 Markdown 了,也就是在保存 Markdown 时,Chrome 自动刷新显示结果的页面:
-
M-x chunyang-markdown-preview-in-chrome
在 Chrome 预览,不同于自带的M-x markdown-preview
,它会重用当前的 Tab,不会一直创建新的 Tab -
M-x chunyang-markdown-preview-in-chrome-mode
一个 Local Minor Mode,会在保存文件时,自动调用上面的命令
(defun chunyang-chrome-refresh ()
"Refresh the current tab of Chrome."
(do-applescript
"tell application \"Chrome\" \
to tell the active tab of its first window to reload"))
(defun chunyang-chrome-url ()
"Return the URL of the current tab of Chrome."
(replace-regexp-in-string
(rx (or (and string-start ?\")
(and ?\" string-end)))
""
(do-applescript
"tell application \"Google Chrome\" to return URL of active tab of first window")))
(defun chunyang-markdown-preview-in-chrome ()
"Export Markdown and preview the result in Chrome.
This function reuses the current tab of Chrome,
unlike `markdown-preview'."
(interactive)
(let ((output (markdown-export)))
(if (string-match-p (regexp-quote output) (chunyang-chrome-url))
(chunyang-chrome-refresh)
(browse-url output))))
(define-minor-mode chunyang-markdown-preview-in-chrome-mode
"Run `chunyang-markdown-preview-in-chrome' on save."
:lighter " MD-Preview-in-Chrome"
(unless (eq major-mode 'markdown-mode)
(user-error "Error: %s is not Markdown Mode" major-mode))
(if chunyang-markdown-preview-in-chrome-mode
(add-hook 'after-save-hook #'chunyang-markdown-preview-in-chrome :append :local)
(remove-hook 'after-save-hook #'chunyang-markdown-preview-in-chrome :local)))
同样的方法可以用在 Org mode 或者其它的格式,甚至导出的格式也不一定得是 HTML,因为 Chrome 也能支持图片、PDF 等。