Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szapp/762b40539b4b8670660e449936e26fe0 to your computer and use it in GitHub Desktop.
Save szapp/762b40539b4b8670660e449936e26fe0 to your computer and use it in GitHub Desktop.
Improved to replace the text only if it was changed to prevent the "unsaved" asterisk
% To remove a Matlab trailing whitespace in the editor
% Original Author: Sam Roberts
% http://stackoverflow.com/questions/19770347/how-to-auto-remove-trailing-whitespaces-on-save-in-matlab
% Modified by Mark Harfouche to remember cursor location
%
%
% Temp variable for shortcut. Give it an unusual name so it's unlikely to
% conflict with anything in the workspace.
shtcutwh__ = struct;
% Check that the editor is available.
if ~matlab.desktop.editor.isEditorAvailable
return
end
% Check that a document exists.
shtcutwh__.activeDoc = matlab.desktop.editor.getActive;
if isempty(shtcutwh__.activeDoc)
return
end
% save the old cursor location
shtcutwh__.Selection = shtcutwh__.activeDoc.Selection;
% Get the current text.
shtcutwh__.txt = shtcutwh__.activeDoc.Text;
% Remove trailing whitespace from each line.
shtcutwh__.lines = deblank(regexp(shtcutwh__.txt,'[^\n]*(\n)|[^\n]*$', 'match'));
% remove the trailing blank lines
for n__ = length(shtcutwh__.lines):-1:1
if length(shtcutwh__.lines{n__}) == 0
shtcutwh__.lines(n__) = [];
else
break
end
end
% Reconcatenate lines.
shtcutwh__.addNewline = @(x)sprintf('%s\n',x);
shtcutwh__.lines = cellfun(shtcutwh__.addNewline, shtcutwh__.lines, 'UniformOutput', false);
% If you always want to add a newline at the end of the file, comment this line out
% Remove the last newline character
shtcutwh__.lines{end}(end) = '';
shtcutwh__.newtxt = horzcat(shtcutwh__.lines{:});
% Check for changes
if (~strcmp(shtcutwh__.activeDoc.Text, shtcutwh__.newtxt))
% Set the current text.
shtcutwh__.activeDoc.Text = shtcutwh__.newtxt;
% Place the cursor back
shtcutwh__.activeDoc.Selection = shtcutwh__.Selection;
end
% Delete temp variable.
clear shtcutwh__ n__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment