How can I edit crontabs in VS Code?

Viewed 3332

If I try to use Visual Studio Code (on macOS 10.15) to edit my crontab, it opens an empty file without the contents of my crontab.

$ VISUAL='code' crontab -e
crontab: no changes made to crontab

I didn't actually expect this to work (without -w) but include it for completeness. But when I add the -w it still fails.

$ VISUAL="code -w" crontab -e
crontab: code -w: No such file or directory
crontab: "code -w" exited with status 1

It occurred to me that there may be some weirdness with quoting, but neither single quotes nor the following fixed anything:

$ function codew() {
function> code -w "$1"
function> }
$ export VISUAL='codew'
$ crontab -e

The problem seems to be that the crontab's tempfile is not actually present. But how do I solve this? How can I use VS Code to edit crontabs?

3 Answers
  1. Create a file touch ~/code-wait.sh:
#!/bin/bash
OPTS=""
if [[ "$1" == /tmp/* ]]; then
    OPTS="-w"
fi

/usr/local/bin/code ${OPTS:-} -a "$@"
  1. Make this file executable:
chmod 755 ~/code-wait.sh 
  1. Add to your .bashrc or .bash_profile or .zshrc:
export VISUAL=~/code-wait.sh
export EDITOR=~/code-wait.sh
  1. Run command:
EDITOR='code' crontab -e

That is quite a complex issue because there is no way to detect which tool calls the preferred editor. The TTY is the same and no environment variables can help.

Still, I was able to come up with a solution that enables the foreground mode (wait) for temporary files. IMHO, most if not all tools that use external editors and are waiting for them to save the file do use temporary files.

Full script is at https://github.com/ssbarnea/harem/blob/master/bin/edit but I will include here the main snippet:

#!/bin/bash
OPTS=""
if [[ "$1" == /tmp/* ]]; then
    OPTS="-w"
fi

/usr/local/bin/code ${OPTS:-} -a "$@"

here the setting works for me.

.bashrc

## vscode
export VISUAL=/path/to/code-wait.sh
export EDITOR=/path/to/code-wait.sh

code-wait.sh

#!/bin/sh
code -w $*
Related