用于MATLAB或Octave的自动缩进清理器?

nau*_*101 11 matlab coding-style indentation octave auto-indent

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

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

基本上,它会只需要缩进开始的行线后function,for,if,while...和取消缩进线开始end*,我想......

澄清:正如Jonas所指出的,MATLAB用户可以只选择所有内容,并使ctrl+I缩进成为可能.不幸的是,我无法访问MATLAB编辑器,能够一次自动缩进一批文件也很不错.

Jon*_*nas 15

CTRL+A(选择全部),然后CTRL+I(自动缩进)将在Matlab编辑器中完成.

  • 具有八度模式的Emacs可以做到这一点.Emacs或Vim(如Jonas所说)+宏可以批量执行(您不必手动打开所有文件). (3认同)
  • 你得到了那个投票,从技术上讲,它回答了这个问题.不幸的是,我实际上使用的是八度,所以我没有matlab编辑器. (2认同)
  • @ naught101:谢谢你的upvote.像[this](http://www.mathworks.com/matlabcentral/fileexchange/21798-editing-matlab-files-in-vim)这样的东西会有帮助吗? (2认同)

nau*_*101 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)
Run Code Online (Sandbox Code Playgroud)