Is there a way I can have vim watch something like /tmp/my-vim for changes whenever vim is opened to edit any other file and then run a function when the change occurs?

I am looking for a way to tie my sxhkd shortcut for switching modes (dark/light, which changes other applications themes) to change currently running vim colorschemes.

  • 1
    Welcome to Vi and Vim! In general, I’m not aware of a builtin mechanism for this. You could use an external tool like entr (your commands would be external commands, so while you could use vim to run some vimscript on the event, it would be in it’s own instance) or use a timer to implement an async polling loop, constantly checking timestamps. – D. Ben Knoble Aug 4 '20 at 23:27
  • Using a timer solved the problem well enough, every 1/2 second I read the file to see if the flag has been set and is different from the vim's local variable and reset the colours accordingly. – Drew Aug 5 '20 at 0:45
  • cool; feel free to add an answer if you’ve solved your problem – D. Ben Knoble Aug 5 '20 at 1:27

Using a timer that regularly read the file for what colour mode is in use I solved the question.

Here is the script that reads and calls the changes:

" Set colour scheme (and more) to light mode
function! ColorModeLight()
    colorscheme onehalflight
    let g:color_mode_light=1

" Set colour scheme (and more) to dark mode
function! ColorModeDark()
    colorscheme onehalfdark
    let g:color_mode_light=0

" Check for system colour mode changed
function! ColorModeCheck(timer)
    for line in readfile('/tmp/SYSTEM_LIGHT_MODE', '', 1)
        if line =~ '0' && get(g:, 'color_mode_light', 0) == 1
            call ColorModeDark()
        elseif line =~ '1' && get(g:, 'color_mode_light', 0) == 0
            call ColorModeLight()

" Set default colour
colorscheme onehalfdark
let g:color_mode_light=0


" Regularly check file for changes
let timer = timer_start(500, 'ColorModeCheck', {'repeat': -1})

My sxhkd runs a script that truncates and writes either 1 or 0 to /tmp/SYSTEM_LIGHT_MODE when called by toggling between the two, after this script is fired vim will soon read that a change occurred and update the colorscheme (lightline and more).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.