Sublime Forum

UTF-8 BOM is lost when save an "hot_exit" file

#1

I would like to describe the problem in a few operations:

  1. create a new file in sublime text and type “abc”;
  2. menu “File” > “Save with Encoding” > “UTF-8 with BOM”;
  3. now you can check the saved file have the BOM bytes ‘EF BB BF’, as expected;
  4. then press ENTER in sublime text to make this file dirty (unsaved);
  5. close sublime text app (hot_exit);
  6. restart sublime text app, the file will be reopen in unsaved state;
  7. press Ctrl+S, and check that the BOM is unexpectedly disappeared.

(Windows platform).

0 Likes

#2

Oh, I really hate to spend time making patches on existing functions, but hope it will help.
Paste below code into Packages/some.py (or create the file) would work (not thoroughly tested).

# workaround for: bom setting of unsaved files is lost on hot_exit
# if sublime.version()<'42xx' # uncomment this line if some further version 42xx fix this issue
class BomWorkaroundEventListener(sublime_plugin.EventListener):
    def on_post_save_async(self, view): self.update_bom_(view)
    def on_post_text_command(self, view, cmd, args): cmd=="set_encoding" and self.update_bom_(view)

    def on_init(self, views): {self.init_bom_(view) for view in views}
    def on_load_async(self, view): self.init_bom_(view)
    def on_reload_async(self, view): self.init_bom_(view)
    def on_revert_async(self, view): self.init_bom_(view)

    @staticmethod
    def init_bom_(view):
        have_bom_now = ('with bom' in (view.encoding() or '').lower())
        have_bom_setting = ('with bom' in (view.settings().get('encoding') or '').lower())
        if have_bom_now != have_bom_setting:
            if not have_bom_now: view.set_encoding(view.settings().get('encoding'))
            if not have_bom_setting: view.settings().set('encoding', view.encoding())

    @staticmethod
    def update_bom_(view):
        have_bom_now = ('with bom' in (view.encoding() or '').lower())
        have_bom_setting = ('with bom' in (view.settings().get('encoding') or '').lower())
        if have_bom_now != have_bom_setting:
            view.settings().set('encoding', view.encoding() if have_bom_now else None)

0 Likes

#3

Maybe file an issue at https://github.com/sublimehq/sublime_text/issues to ensure this bugreport doesn’t get burried?

0 Likes

#4

We’ve got a fix for this in the works.

1 Like

#5

Note: the above class BomWorkaroundEventListener is imperfect. for example, it does not handle the situation when change ‘UTF-8 with BOM’ to ‘UTF-16 with BOM’.

Everything would be OK when sublime save/include current encoding choice in the session data.

0 Likes