Ubuntu – Files starting with a comment have the wrong mime type

default-programsfile formatmime-type

In Ubuntu 14.04 I have a directory with a set of LESS files, all with the .less extension. All but three of the files show a mime type of plain text document (text/plain) under Properties > Basic. The other three are reported as C source code (text/x-csrc) which means they have a different icon and more annoyingly, get opened with a different default application.

I narrowed the problem down to the contents of the files. It seems any files that start with either a CSS comment block (/* Comment */) or a LESS inline comment (// Comment) have a mime type of text/x-csrc.

I've tried editing the /etc/mime.types file to make the system aware of the extension. First I added less as an extension of text/css:

text/css css less

Then I ran sudo update-mime-database /usr/share/mime on the command line but it didn't work, the files still had the wrong mime type so I tried adding it as an extension of text/plain in the same way but again, nothing. So I tried adding a new mime type:

text/less less

I ran the update-mime-database command again but still no luck.

How can I get Ubuntu to handle the files based on their extension instead of their contents?

Best Answer

Save the following as e.g. less.xml:

<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>
  <mime-type type="text/x-less">
    <comment>LESS file</comment>
    <glob pattern="*.less"/>
  </mime-type>
</mime-info>

Then open a Terminal and run

xdg-mime install --novendor less.xml

Now all files with the extension .less should have the MIME type text/x-less.

See Shared MIME-info Database if you want to learn more about how MIME types are defined.