Sublime Forum

XML files encoded with ISO-8859-9

#1

Hello,

I have lots of files with encoding other than UTF8. Below is one example. I have files with other encodings, too.

<?xml version="1.0" encoding="ISO-8859-9"?>

Is it possible for SublimeText to auto select encoding of an XML file depending on the first line? I just don’t want to remember lots of shortcut keys for reloading XML in specific encoding.

Thanks & Regards,

0 Likes

#2

I don’t think it would be difficult to write a plugin that would open the XML file with the specified encoding, but what if the encoding specified isn’t supported by ST ?

0 Likes

#3

I can’t write a plugin for ST. Don’t know how to.
If encoding is not supported, plugin will not do anything, I guess.

0 Likes

#4

What kind of values can these encodings take ? Asking because ST uses it’s own names for encodings which may not match what this encoding parameter might take, so some kind of internal mapping might have to be maintained.

0 Likes

#5

So far, I have files with below encodings.

Windows-1254
ISO8859-9
UTF8

My knowledge, Windows-1254 is identical to ISO-8859-9

0 Likes

#6

Based on the encodings you have specified, here is a simple plugin that will automatically open any XML file in the encoding it specifies.

To use this plugin, go to Tools -> Developer -> New Plugin, remove whatever boilerplate is present in that and paste the below code there. Save that (in the User directory) with any file name you want.

Now, whenever you open any XML file, if it has a encoding specified, it would open it based on the _xml_to_st_encoding_map variable.

import sublime
import sublime_plugin
from xml.dom.minidom import parseString

_xml_to_st_encoding_map = {
    "Windows-1254": "Turkish (Windows 1254)",
    "ISO-8859-9": "Turkish (ISO 8859-9)",
    "UTF-8": "utf-8"
}

class SetXmlEncodingListener(sublime_plugin.ViewEventListener):

    @classmethod
    def is_applicable(cls, settings):
        syntax = settings.get("syntax")
        return syntax == "Packages/XML/XML.sublime-syntax"

    def on_load_async(self):
        opened_file = self.view.file_name()

        try:
            with open(opened_file, "r") as xml_file:
                xml_data = parseString(xml_file.read())
        except Exception as e:
            sublime.status_message("No XML data")
            return

        # If there is no encoding specified, return.
        if not xml_data.encoding:
            sublime.status_message("XML doesn't have any encoding specified.")
            return

        # If the encoding specified is not defined in the map, return.
        if not _xml_to_st_encoding_map.get(xml_data.encoding):
            sublime.status_message("Encoding specified is not present in the mapping.")
            return

        self.view.run_command("reopen", {
            "encoding": _xml_to_st_encoding_map.get(xml_data.encoding)
        })

0 Likes

#7

Thank you. Works just fine.

0 Likes