Use the FileSelectFile Command to Save Instant Hotstrings to an AutoHotkey File

After Taking the Time to Create Hotstrings with the InstantHotstring.ahk Script, It Only Makes Sense to Save the Code to an AutoHotkey File for Future Use

*          *          *

This blog is part of a series of articles discussing how to create instant Hotstrings using the Hotstring() function.

*          *          *

Ultimately, after writing and activating a number of Hotstrings with the InstantHotstrings.ahk script, we want to save them in an AutoHotkey file. That frees us from recreating the set of auto-replacements the next time we need them. Plus, rather than always loading the Hotstrings into the app, we can run the .ahk file directly with AutoHotkey.

Using techniques already found in the script and the FileSelectFile command, I wrote a subroutine which allows the user to pick a filename, then save the list of Hotstrings to that .ahk file.

Using the FileSelectFile Command to Save Data to Files

The FileSelectFile command opens the built-in Windows Select File pop-up tool for locating and choosing files and/or assigning new filenames. It works in the same manner as Windows File Explorer for navigating drives, folders, and files. Working with the Select File window, you can directly create new folders, delete folders/files, move folders/files, and rename either of the two—just as you might with Windows File Explorer. You’ll find as the primary difference an option for an Open or Save button at the bottom of the window:

instanthotstring fileselect

Despite the implications of the wording in the online AutoHotkey documentation (“allows the user to open or save file(s)”), ultimately, the Select File window only assigns the path and a filename to a variable. Designating Open (the default) or Save (add the S option) merely changes the text displayed in the button. It neither opens nor saves anything. You must write separate AutoHotkey code for that action.

The SaveHotstrings Subroutine in the InstantHotstring.ahk Script

In the InstantHotstring.ahk script, clicking the Save button calls the SaveHotstrings subroutine and executes the following behaviors:

  1. If the Hotstrings folder for the saved files does not exist, the subroutine creates it.
  2. The Label subroutine opens the FileSelectFile window allowing the user to select or create a filename.
  3. If the file exists, the code offers options to overwrite or append to the old file. Otherwise, it creates the new .ahk file.
  4. SaveHotstrings extracts the list of Hotstrings from the DropDownList control.
  5. Finally, the subroutine loops through the list only adding the currently active Hotstrings to the selected old or newly created file.

I’ve included the entire SaveHotstrings subroutine at the end of this blog. To view the current version of the Label subroutine within the context of the script, see InstantHotstring.ahk at the Free AutoHotkey Scripts page.

Tip: As seen in this SaveHotstrings subroutine, I include the Gui, +OwnDialogs option as a best practice. (See “Use Gui, +OwnDialogs to Glue Modal Dialogs Boxes to GUI Parent Windows (AutoHotkey Best Practice).”) It ties the FileSelectFile window and each of the MsgBox pop-ups to the main GUI window forcing the user to respond or close the window before moving on. However, since the Gui, +OwnDialogs technique only applies to the current thread, for it to take effect you must add the Gui, +OwnDialogs statement to each called Label subroutine containing the MsgBox or FileSelectFile commands.

The FileSelectFile Command

As stated above, it is important to remember that the FileSelectFile command only locates and selects (or allows the input of) a filename for later use in the subroutine. Although a powerful tool, it solely facilitates the viewing and navigation of the Windows folder structure, then saving any filename selection(s) along with its path to a variable. The FileSelectFile command appears in the InstantHotstring.ahk script as follows:

FileSelectFile, SaveFile, S16
     , %A_ScriptDir%\Hotstrings\, , *.ahk

(The above FileSelectFile command uses line continuation techniques to wrap the line of code for display purposes.)

This command statement assigns the variable SaveFile to store the location and selected (or created) filename. The option codes S16 tells the Select File pop-up window to display the Save button (S) and pop-up message box (shown in the image below) when a filename already exists (16).

The starting file path appears as the third parameter (the script working directory A_ScriptDir plus the subdirectory “\Hotstrings\”).

The next parameter assigns a text prompt to the window. As indicated by the blank space between the commas, I didn’t include any text so it defaulted to File Select – InstantHotstring.ahk.

The last parameter (*.ahk) filters the file list to only display .ahk files. However, if at any time you would like to see all the files in the folder, select All files (*.*) from the Save as type dropdown menu.

Tip: Since the InstantHotstring.ahk script automatically creates a backup file of the most recent Hotstring file by the same name (e.g. HotstringFile.bak), you can select and reload the backup (after clicking the Load button) by opting for All files (*.*). If you make an error by saving over the wrong file, you can restore the original Hotstrings—as long as you only overwrite once.

FileSelectFile Command Options

instanthotstring saveas

You will find the FileSelectFile command options a little quirky. When you click Yes in the message box asking, “[Filename] already exists. Do you want to replace it?” (shown at right), the Select File tool does not actually replace anything. It only provides you the opportunity to select (or create) a different filename when you click No. Otherwise, clicking Yes merely closes the window—continuing to the next AutoHotkey statement.

The “Prompt to Create New File” option (8) works in a similar fashion—only offering a second chance to pick another filename when you click No. Despite the example in the online documentation for combining numerical options (8 + 16 = 24) in the FileSelectFile command, I found the two options mutually exclusive—you can use either one or the other, but not both. Plus, the S option appears to disable the 8 option while I found S16 redundantly performs in the same manner as the 16 alone. (Since the S option tells anyone reading the code that the window displays a Save button, I left the S16 intact.)

To top it all off, none of these options pass along any type of code for use later in the AutoHotkey script. If you want AutoHotkey to know that a file exists, you will need to check that again in AutoHotkey.

Canceling the FileSelectFile Command

Either clicking the Cancel button or closing the FileSelectFile command window by clicking the small x in the upper right-hand corner (or hitting the Escape key), sets the built-in ErrorLevel variable to 1 and closes the window. To prevent further processing of the AutoHotkey SaveHotstrings subroutine, the following code uses the Return command to exit the subroutine and jump back to the calling point in the script:

If ErrorLevel ; "Cancel" button, close, or Escape
   Return

This code should appear before any statements in the subroutine which produce lasting results.

Normalizing Filename Extensions

The filter in the FileSelectFile command does not affect the filename value eventually stored in the variable SaveFile. If you select a file from the Hotstring file list, that filename includes the .ahk extension. If you type in a name with no extension, the filename will not include the .ahk. For consistency, every filename should appear as an AutoHotkey script file using the .ahk extension—even if the user neglects to add it.

To ensure conformance, the code in the SaveHotstrings subroutine first removes any occurrence of .ahk in the filename—later adding it back. This techniques also avoids the problem of a double extension (.ahk.ahk) when selecting a filename from the Select File list:

SaveFile := StrReplace(SaveFile, ".ahk", "")

Now, AutoHotkey checks for the existence of the path and file by appending the extension to the filename:

If FileExist(SaveFile . ".ahk")

Every time the script calls the stored store location and filename, it appends the .ahk either as an expression (SaveFile . “.ahk”, as shown above) or as traditional direct text substitution (%SaveFile%.ahk).

The subroutine offers users two options for existing files:

If FileExist(SaveFile . ".ahk")
  MsgBox, 3, , Yes — Overwrite Old Hotstrings
    !`rNo — Append New Hotstrings!
     IfMsgBox, Cancel
       Return
     IfMsgBox, Yes
       {
          FileCopy, %SaveFile%.ahk, %SaveFile%.bak, 1
          FileDelete, %SaveFile%.ahk
       }

(The above snippet uses line continuation techniques to wrap the MsgBox command line of code for display purposes.)

instanthotstring overwrite

This snippet contains the action required to start the save/overwrite process. If we want to overwrite the original file, then we must first delete it (FileDelete command). For backup, the script creates a copy of the original file (FileCopy command) adding the .bak extension, before deleting it.

If we only plan to add (FileAppend command) the active Hotstrings to the current file, then, at this point, we don’t need to take any extra actions. (That comes next.) Clicking No drops through to the remaining statements in the subroutine. Clicking Cancel exits (Return) the subroutine.

Collecting and Saving Hotstrings to a File

The InstantHotstring.ahk script extracts Hotstring data from the DropDownList control using the ControlGet, OutputVar, List command in the same manner as described in the blog “Create Instant Hotstrings Using the AutoHotkey Hotstring() Function.”

ControlGet, Items, List,, ComboBox1, A

Loop, Parse, Items, `n
{
  If (InStr(A_LoopField, "🛑 Stopped!") = 0)
  {
      FileAppend , %A_LoopField%`r`n, %SaveFile%.ahk, UTF-8
  }
}

The primary difference from the code in the older blog and this snippet consists of excluding any deactivated Hotstrings by checking for the key text (“🛑 Stopped!”). If not inactive, the script attaches (FileAppend command) the Hotstring to the %SaveFile%.ahk file in UTF-8 format. (UTF-8 ensures the saving of extended character sets such as emojis.) Note: If a file does not exist, the FileAppend command creates it automatically the first time its called.

Lastly, a MsgBox command provides positive feedback upon completing the Save procedure:

MsgBox Hotstrings added to the %SaveFile%.ahk file!

instanthotstrings added to file

Without this type of pop-up informational message, the user may not know if the subroutine made it to the end. If the InstantHotstring.ahk script contains no active Hotstrings, then the subroutine adds nothing to the file nor will it create a new filename.

*          *          *

Click the Follow button at the top of the sidebar on the right of this page for e-mail notification of new blogs. (If you’re reading this on a tablet or your phone, then you must scroll all the way to the end of the blog—pass any comments—to find the Follow button.)

*          *          *

The SaveHotstrings subroutine in one piece:

SaveHotstrings:

Gui, Hotstring:+OwnDialogs    ; Makes all pop-up windows modal
If (InStr(FileExist("\Hotstrings"), "D") = 0)
    FileCreateDir, Hotstrings

FileSelectFile, SaveFile , S16, %A_ScriptDir%\Hotstrings\, , *.ahk
If ErrorLevel   ; "Cancel" button, close, or Escape
   Return

SaveFile := StrReplace(SaveFile, ".ahk", "")
If FileExist(SaveFile . ".ahk")
  MsgBox, 3, , Yes — Overwrite Old Hotstrings
    !`rNo — Append New Hotstrings!
     IfMsgBox, Cancel
       Return
     IfMsgBox, Yes
       {
          FileCopy, %SaveFile%.ahk, %SaveFile%.bak, 1
          FileDelete, %SaveFile%.ahk
       }

ControlGet, Items, List,, ComboBox1, A

Loop, Parse, Items, `n
{
  If (InStr(A_LoopField, "🛑 Stopped!") = 0)
  {
      FileAppend , %A_LoopField%`r`n, %SaveFile%.ahk, UTF-8
  }
}
MsgBox Hotstrings added to the %SaveFile%.ahk file!
Return

jack

This post was proofread by Grammarly
(Any other mistakes are all mine.)

(Full disclosure: If you sign up for a free Grammarly account, I get 20¢. I use the spelling/grammar checking service all the time, but, then again, I write a lot more than most people. I recommend Grammarly because it works and it’s free.)

 

4 thoughts on “Use the FileSelectFile Command to Save Instant Hotstrings to an AutoHotkey File

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s