aboutsummaryrefslogtreecommitdiff
path: root/autoload/html/spelllang.vim
blob: dfabf40012097effc5a5e4370dd76e3a152a2ee0 (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
" The line count limit for looking for the pattern; no sense churning through
" the whole document every time it's changed.
"
let s:lines = get(g:, 'html_spelllang_lines', 128)

" Crude regular expression to match an <html>, <body>, or <main> tag on one
" line with a lang= attribute set.  This isn't exact, by any means, but
" I don't want to write an actual HTML parser for a mere 'spelllang' hook
" nicety that fails silently anyway.
"
" The first submatch is the language code, e.g. "en", "es".  The second
" submatch is optional and follows a hyphen and is for the regional code,
" e.g. "US", "GB", "AR".
"
let s:pattern = get(g:, 'html_spelllang_pattern',
      \ '\m\c<\%(html\|body\|main\)\>[^>]*\<lang=["'']\='
      \.'\([a-z-]\{2,}\)\%(-\([a-z]\{2,}\)\)'
      \)

" Look for a language code in the first lines of the current buffer, and if it
" looks understandable, adopt an appropriate spelling language.
"
function! html#spelllang#Set() abort

  " Loop through the first s:lines of the buffer
  for line in getline(1, s:lines)

    " Check if this line has an <html lang=""> tag, or skip it
    let matches = matchlist(line, s:pattern)
    if empty(matches)
      continue
    endif

    " The line seems to match our pattern, and so we have a language code in
    " matches[1], and possibly a region code in matches[2].
    "
    " Next we need to check whether we'll attempt to use this to set
    " a spelling language.  Build the expected path for a spellfile; looks
    " like `$VIMRUNTIME/spell/en.utf-8.spl`.  Note that this path doesn't
    " include any language region, per documentation.
    "
    let spellfile = 'spell/' . join([
          \ tolower(matches[1]),
          \ &encoding,
          \ 'spl',
          \], '.')

    " If a spelling list file of the expected name exists in &runtimepath, try
    " setting the local value of 'spelllang' to reflect what was in the lang=
    " attribute; force it to lowercase and separate the region with an
    " underscore rather than a hyphen (if there is a region).
    "
    if strlen(globpath(&runtimepath, spellfile))
      let &l:spelllang = tolower(join(matches[1:2], '_'))
    endif

  endfor

endfunction