
macOSではクリップボードの内容をpbcopyやpbpasteといったコマンドで操作することができます。
特にpbpasteは、コピーした内容をプログラムから利用したい場合に便利なコマンドですが、例えばWebブラウザで選択した内容をHTMLとして取得することはできません。pbpaste -P rtfを利用し、RTF形式で貼り付けることはできますが、HTML形式はサポートしていないのです。
本日紹介する「macos-pasteboard」は、この処理を可能にするオープンソースツールです。
HTMLをはじめ、さまざまな形式でコピーした内容を出力することができます。
以下使用法を説明します。
macos-pasteboardの使用方法
macos-pasteboarの実行ファイルは公開されていないため、ソースコードからビルドする必要があります。
Xcodeを準備し、以下のコマンドを実行します。
git clone https://github.com/chbrown/macos-pasteboard cd macos-pasteboard make install
実行ファイルpbvは/usr/local/bin以下にインストールされます。必要ならばパスを通しておきます。
実行方法は簡単で、pbvを実行するだけです。
オプションを指定しない場合プレインテキストでクリップボードの内容が出力されます。例えば、macos-pasteboardの公式サイトの見出し(h1タグ)をコピーし、pbvを実行すると次のように出力されます。
$ pbv macos-pasteboard
HTML形式で出力する場合pbv public.htmlと実行します。
$ pbv public.html <h1 style="box-sizing: border-box; font-size: 2em; margin-top: 0px !important; margin-right: 0px; margin-bottom: 16px; margin-left: 0px; font-weight: 600; line-height: 1.25; padding-bottom: 0.3em; border-bottom: 1px solid var(--color-border-secondary); caret-color: rgb(36, 41, 46); color: rgb(36, 41, 46); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji"; font-style: normal; font-variant-caps: normal; letter-spacing: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; text-decoration: none;">macos-pasteboard</h1>
書式がたくさんついていてわかりづらいですが、h1タグが含まれており、HTMLプレビュー可能なエディタで確認すると次のように見出しとして表示されます。

テーブルや箇条書きなど、複雑な構造のHTMLにも対応しています。
pbv --helpでサポートしている形式を確認できます。利用可能なタイプは、コピーしたオブジェクトのタイプだけでなく、コピーしたプログラムによっても異なるとのこと。
$ pbv --help
Usage: pbv [-h|--help]
pbv [dataType [dataType [...]]] [-s|--stream]
Read contents of pasteboard as 'dataType'. If multiple types are specified,
tries each from left to right, stopping at first success. If omitted,
defaults to 'public.utf8-plain-text'.
Options:
-h|--help Show this help and exit
-s|--stream Start an infinite loop polling the Pasteboard 'changeCount',
running as usual whenever it changes
Available types for the 'Apple CFPasteboard general' pasteboard:
dyn.ah62d4rv4gu8y63n2nuuhg5pbsm4ca6dbsr4gnkduqf31k3pcr7u1e3basv61a3k
NeXT smart paste pasteboard type
com.apple.webarchive
Apple Web Archive pasteboard type
public.rtf
NeXT Rich Text Format v1.0 pasteboard type
public.html
Apple HTML pasteboard type
public.utf8-plain-text
NSStringPboardType
com.apple.WebKit.custom-pasteboard-data
public.utf16-external-plain-text
CorePasteboardFlavorType 0x75743136
dyn.ah62d4rv4gk81n65yru
CorePasteboardFlavorType 0x7573746C
com.apple.traditional-mac-plain-text
CorePasteboardFlavorType 0x54455854
dyn.ah62d4rv4gk81g7d3ru
CorePasteboardFlavorType 0x7374796C
プログラムの処理内容が気になる方は、pbv.swiftを確認すると良いかもしれません。
まとめ
macos-pasteboardを使用すると、macOSのクリップボードの内容をHTML形式でコピーすることができます。標準のpbpasteに存在しない機能を求めている方におすすめします。
