Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pygments Support #294

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ __pycache__/
*$py.class

# other
pygments
pyTermTk-Docs
tests/test.dummy.py
*.swp
Expand Down
9 changes: 8 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true,
},{
"name": "Python: Current File with Args",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": true,
"args": ["tools/webExporter/js/ttkproxy.js"]
},{
"name": "Python: Test Player",
"type": "debugpy",
Expand All @@ -30,7 +38,6 @@
"env": {
"PYTHONPATH": "./tools"
}

},{
"name": "Python: TTk Designer Quick",
"type": "debugpy",
Expand Down
7 changes: 7 additions & 0 deletions TermTk/TTkGui/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import importlib.util

from .drag import *
from .textwrap1 import *
from .textcursor import *
from .textdocument import *
from .clipboard import *
from .tooltip import *

if importlib.util.find_spec('pygments'):
from .textdocument_highlight_pygments import *
else:
from .textdocument_highlight import *
8 changes: 8 additions & 0 deletions TermTk/TTkGui/textcursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,7 @@ def document(self) -> TTkTextDocument:
def replaceText(self, text:TTkString, moveCursor:bool=False) -> None:
# if there is no selection, just select the next n chars till the end of the line
# the newline is not replaced
self._document._acquire()
for p in self._properties:
if not p.hasSelection():
line = p.position.line
Expand All @@ -358,9 +359,11 @@ def replaceText(self, text:TTkString, moveCursor:bool=False) -> None:
pos = self._document._dataLines[line].nextPos(pos)
pos = min(size,pos)
p.anchor.set(line,pos)
self._document._release()
return self.insertText(text, moveCursor)

def insertText(self, text:TTkString, moveCursor:bool=False) -> None:
self._document._acquire()
_lineFirst = -1
if self.hasSelection():
_lineFirst, _lineRem, _lineAdd = self._removeSelectedText()
Expand Down Expand Up @@ -446,6 +449,7 @@ def insertText(self, text:TTkString, moveCursor:bool=False) -> None:
pp.anchor.line += diffLine
self._autoChanged = True
self._document.setChanged(True)
self._document._release()
self._document.contentsChanged.emit()
self._document.contentsChange.emit(lineFirst, lineRem, lineAdd)
self._autoChanged = False
Expand Down Expand Up @@ -552,14 +556,17 @@ def _alignPoint(point,st,en):

def removeSelectedText(self) -> None:
if not self.hasSelection(): return
self._document._acquire()
a,b,c = self._removeSelectedText()
self._autoChanged = True
self._document.setChanged(True)
self._document._release()
self._document.contentsChanged.emit()
self._document.contentsChange.emit(a,b,c)
self._autoChanged = False

def applyColor(self, color:TTkColor) -> None:
self._document._acquire()
for p in self._properties:
selSt = p.selectionStart()
selEn = p.selectionEnd()
Expand All @@ -570,6 +577,7 @@ def applyColor(self, color:TTkColor) -> None:
self._document._dataLines[l] = line.setColor(color=color, posFrom=pf, posTo=pt)
self._autoChanged = True
self._document.setChanged(True)
self._document._acquire()
self._document.contentsChanged.emit()
# self._document.contentsChange.emit(0,0,0)
self._autoChanged = True
Expand Down
121 changes: 71 additions & 50 deletions TermTk/TTkGui/textdocument.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,61 +22,64 @@

__all__ = ['TTkTextDocument']

from threading import Lock

from TermTk.TTkCore.log import TTkLog
from TermTk.TTkCore.signal import pyTTkSignal, pyTTkSlot
from TermTk.TTkCore.string import TTkString
from TermTk.TTkCore.color import TTkColor

class TTkTextDocument():
'''
Undo,Redo Logic

Old:

::

_snapshotId: = last saved/undo/redo state
3 = doc4
_snapshots:
[doc1, doc2, doc3, doc4, doc5, doc6, . . .]

New:

::

SnapshotId:
2
Snapshots: _lastSnap _dataLines (unstaged)
╒═══╕ ╒═══╕ ╒═══╕ ╒═══╕ ╒═══╕ ╒═══╕
│ 0 │ │ 1 │ │ 2 │ │ 3 │ │ 4 │ │ 5 │
└───┘ └───┘ └───┘ └───┘ └───┘ └───┘
Cursors:
c0, c1, c2, c3, c4 = _lastCursor
Diffs:
[ d01, d12, d23, d34 ] = Forward Diffs
[ d10, d21, d32, d43 ] = Backward Diffs
Slices: = common txt slices between snapshots
[ s01, s12, s23, s34 ]

::

Data Structure
╔═══════════════╗ ╔═══════════════╗
║ Snapshot B ║ ┌─────────────>║ Snapshot C ║
╟───────────────╢ │ ╟───────────────╢
║ _nextDiff ║──────┐ │ ║ _nextDiff ║───> Next snapshot
┌───║ _prevDiff ║ │ │ ┌───║ _prevDiff ║ or Null if at the end
│ ╚═══════════════╝ │ │ │ ╚═══════════════╝
V A V │ V
╔═══════════════╗ │ ╔═══════════════╗ ╔═══════════════╗
║ Diff B->A ║ │ ║ Diff B->C ║ ║ Diff C->B ║
╟───────────────╢ │ ╟───────────────╢ ╟───────────────╢
║ slice = txtBA ║ │ ║ slice = txtBC ║ ║ slice = txtBA ║
║ snap ║ │ ║ snap ║ ║ snap ║
╚═══════════════╝ │ ╚═══════════════╝ ╚═══════════════╝
│ │
└─────────────────────────────┘

'''
# '''
# Undo,Redo Logic
#
# Old:
#
# ::
#
# _snapshotId: = last saved/undo/redo state
# 3 = doc4
# _snapshots:
# [doc1, doc2, doc3, doc4, doc5, doc6, . . .]
#
# New:
#
# ::
#
# SnapshotId:
# 2
# Snapshots: _lastSnap _dataLines (unstaged)
# ╒═══╕ ╒═══╕ ╒═══╕ ╒═══╕ ╒═══╕ ╒═══╕
# │ 0 │ │ 1 │ │ 2 │ │ 3 │ │ 4 │ │ 5 │
# └───┘ └───┘ └───┘ └───┘ └───┘ └───┘
# Cursors:
# c0, c1, c2, c3, c4 = _lastCursor
# Diffs:
# [ d01, d12, d23, d34 ] = Forward Diffs
# [ d10, d21, d32, d43 ] = Backward Diffs
# Slices: = common txt slices between snapshots
# [ s01, s12, s23, s34 ]
#
# ::
#
# Data Structure
# ╔═══════════════╗ ╔═══════════════╗
# ║ Snapshot B ║ ┌─────────────>║ Snapshot C ║
# ╟───────────────╢ │ ╟───────────────╢
# ║ _nextDiff ║──────┐ │ ║ _nextDiff ║───> Next snapshot
# ┌───║ _prevDiff ║ │ │ ┌───║ _prevDiff ║ or Null if at the end
# │ ╚═══════════════╝ │ │ │ ╚═══════════════╝
# V A V │ V
# ╔═══════════════╗ │ ╔═══════════════╗ ╔═══════════════╗
# ║ Diff B->A ║ │ ║ Diff B->C ║ ║ Diff C->B ║
# ╟───────────────╢ │ ╟───────────────╢ ╟───────────────╢
# ║ slice = txtBA ║ │ ║ slice = txtBC ║ ║ slice = txtBA ║
# ║ snap ║ │ ║ snap ║ ║ snap ║
# ╚═══════════════╝ │ ╚═══════════════╝ ╚═══════════════╝
# │ │
# └─────────────────────────────┘
#
# '''
class _snapDiff():
'''
Doc:
Expand Down Expand Up @@ -122,21 +125,27 @@ def _getSnap(self, lines, d):
'_dataLines', '_modified',
'_snap', '_snapChanged',
'_lastSnap', '_lastCursor',
'_backgroundColor',
'_docMutex',
# Signals
'contentsChange', 'contentsChanged',
'formatChanged',
'cursorPositionChanged',
'undoAvailable', 'redoAvailable', 'undoCommandAdded',
'modificationChanged'
)
def __init__(self, *, text:TTkString=" ") -> None:
from TermTk.TTkGui.textcursor import TTkTextCursor
self._docMutex = Lock()
self.cursorPositionChanged = pyTTkSignal(TTkTextCursor)
self.contentsChange = pyTTkSignal(int,int,int) # int line, int linesRemoved, int linesAdded
self.contentsChanged = pyTTkSignal()
self.formatChanged = pyTTkSignal()
self.undoAvailable = pyTTkSignal(bool)
self.redoAvailable = pyTTkSignal(bool)
self.undoCommandAdded = pyTTkSignal()
self.modificationChanged = pyTTkSignal(bool)
self._backgroundColor = TTkColor.RST
text = text
self._dataLines = [TTkString(t) for t in text.split('\n')]
self._modified = False
Expand Down Expand Up @@ -170,6 +179,12 @@ def __init__(self, *, text:TTkString=" ") -> None:
# z1 = l1+a1 + (a2-r2)
# z2 = l2+a2

def _acquire(self) -> None:
self._docMutex.acquire()

def _release(self) -> None:
self._docMutex.release()

@staticmethod
def _mergeChangesSlices(ch1,ch2):
l1,r1,a1 = ch1
Expand Down Expand Up @@ -221,22 +236,26 @@ def setText(self, text):
remLines = len(self._dataLines)
if not isinstance(text, str) and not isinstance(text,TTkString):
text=str(text)
self._acquire()
self._dataLines = [TTkString(t) for t in text.split('\n')]
self._modified = False
self._lastSnap = self._dataLines.copy()
self._snap = TTkTextDocument._snapshot(self._lastCursor, None, None)
self._release()
self.contentsChanged.emit()
self.contentsChange.emit(0,remLines,len(self._dataLines))
self._snapChanged = None

def appendText(self, text):
if type(text) == str:
text = TTkString() + text
self._acquire()
oldLines = len(self._dataLines)
self._dataLines += text.split('\n')
self._modified = False
self._lastSnap = self._dataLines.copy()
self._snap = TTkTextDocument._snapshot(self._lastCursor, None, None)
self._release()
self.contentsChanged.emit()
self.contentsChange.emit(oldLines,0,len(self._dataLines)-oldLines)
self._snapChanged = None
Expand Down Expand Up @@ -292,10 +311,12 @@ def _restoreSnapshotDiff(self, next=True):
(not next and not self._snap._prevDiff) ):
return None

self._acquire()
if next:
self._snap = self._snap.getNextSnap(self._dataLines)
else:
self._snap = self._snap.getPrevSnap(self._dataLines)
self._release()

self._lastSnap = self._dataLines.copy()
self._lastCursor = self._snap._cursor.copy()
Expand Down
57 changes: 57 additions & 0 deletions TermTk/TTkGui/textdocument_highlight.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# MIT License
#
# Copyright (c) 2024 Eugenio Parodi <ceccopierangiolieugenio AT googlemail DOT com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

__all__ = ['TextDocumentHighlight']

from TermTk.TTkCore.log import TTkLog
from TermTk.TTkCore.signal import pyTTkSlot, pyTTkSignal
from TermTk.TTkGui import TTkTextDocument

class TextDocumentHighlight(TTkTextDocument):
__slots__ = (
#Signals
'highlightUpdate')
def __init__(self, *args, **kwargs):
self.highlightUpdate = pyTTkSignal()
super().__init__(*args, **kwargs)
TTkLog.warn("Pygments not found!!!")

@staticmethod
def getStyles() -> list[str]:
return []

@staticmethod
def getLexers() -> list[str]:
return []

@pyTTkSlot(str)
def setStyle(self, alias:str) -> None:
pass

@pyTTkSlot(str)
def setLexer(self, alias:str) -> None:
pass

@pyTTkSlot(str)
def guessLexerFromFilename(self, fileName:str) -> None:
pass

Loading
Loading