How can I add a backup an option, addSaveCallback, to save a timestamped version of my file, to the MATLAB editor?

조회 수: 12 (최근 30일)
% I'd like to add the option to save backup files - earlier versions every time I save a file in the Matlab editor
editorObj = matlab.desktop.editor.getActive;
editorObj.addSaveCallback(@mySaveCallback);
function mySaveCallback(~, ~)
disp('File has been saved!');
% Add your custom code here
saveBackup(originalFilePath);
end
function saveBackup(originalFilePath)
% Check if the file exists
if ~isfile(originalFilePath)
error('The specified file does not exist.');
end
% Extract file parts
[filePath, fileName, fileExt] = fileparts(originalFilePath);
% Create a timestamp
timestamp = datestr(now, 'yyyymmdd_HHMMSS');
% Define the backup file name
backupFileName = sprintf('%s_backup_%s%s', fileName, timestamp, fileExt);
backupFilePath = fullfile(filePath, backupFileName);
% Copy the file to create a backup
copyfile(originalFilePath, backupFilePath);
fprintf('Backup saved as: %s\n', backupFilePath);
end
  댓글 수: 6
dpb
dpb 2025년 9월 12일
편집: dpb 2025년 9월 12일
It appears the use case here is one of making a simple roll-your-own version control system substitute based on earlier response from @Mark of "The PC I want to run this on is so heavily locked down, I can't run a local version control such as git".
Mark
Mark 2025년 10월 1일 13:13
Yes. If my script or function stops performing after many edits this makes it easy to compare an earlier version and figure out what went wrong, or just revert to the earlier version.

댓글을 달려면 로그인하십시오.

채택된 답변

Yair Altman
Yair Altman 2025년 9월 9일
편집: Yair Altman 2025년 9월 9일
I believe that you can use the editor object's undocumented (hidden) ContentSaved event, as follows:
documentObj = matlab.desktop.editor.getActive;
hListener = addlistener(documentObj, 'ContentSaved', @mySaveCallback);
function mySaveCallback(hDocument, hEventData)
savedFilePath = hDocument.Filename;
saveBackup(savedFilePath);
end
For the record, here is how you can see similar undocumented (hidden) events of a Matlab object:
obj = matlab.desktop.editor.getActive;
mc = metaclass(obj);
events = mc.EventList;
eventNames = {events.Name};
eventAccess = {events.ListenAccess};
eventHidden = [events.Hidden];
[{'Event name','Access','Hidden'}; ...
sortrows([eventNames; eventAccess; arrayfun(@mat2str,eventHidden,'Uniform',false)]')]
and the output in this specific case would be:
ans =
4×3 cell array
{'Event name' } {'Access'} {'Hidden'}
{'ContentDirtied' } {'public'} {'true' }
{'ContentSaved' } {'public'} {'true' }
{'ObjectBeingDestroyed'} {'public'} {'false' }

추가 답변 (3개)

dpb
dpb 2025년 8월 29일
편집: dpb 2025년 8월 29일
I "know nuthink!" about using the programmatic interface but it appears it doesn't have exposed properties for callback functions as do graphics objects like axes but instead you would use addlistener similarly.
The returned handle is to the document and there are no code examples for addlisteener other than one for a figure so I'm not sure just what you would use for the events...in fact, trying this locally I find
>> editorObj = matlab.desktop.editor.getActive
editorObj =
Document with properties:
Filename: '...\MATLAB\Work\writeopeningbalance.m'
Opened: 1
Language: 'MATLAB'
Text: 'function writeopeningbalance(tD,tM,fnOB)↵...
Selection: [9.00 3.00 9.00 3.00]
SelectedText: ''
Modified: 0
ExtendedSelection: [9.00 3.00 9.00 3.00]
ExtendedSelectedText: {''}
Editable: 1
>> events(editorObj)
Events for class matlab.desktop.editor.Document:
ObjectBeingDestroyed
>>
that makes it appear there is no publicly visible event for save or saveAs
I tried Yair Altman's tool to poke at object handles for hidden/undocumented properties, but it doesn't recognize the document handle so no dice there.
  댓글 수: 2
dpb
dpb 2025년 8월 29일
편집: dpb 2025년 8월 29일
However, does seem like a reasonable enhancement.
Submit this to Mathworks as an official support or enhancement request at <Product Support Page>
The alternative would be to use a code repository to handle this topic instead.
Mark
Mark 2025년 8월 29일
Thanks for having a go at this
I was hoping I had missed something but I agree with you that there are no obvious onClose or onSave callbacks exposed for the user. I'll submit an enhancement request as you suggest.
The PC I want to run this on is so heavily locked down, I can't run a local version control such as git.

댓글을 달려면 로그인하십시오.


Matt J
Matt J 2025년 8월 29일
편집: Matt J 2025년 8월 29일
Instead of trying to get the standard Save button to do what you want, you can make a Quick Access Toolbar button which runs your own customized save routine, as implemented in your saveBackup() code.
  댓글 수: 6
Mark
Mark 2025년 8월 30일

I like the custom save button or keyboard shortcuts options. I'll try those and report back.

dpb
dpb 2025년 8월 31일
Would be perfect if the keybindings would allow to overrule the present Ctrl-S

댓글을 달려면 로그인하십시오.


Steven Lord
Steven Lord 2025년 9월 9일
Do the Editor/Debugger Saving settings not satisfy your needs?
  댓글 수: 5
Steven Lord
Steven Lord 2025년 9월 16일
Sure, sounds like a reasonable enhancement to request via Technical Support. Please be sure to describe your desired workflow (how you would use this functionality if it existed) so that the developers can take it into account when or if they design this behavior.
However, I suspect that the developers may push back on this as it seems to me like there would be significant overlap between the functionality you've described and the source control interface MATLAB already provides. So the workflow would need to provide some pretty strong motivation.
dpb
dpb 2025년 9월 16일
편집: dpb 2025년 9월 17일
It's not neecessarily my particular workflow; @Mark provided the justification in that his environment doesn't give him access to the source control tool with which to use the interface.
The VMS-style version would/could simply be an additional option within the present backup selections that don't yield the same ability as is. I've missed it; I haven't put it into the editor for source files, but the workflow you hypothesized I handle by a script that saves the workplace variables to a named mat file including a desriptive comment with a companion tool to retrieve the last or a given comment match.
The version on m-files isn't at all a bad idea, however, without the extra of a full-blown vcs.
.I doubt it would ever get sufficient traction to be implemented, however, owing to that perception from the developers.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

제품


릴리스

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by