Search code examples
matlabeditorsaveremoving-whitespacetrailing

How to auto-remove trailing whitespaces on save in Matlab?


I don't find an essential feature in Matlab 2012b:

Remove trailing whitespaces on save.

Related:

How to auto-remove trailing whitespace in Eclipse?

Aptana 3 - How remove trailing whitespaces on save


Solution

  • I had the same need, and wrote a little script to do something close. Put the following in a MATLAB desktop shortcut. Whenever you click the shortcut button, it will strip trailing whitespace from the active file in the editor. Not quite as good as automatically doing it on save - you need to remember to press the button before saving - but nearly. Tested on 11b, 12a, and 13b, but should also be fine on 12b.

    Hope that helps!

    % Temp variable for shortcut. Give it an unusual name so it's unlikely to
    % conflict with anything in the workspace.
    shtcutwh__ = struct;
    
    % Check that the editor is available.
    if ~matlab.desktop.editor.isEditorAvailable
        return
    end
    
    % Check that a document exists.
    shtcutwh__.activeDoc = matlab.desktop.editor.getActive;
    if isempty(shtcutwh__.activeDoc)
        return
    end
    
    % Get the current text.
    shtcutwh__.txt = shtcutwh__.activeDoc.Text;
    
    % Remove trailing whitespace from each line.
    shtcutwh__.lines = deblank(regexp(shtcutwh__.txt,'[^\n]*(\n)|[^\n]*$', 'match'));
    
    % Reconcatenate lines.
    shtcutwh__.addNewline = @(x)sprintf('%s\n',x);
    shtcutwh__.lines = cellfun(shtcutwh__.addNewline, shtcutwh__.lines, 'UniformOutput', false);
    shtcutwh__.newtxt = horzcat(shtcutwh__.lines{:});
    
    % Set the current text.
    shtcutwh__.activeDoc.Text = shtcutwh__.newtxt;
    
    % Delete temp variable.
    clear shtcutwh__