How to remove trailing whitespace on save
19 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hafiz Luqman
el 11 de En. de 2019
Respondida: Tim
el 5 de Feb. de 2020
I am using MATLAB R2018b. Does matlab provide function to remove trailing white spaces on saving file ?
5 comentarios
Jan
el 11 de En. de 2019
@Hafiz: Sorry, you want a tool which removes white spaces from source code and photos? How strange.
Respuesta aceptada
Jan
el 11 de En. de 2019
Editada: Jan
el 11 de En. de 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.
0 comentarios
Más respuestas (1)
Tim
el 5 de Feb. de 2020
See answer on SO: https://stackoverflow.com/a/21171788/2909078
0 comentarios
Ver también
Categorías
Más información sobre Software Development Tools en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!