Skip to content

Instantly share code, notes, and snippets.

@Kamik423
Created August 30, 2023 19:26
Show Gist options
  • Save Kamik423/80ebcef8d0308aa80307291394b19f5d to your computer and use it in GitHub Desktop.
Save Kamik423/80ebcef8d0308aa80307291394b19f5d to your computer and use it in GitHub Desktop.
Open Sublime Text From Windows Subsystem for Linux Version 2
#!/usr/bin/env python3
# Place in /usr/local/bin or some other path in $PATH
# Description: see https://hans.coffee/blog/subl-on-wsl/
import subprocess
import sys
# The path to the Sublime Text Windows executable in the Linxu file-system.
SUBL = "/mnt/c/Program Files/Sublime Text/subl.exe"
def window_path(path: str) -> str:
# Convert a Linux path to a Windows one so Sublime Text understands it.
result = subprocess.run(f'wslpath -aw "{path}"', shell=True, capture_output=True)
if result.stderr:
raise subprocess.CalledProcessError(
returncode=result.returncode, cmd=result.args, stderr=result.stderr
)
# Somehow `subl` only understands paths using slashes instead of backslashes
# as you would expect from a Windows command line utility. So we replace all
# of the backslashes with regular slashes. Afterwards spaces in the path are
# escaped so `subl` understands any path as a single argument, not multiple.
return result.stdout.decode("utf8").strip().replace("\\", "/").replace(" ", "\\ ")
def main() -> int:
# Execute the command on the Linux command line. Any argument beginning with
# a `-` is passed on directly to `subl` (like `-w` or `--help`). However any
# other argument is converted to a Windows path from a Linux one.
command = f'exec "{SUBL}" ' + " ".join(
[arg if arg.startswith("-") else f"{window_path(arg)}" for arg in sys.argv[1:]]
)
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True
)
# Print any output of `subl` like help text or errors.
print(process.communicate()[0].decode("utf8"), end="", flush=True)
return process.returncode
if __name__ == "__main__":
# Pass through the return code
sys.exit(main())
@Kamik423
Copy link
Author

Full description and problem statement: https://hans.coffee/blog/subl-on-wsl/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment