Skip to content

Instantly share code, notes, and snippets.

@n8henrie
Last active March 9, 2025 02:19
Show Gist options
  • Save n8henrie/6cc2a43c141aea21e98c2fdfbb876090 to your computer and use it in GitHub Desktop.
Save n8henrie/6cc2a43c141aea21e98c2fdfbb876090 to your computer and use it in GitHub Desktop.
JXA to open a Terminal window to the frontmost Finder window
#!/usr/bin/osascript -l JavaScript
'use strict';
const DEBUG = false;
function launchTerminal(path) {
const terminalApp = Application("Terminal.app")
terminalApp.includeStandardAdditions = true
let cmd = `cd ${path}; clear;`
if (DEBUG) {
console.log("cmd: " + cmd)
}
// 20221112: For some reason seems to be necessary to now open a window first,
// then specify the window to run. I can't find a way to create a new window
// other than `doScript()` or `doScript("")`; `terminal.make({new: terminal.Window})`
// doesn't seem to work.
terminalApp.doScript()
terminalApp.doScript(cmd, {in: terminalApp.windows[0]})
terminalApp.activate()
}
function run(argv) {
let terminalName
if (argv.length == 0) {
terminalName = "alacritty"
} else {
terminalName = argv[0].toLowerCase().trim()
}
// A few seconds to focus the appropriate Finder window
if (DEBUG) {
delay(2);
}
let windows = Application("Finder").finderWindows()
if (DEBUG) {
for (var window of windows) {
console.log("- " + window.target().url())
}
}
let url = windows.length > 0 ? windows[0].target().url() : "~"
if (DEBUG) {
console.log("url: " + url)
}
let path = decodeURIComponent(url).replace(/^file:\/\//, "")
if (DEBUG) {
console.log("path: " + path)
}
// https://stackoverflow.com/a/22827128
// Put path in single quotes, and escape internal single quotes
let quotedEscapedPath = `'${path.replace(/'/g, `'\\''`)}'`
switch (terminalName) {
case "terminal":
launchTerminal(quotedEscapedPath)
break
case "alacritty":
let cmd = `open -a alacritty --new --args --working-directory ${quotedEscapedPath}`
if (DEBUG) {
console.log(cmd)
}
let currentApp = Application.currentApplication()
currentApp.includeStandardAdditions = true
currentApp.doShellScript(cmd)
break
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment