-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlisteners.py
More file actions
572 lines (477 loc) · 22.2 KB
/
listeners.py
File metadata and controls
572 lines (477 loc) · 22.2 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
"""Claude Code event listeners for Sublime Text."""
import sublime
import sublime_plugin
import urllib.parse
import os
import platform
from .core import get_session_for_view, get_active_session
from .session import Session
from .context_parser import ContextParser, ContextMenuItem, ContextMenuHandler
_last_copy_meta = None # {file, regions: [(row_start, row_end), ...], text}
class ClaudeCodeEventListener(sublime_plugin.EventListener):
def on_post_text_command(self, view, command_name, args):
global _last_copy_meta
if command_name not in ("copy", "cut"):
return
print(f"[Claude] on_post_text_command: {command_name}")
path = view.file_name()
if not path or view.settings().get("claude_output"):
print(f"[Claude] copy tracking skipped: path={path}, claude_output={view.settings().get('claude_output')}")
return
sel = view.sel()
if not sel:
print("[Claude] copy tracking skipped: no sel")
return
regions = []
for r in sel:
row_start = view.rowcol(r.begin())[0] + 1
row_end = view.rowcol(r.end())[0] + 1
regions.append((row_start, row_end))
_last_copy_meta = {
"file": path,
"regions": regions,
"text": sublime.get_clipboard(),
}
print(f"[Claude] copy tracked: {path} regions={regions}")
def on_window_command(self, window: sublime.Window, command: str, args: dict):
if command == "close_window":
# Stop all sessions in this window
to_remove = []
for view_id, session in sublime._claude_sessions.items():
if session.window == window:
session.stop()
to_remove.append(view_id)
for view_id in to_remove:
del sublime._claude_sessions[view_id]
# Intercept close for claude output views
if command in ("close", "close_file", "close_by_index"):
view = window.active_view()
if command == "close_by_index" and args:
group = args.get("group", 0)
index = args.get("index", 0)
views = window.views_in_group(group)
if index < len(views):
view = views[index]
if view and view.settings().get("claude_output"):
session = sublime._claude_sessions.get(view.id())
if session and (session.initialized or session.is_sleeping):
def _ask():
s = sublime._claude_sessions.get(view.id())
if not s or not (s.initialized or s.is_sleeping):
view.close()
return
if sublime.ok_cancel_dialog("Close this Claude session?", "Close"):
s.stop()
if view.id() in sublime._claude_sessions:
del sublime._claude_sessions[view.id()]
view.close()
sublime.set_timeout(_ask, 0)
return ("noop",)
def on_activated(self, view: sublime.View) -> None:
"""Handle view activated - check if it's for context adding from goto."""
import time
window = view.window()
if not window:
return
# Skip Claude output views
if view.settings().get("claude_output"):
return
# Check if we have a pending context session
session_view_id = window.settings().get("claude_pending_context_session")
if not session_view_id:
return
# Check timestamp - only process if at least 300ms have passed
pending_time = window.settings().get("claude_pending_context_time", 0)
if time.time() - pending_time < 0.3:
return
# Clear the pending state
window.settings().erase("claude_pending_context_session")
window.settings().erase("claude_pending_context_time")
# Get the session
session = sublime._claude_sessions.get(session_view_id)
if not session:
return
# Add the file as context
path = view.file_name()
if path:
content = view.substr(sublime.Region(0, view.size()))
session.add_context_file(path, content)
sublime.status_message(f"Added context: {path.split('/')[-1]}")
# Focus back to Claude output and re-enter input mode
def refocus():
session.output.show()
session.output.enter_input_mode()
if session.draft_prompt:
session.output.view.run_command("append", {"characters": session.draft_prompt})
end = session.output.view.size()
session.output.view.sel().clear()
session.output.view.sel().add(sublime.Region(end, end))
sublime.set_timeout(refocus, 100)
def on_close(self, view: sublime.View) -> None:
# Clean up session when output view is closed
if view.id() in sublime._claude_sessions:
sublime._claude_sessions[view.id()].stop()
del sublime._claude_sessions[view.id()]
# Check if closed view was a terminal mode view
tag = view.settings().get("terminus_view.tag") or ""
if tag.startswith("claude-terminal-"):
for vid, session in sublime._claude_sessions.items():
if session.terminal_mode and session._terminal_tag == tag:
session._on_terminal_exit()
break
class ClaudeOutputEventListener(sublime_plugin.ViewEventListener):
"""Handle keys in the Claude output view."""
@classmethod
def is_applicable(cls, settings):
return settings.get("claude_output", False)
def on_activated(self):
"""Update status bar and title when this output view becomes active."""
window = self.view.window()
if not window:
return
# Mark this as the "active" session for the window
old_active = window.settings().get("claude_active_view")
switched = old_active != self.view.id()
window.settings().set("claude_active_view", self.view.id())
# Check if this is an orphaned view that needs reconnection
s = get_session_for_view(self.view)
if not s:
self._reconnect_orphaned_view(window)
s = get_session_for_view(self.view)
# Update this session's status and title
if s:
s._update_status_bar()
s.output.set_name(s.display_name)
# Auto-enter input mode if session is idle and not already in input mode
if s.initialized and not s.working and not s.output.is_input_mode():
s._enter_input_with_draft()
# If already in input mode, ensure cursor is positioned and view is responsive
elif s.output.is_input_mode():
# Make sure there's a valid cursor position so clicking works
# This fixes mouse selection which requires a valid initial cursor state
input_start = s.output._input_start
sel = self.view.sel()
if len(sel) == 0:
# No selection at all - set cursor to input start
self.view.sel().clear()
self.view.sel().add(sublime.Region(input_start, input_start))
# Remove active marker from previous active session
if old_active and old_active != self.view.id() and old_active in sublime._claude_sessions:
old_session = sublime._claude_sessions[old_active]
old_session.output.set_name(old_session.display_name)
def _reconnect_orphaned_view(self, window):
"""Reconnect an orphaned Claude output view on focus."""
from .session import Session, load_saved_sessions
view = self.view
# Guard against double reconnection
if view.id() in sublime._claude_sessions:
return
if view.settings().get("claude_reconnecting"):
return
view.settings().set("claude_reconnecting", True)
name = view.name()
session_name = None
# Strip status prefixes (new format: ◉/◇/•/❓/💤 + space, old: spinner)
import re
name = re.sub(r'^[◉◇•❓⏸⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]\s*', '', name)
# Strip old "Claude: " prefix
if name.startswith("Claude: "):
name = name[8:]
# Strip backend prefix like "[codex] "
if name.startswith("[") and "] " in name:
name = name[name.index("] ") + 2:]
# Strip trailing ellipsis from truncation
name_was_truncated = name.endswith("…")
if name_was_truncated:
name = name[:-1]
# Extract session name (before " - " suffix if present)
if " - " in name:
session_name = name.split(" - ")[0]
elif name and name != "Claude":
session_name = name
# Try to find session_id from saved sessions
resume_id = None
saved_sessions = load_saved_sessions()
# Method 1: Match by name (exact or prefix if name was truncated)
if session_name:
for saved in saved_sessions:
saved_name = saved.get("name") or ""
if not saved.get("session_id"):
continue
if saved_name == session_name or saved_name.startswith(session_name):
resume_id = saved.get("session_id")
session_name = saved_name
break
# Method 2: Match by first prompt in view content
if not resume_id:
content = view.substr(sublime.Region(0, min(500, view.size())))
m = re.search(r'◎ (.+?) ▶', content)
if m:
first_prompt = m.group(1).strip()
for saved in saved_sessions:
fp = saved.get("first_prompt", "")
if fp and fp == first_prompt and saved.get("query_count", 0) > 0:
resume_id = saved.get("session_id")
session_name = saved.get("name") or session_name
break
# Check for pending rewind point
resume_session_at = None
if resume_id:
for saved in saved_sessions:
if saved.get("session_id") == resume_id:
resume_session_at = saved.get("resume_session_at")
break
print(f"[Claude] reconnect: view={view.name()!r}, session={session_name!r}, resume_id={resume_id}")
# Create session in sleeping state — user wakes with Enter or Wake command
saved_backend = view.settings().get("claude_backend", "claude")
session = Session(window, resume_id=resume_id, backend=saved_backend)
session.name = session_name
session.output.view = view
session.draft_prompt = ""
if resume_session_at:
session._pending_resume_at = resume_session_at
sublime._claude_sessions[view.id()] = session
# Reset active states
session.output.reset_active_states()
# Re-apply backend-specific background color
backend = view.settings().get("claude_backend")
if backend:
backend_themes = {
"codex": "Packages/ClaudeCode/ClaudeOutput-codex.hidden-tmTheme",
"copilot": "Packages/ClaudeCode/ClaudeOutput-copilot.hidden-tmTheme",
}
theme = backend_themes.get(backend)
if theme:
view.settings().set("color_scheme", theme)
# If we have a session_id, sleep it. Otherwise auto-reconnect (old behavior).
if resume_id:
session._apply_sleep_ui()
else:
session.start(resume_session_at=resume_session_at)
# Clear reconnecting flag
view.settings().erase("claude_reconnecting")
def on_text_command(self, command_name, args):
"""Intercept text commands to restrict edits in input mode."""
s = get_session_for_view(self.view)
if not s or not s.output.is_input_mode():
return None
# Commands that are always safe (read-only, navigation, selection)
safe_commands = {
"copy", "select_all", "find_all_under",
"drag_select", "context_menu",
"move", "move_to", "scroll_lines",
"claude_submit_input", "claude_code_interrupt",
"claude_open_link", "claude_close_session"
}
if command_name in safe_commands:
return None
# For paste, delegate to claude_paste_image which handles images
if command_name == "paste":
return ("claude_paste_image", {})
# All other commands are potentially destructive - check if cursor is in input region
input_start = s.output._input_start
sel = self.view.sel()
# Check ALL regions in the selection
for region in sel:
# If typing outside input region, refocus to input area
if region.begin() < input_start or region.end() < input_start:
# For insert commands, move cursor to end of input and allow the command
if command_name == "insert" or (command_name == "insert" and args and "characters" in args):
# Move cursor to end of input area
input_end = self.view.size()
self.view.sel().clear()
self.view.sel().add(sublime.Region(input_end, input_end))
self.view.show(input_end)
return None
# For other commands, block them
print(f"[Claude] BLOCKING {command_name} at position {region.begin()}, input_start={input_start}")
return ("noop", {})
return None
def on_selection_modified(self):
"""Dynamically toggle read_only based on cursor position to protect conversation history."""
s = get_session_for_view(self.view)
if not s:
return
# Only manage read_only state when in input mode
if not s.output.is_input_mode():
return
# CRITICAL BUG FIX: Sublime Text requires at least one region in sel()
# for mouse clicks to work. If sel is completely empty, restore a cursor.
sel = self.view.sel()
if len(sel) == 0:
cursor_pos = self.view.size() if self.view.size() > 0 else 0
self.view.sel().add(sublime.Region(cursor_pos, cursor_pos))
return
# Check if ALL cursors/selections are in the input region
input_start = s.output._input_start
all_in_input_region = True
for region in sel:
# If any part of any selection is before input_start, not safe to edit
if region.begin() < input_start:
all_in_input_region = False
break
# Keep view editable - we handle protection via on_modified (Terminus approach)
# This allows typing anywhere, then we redirect it to input area
if self.view.is_read_only():
self.view.set_read_only(False)
def on_query_context(self, key, operator, operand, match_all):
"""Provide context for key bindings."""
if key == "claude_outside_input_area":
s = get_session_for_view(self.view)
if not s or not s.output.is_input_mode():
return False
input_start = s.output._input_start
sel = self.view.sel()
# Check if cursor is outside input area
for region in sel:
if region.begin() < input_start:
return True
return False
return None
_in_soft_undo = False
def on_modified(self):
"""Track modifications and redirect typing from history to input area."""
if self._in_soft_undo:
return
s = get_session_for_view(self.view)
if not s:
return
# Check what command just ran (Terminus trick)
command, args, _ = self.view.command_history(0)
# Don't redirect during input mode setup
if not s.output.is_input_mode():
return
# Handle insert command - check if typing happened outside input area
if command == "insert" and "characters" in args and len(self.view.sel()) == 1:
input_start = s.output._input_start
current_cursor = self.view.sel()[0].end()
# If the insert happened before input area, redirect it
chars = args["characters"]
insert_pos = max(current_cursor - len(chars), 0)
if insert_pos < input_start:
# Undo the insert (guard against recursion)
self._in_soft_undo = True
try:
self.view.run_command("soft_undo")
finally:
self._in_soft_undo = False
# Move cursor to end of input area
input_end = self.view.size()
self.view.sel().clear()
self.view.sel().add(sublime.Region(input_end, input_end))
# Re-insert at correct position
self.view.run_command("insert", {"characters": chars})
# Show cursor
self.view.show(self.view.size())
return
# Block other commands that happened outside input area
elif command and not command.startswith("claude"):
input_start = s.output._input_start
if len(self.view.sel()) > 0:
for region in self.view.sel():
if region.begin() < input_start:
# Unwanted edit in history - undo it
self.view.run_command("soft_undo")
return
# Save draft
input_text = s.output.get_input_text()
s.draft_prompt = input_text
# Check for @ trigger at cursor
sel = self.view.sel()
if sel and len(sel) == 1:
cursor = sel[0].end()
content = self.view.substr(sublime.Region(0, self.view.size()))
trigger = ContextParser.check_trigger(content, cursor)
if trigger:
self._show_context_popup(s, cursor)
def _show_context_popup(self, session: Session, cursor: int) -> None:
"""Show @ context autocomplete via quick panel."""
window = self.view.window()
if not window:
return
# Remove the @ character first
self.view.run_command("claude_replace", {
"start": cursor - 1,
"end": cursor,
"text": ""
})
# Build list of open files
import os
open_files = []
for v in window.views():
if v.file_name() and not v.settings().get("claude_output"):
name = os.path.basename(v.file_name())
path = v.file_name()
open_files.append((name, path))
# Use context parser to build menu
has_pending = bool(session.pending_context)
pending_count = len(session.pending_context) if has_pending else 0
menu_items = ContextParser.build_menu(open_files, has_pending, pending_count)
# Create handler for menu selection
def on_browse():
self._show_file_picker(session)
def on_clear():
session.clear_context()
sublime.status_message("Context cleared")
def on_add_file(path, _content):
# Find the view for this path and read content
for v in window.views():
if v.file_name() == path:
content = v.substr(sublime.Region(0, v.size()))
session.add_context_file(path, content)
break
handler = ContextMenuHandler(on_browse, on_clear, on_add_file)
def on_select(idx):
handler.handle_selection(menu_items, idx)
window.show_quick_panel(
ContextParser.format_menu_items(menu_items),
on_select,
placeholder="Add context..."
)
def _handle_context_choice(self, session: Session, cursor: int, choice: str) -> None:
"""Handle context menu selection."""
window = self.view.window()
if not window:
return
active_view = None
for v in window.views():
if not v.settings().get("claude_output") and v.file_name():
active_view = v
break
if choice == "file":
if active_view and active_view.file_name():
content = active_view.substr(sublime.Region(0, active_view.size()))
session.add_context_file(active_view.file_name(), content)
elif choice == "selection":
if active_view:
sel = active_view.sel()
if sel and not sel[0].empty():
content = active_view.substr(sel[0])
path = active_view.file_name() or "untitled"
session.add_context_selection(path, content)
elif choice == "open":
for v in window.views():
if v.file_name() and not v.settings().get("claude_output"):
content = v.substr(sublime.Region(0, v.size()))
session.add_context_file(v.file_name(), content)
elif choice == "folder":
if active_view and active_view.file_name():
import os
folder = os.path.dirname(active_view.file_name())
session.add_context_folder(folder)
elif choice == "browse":
self._show_file_picker(session)
elif choice == "clear":
session.clear_context()
sublime.status_message("Context cleared")
def _show_file_picker(self, session: Session) -> None:
"""Show Ctrl+P file picker for context."""
import time
window = self.view.window()
if not window:
return
# Store session and timestamp for the callback
window.settings().set("claude_pending_context_session", session.output.view.id())
window.settings().set("claude_pending_context_time", time.time())
# Show the goto file overlay (Ctrl+P)
window.run_command("show_overlay", {"overlay": "goto", "show_files": True})