サポンテ 勉強ノート

サポンテの勉強ノート・読書メモなどを晒します。

編集中のHTMLに書かれたイメージファイルをQuickLook【CotEditor】

はじめに

 html をテキストエディタで書く人って、少数派だとは思うのですが。

 以前サポンテは html を手書きしていました。html を身につければ、高価なエディタを使わずともホームページを作成できるためです。

 macOS には、QuickLook という非常に便利な機能があります。

 html 編集中に、img タグに埋め込まれているイメージファイルを、ちょこっと確認したいことがあります。Finder に戻っても良いのですが、images ディレクトリが込み入ったところにあったりすると、少々面倒です。そんなときは、編集中のエディタから直接確認できれば便利です。

 CotEditor には、編集中の書類に適用できるスクリプトを簡単に追加できる機能があります。CotEditor と QuickLook のコマンドライン版である qlmanage を AppleScript で組み合わせれば、それが実現可能です。

動作イメージ

 編集中の html(に限りませんが)書類から見た相対パス文字列を選択しスクリプトを起動することで、該当の相対パスに存在するファイルを QuickLook で表示します。確認したら Space キーで閉じることができます。

スクリプト動作イメージ

スクリプト

 一部のスクリプト呆備録様より拝借しました。

ファイル、フォルダの存在確認 - 呆備録

 下記のスクリプトを拡張子 .scpt で保存して CotEditor のスクリプトフォルダに入れれば、CotEditor から直接 QuickLook できるようなります。

-- CotEditor にアクセスする
tell application "CotEditor"
    -- CotEditor が何らかのドキュメントを開いているかどうか確認する
    if (exists front document) then
        -- CotEditor の選択テキストを取得する
        set theSelection to contents of selection of front document
        -- テキストが選択されていたことを確認する
        if theSelection is not "" then
            set dirpath to path of front document
            set dirpath to quoted form of dirpath
            -- 最前面書類のパスを取得する
            set thePath to do shell script "dirname " & dirpath
            -- パスが取得できたことを確認する
            if thePath is not "" then
                -- ファイルが存在することを確認する
                if isExistItem(thePath & "/" & theSelection) of me then
                    -- QuickLook を開く
                    do shell script "qlmanage -p " & thePath & "/" & theSelection
                end if
            end if
        end if
    end if
end tell

on isExistItem(thePosixPath)
    -- 拝借元:https://oppara.hatenadiary.org/entry/20060209/p1
    try
        set theFilePath to thePosixPath as POSIX file
        set theAliasPath to theFilePath as alias
        return true
    on error
        return false
    end try
end isExistItem