Implementing Click-to-Open IDE Files in iTerm2
In the terminal, when you move the cursor to a file path, ⌘+click
can trigger the execution of a command. For example, clicking on a project folder can open WebStorm. However, sometimes I want different file types to trigger different actions, which requires custom script extensions.
Solution
The implementation approach is as follows. Since I’m not very proficient with Shell scripting, for convenience, the actual IDE opening logic is written in JavaScript and executed via Node.js in the shell.
Here’s a portion of the code. Complete code can be found here
iterm2-trigger.js
/**
* Debug script: ./iterm2-trigger.sh '/git/chainmaker-go'
* Set default opening programs for various file types
* key is the condition, value is the command to execute, defaults to system default opener
* For project folders with 'go' in the name, open with GoLand
*/
const commandMap = new Map();
commandMap.set((_filePath) => utils.isDirectory(_filePath) && utils.suffixMatch(10, _filePath, ['.go']), '/usr/local/bin/goland');
commandMap.set((_filePath) => utils.isDirectory(_filePath) && utils.suffixMatch(10, _filePath, ['.js', '.jsx', '.ts', '.tsx']), '/usr/local/bin/webstorm');
commandMap.set((_filePath) => true, 'open');
(function init() {
let commandStr = '';
for (const fn of commandMap.keys()) {
if (fn(filePath)) {
commandStr = commandMap.get(fn);
if (utils.checkAppExist(commandStr)) {
break;
}
}
}
execSync(`${commandStr} ${filePath}`);
})();
iterm2-trigger.sh
#!/usr/bin/env bash
DIR="$(dirname $0)"
/usr/local/bin/node "$DIR/iterm2-trigger.js" $1
exit 0;
In iTerm2, go to Preferences => Profiles => local Profile => Advanced => Semantic History and configure as follows:
$HOME/bin/iterm2-trigger.sh \1
Of course, if you just want all files to open with WebStorm or a specific program, you can configure it directly like this:
/usr/local/bin/webstorm \1
Final Thoughts
With this configuration script, you can flexibly control the actions triggered by clicking on files.