Search code examples
macosvimalfred

Alfred Workflow to open a file in vim in the terminal


How can we write an alfred workflow to open a file from finder to a vim editor?

This is my first attempt to create a workflow in Alfred. I am still learning and wanted to start with a simple workflow.

Here, I first created Hotkey and Keyword.

Open the Alfred3
Go to Workflows
Click + sign at the bottom left sidebar
Choose Blak Workflow
Name: Vim Launcher
Description: Opens a file in the terminal inside vim editor

1. Right-click > Trigger > press cmd-alt-v 
2. Right-click > Inputs > Keyword > open in vim  and title also open in vim

3. Right-click > Actions > Run NSAppleScipt

The copy and paste following contents inside Run NSAppleScipt

on alfred_script(q)
    tell application "Terminal"
        activate
        do script "vim '" & q & "'"
    end tell
end alfred_script

This workflow works but opens two terminals instead of one. How can we fix this make so that it opens only one window?

The workflow summary is given below. enter image description here


Solution

  • You want a Terminal Command action.

    Just connect this object to your triggers and use vim "{query}" on it.

    EDIT:

    I'm editing the answer to reply a comment asking a follow-up question:

    The workflow now create new termnial for each file, can we make it open in the same terminal if a terminal is already running?

    In this case the Run NSAppleScript object could be used with the difference that we have to specify a location where do script should run, since it always open a new window if no location is specified:

    on alfred_script(q)
        tell application "Terminal"
            if not (exists window 1) then reopen
            activate
            do script "vim '" & q & "'" in window 1
        end tell
    end alfred_script