+2

When opening a new file from the command line, sublime should focus the window that already contains it.

Greg Anderson 12 years ago 0
Consider the command:

$ sublime_text file.txt 

This does the right thing if the topmost Sublime window has file.txt open somewhere in it; file.txt becomes the focused tab. You do not get two copies of file.txt open.  However, if there are two or more Sublime windows open, then sublime will open a second copy of file.txt in the frontmost window.

Desired behavior:

Sublime should raise the window that contains file.txt to the front, then focus the tab that contains it, rather than opening a new copy of the same file.

Desired behavior with -n:

$ sublime_text -n file.txt 

If Sublime is invoked from the cli with the -n to open a file that is already open, then the -n flag should be ignored if file.txt is already open in a window that contains no other tabs (including folder views), and the existing window should come frontmost.  If file.txt is open in a window with other tabs, then Sublime should act as if the user had grabbed the file.txt tab and pulled it off into a new window.

Workaround:

On Linux, if you typically open your files in separate Sublime windows, then wmctrl can be used to focus the right window.  Use `sudo apt-get install wmctrl` to install wmctrl.  I use the script below, saved as "se", to enforce the one-window-per-file rule.  This script currently makes no attempt to solve the multiple-folder-view enhancement request (http://sublimetext.userecho.com/topic/88851-opening-a-folder-from-the-command-line-should-focus-on-the-existing-window-if-that-folder-is-already-open-in-sublime/).

#!/bin/bash

for f in "$@" ; do
  # If the parameter is a directory, then open it in a new sublime window
  if [ -d "$f" ] ; then
    sublime_text -n "$f" &
  else
    # Test to see if the file is already open in Sublime; if it is, then
    # bring the focused window frontmost instead of opening a new one.
    d=$(cd "$(dirname "$f")" 2>/dev/null && pwd | sed -e "s|^$HOME|~|")
    b=$(basename -- "$f")
    if [ `wmctrl -l | grep -c "$d/$b"` != 0 ] ; then
      wmctrl -a "$d/$b" &
    else
      sublime_text -n "$f" &
    fi
  fi
done