アイソモカ

知の遊牧民の開発記録

論文をコピペするとき “- “ が邪魔なので消す (Mac)

論文のpdfの本文コピペすると、改行の位置に “- “ ハイフンスペースが挟まってしまう場合がある。邪魔なので、Automator と AppleScript を使ってハイフンスペースを除去するアプリを設定した。

基本的な考え方としては、クリップボードの内容を AppleScript で受け取り、編集して、クリップボードに戻す。

設定方法とスクリプト

ChatGPT に教わりながら作った。手順は次の通り。

  • Autometer を開く
  • Application 新規作成を選択
  • 検索窓に “AppleScript” と入力し、AppleScriptのアクションをワークフローに追加する
  • AppleScriptエディタに以下のコードを貼り付ける
on run {input, parameters}
    set clipboardContents to the clipboard
    set modifiedContents to do shell script "echo " & quoted form of clipboardContents & " | sed -E 's/([a-zA-Z])- ([a-zA-Z])/'\"\\1\\2\"'/g'"
    set the clipboard to modifiedContents
    beep
    return input
end run
  • “▷” (右向き三角)ボタンを押して実行し、想定通り動作するか確認する
  • ファイル > 保存 から、名前をつけて保存する "rm_hypenspace.app"
  • アプリを Dock に追加するか、キーボードショートカットを設定して使いやすくする

使い方

  1. 文章を選択してコピー (command + c)
  2. 上記で作ったアプリ “rm_hypenspace” を実行する
  3. 貼り付ける (command + p)

ハイフンスペースを除去した例

# コピーしてすぐの文
Neural machine translation (NMT) mod- els typically operate with a fixed vocabu- lary, but translation is an open-vocabulary problem.
👇
# ハイフンスペースを除去した文
Neural machine translation (NMT) models typically operate with a fixed vocabulary, but translation is an open-vocabulary problem.

上の文は “Neural Machine Translation of Rare Words with Subword Units” (Sennrich et al., 2016) から。

スクリプトの解説

  • set clipboardContents to the clipboard AppleScriptで、クリップボードの内容を変数 clipboardContents に保存する
  • set modifiedContents to do shell script "echo " & quoted form of clipboardContents & " | sed -E 's/([a-zA-Z])- ([a-zA-Z])/‘\”\\1\\2\”’/g’” 変数を ShellScript に渡し、sed でハイフンスペースのない文字列へ置換する
  • ちなみにここで、quoted form of を使うことで、クリップボードの内容がエスケープされて安全になる
  • sed では、-とその前後の([a-zA-Z])(アルファベット大文字小文字)をキャプチャし、 \1\2 でキャプチャした文字だけを結合するという置換を行なっている
  • set the clipboard to modifiedContents 上で実行した内容をクリップボードに戻す
  • beep アプリが実行をお知らせするビープ音を鳴らす
  • もし視覚的にお知らせしたかったら、display notification "Clipboard modified" with title "rm_hypenspace App" などで通知を出すように変更してもいいね

クリップボードの内容を直接編集できるの、便利だな。他の場面でも使える。

最後に、最近読んでいる本のアフィリエイトリンクを貼ります。