背景:我使用PHPStylist缩进PHP代码,这通常很好。但是,当它找到带有许多参数的函数调用时,它会将所有这些参数放在一行上。例如,bind_param()
调用很容易就是300个字符。
这与我们的编码样式指南不相符,它指示最大行长度为180个字符。
我们的缩进脚本已经有一个sed命令来清除PHPStylist留下的尾随空格,所以我在想,也可以打破太长的行,但只能用逗号?
示例输入:
function xyz()
{
somecall($somevariable1, $somevariable1, $somevariable1, $somevariable1, $somevariable1, $somevariable1, $somevariable1, $somevariable1, $somevariable1);
}
示例输出:
function xyz()
{
somecall($somevariable1, $somevariable1, $somevariable1, $somevariable1,
$somevariable1, $somevariable1, $somevariable1, $somevariable1, $somevariable1);
}
(如果脚本也可以在下一行中巧妙地缩进下一行,我会认为这很难在sed中进行。在awk,perl,python或其他常用工具中的解决方案也会非常受欢迎。)
答案 0 :(得分:2)
作为第一个建议,这样的事情?
sed 's/.\{70\}[^,]*,/&\
/g' file
--- ---编辑
对于缩进,您可以尝试:
sed -e 's/\(.\{70\}[^,]*,\)[[:blank:]]*/\1\
/g; tend' -e n -e :end -e 's/\(^[[:blank:]]*\)\(.*\n\)/\1\2\1/ ' file
答案 1 :(得分:1)
这个awk脚本会在最大行长度之前的最后一个逗号中分割行,如果愿意,可以将其设置为运行时参数。它将分割线比原始线条缩进了4个空格:
$ cat file
function xyz()
{
somecall($somevariable1, $somevariable2, $somevariable3, $somevariable4, $somevariable5, $somevariable6, $somevariable7, $somevariable8, $somevariable9);
somecall($somevariable1, $somevariable2, $somevariable3, $somevariable4, $somevariable5, $somevariable6, $somevariable7, $somevariable8, $somevariable9);
}
$ awk -f tst.awk file
function xyz()
{
somecall($somevariable1, $somevariable2, $somevariable3,
$somevariable4, $somevariable5, $somevariable6,
$somevariable7, $somevariable8,
$somevariable9);
somecall($somevariable1, $somevariable2, $somevariable3,
$somevariable4, $somevariable5, $somevariable6,
$somevariable7, $somevariable8,
$somevariable9);
}
$
$ cat tst.awk
BEGIN{ maxLength = (maxLength ? maxLength : 66) }
(length($0) > maxLength) && /,/ {
indent = $0
sub(/[^[:space:]].*/,"",indent)
tail = $0
while (tail ~ /[^[:space:]]/) {
head = substr(tail,1,maxLength)
sub(/,[^,]+$/,",",head)
tail = substr(tail,length(head)+1)
sub(/^[[:space:]]*/,indent" ",tail)
print head
}
next
}
1
$ awk -v maxLength=100 -f tst.awk file
function xyz()
{
somecall($somevariable1, $somevariable2, $somevariable3, $somevariable4, $somevariable5,
$somevariable6, $somevariable7, $somevariable8,
$somevariable9);
somecall($somevariable1, $somevariable2, $somevariable3, $somevariable4, $somevariable5,
$somevariable6, $somevariable7, $somevariable8,
$somevariable9);
}
$ awk -v maxLength=30 -f tst.awk file
function xyz()
{
somecall($somevariable1,
$somevariable2,
$somevariable3,
$somevariable4,
$somevariable5,
$somevariable6,
$somevariable7,
$somevariable8,
$somevariable9);
somecall($somevariable1,
$somevariable2,
$somevariable3,
$somevariable4,
$somevariable5,
$somevariable6,
$somevariable7,
$somevariable8,
$somevariable9);
}