11

有谁知道自动清理 MATLAB/Octave 脚本缩进的现有方法?我有别人的代码(不,真的!),这太可怕了——没有一个循环或函数是缩进的,其他行的一半缩进到明显随机的深度。

MATLAB 的问题在于它不使用大括号,因此 C++ 样式的缩进器不起作用。Python 的可能会进行一些修改,如果我找不到预先存在的解决方案,我会尝试。

基本上它只需要在以function, for, if, while... 开头的行之后缩进行,并且以 , 开头的行不缩进end*,我认为...

澄清:正如 Jonas 所指出的,MATLAB 用户可以选择全部,并ctrl+I调整缩进。不幸的是,我无法访问 MATLAB 编辑器,而且能够一次自动缩进一批文件也很好。

4

4 回答 4

15

CTRL+A(全选),然后是CTRL+I(自动缩进)将在 Matlab 编辑器中发挥作用。

于 2011-01-28T01:46:33.137 回答
5

啊,我应该知道emacs和vi会有答案。我真的应该学习其中之一。无论如何,我对我正在做的工作感到沮丧,并把它写成一个置换活动。删除+ '.test.m'要替换的文件:

#!/usr/bin/env python

import re, sys

def startswith(line=""):
    # these need some word-boundary condition, but \b isn't working
    ctrlstart = '\s*(function|if|while|for|switch)'
    ctrlcont = '\s*(elseif|else|case|catch|otherwise)'
    ctrlend = '\s*(end|endfunction|endif|endwhile|endfor|endswitch)'
    match = re.match(ctrlstart, line)
    if ( match != None ) :
        return ['start',  match.group(0)]
    match=re.match(ctrlcont, line) 
    if ( match!=None ) :
        return ['cont',  match.group(0)]
    match=re.match(ctrlend, line)
    if ( match!=None ) :
        return ['end',  match.group(0)]
    else :
        return [False,  None]

def main( filelist = list() ) :
    for filename in filelist:
        nextindent = 0
        indentmult = 2
        file = open(filename, 'r')
        filelines = file.readlines()
        for ind in range(0, len(filelines)) :
            indentlevel = nextindent
            match = startswith(filelines[ind])
            if match[0] == 'start' :
                nextindent += 1
            elif match[0] == 'cont' :
                indentlevel -= 1
            elif match[0] == 'end' :
                indentlevel -= 1
                nextindent -= 1
            elif match[0] == False :
                nextindent = indentlevel
            filelines[ind] = ' '*indentlevel*indentmult + filelines[ind].lstrip().rstrip() +'\n'
        outfile = open(filename + '.test.m', 'w')
        outfile.writelines(filelines)
        file.close()
        outfile.close()

args = []
for arg in sys.argv[1:] :
    args += [str(arg)]
main(args)
于 2011-01-28T09:42:26.507 回答
2

我尝试了 emacs 的方式,但它不起作用,我是 ubuntu 和 octave 的新手。所以我采取了最简单的方法:D,为我缩进代码的在线网站,我可以复制/粘贴新的干净代码。

http://base-n.de/matlab/code_beautifier.html

于 2016-11-22T10:10:41.703 回答
-1

这是一个 vim 插件,用于自动缩进和语法高亮八度代码

https://github.com/tranvansang/octave.vim

于 2017-04-25T12:06:04.347 回答