How to remove trailing whitespace on save

16 views (last 30 days)
I am using MATLAB R2018b. Does matlab provide function to remove trailing white spaces on saving file ?
  5 Comments
Jan
Jan on 11 Jan 2019
@Hafiz: Sorry, you want a tool which removes white spaces from source code and photos? How strange.
Hafiz Luqman
Hafiz Luqman on 11 Jan 2019
@jan the word 'optional' mean nice to have. Main query is about remove whitespaces from code. Only those people who know answer/solution are welcomed to comment or reply. Thanks

Sign in to comment.

Accepted Answer

Jan
Jan on 11 Jan 2019
Edited: Jan on 11 Jan 2019
No, there is no such builtin tool. You can use a simple tool like this to cleanup your code:
!!!!!!! TEST THIS EXHAUSTUIVELY BEFORE USING !!!!!!!!!!
function CleanMyFile(FileName)
S = fileread(FileName);
C = strsplit(S, '\n');
C = deblank(C);
C = strrep(sprintf('\t'), blank(3)); % Replace TAB by 3 spaces
fid = fopen(FileName, 'w');
if fid == -1
error('Cannot open file for writing: %s', FileName);
end
fprintf(fid, '%s\n', C{:});
fclose(fid);
end
I added a conversion of TABs to spaces. Maybe you want to call it for all your files:
Base = 'C:\YourMatlabFolder';
Files = dir(fullfile(Base, '\**\*.m'));
for k = 1:numel(Files)
FileName = fullfile(Files(k).folder, Files(k).name);
fprintf('Cleaning: %s\n', FileName);
CleanMyFile(FileName);
end
You could do the same with all open files in the editor:
function CleanupEditorFiles(Opt)
if nargin == 0
Opt = 'active'; % Or 'all' if you like
end
if strcmpi(Opt, 'active') % Active file:
AllDoc = matlab.desktop.editor.getActive;
else % All open files:
AllDoc = matlab.desktop.editor.getAll;
end
for iDoc = 1:numel(AllDoc)
Doc = AllDoc(iDoc);
File = Doc.Filename;
Name = GetFileName(File);
% No actions if file is opened as read-nonly:
if ~Doc.Editable
fprintf(' Locked: %s\n', Name);
continue;
end
origText = Doc.Text;
C = strsplit(origText, '\n');
C = deblank(C);
C = strrep(sprintf('\t'), blank(3)); % Replace TAB by 3 spaces
newText = sprintf(fid, '%s\n', C{:});
if ~strcmp(newText, origText)
fprintf(' update: %s\n', File);
cursor = Doc.Selection;
Doc.Text = newText;
% Restore cursor position, but not the selection:
if ~isempty(cursor)
Doc.goToPositionInLine(cursor(1), 1);
end
end
end
!!!!!!! TEST THIS EXHAUSTUIVELY BEFORE USING !!!!!!!!!!
Create a backup before testing. This was written in the editor of the forum. Add meaningful comments, if you like the function.

More Answers (1)

Tim
Tim on 5 Feb 2020

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!