如何縮排“ed”中的程式碼區塊?

如何縮排“ed”中的程式碼區塊?

我喜歡用於ed小的編輯。目前,我只需手動按空白鍵即可縮排ed. UNIX 的作者就是這樣縮排他們的程式碼的嗎ed?或者他們使用了一些我不知道的快捷方式?

答案1

我認為「UNIX 的作者」最可能的意圖是「一項工作,一種工具」的良好方法:使用 編寫程式碼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/^/ /向行首添加兩個空格,而無需進行其他更改。

#include下面是一個範例編輯會話,其中輸入了一個簡單的 C 程序,在s 和之間沒有縮排或空格main#在命令引入註釋之前。

$ 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

相關內容