-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpjb
More file actions
executable file
·710 lines (630 loc) · 35.8 KB
/
pjb
File metadata and controls
executable file
·710 lines (630 loc) · 35.8 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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
#!/usr/bin/env python3
"""PyJavaBridge CLI tool.
Usage:
pjb search <query> Search the documentation
pjb events [<filter>] List available event names
"""
import re
import sys
from pathlib import Path
# Resolve docs directory relative to this script
SCRIPT_DIR = Path(__file__).resolve().parent
# Try multiple possible locations
DOCS_CANDIDATES = [
SCRIPT_DIR.parent / "docs" / "src",
SCRIPT_DIR / "docs" / "src",
Path.cwd() / "docs" / "src",
]
# Known Bukkit/Paper events with their common fields
EVENTS = {
# =========================================================
# PLAYER EVENTS (org.bukkit.event.player)
# =========================================================
"player_advancement_done": {"fields": ["player", "advancement"], "cancellable": False, "desc": "Player completes an advancement"},
"player_animation": {"fields": ["player", "animation"], "cancellable": True, "desc": "Player arm swing animation"},
"player_armor_stand_manipulate": {"fields": ["player", "armor_stand", "item", "slot"], "cancellable": True, "desc": "Player manipulates armor stand"},
"player_bed_enter": {"fields": ["player", "bed", "enter_result"], "cancellable": True, "desc": "Player attempts to enter bed"},
"player_bed_leave": {"fields": ["player", "bed"], "cancellable": False, "desc": "Player leaves bed"},
"player_bucket_empty": {"fields": ["player", "block", "item", "hand"], "cancellable": True, "desc": "Player empties bucket"},
"player_bucket_entity": {"fields": ["player", "entity", "item"], "cancellable": True, "desc": "Player buckets entity (axolotl, fish)"},
"player_bucket_fill": {"fields": ["player", "block", "item", "hand"], "cancellable": True, "desc": "Player fills bucket"},
"player_changed_world": {"fields": ["player", "from_world"], "cancellable": False, "desc": "Player changes worlds"},
"player_channel_register": {"fields": ["player", "channel"], "cancellable": False, "desc": "Plugin channel registered"},
"player_channel_unregister": {"fields": ["player", "channel"], "cancellable": False, "desc": "Plugin channel unregistered"},
"player_chat": {"fields": ["player", "message", "recipients"], "cancellable": True, "desc": "Legacy player chat event"},
"async_player_chat": {"fields": ["player", "message", "recipients"], "cancellable": True, "desc": "Async chat event"},
"player_command_preprocess": {"fields": ["player", "message"], "cancellable": True, "desc": "Player sends command"},
"player_command_send": {"fields": ["player", "commands"], "cancellable": False, "desc": "Available commands sent to player"},
"player_death": {"fields": ["player", "drops", "death_message"], "cancellable": False, "desc": "Player dies"},
"player_drop_item": {"fields": ["player", "item"], "cancellable": True, "desc": "Player drops item"},
"player_edit_book": {"fields": ["player", "book_meta", "signing"], "cancellable": True, "desc": "Player edits book"},
"player_exp_change": {"fields": ["player", "amount"], "cancellable": True, "desc": "Player exp changes"},
"player_fish": {"fields": ["player", "hook", "state", "caught"], "cancellable": True, "desc": "Fishing event"},
"player_game_mode_change": {"fields": ["player", "new_game_mode"], "cancellable": True, "desc": "Game mode change"},
"player_interact": {"fields": ["player", "action", "block", "item", "hand"], "cancellable": True, "desc": "Player interaction"},
"player_interact_at_entity": {"fields": ["player", "entity", "clicked_position", "hand"], "cancellable": True, "desc": "Precise entity interaction"},
"player_interact_entity": {"fields": ["player", "entity", "hand"], "cancellable": True, "desc": "Player interacts with entity"},
"player_item_break": {"fields": ["player", "item"], "cancellable": False, "desc": "Item breaks"},
"player_item_damage": {"fields": ["player", "item", "damage"], "cancellable": True, "desc": "Item durability damage"},
"player_item_mend": {"fields": ["player", "item", "repair_amount"], "cancellable": True, "desc": "Item mended"},
"player_join": {"fields": ["player", "join_message"], "cancellable": False, "desc": "Player joins server"},
"player_kick": {"fields": ["player", "reason", "leave_message"], "cancellable": True, "desc": "Player kicked"},
"player_level_change": {"fields": ["player", "old_level", "new_level"], "cancellable": False, "desc": "Level changes"},
"player_locale_change": {"fields": ["player", "locale"], "cancellable": False, "desc": "Locale changes"},
"player_login": {"fields": ["player", "hostname", "address"], "cancellable": True, "desc": "Login attempt"},
"async_player_pre_login": {"fields": ["name", "uuid", "address"], "cancellable": True, "desc": "Async pre-login"},
"player_move": {"fields": ["player", "from", "to"], "cancellable": True, "desc": "Player moves"},
"player_pickup_arrow": {"fields": ["player", "arrow"], "cancellable": True, "desc": "Pickup arrow"},
"player_pickup_item": {"fields": ["player", "item"], "cancellable": True, "desc": "Pickup item (legacy)"},
"entity_pickup_item": {"fields": ["entity", "item"], "cancellable": True, "desc": "Entity picks up item"},
"player_portal": {"fields": ["player", "from", "to", "cause"], "cancellable": True, "desc": "Player uses portal"},
"player_quit": {"fields": ["player", "quit_message"], "cancellable": False, "desc": "Player quits"},
"player_respawn": {"fields": ["player", "location", "is_anchor_spawn"], "cancellable": False, "desc": "Player respawns"},
"player_riptide": {"fields": ["player"], "cancellable": False, "desc": "Riptide used"},
"player_shear_entity": {"fields": ["player", "entity"], "cancellable": True, "desc": "Shears entity"},
"player_statistic_increment": {"fields": ["player", "statistic", "amount"], "cancellable": False, "desc": "Statistic increment"},
"player_swap_hand_items": {"fields": ["player", "main_hand_item", "off_hand_item"], "cancellable": True, "desc": "Swap hands"},
"player_item_held": {"fields": ["player", "new_slot", "previous_slot"], "cancellable": True, "desc": "Hotbar slot change"},
"player_take_lectern_book": {"fields": ["player", "lectern"], "cancellable": True, "desc": "Take lectern book"},
"player_teleport": {"fields": ["player", "from", "to", "cause"], "cancellable": True, "desc": "Teleport"},
"player_toggle_flight": {"fields": ["player", "is_flying"], "cancellable": True, "desc": "Toggle flight"},
"player_toggle_sneak": {"fields": ["player", "is_sneaking"], "cancellable": True, "desc": "Toggle sneak"},
"player_toggle_sprint": {"fields": ["player", "is_sprinting"], "cancellable": True, "desc": "Toggle sprint"},
"player_velocity": {"fields": ["player", "velocity"], "cancellable": True, "desc": "Velocity change"},
# =========================================================
# BLOCK EVENTS
# =========================================================
"block_break": {"fields": ["player", "block"], "cancellable": True, "desc": "Block broken"},
"block_burn": {"fields": ["block"], "cancellable": True, "desc": "Block burns"},
"block_can_build": {"fields": ["player", "block", "material"], "cancellable": True, "desc": "Check if block can build"},
"block_damage": {"fields": ["player", "block", "insta_break"], "cancellable": True, "desc": "Block damaged"},
"block_dispense": {"fields": ["block", "item", "velocity"], "cancellable": True, "desc": "Dispenser dispense"},
"block_dispense_armor": {"fields": ["block", "item", "target"], "cancellable": True, "desc": "Dispense armor"},
"block_explode": {"fields": ["block", "blocks", "yield"], "cancellable": True, "desc": "Block explosion"},
"block_fade": {"fields": ["block", "new_state"], "cancellable": True, "desc": "Block fades"},
"block_form": {"fields": ["block", "new_state"], "cancellable": True, "desc": "Block forms"},
"block_from_to": {"fields": ["block", "to_block"], "cancellable": True, "desc": "Liquid flow"},
"block_grow": {"fields": ["block", "new_state"], "cancellable": True, "desc": "Block grows"},
"block_ignite": {"fields": ["block", "cause", "player"], "cancellable": True, "desc": "Block ignited"},
"block_multi_place": {"fields": ["player", "blocks"], "cancellable": True, "desc": "Multiple blocks placed"},
"block_physics": {"fields": ["block", "changed_type"], "cancellable": True, "desc": "Physics update"},
"block_piston_extend": {"fields": ["block", "blocks", "direction"], "cancellable": True, "desc": "Piston extend"},
"block_piston_retract": {"fields": ["block", "blocks", "direction"], "cancellable": True, "desc": "Piston retract"},
"block_place": {"fields": ["player", "block", "item"], "cancellable": True, "desc": "Block placed"},
"block_redstone": {"fields": ["block", "old_current", "new_current"], "cancellable": False, "desc": "Redstone change"},
"block_spread": {"fields": ["source", "block"], "cancellable": True, "desc": "Block spreads"},
"bell_ring": {"fields": ["block", "entity"], "cancellable": True, "desc": "Bell rings"},
"note_play": {"fields": ["block", "instrument", "note"], "cancellable": True, "desc": "Note block plays"},
"sign_change": {"fields": ["player", "block", "lines"], "cancellable": True, "desc": "Sign edited"},
"tnt_prime": {"fields": ["block", "entity", "reason"], "cancellable": True, "desc": "TNT primed"},
# =========================================================
# ENTITY EVENTS
# =========================================================
"area_effect_cloud_apply": {"fields": ["entity", "affected_entities"], "cancellable": False, "desc": "Cloud applies effect"},
"bat_toggle_sleep": {"fields": ["entity", "awake"], "cancellable": True, "desc": "Bat toggles sleep"},
"creature_spawn": {"fields": ["entity", "reason"], "cancellable": True, "desc": "Creature spawn"},
"creeper_power": {"fields": ["entity", "cause"], "cancellable": True, "desc": "Creeper powered"},
"entity_air_change": {"fields": ["entity", "amount"], "cancellable": True, "desc": "Air changes"},
"entity_break_door": {"fields": ["entity", "block"], "cancellable": True, "desc": "Break door"},
"entity_change_block": {"fields": ["entity", "block", "to"], "cancellable": True, "desc": "Entity changes block"},
"entity_combust": {"fields": ["entity", "duration"], "cancellable": True, "desc": "Entity combust"},
"entity_combust_by_block": {"fields": ["entity", "block", "duration"], "cancellable": True, "desc": "Combust by block"},
"entity_combust_by_entity": {"fields": ["entity", "combuster", "duration"], "cancellable": True, "desc": "Combust by entity"},
"entity_damage": {"fields": ["entity", "damage", "cause"], "cancellable": True, "desc": "Entity damaged"},
"entity_damage_by_block": {"fields": ["entity", "damager", "damage", "cause"], "cancellable": True, "desc": "Damage by block"},
"entity_damage_by_entity": {"fields": ["entity", "damager", "damage", "cause"], "cancellable": True, "desc": "Damage by entity"},
"entity_death": {"fields": ["entity", "drops"], "cancellable": False, "desc": "Entity death"},
"entity_dismount": {"fields": ["entity", "dismounted"], "cancellable": True, "desc": "Entity dismount"},
"entity_enter_block": {"fields": ["entity", "block"], "cancellable": False, "desc": "Entity enters block"},
"entity_explode": {"fields": ["entity", "location", "blocks"], "cancellable": True, "desc": "Entity explode"},
"entity_mount": {"fields": ["entity", "mount"], "cancellable": True, "desc": "Entity mount"},
"entity_pickup_item": {"fields": ["entity", "item"], "cancellable": True, "desc": "Entity pickup item"},
"entity_portal": {"fields": ["entity", "from", "to"], "cancellable": True, "desc": "Entity portal"},
"entity_portal_enter": {"fields": ["entity", "location"], "cancellable": False, "desc": "Portal enter"},
"entity_portal_exit": {"fields": ["entity", "from", "to"], "cancellable": True, "desc": "Portal exit"},
"entity_regain_health": {"fields": ["entity", "amount", "reason"], "cancellable": True, "desc": "Regain health"},
"entity_resurrect": {"fields": ["entity"], "cancellable": True, "desc": "Totem resurrection"},
"entity_shoot_bow": {"fields": ["entity", "bow", "projectile", "force"], "cancellable": True, "desc": "Shoot bow"},
"entity_spawn": {"fields": ["entity", "location"], "cancellable": True, "desc": "Entity spawn"},
"entity_target": {"fields": ["entity", "target", "reason"], "cancellable": True, "desc": "Entity target"},
"entity_target_living_entity": {"fields": ["entity", "target", "reason"], "cancellable": True, "desc": "Target living entity"},
"entity_teleport": {"fields": ["entity", "from", "to"], "cancellable": True, "desc": "Entity teleport"},
"entity_tame": {"fields": ["entity", "owner"], "cancellable": True, "desc": "Entity tamed"},
"projectile_hit": {"fields": ["entity", "hit_entity", "hit_block"], "cancellable": True, "desc": "Projectile hit"},
"projectile_launch": {"fields": ["entity"], "cancellable": True, "desc": "Projectile launch"},
# =========================================================
# INVENTORY EVENTS
# =========================================================
"inventory_click": {"fields": ["who", "inventory", "slot", "action", "click"], "cancellable": True, "desc": "Inventory click"},
"inventory_close": {"fields": ["player", "inventory"], "cancellable": False, "desc": "Inventory close"},
"inventory_creative": {"fields": ["who", "inventory", "slot", "item"], "cancellable": True, "desc": "Creative click"},
"inventory_drag": {"fields": ["who", "inventory", "new_items"], "cancellable": True, "desc": "Inventory drag"},
"inventory_move_item": {"fields": ["source", "destination", "item"], "cancellable": True, "desc": "Move item"},
"inventory_open": {"fields": ["player", "inventory"], "cancellable": True, "desc": "Inventory open"},
"prepare_anvil": {"fields": ["inventory", "result"], "cancellable": False, "desc": "Prepare anvil"},
"prepare_grindstone": {"fields": ["inventory", "result"], "cancellable": False, "desc": "Prepare grindstone"},
"prepare_item_craft": {"fields": ["inventory", "recipe"], "cancellable": False, "desc": "Prepare craft"},
"prepare_result": {"fields": ["inventory", "result"], "cancellable": False, "desc": "Generic prepare result"},
"brew_event": {"fields": ["inventory"], "cancellable": True, "desc": "Brewing complete"},
"brewing_stand_fuel": {"fields": ["block", "fuel", "power"], "cancellable": True, "desc": "Brewing fuel"},
# =========================================================
# WORLD EVENTS
# =========================================================
"chunk_generate": {"fields": ["world", "chunk"], "cancellable": False, "desc": "Chunk generated"},
"chunk_load": {"fields": ["world", "chunk"], "cancellable": False, "desc": "Chunk load"},
"chunk_unload": {"fields": ["world", "chunk"], "cancellable": True, "desc": "Chunk unload"},
"loot_generate": {"fields": ["entity", "inventory", "loot_table"], "cancellable": False, "desc": "Loot generate"},
"portal_create": {"fields": ["blocks", "world", "reason"], "cancellable": True, "desc": "Portal create"},
"spawn_change": {"fields": ["world", "previous_location"], "cancellable": False, "desc": "Spawn change"},
"structure_grow": {"fields": ["location", "species", "blocks"], "cancellable": True, "desc": "Tree grow"},
"world_init": {"fields": ["world"], "cancellable": False, "desc": "World init"},
"world_load": {"fields": ["world"], "cancellable": False, "desc": "World load"},
"world_save": {"fields": ["world"], "cancellable": False, "desc": "World save"},
"world_unload": {"fields": ["world"], "cancellable": True, "desc": "World unload"},
# =========================================================
# WEATHER EVENTS
# =========================================================
"thunder_change": {"fields": ["world", "to"], "cancellable": True, "desc": "Thunder change"},
"weather_change": {"fields": ["world", "to"], "cancellable": True, "desc": "Weather change"},
"lightning_strike": {"fields": ["world", "lightning"], "cancellable": True, "desc": "Lightning strike"},
# =========================================================
# VEHICLE EVENTS
# =========================================================
"vehicle_create": {"fields": ["vehicle"], "cancellable": False, "desc": "Vehicle create"},
"vehicle_damage": {"fields": ["vehicle", "attacker", "damage"], "cancellable": True, "desc": "Vehicle damage"},
"vehicle_destroy": {"fields": ["vehicle", "attacker"], "cancellable": True, "desc": "Vehicle destroy"},
"vehicle_enter": {"fields": ["vehicle", "entity"], "cancellable": True, "desc": "Vehicle enter"},
"vehicle_exit": {"fields": ["vehicle", "entity"], "cancellable": True, "desc": "Vehicle exit"},
"vehicle_move": {"fields": ["vehicle", "from", "to"], "cancellable": False, "desc": "Vehicle move"},
"vehicle_update": {"fields": ["vehicle"], "cancellable": False, "desc": "Vehicle update"},
# =========================================================
# HANGING EVENTS
# =========================================================
"hanging_break": {"fields": ["entity", "cause"], "cancellable": True, "desc": "Hanging break"},
"hanging_break_by_entity": {"fields": ["entity", "remover"], "cancellable": True, "desc": "Break by entity"},
"hanging_place": {"fields": ["entity", "player", "block"], "cancellable": True, "desc": "Hanging place"},
# =========================================================
# ENCHANTMENT EVENTS
# =========================================================
"enchant_item": {"fields": ["player", "item", "enchants"], "cancellable": True, "desc": "Enchant item"},
"prepare_item_enchant": {"fields": ["player", "item", "offers"], "cancellable": True, "desc": "Prepare enchant"},
# =========================================================
# SERVER EVENTS
# =========================================================
"map_initialize": {"fields": ["map_view"], "cancellable": False, "desc": "Map initialize"},
"plugin_enable": {"fields": ["plugin"], "cancellable": False, "desc": "Plugin enable"},
"plugin_disable": {"fields": ["plugin"], "cancellable": False, "desc": "Plugin disable"},
"server_command": {"fields": ["sender", "command"], "cancellable": True, "desc": "Server command"},
"server_load": {"fields": ["type"], "cancellable": False, "desc": "Server load"},
"service_register": {"fields": ["provider"], "cancellable": False, "desc": "Service register"},
"service_unregister": {"fields": ["provider"], "cancellable": False, "desc": "Service unregister"},
}
def find_docs_dir():
for candidate in DOCS_CANDIDATES:
if candidate.is_dir():
return candidate
return None
def build_symbol_index(docs_dir):
"""Build an index of symbols from doc headings.
Each symbol has:
- class_name: The top-level # heading (e.g. "Player")
- name: The ### heading (e.g. "name", "teleport")
- section: The ## heading (e.g. "Attributes", "Methods")
- qualified: "Class.member" or just "Class"
- desc: First non-empty line after the heading
- file, line
"""
symbols = []
for md_file in sorted(docs_dir.glob("*.md")):
content = md_file.read_text(encoding="utf-8")
lines = content.split("\n")
class_name = md_file.stem.capitalize()
section = ""
subtitle = ""
in_code_block = False
# Extract subtitle from frontmatter
in_frontmatter = False
for line in lines:
if line.strip() == "---":
in_frontmatter = not in_frontmatter
continue
if in_frontmatter and line.startswith("subtitle:"):
subtitle = line.split(":", 1)[1].strip()
for i, line in enumerate(lines):
stripped = line.strip()
# Track fenced code blocks
if stripped.startswith("```"):
in_code_block = not in_code_block
continue
if in_code_block:
continue
if stripped.startswith("# ") and not stripped.startswith("## "):
class_name = stripped.lstrip("# ").replace("[ext]", "").strip()
desc = _get_desc_after(lines, i)
symbols.append({
"class_name": class_name,
"name": None,
"section": None,
"qualified": class_name,
"desc": subtitle or desc,
"file": md_file.stem,
"line": i + 1,
})
elif stripped.startswith("## ") and not stripped.startswith("### "):
section = stripped.lstrip("# ").strip()
elif stripped.startswith("### "):
member = stripped.lstrip("# ").strip()
# Only index code-like symbols (no spaces = identifier)
if " " in member:
continue
desc = _get_desc_after(lines, i)
sig = _get_signature(lines, i, member)
symbols.append({
"class_name": class_name,
"name": member,
"section": section,
"qualified": f"{class_name}.{member}",
"desc": desc,
"sig": sig,
"file": md_file.stem,
"line": i + 1,
})
return symbols
def _get_desc_after(lines, heading_idx):
"""Get the first meaningful content line after a heading."""
for j in range(heading_idx + 1, min(heading_idx + 8, len(lines))):
l = lines[j].strip()
if not l or l == "---" or l.startswith("#") or l.startswith("```"):
continue
# Strip markdown formatting
l = re.sub(r'\[([^\]]*)\]\([^)]*\)', r'\1', l) # [text](url) → text
l = re.sub(r'`([^`]*)`', r'\1', l) # `code` → code
l = l.replace('**', '').replace('*', '').replace('_', '')
if l.startswith("- Type:"):
return l.strip()
return l[:100]
return ""
def _get_signature(lines, heading_idx, member):
"""Extract method signature from the code block after a ### heading."""
in_code = False
for j in range(heading_idx + 1, min(heading_idx + 6, len(lines))):
l = lines[j].strip()
if l.startswith("```"):
if not in_code:
in_code = True
continue
else:
break
if in_code and member in l:
# Extract args from the call: member(args)
m = re.search(re.escape(member) + r'\((.*)\)', l)
if m:
return f"({m.group(1)})"
return None
def _strip_md(line):
"""Strip markdown formatting from a line for terminal display."""
line = re.sub(r'\[([^\]]*)\]\([^)]*\)', r'\1', line) # links
line = re.sub(r'`([^`]*)`', r'\1', line) # inline code
line = line.replace('**', '').replace('*', '')
return line
# Extension doc file stems (matches Extensions section in docs/build.py)
_EXT_FILES = {
"imagedisplay", "meshdisplay", "quest", "dialog", "bank", "shop",
"trade", "ability", "mana", "combat", "levels", "region", "party",
"guild", "customitem", "leaderboard", "visualeffect", "playerdatastore",
"dungeon",
}
_EXT_TAG = " \033[33m[ext]\033[0m"
# ANSI color codes
_C_KEYWORD = "\033[35m" # magenta
_C_BUILTIN = "\033[33m" # yellow
_C_STRING = "\033[32m" # green
_C_COMMENT = "\033[90m" # gray
_C_NUMBER = "\033[34m" # blue
_C_FUNC = "\033[36m" # cyan
_C_RESET = "\033[0m"
_PY_KEYWORDS = {
'False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield',
}
_PY_BUILTINS = {
'print', 'len', 'range', 'int', 'str', 'float', 'bool', 'list',
'dict', 'set', 'tuple', 'type', 'isinstance', 'super', 'property',
'staticmethod', 'classmethod', 'enumerate', 'zip', 'map', 'filter',
}
def _highlight_python(line):
"""Apply basic Python syntax highlighting with ANSI colors."""
result = []
i = 0
n = len(line)
while i < n:
# Comments
if line[i] == '#':
result.append(f"{_C_COMMENT}{line[i:]}{_C_RESET}")
break
# Strings (single/double, triple-quoted handled simply)
if line[i] in ('"', "'"):
quote = line[i]
# Check for triple quote
if line[i:i+3] in ('"""', "'''"):
end = line.find(quote * 3, i + 3)
if end == -1:
end = n
else:
end += 3
else:
end = i + 1
while end < n and line[end] != quote:
if line[end] == '\\':
end += 1
end += 1
end = min(end + 1, n)
result.append(f"{_C_STRING}{line[i:end]}{_C_RESET}")
i = end
continue
# Numbers
if line[i].isdigit() or (line[i] == '.' and i + 1 < n and line[i+1].isdigit()):
j = i
while j < n and (line[j].isdigit() or line[j] in '.eE_xXabcdefABCDEF'):
j += 1
result.append(f"{_C_NUMBER}{line[i:j]}{_C_RESET}")
i = j
continue
# Identifiers / keywords
if line[i].isalpha() or line[i] == '_':
j = i
while j < n and (line[j].isalnum() or line[j] == '_'):
j += 1
word = line[i:j]
if word in _PY_KEYWORDS:
result.append(f"{_C_KEYWORD}{word}{_C_RESET}")
elif word in _PY_BUILTINS:
result.append(f"{_C_BUILTIN}{word}{_C_RESET}")
elif j < n and line[j] == '(':
result.append(f"{_C_FUNC}{word}{_C_RESET}")
else:
result.append(word)
i = j
continue
# Decorators
if line[i] == '@':
j = i + 1
while j < n and (line[j].isalnum() or line[j] in '_.'):
j += 1
result.append(f"{_C_FUNC}{line[i:j]}{_C_RESET}")
i = j
continue
result.append(line[i])
i += 1
return "".join(result)
def _get_class_doc(md_path, ext_tag=""):
"""Extract class-level documentation (before first ### member heading)."""
content = md_path.read_text(encoding="utf-8")
lines = content.split("\n")
out = []
in_frontmatter = False
past_frontmatter = False
in_code_block = False
for line in lines:
stripped = line.strip()
# Skip frontmatter
if stripped == "---":
if not past_frontmatter:
in_frontmatter = not in_frontmatter
if not in_frontmatter:
past_frontmatter = True
continue
elif not in_code_block:
continue # skip --- separators
if in_frontmatter:
continue
# Stop at first ### heading (member definitions)
if stripped.startswith("### ") and not in_code_block:
# Drop trailing section headers and blank lines
while out and not out[-1].strip():
out.pop()
if out and out[-1].strip().startswith("\033[1m"):
out.pop()
break
# Track code blocks
if stripped.startswith("```"):
in_code_block = not in_code_block
continue # hide ``` markers
if in_code_block:
out.append(f" {_highlight_python(line.rstrip())}")
elif stripped.startswith("# "):
title = stripped.lstrip('# ').replace('[ext]', '').strip()
out.append(f" \033[36;1m# {title}\033[0m{ext_tag}")
elif stripped.startswith("## "):
heading = stripped.lstrip('# ').strip()
if heading == "Constructor":
continue # skip Constructor header
out.append(f" \033[1m## {heading}\033[0m")
elif stripped.startswith("- "):
out.append(f" {_strip_md(line.rstrip())}")
elif stripped:
out.append(f" {_strip_md(line.rstrip())}")
else:
out.append("")
# Trim trailing blank lines
while out and not out[-1].strip():
out.pop()
# Collapse consecutive blank lines
collapsed = []
for line in out:
if not line.strip() and collapsed and not collapsed[-1].strip():
continue
collapsed.append(line)
return "\n".join(collapsed)
def _get_member_doc(md_path, heading_line):
"""Extract the full documentation block for a ### member heading.
`heading_line` is 1-based line number where the ### heading appears.
Returns formatted text similar to `_get_class_doc`.
"""
content = md_path.read_text(encoding="utf-8")
lines = content.split("\n")
out = []
in_code_block = False
start = max(0, heading_line - 1)
for j in range(start, len(lines)):
line = lines[j]
stripped = line.strip()
# Track fenced code blocks
if stripped.startswith("```"):
in_code_block = not in_code_block
continue
# Stop at the next member or section (if not inside a code block)
if not in_code_block and j > start and (stripped.startswith("### ") or stripped.startswith("## ")):
break
if in_code_block:
out.append(f" {_highlight_python(line.rstrip())}")
elif stripped.startswith("### "):
# Skip the first heading line since the caller already prints it
if j == start:
continue
out.append(f" \033[36;1m{stripped.lstrip('# ')}\033[0m")
elif stripped.startswith("- "):
out.append(f" {_strip_md(line.rstrip())}")
elif stripped:
out.append(f" {_strip_md(line.rstrip())}")
else:
out.append("")
# Trim trailing blank lines
while out and not out[-1].strip():
out.pop()
# Collapse consecutive blank lines
collapsed = []
for line in out:
if not line.strip() and collapsed and not collapsed[-1].strip():
continue
collapsed.append(line)
return "\n".join(collapsed)
def cmd_search(query):
docs_dir = find_docs_dir()
if docs_dir is None:
print("Error: Could not find docs/src directory.")
print("Run this from the PyJavaBridge project root.")
sys.exit(1)
symbols = build_symbol_index(docs_dir)
if query.endswith("."):
# "Player." → list all members of that class
class_q = query[:-1].lower()
members = [s for s in symbols if s["class_name"].lower() == class_q and s["name"]]
if not members:
print(f"No class '{query[:-1]}' found")
return
ext = _EXT_TAG if members[0]['file'] in _EXT_FILES else ""
print(f"\033[1m{members[0]['class_name']}\033[0m \033[90m({members[0]['file']}.md)\033[0m{ext}")
current_section = None
for s in members:
section = s['section'] or ''
if section != current_section:
current_section = section
if section:
print(f" \033[90m## {section}\033[0m")
sig = s.get('sig', '') or ''
print(f" \033[90m###\033[0m \033[36m.{s['name']}{sig}\033[0m")
elif "." in query:
# "Player.name" → find specific member(s)
class_q, member_q = query.split(".", 1)
class_q, member_q = class_q.lower(), member_q.lower()
results = []
for s in symbols:
if not s["name"]:
continue
if s["class_name"].lower() == class_q and member_q in s["name"].lower():
exact = s["name"].lower() == member_q
results.append((0 if exact else 1, s))
results.sort(key=lambda x: (x[0], x[1]["qualified"]))
if not results:
print(f"No symbol '{query}' found")
return
for _, s in results:
# If the user asked for the exact member, show the full member block
if s['name'].lower() == member_q:
ext = _EXT_TAG if s['file'] in _EXT_FILES else ""
print(f" \033[90m{s['class_name']}.\033[0m\033[36m{s['name']}\033[0m \033[90m({s['section'] or 'class'})\033[0m{ext}")
md_path = docs_dir / f"{s['file']}.md"
if md_path.exists():
print(_get_member_doc(md_path, s['line']))
else:
desc = f" \033[90m{s['desc']}\033[0m" if s['desc'] else ""
print(desc)
else:
desc = f" \033[90m{s['desc']}\033[0m" if s['desc'] else ""
ext = _EXT_TAG if s['file'] in _EXT_FILES else ""
print(f" \033[90m{s['class_name']}.\033[0m\033[36m{s['name']}\033[0m \033[90m({s['section'] or 'class'})\033[0m{ext}{desc}")
else:
# "Player" → match class names, or fall back to member names
q = query.lower()
classes = [s for s in symbols if not s["name"] and q in s["class_name"].lower()]
classes.sort(key=lambda s: (s["class_name"].lower() != q, s["class_name"]))
if classes:
for s in classes:
ext = _EXT_TAG if s['file'] in _EXT_FILES else ""
# Show the class-level doc text (everything before first ### member)
md_path = docs_dir / f"{s['file']}.md"
if md_path.exists():
print(_get_class_doc(md_path, ext))
else:
print(f" \033[36;1m{s['class_name']}\033[0m{ext}")
else:
# No class match → search member names across all classes
results = []
for s in symbols:
if not s["name"]:
continue
if q == s["name"].lower():
results.append((0, s))
elif s["name"].lower().startswith(q):
results.append((1, s))
elif q in s["name"].lower():
results.append((2, s))
results.sort(key=lambda x: (x[0], x[1]["qualified"]))
if not results:
print(f"No symbols matching '{query}'")
return
for _, s in results:
ext = _EXT_TAG if s['file'] in _EXT_FILES else ""
print(f" \033[90m{s['class_name']}.\033[0m\033[36m{s['name']}\033[0m \033[90m({s['section'] or 'class'})\033[0m{ext}")
def cmd_events(filter_str=None):
filter_lower = filter_str.lower() if filter_str else None
matching = {}
for name, info in sorted(EVENTS.items()):
if filter_lower:
if filter_lower not in name and filter_lower not in info["desc"].lower():
if not any(filter_lower in f for f in info["fields"]):
continue
matching[name] = info
if not matching:
print(f"No events matching '{filter_str}'")
return
print(f"\033[1m{len(matching)} event(s){' (filter: ' + filter_str + ')' if filter_str else ''}:\033[0m\n")
for name, info in matching.items():
cancel = "\033[32m✓\033[0m" if info["cancellable"] else "\033[90m✗\033[0m"
fields = ", ".join(info["fields"]) if info["fields"] else "(none)"
print(f" {cancel} \033[36m{name}\033[0m")
print(f" {info['desc']}")
print(f" \033[90mfields: {fields}\033[0m")
def main():
if len(sys.argv) < 2:
print(__doc__)
sys.exit(1)
cmd = sys.argv[1].lower()
if cmd == "search":
if len(sys.argv) < 3:
print("Usage: pjb search <query>")
sys.exit(1)
cmd_search(" ".join(sys.argv[2:]))
elif cmd == "events":
filter_str = " ".join(sys.argv[2:]) if len(sys.argv) > 2 else None
cmd_events(filter_str)
else:
print(f"Unknown command: {cmd}")
print(__doc__)
sys.exit(1)
if __name__ == "__main__":
main()