mnv9script

# MNV functions for file type detection
#
# Maintainer:		The MNV Project <https://github.com/Project-Tick/Project-Tick>
# Last Change:		2026 Mar 24
# Former Maintainer:	Bram Moolenaar <Bram@mnv.org>

# These functions are moved here from runtime/filetype.mnv to make startup
# faster.

var prolog_pattern = '^\s*\(:-\|%\+\(\s\|$\)\|\/\*\)\|\.\s*$'

def IsObjectScriptRoutine(): bool
  var line1 = getline(1)
  line1 = substitute(line1, '^\ufeff', '', '')
  return line1 =~? '^\s*routine\>\s\+[%A-Za-z][%A-Za-z0-9_.]*\%(\s*\[\|\s*;\|$\)'
enddef

export def Check_inp()
  if getline(1) =~ '%%'
    setf tex
  elseif getline(1) =~ '^\*'
    setf abaqus
  else
    var n = 1
    var nmax = line("$") > 500 ? 500 : line("$")
    while n <= nmax
      if getline(n) =~? "^header surface data"
	setf trasys
	break
      endif
      n += 1
    endwhile
  endif
enddef

# Erlang Application Resource Files (*.app.src is matched by extension)
# See: https://erlang.org/doc/system/applications
export def FTapp()
  if exists("g:filetype_app")
    exe "setf " .. g:filetype_app
    return
  endif
  const pat = '^\s*{\s*application\s*,\s*\(''\=\)' .. expand("%:t:r:r") .. '\1\s*,'
  var line: string
  for lnum in range(1, min([line("$"), 100]))
    line = getline(lnum)
    # skip Erlang comments, might be something else
    if line =~ '^\s*%' || line =~ '^\s*$'
      continue
    elseif line =~ '^\s*{' &&
	getline(lnum, lnum + 9)->filter((_, v) => v !~ '^\s*%')->join(' ') =~# pat
      setf erlang
    endif
    return
  endfor
enddef

# This function checks for the kind of assembly that is wanted by the user, or
# can be detected from the beginning of the file.
export def FTasm()
  # make sure b:asmsyntax exists
  if !exists("b:asmsyntax")
    b:asmsyntax = ""
  endif

  if b:asmsyntax == ""
    FTasmsyntax()
  endif

  # if b:asmsyntax still isn't set, default to asmsyntax or GNU
  if b:asmsyntax == ""
    if exists("g:asmsyntax")
      b:asmsyntax = g:asmsyntax
    else
      b:asmsyntax = "asm"
    endif
  endif

  exe "setf " .. fnameescape(b:asmsyntax)
enddef

export def FTmac()
  if exists("g:filetype_mac")
    exe "setf " .. g:filetype_mac
  else
    if IsObjectScriptRoutine()
      setf objectscript_routine
    else
      FTasm()
    endif
  endif
enddef

export def FTasmsyntax()
  # see if the file contains any asmsyntax=foo overrides. If so, change
  # b:asmsyntax appropriately
  var head = " " .. getline(1) .. " " .. getline(2) .. " "
	.. getline(3) .. " " .. getline(4) ..  " " .. getline(5) .. " "
  var match = matchstr(head, '\sasmsyntax=\zs[a-zA-Z0-9]\+\ze\s')
  if match != ''
    b:asmsyntax = match
    return
  endif
  # Use heuristics
  var is_slash_star_encountered = false
  var i = 1
  const n = min([50, line("$")])
  while i <= n
    const line = getline(i)
    if line =~ '^/\*'
      is_slash_star_encountered = true
    endif
    if line =~# '^; Listing generated by Microsoft' || line =~? '^\%(\%(CONST\|_BSS\|_DATA\|_TEXT\)\s\+SEGMENT\>\)\|\s*\.[2-6]86P\?\>\|\s*\.XMM\>'
      b:asmsyntax = "masm"
      return
    elseif line =~ 'Texas Instruments Incorporated' || (line =~ '^\*' && !is_slash_star_encountered)
      # tiasm uses `* comment`, but detection is unreliable if '/*' is seen
      b:asmsyntax = "tiasm"
      return
    elseif ((line =~? '\.title\>\|\.ident\>\|\.macro\>\|\.subtitle\>\|\.library\>'))
      b:asmsyntax = "vmasm"
      return
    endif
    i += 1
  endwhile
enddef

var ft_visual_basic_content = '\c^\s*\%(Attribute\s\+VB_Name\|Begin\s\+\%(VB\.\|{\%(\x\+-\)\+\x\+}\)\)'

# See FTfrm() for Visual Basic form file detection
export def FTbas()
  if exists("g:filetype_bas")
    exe "setf " .. g:filetype_bas
    return
  endif

  # most frequent FreeBASIC-specific keywords in distro files
  var fb_keywords = '\c^\s*\%(extern\|var\|enum\|private\|scope\|union\|byref\|operator\|constructor\|delete\|namespace\|public\|property\|with\|destructor\|using\)\>\%(\s*[:=(]\)\@!'
  var fb_preproc  = '\c^\s*\%(' ..
                      # preprocessor
                      '#\s*\a\+\|' ..
                      # compiler option
                      'option\s\+\%(byval\|dynamic\|escape\|\%(no\)\=gosub\|nokeyword\|private\|static\)\>\|' ..
                      # metacommand
                      '\%(''\|rem\)\s*\$lang\>\|' ..
                      # default datatype
                      'def\%(byte\|longint\|short\|ubyte\|uint\|ulongint\|ushort\)\>' ..
                    '\)'
  var fb_comment  = "^\\s*/'"

  # OPTION EXPLICIT, without the leading underscore, is common to many dialects
  var qb64_preproc = '\c^\s*\%($\a\+\|option\s\+\%(_explicit\|_\=explicitarray\)\>\)'

  for lnum in range(1, min([line("$"), 100]))
    var line = getline(lnum)
    if line =~ ft_visual_basic_content
      setf vb
      return
    elseif line =~ fb_preproc || line =~ fb_comment || line =~ fb_keywords
      setf freebasic
      return
    elseif line =~ qb64_preproc
      setf qb64
      return
    endif
  endfor
  setf basic
enddef

export def FTbtm()
  if exists("g:dosbatch_syntax_for_btm") && g:dosbatch_syntax_for_btm
    setf dosbatch
  else
    setf btm
  endif
enddef

export def BindzoneCheck(default = '')
  if getline(1) .. getline(2) .. getline(3) .. getline(4)
	  =~ '^; <<>> DiG [0-9.]\+.* <<>>\|$ORIGIN\|$TTL\|IN\s\+SOA'
    setf bindzone
  elseif default != ''
    exe 'setf ' .. default
  endif
enddef

# Returns true if file content looks like RAPID
def IsRapid(sChkExt: string = ""): bool
  if sChkExt == "cfg"
    return getline(1) =~? '\v^%(EIO|MMC|MOC|PROC|SIO|SYS):CFG'
  endif
  # called from FTmod, FTprg or FTsys
  return getline(nextnonblank(1)) =~? '\v^\s*%(\%{3}|module\s+\k+\s*%(\(|$))'
enddef

export def FTcfg()
  if exists("g:filetype_cfg")
    exe "setf " .. g:filetype_cfg
  elseif IsRapid("cfg")
    setf rapid
  else
    setf cfg
  endif
enddef

export def FTcl()
  if join(getline(1, 4), '') =~ '/\*'
    setf opencl
  else
    setf lisp
  endif
enddef

# Determines whether a *.cls file is ObjectScript, TeX, Rexx, Visual Basic, or Smalltalk.
export def FTcls()
  if exists("g:filetype_cls")
    exe "setf " .. g:filetype_cls
    return
  endif

  var line1 = getline(1)
  if line1 =~ '^#!.*\<\%(rexx\|regina\)\>'
    setf rexx
    return
  elseif line1 == 'VERSION 1.0 CLASS'
    setf vb
    return
  endif

  var nonblank1 = getline(nextnonblank(1))
  var lnum = nextnonblank(1)
  while lnum > 0 && lnum <= line("$")
    var line = getline(lnum)
    if line =~? '^\s*\%(import\|include\|includegenerator\)\>'
      lnum = nextnonblank(lnum + 1)
    else
      nonblank1 = line
      break
    endif
  endwhile

  if nonblank1 =~? '^\s*class\>\s\+[%A-Za-z][%A-Za-z0-9_.]*\%(\s\+extends\>\|\s*\[\|\s*{\|$\)'
    setf objectscript
  elseif nonblank1 =~ '^\v%(\%|\\)'
    setf tex
  elseif nonblank1 =~ '^\s*\%(/\*\|::\w\)'
    setf rexx
  else
    setf st
  endif
enddef

export def FTll()
  if getline(1) =~ ';\|\<source_filename\>\|\<target\>'
    setf llvm
    return
  endif
  var n = 1
  while n < 100 && n <= line("$")
    var line = getline(n)
    if line =~ '^\s*%'
      setf lex
      return
    endif
    n += 1
  endwhile
  setf lifelines
enddef

export def FTlpc()
  if exists("g:lpc_syntax_for_c")
    var lnum = 1
    while lnum <= 12
      if getline(lnum) =~# '^\(//\|inherit\|private\|protected\|nosave\|string\|object\|mapping\|mixed\)'
	setf lpc
	return
      endif
      lnum += 1
    endwhile
  endif
  setf c
enddef

# Searches within the first `maxlines` lines of the file for distinctive
# Objective-C or C++ syntax and returns the appropriate filetype. Returns a
# null_string if the search was inconclusive.
def CheckObjCOrCpp(maxlines = 100): string
  var n = 1
  while n < maxlines && n <= line('$')
    const line = getline(n)
    if line =~ '\v^\s*\@%(class|interface|end)>'
      return 'objcpp'
    elseif line =~ '\v^\s*%(class|namespace|template|using)>'
      return 'cpp'
    endif
    ++n
  endwhile
  return null_string
enddef

# Determines whether a *.h file is C, C++, Ch, or Objective-C/Objective-C++.
export def FTheader()
  if exists('g:filetype_h')
    execute $'setf {g:filetype_h}'
  elseif exists('g:c_syntax_for_h')
    setf c
  elseif exists('g:ch_syntax_for_h')
    setf ch
  else
    # Search the first 100 lines of the file for distinctive Objective-C or C++
    # syntax and set the filetype accordingly. Otherwise, use C as the default
    # filetype.
    execute $'setf {CheckObjCOrCpp() ?? 'c'}'
  endif
enddef

# This function checks if one of the first ten lines start with a '@'.  In
# that case it is probably a change file.
# If the first line starts with # or ! it's probably a ch file.
# If a line has "main", "include", "//" or "/*" it's probably ch.
# Otherwise CHILL is assumed.
export def FTchange()
  var lnum = 1
  while lnum <= 10
    if getline(lnum)[0] == '@'
      setf change
      return
    endif
    if lnum == 1 && (getline(1)[0] == '#' || getline(1)[0] == '!')
      setf ch
      return
    endif
    if getline(lnum) =~ "MODULE"
      setf chill
      return
    endif
    if getline(lnum) =~ 'main\s*(\|#\s*include\|//'
      setf ch
      return
    endif
    lnum += 1
  endwhile
  setf chill
enddef

export def FTent()
  # This function checks for valid cl syntax in the first five lines.
  # Look for either an opening comment, '#', or a block start, '{'.
  # If not found, assume SGML.
  var lnum = 1
  while lnum < 6
    var line = getline(lnum)
    if line =~ '^\s*[#{]'
      setf cl
      return
    elseif line !~ '^\s*$'
      # Not a blank line, not a comment, and not a block start,
      # so doesn't look like valid cl code.
      break
    endif
    lnum += 1
  endwhile
  setf dtd
enddef

export def ExCheck()
  var lines = getline(1, min([line("$"), 100]))
  if exists('g:filetype_euphoria')
    exe 'setf ' .. g:filetype_euphoria
  elseif match(lines, '^--\|^ifdef\>\|^include\>') > -1
    setf euphoria3
  else
    setf elixir
  endif
enddef

export def EuphoriaCheck()
  if exists('g:filetype_euphoria')
    exe 'setf ' .. g:filetype_euphoria
  else
    setf euphoria3
  endif
enddef

export def DtraceCheck()
  if did_filetype()
    # Filetype was already detected
    return
  endif
  var lines = getline(1, min([line("$"), 100]))
  if match(lines, '^module\>\|^import\>') > -1
    # D files often start with a module and/or import statement.
    setf d
  elseif match(lines, '^#!\S\+dtrace\|#pragma\s\+D\s\+option\|:\S\{-}:\S\{-}:') > -1
    setf dtrace
  else
    setf d
  endif
enddef

export def FTdef()
  # LaTeX def files are usually generated by docstrip, which will output '%%' in first line
  if getline(1) =~ '%%'
    setf tex
  endif
  if get(g:, "filetype_def", "") == "modula2" || IsModula2()
    SetFiletypeModula2()
    return
  endif

  if exists("g:filetype_def")
    exe "setf " .. g:filetype_def
  else
    setf def
  endif
enddef

export def FTe()
  if exists('g:filetype_euphoria')
    exe 'setf ' .. g:filetype_euphoria
  else
    var n = 1
    while n < 100 && n <= line("$")
      if getline(n) =~ "^\\s*\\(<'\\|'>\\)\\s*$"
	setf specman
	return
      endif
      n += 1
    endwhile
    setf eiffel
  endif
enddef

def IsForth(): bool
  var first_line = nextnonblank(1)

  # SwiftForth block comment (line is usually filled with '-' or '=') or
  # OPTIONAL (sometimes precedes the header comment)
  if getline(first_line) =~? '^\%({\%(\s\|$\)\|OPTIONAL\s\)'
    return true
  endif

  var n = first_line
  while n < 100 && n <= line("$")
    # Forth comments and colon definitions
    if getline(n) =~ '^[:(\\] '
      return true
    endif
    n += 1
  endwhile
  return false
enddef

# Distinguish between Forth and Fortran
export def FTf()
  if exists("g:filetype_f")
    exe "setf " .. g:filetype_f
  elseif IsForth()
    setf forth
  else
    setf fortran
  endif
enddef

export def FTfrm()
  if exists("g:filetype_frm")
    exe "setf " .. g:filetype_frm
    return
  endif

  if getline(1) == "VERSION 5.00"
    setf vb
    return
  endif

  var lines = getline(1, min([line("$"), 5]))

  if match(lines, ft_visual_basic_content) > -1
    setf vb
  else
    setf form
  endif
enddef

# Distinguish between Forth and F#
export def FTfs()
  if exists("g:filetype_fs")
    exe "setf " .. g:filetype_fs
  elseif IsForth()
    setf forth
  else
    setf fsharp
  endif
enddef

# Recursively searches for Hare source files within a directory, up to a given
# depth.
def IsHareModule(dir: string, depth: number): bool
  if depth < 1
    return false
  elseif depth == 1
    return !glob(dir .. '/*.ha')->empty()
  endif

  # Check all files in the directory before recursing into subdirectories.
  const items = glob(dir .. '/*', true, true)
    ->sort((a, b) => isdirectory(a) - isdirectory(b))
  for n in items
    if isdirectory(n)
      if IsHareModule(n, depth - 1)
        return true
      endif
    elseif n =~ '\.ha$'
      return true
    endif
  endfor

  return false
enddef

# Determines whether a README file is inside a Hare module and should receive
# the 'haredoc' filetype.
export def FTharedoc()
  if IsHareModule('<afile>:h', get(g:, 'filetype_haredoc', 1))
    setf haredoc
  endif
enddef

# Distinguish between HTML, XHTML, Django and Angular
export def FThtml()
  var n = 1

  # Test if the filename follows the Angular component template convention
  # Disabled for the reasons mentioned here: #13594
  # if expand('%:t') =~ '^.*\.component\.html$'
  #   setf htmlangular
  #   return
  # endif

  while n < 40 && n <= line("$")
    # Check for Angular
    if getline(n) =~ '@\(if\|for\|defer\|switch\)\|\*\(ngIf\|ngFor\|ngSwitch\|ngTemplateOutlet\)\|ng-template\|ng-content'
      setf htmlangular
      return
    endif
    # Check for XHTML
    if getline(n) =~ '\<DTD\s\+XHTML\s'
      setf xhtml
      return
    endif
    # Check for Django
    if getline(n) =~ '{%\s*\(autoescape\|block\|comment\|csrf_token\|cycle\|debug\|extends\|filter\|firstof\|for\|if\|ifchanged\|include\|load\|lorem\|now\|query_string\|regroup\|resetcycle\|spaceless\|templatetag\|url\|verbatim\|widthratio\|with\)\>\|{#\s\+'
      setf htmldjango
      return
    endif
    # Check for SuperHTML
    if getline(n) =~ '<extend\|<super>'
        setf superhtml
        return
    endif
    n += 1
  endwhile
  setf FALLBACK html
enddef

# Distinguish between standard IDL and MS-IDL
export def FTidl()
  var n = 1
  while n < 50 && n <= line("$")
    if getline(n) =~ '^\s*import\s\+"\(unknwn\|objidl\)\.idl"'
      setf msidl
      return
    endif
    n += 1
  endwhile
  setf idl
enddef

# Distinguish between "default", Prolog, zsh module's C and Cproto prototype file.
export def ProtoCheck(default: string)
  # zsh modules use '#include "*.pro"'
  # https://github.com/zsh-users/zsh/blob/63f086d167960a27ecdbcb762179e2c2bf8a29f5/Src/Modules/example.c#L31
  if getline(1) =~ '/* Generated automatically */'
    setf c
  # Cproto files have a comment in the first line and a function prototype in
  # the second line, it always ends in ";".  Indent files may also have
  # comments, thus we can't match comments to see the difference.
  # IDL files can have a single ';' in the second line, require at least one
  # chacter before the ';'.
  elseif getline(2) =~ '.;$'
    setf cpp
  else
    # recognize Prolog by specific text in the first non-empty line
    # require a blank after the '%' because Perl uses "%list" and "%translate"
    var lnum = getline(nextnonblank(1))
    if lnum =~ '\<prolog\>' || lnum =~ prolog_pattern
      setf prolog
    else
      exe 'setf ' .. default
    endif
  endif
enddef

export def FTm()
  if exists("g:filetype_m")
    exe "setf " .. g:filetype_m
    return
  endif

  # excluding end(for|function|if|switch|while) common to Murphi
  var octave_block_terminators = '\<end\%(_try_catch\|classdef\|enumeration\|events\|methods\|parfor\|properties\)\>'

  var objc_preprocessor = '^\s*#\s*\%(import\|include\|define\|if\|ifn\=def\|undef\|line\|error\|pragma\)\>'

  var n = 1
  var saw_comment = 0  # Whether we've seen a multiline comment leader.
  while n < 100
    var line = getline(n)
    if line =~ '^\s*/\*'
      # /* ... */ is a comment in Objective C and Murphi, so we can't conclude
      # it's either of them yet, but track this as a hint in case we don't see
      # anything more definitive.
      saw_comment = 1
    endif
    if line =~ '^\s*//' || line =~ '^\s*@import\>' || line =~ objc_preprocessor
      setf objc
      return
    endif
    if line =~ '^\s*\%(#\|%!\)' || line =~ '^\s*unwind_protect\>' ||
	  \ line =~ '\%(^\|;\)\s*' .. octave_block_terminators
      setf octave
      return
    endif
    # TODO: could be Matlab or Octave
    if line =~ '^\s*%'
      setf matlab
      return
    endif
    if line =~ '^\s*(\*'
      setf mma
      return
    endif
    if line =~ '^\c\s*\(\(type\|var\)\>\|--\)'
      setf murphi
      return
    endif
    n += 1
  endwhile

  if saw_comment
    # We didn't see anything definitive, but this looks like either Objective C
    # or Murphi based on the comment leader. Assume the former as it is more
    # common.
    setf objc
  else
    # Default is Matlab
    setf matlab
  endif
enddef

# For files ending in *.m4, distinguish:
#  – *.html.m4 files
#  - *fvwm2rc*.m4 files
#  – files in the Autoconf M4 dialect
#  – files in POSIX M4
export def FTm4()
  var fname = expand('%:t')
  var path  = expand('%:p:h')

  if fname =~# 'html\.m4$'
    setf htmlm4
    return
  endif

  if fname =~# 'fvwm2rc'
    setf fvwm2m4
    return
  endif

  # Canonical Autoconf file
  if fname ==# 'aclocal.m4'
    setf config
    return
  endif

  # Repo heuristic for Autoconf M4 (nearby configure.ac)
  if filereadable(path .. '/../configure.ac') || filereadable(path .. '/configure.ac')
    setf config
    return
  endif

  # Content heuristic for Autoconf M4 (scan first ~200 lines)
  # Signals:
  #   - Autoconf macro prefixes: AC_/AM_/AS_/AU_/AT_
  var n = 1
  var max = min([200, line('$')])
  while n <= max
    var line = getline(n)
    if line =~# '^\s*A[CMSUT]_'
      setf config
      return
    endif
    n += 1
  endwhile

  # Default to POSIX M4
  setf m4
enddef

export def FTmake()
  # Check if it is a BSD, GNU, or Microsoft Makefile
  unlet! b:make_flavor

  # 1. filename
  if expand('%:t') == 'BSDmakefile'
    b:make_flavor = 'bsd'
    setf make
    return
  elseif expand('%:t') == 'GNUmakefile'
    b:make_flavor = 'gnu'
    setf make
    return
  endif

  # 2. user's setting
  if exists('g:make_flavor')
    b:make_flavor = g:make_flavor
    setf make
    return
  elseif get(g:, 'make_microsoft')
    echom "make_microsoft is deprecated; try g:make_flavor = 'microsoft' instead"
    b:make_flavor = 'microsoft'
    setf make
    return
  endif

  # 3. try to detect a flavor from file content
  var n = 1
  while n < 1000 && n <= line('$')
    var line = getline(n)
    if line =~? '^\s*!\s*\(ifn\=\(def\)\=\|include\|message\|error\)\>'
      b:make_flavor = 'microsoft'
      break
    elseif line =~ '^\.\%(export\|error\|for\|if\%(n\=\%(def\|make\)\)\=\|info\|warning\)\>'
      b:make_flavor = 'bsd'
      break
    elseif line =~ '^ *\%(ifn\=\%(eq\|def\)\|define\|override\)\>'
      b:make_flavor = 'gnu'
      break
    elseif line =~ '\$[({][a-z-]\+\s\+\S\+'  # a function call, e.g. $(shell pwd)
      b:make_flavor = 'gnu'
      break
    endif
    n += 1
  endwhile
  setf make
enddef

export def FTmms()
  var n = 1
  while n < 20
    var line = getline(n)
    if line =~ '^\s*\(%\|//\)' || line =~ '^\*'
      setf mmix
      return
    endif
    if line =~ '^\s*#'
      setf make
      return
    endif
    n += 1
  endwhile
  setf mmix
enddef

# This function checks if one of the first five lines start with a typical
# nroff pattern in man files.  In that case it is probably an nroff file:
# 'filetype' is set and 1 is returned.
export def FTnroff(): number
  var n = 1
  while n <= 5
    var line = getline(n)
    if line =~ '^\%([.'']\s*\%(TH\|D[dt]\|S[Hh]\|d[es]1\?\|so\)\s\+\S\|[.'']\s*ig\>\|\%([.'']\s*\)\?\\"\)'
      setf nroff
      return 1
    endif
    n += 1
  endwhile
  return 0
enddef

export def FTmm()
  var n = 1
  while n < 20
    if getline(n) =~ '^\s*\(#\s*\(include\|import\)\>\|@import\>\|/\*\)'
      setf objcpp
      return
    endif
    n += 1
  endwhile
  setf nroff
enddef

# Returns true if file content looks like LambdaProlog module
def IsLProlog(): bool
  # skip apparent comments and blank lines, what looks like
  # LambdaProlog comment may be RAPID header
  var lnum: number = nextnonblank(1)
  while lnum > 0 && lnum < line('$') && getline(lnum) =~ '^\s*%' # LambdaProlog comment
    lnum = nextnonblank(lnum + 1)
  endwhile
  # this pattern must not catch a go.mod file
  return getline(lnum) =~ '\<module\s\+\w\+\s*\.\s*\(%\|$\)'
enddef

def IsModula2(): bool
  return getline(nextnonblank(1)) =~ '\<MODULE\s\+\w\+\s*\%(\[.*]\s*\)\=;\|^\s*(\*'
enddef

def SetFiletypeModula2()
  const KNOWN_DIALECTS = ["iso", "pim", "r10"]
  const KNOWN_EXTENSIONS = ["gm2"]
  const LINE_COUNT = 200
  const TAG = '(\*!m2\(\w\+\)\%(+\(\w\+\)\)\=\*)'

  var dialect = get(g:, "modula2_default_dialect", "pim")
  var extension = get(g:, "modula2_default_extension", "")

  var matches = []

  # ignore unknown dialects or badly formatted tags
  for lnum in range(1, min([line("$"), LINE_COUNT]))
    matches = matchlist(getline(lnum), TAG)
    if !empty(matches)
      if index(KNOWN_DIALECTS, matches[1]) >= 0
         dialect = matches[1]
      endif
      if index(KNOWN_EXTENSIONS, matches[2]) >= 0
         extension = matches[2]
      endif
      break
    endif
  endfor

  modula2#SetDialect(dialect, extension)

  setf modula2
enddef

# Determine if *.mod is ABB RAPID, LambdaProlog, Modula-2, Modsim III or go.mod
export def FTmod()
  if get(g:, "filetype_mod", "") == "modula2" || IsModula2()
    SetFiletypeModula2()
    return
  endif

  if exists("g:filetype_mod")
    exe "setf " .. g:filetype_mod
  elseif expand("<afile>") =~ '\<go.mod$'
    setf gomod
  elseif IsLProlog()
    setf lprolog
  elseif IsRapid()
    setf rapid
  else
    # Nothing recognized, assume modsim3
    setf modsim3
  endif
enddef

export def FTpl()
  if exists("g:filetype_pl")
    exe "setf " .. g:filetype_pl
  else
    # recognize Prolog by specific text in the first non-empty line
    # require a blank after the '%' because Perl uses "%list" and "%translate"
    var line = getline(nextnonblank(1))
    if line =~ '\<prolog\>' || line =~ prolog_pattern
      setf prolog
    else
      setf perl
    endif
  endif
enddef

export def FTinc()
  if exists("g:filetype_inc")
    exe "setf " .. g:filetype_inc
  else
    if IsObjectScriptRoutine()
      setf objectscript_routine
      return
    endif
    for lnum in range(1, min([line("$"), 20]))
      var line = getline(lnum)
      if line =~? "perlscript"
        setf aspperl
        return
      elseif line =~ "<%"
        setf aspvbs
        return
      elseif line =~ "<?"
        setf php
        return
      # Pascal supports // comments but they're vary rarely used for file
      # headers so assume POV-Ray
      elseif line =~ '^\s*\%({\|(\*\)' || line =~? ft_pascal_keywords
        setf pascal
        return
      elseif line =~# '\<\%(require\|inherit\)\>' || line =~# '[A-Z][A-Za-z0-9_:${}/]*\s\+\%(??\|[?:+.]\)\?=.\? '
        setf bitbake
        return
      endif
    endfor
    FTasmsyntax()
    if exists("b:asmsyntax")
      exe "setf " .. fnameescape(b:asmsyntax)
    else
      setf pov
    endif
  endif
enddef

export def FTprogress_cweb()
  if exists("g:filetype_w")
    exe "setf " .. g:filetype_w
    return
  endif
  if getline(1) =~ '&ANALYZE' || getline(3) =~ '&GLOBAL-DEFINE'
    setf progress
  else
    setf cweb
  endif
enddef

# These include the leading '%' sign
var ft_swig_keywords = '^\s*%\%(addmethods\|apply\|beginfile\|clear\|constant\|define\|echo\|enddef\|endoffile\|extend\|feature\|fragment\|ignore\|import\|importfile\|include\|includefile\|inline\|insert\|keyword\|module\|name\|namewarn\|native\|newobject\|parms\|pragma\|rename\|template\|typedef\|typemap\|types\|varargs\|warn\)'
# This is the start/end of a block that is copied literally to the processor file (C/C++)
var ft_swig_verbatim_block_start = '^\s*%{'

export def FTi()
  if exists("g:filetype_i")
    exe "setf " .. g:filetype_i
    return
  endif
  # This function checks for an assembly comment or a SWIG keyword or verbatim block in the first 50 lines.
  # If not found, assume Progress.
  var lnum = 1
  while lnum <= 50 && lnum < line('$')
    var line = getline(lnum)
    if line =~ '^\s*;' || line =~ '^\*'
      FTasm()
      return
    elseif line =~ ft_swig_keywords || line =~ ft_swig_verbatim_block_start
      setf swig
      return
    endif
    lnum += 1
  endwhile
  setf progress
enddef

export def FTint()
  if exists("g:filetype_int")
    exe "setf " .. g:filetype_int
  elseif IsObjectScriptRoutine()
    setf objectscript_routine
  else
    setf hex
  endif
enddef

var ft_pascal_comments = '^\s*\%({\|(\*\|//\)'
var ft_pascal_keywords = '^\s*\%(program\|unit\|library\|uses\|begin\|procedure\|function\|const\|type\|var\)\>'

export def FTprogress_pascal()
  if exists("g:filetype_p")
    exe "setf " .. g:filetype_p
    return
  endif
  # This function checks for valid Pascal syntax in the first ten lines.
  # Look for either an opening comment or a program start.
  # If not found, assume Progress.
  var lnum = 1
  while lnum <= 10 && lnum < line('$')
    var line = getline(lnum)
    if line =~ ft_pascal_comments || line =~? ft_pascal_keywords
      setf pascal
      return
    elseif line !~ '^\s*$' || line =~ '^/\*'
      # Not an empty line: Doesn't look like valid Pascal code.
      # Or it looks like a Progress /* comment
      break
    endif
    lnum += 1
  endwhile
  setf progress
enddef

export def FTpp()
  if exists("g:filetype_pp")
    exe "setf " .. g:filetype_pp
  else
    var line = getline(nextnonblank(1))
    if line =~ ft_pascal_comments || line =~? ft_pascal_keywords
      setf pascal
    else
      setf puppet
    endif
  endif
enddef

# Determine if *.prg is ABB RAPID. Can also be Clipper, FoxPro or eviews
export def FTprg()
  if exists("g:filetype_prg")
    exe "setf " .. g:filetype_prg
  elseif IsRapid()
    setf rapid
  else
    # Nothing recognized, assume Clipper
    setf clipper
  endif
enddef

export def FTr()
  var max = line("$") > 50 ? 50 : line("$")

  for n in range(1, max)
    # Rebol is easy to recognize, check for that first
    if getline(n) =~? '\<REBOL\>'
      setf rebol
      return
    endif
  endfor

  for n in range(1, max)
    # R has # comments
    if getline(n) =~ '^\s*#'
      setf r
      return
    endif
    # Rexx has /* comments */
    if getline(n) =~ '^\s*/\*'
      setf rexx
      return
    endif
  endfor

  # Nothing recognized, use user default or assume Rexx
  if exists("g:filetype_r")
    exe "setf " .. g:filetype_r
  else
    # Rexx used to be the default, but R appears to be much more popular.
    setf r
  endif
enddef

export def McSetf()
  # Rely on the file to start with a comment.
  # MS message text files use ';', Sendmail files use '#' or 'dnl'
  for lnum in range(1, min([line("$"), 20]))
    var line = getline(lnum)
    if line =~ '^\s*\(#\|dnl\)'
      setf m4  # Sendmail .mc file
      return
    elseif line =~ '^\s*;'
      setf msmessages  # MS Message text file
      return
    endif
  endfor
  setf m4  # Default: Sendmail .mc file
enddef

# Called from filetype.mnv and scripts.mnv.
# When "setft" is passed and false then the 'filetype' option is not set.
export def SetFileTypeSH(name: string, setft = true): string
  if setft && did_filetype()
    # Filetype was already detected
    return ''
  endif
  if setft && expand("<amatch>") =~ g:ft_ignore_pat
    return ''
  endif
  if name =~ '^csh$' || name =~ '^#!.\{-2,}\<csh\>'
    # Some .sh scripts contain #!/bin/csh.
    return SetFileTypeShell("csh", setft)
  elseif name =~ '^tcsh$' || name =~ '^#!.\{-2,}\<tcsh\>'
    # Some .sh scripts contain #!/bin/tcsh.
    return SetFileTypeShell("tcsh", setft)
  elseif name =~ '^zsh$' || name =~ '^#!.\{-2,}\<zsh\>'
    # Some .sh scripts contain #!/bin/zsh.
    return SetFileTypeShell("zsh", setft)
  elseif name =~ '^ksh$' || name =~ '^#!.\{-2,}\<ksh\>'
    b:is_kornshell = 1
    if exists("b:is_bash")
      unlet b:is_bash
    endif
    if exists("b:is_sh")
      unlet b:is_sh
    endif
  elseif exists("g:bash_is_sh") || name =~ '^bash2\=$' ||
	  \ name =~ '^#!.\{-2,}\<bash2\=\>'
    b:is_bash = 1
    if exists("b:is_kornshell")
      unlet b:is_kornshell
    endif
    if exists("b:is_sh")
      unlet b:is_sh
    endif
  elseif name =~ '^\%(da\)\=sh$' || name =~ '^#!.\{-2,}\<\%(da\)\=sh\>'
    # Ubuntu links "sh" to "dash", thus it is expected to work the same way
    b:is_sh = 1
    if exists("b:is_kornshell")
      unlet b:is_kornshell
    endif
    if exists("b:is_bash")
      unlet b:is_bash
    endif
  endif

  return SetFileTypeShell("sh", setft)
enddef

# For shell-like file types, check for an "exec" command hidden in a comment,
# as used for Tcl.
# When "setft" is passed and false then the 'filetype' option is not set.
# Also called from scripts.mnv, thus can't be local to this script.
export def SetFileTypeShell(name: string, setft = true): string
  if setft && did_filetype()
    # Filetype was already detected
    return ''
  endif
  if setft && expand("<amatch>") =~ g:ft_ignore_pat
    return ''
  endif

  var lnum = 2
  while lnum < 20 && lnum < line("$") && getline(lnum) =~ '^\s*\(#\|$\)'
    # Skip empty and comment lines.
    lnum += 1
  endwhile
  if lnum < line("$") && getline(lnum) =~ '\s*exec\s' && getline(lnum - 1) =~ '^\s*#.*\\$'
    # Found an "exec" line after a comment with continuation
    var n = substitute(getline(lnum), '\s*exec\s\+\([^ ]*/\)\=', '', '')
    if n =~ '\<tclsh\|\<wish'
      if setft
	setf tcl
      endif
      return 'tcl'
    endif
  endif

  if setft
    exe "setf " .. name
  endif
  return name
enddef

export def CSH()
  if did_filetype()
    # Filetype was already detected
    return
  endif
  if exists("g:filetype_csh")
    SetFileTypeShell(g:filetype_csh)
  elseif &shell =~ "tcsh"
    SetFileTypeShell("tcsh")
  else
    SetFileTypeShell("csh")
  endif
enddef

var ft_rules_udev_rules_pattern = '^\s*\cudev_rules\s*=\s*"\([^"]\{-1,}\)/*".*'
export def FTRules()
  var path = expand('<amatch>:p')
  if path =~ '/\(etc/udev/\%(rules\.d/\)\=.*\.rules\|\%(usr/\)\=lib/udev/\%(rules\.d/\)\=.*\.rules\)$'
    setf udevrules
    return
  endif
  if path =~ '^/etc/ufw/'
    setf conf  # Better than hog
    return
  endif
  if path =~ '^/\(etc\|usr/share\)/polkit-1/rules\.d'
    setf javascript
    return
  endif
  var config_lines: list<string>
  try
    config_lines = readfile('/etc/udev/udev.conf')
  catch /^MNV\%((\a\+)\)\=:E484/
    setf hog
    return
  endtry
  var dir = expand('<amatch>:p:h')
  for line in config_lines
    if line =~ ft_rules_udev_rules_pattern
      var udev_rules = substitute(line, ft_rules_udev_rules_pattern, '\1', "")
      if dir == udev_rules
	setf udevrules
      endif
      break
    endif
  endfor
  setf hog
enddef

export def SQL()
  if exists("g:filetype_sql")
    exe "setf " .. g:filetype_sql
  else
    setf sql
  endif
enddef

export def FTsa()
  if join(getline(1, 4), "\n") =~# '\%(^\|\n\);'
    setf tiasm
    return
  endif
  setf sather
enddef

# This function checks the first 25 lines of file extension "sc" to resolve
# detection between scala and SuperCollider.
# NOTE: We don't check for 'Class : Method', as this can easily be confused
# 	with valid Scala like `val x : Int = 3`. So we instead only rely on
# 	checks that can't be confused.
export def FTsc()
  for lnum in range(1, min([line("$"), 25]))
    if getline(lnum) =~# 'var\s<\|classvar\s<\|\^this.*\||\w\+|\|+\s\w*\s{\|\*ar\s'
      setf supercollider
      return
    endif
  endfor
  setf scala
enddef

# This function checks the first line of file extension "scd" to resolve
# detection between scdoc and SuperCollider
export def FTscd()
  if getline(1) =~# '\%^\S\+(\d[0-9A-Za-z]*)\%(\s\+\"[^"]*\"\%(\s\+\"[^"]*\"\)\=\)\=$'
    setf scdoc
  else
    setf supercollider
  endif
enddef

# If the file has an extension of 't' and is in a directory 't' or 'xt' then
# it is almost certainly a Perl test file.
# If the first line starts with '#' and contains 'perl' it's probably a Perl
# file.
# (Slow test) If a file contains a 'use' statement then it is almost certainly
# a Perl file.
export def FTperl(): number
  var dirname = expand("%:p:h:t")
  if expand("%:e") == 't' && (dirname == 't' || dirname == 'xt')
    setf perl
    return 1
  endif
  if getline(1)[0] == '#' && getline(1) =~ 'perl'
    setf perl
    return 1
  endif
  var save_cursor = getpos('.')
  call cursor(1, 1)
  var has_use = search('^use\s\s*\k', 'c', 30) > 0
  call setpos('.', save_cursor)
  if has_use
    setf perl
    return 1
  endif
  return 0
enddef

# LambdaProlog and Standard ML signature files
export def FTsig()
  if exists("g:filetype_sig")
    exe "setf " .. g:filetype_sig
    return
  endif

  var lprolog_comment = '^\s*\%(/\*\|%\)'
  var lprolog_keyword = '^\s*sig\s\+\a'
  var sml_comment = '^\s*(\*'
  var sml_keyword = '^\s*\%(signature\|structure\)\s\+\a'

  var line = getline(nextnonblank(1))

  if line =~ lprolog_comment || line =~# lprolog_keyword
    setf lprolog
  elseif line =~ sml_comment || line =~# sml_keyword
    setf sml
  endif
enddef

# This function checks the first 100 lines of files matching "*.sil" to
# resolve detection between Swift Intermediate Language and SILE.
export def FTsil()
  for lnum in range(1, [line('$'), 100]->min())
    var line: string = getline(lnum)
    if line =~ '^\s*[\\%]'
      setf sile
      return
    elseif line =~ '^\s*\S'
      setf sil
      return
    endif
  endfor
  # no clue, default to "sil"
  setf sil
enddef

export def FTsys()
  if exists("g:filetype_sys")
    exe "setf " .. g:filetype_sys
  elseif IsRapid()
    setf rapid
  else
    setf bat
  endif
enddef

# Choose context, plaintex, or tex (LaTeX) based on these rules:
# 1. Check the first line of the file for "%&<format>".
# 2. Check the first 1000 non-comment lines for LaTeX or ConTeXt keywords.
# 3. Default to "plain" or to g:tex_flavor, can be set in user's mnvrc.
export def FTtex()
  var firstline = getline(1)
  var format: string
  if firstline =~ '^%&\s*\a\+'
    format = tolower(matchstr(firstline, '\a\+'))
    format = substitute(format, 'pdf', '', '')
    if format == 'tex'
      format = 'latex'
    elseif format == 'plaintex'
      format = 'plain'
    endif
  elseif expand('%') =~ 'tex/context/.*/.*.tex'
    format = 'context'
  else
    # Default value, may be changed later:
    format = exists("g:tex_flavor") ? g:tex_flavor : 'plain'
    # Save position, go to the top of the file, find first non-comment line.
    var save_cursor = getpos('.')
    call cursor(1, 1)
    var firstNC = search('^\s*[^[:space:]%]', 'c', 1000)
    if firstNC > 0
      # Check the next thousand lines for a LaTeX or ConTeXt keyword.
      var lpat = 'documentclass\>\|usepackage\>\|begin{\|newcommand\>\|renewcommand\>'
      var cpat = 'start\a\+\|setup\a\+\|usemodule\|enablemode\|enableregime\|setvariables\|useencoding\|usesymbols\|stelle\a\+\|verwende\a\+\|stel\a\+\|gebruik\a\+\|usa\a\+\|imposta\a\+\|regle\a\+\|utilisemodule\>'
      var kwline = search('^\s*\\\%(' .. lpat .. '\)\|^\s*\\\(' .. cpat .. '\)',
			      'cnp', firstNC + 1000)
      if kwline == 1		# lpat matched
	format = 'latex'
      elseif kwline == 2	# cpat matched
	format = 'context'
      endif		# If neither matched, keep default set above.
      # let lline = search('^\s*\\\%(' . lpat . '\)', 'cn', firstNC + 1000)
      # let cline = search('^\s*\\\%(' . cpat . '\)', 'cn', firstNC + 1000)
      # if cline > 0
      #   let format = 'context'
      # endif
      # if lline > 0 && (cline == 0 || cline > lline)
      #   let format = 'tex'
      # endif
    endif # firstNC
    call setpos('.', save_cursor)
  endif # firstline =~ '^%&\s*\a\+'

  # Translation from formats to file types.  TODO:  add AMSTeX, RevTex, others?
  if format == 'plain'
    setf plaintex
  elseif format == 'context'
    setf context
  else # probably LaTeX
    setf tex
  endif
  return
enddef

export def FTxml()
  var n = 1
  while n < 100 && n <= line("$")
    var line = getline(n)
    # DocBook 4 or DocBook 5.
    var is_docbook4 = line =~ '<!DOCTYPE.*DocBook'
    var is_docbook5 = line =~ ' xmlns="http://docbook.org/ns/docbook"'
    if is_docbook4 || is_docbook5
      b:docbk_type = "xml"
      if is_docbook5
	b:docbk_ver = 5
      else
	b:docbk_ver = 4
      endif
      setf docbk
      return
    endif
    if line =~ 'xmlns:xbl="http://www.mozilla.org/xbl"'
      setf xbl
      return
    endif
    n += 1
  endwhile
  setf xml
enddef

export def FTy()
  var n = 1
  while n < 100 && n <= line("$")
    var line = getline(n)
    if line =~ '^\s*%'
      setf yacc
      return
    endif
    if getline(n) =~ '^\s*\(#\|class\>\)' && getline(n) !~ '^\s*#\s*include'
      setf racc
      return
    endif
    n += 1
  endwhile
  setf yacc
enddef

export def Redif()
  var lnum = 1
  while lnum <= 5 && lnum < line('$')
    if getline(lnum) =~ "^\ctemplate-type:"
      setf redif
      return
    endif
    lnum += 1
  endwhile
enddef

# This function is called for all files under */debian/patches/*, make sure not
# to non-dep3patch files, such as README and other text files.
export def Dep3patch()
  if expand('%:t') ==# 'series'
    return
  endif

  for ln in getline(1, 100)
    if ln =~# '^\%(Description\|Subject\|Origin\|Bug\|Forwarded\|Author\|From\|Reviewed-by\|Acked-by\|Last-Updated\|Applied-Upstream\):'
      setf dep3patch
      return
    elseif ln =~# '^---'
      # end of headers found. stop processing
      return
    endif
  endfor
enddef

# This function checks the first 15 lines for appearance of 'FoamFile'
# and then 'object' in a following line.
# In that case, it's probably an OpenFOAM file
export def FTfoam()
    var ffile = 0
    var lnum = 1
    while lnum <= 15
      if getline(lnum) =~# '^FoamFile'
	ffile = 1
      elseif ffile == 1 && getline(lnum) =~# '^\s*object'
	setf foam
	return
      endif
      lnum += 1
    endwhile
enddef

# Determine if a *.tf file is TF mud client or terraform
export def FTtf()
  var numberOfLines = line('$')
  for i in range(1, numberOfLines)
    var currentLine = trim(getline(i))
    var firstCharacter = currentLine[0]
    if firstCharacter !=? ";" && firstCharacter !=? "/" && firstCharacter !=? ""
      setf terraform
      return
    endif
  endfor
  setf tf
enddef

var ft_krl_header = '\&\w+'
# Determine if a *.src file is Kuka Robot Language
export def FTsrc()
  var ft_krl_def_or_deffct = '%(global\s+)?def%(fct)?>'
  if exists("g:filetype_src")
    exe "setf " .. g:filetype_src
  elseif getline(nextnonblank(1)) =~? '\v^\s*%(' .. ft_krl_header .. '|' .. ft_krl_def_or_deffct .. ')'
    setf krl
  endif
enddef

# Determine if a *.dat file is Kuka Robot Language
export def FTdat()
  var ft_krl_defdat = 'defdat>'
  if exists("g:filetype_dat")
    exe "setf " .. g:filetype_dat
  elseif getline(nextnonblank(1)) =~? '\v^\s*%(' .. ft_krl_header .. '|' .. ft_krl_defdat .. ')'
    setf krl
  endif
enddef

export def FTlsl()
  if exists("g:filetype_lsl")
    exe "setf " .. g:filetype_lsl
  endif

  var line = getline(nextnonblank(1))
  if line =~ '^\s*%' || line =~# ':\s*trait\s*$'
    setf larch
  else
    setf lsl
  endif
enddef

export def FTtyp()
  if exists("g:filetype_typ")
    exe "setf " .. g:filetype_typ
    return
  endif

  # Look for SQL type definition syntax
  for line in getline(1, 200)
    # SQL type files may define the casing
    if line =~ '^CASE\s\==\s\=\(SAME\|LOWER\|UPPER\|OPPOSITE\)$'
      setf sql
      return
    endif

    # SQL type files may define some types as follows
    if line =~ '^TYPE\s.*$'
      setf sql
      return
    endif
  endfor

  # Otherwise, affect the typst filetype
  setf typst
enddef

# Detect Microsoft Developer Studio Project files (Makefile) or Faust DSP
# files.
export def FTdsp()
  if exists("g:filetype_dsp")
    exe "setf " .. g:filetype_dsp
    return
  endif

  # Test the filename
  if expand('%:t') =~ '^[mM]akefile.*$'
    setf make
    return
  endif

  # Test the file contents
  for line in getline(1, 200)
    # Check for comment style
    if line =~ '^#.*'
      setf make
      return
    endif

    # Check for common lines
    if line =~ '^.*Microsoft Developer Studio Project File.*$'
      setf make
      return
    endif

    if line =~ '^!MESSAGE This is not a valid makefile\..+$'
      setf make
      return
    endif

    # Check for keywords
    if line =~ '^!(IF,ELSEIF,ENDIF).*$'
      setf make
      return
    endif

    # Check for common assignments
    if line =~ '^SOURCE=.*$'
      setf make
      return
    endif
  endfor

  # Otherwise, assume we have a Faust file
  setf faust
enddef

# Set the filetype of a *.v file to Verilog, V or Cog based on the first 500
# lines.
export def FTv()
  if did_filetype()
    # ":setf" will do nothing, bail out early
    return
  endif
  if exists("g:filetype_v")
    exe "setf " .. g:filetype_v
    return
  endif

  var in_comment = 0
  for lnum in range(1, min([line("$"), 500]))
    var line = getline(lnum)
    # Skip Verilog and V comments (lines and blocks).
    if line =~ '^\s*/\*'
      # start comment block
      in_comment = 1
    endif
    if in_comment == 1
      if line =~ '\*/'
        # end comment block
        in_comment = 0
      endif
      # skip comment-block line
      continue
    endif
    if line =~ '^\s*//'
      # skip comment line
      continue
    endif

    # Coq: line ends with a '.' followed by an optional variable number of
    # spaces or contains the start of a comment, but not inside a Verilog or V
    # comment.
    # Example: "Definition x := 10. (*".
    if (line =~ '\.\s*$' && line !~ '/[/*]') || (line =~ '(\*' && line !~ '/[/*].*(\*')
      setf coq
      return
    endif

    # Verilog: line ends with ';' followed by an optional variable number of
    # spaces and an optional start of a comment.
    # Example: " b <= a + 1; // Add 1".
    # Alternatively: a module is defined: " module MyModule ( input )"
    if line =~ ';\s*\(/[/*].*\)\?$' || line =~ '\C^\s*module\s\+\w\+\s*('
      setf verilog
      return
    endif
  endfor

  # No line matched, fall back to "v".
  setf v
enddef

export def FTvba()
  if getline(1) =~ '^["#] MNVball Archiver'
    setf mnv
  else
    setf vb
  endif
enddef

export def Detect_UCI_statements(): bool
  # Match a config or package statement at the start of the line.
  const config_or_package_statement = '^\s*\(\(c\|config\)\|\(p\|package\)\)\s\+\S'
  # Match a line that is either all blank or blank followed by a comment
  const comment_or_blank = '^\s*\(#.*\)\?$'

  # Return true iff the file has a config or package statement near the
  # top of the file and all preceding lines were comments or blank.
  return getline(1) =~# config_or_package_statement
  \   || getline(1) =~# comment_or_blank
  \      && (   getline(2) =~# config_or_package_statement
  \          || getline(2) =~# comment_or_blank
  \             && getline(3) =~# config_or_package_statement
  \         )
enddef

export def DetectFromName()
  const amatch = expand("<amatch>")
  const name = fnamemodify(amatch, ':t')
  const ft = get(ft_from_name, name, '')
  if ft != ''
    execute "setf " .. ft
  endif
enddef

export def DetectFromExt()
  const amatch = expand("<amatch>")
  var ext = fnamemodify(amatch, ':e')
  const name = fnamemodify(amatch, ':t')
  if ext == '' && name[0] == '.'
    ext = name[1 : ]
  endif
  const ft =  get(ft_from_ext, ext, '')
  if ft != ''
    execute "setf " .. ft
  endif
enddef

# Key: extension of the file name. without `.`
# Value: filetype
const ft_from_ext = {
  # 8th (Firth-derivative)
  "8th": "8th",
  # A-A-P recipe
  "aap": "aap",
  # ABAB/4
  "abap": "abap",
  # ABC music notation
  "abc": "abc",
  # ABEL
  "abl": "abel",
  # ABNF
  "abnf": "abnf",
  # AceDB
  "wrm": "acedb",
  # Ada (83, 9X, 95)
  "adb": "ada",
  "ads": "ada",
  "ada": "ada",
  # AHDL
  "tdf": "ahdl",
  # AIDL
  "aidl": "aidl",
  # AMPL
  "run": "ampl",
  # ANTLR / PCCTS
  "g": "pccts",
  # ANTLR 4
  "g4": "antlr4",
  # Arduino
  "ino": "arduino",
  "pde": "arduino",
  # Asymptote
  "asy": "asy",
  # XA65 MOS6510 cross assembler
  "a65": "a65",
  # Applescript
  "applescript": "applescript",
  "scpt": "applescript",
  # Applix ELF
  "am": "elf",
  # Arc Macro Language
  "aml": "aml",
  # ART*Enterprise (formerly ART-IM)
  "art": "art",
  # AsciiDoc
  "asciidoc": "asciidoc",
  "adoc": "asciidoc",
  # ASN.1
  "asn": "asn",
  "asn1": "asn",
  # Assembly - Netwide
  "nasm": "nasm",
  # Assembly - Microsoft
  "masm": "masm",
  # Assembly - Macro (VAX)
  "mar": "vmasm",
  # Astro
  "astro": "astro",
  # Atlas
  "atl": "atlas",
  "as": "atlas",
  # Atom is based on XML
  "atom": "xml",
  # Authzed
  "zed": "authzed",
  # Autoit v3
  "au3": "autoit",
  # Autohotkey
  "ahk": "autohotkey",
  # Autotest .at files are actually Autoconf M4
  "at": "config",
  # Avenue
  "ave": "ave",
  # Awk
  "awk": "awk",
  "gawk": "awk",
  # B
  "mch": "b",
  "ref": "b",
  "imp": "b",
  # Bass
  "bass": "bass",
  # IBasic file (similar to QBasic)
  "iba": "ibasic",
  "ibi": "ibasic",
  # FreeBasic file (similar to QBasic)
  "fb": "freebasic",
  # Batch file for MSDOS. See dist#ft#FTsys for *.sys
  "bat": "dosbatch",
  # BC calculator
  "bc": "bc",
  # BDF font
  "bdf": "bdf",
  # Beancount
  "beancount": "beancount",
  # BibTeX bibliography database file
  "bib": "bib",
  # BibTeX Bibliography Style
  "bst": "bst",
  # Bicep
  "bicep": "bicep",
  "bicepparam": "bicep-params",
  # BIND zone
  "zone": "bindzone",
  # Blank
  "bl": "blank",
  # Brighterscript
  "bs": "brighterscript",
  # Brightscript
  "brs": "brightscript",
  # BSDL
  "bsd": "bsdl",
  "bsdl": "bsdl",
  # Bpftrace
  "bt": "bpftrace",
  # C3
  "c3": "c3",
  "c3i": "c3",
  "c3t": "c3",
  # Cairo
  "cairo": "cairo",
  # Cap'n Proto
  "capnp": "capnp",
  # Common Package Specification
  "cps": "json",
  # C#
  "cs": "cs",
  "csx": "cs",
  "cake": "cs",
  # CSDL
  "csdl": "csdl",
  # Ctags
  "ctags": "conf",
  # Cabal
  "cabal": "cabal",
  # Cedar
  "cedar": "cedar",
  # ChaiScript
  "chai": "chaiscript",
  # Chatito
  "chatito": "chatito",
  # Chuck
  "ck": "chuck",
  # Comshare Dimension Definition Language
  "cdl": "cdl",
  # Conary Recipe
  "recipe": "conaryrecipe",
  # Corn config file
  "corn": "corn",
  # ChainPack Object Notation (CPON)
  "cpon": "cpon",
  # Controllable Regex Mutilator
  "crm": "crm",
  # Cyn++
  "cyn": "cynpp",
  # Cypher query language
  "cypher": "cypher",
  # C++
  "cxx": "cpp",
  "c++": "cpp",
  "hh": "cpp",
  "hxx": "cpp",
  "hpp": "cpp",
  "ipp": "cpp",
  "moc": "cpp",
  "tcc": "cpp",
  "inl": "cpp",
  # MS files (ixx: C++ module interface file, Microsoft Project file)
  "ixx": "cpp",
  "mpp": "cpp",
  # C++ 20 modules (clang)
  # https://clang.llvm.org/docs/StandardCPlusPlusModules.html#file-name-requirement
  "cppm": "cpp",
  "ccm": "cpp",
  "cxxm": "cpp",
  "c++m": "cpp",
  # Ch (CHscript)
  "chf": "ch",
  # TLH files are C++ headers generated by Visual C++'s #import from typelibs
  "tlh": "cpp",
  # Cascading Style Sheets
  "css": "css",
  # Common Expression Language (CEL) - https://cel.dev
  "cel": "cel",
  # Century Term Command Scripts (*.cmd too)
  "con": "cterm",
  # ChordPro
  "chopro": "chordpro",
  "crd": "chordpro",
  "cho": "chordpro",
  "crdpro": "chordpro",
  "chordpro": "chordpro",
  # Clean
  "dcl": "clean",
  "icl": "clean",
  # Clever
  "eni": "cl",
  # Clojure
  "clj": "clojure",
  "cljs": "clojure",
  "cljx": "clojure",
  "cljc": "clojure",
  # Cobol
  "cbl": "cobol",
  "cob": "cobol",
  # Coco/R
  "atg": "coco",
  # Cold Fusion
  "cfm": "cf",
  "cfi": "cf",
  "cfc": "cf",
  # Cooklang
  "cook": "cook",
  # Clinical Quality Language (CQL)
  # .cql is also mentioned as the 'XDCC Catcher queue list' file extension.
  # If support for XDCC Catcher is needed in the future, the contents of the file
  # needs to be inspected.
  "cql": "cqlang",
  # Crystal
  "cr": "crystal",
  # CSV Files
  "csv": "csv",
  # Concertor
  "cto": "concerto",
  # CUDA Compute Unified Device Architecture
  "cu": "cuda",
  "cuh": "cuda",
  # Cue
  "cue": "cue",
  # DAX
  "dax": "dax",
  # WildPackets EtherPeek Decoder
  "dcd": "dcd",
  # Elvish
  "elv": "elvish",
  # Faust
  "lib": "faust",
  # Fennel
  "fnl": "fennel",
  "fnlm": "fennel",
  # Libreoffice config files
  "xcu": "xml",
  "xlb": "xml",
  "xlc": "xml",
  "xba": "xml",
  # Libtool files
  "lo": "sh",
  "la": "sh",
  "lai": "sh",
  # LyRiCs
  "lrc": "lyrics",
  # MLIR
  "mlir": "mlir",
  # Quake C
  "qc": "c",
  # Cucumber
  "feature": "cucumber",
  # Communicating Sequential Processes
  "csp": "csp",
  "fdr": "csp",
  # CUPL logic description and simulation
  "pld": "cupl",
  "si": "cuplsim",
  # Dafny
  "dfy": "dafny",
  # Dart
  "dart": "dart",
  "drt": "dart",
  # Dhall
  "dhall": "dhall",
  # ROCKLinux package description
  "desc": "desc",
  # Desktop files
  "desktop": "desktop",
  "directory": "desktop",
  # Diff files
  "diff": "diff",
  "rej": "diff",
  # Djot
  "dj": "djot",
  "djot": "djot",
  # DOT
  "dot": "dot",
  "gv": "dot",
  # Dylan - lid files
  "lid": "dylanlid",
  # Dylan - intr files (melange)
  "intr": "dylanintr",
  # Dylan
  "dylan": "dylan",
  # Dracula
  "drac": "dracula",
  "drc": "dracula",
  "lvs": "dracula",
  "lpe": "dracula",
  # Datascript
  "ds": "datascript",
  # DTD (Document Type Definition for XML)
  "dtd": "dtd",
  # Devicetree (.its for U-Boot Flattened Image Trees, .keymap for ZMK keymap, and
  # .overlay for Zephyr overlay)
  "dts": "dts",
  "dtsi": "dts",
  "dtso": "dts",
  "its": "dts",
  "keymap": "dts",
  "overlay": "dts",
  # Embedix Component Description
  "ecd": "ecd",
  # ERicsson LANGuage; Yaws is erlang too
  "erl": "erlang",
  "hrl": "erlang",
  "yaws": "erlang",
  # Elm
  "elm": "elm",
  # Elsa - https://github.com/ucsd-progsys/elsa
  "lc": "elsa",
  # EdgeDB Schema Definition Language
  "esdl": "esdl",
  # ESQL-C
  "ec": "esqlc",
  "EC": "esqlc",
  # Esterel
  "strl": "esterel",
  # Essbase script
  "csc": "csc",
  # Expect
  "exp": "expect",
  # Falcon
  "fal": "falcon",
  # Fantom
  "fan": "fan",
  "fwt": "fan",
  # Factor
  "factor": "factor",
  # FGA
  "fga": "fga",
  # FIRRTL - Flexible Internal Representation for RTL
  "fir": "firrtl",
  # Fish shell
  "fish": "fish",
  # Flix
  "flix": "flix",
  # Fluent
  "ftl": "fluent",
  # Focus Executable
  "fex": "focexec",
  "focexec": "focexec",
  # Focus Master file (but not for auto.master)
  "mas": "master",
  "master": "master",
  # Forth
  "ft": "forth",
  "fth": "forth",
  "4th": "forth",
  # Reva Forth
  "frt": "reva",
  # Framescript
  "fsl": "framescript",
  # Func
  "fc": "func",
  # Fusion
  "fusion": "fusion",
  # FHIR Shorthand (FSH)
  "fsh": "fsh",
  # F#
  "fsi": "fsharp",
  "fsx": "fsharp",
  # GDMO
  "mo": "gdmo",
  "gdmo": "gdmo",
  # GDscript
  "gd": "gdscript",
  # Godot resource
  "tscn": "gdresource",
  "tres": "gdresource",
  # Godot shader
  "gdshader": "gdshader",
  "shader": "gdshader",
  # Gemtext
  "gmi": "gemtext",
  "gemini": "gemtext",
  # Gift (Moodle)
  "gift": "gift",
  # Gleam
  "gleam": "gleam",
  # GLSL
  # Extensions supported by Khronos reference compiler (with one exception, ".glsl")
  # https://github.com/KhronosGroup/glslang
  "vert": "glsl",
  "tesc": "glsl",
  "tese": "glsl",
  "glsl": "glsl",
  "geom": "glsl",
  "frag": "glsl",
  "comp": "glsl",
  "rgen": "glsl",
  "rmiss": "glsl",
  "rchit": "glsl",
  "rahit": "glsl",
  "rint": "glsl",
  "rcall": "glsl",
  # GN (generate ninja) files
  "gn": "gn",
  "gni": "gn",
  # Glimmer-flavored TypeScript and JavaScript
  "gts": "typescript.glimmer",
  "gjs": "javascript.glimmer",
  # Go (Google)
  "go": "go",
  # GrADS scripts
  "gs": "grads",
  # GraphQL
  "graphql": "graphql",
  "graphqls": "graphql",
  "gql": "graphql",
  # Gretl
  "gretl": "gretl",
  # GNU Server Pages
  "gsp": "gsp",
  # GYP
  "gyp": "gyp",
  "gypi": "gyp",
  # Hack
  "hack": "hack",
  "hackpartial": "hack",
  # Haml
  "haml": "haml",
  # Hamster Classic | Playground files
  "hsm": "hamster",
  # Handlebars
  "hbs": "handlebars",
  # Hare
  "ha": "hare",
  # Haskell
  "hs": "haskell",
  "hsc": "haskell",
  "hs-boot": "haskell",
  "hsig": "haskell",
  "lhs": "lhaskell",
  "chs": "chaskell",
  # Haste
  "ht": "haste",
  "htpp": "hastepreproc",
  # Haxe
  "hx": "haxe",
  # HCL
  "hcl": "hcl",
  # Hercules
  "vc": "hercules",
  "ev": "hercules",
  "sum": "hercules",
  "errsum": "hercules",
  # HEEx
  "heex": "heex",
  # HEX (Intel)
  "hex": "hex",
  "ihex": "hex",
  "int": "hex",
  "ihe": "hex",
  "ihx": "hex",
  "mcs": "hex",
  "h32": "hex",
  "h80": "hex",
  "h86": "hex",
  "a43": "hex",
  "a90": "hex",
  # Hjson
  "hjson": "hjson",
  # HLS Playlist (or another form of playlist)
  "m3u": "hlsplaylist",
  "m3u8": "hlsplaylist",
  # Hollywood
  "hws": "hollywood",
  # Hoon
  "hoon": "hoon",
  # TI Code Composer Studio General Extension Language
  "gel": "gel",
  # HTTP request files
  "http": "http",
  # HTML with Ruby - eRuby
  "erb": "eruby",
  "rhtml": "eruby",
  # Some template.  Used to be HTML Cheetah.
  "tmpl": "template",
  # Hurl
  "hurl": "hurl",
  # Hylo
  "hylo": "hylo",
  # Hyper Builder
  "hb": "hb",
  # Httest
  "htt": "httest",
  "htb": "httest",
  # Icon
  "icn": "icon",
  # Microsoft IDL (Interface Description Language)  Also *.idl
  # MOF = WMI (Windows Management Instrumentation) Managed Object Format
  "odl": "msidl",
  "mof": "msidl",
  # Idris2
  "idr": "idris2",
  "lidr": "lidris2",
  # Inform
  "inf": "inform",
  "INF": "inform",
  # Ipkg for Idris 2 language
  "ipkg": "ipkg",
  # Informix 4GL (source - canonical, include file, I4GL+M4 preproc.)
  "4gl": "fgl",
  "4gh": "fgl",
  "m4gl": "fgl",
  # .INI file for MSDOS
  "ini": "dosini",
  "INI": "dosini",
  # Inko
  "inko": "inko",
  # Inno Setup
  "iss": "iss",
  # J
  "ijs": "j",
  # JAL
  "jal": "jal",
  "JAL": "jal",
  # Jam
  "jpl": "jam",
  "jpr": "jam",
  # Janet
  "janet": "janet",
  # Java
  "java": "java",
  "jav": "java",
  "jsh": "java",
  # JavaCC
  "jj": "javacc",
  "jjt": "javacc",
  # JavaScript, ECMAScript, ES module script, CommonJS script
  "js": "javascript",
  "jsm": "javascript",
  "javascript": "javascript",
  "es": "javascript",
  "mjs": "javascript",
  "cjs": "javascript",
  # JavaScript with React
  "jsx": "javascriptreact",
  # Java Server Pages
  "jsp": "jsp",
  # Jess
  "clp": "jess",
  # Jgraph
  "jgr": "jgraph",
  # Jinja
  "jinja": "jinja",
  # Jujutsu
  "jjdescription": "jjdescription",
  # Jovial
  "jov": "jovial",
  "j73": "jovial",
  "jovial": "jovial",
  # Jq
  "jq": "jq",
  # JSON5
  "json5": "json5",
  # JSON Patch (RFC 6902)
  "json-patch": "json",
  # Geojson is also json
  "geojson": "json",
  # Jupyter Notebook and jupyterlab config is also json
  "ipynb": "json",
  "jupyterlab-settings": "json",
  # Sublime config
  "sublime-project": "json",
  "sublime-settings": "json",
  "sublime-workspace": "json",
  # JSON
  "json": "json",
  "jsonp": "json",
  "webmanifest": "json",
  # JSON Lines
  "jsonl": "jsonl",
  # Jsonnet
  "jsonnet": "jsonnet",
  "libsonnet": "jsonnet",
  # Julia
  "jl": "julia",
  # KAREL
  "kl": "karel",
  "KL": "karel",
  # KDL
  "kdl": "kdl",
  # KerML
  "kerml": "kerml",
  # Kixtart
  "kix": "kix",
  # Kimwitu[++]
  "k": "kwt",
  # Kivy
  "kv": "kivy",
  # Koka
  "kk": "koka",
  # Kos
  "kos": "kos",
  # Kotlin
  "kt": "kotlin",
  "ktm": "kotlin",
  "kts": "kotlin",
  # KDE script
  "ks": "kscript",
  # Kyaml
  "kyaml": "yaml",
  "kyml": "yaml",
  # Lace (ISE)
  "ace": "lace",
  "ACE": "lace",
  # Latte
  "latte": "latte",
  "lte": "latte",
  # LDAP LDIF
  "ldif": "ldif",
  # Lean
  "lean": "lean",
  # Ledger
  "ldg": "ledger",
  "ledger": "ledger",
  "journal": "ledger",
  # Leex
  "xrl": "leex",
  # Leo
  "leo": "leo",
  # Less
  "less": "less",
  # Lex
  "lex": "lex",
  "l": "lex",
  "lxx": "lex",
  "l++": "lex",
  # Lilypond
  "ly": "lilypond",
  "ily": "lilypond",
  # Liquidsoap
  "liq": "liquidsoap",
  # Liquid
  "liquid": "liquid",
  # Lite
  "lite": "lite",
  "lt": "lite",
  # Livebook
  "livemd": "livebook",
  # Logtalk
  "lgt": "logtalk",
  # LOTOS
  "lotos": "lotos",
  # Lout (also: *.lt)
  "lou": "lout",
  "lout": "lout",
  # Luau
  "luau": "luau",
  # Lynx style file (or LotusScript!)
  "lss": "lss",
  # MaGic Point
  "mgp": "mgp",
  # MakeIndex
  "ist": "ist",
  "mst": "ist",
  # Mallard
  "page": "mallard",
  # Manpage
  "man": "man",
  # Maple V
  "mv": "maple",
  "mpl": "maple",
  "mws": "maple",
  # Mason (it used to include *.comp, are those Mason files?)
  "mason": "mason",
  "mhtml": "mason",
  # Mathematica notebook and package files
  "nb": "mma",
  "wl": "mma",
  # Maya Extension Language
  "mel": "mel",
  # mcmeta
  "mcmeta": "json",
  # MediaWiki
  "mw": "mediawiki",
  "wiki": "mediawiki",
  # Mermaid
  "mmd": "mermaid",
  "mmdc": "mermaid",
  "mermaid": "mermaid",
  # Meson Build system config
  "wrap": "dosini",
  # Metafont
  "mf": "mf",
  # MetaPost
  "mp": "mp",
  # MGL
  "mgl": "mgl",
  # MIX - Knuth assembly
  "mix": "mix",
  "mixal": "mix",
  # Symbian meta-makefile definition (MMP)
  "mmp": "mmp",
  # Larch/Modula-3
  "lm3": "modula3",
  # Monk
  "isc": "monk",
  "monk": "monk",
  "ssc": "monk",
  "tsc": "monk",
  # MOO
  "moo": "moo",
  # Moonscript
  "moon": "moonscript",
  # Move language
  "move": "move",
  # MPD is based on XML
  "mpd": "xml",
  # Motorola S record
  "s19": "srec",
  "s28": "srec",
  "s37": "srec",
  "mot": "srec",
  "srec": "srec",
  # Msql
  "msql": "msql",
  # MuPAD source
  "mu": "mupad",
  # Mush
  "mush": "mush",
  # Mustache
  "mustache": "mustache",
  # N1QL
  "n1ql": "n1ql",
  "nql": "n1ql",
  # Neon
  "neon": "neon",
  # NetLinx
  "axs": "netlinx",
  "axi": "netlinx",
  # Nickel
  "ncl": "nickel",
  # Nim file
  "nim": "nim",
  "nims": "nim",
  "nimble": "nim",
  # Ninja file
  "ninja": "ninja",
  # Nix
  "nix": "nix",
  # Norg
  "norg": "norg",
  # Novell netware batch files
  "ncf": "ncf",
  # N-Quads
  "nq": "nq",
  # Not Quite C
  "nqc": "nqc",
  # NSE - Nmap Script Engine - uses Lua syntax
  "nse": "lua",
  # NSIS
  "nsi": "nsis",
  "nsh": "nsis",
  # N-Triples
  "nt": "ntriples",
  # Nu
  "nu": "nu",
  # Numbat
  "nbt": "numbat",
  # Oblivion Language and Oblivion Script Extender
  "obl": "obse",
  "obse": "obse",
  "oblivion": "obse",
  "obscript": "obse",
  # Objdump
  "objdump": "objdump",
  "cppobjdump": "objdump",
  # Occam
  "occ": "occam",
  # Odin
  "odin": "odin",
  # Omnimark
  "xom": "omnimark",
  "xin": "omnimark",
  # OpenROAD
  "or": "openroad",
  # OpenSCAD
  "scad": "openscad",
  # Oracle config file
  "ora": "ora",
  # Org (Emacs' org-mode)
  "org": "org",
  "org_archive": "org",
  # PApp
  "papp": "papp",
  "pxml": "papp",
  "pxsl": "papp",
  # Pascal (also *.p, *.pp, *.inc)
  "pas": "pascal",
  # Delphi
  "dpr": "pascal",
  # Free Pascal makefile definition file
  "fpc": "fpcmake",
  # Path of Exile item filter
  "filter": "poefilter",
  # PDF
  "pdf": "pdf",
  # PCMK - HAE - crm configure edit
  "pcmk": "pcmk",
  # PEM (Privacy-Enhanced Mail)
  "pem": "pem",
  "cer": "pem",
  "crt": "pem",
  "csr": "pem",
  # Perl POD
  "pod": "pod",
  # Pike and Cmod
  "pike": "pike",
  "pmod": "pike",
  "cmod": "cmod",
  # Palm Resource compiler
  "rcp": "pilrc",
  # Pip requirements
  "pip": "requirements",
  # PL/1, PL/I
  "pli": "pli",
  "pl1": "pli",
  # PL/M (also: *.inp)
  "plm": "plm",
  "p36": "plm",
  "pac": "plm",
  # PL/SQL
  "pls": "plsql",
  "plsql": "plsql",
  # PLP
  "plp": "plp",
  # PO and PO template (GNU gettext)
  "po": "po",
  "pot": "po",
  # Pony
  "pony": "pony",
  # PostScript (+ font files, encapsulated PostScript, Adobe Illustrator)
  "ps": "postscr",
  "pfa": "postscr",
  "afm": "postscr",
  "eps": "postscr",
  "epsf": "postscr",
  "epsi": "postscr",
  "ai": "postscr",
  # PostScript Printer Description
  "ppd": "ppd",
  # Povray
  "pov": "pov",
  # Power Query M
  "pq": "pq",
  # Prisma
  "prisma": "prisma",
  # PPWizard
  "it": "ppwiz",
  "ih": "ppwiz",
  # Pug
  "pug": "pug",
  # Embedded Puppet
  "epp": "epuppet",
  # Obj 3D file format
  # TODO: is there a way to avoid MS-Windows Object files?
  "obj": "obj",
  # Oracle Pro*C/C++
  "pc": "proc",
  # Privoxy actions file
  "action": "privoxy",
  # Software Distributor Product Specification File (POSIX 1387.2-1995)
  "psf": "psf",
  # Prolog
  "pdb": "prolog",
  # Promela
  "pml": "promela",
  # Property Specification Language (PSL)
  "psl": "psl",
  # Google protocol buffers
  "proto": "proto",
  "txtpb": "pbtxt",
  "textproto": "pbtxt",
  "textpb": "pbtxt",
  "pbtxt": "pbtxt",
  "aconfig": "pbtxt", # Android aconfig files
  # Poke
  "pk": "poke",
  # Nvidia PTX (Parallel Thread Execution)
  # See https://docs.nvidia.com/cuda/parallel-thread-execution/
  "ptx": "ptx",
  # Purescript
  "purs": "purescript",
  # Pyret
  "arr": "pyret",
  # Pyrex/Cython
  "pyx": "pyrex",
  "pyx+": "pyrex",
  "pxd": "pyrex",
  "pxi": "pyrex",
  # QL
  "ql": "ql",
  "qll": "ql",
  # QML
  "qml": "qml",
  "qbs": "qml",
  # Quarto
  "qmd": "quarto",
  # QuickBms
  "bms": "quickbms",
  # Racket (formerly detected as "scheme")
  "rkt": "racket",
  "rktd": "racket",
  "rktl": "racket",
  # Radiance
  "rad": "radiance",
  "mat": "radiance",
  # Raku (formerly Perl6)
  "pm6": "raku",
  "p6": "raku",
  "t6": "raku",
  "pod6": "raku",
  "raku": "raku",
  "rakumod": "raku",
  "rakudoc": "raku",
  "rakutest": "raku",
  # Razor
  "cshtml": "razor",
  "razor": "razor",
  # Renderman Interface Bytestream
  "rib": "rib",
  # Rego Policy Language
  "rego": "rego",
  # Rexx
  "rex": "rexx",
  "orx": "rexx",
  "rxo": "rexx",
  "rxj": "rexx",
  "jrexx": "rexx",
  "rexxj": "rexx",
  "rexx": "rexx",
  "testGroup": "rexx",
  "testUnit": "rexx",
  # RSS looks like XML
  "rss": "xml",
  # ReScript
  "res": "rescript",
  "resi": "rescript",
  # Relax NG Compact
  "rnc": "rnc",
  # Relax NG XML
  "rng": "rng",
  # ILE RPG
  "rpgle": "rpgle",
  "rpgleinc": "rpgle",
  # RPL/2
  "rpl": "rpl",
  # Robot Framework
  "robot": "robot",
  "resource": "robot",
  # Roc
  "roc": "roc",
  # RON (Rusty Object Notation)
  "ron": "ron",
  # MikroTik RouterOS script
  "rsc": "routeros",
  # Rpcgen
  "x": "rpcgen",
  # reStructuredText Documentation Format
  "rst": "rst",
  # RTF
  "rtf": "rtf",
  # Ruby
  "rb": "ruby",
  "rbw": "ruby",
  # RubyGems
  "gemspec": "ruby",
  # RBS (Ruby Signature)
  "rbs": "rbs",
  # Rackup
  "ru": "ruby",
  # Ruby on Rails
  "builder": "ruby",
  "rxml": "ruby",
  "rjs": "ruby",
  # Sorbet (Ruby typechecker)
  "rbi": "ruby",
  # Rust
  "rs": "rust",
  # S-lang
  "sl": "slang",
  # Sage
  "sage": "sage",
  # SAS script
  "sas": "sas",
  # Sass
  "sass": "sass",
  # Scala
  "scala": "scala",
  "mill": "scala",
  # SBT - Scala Build Tool
  "sbt": "sbt",
  # Slang Shading Language
  "slang": "shaderslang",
  # Slint
  "slint": "slint",
  # Scilab
  "sci": "scilab",
  "sce": "scilab",
  # SCSS
  "scss": "scss",
  # SD: Streaming Descriptors
  "sd": "sd",
  # SDL
  "sdl": "sdl",
  "pr": "sdl",
  # sed
  "sed": "sed",
  # SubRip
  "srt": "srt",
  # SubStation Alpha
  "ass": "ssa",
  "ssa": "ssa",
  # svelte
  "svelte": "svelte",
  # Sieve (RFC 3028, 5228)
  "siv": "sieve",
  "sieve": "sieve",
  # TriG
  "trig": "trig",
  # Zig and Zig Object Notation (ZON)
  "zig": "zig",
  "zon": "zig",
  # Ziggy and Ziggy Schema
  "ziggy": "ziggy",
  "ziggy-schema": "ziggy_schema",
  # Zserio
  "zs": "zserio",
  # Salt state files
  "sls": "salt",
  # Sexplib
  "sexp": "sexplib",
  # Simula
  "sim": "simula",
  # SINDA
  "sin": "sinda",
  "s85": "sinda",
  # SiSU
  "sst": "sisu",
  "ssm": "sisu",
  "ssi": "sisu",
  "-sst": "sisu",
  "_sst": "sisu",
  # SKILL
  "il": "skill",
  "ils": "skill",
  "cdf": "skill",
  # Cadence
  "cdc": "cdc",
  # Cangjie
  "cj": "cangjie",
  # SLRN
  "score": "slrnsc",
  # Smali
  "smali": "smali",
  # Smalltalk
  "st": "st",
  # Smarty templates
  "tpl": "smarty",
  # SMITH
  "smt": "smith",
  "smith": "smith",
  # Smithy
  "smithy": "smithy",
  # Snobol4 and spitbol
  "sno": "snobol4",
  "spt": "snobol4",
  # SNMP MIB files
  "mib": "mib",
  "my": "mib",
  # Solidity
  "sol": "solidity",
  # SPARQL queries
  "rq": "sparql",
  "sparql": "sparql",
  # Spec (Linux RPM)
  "spec": "spec",
  # Speedup (AspenTech plant simulator)
  "speedup": "spup",
  "spdata": "spup",
  "spd": "spup",
  # Slice
  "ice": "slice",
  # Microsoft Visual Studio Solution
  "sln": "solution",
  "slnf": "json",
  "slnx": "xml",
  # Spice
  "sp": "spice",
  "spice": "spice",
  # Spyce
  "spy": "spyce",
  "spi": "spyce",
  # SQL for Oracle Designer
  "tyb": "sql",
  "tyc": "sql",
  "pkb": "sql",
  "pks": "sql",
  # SQLJ
  "sqlj": "sqlj",
  # PRQL
  "prql": "prql",
  # SQR
  "sqr": "sqr",
  "sqi": "sqr",
  # Squirrel
  "nut": "squirrel",
  # Starlark
  "ipd": "starlark",
  "sky": "starlark",
  "star": "starlark",
  "starlark": "starlark",
  # OpenVPN configuration
  "ovpn": "openvpn",
  # Stata
  "ado": "stata",
  "do": "stata",
  "imata": "stata",
  "mata": "stata",
  # SMCL
  "hlp": "smcl",
  "ihlp": "smcl",
  "smcl": "smcl",
  # Soy
  "soy": "soy",
  # Stored Procedures
  "stp": "stp",
  # Standard ML
  "sml": "sml",
  # Sratus VOS command macro
  "cm": "voscm",
  # Sway (programming language)
  "sw": "sway",
  # Swift
  "swift": "swift",
  "swiftinterface": "swift",
  # Swig
  "swg": "swig",
  "swig": "swig",
  # Synopsys Design Constraints
  "sdc": "sdc",
  # SVG (Scalable Vector Graphics)
  "svg": "svg",
  # Surface
  "sface": "surface",
  # SysML
  "sysml": "sysml",
  # LLVM TableGen
  "td": "tablegen",
  # TAK
  "tak": "tak",
  # Unx Tal
  "tal": "tal",
  # templ
  "templ": "templ",
  # Teal
  "tl": "teal",
  # TealInfo
  "tli": "tli",
  # Telix Salt
  "slt": "tsalt",
  # Terminfo
  "ti": "terminfo",
  # Tera
  "tera": "tera",
  # Terraform variables
  "tfvars": "terraform-vars",
  # TeX
  "latex": "tex",
  "sty": "tex",
  "dtx": "tex",
  "ltx": "tex",
  "bbl": "tex",
  # LaTeX files generated by Inkscape
  "pdf_tex": "tex",
  # ConTeXt
  "mkii": "context",
  "mkiv": "context",
  "mkvi": "context",
  "mkxl": "context",
  "mklx": "context",
  # Texinfo
  "texinfo": "texinfo",
  "texi": "texinfo",
  "txi": "texinfo",
  # Thrift (Apache)
  "thrift": "thrift",
  # Tiger
  "tig": "tiger",
  # TLA+
  "tla": "tla",
  # TPP - Text Presentation Program
  "tpp": "tpp",
  # TRACE32 Script Language
  "cmm": "trace32",
  "cmmt": "trace32",
  "t32": "trace32",
  # Treetop
  "treetop": "treetop",
  # TSS - Geometry
  "tssgm": "tssgm",
  # TSS - Optics
  "tssop": "tssop",
  # TSS - Command Line (temporary)
  "tsscl": "tsscl",
  # TSV Files
  "tsv": "tsv",
  # Tutor mode
  "tutor": "tutor",
  # TWIG files
  "twig": "twig",
  # TypeScript module and common
  "mts": "typescript",
  "cts": "typescript",
  # TypeScript with React
  "tsx": "typescriptreact",
  # TypeSpec files
  "tsp": "typespec",
  # Motif UIT/UIL files
  "uit": "uil",
  "uil": "uil",
  # Ungrammar, AKA Un-grammar
  "ungram": "ungrammar",
  # UnrealScript
  "uc": "uc",
  # URL shortcut
  "url": "urlshortcut",
  # V
  "vsh": "v",
  "vv": "v",
  # Vala
  "vala": "vala",
  # VDF
  "vdf": "vdf",
  # VDM
  "vdmpp": "vdmpp",
  "vpp": "vdmpp",
  "vdmrt": "vdmrt",
  "vdmsl": "vdmsl",
  "vdm": "vdmsl",
  # Vento
  "vto": "vento",
  # Vera
  "vr": "vera",
  "vri": "vera",
  "vrh": "vera",
  # Verilog-AMS HDL
  "va": "verilogams",
  "vams": "verilogams",
  # SystemVerilog
  "sv": "systemverilog",
  "svh": "systemverilog",
  # VHS tape
  # .tape is also used by TapeCalc, which we do not support ATM.  If TapeCalc
  # support is needed the contents of the file needs to be inspected.
  "tape": "vhs",
  # VHDL
  "hdl": "vhdl",
  "vhd": "vhdl",
  "vhdl": "vhdl",
  "vbe": "vhdl",
  "vst": "vhdl",
  "vho": "vhdl",
  # Visual Basic
  # user control, ActiveX document form, active designer, property page
  "ctl": "vb",
  "dob": "vb",
  "dsr": "vb",
  "pag": "vb",
  # Visual Basic Project
  "vbp": "dosini",
  # VBScript (close to Visual Basic)
  "vbs": "vb",
  # Visual Basic .NET (close to Visual Basic)
  "vb": "vb",
  # Visual Studio Macro
  "dsm": "vb",
  # SaxBasic (close to Visual Basic)
  "sba": "vb",
  # VRML V1.0c
  "wrl": "vrml",
  # Vroom (mnv testing and executable documentation)
  "vroom": "vroom",
  # Vue.js Single File Component
  "vue": "vue",
  # WebAssembly
  "wat": "wat",
  "wast": "wat",
  # WebAssembly Interface Type (WIT)
  "wit": "wit",
  # Webmacro
  "wm": "webmacro",
  # WebGPU Shading Language (WGSL)
  "wgsl": "wgsl",
  # Website MetaLanguage
  "wml": "wml",
  # Winbatch
  "wbt": "winbatch",
  # WSML
  "wsml": "wsml",
  # WPL
  "wpl": "xml",
  # XHTML
  "xhtml": "xhtml",
  "xht": "xhtml",
  # Xilinx Vivado/Vitis project files and block design files
  "xpr": "xml",
  "xpfm": "xml",
  "spfm": "xml",
  "bxml": "xml",
  "mmi": "xml",
  "bd": "json",
  "bda": "json",
  "xci": "json",
  "mss": "mss",
  # XS Perl extension interface language
  "xs": "xs",
  # Xmath
  "msc": "xmath",
  "msf": "xmath",
  # XMI (holding UML models) is also XML
  "xmi": "xml",
  # Unison Language
  "u": "unison",
  "uu": "unison",
  # Qt Linguist translation source and Qt User Interface Files are XML
  # However, for .ts TypeScript is more common.
  "ui": "xml",
  # TPM's are RDF-based descriptions of TeX packages (Nikolai Weibull)
  "tpm": "xml",
  # Web Services Description Language (WSDL)
  "wsdl": "xml",
  # Workflow Description Language (WDL)
  "wdl": "wdl",
  # XLIFF (XML Localisation Interchange File Format) is also XML
  "xlf": "xml",
  "xliff": "xml",
  # XML User Interface Language
  "xul": "xml",
  # Xquery
  "xq": "xquery",
  "xql": "xquery",
  "xqm": "xquery",
  "xquery": "xquery",
  "xqy": "xquery",
  # XSD
  "xsd": "xsd",
  # Xslt
  "xsl": "xslt",
  "xslt": "xslt",
  # Yacc
  "yy": "yacc",
  "yxx": "yacc",
  "y++": "yacc",
  # Yaml
  "yaml": "yaml",
  "yml": "yaml",
  "eyaml": "yaml",
  # Raml
  "raml": "raml",
  # YANG
  "yang": "yang",
  # YARA, YARA-X
  "yara": "yara",
  "yar": "yara",
  # Yuck
  "yuck": "yuck",
  # Zimbu
  "zu": "zimbu",
  # Zimbu Templates
  "zut": "zimbutempl",
  # Z80 assembler asz80
  "z8a": "z8a",
  # Stylus
  "styl": "stylus",
  "stylus": "stylus",
  # Universal Scene Description
  "usda": "usd",
  "usd": "usd",
  # Rofi stylesheet
  "rasi": "rasi",
  "rasinc": "rasi",
  # Zsh module
  # mdd: https://github.com/zsh-users/zsh/blob/57248b88830ce56adc243a40c7773fb3825cab34/Etc/zsh-development-guide#L285-L288
  # mdh, pro: https://github.com/zsh-users/zsh/blob/57248b88830ce56adc243a40c7773fb3825cab34/Etc/zsh-development-guide#L268-L271
  # *.mdd will generate *.mdh, *.pro and *.epro.
  # module's *.c will #include *.mdh containing module dependency information and
  # *.pro containing all static declarations of *.c
  # *.epro contains all external declarations of *.c
  "mdh": "c",
  "epro": "c",
  "mdd": "sh",
  # Blueprint markup files
  "blp": "blueprint",
  # Blueprint build system file
  "bp": "bp",
  # Tiltfile
  "Tiltfile": "tiltfile",
  "tiltfile": "tiltfile"
}
# Key: file name (the final path component, excluding the drive and root)
# Value: filetype
const ft_from_name = {
  # Ant
  "build.xml": "ant",
  # Ash of busybox
  ".ash_history": "sh",
  # Automake (must be before the *.am pattern)
  "makefile.am": "automake",
  "Makefile.am": "automake",
  "GNUmakefile.am": "automake",
  # APT config file
  "apt.conf": "aptconf",
  # BIND zone
  "named.root": "bindzone",
  # Brewfile (uses Ruby syntax)
  "Brewfile": "ruby",
  # Busted (Lua unit testing framework - configuration files)
  ".busted": "lua",
  # Bun history
  ".bun_repl_history": "javascript",
  # Calendar
  "calendar": "calendar",
  # Cgdb config file
  "cgdbrc": "cgdbrc",
  # Cfengine
  "cfengine.conf": "cfengine",
  # Chktex
  ".chktexrc": "conf",
  # Codeowners
  "CODEOWNERS": "codeowners",
  # Clangd
  ".clangd": "yaml",
  # Conda configuration file
  ".condarc": "yaml",
  "condarc": "yaml",
  # Cling
  ".cling_history": "cpp",
  # CmakeCache
  "CMakeCache.txt": "cmakecache",
  # Configure scripts
  "configure.in": "config",
  "configure.ac": "config",
  # Debian devscripts
  "devscripts.conf": "sh",
  ".devscripts": "sh",
  # Fontconfig config files
  "fonts.conf": "xml",
  # Libreoffice config files
  "psprint.conf": "dosini",
  "sofficerc": "dosini",
  # Lynx config files
  "lynx.cfg": "lynx",
  # Mamba configuration file
  ".mambarc": "yaml",
  "mambarc": "yaml",
  # XDG mimeapps.list
  "mimeapps.list": "dosini",
  # Many tools written in Python use dosini as their config
  # like setuptools, pudb, coverage, pypi, gitlint, oelint-adv, pylint, bpython, mypy
  # (must be before *.cfg)
  "pip.conf": "dosini",
  "setup.cfg": "dosini",
  "pudb.cfg": "dosini",
  ".coveragerc": "dosini",
  ".pypirc": "dosini",
  ".gitlint": "dosini",
  ".oelint.cfg": "dosini",
  # Many tools written in Python use toml as their config, like black
  ".black": "toml",
  # Wakatime config
  ".wakatime.cfg": "dosini",
  # Deno history
  "deno_history.txt": "javascript",
  # Deny hosts
  "denyhosts.conf": "denyhosts",
  # Dict config
  "dict.conf": "dictconf",
  ".dictrc": "dictconf",
  # Earthfile
  "Earthfile": "earthfile",
  # EditorConfig
  ".editorconfig": "editorconfig",
  # Elinks configuration
  "elinks.conf": "elinks",
  # Erlang
  "rebar.config": "erlang",
  # Exim
  "exim.conf": "exim",
  # Exports
  "exports": "exports",
  # Fetchmail RC file
  ".fetchmailrc": "fetchmail",
  # Focus Master file (but not for auto.master)
  "auto.master": "conf",
  # FStab
  "fstab": "fstab",
  "mtab": "fstab",
  # Git
  "COMMIT_EDITMSG": "gitcommit",
  "MERGE_MSG": "gitcommit",
  "TAG_EDITMSG": "gitcommit",
  "NOTES_EDITMSG": "gitcommit",
  "EDIT_DESCRIPTION": "gitcommit",
  # gnash(1) configuration files
  "gnashrc": "gnash",
  ".gnashrc": "gnash",
  "gnashpluginrc": "gnash",
  ".gnashpluginrc": "gnash",
  # Gitolite
  "gitolite.conf": "gitolite",
  # Go (Google)
  "Gopkg.lock": "toml",
  "go.work": "gowork",
  # GoAccess configuration
  "goaccess.conf": "goaccess",
  # GTK RC
  ".gtkrc": "gtkrc",
  "gtkrc": "gtkrc",
  # Haskell
  "cabal.project": "cabalproject",
  # Go checksum file (must be before *.sum Hercules)
  "go.sum": "gosum",
  "go.work.sum": "gosum",
  # Indent profile (must come before IDL *.pro!)
  ".indent.pro": "indent",
  # Indent RC
  "indentrc": "indent",
  # Ipfilter
  "ipf.conf": "ipfilter",
  "ipf6.conf": "ipfilter",
  "ipf.rules": "ipfilter",
  # SysV Inittab
  "inittab": "inittab",
  # JavaScript, ECMAScript, ES module script, CommonJS script
  ".node_repl_history": "javascript",
  # Other files that look like json
  ".prettierrc": "json",
  ".firebaserc": "json",
  ".stylelintrc": "json",
  ".lintstagedrc": "json",
  "flake.lock": "json",
  "deno.lock": "json",
  ".swcrc": "json",
  "composer.lock": "json",
  "symfony.lock": "json",
  # Kconfig
  "Kconfig": "kconfig",
  "Kconfig.debug": "kconfig",
  "Config.in": "kconfig",
  # Latexmkrc
  ".latexmkrc": "perl",
  "latexmkrc": "perl",
  # LDAP configuration
  "ldaprc": "ldapconf",
  ".ldaprc": "ldapconf",
  "ldap.conf": "ldapconf",
  # Luadoc, Ldoc (must be before *.ld)
  "config.ld": "lua",
  # lf configuration (lfrc)
  "lfrc": "lf",
  # Lilo: Linux loader
  "lilo.conf": "lilo",
  # SBCL implementation of Common Lisp
  "sbclrc": "lisp",
  ".sbclrc": "lisp",
  # Luau config
  ".luaurc": "jsonc",
  # Luacheck
  ".luacheckrc": "lua",
  # Mailcap configuration file
  ".mailcap": "mailcap",
  "mailcap": "mailcap",
  # Meson Build system config
  "meson.build": "meson",
  "meson.options": "meson",
  "meson_options.txt": "meson",
  # msmtp
  ".msmtprc": "msmtp",
  # Mrxvtrc
  "mrxvtrc": "mrxvtrc",
  ".mrxvtrc": "mrxvtrc",
  # Noemutt setup file
  "Neomuttrc": "neomuttrc",
  # Netrc
  ".netrc": "netrc",
  # NPM RC file
  "npmrc": "dosini",
  ".npmrc": "dosini",
  # ondir
  ".ondirrc": "ondir",
  # OpenAL Soft config files
  ".alsoftrc": "dosini",
  "alsoft.conf": "dosini",
  "alsoft.ini": "dosini",
  "alsoftrc.sample": "dosini",
  # Packet filter conf
  "pf.conf": "pf",
  # ini style config files, using # comments
  "pacman.conf": "confini",
  "mpv.conf": "confini",
  # Pam environment
  "pam_env.conf": "pamenv",
  ".pam_environment": "pamenv",
  # Perl Reply
  ".replyrc": "dosini",
  # Pine config
  ".pinerc": "pine",
  "pinerc": "pine",
  ".pinercex": "pine",
  "pinercex": "pine",
  # Pip requirements
  "requirements.txt": "requirements",
  # Pipenv Pipfiles
  "Pipfile": "toml",
  "Pipfile.lock": "json",
  # Pixi lock
  "pixi.lock": "yaml",
  # Postfix main config
  "main.cf": "pfmain",
  "main.cf.proto": "pfmain",
  # Povray configuration
  ".povrayrc": "povini",
  # Puppet
  "Puppetfile": "ruby",
  # Procmail
  ".procmail": "procmail",
  ".procmailrc": "procmail",
  # PyPA manifest files
  "MANIFEST.in": "pymanifest",
  # QMLdir
  "qmldir": "qmldir",
  # Ratpoison config/command files
  ".ratpoisonrc": "ratpoison",
  "ratpoisonrc": "ratpoison",
  # Readline
  ".inputrc": "readline",
  "inputrc": "readline",
  # R profile file
  ".Rhistory": "r",
  ".Rprofile": "r",
  "Rprofile": "r",
  "Rprofile.site": "r",
  # Resolv.conf
  "resolv.conf": "resolv",
  # Robots.txt
  "robots.txt": "robots",
  # Interactive Ruby shell
  ".irbrc": "ruby",
  "irbrc": "ruby",
  ".irb_history": "ruby",
  "irb_history": "ruby",
  # Bundler
  "Gemfile": "ruby",
  # Samba config
  "smb.conf": "samba",
  # Sendmail
  "sendmail.cf": "sm",
  # SGML catalog file
  "catalog": "catalog",
  # Alpine Linux APKBUILDs are actually POSIX sh scripts with special treatment.
  "APKBUILD": "apkbuild",
  # Screen RC
  ".screenrc": "screen",
  "screenrc": "screen",
  # skhd (simple hotkey daemon for macOS)
  ".skhdrc": "skhd",
  "skhdrc": "skhd",
  # SLRN
  ".slrnrc": "slrnrc",
  # Squid
  "squid.conf": "squid",
  # OpenSSH server configuration
  "sshd_config": "sshdconfig",
  # Tags
  "tags": "tags",
  # Xilinx's xsct and xsdb use tcl
  ".xsctcmdhistory": "tcl",
  ".xsdbcmdhistory": "tcl",
  # TeX configuration
  "texmf.cnf": "texmf",
  # Tidy config
  ".tidyrc": "tidy",
  "tidyrc": "tidy",
  "tidy.conf": "tidy",
  # TF (TinyFugue) mud client
  ".tfrc": "tf",
  "tfrc": "tf",
  # Tilefile
  "Tiltfile": "tiltfile",
  "tiltfile": "tiltfile",
  # Trustees
  "trustees.conf": "trustees",
  # Vagrant (uses Ruby syntax)
  "Vagrantfile": "ruby",
  # MNVinfo file
  ".mnvinfo": "mnvinfo",
  "_mnvinfo": "mnvinfo",
  # Vgrindefs file
  "vgrindefs": "vgrindefs",
  # Wget config
  ".wgetrc": "wget",
  "wgetrc": "wget",
  # Wget2 config
  ".wget2rc": "wget2",
  "wget2rc": "wget2",
  # WvDial
  "wvdial.conf": "wvdial",
  ".wvdialrc": "wvdial",
  # CVS RC file
  ".cvsrc": "cvsrc",
  # X11vnc
  ".x11vncrc": "conf",
  # Xprofile
  ".xprofile": "sh",
  # X compose file
  ".XCompose": "xcompose",
  "Compose": "xcompose",
  # MSBUILD configuration files are also XML
  "Directory.Packages.props": "xml",
  "Directory.Build.targets": "xml",
  "Directory.Build.props": "xml",
  # ATI graphics driver configuration
  "fglrxrc": "xml",
  # Nfs
  "nfs.conf": "dosini",
  "nfsmount.conf": "dosini",
  # Yarn lock
  "yarn.lock": "yaml",
  # Zathurarc
  "zathurarc": "zathurarc",
}

# Uncomment this line to check for compilation errors early
# defcompile
