aboutsummaryrefslogtreecommitdiff
path: root/vim/autoload/fortune.vim
blob: da6e2fa3eff45afe72ac0f5c86283f8873cac1d5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
" Declare paths to check for fortune files
let s:paths = [
      \ $HOME.'/.fortunes',
      \ $HOME.'/.local/share/games/fortunes',
      \]

" List of executables for which we need to check
let s:executables = [
      \ 'fortune',
      \ 'timeout',
      \]

" Entry point for plugin
function! fortune#() abort

  " Check we have all of the executables we need
  for executable in s:executables
    if !executable(executable)
      echoerr 'Missing executable "'.executable.'"'
    endif
  endfor

  " Maximum length of fortunes is the width of the screen minus 1; characters
  " wider than one column will break this
  "
  let limit = &columns - 1

  " Some implementations of fortune(6) thrash the disk if they can't meet the
  " length limit, so we need to rap this invocation in a timeout(1) call
  let command = [
        \ 'timeout',
        \ '0.3s',
        \ 'fortune',
        \ '-s',
        \ '-n',
        \ limit,
        \]

  " Find a path for custom fortunes and add it on to the command if found
  for path in s:paths
    if isdirectory(path)
      call add(command, path)
      break
    endif
  endfor

  " Run the command and condense any control or space character groups into
  " just one space
  let fortune = substitute(
        \ system(join(command)),
        \ '[[:cntrl:][:space:]]\+',
        \ ' ',
        \ 'g',
        \)

  " Show the fortune message!
  echomsg fortune

endfunction