TeXShop 中 latexindent 的集成

TeXShop 中 latexindent 的集成

我花了很长时间试图弄清楚如何将 latexindent(顺便说一句,这真是个好工具!)集成到 TeXShop 中。我很惊讶地发现没有现成的解决方案(latexindent 现在非常标准,并且默认集成在几个 IDE 中,例如 VSCode 上的 latex-workshop 或 IntelliJ 中的 TeXiFy)。

因此,我最终编写了自己的 AppleScript,使用 latexindent 格式化我的代码,并提供了一个简单的快捷方式(Cmd + I对我来说)。可以使用此操作恢复Cmd + Z(如果使用外部脚本直接修改 .tex 文件,则不会出现这种情况)。

由于这可能对其他人有用,所以我将其发布在这里。这是我第一次使用 AppleScript(以及更广泛意义上的 TeXShop 中的宏),因此我非常乐意收到一些反馈或建议来改进此功能。

此外,如果我错过了已经存在的解决方案,请告诉我!

答案1

要使用此脚本,请在“宏”菜单中打开宏编辑器,单击“新建项目”并复制粘贴下面的内容。您可以为宏指定任何名称(例如“latexindent”)和一个可选键(例如“i”,如果您想使用 启动脚本Cmd + I)。然后单击“保存”。

请报告此线程上的任何错误。

--AppleScript
--This script runs latexindent on the current document.

set filepath to #FILEPATH#
set docname to #DOCUMENTNAME#

if filepath = "" then
    display dialog "You must save the document before using latexindent." buttons {"OK"} default button "OK" with icon note
    return false
end if

tell application "TeXShop" to save document docname

try
    --Don't forget the "without altering line endings", otherwise LF will be converted to CR and trailing blank lines will be removed.
    set indentedText to do shell script ("/Library/TeX/texbin/latexindent -m -l " & filepath) without altering line endings
on error number errnum
    display dialog ("latexindent returned error number " & errnum) buttons {"OK"} default button "OK" with icon stop
    return false
end try

tell application "TeXShop"
    set previousOffset to offset of selection of document docname
    set offset of selection of document docname to -1
    set n to offset of selection of document docname
    set offset of selection of document docname to 0
    set length of selection of document docname to n
    --set originalText to content of selection of document docname
    set content of selection of document docname to indentedText
    set offset of selection of document docname to previousOffset
    save document docname
end tell

return true

相关内容