`ed` でコードブロックをインデントするにはどうすればいいでしょうか?

`ed` でコードブロックをインデントするにはどうすればいいでしょうか?

ちょっとした編集には を使うのが好きですed。現在は、 内のコード ブロックをインデントするには、手動でスペースバーを押すだけですed。UNIX の作者は 内でコードをインデントする方法としてこれを使っていますかed? それとも、私が知らないショートカットを使っていたのでしょうか?

答え1

「UNIX の作者」が意図していた可能性が最も高い方法は、古き良き「1 つのジョブ、1 つのツール」アプローチ、つまり を使用してコードを記述しedindentその後に を使用して適切にインデントする、というものだったと思います。

答え2

行エディターなので、ed行間のインデントは追跡されません。

e !commandファイルに対して外部コードフォーマッタを呼び出すために使用できます。

単純な C プログラムを作成、編集、インデントする一般的な編集セッションは次のようになります。

$ rm test.c
$ ed -p'> ' test.c
test.c: No such file or directory
> H
cannot open input file
> i
#include <stdlib.h>

int main(void)
{
/* There is no place else to go.
 * The theatre is closed.
 */

return EXIT_SUCCESS;
}
.
> /void/
int main(void)
> s/void/int argc, char **argv/
> %p
#include <stdlib.h>

int main(int argc, char **argv)
{
/* There is no place else to go.
 * The theatre is closed.
 */

return EXIT_SUCCESS;
}
> w
142
> e !clang-format test.c
158
> %p
#include <stdlib.h>

int main(int argc, char **argv)
{
    /* There is no place else to go.
     * The theatre is closed.
     */

    return EXIT_SUCCESS;
}
> w
158
> q
$

コード フォーマッタ (clang-formatこの場合は ) を呼び出す前と後にファイルを書き込むことに注意してください。ファイルに書き込みtest.c、このファイルでコマンドを実行した結果を読み込んでいます。

答え3

私の知る限り、ed行をインデントするための特定のコマンドはありません。自動的にインデントされることはなく、行の先頭に固定量の空白を追加するための基本的なコマンドもありません。

ただし、たとえば を使用するとs/^/ /、行の先頭に 2 つのスペースを追加し、それ以外の変更を加える必要はありません。

以下は、コマンドがコメントを導入する前に、インデントや#includes とmain.の間のスペースなしで入力された単純な C プログラムの編集セッションの例です。#

$ ed '-p> ' hello_world.c
hello_world.c: No such file or directory
# print the buffer
> ,n
?
# insert text until "." from the beginning of the buffer.
> 0a
#include <stdio.h>
#include <stdlib.h>
int main() {
printf("%d\n", 47);
return 0;
}
# print the buffer
> ,n
1   #include <stdio.h>
2   #include <stdlib.h>
3   int main() {
4   printf("%d\n", 47);
5   return 0;
6   }
# indent lines 4 and 5
> 4,5s/^/  /
# print the buffer again, see if it makes sense.
> ,n
1   #include <stdio.h>
2   #include <stdlib.h>
3   int main() {
4     printf("%d\n", 47);
5     return 0;
6   }
# add a blank line after line 2.
> 2a

.
# print the buffer again out of paranoia.
> ,n
1   #include <stdio.h>
2   #include <stdlib.h>
3   
4   int main() {
5     printf("%d\n", 47);
6     return 0;
7   }
# looks good, write and quit.
> wq
# size of file in bytes.
89

関連情報