This repository was archived by the owner on Jul 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.py
More file actions
47 lines (42 loc) · 1.81 KB
/
util.py
File metadata and controls
47 lines (42 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import sublime
import sublime_plugin
def is_dlang(syntax):
"""Returns whether the given syntax corresponds to a D source file"""
return syntax == 'Packages/D/D.sublime-syntax'
def goto_offset(view, offset):
"""Given an offset into a view, shows the view and moves the cursor to the offset"""
region = sublime.Region(offset)
view.sel().clear()
view.sel().add(region)
view.show_at_center(region)
def char_offset_to_encoding_offset(view, char_offset, encoding):
"""Given a character offset into a view, returns the corresponding byte offset w.r.t. to the given encoding"""
assert char_offset <= view.size()
encoded = view.substr(sublime.Region(0, char_offset)).encode(encoding)
return len(encoded)
def encoding_offset_to_char_offset(view, byte_offset, encoding):
"""Given a byte offset into a view w.r.t. the given encoding, returns the corresponding character offset"""
assert byte_offset <= view.size()
encoded = view.substr(sublime.Region(0, byte_offset)).encode(encoding)
if len(encoded) == byte_offset:
return byte_offset
decoded = encoded[0:byte_offset].decode(encoding)
return len(decoded)
def open_file_byte_offset(file_name, byte_offset, encoding):
"""Similar to builtin open_file, but it opens the file at a byte offset w.r.t. to the given encoding"""
class OnLoadListener:
def __init__(self, view):
self.view = view
sublime_plugin.all_callbacks['on_load'].append(self)
def on_load(self, view):
if view.id() == self.view.id():
sublime_plugin.all_callbacks['on_load'].remove(self)
offset = encoding_offset_to_char_offset(view, byte_offset, encoding)
goto_offset(view, offset)
view = sublime.active_window().open_file(file_name)
if view.is_loading():
OnLoadListener(view)
else:
offset = encoding_offset_to_char_offset(view, byte_offset, encoding)
goto_offset(view, offset)
return view