How to remove trailing whitespace on save

18 次查看(过去 30 天)
I am using MATLAB R2018b. Does matlab provide function to remove trailing white spaces on saving file ?
  5 个评论
Jan
Jan 2019-1-11
@Hafiz: Sorry, you want a tool which removes white spaces from source code and photos? How strange.
Hafiz Luqman
Hafiz Luqman 2019-1-11
@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

请先登录,再进行评论。

采纳的回答

Jan
Jan 2019-1-11
编辑:Jan 2019-1-11
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.

更多回答(1 个)

Tim
Tim 2020-2-5

类别

Help CenterFile Exchange 中查找有关 Software Development Tools 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by