-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKavin python ide.py
More file actions
1664 lines (1493 loc) · 77 KB
/
Copy pathKavin python ide.py
File metadata and controls
1664 lines (1493 loc) · 77 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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Kavin IDE — VS Code–style Python IDE
Run: python kavin_ide_final.py
Needs: Python 3.8+ (tkinter ships with Python on Windows/macOS)
Linux: sudo apt install python3-tk
"""
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, simpledialog
import subprocess, threading, os, sys, re, tempfile, time
from pathlib import Path
# ╔══════════════════════════════════════════════════════════╗
# VS CODE EXACT COLORS
# ╚══════════════════════════════════════════════════════════╝
VS = {
# backgrounds
"titlebar": "#3c3c3c",
"menubar": "#3c3c3c",
"activity": "#333333",
"sidebar": "#252526",
"sidebar_hdr": "#252526",
"editor": "#1e1e1e",
"editor_gutter": "#1e1e1e",
"tab_bar": "#2d2d2d",
"tab_active": "#1e1e1e",
"tab_inactive": "#2d2d2d",
"panel": "#1e1e1e",
"panel_hdr": "#252526",
"statusbar": "#007acc",
"input": "#3c3c3c",
"dropdown": "#252526",
"dropdown_sel": "#094771",
"hover": "#2a2d2e",
"selection": "#264f78",
"line_hl": "#2a2a2a",
"border": "#474747",
"sash": "#474747",
"scrollbar": "#424242",
# text
"fg": "#cccccc",
"fg_dim": "#858585",
"fg_muted": "#5a5a5a",
"fg_tab_on": "#ffffff",
"fg_tab_off": "#8d8d8d",
"fg_statusbar": "#ffffff",
"fg_line": "#5a5a5a",
"fg_line_cur": "#c6c6c6",
"fg_sidebar": "#cccccc",
"fg_sidebar_hdr":"#bbbbbb",
# syntax — VS Code Dark+ exact
"kw": "#569cd6", # blue — if for while
"kw2": "#c586c0", # pink — class def import
"bi": "#dcdcaa", # yellow — builtins
"str_": "#ce9178", # orange — strings
"doc": "#6a9955", # green — docstrings / comments
"cmt": "#6a9955",
"num": "#b5cea8", # light green — numbers
"dec": "#dcdcaa", # yellow — decorators
"cls_n": "#4ec9b0", # teal — class names
"fn_n": "#dcdcaa", # yellow — function names
"slf": "#9cdcfe", # light blue — self / cls
"op": "#d4d4d4", # white — operators
"param": "#9cdcfe", # light blue — params
# autocomplete popup
"ac_bg": "#252526",
"ac_sel": "#094771",
"ac_border": "#454545",
"ac_detail": "#1e1e1e",
"ac_fg": "#d4d4d4",
"ac_dim": "#858585",
# kind icon colors
"ic_kw": "#569cd6",
"ic_fn": "#dcdcaa",
"ic_cls": "#4ec9b0",
"ic_snip": "#c586c0",
"ic_mod": "#9cdcfe",
"ic_const": "#4fc1ff",
"ic_var": "#9cdcfe",
# run button
"run_bg": "#388a34",
"run_fg": "#ffffff",
# error
"err_line": "#4b1818",
"err_fg": "#f48771",
}
# ╔══════════════════════════════════════════════════════════╗
# AUTOCOMPLETE DATABASE (triggers on every letter typed)
# ╚══════════════════════════════════════════════════════════╝
# Format: (label, kind, detail_signature)
_KW = "kw"; _BI = "bi"; _CLS = "cls"; _SNIP = "snip"
_MOD = "mod"; _CONST = "const"
COMPLETIONS = [
# ── Python keywords ──────────────────────────────────────
("False", _KW, "bool False"),
("None", _KW, "None"),
("True", _KW, "bool True"),
("and", _KW, "and (logical and)"),
("as", _KW, "as alias"),
("assert", _KW, "assert expression [, message]"),
("async", _KW, "async def / async for / async with"),
("await", _KW, "await coroutine"),
("break", _KW, "break (exit loop)"),
("class", _KW, "class Name(Base):"),
("continue", _KW, "continue (next iteration)"),
("def", _KW, "def function_name(params):"),
("del", _KW, "del object"),
("elif", _KW, "elif condition:"),
("else", _KW, "else:"),
("except", _KW, "except ExceptionType as e:"),
("finally", _KW, "finally:"),
("for", _KW, "for item in iterable:"),
("from", _KW, "from module import name"),
("global", _KW, "global variable"),
("if", _KW, "if condition:"),
("import", _KW, "import module"),
("in", _KW, "in (membership test)"),
("is", _KW, "is (identity test)"),
("lambda", _KW, "lambda params: expression"),
("nonlocal", _KW, "nonlocal variable"),
("not", _KW, "not expression"),
("or", _KW, "or (logical or)"),
("pass", _KW, "pass (no-op)"),
("raise", _KW, "raise ExceptionType(message)"),
("return", _KW, "return value"),
("try", _KW, "try:"),
("while", _KW, "while condition:"),
("with", _KW, "with expression as alias:"),
("yield", _KW, "yield value"),
# ── Built-in functions ───────────────────────────────────
("print", _BI, "print(*objects, sep=' ', end='\\n', file=None, flush=False)"),
("len", _BI, "len(s) -> int Return the length of s"),
("range", _BI, "range(stop) | range(start, stop[, step])"),
("type", _BI, "type(object) -> type"),
("int", _BI, "int(x=0, base=10) -> int"),
("str", _BI, "str(object='') -> str"),
("float", _BI, "float(x=0.0) -> float"),
("bool", _BI, "bool(x=False) -> bool"),
("list", _BI, "list(iterable=()) -> list"),
("dict", _BI, "dict(**kwargs) -> dict"),
("tuple", _BI, "tuple(iterable=()) -> tuple"),
("set", _BI, "set(iterable=set()) -> set"),
("frozenset", _BI, "frozenset(iterable=()) -> frozenset"),
("bytes", _BI, "bytes(source, encoding, errors) -> bytes"),
("bytearray", _BI, "bytearray(source, encoding, errors) -> bytearray"),
("input", _BI, "input(prompt='') -> str"),
("open", _BI, "open(file, mode='r', buffering=-1, encoding=None, ...) -> IO"),
("print", _BI, "print(*objects, sep=' ', end='\\n')"),
("enumerate", _BI, "enumerate(iterable, start=0) -> iterator of (index, value)"),
("zip", _BI, "zip(*iterables) -> iterator of tuples"),
("map", _BI, "map(function, iterable, ...) -> iterator"),
("filter", _BI, "filter(function, iterable) -> iterator"),
("sorted", _BI, "sorted(iterable, *, key=None, reverse=False) -> list"),
("reversed", _BI, "reversed(sequence) -> iterator"),
("sum", _BI, "sum(iterable, /, start=0) -> number"),
("min", _BI, "min(iterable, *, key=None, default=...) -> value"),
("max", _BI, "max(iterable, *, key=None, default=...) -> value"),
("abs", _BI, "abs(x) -> number Return absolute value"),
("round", _BI, "round(number, ndigits=None) -> number"),
("pow", _BI, "pow(base, exp, mod=None) -> number"),
("divmod", _BI, "divmod(a, b) -> (quotient, remainder)"),
("repr", _BI, "repr(object) -> str"),
("hash", _BI, "hash(object) -> int"),
("id", _BI, "id(object) -> int Return memory address"),
("hex", _BI, "hex(x) -> str Convert int to hex string"),
("oct", _BI, "oct(x) -> str Convert int to octal string"),
("bin", _BI, "bin(x) -> str Convert int to binary string"),
("chr", _BI, "chr(i) -> str Return Unicode character"),
("ord", _BI, "ord(c) -> int Return Unicode code point"),
("format", _BI, "format(value, format_spec='') -> str"),
("super", _BI, "super() -> proxy for parent class"),
("object", _BI, "object() Base class of all classes"),
("isinstance", _BI, "isinstance(object, classinfo) -> bool"),
("issubclass", _BI, "issubclass(class, classinfo) -> bool"),
("hasattr", _BI, "hasattr(object, name) -> bool"),
("getattr", _BI, "getattr(object, name[, default]) -> value"),
("setattr", _BI, "setattr(object, name, value)"),
("delattr", _BI, "delattr(object, name)"),
("callable", _BI, "callable(object) -> bool"),
("dir", _BI, "dir(object) -> list of names"),
("vars", _BI, "vars([object]) -> dict"),
("globals", _BI, "globals() -> dict Global symbol table"),
("locals", _BI, "locals() -> dict Local symbol table"),
("any", _BI, "any(iterable) -> bool"),
("all", _BI, "all(iterable) -> bool"),
("next", _BI, "next(iterator[, default]) -> value"),
("iter", _BI, "iter(object[, sentinel]) -> iterator"),
("exec", _BI, "exec(source, globals=None, locals=None)"),
("eval", _BI, "eval(expression, globals=None, locals=None) -> value"),
("compile", _BI, "compile(source, filename, mode) -> code"),
("__import__", _BI, "__import__(name, ...) -> module"),
("staticmethod",_BI, "@staticmethod — decorator"),
("classmethod", _BI, "@classmethod — decorator"),
("property", _BI, "@property — decorator"),
("slice", _BI, "slice(stop) | slice(start, stop[, step])"),
("complex", _BI, "complex(real=0, imag=0) -> complex"),
("memoryview", _BI, "memoryview(object) -> memoryview"),
("NotImplemented",_CONST,"NotImplemented — singleton"),
("Ellipsis", _CONST,"... — Ellipsis singleton"),
# ── Built-in Exceptions ──────────────────────────────────
("Exception", _CLS, "Exception(*args) Base exception"),
("BaseException", _CLS, "BaseException(*args)"),
("ArithmeticError", _CLS, "ArithmeticError(*args)"),
("ValueError", _CLS, "ValueError(*args) Inappropriate value"),
("TypeError", _CLS, "TypeError(*args) Wrong type"),
("KeyError", _CLS, "KeyError(key) Dict key not found"),
("IndexError", _CLS, "IndexError(*args) Index out of range"),
("AttributeError", _CLS, "AttributeError(*args)"),
("NameError", _CLS, "NameError(*args) Name not defined"),
("ImportError", _CLS, "ImportError(*args)"),
("ModuleNotFoundError", _CLS, "ModuleNotFoundError(*args)"),
("FileNotFoundError", _CLS, "FileNotFoundError(*args)"),
("FileExistsError", _CLS, "FileExistsError(*args)"),
("PermissionError", _CLS, "PermissionError(*args)"),
("IsADirectoryError", _CLS, "IsADirectoryError(*args)"),
("RuntimeError", _CLS, "RuntimeError(*args)"),
("StopIteration", _CLS, "StopIteration(*args)"),
("StopAsyncIteration", _CLS, "StopAsyncIteration(*args)"),
("GeneratorExit", _CLS, "GeneratorExit(*args)"),
("SystemExit", _CLS, "SystemExit(code)"),
("KeyboardInterrupt", _CLS, "KeyboardInterrupt(*args)"),
("NotImplementedError", _CLS, "NotImplementedError(*args)"),
("OverflowError", _CLS, "OverflowError(*args)"),
("ZeroDivisionError", _CLS, "ZeroDivisionError(*args)"),
("MemoryError", _CLS, "MemoryError(*args)"),
("RecursionError", _CLS, "RecursionError(*args)"),
("BufferError", _CLS, "BufferError(*args)"),
("EOFError", _CLS, "EOFError(*args)"),
("OSError", _CLS, "OSError(*args)"),
("ConnectionError", _CLS, "ConnectionError(*args)"),
("TimeoutError", _CLS, "TimeoutError(*args)"),
("UnicodeError", _CLS, "UnicodeError(*args)"),
("UnicodeDecodeError", _CLS, "UnicodeDecodeError(*args)"),
("UnicodeEncodeError", _CLS, "UnicodeEncodeError(*args)"),
("AssertionError", _CLS, "AssertionError(*args)"),
("LookupError", _CLS, "LookupError(*args)"),
("SyntaxError", _CLS, "SyntaxError(*args)"),
("IndentationError", _CLS, "IndentationError(*args)"),
("TabError", _CLS, "TabError(*args)"),
("SystemError", _CLS, "SystemError(*args)"),
("ReferenceError", _CLS, "ReferenceError(*args)"),
("Warning", _CLS, "Warning(*args)"),
("DeprecationWarning", _CLS, "DeprecationWarning(*args)"),
("UserWarning", _CLS, "UserWarning(*args)"),
# ── Snippets ─────────────────────────────────────────────
("__init__", _SNIP, "def __init__(self, ...):"),
("__str__", _SNIP, "def __str__(self) -> str:"),
("__repr__", _SNIP, "def __repr__(self) -> str:"),
("__len__", _SNIP, "def __len__(self) -> int:"),
("__iter__", _SNIP, "def __iter__(self):"),
("__next__", _SNIP, "def __next__(self):"),
("__enter__", _SNIP, "def __enter__(self):"),
("__exit__", _SNIP, "def __exit__(self, exc_type, exc_val, tb):"),
("__getitem__", _SNIP, "def __getitem__(self, key):"),
("__setitem__", _SNIP, "def __setitem__(self, key, value):"),
("__delitem__", _SNIP, "def __delitem__(self, key):"),
("__contains__", _SNIP, "def __contains__(self, item) -> bool:"),
("__call__", _SNIP, "def __call__(self, *args, **kwargs):"),
("__main__", _SNIP, 'if __name__ == "__main__":'),
# ── Constants ─────────────────────────────────────────────
("__name__", _CONST, "__name__ str current module name"),
("__file__", _CONST, "__file__ str path to current file"),
("__doc__", _CONST, "__doc__ str module docstring"),
("__all__", _CONST, "__all__ list public API names"),
("__version__", _CONST, "__version__ str package version"),
("__author__", _CONST, "__author__ str author name"),
("__package__", _CONST, "__package__ str package name"),
("__spec__", _CONST, "__spec__ ModuleSpec"),
# ── Standard library modules ──────────────────────────────
("os", _MOD, "import os — Miscellaneous OS interfaces"),
("os.path", _MOD, "import os.path — Common pathname manipulations"),
("sys", _MOD, "import sys — System-specific parameters"),
("re", _MOD, "import re — Regular expression operations"),
("json", _MOD, "import json — JSON encoder and decoder"),
("math", _MOD, "import math — Mathematical functions"),
("random", _MOD, "import random — Generate random numbers"),
("datetime", _MOD, "import datetime — Date and time types"),
("time", _MOD, "import time — Time access and conversions"),
("pathlib", _MOD, "import pathlib — Object-oriented filesystem paths"),
("collections", _MOD, "import collections — Container datatypes"),
("itertools", _MOD, "import itertools — Functional tools for iterators"),
("functools", _MOD, "import functools — Higher-order functions"),
("operator", _MOD, "import operator — Standard operators as functions"),
("typing", _MOD, "import typing — Support for type hints"),
("dataclasses", _MOD, "import dataclasses — Data Classes"),
("abc", _MOD, "import abc — Abstract Base Classes"),
("contextlib", _MOD, "import contextlib — Utilities for with-statement contexts"),
("io", _MOD, "import io — Core tools for working with streams"),
("copy", _MOD, "import copy — Shallow and deep copy"),
("pprint", _MOD, "import pprint — Data pretty printer"),
("string", _MOD, "import string — Common string operations"),
("textwrap", _MOD, "import textwrap — Text wrapping and filling"),
("struct", _MOD, "import struct — Interpret bytes as packed binary data"),
("enum", _MOD, "import enum — Support for enumerations"),
("threading", _MOD, "import threading — Thread-based parallelism"),
("multiprocessing",_MOD,"import multiprocessing — Process-based parallelism"),
("subprocess", _MOD, "import subprocess — Subprocess management"),
("socket", _MOD, "import socket — Low-level networking interface"),
("ssl", _MOD, "import ssl — TLS/SSL wrapper for socket objects"),
("http", _MOD, "import http — HTTP modules"),
("urllib", _MOD, "import urllib — URL handling modules"),
("email", _MOD, "import email — Email and MIME handling package"),
("html", _MOD, "import html — HyperText Markup Language support"),
("xml", _MOD, "import xml — XML processing modules"),
("sqlite3", _MOD, "import sqlite3 — DB-API 2.0 interface for SQLite"),
("csv", _MOD, "import csv — CSV File Reading and Writing"),
("configparser", _MOD, "import configparser — Configuration file parser"),
("argparse", _MOD, "import argparse — Parser for command-line options"),
("logging", _MOD, "import logging — Logging facility for Python"),
("unittest", _MOD, "import unittest — Unit testing framework"),
("doctest", _MOD, "import doctest — Test interactive Python examples"),
("timeit", _MOD, "import timeit — Measure execution time of small code"),
("profile", _MOD, "import profile — Python profiler"),
("hashlib", _MOD, "import hashlib — Secure hashes and message digests"),
("hmac", _MOD, "import hmac — Keyed-Hashing for Message Authentication"),
("secrets", _MOD, "import secrets — Generate secure random numbers"),
("base64", _MOD, "import base64 — Base16, Base32, Base64 encodings"),
("pickle", _MOD, "import pickle — Python object serialization"),
("shelve", _MOD, "import shelve — Python object persistence"),
("shutil", _MOD, "import shutil — High-level file operations"),
("glob", _MOD, "import glob — Unix style pathname pattern expansion"),
("fnmatch", _MOD, "import fnmatch — Unix filename pattern matching"),
("tempfile", _MOD, "import tempfile — Generate temporary files and dirs"),
("platform", _MOD, "import platform — Access to underlying platform data"),
("signal", _MOD, "import signal — Set handlers for asynchronous events"),
("gc", _MOD, "import gc — Garbage Collector interface"),
("inspect", _MOD, "import inspect — Inspect live objects"),
("traceback", _MOD, "import traceback — Print or retrieve stack traceback"),
("warnings", _MOD, "import warnings — Warning control"),
("weakref", _MOD, "import weakref — Weak references"),
("queue", _MOD, "import queue — A synchronized queue class"),
("asyncio", _MOD, "import asyncio — Asynchronous I/O"),
("concurrent", _MOD, "import concurrent.futures — Launching parallel tasks"),
("tkinter", _MOD, "import tkinter — Python interface to Tk GUI toolkit"),
# ── Popular third-party ───────────────────────────────────
("numpy", _MOD, "import numpy as np — Numerical computing"),
("pandas", _MOD, "import pandas as pd — Data analysis and manipulation"),
("matplotlib", _MOD, "import matplotlib.pyplot as plt — Plotting"),
("scipy", _MOD, "import scipy — Scientific computing"),
("sklearn", _MOD, "import sklearn — Machine learning"),
("requests", _MOD, "import requests — HTTP for Humans"),
("flask", _MOD, "import flask — Micro web framework"),
("django", _MOD, "import django — Web framework"),
("fastapi", _MOD, "import fastapi — Modern fast web framework"),
("sqlalchemy", _MOD, "import sqlalchemy — Database toolkit"),
("pytest", _MOD, "import pytest — Testing framework"),
("PIL", _MOD, "from PIL import Image — Pillow image processing"),
("cv2", _MOD, "import cv2 — OpenCV computer vision"),
("torch", _MOD, "import torch — PyTorch deep learning"),
("tensorflow", _MOD, "import tensorflow as tf — TensorFlow"),
("pydantic", _MOD, "import pydantic — Data validation"),
("aiohttp", _MOD, "import aiohttp — Async HTTP client/server"),
("boto3", _MOD, "import boto3 — AWS SDK for Python"),
("paramiko", _MOD, "import paramiko — SSH protocol library"),
("cryptography", _MOD, "import cryptography — Cryptographic recipes"),
("rich", _MOD, "import rich — Rich text and formatting in terminal"),
("click", _MOD, "import click — Command line interface creation"),
("celery", _MOD, "import celery — Distributed task queue"),
("redis", _MOD, "import redis — Python client for Redis"),
("pymongo", _MOD, "import pymongo — MongoDB driver"),
]
# ── kind icon + color ──────────────────────────────────────
KIND = {
_KW: ("$(symbol-keyword)", VS["ic_kw"], "keyword"),
_BI: ("$(symbol-function)", VS["ic_fn"], "function"),
_CLS: ("$(symbol-class)", VS["ic_cls"], "class"),
_SNIP: ("$(symbol-snippet)", VS["ic_snip"], "snippet"),
_MOD: ("$(symbol-module)", VS["ic_mod"], "module"),
_CONST: ("$(symbol-constant)", VS["ic_const"],"constant"),
}
KIND_ICON_CHAR = {
_KW: "K", _BI: "F", _CLS: "C", _SNIP: "S", _MOD: "M", _CONST: "V",
}
# ╔══════════════════════════════════════════════════════════╗
# SYNTAX HIGHLIGHTER
# ╚══════════════════════════════════════════════════════════╝
class Highlighter:
RULES = [
("doc", r'("""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\')'),
("str_", r'(f?"(?:[^"\\]|\\.)*"|f?\'(?:[^\'\\]|\\.)*\')'),
("cmt", r'(#[^\n]*)'),
("dec", r'(@[\w.]+)'),
("kw2", r'\b(class|def|lambda|return|yield|import|from|as|with|async|await|raise|pass|del|global|nonlocal)\b'),
("kw", r'\b(False|None|True|and|assert|break|continue|elif|else|except|finally|for|if|in|is|not|or|try|while)\b'),
("cls_n",r'\bclass\s+(\w+)'),
("fn_n", r'\bdef\s+(\w+)'),
("bi", r'\b(print|len|range|int|str|float|list|dict|tuple|set|bool|type|input|open|enumerate|zip|map|filter|sorted|reversed|sum|min|max|abs|round|pow|divmod|repr|hash|id|hex|oct|bin|chr|ord|format|super|object|isinstance|issubclass|hasattr|getattr|setattr|delattr|callable|dir|vars|globals|locals|any|all|next|iter|exec|eval|compile|staticmethod|classmethod|property|slice|complex|bytes|bytearray|frozenset|memoryview)\b'),
("slf", r'\b(self|cls)\b'),
("num", r'\b(0x[0-9a-fA-F]+|0b[01]+|0o[0-7]+|\d+\.?\d*([eE][+-]?\d+)?[jJ]?)\b'),
("op", r'(->|:=|==|!=|<=|>=|\*\*|//|[+\-*/%&|^~<>=!])'),
]
TAG_COLOR = {
"kw": VS["kw"], "kw2": VS["kw2"], "bi": VS["bi"],
"str_": VS["str_"], "doc": VS["doc"], "cmt": VS["cmt"],
"num": VS["num"], "dec": VS["dec"], "cls_n": VS["cls_n"],
"fn_n": VS["fn_n"], "slf": VS["slf"], "op": VS["op"],
}
def __init__(self, w):
self.w = w
for tag, color in self.TAG_COLOR.items():
self.w.tag_configure(tag, foreground=color)
self.w.tag_configure("err_ln", background=VS["err_line"])
self.w.tag_configure("find_hl", background="#623315", foreground="#ffffff")
self.w.tag_configure("cur_line", background=VS["line_hl"])
self._job = None
def schedule(self, *_):
if self._job: self.w.after_cancel(self._job)
self._job = self.w.after(80, self._run)
def _run(self):
c = self.w.get("1.0", "end-1c")
for tag in self.TAG_COLOR:
self.w.tag_remove(tag, "1.0", "end")
for tag, pat in self.RULES:
g = 1 if tag in ("cls_n", "fn_n") else 0
for m in re.finditer(pat, c):
try:
self.w.tag_add(tag, self._p(c, m.start(g)), self._p(c, m.end(g)))
except: pass
def _p(self, c, off):
ln = c[:off].count("\n") + 1
col = off - c[:off].rfind("\n") - 1
return f"{ln}.{col}"
def mark_err(self, ln):
self.w.tag_remove("err_ln", "1.0", "end")
if ln: self.w.tag_add("err_ln", f"{ln}.0", f"{ln}.end+1c")
def clr_err(self): self.w.tag_remove("err_ln", "1.0", "end")
# ╔══════════════════════════════════════════════════════════╗
# LINE NUMBER GUTTER
# ╚══════════════════════════════════════════════════════════╝
class Gutter(tk.Canvas):
W = 58
def __init__(self, parent, tw):
super().__init__(parent, width=self.W,
bg=VS["editor_gutter"], highlightthickness=0)
self.tw = tw
for ev in ("<KeyRelease>","<MouseWheel>","<Button-4>","<Button-5>",
"<<Change>>","<Configure>","<ButtonRelease>"):
tw.bind(ev, self.redraw, add=True)
def redraw(self, *_):
self.delete("all")
cur = self.tw.index("insert").split(".")[0]
i = self.tw.index("@0,0")
while True:
dl = self.tw.dlineinfo(i)
if dl is None: break
ln = int(str(i).split(".")[0])
fg = VS["fg_line_cur"] if str(ln) == cur else VS["fg_line"]
self.create_text(self.W - 10, dl[1] + 2, anchor="ne",
text=str(ln), fill=fg, font=("Consolas", 12))
nx = self.tw.index(f"{i}+1line")
if nx == i: break
i = nx
# ╔══════════════════════════════════════════════════════════╗
# INTELLISENSE POPUP — real VS Code style
# ╚══════════════════════════════════════════════════════════╝
class IntelliSense:
PW = 480 # popup width
RH = 22 # row height
VIS = 12 # visible rows
DH = 68 # detail panel height
def __init__(self, tw, root):
self.tw = tw
self.root = root
self.win = None
self.cvs = None
self.det = None
self.items = [] # list of (label, kind, detail)
self.sel = 0
self._job = None
self.active = False
# bind every printable key release
tw.bind("<KeyRelease>", self._on_key_release)
tw.bind("<Escape>", self.hide)
tw.bind("<FocusOut>", self.hide)
# ── word under cursor ────────────────────────────────
def _cur_word(self):
idx = self.tw.index("insert")
row, col = idx.split(".")
line = self.tw.get(f"{row}.0", idx)
m = re.search(r'[\w.]*$', line)
return m.group().lstrip(".") if m else ""
# ── trigger after every key ──────────────────────────
def _on_key_release(self, event):
sym = event.keysym
# navigation keys that should not retrigger
if sym in ("Escape","Up","Down","Return","Tab",
"Left","Right","Home","End","Prior","Next",
"Shift_L","Shift_R","Control_L","Control_R",
"Alt_L","Alt_R","F1","F2","F3","F4","F5",
"F6","F7","F8","F9","F10","F11","F12"):
return
# hide on backspace/delete if word becomes empty
if sym in ("BackSpace", "Delete"):
if len(self._cur_word()) < 1:
self.hide(); return
# schedule compute
if self._job: self.tw.after_cancel(self._job)
self._job = self.tw.after(60, self._compute)
def _compute(self):
word = self._cur_word()
if not word:
self.hide(); return
wl = word.lower()
# build ranked matches
prefix, substr = [], []
seen = set()
for label, kind, detail in COMPLETIONS:
ll = label.lower()
if ll == wl:
continue # exact match — no popup needed
if ll.startswith(wl) and label not in seen:
prefix.append((label, kind, detail))
seen.add(label)
for label, kind, detail in COMPLETIONS:
if label not in seen and wl in label.lower():
substr.append((label, kind, detail))
seen.add(label)
# sort by length within each group so shortest match comes first
prefix.sort(key=lambda x: len(x[0]))
substr.sort(key=lambda x: len(x[0]))
matches = (prefix + substr)[:20]
if not matches:
self.hide(); return
self.items = matches
self.sel = 0
self._show_popup()
# ── popup window ─────────────────────────────────────
def _show_popup(self):
if not self.win or not self.win.winfo_exists():
self._build_popup()
self._reposition()
self._render()
self.active = True
def _build_popup(self):
self.win = tk.Toplevel(self.root)
self.win.wm_overrideredirect(True)
self.win.configure(bg=VS["ac_bg"])
self.win.attributes("-topmost", True)
# list canvas
ch = self.RH * self.VIS
outer = tk.Frame(self.win, bg=VS["ac_border"], bd=1, relief="flat")
outer.pack(fill="both", expand=True)
self.cvs = tk.Canvas(outer, bg=VS["ac_bg"],
highlightthickness=0,
width=self.PW, height=ch)
self.sb = tk.Scrollbar(outer, orient="vertical",
command=self.cvs.yview,
bg=VS["scrollbar"], troughcolor=VS["ac_bg"],
width=8, relief="flat", bd=0)
self.cvs.configure(yscrollcommand=self.sb.set)
self.sb.pack(side="right", fill="y")
self.cvs.pack(fill="both", expand=True)
# detail panel
self.det = tk.Label(self.win, bg=VS["ac_detail"],
fg=VS["fg_dim"],
font=("Consolas", 10),
anchor="w", justify="left",
padx=12, pady=6,
wraplength=self.PW - 20,
height=3)
tk.Frame(self.win, bg=VS["ac_border"], height=1).pack(fill="x")
self.det.pack(fill="x")
self.cvs.bind("<Button-1>", self._click)
# attach nav keys to text widget
self.tw.bind("<Down>", self._nav_down)
self.tw.bind("<Up>", self._nav_up)
self.tw.bind("<Return>", self._accept_key)
self.tw.bind("<Tab>", self._accept_key)
def _reposition(self):
try:
bx, by, _, bh = self.tw.bbox("insert")
except:
return
rx = self.tw.winfo_rootx() + bx
ry = self.tw.winfo_rooty() + by + bh + 2
list_h = self.RH * self.VIS
total = list_h + self.DH + 2
sw = self.root.winfo_screenwidth()
sh = self.root.winfo_screenheight()
if rx + self.PW > sw: rx = sw - self.PW - 4
if ry + total > sh: ry = self.tw.winfo_rooty() + by - total - 2
self.win.geometry(f"{self.PW}x{total}+{max(0,rx)}+{max(0,ry)}")
self.win.lift()
def _render(self):
self.cvs.delete("all")
total_h = max(len(self.items) * self.RH, self.RH * self.VIS)
self.cvs.configure(scrollregion=(0, 0, self.PW, total_h))
for i, (label, kind, detail) in enumerate(self.items):
y0 = i * self.RH
y1 = y0 + self.RH
bg = VS["ac_sel"] if i == self.sel else VS["ac_bg"]
# row bg
self.cvs.create_rectangle(0, y0, self.PW, y1, fill=bg, outline="")
# kind icon box (colored square like VS Code)
icon_char = KIND_ICON_CHAR.get(kind, "?")
_, ic_col, klbl = KIND.get(kind, ("?", VS["fg_dim"], ""))
# colored square
self.cvs.create_rectangle(6, y0+3, 20, y1-3,
fill=ic_col, outline="")
self.cvs.create_text(13, y0 + self.RH//2, text=icon_char,
fill="#000000", font=("Consolas", 9, "bold"),
anchor="center")
# label
self.cvs.create_text(28, y0 + self.RH//2,
text=label,
fill=VS["fg"] if i == self.sel else VS["ac_fg"],
font=("Consolas", 12),
anchor="w")
# kind badge right
self.cvs.create_text(self.PW - 8, y0 + self.RH//2,
text=klbl,
fill=VS["fg_dim"],
font=("Consolas", 10),
anchor="e")
# scroll selected row into view
if self.items:
frac = (self.sel * self.RH) / max(total_h, 1)
self.cvs.yview_moveto(frac)
# detail
label, kind, detail = self.items[self.sel]
self.det.config(text=f" {detail}")
def _nav_down(self, event):
if not self.active: return
self.sel = (self.sel + 1) % len(self.items)
self._render()
return "break"
def _nav_up(self, event):
if not self.active: return
self.sel = (self.sel - 1) % len(self.items)
self._render()
return "break"
def _accept_key(self, event):
if not self.active: return "break"
self._do_accept()
return "break"
def _click(self, event):
row = event.y // self.RH
if 0 <= row < len(self.items):
self.sel = row
self._do_accept()
def _do_accept(self):
if not self.items: return
label = self.items[self.sel][0]
word = self._cur_word()
cur = self.tw.index("insert")
r, c = cur.split(".")
start = f"{r}.{int(c) - len(word)}"
self.tw.delete(start, cur)
self.tw.insert(start, label)
self.hide()
def hide(self, *_):
self.active = False
# restore normal bindings
self.tw.bind("<Down>", lambda e: None)
self.tw.bind("<Up>", lambda e: None)
self.tw.bind("<Return>", lambda e: None)
self.tw.bind("<Tab>", self._tab_spaces)
if self.win and self.win.winfo_exists():
self.win.destroy()
self.win = None; self.cvs = None; self.det = None
def _tab_spaces(self, e):
self.tw.insert("insert", " ")
return "break"
# ╔══════════════════════════════════════════════════════════╗
# EDITOR TAB
# ╚══════════════════════════════════════════════════════════╝
class EditorTab:
def __init__(self, nb, root, fn=None):
self.nb = nb
self.root = root
self.fn = fn
self.mod = False
self.frame = tk.Frame(nb, bg=VS["editor"])
nb.add(self.frame, text=self._lbl())
# layout: gutter | editor
row = tk.Frame(self.frame, bg=VS["editor"])
row.pack(fill="both", expand=True)
self.tw = tk.Text(
row,
bg=VS["editor"], fg=VS["fg"],
insertbackground="#aeafad",
selectbackground=VS["selection"],
selectforeground=VS["fg"],
font=("Consolas", 13),
relief="flat", bd=0,
wrap="none",
undo=True, maxundo=500,
padx=8, pady=4,
highlightthickness=0,
spacing1=1, spacing3=1,
exportselection=True,
)
self.gut = Gutter(row, self.tw)
self.gut.pack(side="left", fill="y")
sy = tk.Scrollbar(row, orient="vertical",
command=self.tw.yview,
bg=VS["scrollbar"], troughcolor=VS["editor"],
width=10, relief="flat", bd=0)
sx = tk.Scrollbar(self.frame, orient="horizontal",
command=self.tw.xview,
bg=VS["scrollbar"], troughcolor=VS["editor"],
width=10, relief="flat", bd=0)
self.tw.configure(yscrollcommand=sy.set, xscrollcommand=sx.set)
sy.pack(side="right", fill="y")
self.tw.pack(side="left", fill="both", expand=True)
sx.pack(fill="x")
self.hl = Highlighter(self.tw)
self.ac = IntelliSense(self.tw, root)
self.tw.bind("<KeyRelease>", self._changed)
self.tw.bind("<Tab>", self._tab)
self.tw.bind("<Return>", self._indent)
self.tw.bind("<BackSpace>", self._bs)
self.tw.bind("<Control-z>", lambda e: (self.tw.edit_undo(), "break")[1])
self.tw.bind("<Control-y>", lambda e: (self.tw.edit_redo(), "break")[1])
self.tw.bind("<Control-slash>", self._comment)
self.tw.bind("<Control-d>", self._dup_line)
# auto-pair
for o, c in [("(",")"),('"','"'),("'","'"),("[","]"),("{","}")]:
self.tw.bind(o, lambda e, o=o, c=c: self._pair(o, c))
if fn and os.path.exists(fn):
self._load()
def _lbl(self):
return f" {os.path.basename(self.fn) if self.fn else 'Untitled'} "
def _load(self):
try:
txt = Path(self.fn).read_text(encoding="utf-8")
self.tw.delete("1.0", "end")
self.tw.insert("1.0", txt)
self.hl._run(); self.gut.redraw()
self.mod = False
except Exception as ex: messagebox.showerror("Error", str(ex))
def save(self):
if not self.fn:
self.fn = filedialog.asksaveasfilename(
defaultextension=".py",
filetypes=[("Python","*.py"),("All files","*.*")])
if not self.fn: return False
try:
Path(self.fn).write_text(self.tw.get("1.0","end-1c"), encoding="utf-8")
self.mod = False
self.nb.tab(self.frame, text=self._lbl())
return True
except Exception as ex:
messagebox.showerror("Error", str(ex)); return False
def content(self): return self.tw.get("1.0","end-1c")
def _changed(self, *_):
self.hl.schedule(); self.gut.redraw()
if not self.mod:
self.mod = True
n = os.path.basename(self.fn) if self.fn else "Untitled"
self.nb.tab(self.frame, text=f" ● {n} ")
def _tab(self, e):
try:
sl = self.tw.index("sel.first linestart")
el = self.tw.index("sel.last lineend")
for ln in range(int(sl.split(".")[0]), int(el.split(".")[0])+1):
self.tw.insert(f"{ln}.0", " ")
except tk.TclError:
self.tw.insert("insert", " ")
return "break"
def _indent(self, e):
idx = self.tw.index("insert")
ln = idx.split(".")[0]
line = self.tw.get(f"{ln}.0", f"{ln}.end")
ind = re.match(r'^(\s*)', line).group(1)
extra = " " if line.rstrip().endswith(":") else ""
self.tw.insert("insert", "\n" + ind + extra)
self.gut.redraw(); return "break"
def _bs(self, e):
idx = self.tw.index("insert"); r, c = idx.split(".")
if int(c) >= 4 and self.tw.get(f"{r}.{int(c)-4}", idx) == " ":
self.tw.delete(f"{r}.{int(c)-4}", idx); return "break"
def _pair(self, o, c):
if o == c: # quotes
self.tw.insert("insert", o + c)
self.tw.mark_set("insert", "insert-1c"); return "break"
self.tw.insert("insert", o + c)
self.tw.mark_set("insert", "insert-1c"); return "break"
def _comment(self, e=None):
try: s=self.tw.index("sel.first linestart"); en=self.tw.index("sel.last lineend")
except: s=self.tw.index("insert linestart"); en=self.tw.index("insert lineend")
lines = self.tw.get(s, en).split("\n")
all_c = all(l.lstrip().startswith("#") for l in lines if l.strip())
new = [re.sub(r'^(\s*)# ?',r'\1',l,1) if all_c
else re.sub(r'^(\s*)',r'\1# ',l,1) for l in lines]
self.tw.delete(s, en); self.tw.insert(s, "\n".join(new)); return "break"
def _dup_line(self, e=None):
idx = self.tw.index("insert"); ln = idx.split(".")[0]
line = self.tw.get(f"{ln}.0", f"{ln}.end")
self.tw.insert(f"{ln}.end", "\n" + line); return "break"
# ╔══════════════════════════════════════════════════════════╗
# TERMINAL POPUP WINDOW
# ╚══════════════════════════════════════════════════════════╝
class Terminal:
ANSI = re.compile(r'\x1b\[[0-9;]*m')
def __init__(self, root):
self.root = root; self.proc = None; self.win = None
def show(self):
if self.win and self.win.winfo_exists():
self.win.lift(); self.win.focus_force(); return
self.win = tk.Toplevel(self.root)
self.win.title("Terminal — Kavin IDE")
self.win.geometry("860x380")
self.win.configure(bg=VS["panel"])
rx = self.root.winfo_x() + self.root.winfo_width()//2 - 430
ry = self.root.winfo_y() + self.root.winfo_height()//2 - 190
self.win.geometry(f"860x380+{max(0,rx)}+{max(0,ry)}")
# header
hdr = tk.Frame(self.win, bg=VS["panel_hdr"], height=30)
hdr.pack(fill="x"); hdr.pack_propagate(False)
tk.Label(hdr, text=" TERMINAL", bg=VS["panel_hdr"],
fg=VS["fg_dim"], font=("Segoe UI",9,"bold")).pack(side="left", pady=5, padx=6)
for txt, fg_, cmd in [
("✕", "#f48771", lambda: self.win.destroy()),
("⏹", VS["fg_dim"], self.stop),
("🗑", VS["fg_muted"], self.clear),
]:
b = tk.Button(hdr, text=txt, bg=VS["panel_hdr"], fg=fg_,
activebackground=VS["hover"], activeforeground=fg_,
relief="flat", font=("Segoe UI",10), cursor="hand2",
bd=0, padx=8, command=cmd)
b.pack(side="right", pady=3)
tk.Frame(self.win, bg=VS["border"], height=1).pack(fill="x")
# output
of = tk.Frame(self.win, bg=VS["panel"]); of.pack(fill="both", expand=True)
self.out = tk.Text(of, bg=VS["panel"], fg=VS["fg"],
font=("Consolas",12), relief="flat",
state="disabled", wrap="word",
padx=14, pady=8, highlightthickness=0)
sb_ = tk.Scrollbar(of, command=self.out.yview,
bg=VS["scrollbar"], troughcolor=VS["panel"],
width=8, relief="flat", bd=0)
self.out.configure(yscrollcommand=sb_.set)
sb_.pack(side="right", fill="y"); self.out.pack(fill="both", expand=True)
self.out.tag_configure("err", foreground=VS["err_fg"])
self.out.tag_configure("ok", foreground="#4ec9b0")
self.out.tag_configure("info", foreground="#569cd6")
self.out.tag_configure("dim", foreground=VS["fg_muted"])
self.out.tag_configure("prm", foreground="#dcdcaa")
# stdin
ir = tk.Frame(self.win, bg="#141414"); ir.pack(fill="x")
tk.Label(ir, text=" > ", bg="#141414", fg="#4ec9b0",
font=("Consolas",11)).pack(side="left")
self.svar = tk.StringVar()
ent = tk.Entry(ir, textvariable=self.svar,
bg="#141414", fg=VS["fg"],
insertbackground=VS["fg"],
relief="flat", font=("Consolas",12),
highlightthickness=0)
ent.pack(fill="x", expand=True, padx=6, pady=5)
ent.bind("<Return>", self._send)
self._w("Kavin IDE Terminal\n", "info")
self._w("─" * 54 + "\n", "dim")
def _w(self, text, tag=None):
if not self.win or not self.win.winfo_exists(): return
text = self.ANSI.sub("", text)
self.out.configure(state="normal")
if tag: self.out.insert("end", text, tag)
else: self.out.insert("end", text)
self.out.see("end"); self.out.configure(state="disabled")
def run(self, code, fn=None, on_err=None):
self.show(); self.stop(); self.clear()
label = os.path.basename(fn) if fn else "untitled.py"
self._w(f"▶ {label}\n", "prm")
self._w("─" * 54 + "\n", "dim")
if fn and os.path.exists(fn):
script, cwd = fn, os.path.dirname(fn) or "."
else:
tmp = tempfile.NamedTemporaryFile(suffix=".py", delete=False,
mode="w", encoding="utf-8")
tmp.write(code); tmp.flush(); tmp.close()
script, cwd = tmp.name, os.getcwd()
def worker():
t0 = time.time()
try:
self.proc = subprocess.Popen(
[sys.executable, "-u", script],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE, text=True, cwd=cwd, bufsize=1)
for line in iter(self.proc.stdout.readline, ""):
if self.win and self.win.winfo_exists():
self.win.after(0, self._w, line)
err = self.proc.stderr.read()
if err:
if self.win and self.win.winfo_exists():
self.win.after(0, self._w, "\n" + err, "err")
m = re.search(r'line (\d+)', err)
if on_err and self.win and self.win.winfo_exists():
self.win.after(0, on_err, int(m.group(1)) if m else None)
else:
if on_err and self.win and self.win.winfo_exists():
self.win.after(0, on_err, None)
self.proc.wait()
rc = self.proc.returncode; el = time.time() - t0
if self.win and self.win.winfo_exists():
self.win.after(0, self._w, "─" * 54 + "\n", "dim")
msg = f"✓ Exit {rc} ({el:.2f}s)\n"
self.win.after(0, self._w, msg, "ok" if rc == 0 else "err")
except Exception as ex:
if self.win and self.win.winfo_exists():
self.win.after(0, self._w, f"Error: {ex}\n", "err")
finally: self.proc = None
threading.Thread(target=worker, daemon=True).start()
def _send(self, *_):
if self.proc and self.proc.stdin:
try:
t = self.svar.get() + "\n"
self.proc.stdin.write(t); self.proc.stdin.flush()
self._w(f" {t}", "prm"); self.svar.set("")
except: pass
def stop(self):
if self.proc:
try: self.proc.terminate()
except: pass
def clear(self):
if not self.win or not self.win.winfo_exists(): return
self.out.configure(state="normal"); self.out.delete("1.0","end")
self.out.configure(state="disabled")