typsteditor 0.3.0__tar.gz
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.
- typsteditor-0.3.0/LICENSE +21 -0
- typsteditor-0.3.0/PKG-INFO +59 -0
- typsteditor-0.3.0/README.md +40 -0
- typsteditor-0.3.0/pyproject.toml +35 -0
- typsteditor-0.3.0/setup.cfg +4 -0
- typsteditor-0.3.0/tests/test_follow.py +22 -0
- typsteditor-0.3.0/tests/test_typst.py +43 -0
- typsteditor-0.3.0/typsteditor/__init__.py +0 -0
- typsteditor-0.3.0/typsteditor/__main__.py +3 -0
- typsteditor-0.3.0/typsteditor/app.py +58 -0
- typsteditor-0.3.0/typsteditor/code_editor.py +104 -0
- typsteditor-0.3.0/typsteditor/constants.py +15 -0
- typsteditor-0.3.0/typsteditor/find_bar.py +157 -0
- typsteditor-0.3.0/typsteditor/follow.py +50 -0
- typsteditor-0.3.0/typsteditor/icon.svg +26 -0
- typsteditor-0.3.0/typsteditor/icons.py +43 -0
- typsteditor-0.3.0/typsteditor/main_window.py +731 -0
- typsteditor-0.3.0/typsteditor/themes.py +117 -0
- typsteditor-0.3.0/typsteditor/typst.py +148 -0
- typsteditor-0.3.0/typsteditor/version.py +2 -0
- typsteditor-0.3.0/typsteditor/views.py +54 -0
- typsteditor-0.3.0/typsteditor.egg-info/PKG-INFO +59 -0
- typsteditor-0.3.0/typsteditor.egg-info/SOURCES.txt +25 -0
- typsteditor-0.3.0/typsteditor.egg-info/dependency_links.txt +1 -0
- typsteditor-0.3.0/typsteditor.egg-info/entry_points.txt +2 -0
- typsteditor-0.3.0/typsteditor.egg-info/requires.txt +1 -0
- typsteditor-0.3.0/typsteditor.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Emmanuel Desmontils
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: typsteditor
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Éditeur Typst de bureau : code à gauche, document en direct à droite (PyQt6, typst watch)
|
|
5
|
+
Author: Emmanuel Desmontils
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: typst,editor,pyqt6,pdf
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Environment :: X11 Applications :: Qt
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Natural Language :: French
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Software Development :: Documentation
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: PyQt6>=6.8
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# TypstEditor
|
|
21
|
+
|
|
22
|
+
Éditeur [Typst](https://typst.app) de bureau (Python 3.10+, PyQt6) : le code à gauche, avec coloration syntaxique, le document PDF en direct à droite. Même esprit que MocodoEditor et PUMLEditor.
|
|
23
|
+
|
|
24
|
+
## Prérequis
|
|
25
|
+
|
|
26
|
+
- Python ≥ 3.10 et PyQt6 (`pip install -r requirements.txt`)
|
|
27
|
+
- Typst en ligne de commande : `brew install typst`
|
|
28
|
+
|
|
29
|
+
## Utilisation
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
python3 -m typsteditor [fichier.typ]
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
L'aperçu est alimenté par `typst watch` : chaque modification est écrite sur le disque (sauvegarde automatique, une demi-seconde après la dernière frappe) et Typst recompile aussitôt. La position de lecture est conservée entre deux compilations. Les erreurs s'affichent sous l'aperçu ; **Édition ▸ Aller à l'erreur** (Ctrl+E) place le curseur sur la ligne fautive, même dans un autre fichier.
|
|
36
|
+
|
|
37
|
+
### Suivi du curseur
|
|
38
|
+
|
|
39
|
+
L'aperçu se place sur la page du texte voisin du curseur (menu **Préférences** : *Mode synchronisé*, par défaut, ou *Mode non synchronisé*, où l'aperçu reste où il est ; **Affichage ▸ Afficher la page du curseur**, Ctrl+Maj+J, force le défilement dans les deux modes). Typst ne donne pas la correspondance source → page en ligne de commande : l'éditeur cherche dans le PDF un court fragment du texte de la ligne (ou des lignes voisines) et vise la bonne occurrence. Limites : une ligne sans texte visible (code, maths, `#pagebreak()`) se rabat sur ses voisines ; un texte qui ne figure pas tel quel dans le PDF (généré, transformé) ou une page de l'aperçu sans texte repérable n'est pas retrouvé ; en édition d'un fichier inclus, l'occurrence visée peut être la première du document plutôt que la bonne.
|
|
40
|
+
|
|
41
|
+
### Document principal
|
|
42
|
+
|
|
43
|
+
Pour un projet de plusieurs fichiers (`#include`, `#import`), désigner le fichier racine avec **Fichier ▸ Document principal** :
|
|
44
|
+
|
|
45
|
+
- *Utiliser le document courant* (Ctrl+Maj+M) ;
|
|
46
|
+
- *Choisir…* un autre fichier ;
|
|
47
|
+
- *Aucun* : sans document principal, le document courant est compilé.
|
|
48
|
+
|
|
49
|
+
Le document principal est mémorisé d'une session à l'autre ; son nom apparaît dans la barre d'état et le titre. Les fichiers inclus sont édités normalement, l'aperçu montre toujours le résultat du document principal.
|
|
50
|
+
|
|
51
|
+
Un nouveau document (jamais enregistré) est écrit dans un dossier temporaire ; l'enregistrer pour l'utiliser comme principal.
|
|
52
|
+
|
|
53
|
+
### Plusieurs fenêtres
|
|
54
|
+
|
|
55
|
+
**Fichier ▸ Nouvelle fenêtre** (Ctrl+Maj+N) ouvre une fenêtre indépendante, avec son propre aperçu et son propre `typst watch`. Ouvrir un fichier le place dans la fenêtre courante si elle est encore vierge, sinon dans une nouvelle fenêtre ; un fichier déjà ouvert ramène sa fenêtre au premier plan. Le document principal n'est restauré qu'à la première fenêtre.
|
|
56
|
+
|
|
57
|
+
## Autres commandes
|
|
58
|
+
|
|
59
|
+
`python3 -I -m pytest -q tests` pour les tests ; `./packaging/build_app.sh [--open | --install]` pour construire le `.app` (py2app).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# TypstEditor
|
|
2
|
+
|
|
3
|
+
Éditeur [Typst](https://typst.app) de bureau (Python 3.10+, PyQt6) : le code à gauche, avec coloration syntaxique, le document PDF en direct à droite. Même esprit que MocodoEditor et PUMLEditor.
|
|
4
|
+
|
|
5
|
+
## Prérequis
|
|
6
|
+
|
|
7
|
+
- Python ≥ 3.10 et PyQt6 (`pip install -r requirements.txt`)
|
|
8
|
+
- Typst en ligne de commande : `brew install typst`
|
|
9
|
+
|
|
10
|
+
## Utilisation
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
python3 -m typsteditor [fichier.typ]
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
L'aperçu est alimenté par `typst watch` : chaque modification est écrite sur le disque (sauvegarde automatique, une demi-seconde après la dernière frappe) et Typst recompile aussitôt. La position de lecture est conservée entre deux compilations. Les erreurs s'affichent sous l'aperçu ; **Édition ▸ Aller à l'erreur** (Ctrl+E) place le curseur sur la ligne fautive, même dans un autre fichier.
|
|
17
|
+
|
|
18
|
+
### Suivi du curseur
|
|
19
|
+
|
|
20
|
+
L'aperçu se place sur la page du texte voisin du curseur (menu **Préférences** : *Mode synchronisé*, par défaut, ou *Mode non synchronisé*, où l'aperçu reste où il est ; **Affichage ▸ Afficher la page du curseur**, Ctrl+Maj+J, force le défilement dans les deux modes). Typst ne donne pas la correspondance source → page en ligne de commande : l'éditeur cherche dans le PDF un court fragment du texte de la ligne (ou des lignes voisines) et vise la bonne occurrence. Limites : une ligne sans texte visible (code, maths, `#pagebreak()`) se rabat sur ses voisines ; un texte qui ne figure pas tel quel dans le PDF (généré, transformé) ou une page de l'aperçu sans texte repérable n'est pas retrouvé ; en édition d'un fichier inclus, l'occurrence visée peut être la première du document plutôt que la bonne.
|
|
21
|
+
|
|
22
|
+
### Document principal
|
|
23
|
+
|
|
24
|
+
Pour un projet de plusieurs fichiers (`#include`, `#import`), désigner le fichier racine avec **Fichier ▸ Document principal** :
|
|
25
|
+
|
|
26
|
+
- *Utiliser le document courant* (Ctrl+Maj+M) ;
|
|
27
|
+
- *Choisir…* un autre fichier ;
|
|
28
|
+
- *Aucun* : sans document principal, le document courant est compilé.
|
|
29
|
+
|
|
30
|
+
Le document principal est mémorisé d'une session à l'autre ; son nom apparaît dans la barre d'état et le titre. Les fichiers inclus sont édités normalement, l'aperçu montre toujours le résultat du document principal.
|
|
31
|
+
|
|
32
|
+
Un nouveau document (jamais enregistré) est écrit dans un dossier temporaire ; l'enregistrer pour l'utiliser comme principal.
|
|
33
|
+
|
|
34
|
+
### Plusieurs fenêtres
|
|
35
|
+
|
|
36
|
+
**Fichier ▸ Nouvelle fenêtre** (Ctrl+Maj+N) ouvre une fenêtre indépendante, avec son propre aperçu et son propre `typst watch`. Ouvrir un fichier le place dans la fenêtre courante si elle est encore vierge, sinon dans une nouvelle fenêtre ; un fichier déjà ouvert ramène sa fenêtre au premier plan. Le document principal n'est restauré qu'à la première fenêtre.
|
|
37
|
+
|
|
38
|
+
## Autres commandes
|
|
39
|
+
|
|
40
|
+
`python3 -I -m pytest -q tests` pour les tests ; `./packaging/build_app.sh [--open | --install]` pour construire le `.app` (py2app).
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "typsteditor"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Éditeur Typst de bureau : code à gauche, document en direct à droite (PyQt6, typst watch)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
authors = [{ name = "Emmanuel Desmontils" }]
|
|
14
|
+
keywords = ["typst", "editor", "pyqt6", "pdf"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Environment :: X11 Applications :: Qt",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"Natural Language :: French",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Topic :: Software Development :: Documentation",
|
|
22
|
+
]
|
|
23
|
+
dependencies = ["PyQt6>=6.8"]
|
|
24
|
+
|
|
25
|
+
[project.scripts]
|
|
26
|
+
typsteditor = "typsteditor.app:main"
|
|
27
|
+
|
|
28
|
+
[tool.setuptools]
|
|
29
|
+
packages = ["typsteditor"]
|
|
30
|
+
|
|
31
|
+
[tool.setuptools.package-data]
|
|
32
|
+
typsteditor = ["icon.svg"]
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.dynamic]
|
|
35
|
+
version = { attr = "typsteditor.version.__version__" }
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
5
|
+
|
|
6
|
+
from typsteditor.follow import candidates, fragments # noqa: E402
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_titre_et_texte():
|
|
10
|
+
assert fragments("= Bonjour Typst")[0] == "Bonjour Typst"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_ignore_code_et_maths():
|
|
14
|
+
assert fragments("#set page(width: 16cm)") == []
|
|
15
|
+
assert fragments("$ x^2 + y^2 $") == []
|
|
16
|
+
assert fragments("#pagebreak()") == []
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_voisines_et_rang():
|
|
20
|
+
lines = ["Alpha beta", "#pagebreak()", "Alpha beta", "#set x", ""]
|
|
21
|
+
got = list(candidates(lines, 3))
|
|
22
|
+
assert got[0][1:] == ("Alpha beta", 1) # ligne 2 : deuxième occurrence
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
5
|
+
|
|
6
|
+
from typsteditor.typst import parse_output # noqa: E402
|
|
7
|
+
|
|
8
|
+
ERR = """watching a.typ
|
|
9
|
+
writing to out.pdf
|
|
10
|
+
|
|
11
|
+
[18:21:30] compiled with errors
|
|
12
|
+
|
|
13
|
+
error: unclosed delimiter
|
|
14
|
+
┌─ a.typ:2:4
|
|
15
|
+
│
|
|
16
|
+
2 │ #foo(
|
|
17
|
+
│ ^
|
|
18
|
+
|
|
19
|
+
watching a.typ
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_succes():
|
|
24
|
+
assert parse_output("[18:21:28] compiled successfully in 3 ms\n") == ("ok", [])
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_en_cours():
|
|
28
|
+
assert parse_output("[18:21:28] compiling ...\n")[0] == "compiling"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_inconnu():
|
|
32
|
+
assert parse_output("watching a.typ\n") == ("unknown", [])
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_erreur():
|
|
36
|
+
state, diags = parse_output(ERR)
|
|
37
|
+
assert state == "errors"
|
|
38
|
+
assert (diags[0].file, diags[0].line, diags[0].column) == ("a.typ", 2, 4)
|
|
39
|
+
assert diags[0].message == "error: unclosed delimiter"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_dernier_cycle_seulement():
|
|
43
|
+
assert parse_output(ERR + "[18:22:00] compiled successfully in 1 ms\n")[0] == "ok"
|
|
File without changes
|
|
@@ -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()
|
|
@@ -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())
|
|
@@ -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>
|