4

I would like to be able to select text in a file and have it sent to an external terminal. Is this possible?

If not, could it be done via applescript?

nachocab
  • 13,328
  • 21
  • 91
  • 149
  • What does 'have it sent to an external terminal' mean? – pvg Sep 04 '17 at 00:42
  • @pvg Basically, copy and paste it – nachocab Sep 04 '17 at 00:44
  • You want to paste it into what? A window of `Terminal.app`? Which window? Or tab? It's not really clear what you're trying to accomplish. – pvg Sep 04 '17 at 00:46
  • @pvg yes, the currently active tab of iTerm.app – nachocab Sep 04 '17 at 00:47
  • It sounds doable, if likely misguided. This answer has a pointer to an extension that operates on selections https://stackoverflow.com/questions/35184509/visual-studio-code-make-selected-block-of-text-uppercase that you could modify and applescript away from there (you can invoke AS with shell commands). – pvg Sep 04 '17 at 00:52
  • @pvg what if it wasn't an external terminal, but the integrated one. Is there a way to execute a selection? – nachocab Sep 04 '17 at 00:56
  • Yes, that's much easier. There's this https://stackoverflow.com/questions/38952053/how-to-run-the-select-code-in-vscode and extensions like https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner – pvg Sep 04 '17 at 00:59

1 Answers1

1

I ended up writing my own extension to do this using AppleScript. It was as simple as this:

function activate(context) {
  const runIterm = vscode.commands.registerCommand('run-external.iterm', function() {
    const editor = vscode.window.activeTextEditor;
    let textToPaste;
    if (editor.selection.isEmpty) {
      textToPaste = editor.document.lineAt(editor.selection.active.line).text;
    } else {
      textToPaste = editor.document.getText(editor.selection);
    }
    exec(
      `osascript ` +
        ` -e 'tell app "iTerm"' ` +
        ` -e 'set mysession to current session of current window' ` +
        ` -e 'tell mysession to write text "${textToPaste}"' ` +
        ` -e 'end tell'`
    );
  });

  context.subscriptions.push(runIterm);
}
exports.activate = activate;
nachocab
  • 13,328
  • 21
  • 91
  • 149