2

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

1 Answers1

1

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
xilopaint
  • 699
  • 1
  • 7
  • 16
  • Are you sure adding bash script with above command will open the given file in the terminal with vim? It didn't work for me. –  Apr 15 '18 at 19:28
  • @astro123 yes, I am. I did the test. Can you share a link for your workflow as a comment and I point out what you did wrong? – xilopaint Apr 15 '18 at 20:03
  • Sure, what I did is given here, Please check: https://github.com/bhishanpdl/Shared/blob/master/Alfred-workflows/VimLauncher.alfredworkflow –  Apr 15 '18 at 21:23
  • @astro123 It's working for me. You just have to connect the triggers (`File Action` and `Hotkey`) to the `Terminal Command` object. – xilopaint Apr 15 '18 at 21:31
  • The workflow now create new termnial for each file, can we make it open in the same terminal if a terminal is already running? –  Apr 15 '18 at 21:36
  • @astro123, I've edited the answer with the solution. – xilopaint Apr 16 '18 at 00:32