typsteditor 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,3 @@
1
+ from .app import main
2
+
3
+ main()
typsteditor/app.py ADDED
@@ -0,0 +1,58 @@
1
+ """Application : QApplication (ouverture depuis le Finder) et fonction main()."""
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ from PyQt6.QtCore import QEvent
6
+ from PyQt6.QtGui import QIcon
7
+ from PyQt6.QtWidgets import QApplication
8
+
9
+ from .constants import APP_NAME
10
+ from .main_window import MainWindow
11
+ from .version import __version__
12
+
13
+
14
+ def set_macos_app_name(name):
15
+ """Sous macOS, le menu de l'application s'appelle « Python » ; on le renomme (pyobjc optionnel)."""
16
+ if sys.platform != "darwin":
17
+ return
18
+ try:
19
+ from Foundation import NSBundle
20
+ except ImportError:
21
+ return
22
+ NSBundle.mainBundle().infoDictionary()["CFBundleName"] = name
23
+
24
+
25
+ class TypstApplication(QApplication):
26
+ """Gère l'ouverture d'un fichier par Finder (double-clic, « Ouvrir avec »)."""
27
+ pending: str | None = None
28
+
29
+ def event(self, e):
30
+ if e.type() == QEvent.Type.FileOpen:
31
+ wins = MainWindow.windows
32
+ if wins:
33
+ (self.activeWindow() or wins[-1]).open_in_window(e.file())
34
+ else:
35
+ self.pending = e.file()
36
+ return True
37
+ return super().event(e)
38
+
39
+
40
+ def main():
41
+ if "--version" in sys.argv[1:]:
42
+ print(f"{APP_NAME} {__version__}")
43
+ sys.exit(0)
44
+ set_macos_app_name(APP_NAME)
45
+ app = TypstApplication(sys.argv)
46
+ if sys.platform != "darwin":
47
+ app.setStyle("Fusion")
48
+ app.setApplicationName(APP_NAME)
49
+ app.setApplicationVersion(__version__)
50
+ app.setWindowIcon(QIcon(str(Path(__file__).with_name("icon.svg")))) # icône du Dock hors .app
51
+ win = MainWindow()
52
+ win.show()
53
+ start = app.pending or next((a for a in sys.argv[1:] if Path(a).is_file()), None)
54
+ if start:
55
+ win.load_path(Path(start))
56
+ else:
57
+ win.open_last_recent()
58
+ sys.exit(app.exec())
@@ -0,0 +1,104 @@
1
+ """Éditeur de code avec numéros de ligne et ligne courante mise en valeur."""
2
+ from PyQt6.QtCore import QRect, QSize, Qt
3
+ from PyQt6.QtGui import QColor, QFont, QPainter, QPalette, QTextFormat
4
+ from PyQt6.QtWidgets import QFrame, QPlainTextEdit, QTextEdit, QWidget
5
+
6
+
7
+ class LineNumberArea(QWidget):
8
+ def __init__(self, editor):
9
+ super().__init__(editor)
10
+ self.editor = editor
11
+
12
+ def sizeHint(self):
13
+ return QSize(self.editor.number_area_width(), 0)
14
+
15
+ def paintEvent(self, event):
16
+ self.editor.paint_numbers(event)
17
+
18
+
19
+ class CodeEditor(QPlainTextEdit):
20
+ """QPlainTextEdit avec une marge de numéros de ligne, sans cadre, à fond uni."""
21
+
22
+ def __init__(self):
23
+ super().__init__()
24
+ self.setFrameShape(QFrame.Shape.NoFrame)
25
+ self.setCursorWidth(2)
26
+ self.document().setDocumentMargin(10)
27
+ self.number_area = LineNumberArea(self)
28
+ self.gutter_bg = QColor("#ffffff")
29
+ self.gutter_fg, self.gutter_fg_current = QColor("#a1a1a6"), QColor("#5a5a5f")
30
+ self.current_line_color = QColor("#f4f6fa")
31
+ self.blockCountChanged.connect(self.update_margin)
32
+ self.updateRequest.connect(self.update_numbers)
33
+ self.cursorPositionChanged.connect(self.highlight_current_line)
34
+ self.update_margin()
35
+ self.highlight_current_line()
36
+
37
+ def gutter_font(self):
38
+ font = QFont(self.font())
39
+ font.setPointSizeF(max(self.font().pointSizeF() - 2, 8))
40
+ return font
41
+
42
+ def number_area_width(self):
43
+ digits = max(2, len(str(max(1, self.blockCount()))))
44
+ return 22 + self.fontMetrics().horizontalAdvance("9") * digits
45
+
46
+ def setFont(self, font):
47
+ super().setFont(font)
48
+ self.update_margin()
49
+
50
+ def update_margin(self):
51
+ self.setViewportMargins(self.number_area_width(), 0, 0, 0)
52
+
53
+ def update_numbers(self, rect, dy):
54
+ if dy:
55
+ self.number_area.scroll(0, dy)
56
+ else:
57
+ self.number_area.update(0, rect.y(), self.number_area.width(), rect.height())
58
+ if rect.contains(self.viewport().rect()):
59
+ self.update_margin()
60
+
61
+ def resizeEvent(self, event):
62
+ super().resizeEvent(event)
63
+ cr = self.contentsRect()
64
+ self.number_area.setGeometry(QRect(cr.left(), cr.top(), self.number_area_width(), cr.height()))
65
+
66
+ def set_colors(self, theme):
67
+ """Applique les couleurs du thème : fond et texte via la palette, le reste en direct."""
68
+ palette = self.palette()
69
+ palette.setColor(QPalette.ColorRole.Base, QColor(theme["editor_bg"]))
70
+ palette.setColor(QPalette.ColorRole.Text, QColor(theme["editor_fg"]))
71
+ self.setPalette(palette)
72
+ self.gutter_bg = QColor(theme["editor_bg"])
73
+ self.gutter_fg = QColor(theme["gutter_fg"])
74
+ self.gutter_fg_current = QColor(theme["gutter_fg_current"])
75
+ self.current_line_color = QColor(theme["current_line"])
76
+ self.highlight_current_line()
77
+ self.number_area.update()
78
+
79
+ def highlight_current_line(self):
80
+ selection = QTextEdit.ExtraSelection()
81
+ selection.format.setBackground(self.current_line_color)
82
+ selection.format.setProperty(QTextFormat.Property.FullWidthSelection, True)
83
+ selection.cursor = self.textCursor()
84
+ selection.cursor.clearSelection()
85
+ self.setExtraSelections([] if self.textCursor().hasSelection() else [selection])
86
+ self.number_area.update()
87
+
88
+ def paint_numbers(self, event):
89
+ painter = QPainter(self.number_area)
90
+ painter.fillRect(event.rect(), self.gutter_bg)
91
+ painter.setFont(self.gutter_font())
92
+ current = self.textCursor().blockNumber()
93
+ block = self.firstVisibleBlock()
94
+ top = round(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
95
+ while block.isValid() and top <= event.rect().bottom():
96
+ height = round(self.blockBoundingRect(block).height())
97
+ if block.isVisible() and top + height >= event.rect().top():
98
+ number = block.blockNumber()
99
+ painter.setPen(self.gutter_fg_current if number == current else self.gutter_fg)
100
+ painter.drawText(0, top, self.number_area.width() - 10, height,
101
+ Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter,
102
+ str(number + 1))
103
+ block = block.next()
104
+ top += height
@@ -0,0 +1,15 @@
1
+ """Constantes partagées."""
2
+
3
+ TEMPLATE = """#set page(width: 16cm, height: auto, margin: 1cm)
4
+ #set text(lang: "fr")
5
+
6
+ = Bonjour Typst
7
+
8
+ Une équation : $ sum_(k=1)^n k = (n (n + 1)) / 2 $
9
+
10
+ - Premier point
11
+ - Second point avec du *gras* et de l'_italique_
12
+ """
13
+ APP_NAME = "TypstEditor"
14
+ MAX_RECENT = 8
15
+ FILTER = "Fichiers Typst (*.typ);;Tous les fichiers (*)"
@@ -0,0 +1,157 @@
1
+ """Barre de recherche et de remplacement."""
2
+ from PyQt6.QtCore import Qt, pyqtSignal
3
+ from PyQt6.QtGui import QColor, QPainter, QTextCursor, QTextDocument
4
+ from PyQt6.QtWidgets import QHBoxLayout, QLineEdit, QPushButton, QToolButton, QVBoxLayout, QWidget
5
+
6
+
7
+ class FindBar(QWidget):
8
+ """Barre de recherche sous l'éditeur (Entrée : suivant, Maj+Entrée : précédent)."""
9
+ not_found = pyqtSignal()
10
+ info = pyqtSignal(str)
11
+
12
+ def __init__(self, editor):
13
+ super().__init__()
14
+ self.editor = editor
15
+ self.field = QLineEdit(placeholderText="Rechercher…", clearButtonEnabled=True)
16
+ self.case = QToolButton(text="Aa", checkable=True, autoRaise=True)
17
+ self.case.setToolTip("Respecter la casse")
18
+ prev_btn, next_btn, close_btn = (QToolButton(text=t, autoRaise=True) for t in ("‹", "›", "✕"))
19
+ for b, tip in [(prev_btn, "Précédent"), (next_btn, "Suivant"), (close_btn, "Fermer")]:
20
+ b.setToolTip(tip)
21
+ b.setFixedWidth(28)
22
+
23
+ self.replace_field = QLineEdit(placeholderText="Remplacer par…", clearButtonEnabled=True)
24
+ replace_btn, replace_all_btn = QPushButton("Remplacer"), QPushButton("Tout remplacer")
25
+ self.replace_row = QWidget()
26
+ row = QHBoxLayout(self.replace_row)
27
+ row.setContentsMargins(0, 0, 0, 0)
28
+ for w in (self.replace_field, replace_btn, replace_all_btn):
29
+ row.addWidget(w)
30
+
31
+ layout = QVBoxLayout(self)
32
+ layout.setContentsMargins(10, 8, 10, 8)
33
+ layout.setSpacing(6)
34
+ top = QHBoxLayout()
35
+ for w in (self.field, self.case, prev_btn, next_btn, close_btn):
36
+ top.addWidget(w)
37
+ layout.addLayout(top)
38
+ layout.addWidget(self.replace_row)
39
+
40
+ self.field.returnPressed.connect(self.find_next)
41
+ self.replace_field.returnPressed.connect(self.replace_current)
42
+ next_btn.clicked.connect(self.find_next)
43
+ prev_btn.clicked.connect(self.find_prev)
44
+ close_btn.clicked.connect(self.close_bar)
45
+ replace_btn.clicked.connect(self.replace_current)
46
+ replace_all_btn.clicked.connect(self.replace_all)
47
+ self.field.textChanged.connect(lambda: self.find(backward=False, from_start=True))
48
+ self.hide()
49
+
50
+ def paintEvent(self, event):
51
+ """Fond de barre et filet supérieur, comme une barre secondaire macOS."""
52
+ p = QPainter(self)
53
+ p.fillRect(self.rect(), self.palette().window())
54
+ line = QColor(self.palette().windowText().color())
55
+ line.setAlpha(36)
56
+ p.fillRect(0, 0, self.width(), 1, line)
57
+ p.end()
58
+
59
+ def keyPressEvent(self, event):
60
+ if event.key() == Qt.Key.Key_Escape:
61
+ self.close_bar()
62
+ elif (event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter)
63
+ and event.modifiers() & Qt.KeyboardModifier.ShiftModifier):
64
+ self.find_prev()
65
+ else:
66
+ super().keyPressEvent(event)
67
+
68
+ def open_bar(self, replace=False):
69
+ sel = self.editor.textCursor().selection().toPlainText()
70
+ if sel and "\n" not in sel:
71
+ self.field.setText(sel)
72
+ self.replace_row.setVisible(replace)
73
+ self.show()
74
+ self.field.setFocus()
75
+ self.field.selectAll()
76
+
77
+ def open_replace(self):
78
+ self.open_bar(replace=True)
79
+
80
+ def case_flags(self):
81
+ return (QTextDocument.FindFlag.FindCaseSensitively if self.case.isChecked()
82
+ else QTextDocument.FindFlag(0))
83
+
84
+ def selection_matches(self):
85
+ sel = self.editor.textCursor().selectedText()
86
+ text = self.field.text()
87
+ if not sel:
88
+ return False
89
+ return sel == text if self.case.isChecked() else sel.lower() == text.lower()
90
+
91
+ def replace_current(self):
92
+ """Remplace l'occurrence sélectionnée (la sélectionne d'abord si besoin), puis passe à la suivante."""
93
+ if not self.field.text():
94
+ return
95
+ if not self.selection_matches():
96
+ self.find_next()
97
+ if not self.selection_matches():
98
+ return
99
+ cur = self.editor.textCursor()
100
+ cur.insertText(self.replace_field.text())
101
+ self.editor.setTextCursor(cur)
102
+ self.find_next()
103
+
104
+ def replace_all(self):
105
+ text = self.field.text()
106
+ if not text:
107
+ return
108
+ doc, flags, repl = self.editor.document(), self.case_flags(), self.replace_field.text()
109
+ count, pos = 0, 0
110
+ edit = QTextCursor(doc)
111
+ edit.beginEditBlock() # une seule étape d'annulation pour tout le remplacement
112
+ while True:
113
+ found = doc.find(text, pos, flags)
114
+ if found.isNull():
115
+ break
116
+ found.insertText(repl)
117
+ pos = found.position()
118
+ count += 1
119
+ edit.endEditBlock()
120
+ if count:
121
+ self.info.emit(f"{count} remplacement{'s' if count > 1 else ''}")
122
+ else:
123
+ self.not_found.emit()
124
+
125
+ def close_bar(self):
126
+ self.hide()
127
+ self.editor.setFocus()
128
+
129
+ def find_next(self):
130
+ self.find(backward=False)
131
+
132
+ def find_prev(self):
133
+ self.find(backward=True)
134
+
135
+ def find(self, backward, from_start=False):
136
+ text = self.field.text()
137
+ if not text:
138
+ return
139
+ flags = QTextDocument.FindFlag(0)
140
+ if backward:
141
+ flags |= QTextDocument.FindFlag.FindBackward
142
+ if self.case.isChecked():
143
+ flags |= QTextDocument.FindFlag.FindCaseSensitively
144
+ cur = self.editor.textCursor()
145
+ if from_start: # recherche incrémentale : repartir du début de la sélection courante
146
+ cur.setPosition(cur.selectionStart())
147
+ self.editor.setTextCursor(cur)
148
+ if self.editor.find(text, flags):
149
+ return
150
+ # retour à la ligne : on repart du début (ou de la fin)
151
+ wrap = QTextCursor(self.editor.document())
152
+ wrap.movePosition(QTextCursor.MoveOperation.End if backward
153
+ else QTextCursor.MoveOperation.Start)
154
+ self.editor.setTextCursor(wrap)
155
+ if not self.editor.find(text, flags):
156
+ self.editor.setTextCursor(cur)
157
+ self.not_found.emit()
typsteditor/follow.py ADDED
@@ -0,0 +1,50 @@
1
+ """Repérage dans le texte source de ce qui se retrouve tel quel dans le PDF.
2
+
3
+ Typst ne fournit pas la correspondance source → page en ligne de commande ; on cherche donc dans le
4
+ PDF un court fragment du texte voisin du curseur. Sans dépendance à Qt."""
5
+ import re
6
+
7
+ STRIP = [
8
+ re.compile(r"\$[^$]*\$"), # mathématiques
9
+ re.compile(r"//.*$"), # commentaire de ligne
10
+ re.compile(r"#(?:let|set|show|import|include)\b.*$"), # instructions sans texte visible
11
+ re.compile(r"#[A-Za-z_][\w\-.]*(?:\([^()]*\))?"), # appels #fonction(...)
12
+ re.compile(r"[<@][A-Za-z_][\w\-.:]*>?"), # étiquettes et références
13
+ re.compile(r"^\s*(?:=+|[-+/]|\d+\.)\s+"), # marqueurs de titre / liste
14
+ ]
15
+ WORD = re.compile(r"[^\W_]{2,}(?:['’\-][^\W_]+)*")
16
+
17
+
18
+ def fragments(line: str) -> list[str]:
19
+ """Fragments candidats d'une ligne, du plus fiable au moins fiable : trois mots consécutifs
20
+ (début du plus long groupe), puis le mot le plus long. Vide si la ligne n'a pas de texte visible."""
21
+ for rx in STRIP:
22
+ line = rx.sub(" ", line)
23
+ line = re.sub(r"[*_`\\~\[\]{}]", " ", line)
24
+ runs = [r for r in re.split(r"[.,;:!?…()«»\"“”]+", line) if WORD.search(r)]
25
+ if not runs:
26
+ return []
27
+ best = max(runs, key=lambda r: len(r.strip()))
28
+ words = WORD.findall(best)
29
+ out = []
30
+ if len(words) >= 2:
31
+ out.append(" ".join(words[:3]))
32
+ longest = max(words, key=len)
33
+ if len(longest) >= 4:
34
+ out.append(longest)
35
+ return out
36
+
37
+
38
+ def candidates(lines: list[str], index: int, spread: int = 12):
39
+ """(rang de ligne, fragment, occurrences précédentes) pour la ligne `index`, puis les voisines
40
+ (avant, après, en alternance) jusqu'à `spread` lignes. « Occurrences précédentes » compte les
41
+ fragments identiques situés avant la ligne dans le texte, pour viser la bonne occurrence."""
42
+ order = [index]
43
+ for d in range(1, spread + 1):
44
+ order += [index - d, index + d]
45
+ for i in order:
46
+ if not 0 <= i < len(lines):
47
+ continue
48
+ for frag in fragments(lines[i]):
49
+ before = "\n".join(lines[:i]).lower()
50
+ yield i, frag, before.count(frag.lower())
typsteditor/icon.svg ADDED
@@ -0,0 +1,26 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
2
+ <defs>
3
+ <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#2f3542"/><stop offset="1" stop-color="#0f1218"/></linearGradient>
4
+ <linearGradient id="teal" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#3fd0d4"/><stop offset="1" stop-color="#1b8fa6"/></linearGradient>
5
+ <linearGradient id="shine" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff" stop-opacity="0.12"/><stop offset="0.45" stop-color="#fff" stop-opacity="0"/></linearGradient>
6
+ </defs>
7
+ <rect x="100" y="100" width="824" height="824" rx="185" fill="url(#bg)"/>
8
+ <rect x="100" y="100" width="824" height="824" rx="185" fill="url(#shine)"/>
9
+ <!-- code, à gauche : lignes de code colorées -->
10
+ <g stroke-width="34" stroke-linecap="round" fill="none">
11
+ <line x1="215" y1="330" x2="365" y2="330" stroke="#fc5fa3"/>
12
+ <line x1="395" y1="330" x2="440" y2="330" stroke="#5dd8ff"/>
13
+ <line x1="215" y1="410" x2="300" y2="410" stroke="#d0bf69"/>
14
+ <line x1="330" y1="410" x2="440" y2="410" stroke="#ffffff" stroke-opacity="0.75"/>
15
+ <line x1="215" y1="490" x2="415" y2="490" stroke="#ffffff" stroke-opacity="0.75"/>
16
+ <line x1="215" y1="570" x2="320" y2="570" stroke="#fc6a5d"/>
17
+ <line x1="350" y1="570" x2="440" y2="570" stroke="#ffffff" stroke-opacity="0.75"/>
18
+ <line x1="215" y1="650" x2="395" y2="650" stroke="#ffffff" stroke-opacity="0.75"/>
19
+ </g>
20
+ <!-- document, à droite : page blanche avec un T -->
21
+ <rect x="500" y="230" width="330" height="464" rx="30" fill="#ffffff"/>
22
+ <path d="M568 305 H762 V362 H692 V520 H638 V362 H568z" fill="url(#teal)"/>
23
+ <g stroke="#c9ced6" stroke-width="22" stroke-linecap="round">
24
+ <line x1="568" y1="582" x2="762" y2="582"/><line x1="568" y1="632" x2="710" y2="632"/>
25
+ </g>
26
+ </svg>
typsteditor/icons.py ADDED
@@ -0,0 +1,43 @@
1
+ """Icônes de la barre d'outils : traits fins à bouts arrondis, dans l'esprit des symboles SF.
2
+
3
+ Dessinées en SVG (grille 24 × 24) et teintées à la demande, pour suivre le thème clair/sombre."""
4
+ from PyQt6.QtCore import QByteArray, QRectF, Qt
5
+ from PyQt6.QtGui import QIcon, QImage, QPainter, QPixmap
6
+ from PyQt6.QtSvg import QSvgRenderer
7
+
8
+ SIZE = 20 # points
9
+
10
+ PATHS = {
11
+ "new": "M14 3.5H7.5a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2V8z M14 3.5V8h4.5 M12 11.5v5 M9.5 14h5",
12
+ "open": "M3.5 7.5a2 2 0 0 1 2-2h4l2 2.2h7a2 2 0 0 1 2 2v7.8a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2z",
13
+ "save": "M12 4v11 M7.5 10.8l4.5 4.5 4.5-4.5 M5 15.5v2a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-2",
14
+ "export": "M12 15V4 M7.8 8.2L12 4l4.2 4.2 M8 11.5H7a2 2 0 0 0-2 2V18a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-4.5a2 2 0 0 0-2-2h-1",
15
+ "zoom_in": "M10.5 4.3a6.2 6.2 0 1 0 0 12.4 6.2 6.2 0 0 0 0-12.4z M15.2 15.2L20 20 M8 10.5h5 M10.5 8v5",
16
+ "zoom_out": "M10.5 4.3a6.2 6.2 0 1 0 0 12.4 6.2 6.2 0 0 0 0-12.4z M15.2 15.2L20 20 M8 10.5h5",
17
+ "fit": "M4 9V6a2 2 0 0 1 2-2h3 M15 4h3a2 2 0 0 1 2 2v3 M20 15v3a2 2 0 0 1-2 2h-3 M9 20H6a2 2 0 0 1-2-2v-3",
18
+ "main": "M12 3.5l2.6 5.3 5.9.9-4.3 4.1 1 5.8-5.2-2.7-5.2 2.7 1-5.8-4.3-4.1 5.9-.9z",
19
+ "search": "M10.5 4.3a6.2 6.2 0 1 0 0 12.4 6.2 6.2 0 0 0 0-12.4z M15.2 15.2L20 20",
20
+ }
21
+
22
+
23
+ def pixmap(name: str, color: str, alpha: float = 1.0, ratio: float = 2.0) -> QPixmap:
24
+ svg = (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" '
25
+ f'stroke="{color}" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">'
26
+ f'<path d="{PATHS[name]}"/></svg>')
27
+ px = int(SIZE * ratio)
28
+ image = QImage(px, px, QImage.Format.Format_ARGB32_Premultiplied)
29
+ image.fill(Qt.GlobalColor.transparent)
30
+ painter = QPainter(image)
31
+ painter.setOpacity(alpha)
32
+ QSvgRenderer(QByteArray(svg.encode())).render(painter, QRectF(0, 0, px, px))
33
+ painter.end()
34
+ pm = QPixmap.fromImage(image)
35
+ pm.setDevicePixelRatio(ratio)
36
+ return pm
37
+
38
+
39
+ def icon(name: str, color: str) -> QIcon:
40
+ result = QIcon()
41
+ result.addPixmap(pixmap(name, color), QIcon.Mode.Normal)
42
+ result.addPixmap(pixmap(name, color, alpha=0.3), QIcon.Mode.Disabled)
43
+ return result