-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
297 lines (231 loc) · 8.58 KB
/
utils.py
File metadata and controls
297 lines (231 loc) · 8.58 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import os
from typing import Optional
import sublime
from .constants import SETTINGS_FILE
def claudette_chat_status_message(
window, message: str, prefix: str = "ℹ️", copy_path: Optional[str] = None
) -> int:
"""
Display a status message in the active chat view.
Args:
window: The Sublime Text window
message (str): Status text to display
prefix (str, optional): Prefix icon/text (default "ℹ️")
copy_path (str, optional): If set, show a Copy Path phantom
Returns:
int: End position of the message in the view, or -1 if missing
"""
if not window:
return -1
# Find the active chat view
current_chat_view = None
for view in window.views():
if view.settings().get(
"claudette_is_chat_view", False
) and view.settings().get("claudette_is_current_chat", False):
current_chat_view = view
break
if not current_chat_view:
return -1
if current_chat_view.size() > 0:
view_size = current_chat_view.size()
last_chars = current_chat_view.substr(
sublime.Region(max(0, view_size - 2), view_size)
)
if last_chars == "\n\n":
# Two trailing newlines: do not add another before the message
formatted_message = f"{prefix + ' ' if prefix else ''}{message}"
elif last_chars.endswith("\n"):
# Content ends with one newline, add one more for spacing
formatted_message = f"\n{prefix + ' ' if prefix else ''}{message}"
else:
# Content doesn't end with newline, add two for spacing
formatted_message = (
f"\n\n{prefix + ' ' if prefix else ''}{message}"
)
else:
formatted_message = f"{prefix + ' ' if prefix else ''}{message}"
current_chat_view.set_read_only(False)
current_chat_view.run_command(
"append",
{
"characters": formatted_message,
"force": True,
"scroll_to_end": True,
},
)
# Add "Copy Path" button as phantom if path is provided
if copy_path:
button_position = current_chat_view.size()
_add_copy_path_phantom(current_chat_view, button_position, copy_path)
# Add trailing newline
current_chat_view.run_command(
"append", {"characters": "\n", "force": True, "scroll_to_end": True}
)
end_point = current_chat_view.size()
current_chat_view.sel().clear()
current_chat_view.sel().add(sublime.Region(end_point, end_point))
current_chat_view.set_read_only(True)
return end_point
# Store phantom sets for copy path buttons per view
_copy_path_phantom_sets = {}
def claudette_cleanup_copy_path_phantoms_for_view(view):
"""Remove copy-path phantom state when a view is closed."""
view_id = view.id()
if view_id not in _copy_path_phantom_sets:
return
_copy_path_phantom_sets[view_id].update([])
del _copy_path_phantom_sets[view_id]
def claudette_clear_copy_path_phantom_registry():
"""Clear all copy-path phantom registry entries (e.g. on plugin unload)."""
_copy_path_phantom_sets.clear()
def _add_copy_path_phantom(view, position: int, path: str):
"""
Add a "Copy Path" phantom button at the specified position.
Args:
view: The Sublime Text view
position: The position in the view to add the phantom
path: The path to copy when the button is clicked
"""
view_id = view.id()
if view_id not in _copy_path_phantom_sets:
_copy_path_phantom_sets[view_id] = sublime.PhantomSet(
view, f"copy_path_buttons_{view_id}"
)
phantom_set = _copy_path_phantom_sets[view_id]
# Escape the path for use in HTML
escaped_path = (
path.replace("&", "&")
.replace('"', """)
.replace("<", "<")
.replace(">", ">")
)
button_html = (
' <span class="copy-path-button" style="padding-left: 8px">'
f'<a href="copy:{escaped_path}">Copy Path</a></span>'
)
def on_navigate(href):
if href.startswith("copy:"):
path_to_copy = href[5:]
sublime.set_clipboard(path_to_copy)
sublime.status_message("File path copied to clipboard")
region = sublime.Region(position, position)
phantom = sublime.Phantom(
region, button_html, sublime.LAYOUT_INLINE, on_navigate
)
# Get existing phantoms and add the new one
existing_phantoms = list(phantom_set.phantoms)
existing_phantoms.append(phantom)
phantom_set.update(existing_phantoms)
def claudette_estimate_api_tokens(text):
"""Rough token estimate from character count (chars / 4)."""
return len(text) // 4
def claudette_detect_encoding(sample):
"""
Detect file encoding using BOMs and content analysis.
Similar to how Sublime Text handles encodings.
"""
# Check for BOMs
if sample.startswith(b"\xef\xbb\xbf"):
return "utf-8-sig"
elif sample.startswith(b"\xfe\xff"):
return "utf-16be"
elif sample.startswith(b"\xff\xfe"):
return "utf-16le"
elif sample.startswith(b"\x00\x00\xfe\xff"):
return "utf-32be"
elif sample.startswith(b"\xff\xfe\x00\x00"):
return "utf-32le"
# Try UTF-8
try:
sample.decode("utf-8")
return "utf-8"
except UnicodeDecodeError:
return "latin-1" # Fallback encoding
def claudette_is_text_file(
file_path, sample_size=4096, max_size=1024 * 1024 * 10
):
"""
More complete implementation of Sublime Text's text file detection.
Args:
file_path: Path to the file to check
sample_size: Number of bytes to sample
max_size: Maximum file size to consider (10MB default)
Returns:
tuple: (is_text, encoding, reason)
"""
try:
file_size = os.path.getsize(file_path)
# Size check
if file_size > max_size:
return False, None, "File too large"
# Empty file check
if file_size == 0:
return True, "utf-8", "Empty file"
with open(file_path, "rb") as f:
sample = f.read(min(sample_size, file_size))
# Binary check
if b"\x00" in sample:
null_percentage = sample.count(b"\x00") / len(sample)
if null_percentage > 0.01: # More than 1% nulls
return False, None, "Binary file (contains NULL bytes)"
# Encoding detection
encoding = claudette_detect_encoding(sample)
# Verification check
try:
with open(file_path, "r", encoding=encoding) as f:
f.read(sample_size)
return True, encoding, "Valid text file"
except UnicodeDecodeError:
return False, None, "Unable to decode with detected encoding"
except IOError as e:
return False, None, f"IO Error: {str(e)}"
def claudette_get_api_key():
"""
Get the currently active API key.
Returns:
dict or None: Active key dict with 'key' and 'name', else None
"""
settings = sublime.load_settings(SETTINGS_FILE)
api_key = settings.get("api_key")
# For string API key, return a dict format
if isinstance(api_key, str) and api_key.strip():
return {"key": api_key, "name": "Default"}
# For dict with multiple keys, get the current one
elif (
isinstance(api_key, dict)
and api_key.get("keys")
and isinstance(api_key["keys"], list)
):
keys = api_key["keys"]
current_index = api_key.get("active_key", 0)
# If there's a valid current index, return that key
if isinstance(current_index, int) and 0 <= current_index < len(keys):
key_entry = keys[current_index]
if isinstance(key_entry, dict) and key_entry.get("key"):
return key_entry
# Otherwise return the first valid key
for key_entry in keys:
if isinstance(key_entry, dict) and key_entry.get("key"):
return key_entry
return None
def claudette_get_api_key_value():
"""
Extract the API key value from the API key dictionary.
Returns:
str: The API key value, or an empty string if not available
"""
api_key = claudette_get_api_key()
if isinstance(api_key, dict):
return api_key.get("key", "")
return ""
def claudette_get_api_key_name():
"""
Get the API key name from the API key dictionary.
Returns:
str: The API key name, 'Default' if the key has no name, or 'Undefined'
"""
api_key = claudette_get_api_key()
if isinstance(api_key, dict):
return api_key.get("name", "Default")
return "Undefined"