Text to speech in (neo)vim...

Some dirty hacks to read the vim buffer with espeak.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
-- In Visual mode, read the selected text
vim.keymap.set('v', '<F1>', ':w !setsid -f espeak -s 150 -D<cr><cr>')
-- In Normal mode play the current line
vim.keymap.set('n', '<F1>', ':.w !setsid -f espeak -s 150 -D<cr><cr>')
-- Play from the current line to the end of file.
vim.keymap.set('n', '<F11>', ':.,$w !setsid -f espeak -s 150 -D<cr><cr>')
-- In insert mode, use ctrl-enter to read the newly inserted line.
vim.keymap.set('i', '<C-CR>', '<Esc>:.w !setsid -f espeak<CR>o')
-- Stop playing
vim.keymap.set('n', '<F12>', ':!pkill espeak<cr><cr>')

What does the command mean

A simplified version is:

:.,$w !espeak
  • : go to command mode
  • .,$ is a range filter, . means the current line, $ means end of file.
  • w means write, but unlike your normal :wq, it doesn’t write to a file. Instead the text is written to the stdio of a command started by a bang !
  • espeak this is the final (external) command.
  • setsid -f see below.

What is setsid -f

  • It’s simple, you don’t want to block your editor while playing the sound! So you want espeak to run “in the background”.
  • I’m being lazy here, setsid -f is to tell the shell to always create new process (fork)
  • Another option is to use nohup and redirect output to /dev/null
  • There are better ways to do it, see below

Actung dirty Hack!

  • Perhaps I should use async instead of setsid -f, and keep espeak as a daemon.
  • Perhaps I should make the parameters configurable, but since I’m not publishing a plugin, this should be fine… daemon.

Conclusion: it works.

edited 15.10.2023
created 12.10.2023
EOF
[+] click to leave a comment [+]
the comment system on this blog works via email. The button
below will generate a mailto: link based on this page's url 
and invoke your email client - please edit the comment there!

[optional] even better, encrypt the email with my public key

- don't modify the subject field
- specify a nickname, otherwise your comment will be shown as   
  anonymous
- your email address will not be disclosed
- you agree that the comment is to be made public.
- to take down a comment, send the request via email.

>> SEND COMMENT <<