LoginSignup
2
0

More than 1 year has passed since last update.

[秀丸エディタ] [マクロ] grep結果に対し、検索ヒット行の内容を前後の行内容に変更

Posted at

はじめに

以下が投稿の動機です。刺さらないという方は、そっ閉じしていただければと思います。

grep結果には検索にヒットした行の内容が表示されます。
普段はそれで良いんですが、前後の内容もほしいときがあります。

そのような機能(というか秀丸マクロ)は、公式サイトに行けばあるようです。
しかし、前後の内容も出力すると、grep結果の行数に意味があるとき(例:X箇所を変更した証拠として、grepでX行ヒットすることを見たいとき)にどうなんだろうか?と思って、自作してみることにしました。

・・・この投稿で示す秀丸マクロも、世の中にあったら申し訳ないです。
あとは、他のエディタでマクロを組める方のお役に立てたら嬉しいです。

マクロを作る背景

以下にイメージで示すようなyamlがあるとします。
(別に、xmlでもjsonでも良いですが)

params:
  - path: "001/"
    exec: off
  - path: "001/001/"
    exec: off
  - path: "002/"
    exec: off
  - path: "002/001/"
    exec: off
  - path: "002/002/"
    exec: off
#    :
#    :
# 以降、省略します
# (似たようなデータが延々と続きます)

このyamlに、もしも何百もの要素があって、意図した10箇所だけexec: onにするとき、その作業が終わった後で確認のためにgrepすると、以下のようになります。

hoge.yaml(5):     exec: on
hoge.yaml(15):     exec: on
hoge.yaml(17):     exec: on
hoge.yaml(39):     exec: on
hoge.yaml(77):     exec: on
hoge.yaml(81):     exec: on
hoge.yaml(83):     exec: on
hoge.yaml(85):     exec: on
hoge.yaml(93):     exec: on
hoge.yaml(101):     exec: on

10箇所をexec: onに変更できたことは分かりますが、意図した10箇所を変更したかどうかは分からないです。
そこで、秀丸マクロを作成して、grep結果を以下のように変えることを狙いました。

hoge.yaml(5):   - path: "001/001/"
hoge.yaml(15):   - path: "004/002/"
hoge.yaml(17):   - path: "004/003/"
hoge.yaml(39):   - path: "007/005/"
hoge.yaml(77):   - path: "015/001/"
hoge.yaml(81):   - path: "015/003/"
hoge.yaml(83):   - path: "015/004/"
hoge.yaml(85):   - path: "015/005/"
hoge.yaml(93):   - path: "017/001/"
hoge.yaml(101):   - path: "017/005/"

作成したマクロ

以下になりました。(秀丸マクロ用の強調表示を知らず、適当な表示で申し訳ないです)
バグがあったら、教えていただけると嬉しいです。

// オフセット行数の入力
$Offset = input("オフセット行数(整数)を入力してください。\n" +
				" ・秀丸でタグジャンプできるgrep結果の選択中が前提\n" +
				" ・負の数を指定した場合、grepヒット箇所より前を取得", "0");
#Offset = val($Offset) / 1;
if (str(#Offset) != $Offset) {
	// 整数入力でなければ終了
	endmacro;
}

// grep結果の行内容部分クリア
replaceall "([\\(\\:][0-9]+\\)?\\:).*", "\\1 ", regular;
#LineNo = 0;
moveto 0, #LineNo;
#Source = hidemaruhandle(0);

// grep結果の各行ループ
while (code != eof) {
	// ヒット箇所からのオフセット位置に移動
	tagjump;
	#Dest = hidemaruhandle(0);
	if (#Offset < 0) {
		up -#Offset;
	} else if (#Offset > 0) {
		down #Offset;
	} else {
		// 何もしない
	}
	
	// 移動した位置の行内容を取得してクローズ
	$LineStr = gettext(0, y, linelen, y);
	setactivehidemaru #Source;
	closehidemaruforced #Dest;
	
	// grep結果に行内容を挿入
	golineend;
	insert $LineStr;
	
	// 次行に進む
	#LineNo = #LineNo + 1;
	moveto 0, #LineNo;
}
endmacro;
2
0
0

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
2
0