Skip to content

Launch .txt File In Windows Using Zim or WordPad

bkidwell edited this page Oct 10, 2014 · 10 revisions

Use this script as the default associated program for .txt files in Windows, and it will launch the file in Zim or WordPad, according to whether or not it is a Zim wiki page.

To install the script, save it as txt-zim-launcher.cmd in your %USERPROFILE%/bin folder (or anywhere else you wish). Then browse to anywhere you have a .txt file in Windows Explorer, select "Open With..." and associate .txt files with the new txt-zim-launcher.cmd script.

If the Zim content type is not detected, the file is sent to WordPad. Else, if it is a Zim file, the script the first item it finds in this list and send the specified .txt file to it:

  1. zim-launcher.vbs in the same folder as the first script (Personally I have a custom launcher with this name in the same folder that prepares my Zim environment.)
  2. C:\Program Files (x86)\Zim Desktop Wiki\zim.exe
  3. C:\Program Files\Zim Desktop Wiki\zim.exe
  4. zim.exe (assumed to be in %PATH%)

Here is the script:

@set @z=0 /*
@echo off
start "" wscript //nologo //E:jscript "%~f0" %*
goto :eof
*/;

/***********************************************************************
BE SURE TO NAME THIS FILE ENDING WITH ".cmd" or else Windows Explorer
won't want to use it as a default program for a file type.
***********************************************************************/

filename = WScript.Arguments(0);
shell = WScript.CreateObject('WScript.Shell');
fs = WScript.CreateObject('Scripting.FileSystemObject');

if(isZimFile(filename)) {
    shell.Run(zimExecutable() + ' "' + filename + '"');
} else {
    shell.Run('wordpad.exe "' + filename + '"');
}

/** Doe the specified file contain Content-Type header saying "text/x-zim-wiki"? */
function isZimFile(filename) {
    var FOR_READING = 1;
    var ts = fs.GetFile(filename).OpenAsTextStream(FOR_READING);
    var value = ts.ReadLine();
    ts.Close();
    return value.match(/Content-Type: text\/x-zim-wiki/i) != null;
}

/** Get path of launcher script or zim.exe */
function zimExecutable() {
    // Is there a zim-launcher.vbs in the same folder as txt-zim-launcher.cmd?
    var launcher = WScript.ScriptFullName.replace(/(\\)([^\\"]+)("?)$/, '$1zim-launcher.vbs$3');
    if(fs.FileExists(launcher)) {
        return 'wscript.exe ' + launcher;
    }

    // Look for zim.exe in "Program Files (x86)" and "Program Files"
    launcher = 'C:\\Program Files (x86)\\Zim Desktop Wiki\\zim.exe';
    if(fs.FileExists(launcher)) {
        return '"' + launcher + "'";
    }
    launcher = 'C:\\Program Files\\Zim Desktop Wiki\\zim.exe';
    if(fs.FileExists(launcher)) {
        return '"' + launcher + "'";
    }
    
    // Assume zim.exe is in $PATH somewhere
    return 'zim.exe';
}
Clone this wiki locally