2

I want to define an application for opening files based on the filename.

For example I want a file called Gemfile or Dockerfile to be opened with sublime or atom.

I know I can use the mime-type but for both files it will be text/plain.

Or is there a mime-type for Gemfile?

1 Answer 1

0

Matching based on filename is one of the easiest ways to define a mimetype. There is no official mimetype for Gemfiles or Dockerfiles, but take a look in /usr/share/mime/packages/ and you will find many unofficial mimetypes that have <sub-class-of type="text/plain"/> and are typically named text/x-*, such as text/x-python or text/x-markdown.

Adding custom mimetypes is generally straightforward, especially in this case where we can just use the filename.

As you observed the current mimetype of a Dockerfile and Gemfile are both text/plain:

$ xdg-mime query filetype Dockerfile 
text/plain
$ xdg-mime query filetype Gemfile 
text/plain

We will create a new mimetype text/x-dockerfile for files named Dockerfile or *.dockerfile and a new mimetype text/x-gemfile for files named Gemfile. To accomplish this, create an XML file named x-dockerfile.xml with these contents:

<?xml version="1.0"?>
<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>
    <mime-type type="text/x-dockerfile">
        <comment>Dockerfile</comment>
        <sub-class-of type="text/plain"/>
        <glob pattern="Dockerfile"/>
        <glob pattern="*.dockerfile"/>
    </mime-type>
</mime-info>

and another file named x-gemfile.xml with these contents:

<?xml version="1.0"?>
<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>
    <mime-type type="text/x-gemfile">
        <comment>Gemfile</comment>
        <sub-class-of type="text/plain"/>
        <glob pattern="Gemfile"/>
    </mime-type>
</mime-info>

Next, install the mimetypes. For a local user, run these commands:

xdg-mime install --mode user x-dockerfile.xml
xdg-mime install --mode user x-gemfile.xml
update-mime-database ~/.local/share/mime

To install system-wide, run these commands:

xdg-mime install --mode system x-dockerfile.xml
xdg-mime install --mode system x-gemfile.xml
update-mime-database /usr/share/mime

Observe that the detected mimetypes have now changed.

$ xdg-mime query filetype Dockerfile 
text/x-dockerfile
$ xdg-mime query filetype Gemfile
text/x-gemfile

Now you can assign these to whichever text editor you prefer.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .