How to remove trailing whitespace on save

조회 수: 18 (최근 30일)
Hafiz Luqman
Hafiz Luqman 2019년 1월 11일
답변: Tim 2020년 2월 5일
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