Hi,
I am new to Sublime (Windows) and am trying to reproduce my normal editing workflows.
Although Sublime Text Snippets are very powerful, I have a library of simple text files I would like to use:
- Assign a hot key to insert_template e.g. alt+t
- Launch fzf.exe (with bat.exe preview) to select a file
- Insert the template text at the (every) caret.
My attempts so far:
- Keybinding
{ "keys": ["alt+t"], "command": "exec", "args": { "cmd": ["cmd.exe","/C start /MAX "," O:\\MyProfile\\editor\\confSublime\\Data\\Packages\\User\\scripts\\alt-t.bat"], "quiet": true} },
- Batch file
@echo off
REM Allow delayed expansion of variables
setlocal EnableDelayedExpansion
REM Set title so autohotkey can modify FZF keyboard shortcuts
title FZF
REM point FZF at my template folder
set FZF_DEFAULT_COMMAND=dir /s/b/a-d "O:\MyProfile\editor\templates"
for /f "delims=" %%f in ('fzf.exe --tac --preview "bat.exe --color=always --style=plain --line-range=:500 {}"') do (
REM Assign variable so we can substitute slashes
set fname=%%f
REM Convert slashes
set fname=!fname:\=/!
REM Assign json variable to avoid tiresome escaping of quotes
set json={"command":"insert_file_contents","args":{"filename":"!fname!"}}
O:\MyProfile\editor\confSublime\subl.exe --command "!json!"
)
exit
- User plugin to insert_file_contents (O:\MyProfile\editor\confSublime\Data\Packages\User\InsertFileContents.py) - AI generated as I don’t grok python.
import sublime
import sublime_plugin
import os
class InsertFileContentsCommand(sublime_plugin.TextCommand):
def run(self, edit, filename=None):
if filename is None:
# For testing add known file
filename = "O:/MyProfile/editor/confSublime/ToDo.txt"
# return
# expand user and vars, normalize
filename = os.path.expandvars(os.path.expanduser(filename))
filename = os.path.normpath(filename)
if not os.path.exists(filename):
sublime.error_message(f"File not found:\n{filename}")
return
try:
with open(filename, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
for region in self.view.sel():
self.view.replace(edit, region, content)
except Exception as e:
sublime.error_message(f"Error reading file:\n{str(e)}")
I have successfully used a similar approach to select snippet files and send the “insert_snippet” command via subl.exe - but targeting a user defined command seems more difficult.
Any guidance about how to make this work would be appreciated.
Kind Regards Gavin Holt