LoginSignup
5
6

More than 5 years have passed since last update.

Rubyで書くCotEditorスクリプト

Last updated at Posted at 2014-12-16

MacではテキストエディタとしてCotEditorを常用しています(コーディングはSublime Text)。

ソートがしたくてスクリプトを触ってみたところ、Rubyで簡単にCotEditorスクリプトが書けるっぽいです。

マジックコメント

CotEditorスクリプトでは、先頭行に次のマジックコメントが必要です。

#!/usr/bin/env ruby -Ku
#%%%{CotEditorXInput=Selection}%%%
#%%%{CotEditorXOutput=ReplaceSelection}%%%

サンプルスクリプトにはファイル末尾にexitが書かれていますが、不要です。

選択部分が標準入力になる

CotEditorでは文字列を選択しながらスクリプトを実行します。
選択した部分は標準入力となります。
何も選択せずにスクリプトを実行しても、スクリプトは実行されないようです。

getsは、呼び出される度に標準入力の中身を1行ずつ取り出して返却します。

# あああ\nいいい\nううう を選択した状態でスクリプトを実行
gets #=> "あああ\n"
gets #=> "いいい\n"
gets #=> "ううう"
gets #=> nil

一方$stdin.readは標準入力の中身を全て取り出して返却します。

# あああ\nいいい\nううう を選択した状態でスクリプトを実行
$stdin.read #=> "あああ\nいいい\nううう"
$stdin.read #=> ""

$stdin.readを一度評価した時点で標準入力が空になるので、その後getsを評価してもnilが返されます。

# あああ\nいいい\nううう を選択した状態でスクリプトを実行
$stdin.read #=> "あああ\nいいい\nううう"
gets #=> nil

標準出力が選択部分に反映される

ここは理解できているか怪しいですが、、

print等のメソッドを使うと、選択部分を上書きされる形で出力されます。
典型的な例は、while gets .. endで回すものです。

# 行頭に "// " を付加する
while gets
  print "// #{$_}" # $_ : 最後に実行されたgetsまたはreadlineの戻り値
end

# $_ は「知らなければ書けない・読めない」ので、良くないと考える人もいる
# cf. http://www.sist.ac.jp/~suganuma/home/Ruby/library/var/var.htm

このように、printは選択した行から数えてn行目(n:getsを呼び出した回数)に対して行われます。
たとえば、次のようなコードが可能です。

# 選択部分から数えて3の倍数行はFIZZに置換する
i = 1
while var = gets
  ( i % 3 == 0 ) ? print("FIZZ\n") : print(var)
  i += 1
end

ソートスクリプトの実装

coteditor_sort.rb
#!/usr/bin/env ruby -Ku
#%%%{CotEditorXInput=Selection}%%%
#%%%{CotEditorXOutput=ReplaceSelection}%%%

input = $stdin.read
output = input.split("\n").sort.join("\n")
print output

簡単に書けます。

参考

5
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6