Search code examples
pythonvimfile-typepygments

determine file type of a file without extension


I want to use pygmentize to highlight some script files (python/bash/...) without extension. But pygmentize requires me to specify the lexer using -l. It does not automatically identify the file type from the content.

I have the following options at hand, but none of them work now:

  1. use file -b --mime-type. But this command output x-python and x-shellscript instead of python and bash and I don't know the rules
  2. use vim -e -c 'echo &ft|q' the_file. For any file with or without file extension, vim has a mechanism to guess the file type. But it doesn't work. Since the output goes to the vim window and disappears after q.

What can I do?


@Samborski's method works fine in normal case but it does not work in python subprocess.check_output since the pts is not allocated. If you use nvim, you can use this more straightforward way:

HOME=_ nvim --headless -es file <<EOF
call writefile([&ft], "/dev/stdout")
EOF

Solution

  • You can use vim this way:

    vim -c ':silent execute ":!echo " . &ft . " > /dev/stdout"' -c ':q!' the_file
    

    It simply constructs command to run in the shell as a string concatenation.