规范Matlab代码

以下程序用于规范Matlab代码,仅为备用。
原作者:打浦桥程序员

function formatMcode
  try %#ok
    document = matlab.desktop.editor.getActive;
    position = document.Selection;
    document.Text = format(document.Text);
    document.goToPositionInLine(position(1), position(2)) % 还原光标位置
    document.smartIndentContents();
  end
  
function code = format(code)
  code = regexprep(code, {'(\S)[ \f\v\t]+\n', '([^\n])$'}, '$1\n');
  tree = mtree(code, '-comments');
  assert(isempty(tree.mtfind('Kind', 'ERR')))
  
  % a(:) 不替换为 a( : )
  colons = tree.mtfind('Kind', 'COLON');
  colonPos = colons.position();
  colonPos = colonPos(colons.lefttreepos == colons.righttreepos);
  
  % 字符串、注释、数值中的符号以及一元操作符不处理
  exc = tree.mtfind('Kind', 'CHARVECTOR') | tree.mtfind('Kind', 'STRING') | ...
    tree.mtfind('Kind', 'DOUBLE') | tree.mtfind('Kind', 'COMMENT') | ...
    tree.mtfind('Kind', 'UPLUS') | tree.mtfind('Kind', 'UMINUS');
  excPos = [colonPos' ...
    cell2mat(arrayfun(@colon, exc.lefttreepos, exc.righttreepos, 'un', 0)')];
  
  [ops, code, start] = regexp(string(code), ...
    '(\.(\^|\*|/|\\)|<=|>=|==|~=|&&|\|\||\+|\-|\*|\\|/|\^|\||&|<|>|=|,|;|:)', ...
    'match', 'split', 'start');
  idx = ~ismember(start, excPos);
  code(idx) = regexprep(code(idx), '[ \f\r\t\v]+$', '');
  code([false idx]) = regexprep(code([false idx]), '^[ \f\r\t\v]+', '');
  
  ops(idx) = ops(idx) + " ";
  idx = idx & ~ops.startsWith(["," ";"]);
  ops(idx) = " " + ops(idx);
  code = char(strjoin([code; ops ""], ''));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值