Saturday, January 23, 2010

UltraEdit Javascript to create timestamped backup of current file

This is a Javascript that UltraEdit can use (Scripting > Scripts) to make a timestamped copy of the current file. UltraEdit already has at least two good backup functions, so this is nothing new. It has a function to backup a single file on demand (File > Make Copy/Backup > use file dialog) and an automatic backup (Advanced > Configuration > File Handling > Backup) which lets you backup per save or on a time period basis with controls over file name, location and number of backups. I use the latter all the time, but I wanted a way to do the former without having to go through the file dialog that it uses. I.e. I wanted to run the function (scripts can have keyboard short-cut assignments) and have it save the file without asking me anything.

This script will make a time-stamped copy of the current document, saved to the same directory. Backup file names are of the form filename.extension.yyyymmdd-hhmmss, e.g. backup backupSingleFile.js to backupSingleFile.js.2010023-174610.bak. (It's easy to modify this script for your own time stamp preferences.)

 
// Make a time-stamped copy of the current document, saved to the same directory.
// Backup file names are of the form filename.extension.yyyymmdd-hhmmss,
// e.g. backup backupSingleFile.js to backupSingleFile.js.2010023-174610.bak.

// Created by Robert Mark Bram, 23/01/2010 5:48:38 PM
// Thanks Mofi for telling me how to fix it up.

// Determine the document index of the active document.
var nActiveDocIndex = 0;
while (nActiveDocIndex < UltraEdit.document.length) {
   if (UltraEdit.activeDocument.path == UltraEdit.document[nActiveDocIndex].path) break;
   nActiveDocIndex++;
}
// Copy file contents and reset cursor back to where it was.
var x = UltraEdit.activeDocument.currentLineNum;
var y = UltraEdit.activeDocument.currentColumnNum;
UltraEdit.activeDocument.selectAll();
UltraEdit.activeDocument.copy();
UltraEdit.activeDocument.gotoLine(x, y+1);

// Copy contents into the backup file, save and close it.
var FullFileName = UltraEdit.activeDocument.path;
UltraEdit.newFile();
UltraEdit.activeDocument.paste();
var now = new Date();
UltraEdit.saveAs(FullFileName
      + "."
      + now.getFullYear()
      + now.getMonth()
      + now.getDate()
      + "-"
      + now.getHours()
      + now.getMinutes()
      + now.getSeconds()
      + ".bak");
UltraEdit.closeFile(UltraEdit.activeDocument.path,2);

// Go back to the document whose contents we copied.
UltraEdit.document[nActiveDocIndex].setActive();