Undocumented Matlab
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT
  • SERVICES
    • Consulting
    • Development
    • Training
    • Gallery
    • Testimonials
  • PRODUCTS
    • IQML: IQFeed-Matlab connector
    • IB-Matlab: InteractiveBrokers-Matlab connector
    • EODML: EODHistoricalData-Matlab connector
    • Webinars
  • BOOKS
    • Secrets of MATLAB-Java Programming
    • Accelerating MATLAB Performance
    • MATLAB Succinctly
  • ARTICLES
  • ABOUT
    • Policies
  • CONTACT

Recovering previous editor state

January 11, 2012 22 Comments

Editor with multiple loaded documents I find it very useful to use the Matlab editor’s ability to load multiple files to help me remember which files I still need to work on. I typically have a few dozen files loaded in the editor. I guess you could say that the editor’s list of files is a simple reflection of my open tasks. It would be extremely inconvenient if I ever lost this list.
Which is, unfortunately, exactly what happened to me yesterday.
I was about to close a figure window and accidentally closed the editor window that was behind it.
I was now in quite a jam: reopening the editor would not load all my files, but start with a blank (empty) editor. The Matlab editor, unlike modern browsers, does not have a ‘reopen last session’ option, and using the most-recently-used (MRU) files list would at best return the latest 9 files (the default Matlab preference is to have an MRU depth of only 4 files, but this is one of the very first things that I change whenever I install Matlab, along with a few other very questionable [IMHO] default preferences).
Luckily for me, there is an escape hatch: Matlab stores its Desktop windows state in a file called MATLABDesktop.xml that is located in the user’s prefdir folder. This file includes information about the position and state (docked/undocked etc.) of every Desktop window. Since the editor files are considered Desktop documents (you can see them under the Desktop’s main menu’s Window menu), they are also included in this file. When I closed the Editor, these documents were simply removed from the MATLABDesktop.xml file.
It turns out that Matlab automatically stores a backup version of this file in another file called MATLABDesktop.xml.prev, in the same prefdir folder. We can inspect the folder using our system’s file browser. For example, on Windows we could use:

winopen(prefdir)

winopen(prefdir)

So before doing anything else, I closed Matlab (I actually crashed it to prevent any cleanup tasks to accidentally erase this backup file, but that turned out to be an unnecessary precaution), deleted the latest MATLABDesktop.xml file, replaced it with a copy of the MATLABDesktop.xml.prev file (which I renamed MATLABDesktop.xml), and only then did I restart Matlab.
Problem solved – everything back to normal. Resume breathing. Once again I have my never-ending virtual task list in front of me as I write this.
Lessons learned:

  1. don’t be too quick on the close button trigger
  2. always keep a relatively recent backup copy of your important config files (BTW, I use the same advice with my FireFox browser, where I normally have dozens of open tabs – I keep a backup copy of the sessionstore.js file)
  3. if you do get into a jam, don’t do anything hasty that might make recovery impossible. Calm down, look around, and maybe you’ll find an automatic backup somewhere

Related posts:

  1. EditorMacro – assign a keyboard macro in the Matlab editor – EditorMacro is a new utility that enables setting keyboard macros in the Matlab editor. this post details its inner workings....
  2. Tri-state checkbox – Matlab checkboxes can easily be made to support tri-state functionality....
  3. Variables Editor scrolling – The Matlab Variables Editor can be accessed to provide immediate scrolling to a specified cell location. ...
  4. Spicing up the Matlab Editor – Matlab's Editor and Workspace can be enhanced quite significantly using an open-source utility. ...
  5. Determining axes zoom state – The information of whether or not an axes is zoomed or panned can easily be inferred from an internal undocumented object....
  6. Non-textual editor actions – The UIINSPECT utility can be used to expand EditorMacro capabilities to non-text-insertion actions. This is how:...
Desktop Editor Pure Matlab Undocumented feature
Print Print
« Previous
Next »
22 Responses
  1. Alexander January 12, 2012 at 01:33 Reply

    Hello Yair,

    in above article you state “…best return the latest 9 files (the default Matlab preference is to have an MRU depth of only 4 files, but this is one of the very first things that I change whenever I install Matlab, along with a few other very questionable [IMHO] default preferences).”.

    It might be interesting to me and maybe other readers what these questionable default preferences are. Perhaps you find the time to write an article on this topic.

    Alexander

  2. Rafael January 12, 2012 at 01:58 Reply

    One alternative I always do is to leave one blank unsaved file all the time open, so that when you close the editor by accident, it will first ask if you want to save that file, and then you have the option to cancel…
    BTW, I’m also curious about what are your ‘default’ preferences 🙂
    Mine are:
    -display format using short g (I always work with matrix that represent different states at each line, and I hate when MATLAB just shows everything as 1e5 * [1 0.0001 0.01] instead of [1e5 10 1e3])
    -increase java heap, I quite often hit the default value of 128mb…
    -change the default font from to Consolas
    -enable code folding for everything
    -change indentation mode to all functions
    -disable wrap comments (we have widescreen monitors, don’t need everything to be within 80 col anymore!)
    -increase the number of lines in the cmd window buffer (one of the libraries I use outputs a lot of text to the cmd window, and I want to be able to scroll up and see what was before)
    -when on linux, change the default keyboard set from emacs to windows (give me back my Ctrl+C Ctrl+V 🙂 )

    any other I’m missing?

  3. Amit January 12, 2012 at 11:02 Reply

    What could be really nice is to be able to easily change the colors of the names of the files, so as to group them into projects.

    And regarding default options, naturally remove the vertical line from the middle of the screen.

  4. Brian Emery January 12, 2012 at 14:05 Reply

    Very cool! It seems we have a similar work flow. It also seems a reasonable task then to write some code that will make saving and restoring different editor states for different projects an easy thing to do. I’ll get right on it …

  5. Robert Cumming January 14, 2012 at 01:46 Reply

    Yair,

    I had a similar problem a while back and wrote a function to manage it, I have finally uploaded it on Matlab FEX.

    Regards

    • Amit January 16, 2012 at 23:36 Reply

      Robert,
      This is simple and excellent , thank you.

  6. MLintFailureFiles or: Why can’t I save my m-file?! | Undocumented Matlab February 1, 2012 at 17:15 Reply

    […] a few weeks ago, when I explained how to use the stored editor state file that is stored in the prefdir folder […]

  7. CarzyOliv August 2, 2012 at 09:22 Reply

    Thaks a lot for this post.
    I use to work the same way you do (you = the original poster).
    It was a very hard task to automately recover my document bar after I closed and reopened an ancient project.
    Now it is, and I quote Tommy Lee Jones, Ladies Lingerie.

    Very great investigation.

    I resume the way I do :

    1. I have got a very ramified document bar in my editor I want to save and recover after.
    2. I write the command : winopen(prefdir)
    3. I copy the file MATLABDesktop.xml (this only very file) I found in the folder
    4. I paste the copy on the folder of my project, somewhere I can easily recover it in a far future.
    5. I close the editor.
    6. start a new project out of a blank document bar.
    7. long time after, I write the command winopen(prefdir)
    8. I close Matlab, using the regular way.
    9. paste into the previously opened prefdir directory the MATLABDesktop.xml related to the project I want to recover. Matlab use to be shut-down
    10. I open Matlab.
    11. I enjoy a automatic startup of the editor with the document bar I used to deal with a few time ago.

    This is very easy and intuitive.

    Thanks

  8. MFloyd March 26, 2014 at 22:35 Reply

    Is there a way to programmatically change where files are loaded in the editor? The editor can have split panes for example with multiple files associated with one pane or another. MATLABDesktop.xml contains the information, but my current matlab version (2013b) always loads them to a single pane if opening matlab after closing it. So even though I know how to manually modify the xml, it won’t load to correct panes in the first place.

    Robot Cumming’s file works well to load different sets of files without changing the xml directly. I just can’t find where outside of the xml file pane position can be found or changed, either in the com.mathworks.mde.editor.MatlabEditor class or elsewhere.
    Being able to programmatically change the pane location would allow organizing by location or name as well, instead having to manually drag and drop each file to the desired location in the editor.

    Thanks

    • Yair Altman March 27, 2014 at 02:34 Reply

      @MFloyd – you can access the Desktop handle as explained here, and then use its setClientLocation method. Something like this:

      jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
      jDesktop.setClientLocation(fullFileName, location)

      jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance; jDesktop.setClientLocation(fullFileName, location)

      Where location is a com.mathworks.widgets.desk.DTTiledLocation object. You can get existing client locations via

      location=jDesktop.getClientLocation(fullFileName)

      location=jDesktop.getClientLocation(fullFileName)

      But I’m not sure exactly how to create new locations. It’s something like com.mathworks.widgets.desk.DTTiledLocation.create(...) or com.mathworks.widgets.desk.DTTiledLocation.fromXML(com.mathworks.mwswing.SimpleElement), but you’ll need to find out for yourself. Let us know if you discover anything useful.

      • MFloyd April 24, 2014 at 10:55

        Thanks, you helped a lot. It took a while, but I finally got something working end to end.

        To get an existing location I had to make a small change:

        jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance;
        jEditorViewClient = jDesktop.getClient(fileName);
        location = jDesktop.getClientLocation(jEditorViewClient)

        jDesktop = com.mathworks.mde.desk.MLDesktop.getInstance; jEditorViewClient = jDesktop.getClient(fileName); location = jDesktop.getClientLocation(jEditorViewClient)

        Where fileName could be the short name found in the tab title including the ‘*’ at the end if modified or if unsaved it could be ‘Unsaved#’. Specifying a location independent of a specific view can be done with

        location = com.mathworks.widgets.desk.DTLocation.create(tileNumber)

        location = com.mathworks.widgets.desk.DTLocation.create(tileNumber)

        Note that getting a location from a specific view will have properties specifying the view placement (x,y,w,h), but creating one directly from the tileNumber will only set tileNumber to something meaningful. In either case they work equally well for setting a view to a specific location.

        To set or change the location the following options worked:

        jDesktop.setClientLocation(jEditorViewClient, location)
        jDesktop.setClientLocation(fileName, location)

        jDesktop.setClientLocation(jEditorViewClient, location) jDesktop.setClientLocation(fileName, location)

        I spent a long time trying to figure out how to create a new location. Creating a new DTLocation object was insufficient in any case and was only useful if it already existed. If a DTLocation that did exist was saved and files were later moved to other locations so that tile no longer existed, it wouldn’t recreate the tile. It would always set it to one of the existing tiles.

        To change the editor layout I used the following functions:

        jDesktop.setDocumentArrangement('Editor',2,java.awt.Dimension(nTilesW,nTilesH));
        jDesktop.setDocumentColumnSpan('Editor',row,column,columnSpan);
        jDesktop.setDocumentRowSpan('Editor',row,column,rowSpan);
        jDesktop.setDocumentRowHeights('Editor',hieghtPercentages)
        jDesktop.setDocumentColumnWidths('Editor',widthPercentages)

        jDesktop.setDocumentArrangement('Editor',2,java.awt.Dimension(nTilesW,nTilesH)); jDesktop.setDocumentColumnSpan('Editor',row,column,columnSpan); jDesktop.setDocumentRowSpan('Editor',row,column,rowSpan); jDesktop.setDocumentRowHeights('Editor',hieghtPercentages) jDesktop.setDocumentColumnWidths('Editor',widthPercentages)

        There were some tricky parts in using these to avoid “eating” files in adjacent tiles when expanding tiles using ColumnSpan and RowSpan functions as well as correlating between old tile numbers and new tile numbers since the sequence of how tiles are expanded/created affects tile numbers.

        I made a session manager inspired by Robert Cummings file exchange submission mentioned above. I completely reworked it and it is likely not backward compatible, but is found here: Editor Session Manager

        Thanks for your help!

    • Robert Cumming April 25, 2014 at 05:53 Reply

      MFloyd – Good to hear that you have taken inspiration from my submission! 🙂

      I will have to have a look at your code later.

      Regards

  9. cw September 18, 2014 at 15:02 Reply

    This is pretty much one of the most useful posts I’ve encountered in a very long time. Thank you !

  10. Eric Melonakos January 12, 2015 at 15:30 Reply

    Thank you! This just saved me a ton of time and confusion!

  11. Noam Greenboim May 27, 2015 at 08:57 Reply

    Thanks for posting this, I have the same issue every now and then.

  12. DoTTy November 17, 2015 at 08:45 Reply

    Thank you very much for this post, it saved my live!! 😉 Regards

  13. Michael March 4, 2016 at 16:11 Reply

    Inspired by this post, I created a shortcut in Matlab with the following content:

    %parse XML file
    xmlFiles    = xmlread([prefdir filesep 'MATLABDesktop.xml.prev']);
    %Retrieve the "clients"
    FileNodes   = xmlFiles.getElementsByTagName('Client');
    %get the length of the FileNodes
    nrFiles     = FileNodes.getLength;
    %initialize Files
    Files       = cell(nrFiles,1);
    %initialize isFile
    isFile      = zeros(nrFiles,1);
    %Iterate over all Elements and check if it is a file.
    for iNode = 0:nrFiles-1 % Java indexing.
        %Files
        Files{iNode+1} = char(FileNodes.item(iNode).getAttribute('Title'));
        %check if the "client" is a file:
        isFile(iNode+1) = exist(Files{iNode+1},'file') == 2 && ~(strcmp(Files{iNode+1},'Workspace'));
    end
    %remove the other files:
    MyFiles = Files(find(isFile));
    %open the files in the editor:
    edit(MyFiles{:});

    %parse XML file xmlFiles = xmlread([prefdir filesep 'MATLABDesktop.xml.prev']); %Retrieve the "clients" FileNodes = xmlFiles.getElementsByTagName('Client'); %get the length of the FileNodes nrFiles = FileNodes.getLength; %initialize Files Files = cell(nrFiles,1); %initialize isFile isFile = zeros(nrFiles,1); %Iterate over all Elements and check if it is a file. for iNode = 0:nrFiles-1 % Java indexing. %Files Files{iNode+1} = char(FileNodes.item(iNode).getAttribute('Title')); %check if the "client" is a file: isFile(iNode+1) = exist(Files{iNode+1},'file') == 2 && ~(strcmp(Files{iNode+1},'Workspace')); end %remove the other files: MyFiles = Files(find(isFile)); %open the files in the editor: edit(MyFiles{:});

    So whenever I close my editor by accident, I click on the shortcut to retrieve the files. It works in R2013a for me – I did not check other versions.

    BR Michael

    • Martin WH April 19, 2016 at 13:17 Reply

      Great – thanks! This doesn’t happen to me very often, but when it does, it’s really annoying. Your script works fine in R2016a (Mac) by the way.

    • Oleg Shebanits August 19, 2016 at 11:48 Reply

      This is brilliant! Thank you so much!
      Works in R2016a and much simpler than making functions etc.

  14. Me May 5, 2016 at 23:46 Reply

    I wish there were more people like you in this world!
    Saved a lot of my time!

  15. Hexler October 10, 2016 at 02:14 Reply

    For some reason this didn’t work for me. It had just stored 4 out of a bunch of tabs.
    However, I found a list of files in MATLAB_Editor_State.xml. It looks like the tabs I was working on.

    • Yair Altman October 10, 2016 at 10:44 Reply

      @Hexler – I believe that MATLAB_Editor_State.xml merely stores the states of the various folding blocks in the code of every m-file that you have ever opened in the Editor, not just those files that are currently open.

Leave a Reply
HTML tags such as <b> or <i> are accepted.
Wrap code fragments inside <pre lang="matlab"> tags, like this:
<pre lang="matlab">
a = magic(3);
disp(sum(a))
</pre>
I reserve the right to edit/delete comments (read the site policies).
Not all comments will be answered. You can always email me (altmany at gmail) for private consulting.

Click here to cancel reply.

Useful links
  •  Email Yair Altman
  •  Subscribe to new posts (feed)
  •  Subscribe to new posts (reader)
  •  Subscribe to comments (feed)
 
Accelerating MATLAB Performance book
Recent Posts

Speeding-up builtin Matlab functions – part 3

Improving graphics interactivity

Interesting Matlab puzzle – analysis

Interesting Matlab puzzle

Undocumented plot marker types

Matlab toolstrip – part 9 (popup figures)

Matlab toolstrip – part 8 (galleries)

Matlab toolstrip – part 7 (selection controls)

Matlab toolstrip – part 6 (complex controls)

Matlab toolstrip – part 5 (icons)

Matlab toolstrip – part 4 (control customization)

Reverting axes controls in figure toolbar

Matlab toolstrip – part 3 (basic customization)

Matlab toolstrip – part 2 (ToolGroup App)

Matlab toolstrip – part 1

Categories
  • Desktop (45)
  • Figure window (59)
  • Guest bloggers (65)
  • GUI (165)
  • Handle graphics (84)
  • Hidden property (42)
  • Icons (15)
  • Java (174)
  • Listeners (22)
  • Memory (16)
  • Mex (13)
  • Presumed future risk (394)
    • High risk of breaking in future versions (100)
    • Low risk of breaking in future versions (160)
    • Medium risk of breaking in future versions (136)
  • Public presentation (6)
  • Semi-documented feature (10)
  • Semi-documented function (35)
  • Stock Matlab function (140)
  • Toolbox (10)
  • UI controls (52)
  • Uncategorized (13)
  • Undocumented feature (217)
  • Undocumented function (37)
Tags
AppDesigner (9) Callbacks (31) Compiler (10) Desktop (38) Donn Shull (10) Editor (8) Figure (19) FindJObj (27) GUI (141) GUIDE (8) Handle graphics (78) HG2 (34) Hidden property (51) HTML (26) Icons (9) Internal component (39) Java (178) JavaFrame (20) JIDE (19) JMI (8) Listener (17) Malcolm Lidierth (8) MCOS (11) Memory (13) Menubar (9) Mex (14) Optical illusion (11) Performance (78) Profiler (9) Pure Matlab (187) schema (7) schema.class (8) schema.prop (18) Semi-documented feature (6) Semi-documented function (33) Toolbar (14) Toolstrip (13) uicontrol (37) uifigure (8) UIInspect (12) uitable (6) uitools (20) Undocumented feature (187) Undocumented function (37) Undocumented property (20)
Recent Comments
Contact us
Captcha image for Custom Contact Forms plugin. You must type the numbers shown in the image
Undocumented Matlab © 2009 - Yair Altman
This website and Octahedron Ltd. are not affiliated with The MathWorks Inc.; MATLAB® is a registered trademark of The MathWorks Inc.
Scroll to top