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
2019년 1월 11일
@Hafiz: Sorry, you want a tool which removes white spaces from source code and photos? How strange.
채택된 답변
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.
댓글 수: 0
추가 답변 (1개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Software Development Tools에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!