matlab快捷方式,自动加空格、缩进等美化代码功能

参考知乎MATLAB美化代码的神器 - 知乎 (zhihu.com)

zh博客将问题和代码写地很清楚,都是照搬过来
但没有具体matlab界面中详细操作

代码有以下问题:

  • 1 一行注释过长了, 导致要看完整, 不得不拖动水平进度条.
  • 2 逗号后面没有空格
  • 3 等号两边没有空格
  • 4 缩进一塌糊涂
step1:

代码,任意文件夹生成一个formatMcode.m文件

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 ""], ''));

生成.m文件

step2:

主页->收藏夹->新建收藏项->命名标签label“美化代码”->添加到快速访问工具栏,那两个工具栏打勾->图标有需要自己上传icon,这里使用默认图标->保存。

成功之后会显示

快捷方式显示在主页面右上角。点击图标,就完成上述缩进等美化功能。

注:再点击图标后,第一次使用会出现在命令框出现“需要添加到路径”。

会出现由于是任意路径生成.m文件,点击红色标框内容,自动生成语句。

addpath 'F:\'

然后再点击图标就成功。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值