Reliably checking if edited file is unsaved from the command line?



  • I have a script that modifies/adds to a raw file of writing ideas, but I found I forget to save that file before running the script again.

    So I thought I’d put in a stub to see if the file was in an unsaved state. Here is my PERL code (not that such a check has to be in PERL. I thought I’d show what I was trying to do):

    my $c;
    while ($c = <C>)
    {
      if ($c =~ /flip.txt/)
      {
        if ($c =~ /backupFilePath=\"[^\"]/i)
        {
    	`$output`;
        Win32::MsgBox("Save wfl.txt before copying over", 0, "Less annoying than overwriting");
        }
        last;
      }
    }
    close(C);
    

    Here I’m just checking the session.xml file and seeing if the flip.txt entry has a non-empty backupFilePath. And the code isn’t perfect, but it is a good first step. It works pretty well, unless I run the script and edit the file and quickly run the script again. Then, session.xml hasn’t updated soon enough.

    Is there a better way to check for if a file has been modified in Notepad++? This isn’t a huge deal for me, since 95% of the time it’ll work, and when it doesn’t, I can just re-delete the lines I got rid of. Still, I’d like to be more precise.

    Thanks!

    (By the way, if you’re curious about the test case, my file wfl.pl takes in an argument, reads a complete list of English words, and then alphabetically writes out all words starting or ending with the argument-word, with a special annotation if (compound word without argument word) is a word itself. So sometimes I get a few ideas for words based on what my latest try gives me, and I can have binges of saving and deleting text.)



  • Your method will mostly work as long as you’ve got Settings > Preferences > Backup correctly enabled, and you have a short enough backup time. If you want to make sure it’s got enough time to register the changes in the file, add a sleep($time) before the check, where $time matches your NPP backup interval.

    I would probably add a test for existence of the backup file, not just it being listed in session.xml. (I just ran an experiment, and a minute after my most recent save, when the backup file was gone, session.xml still listed the backup file). I would also use -M to check the modified-time of both the original and the backup, since I found outdated “backups” in my backup directory that were months out of date (probably remained open after a reboot or crash).

    Also, if you find that the file hasn’t been saved yet, you could also use Win32::OLE or Win32::GuiTest to force NPP to save the file, if you wanted, instead of just pestering yourself with a message box. But that’s up to you.

    PS: Perl is not an acronym: “Perl” is the language, “perl” is the executable/interpreter, “PERL” is a backronym.