-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPyEdit2.py
1613 lines (1411 loc) · 64.4 KB
/
PyEdit2.py
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
#!/usr/bin/python3
# -- coding: utf-8 --
# syntax_py https://wiki.python.org/moin/PyQt/Python%20syntax%20highlighting
# "© 2017 Axel Schneider <[email protected]> https://goodoldsongs.jimdo.com/"
from __future__ import print_function
from PyQt5.QtWidgets import (QPlainTextEdit, QWidget, QVBoxLayout, QApplication, QFileDialog, QMessageBox, QLabel, QCompleter,
QHBoxLayout, QTextEdit, QToolBar, QComboBox, QAction, QLineEdit, QDialog, QPushButton, QSizePolicy,
QToolButton, QMenu, QMainWindow, QInputDialog, QColorDialog, QStatusBar, QSystemTrayIcon)
from PyQt5.QtGui import (QIcon, QPainter, QTextFormat, QColor, QTextCursor, QKeySequence, QClipboard, QTextDocument,
QPixmap, QStandardItemModel, QStandardItem, QCursor)
from PyQt5.QtCore import (Qt, QVariant, QRect, QDir, QFile, QFileInfo, QTextStream, QSettings, QTranslator, QLocale,
QProcess, QPoint, QSize, QCoreApplication, QStringListModel, QLibraryInfo)
from PyQt5 import QtPrintSupport
from syntax_py import *
import os
#import sys
lineBarColor = QColor("#d3d7cf")
lineHighlightColor = QColor("#fce94f")
tab = chr(9)
eof = "\n"
iconsize = QSize(16, 16)
#####################################################################
class TextEdit(QPlainTextEdit):
def __init__(self, parent=None):
super(TextEdit, self).__init__(parent)
self.installEventFilter(self)
self._completer = None
def setCompleter(self, c):
if self._completer is not None:
self._completer.activated.disconnect()
self._completer = c
c.popup().setStyleSheet("background-color: #555753; color: #eeeeec; font-size: 8pt; selection-background-color: #4e9a06;")
c.setWidget(self)
c.setCompletionMode(QCompleter.PopupCompletion)
c.activated.connect(self.insertCompletion)
def completer(self):
return self._completer
def insertCompletion(self, completion):
if self._completer.widget() is not self:
return
tc = self.textCursor()
extra = len(completion) - len(self._completer.completionPrefix())
tc.movePosition(QTextCursor.Left)
tc.movePosition(QTextCursor.EndOfWord)
ins = completion[-extra:]
tc.insertText(ins)
self.setTextCursor(tc)
def textUnderCursor(self):
tc = self.textCursor()
tc.select(QTextCursor.WordUnderCursor)
return tc.selectedText()
def focusInEvent(self, e):
if self._completer is not None:
self._completer.setWidget(self)
super(TextEdit, self).focusInEvent(e)
def keyPressEvent(self, e):
if e.key() == Qt.Key_Tab:
self.textCursor().insertText(" ")
return
if self._completer is not None and self._completer.popup().isVisible():
# The following keys are forwarded by the completer to the widget.
if e.key() in (Qt.Key_Enter, Qt.Key_Return):
e.ignore()
# Let the completer do default behavior.
return
isShortcut = ((e.modifiers() & Qt.ControlModifier) != 0 and e.key() == Qt.Key_Escape)
if self._completer is None or not isShortcut:
# Do not process the shortcut when we have a completer.
super(TextEdit, self).keyPressEvent(e)
ctrlOrShift = e.modifiers() & (Qt.ControlModifier | Qt.ShiftModifier)
if self._completer is None or (ctrlOrShift and len(e.text()) == 0):
return
eow = "~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-="
hasModifier = (e.modifiers() != Qt.NoModifier) and not ctrlOrShift
completionPrefix = self.textUnderCursor()
if not isShortcut and (hasModifier or len(e.text()) == 0 or len(completionPrefix) < 2 or e.text()[-1] in eow):
self._completer.popup().hide()
return
if completionPrefix != self._completer.completionPrefix():
self._completer.setCompletionPrefix(completionPrefix)
self._completer.popup().setCurrentIndex(
self._completer.completionModel().index(0, 0))
cr = self.cursorRect()
cr.setWidth(self._completer.popup().sizeHintForColumn(0) + self._completer.popup().verticalScrollBar().sizeHint().width())
self._completer.complete(cr)
####################################################################
class NumberBar(QWidget):
def __init__(self, parent = None):
super(NumberBar, self).__init__(parent)
self.editor = parent
layout = QVBoxLayout()
self.editor.blockCountChanged.connect(self.update_width)
self.editor.updateRequest.connect(self.update_on_scroll)
self.update_width('1')
def update_on_scroll(self, rect, scroll):
if self.isVisible():
if scroll:
self.scroll(0, scroll)
else:
self.update()
def update_width(self, string):
width = self.fontMetrics().width(str(string)) + 8
if self.width() != width:
self.setFixedWidth(width)
def paintEvent(self, event):
if self.isVisible():
block = self.editor.firstVisibleBlock()
height = self.fontMetrics().height()
number = block.blockNumber()
painter = QPainter(self)
painter.fillRect(event.rect(), lineBarColor)
painter.drawRect(0, 0, event.rect().width() - 1, event.rect().height() - 1)
font = painter.font()
current_block = self.editor.textCursor().block().blockNumber() + 1
condition = True
while block.isValid() and condition:
block_geometry = self.editor.blockBoundingGeometry(block)
offset = self.editor.contentOffset()
block_top = block_geometry.translated(offset).top()
number += 1
rect = QRect(0, block_top + 2, self.width() - 5, height)
if number == current_block:
font.setBold(True)
else:
font.setBold(False)
painter.setFont(font)
painter.drawText(rect, Qt.AlignRight, '%i'%number)
if block_top > event.rect().bottom():
condition = False
block = block.next()
painter.end()
class myEditor(QMainWindow):
def __init__(self, parent = None):
super(myEditor, self).__init__(parent)
self.words = []
self.root = QFileInfo.path(QFileInfo(QCoreApplication.arguments()[0]))
self.wordList = []
self.bookmarkslist = []
print("self.root is: ", self.root)
self.appfolder = self.root
self.openPath = ""
self.statusBar().showMessage(self.appfolder)
self.lineLabel = QLabel("line")
self.statusBar().addPermanentWidget(self.lineLabel)
self.MaxRecentFiles = 15
self.windowList = []
self.recentFileActs = []
self.settings = QSettings("PyEdit", "PyEdit")
self.dirpath = QDir.homePath() + "/Dokumente/python_files/"
self.setAttribute(Qt.WA_DeleteOnClose)
self.setWindowIcon(QIcon.fromTheme("python3"))
# Editor Widget ...
self.editor = TextEdit()
self.completer = QCompleter(self)
self.completer.setModel(self.modelFromFile(self.root + '/resources/wordlist.txt'))
self.completer.setModelSorting(QCompleter.CaseInsensitivelySortedModel)
self.completer.setCaseSensitivity(Qt.CaseInsensitive)
self.completer.setFilterMode(Qt.MatchContains)
self.completer.setWrapAround(False)
self.completer.setCompletionRole(Qt.DisplayRole)
self.editor.setCompleter(self.completer)
if int(sys.version[0]) > 2:
self.setStyleSheet(stylesheet2(self))
# self.editor.setTabStopWidth(20)
self.editor.cursorPositionChanged.connect(self.cursorPositionChanged)
self.extra_selections = []
self.mainText = "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n"
self.fname = ""
self.filename = ""
self.mypython = "2"
self.shellWin = QTextEdit()
self.shellWin.setContextMenuPolicy(Qt.CustomContextMenu)
self.shellWin.setFixedHeight(90)
# Line Numbers ...
self.numbers = NumberBar(self.editor)
self.createActions()
# Syntax Highlighter ...
self.highlighter = Highlighter(self.editor.document())
# Laying out...
layoutH = QHBoxLayout()
layoutH.setSpacing(1.5)
layoutH.addWidget(self.numbers)
layoutH.addWidget(self.editor)
### systray
self.createTrayIcon()
self.trayIcon.show()
### statusbar
self.statusBar()
self.statusBar().showMessage('Welcome')
### begin toolbar
tb = self.addToolBar("File")
tb.setContextMenuPolicy(Qt.PreventContextMenu)
tb.setIconSize(QSize(iconsize))
tb.setMovable(False)
tb.setAllowedAreas(Qt.AllToolBarAreas)
tb.setFloatable(False)
### file buttons
self.newAct = QAction("&New", self, shortcut=QKeySequence.New,
statusTip="new file", triggered=self.newFile)
self.newAct.setIcon(QIcon.fromTheme(self.root + "/icons/new24"))
tb.addAction(self.newAct)
self.openAct = QAction("&Open", self, shortcut=QKeySequence.Open,
statusTip="open file", triggered=self.openFile)
self.openAct.setIcon(QIcon.fromTheme(self.root + "/icons/open24"))
tb.addAction(self.openAct)
self.saveAct = QAction("&Save", self, shortcut=QKeySequence.Save,
statusTip="save file", triggered=self.fileSave)
self.saveAct.setIcon(QIcon.fromTheme(self.root + "/icons/floppy24"))
tb.addAction(self.saveAct)
self.saveAsAct = QAction("&Save as ...", self, shortcut=QKeySequence.SaveAs,
statusTip="save file as ...", triggered=self.fileSaveAs)
self.saveAsAct.setIcon(QIcon.fromTheme(self.root + "/icons/floppy25"))
tb.addAction(self.saveAsAct)
self.jumpToAct = QAction("go to Definition", self, shortcut="F12",
statusTip="go to def", triggered=self.gotoBookmarkFromMenu)
self.jumpToAct.setIcon(QIcon.fromTheme("go-next"))
### comment buttons
tb.addSeparator()
self.commentAct = QAction("#comment Line", self, shortcut="F2",
statusTip="comment Line (F2)", triggered=self.commentLine)
self.commentAct.setIcon(QIcon.fromTheme(self.root + "/icons/comment"))
tb.addAction(self.commentAct)
self.uncommentAct = QAction("uncomment Line", self, shortcut="F3",
statusTip="uncomment Line (F3)", triggered=self.uncommentLine)
self.uncommentAct.setIcon(QIcon.fromTheme(self.root + "/icons/uncomment"))
tb.addAction(self.uncommentAct)
self.commentBlockAct = QAction("comment Block", self, shortcut="F6",
statusTip="comment selected block (F6)", triggered=self.commentBlock)
self.commentBlockAct.setIcon(QIcon.fromTheme(self.root + "/icons/commentBlock"))
tb.addAction(self.commentBlockAct)
self.uncommentBlockAct = QAction("uncomment Block (F7)", self, shortcut="F7",
statusTip="uncomment selected block (F7)", triggered=self.uncommentBlock)
self.uncommentBlockAct.setIcon(QIcon.fromTheme(self.root + "/icons/uncommentBlock"))
tb.addAction(self.uncommentBlockAct)
### color chooser
tb.addSeparator()
tb.addAction(QIcon.fromTheme(self.root + "/icons/color1"),"insert QColor", self.insertColor)
tb.addSeparator()
tb.addAction(QIcon.fromTheme("preferences-color"),"change Color", self.changeColor)
###insert templates
tb.addSeparator()
self.templates = QComboBox()
self.templates.setFixedWidth(120)
self.templates.setToolTip("insert template")
self.templates.activated[str].connect(self.insertTemplate)
tb.addWidget(self.templates)
### path python buttons
tb.addSeparator()
self.py2Act = QAction("run in Python 2 (F4)", self, shortcut="F4",
statusTip="run in Python 2 (F4)", triggered=self.runPy2)
self.py2Act.setIcon(QIcon.fromTheme("python"))
tb.addAction(self.py2Act)
self.py3Act = QAction("run in Python 3.6 (F6)", self, shortcut="F6",
statusTip="run in Python 3 (F5)", triggered=self.runPy3)
self.py3Act.setIcon(QIcon.fromTheme(self.root + "/icons/python3"))
tb.addAction(self.py3Act)
tb.addSeparator()
self.termAct = QAction("run in Terminal",
statusTip="run in Terminal", triggered=self.runInTerminal)
self.termAct.setIcon(QIcon.fromTheme("x-terminal-emulator"))
tb.addAction(self.termAct)
tb.addSeparator()
tb.addAction(QIcon.fromTheme("edit-clear"),"clear Output Label", self.clearLabel)
tb.addSeparator()
### print preview
self.printPreviewAct = QAction("Print Preview", self, shortcut="Ctrl+Shift+P",
statusTip="Preview Document", triggered=self.handlePrintPreview)
self.printPreviewAct.setIcon(QIcon.fromTheme("document-print-preview"))
tb.addAction(self.printPreviewAct)
### print
self.printAct = QAction("Print", self, shortcut=QKeySequence.Print,
statusTip="Print Document", triggered=self.handlePrint)
self.printAct.setIcon(QIcon.fromTheme("document-print"))
tb.addAction(self.printAct)
### about buttons
tb.addSeparator()
tb.addAction(QIcon.fromTheme(self.root + "/icons/info2"),"&About PyEdit", self.about)
tb.addAction(QAction(QIcon.fromTheme("process-stop"), "kill python", self, triggered=self.killPython))
### show / hide shellWin
tb.addSeparator()
self.shToggleAction = QAction("show/ hide shell window", self,
statusTip="show/ hide shell window", triggered=self.handleShellWinToggle)
self.shToggleAction.setIcon(QIcon.fromTheme("terminal"))
self.shToggleAction.setCheckable(True)
tb.addAction(self.shToggleAction)
### thunar
tb.addSeparator()
self.fmanAction = QAction("open Filemanager", self,
statusTip="open Filemanager", triggered=self.handleFM)
self.fmanAction.setIcon(QIcon.fromTheme("file-manager"))
tb.addAction(self.fmanAction)
### TextEdit
self.texteditAction = QAction("open selected Text in QTextEdit", self,
statusTip="open selected Text in QTextEdit", triggered=self.handleTextEdit)
self.texteditAction.setIcon(QIcon.fromTheme("text-editor"))
tb.addAction(self.texteditAction)
### exit button
tb.addSeparator()
## addStretch
empty = QWidget();
empty.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Preferred);
tb.addWidget(empty)
self.exitAct = QAction("exit", self, shortcut=QKeySequence.Quit,
statusTip="Exit", triggered=self.handleQuit)
self.exitAct.setIcon(QIcon.fromTheme(self.root + "/icons/quit"))
tb.addAction(self.exitAct)
### end toolbar
self.indentAct = QAction(QIcon.fromTheme(self.root + "/icons/format-indent-more"), "indent more", self, triggered = self.indentLine, shortcut = "F8")
self.indentLessAct = QAction(QIcon.fromTheme(self.root + "/icons/format-indent-less"), "indent less", self, triggered = self.indentLessLine, shortcut = "F9")
### find / replace toolbar
self.addToolBarBreak()
tbf = self.addToolBar("Find")
tbf.setContextMenuPolicy(Qt.PreventContextMenu)
tbf.setMovable(False)
tbf.setIconSize(QSize(iconsize))
self.findfield = QLineEdit()
self.findfield.addAction(QIcon.fromTheme("edit-find"), QLineEdit.LeadingPosition)
self.findfield.setClearButtonEnabled(True)
self.findfield.setFixedWidth(150)
self.findfield.setPlaceholderText("find")
self.findfield.setToolTip("press RETURN to find")
self.findfield.setText("")
ft = self.findfield.text()
self.findfield.returnPressed.connect(self.findText)
tbf.addWidget(self.findfield)
self.replacefield = QLineEdit()
self.replacefield.addAction(QIcon.fromTheme("edit-find-and-replace"), QLineEdit.LeadingPosition)
self.replacefield.setClearButtonEnabled(True)
self.replacefield.setFixedWidth(150)
self.replacefield.setPlaceholderText("replace with")
self.replacefield.setToolTip("press RETURN to replace the first")
self.replacefield.returnPressed.connect(self.replaceOne)
tbf.addSeparator()
tbf.addWidget(self.replacefield)
tbf.addSeparator()
self.repAllAct = QPushButton("replace all")
self.repAllAct.setFixedWidth(100)
self.repAllAct.setIcon(QIcon.fromTheme("gtk-find-and-replace"))
self.repAllAct.setStatusTip("replace all")
self.repAllAct.clicked.connect(self.replaceAll)
tbf.addWidget(self.repAllAct)
tbf.addSeparator()
tbf.addAction(self.indentAct)
tbf.addAction(self.indentLessAct)
tbf.addSeparator()
self.gotofield = QLineEdit()
self.gotofield.addAction(QIcon.fromTheme("next"), QLineEdit.LeadingPosition)
self.gotofield.setClearButtonEnabled(True)
self.gotofield.setFixedWidth(120)
self.gotofield.setPlaceholderText("go to line")
self.gotofield.setToolTip("press RETURN to go to line")
self.gotofield.returnPressed.connect(self.gotoLine)
tbf.addWidget(self.gotofield)
tbf.addSeparator()
self.bookmarks = QComboBox()
self.bookmarks.setFixedWidth(280)
self.bookmarks.setToolTip("go to bookmark")
self.bookmarks.activated[str].connect(self.gotoBookmark)
tbf.addWidget(self.bookmarks)
self.bookAct = QAction("add Bookmark", self,
statusTip="add Bookmark", triggered=self.addBookmark)
self.bookAct.setIcon(QIcon.fromTheme("previous"))
tbf.addAction(self.bookAct)
tbf.addSeparator()
self.bookrefresh = QAction("update Bookmarks", self,
statusTip="update Bookmarks", triggered=self.findBookmarks)
self.bookrefresh.setIcon(QIcon.fromTheme("view-refresh"))
tbf.addAction(self.bookrefresh)
tbf.addAction(QAction(QIcon.fromTheme("document-properties"), "check && reindent Text", self, triggered=self.reindentText))
layoutV = QVBoxLayout()
bar=self.menuBar()
self.filemenu=bar.addMenu("File")
self.separatorAct = self.filemenu.addSeparator()
self.filemenu.addAction(self.newAct)
self.filemenu.addAction(self.openAct)
self.filemenu.addAction(self.saveAct)
self.filemenu.addAction(self.saveAsAct)
self.filemenu.addSeparator()
for i in range(self.MaxRecentFiles):
self.filemenu.addAction(self.recentFileActs[i])
self.updateRecentFileActions()
self.filemenu.addSeparator()
self.clearRecentAct = QAction("clear Recent Files List", self, triggered=self.clearRecentFiles)
self.clearRecentAct.setIcon(QIcon.fromTheme("edit-clear"))
self.filemenu.addAction(self.clearRecentAct)
self.filemenu.addSeparator()
self.filemenu.addAction(self.exitAct)
editmenu = bar.addMenu("Edit")
editmenu.addAction(QAction(QIcon.fromTheme('edit-undo'), "Undo", self, triggered = self.editor.undo, shortcut = "Ctrl+u"))
editmenu.addAction(QAction(QIcon.fromTheme('edit-redo'), "Redo", self, triggered = self.editor.redo, shortcut = "Shift+Ctrl+u"))
editmenu.addSeparator()
editmenu.addAction(QAction(QIcon.fromTheme('edit-copy'), "Copy", self, triggered = self.editor.copy, shortcut = "Ctrl+c"))
editmenu.addAction(QAction(QIcon.fromTheme('edit-cut'), "Cut", self, triggered = self.editor.cut, shortcut = "Ctrl+x"))
editmenu.addAction(QAction(QIcon.fromTheme('edit-paste'), "Paste", self, triggered = self.editor.paste, shortcut = "Ctrl+v"))
editmenu.addAction(QAction(QIcon.fromTheme('edit-delete'), "Delete", self, triggered = self.editor.cut, shortcut = "Del"))
editmenu.addSeparator()
editmenu.addAction(QAction(QIcon.fromTheme('edit-select-all'), "Select All", self, triggered = self.editor.selectAll, shortcut = "Ctrl+a"))
editmenu.addSeparator()
editmenu.addAction(self.commentAct)
editmenu.addAction(self.uncommentAct)
editmenu.addSeparator()
editmenu.addAction(self.commentBlockAct)
editmenu.addAction(self.uncommentBlockAct)
editmenu.addSeparator()
editmenu.addAction(self.py2Act)
editmenu.addAction(self.py3Act)
editmenu.addSeparator()
editmenu.addAction(self.jumpToAct)
editmenu.addSeparator()
editmenu.addAction(self.indentAct)
editmenu.addAction(self.indentLessAct)
layoutV.addLayout(layoutH)
self.shellWin.setMinimumHeight(28)
self.shellWin.setStyleSheet(stylesheet2(self))
self.shellWin.customContextMenuRequested.connect(self.shellWincontextMenuRequested)
layoutV.addWidget(self.shellWin)
### main window
mq = QWidget(self)
mq.setLayout(layoutV)
self.setCentralWidget(mq)
# Event Filter ...
# self.installEventFilter(self)
self.editor.setFocus()
self.cursor = QTextCursor()
self.editor.setTextCursor(self.cursor)
self.editor.setPlainText(self.mainText)
self.editor.moveCursor(self.cursor.End)
self.editor.document().modificationChanged.connect(self.setWindowModified)
# Brackets ExtraSelection ...
self.left_selected_bracket = QTextEdit.ExtraSelection()
self.right_selected_bracket = QTextEdit.ExtraSelection()
### shell settings
self.process = QProcess(self)
self.process.setProcessChannelMode(QProcess.MergedChannels)
self.process.readyRead.connect(self.dataReady)
self.process.started.connect(lambda: self.shellWin.append("starting shell"))
self.process.finished.connect(lambda: self.shellWin.append("shell ended"))
self.editor.setContextMenuPolicy(Qt.CustomContextMenu)
self.editor.customContextMenuRequested.connect(self.contextMenuRequested)
self.loadTemplates()
self.readSettings()
self.statusBar().showMessage("self.root is: " + self.root, 0)
def runInTerminal(self):
print("running in terminal")
if self.editor.toPlainText() == "":
self.statusBar().showMessage("no Code!")
return
if not self.editor.toPlainText() == self.mainText:
if self.filename:
# self.mypython = "3"
self.statusBar().showMessage("running " + self.filename + " in Lua")
self.fileSave()
self.shellWin.clear()
dname = QFileInfo(self.filename).filePath().replace(QFileInfo(self.filename).fileName(), "")
cmd = str('xfce4-terminal -e "python3 ' + dname + self.strippedName(self.filename) + '"')
self.statusBar().showMessage(str(dname))
QProcess().execute("cd '" + dname + "'")
print(cmd)
self.process.start(cmd)
else:
self.filename = "/tmp/tmp.py"
self.fileSave()
self.runInTerminal()
else:
self.statusBar().showMessage("no code to run")
def handleShellWinToggle(self):
if self.shellWin.isVisible():
self.shellWin.setVisible(False)
else:
self.shellWin.setVisible(True)
def handleFM(self):
if "/" in self.shellWin.textCursor().selectedText():
QProcess.startDetached("thunar", [self.shellWin.textCursor().selectedText()])
else:
QProcess.startDetached("thunar")
def handleTextEdit(self):
dir = os.path.dirname(sys.argv[0])
filename = "QTextEdit.py"
text = self.editor.textCursor().selectedText()
f = os.path.join(dir, filename)
cmd = f + " '" + text + "'"
print(cmd)
QProcess.startDetached(f, [text])
def killPython(self):
if int(sys.version[0]) < 3:
os.system("killall python")
else:
os.system("killall python3")
def keyPressEvent(self, event):
if self.editor.hasFocus():
if event.key() == Qt.Key_F10:
self.findNextWord()
def cursorPositionChanged(self):
line = self.editor.textCursor().blockNumber() + 1
pos = self.editor.textCursor().positionInBlock()
self.lineLabel.setText("line " + str(line) + " - position " + str(pos))
def textColor(self):
col = QColorDialog.getColor(QColor("#" + self.editor.textCursor().selectedText()), self)
self.pix.fill(col)
if not col.isValid():
return
else:
colorname = 'QColor("' + col.name() + '")'
self.editor.textCursor().insertText(colorname)
self.pix.fill(col)
def loadTemplates(self):
folder = self.appfolder + "/templates"
if QDir().exists(folder):
self.currentDir = QDir(folder)
count = self.currentDir.count()
fileName = "*"
files = self.currentDir.entryList([fileName],
QDir.Files | QDir.NoSymLinks)
for i in range(len(files)):
file = (files[i])
if file.endswith(".txt"):
self.templates.addItem(file.replace(self.appfolder + "/templates", "").replace(".txt", ""))
def Test(self):
self.editor.selectAll()
def reindentText(self):
if self.editor.toPlainText() == "" or self.editor.toPlainText() == self.mainText:
self.statusBar().showMessage("no code to reindent")
else:
self.editor.selectAll()
tab = "\t"
oldtext = self.editor.textCursor().selectedText()
newtext = oldtext.replace(tab, " ")
self.editor.textCursor().insertText(newtext)
self.statusBar().showMessage("code reindented")
def insertColor(self):
col = QColorDialog.getColor(QColor("#000000"), self)
if not col.isValid():
return
else:
colorname = 'QColor("' + col.name() + '")'
self.editor.textCursor().insertText(colorname)
def changeColor(self):
if not self.editor.textCursor().selectedText() == "":
col = QColorDialog.getColor(QColor("#" + self.editor.textCursor().selectedText()), self)
if not col.isValid():
return
else:
colorname = col.name()
self.editor.textCursor().insertText(colorname.replace("#", ""))
else:
col = QColorDialog.getColor(QColor("black"), self)
if not col.isValid():
return
else:
colorname = col.name()
self.editor.textCursor().insertText(colorname)
### QPlainTextEdit contextMenu
def contextMenuRequested(self, point):
cmenu = QMenu()
cmenu = self.editor.createStandardContextMenu()
cmenu.addSeparator()
cmenu.addAction(self.jumpToAct)
cmenu.addSeparator()
if not self.editor.textCursor().selectedText() == "":
cmenu.addAction(QIcon.fromTheme("gtk-find-and-replace"),"replace all occurrences with", self.replaceThis)
cmenu.addSeparator()
cmenu.addAction(QIcon.fromTheme("zeal"),"show help with 'zeal'", self.showZeal)
cmenu.addAction(QIcon.fromTheme("firefox"),"find with 'firefox'", self.findWithFirefox)
cmenu.addAction(QIcon.fromTheme("gtk-find-"),"find this (F10)", self.findNextWord)
cmenu.addAction(self.texteditAction)
cmenu.addSeparator()
cmenu.addAction(self.py2Act)
cmenu.addAction(self.py3Act)
cmenu.addSeparator()
cmenu.addAction(self.commentAct)
cmenu.addAction(self.uncommentAct)
cmenu.addSeparator()
if not self.editor.textCursor().selectedText() == "":
cmenu.addAction(self.commentBlockAct)
cmenu.addAction(self.uncommentBlockAct)
cmenu.addSeparator()
cmenu.addAction(self.indentAct)
cmenu.addAction(self.indentLessAct)
cmenu.addSeparator()
cmenu.addAction(QIcon.fromTheme("preferences-color"),"insert QColor", self.insertColor)
cmenu.addSeparator()
cmenu.addAction(QIcon.fromTheme("preferences-color"),"change Color", self.changeColor)
cmenu.exec_(self.editor.mapToGlobal(point))
### shellWin contextMenu
def shellWincontextMenuRequested(self, point):
shellWinMenu = QMenu()
shellWinMenu = self.shellWin.createStandardContextMenu()
# shellWinMenu.addAction(QAction(QIcon.fromTheme('edit-copy'), "Copy", self, triggered = self.shellWin.copy, shortcut = "Ctrl+c"))
shellWinMenu.addSeparator()
shellWinMenu.addAction(QIcon.fromTheme("zeal"),"show help with 'zeal'", self.showZeal_shell)
shellWinMenu.addAction(QIcon.fromTheme("firefox"),"find with 'firefox'", self.findWithFirefox_shell)
if "/" in self.shellWin.textCursor().selectedText():
shellWinMenu.addAction(self.fmanAction)
shellWinMenu.exec_(self.shellWin.mapToGlobal(point))
def replaceThis(self):
rtext = self.editor.textCursor().selectedText()
text = QInputDialog.getText(self, "replace with","replace '" + rtext + "' with:", QLineEdit.Normal, "")
oldtext = self.editor.document().toPlainText()
if not (text[0] == ""):
newtext = oldtext.replace(rtext, text[0])
self.editor.setPlainText(newtext)
self.setModified(True)
def showZeal(self):
if self.editor.textCursor().selectedText() == "":
tc = self.editor.textCursor()
tc.select(QTextCursor.WordUnderCursor)
rtext = tc.selectedText()
print(rtext)
else:
rtext = self.editor.textCursor().selectedText() ##.replace(".", "::")
cmd = "zeal " + str(rtext)
QProcess().startDetached(cmd)
def findWithFirefox(self):
if self.editor.textCursor().selectedText() == "":
tc = self.editor.textCursor()
tc.select(QTextCursor.WordUnderCursor)
rtext = tc.selectedText()
else:
rtext = "python%20" + self.editor.textCursor().selectedText().replace(" ", "%20")
url = "https://www.google.com/search?q=" + rtext
QProcess.startDetached("firefox " + url)
def showZeal_shell(self):
if not self.shellWin.textCursor().selectedText() == "":
rtext = self.shellWin.textCursor().selectedText()
cmd = "zeal " + str(rtext)
QProcess().startDetached(cmd)
def findWithFirefox_shell(self):
if not self.shellWin.textCursor().selectedText() == "":
rtext = "python%20" + self.shellWin.textCursor().selectedText().replace(" ", "%20")
url = "https://www.google.com/search?q=" + rtext.replace(" ", "%20")
QProcess.startDetached("firefox " + url)
def findNextWord(self):
if self.editor.textCursor().selectedText() == "":
tc = self.editor.textCursor()
tc.select(QTextCursor.WordUnderCursor)
rtext = tc.selectedText()
else:
rtext = self.editor.textCursor().selectedText()
self.findfield.setText(rtext)
self.findText()
def indentLine(self):
if not self.editor.textCursor().selectedText() == "":
newline = u"\u2029"
ot = self.editor.textCursor().selectedText()
theList = ot.splitlines()
newlist = [" " + suit for suit in theList]
newtext = newline.join(newlist)
self.editor.textCursor().insertText(newtext)
self.setModified(True)
self.editor.find(newtext)
self.statusBar().showMessage("more indented")
def indentLessLine(self):
if not self.editor.textCursor().selectedText() == "":
newline = u"\u2029"
ot = self.editor.textCursor().selectedText()
theList = ot.splitlines()
newlist = [suit.replace(" ", "", 1) for suit in theList]
newtext = newline.join(newlist)
self.editor.textCursor().insertText(newtext)
self.setModified(True)
self.editor.find(newtext)
self.statusBar().showMessage("less indented")
def dataReady(self):
out = ""
try:
out = str(self.process.readAll(), encoding = 'utf8').rstrip()
except TypeError:
self.msgbox("Error", str(self.process.readAll(), encoding = 'utf8'))
out = str(self.process.readAll()).rstrip()
self.shellWin.moveCursor(self.cursor.Start) ### changed
self.shellWin.append(out)
if self.shellWin.find("line", QTextDocument.FindWholeWords):
t = self.shellWin.toPlainText().partition("line")[2].partition("\n")[0].lstrip()
if t.find(",", 0):
tr = t.partition(",")[0]
else:
tr = t.lstrip()
self.gotoErrorLine(tr)
else:
return
self.shellWin.moveCursor(self.cursor.End)
self.shellWin.ensureCursorVisible()
def createActions(self):
for i in range(self.MaxRecentFiles):
self.recentFileActs.append(
QAction(self, visible=False,
triggered=self.openRecentFile))
def addBookmark(self):
linenumber = self.getLineNumber()
linetext = self.editor.textCursor().block().text().strip()
self.bookmarks.addItem(linetext, linenumber)
def getLineNumber(self):
self.editor.moveCursor(self.cursor.StartOfLine)
linenumber = self.editor.textCursor().blockNumber() + 1
return linenumber
def gotoLine(self):
ln = int(self.gotofield.text())
linecursor = QTextCursor(self.editor.document().findBlockByLineNumber(ln-1))
self.editor.moveCursor(QTextCursor.End)
self.editor.setTextCursor(linecursor)
def gotoErrorLine(self, ln):
if ln.isalnum:
t = int(ln)
if t != 0:
linecursor = QTextCursor(self.editor.document().findBlockByLineNumber(t-1))
self.editor.moveCursor(QTextCursor.End)
self.editor.setTextCursor(linecursor)
self.editor.moveCursor(QTextCursor.EndOfLine, QTextCursor.KeepAnchor)
else:
return
def gotoBookmark(self):
if self.editor.find(self.bookmarks.itemText(self.bookmarks.currentIndex())):
pass
else:
self.editor.moveCursor(QTextCursor.Start)
self.editor.find(self.bookmarks.itemText(self.bookmarks.currentIndex()))
self.editor.centerCursor()
self.editor.moveCursor(self.cursor.StartOfLine, self.cursor.MoveAnchor)
def gotoBookmarkFromMenu(self):
if self.editor.textCursor().selectedText() == "":
tc = self.editor.textCursor()
tc.select(QTextCursor.WordUnderCursor)
rtext = tc.selectedText()
else:
rtext = self.editor.textCursor().selectedText()
toFind = rtext
self.bookmarks.setCurrentIndex(0)
if self.bookmarks.findText(toFind, Qt.MatchContains):
row = self.bookmarks.findText(toFind, Qt.MatchContains)
self.statusBar().showMessage("found '" + toFind + "' at bookmark " + str(row))
self.bookmarks.setCurrentIndex(row)
self.gotoBookmark()
else:
self.statusBar().showMessage("def not found")
def clearBookmarks(self):
self.bookmarks.clear()
#### find lines with def or class
def findBookmarks(self):
self.editor.setFocus()
self.editor.moveCursor(QTextCursor.Start)
if not self.editor.toPlainText() == "":
self.clearBookmarks()
newline = "\n" #u"\2029"
fr = "from"
im = "import"
d = "def"
d2 = " def"
c = "class"
sn = str("if __name__ ==")
line = ""
list = []
ot = self.editor.toPlainText()
theList = ot.split(newline)
linecount = ot.count(newline)
for i in range(linecount + 1):
if theList[i].startswith(im):
line = str(theList[i]).replace("'\t','[", "").replace("]", "")
self.bookmarks.addItem(str(line), i)
elif theList[i].startswith(fr):
line = str(theList[i]).replace("'\t','[", "").replace("]", "")
self.bookmarks.addItem(str(line), i)
elif theList[i].startswith(c):
line = str(theList[i]).replace("'\t','[", "").replace("]", "")
self.bookmarks.addItem(str(line), i)
elif theList[i].startswith(tab + d):
line = str(theList[i]).replace(tab, "").replace("'\t','[", "").replace("]", "")
self.bookmarks.addItem(str(line), i)
elif theList[i].startswith(d):
line = str(theList[i]).replace(tab, "").replace("'\t','[", "").replace("]", "")
self.bookmarks.addItem(str(line), i)
elif theList[i].startswith(d2):
line = str(theList[i]).replace(tab, "").replace("'\t','[", "").replace("]", "")
self.bookmarks.addItem(str(line), i)
elif theList[i].startswith(sn):
line = str(theList[i]).replace("'\t','[", "").replace("]", "")
self.bookmarks.addItem(str(line), i)
self.bookmarkslist = [self.bookmarks.itemText(i) for i in range(self.bookmarks.count())]
self.bookmarkslist = [w.replace(' ', '') for w in self.bookmarkslist]
# self.bookmarkslist = sorted(self.bookmarkslist, key = lambda x: (x[0]))
self.bookmarkslist.sort()
self.bookmarks.clear()
self.bookmarks.addItems(self.bookmarkslist)
self.statusBar().showMessage("bookmarks changed")
def clearLabel(self):
self.shellWin.setText("")
def openRecentFile(self):
action = self.sender()
if action:
myfile = action.data()
print(myfile)
if (self.maybeSave()):
if QFile.exists(myfile):
self.openFileOnStart(myfile)
else:
self.msgbox("Info", "File does not exist!")
### New File
def newFile(self):
if self.maybeSave():
self.editor.clear()
self.editor.setPlainText(self.mainText)
self.filename = ""
self.setModified(False)
self.editor.moveCursor(self.cursor.End)
self.statusBar().showMessage("new File created.")
self.editor.setFocus()
self.bookmarks.clear()
self.setWindowTitle("new File[*]")
### open File
def openFileOnStart(self, path=None):
if path:
self.openPath = QFileInfo(path).path() ### store path for next time
inFile = QFile(path)
if inFile.open(QFile.ReadWrite | QFile.Text):
text = inFile.readAll()
try:
# Python v3.
text = str(text, encoding = 'utf8')
except TypeError:
# Python v2.
text = str(text)
self.editor.setPlainText(text.replace(tab, " "))
self.setModified(False)
self.setCurrentFile(path)
self.editor.setFocus()
self.findBookmarks()
### save backup
file = QFile(self.filename + "_backup")
if not file.open( QFile.WriteOnly | QFile.Text):
QMessageBox.warning(self, "Error",
"Cannot write file %s:\n%s." % (self.filename, file.errorString()))
return
outstr = QTextStream(file)
QApplication.setOverrideCursor(Qt.WaitCursor)
outstr << self.editor.toPlainText()
QApplication.restoreOverrideCursor()
self.statusBar().showMessage("File '" + path + "' loaded succesfully & bookmarks added & backup created ('" + self.filename + "_backup" + "')")
# self.settings.setValue('recentFileList', [])
# self.addToWordlist(path)
### add all words to completer ###
# mystr = self.editor.toPlainText()
# self.wordList =mystr.split()
# print(mystr)
def addToWordlist(self, file):
wl = []
with open(file,'r') as f:
for line in f:
for word in line.split(" "):
if len(word) > 1:
if not "." in word:
self.words.append(word.replace('\n', ''))
else:
self.words.append(word.replace('\n', '').partition(".")[0])
self.words.append(word.replace('\n', '').partition(".")[2])
self.completer.model().setStringList(self.words)
# self.completer.setModel(self.modelFromFile(self.root + '/resources/wordlist.txt'))
# print(self.completer.model().stringList())
### open File
def openFile(self, path=None):
if self.openPath == "":
self.openPath = self.dirpath
if self.maybeSave():
if not path:
path, _ = QFileDialog.getOpenFileName(self, "Open File", self.openPath,
"Python Files (*.py);; all Files (*)")
if path:
self.openFileOnStart(path)
def fileSave(self):
if (self.filename != ""):
file = QFile(self.filename)
if not file.open( QFile.WriteOnly | QFile.Text):
QMessageBox.warning(self, "Error",
"Cannot write file %s:\n%s." % (self.filename, file.errorString()))
return
outstr = QTextStream(file)
QApplication.setOverrideCursor(Qt.WaitCursor)
outstr << self.editor.toPlainText()
QApplication.restoreOverrideCursor()
self.setModified(False)
self.fname = QFileInfo(self.filename).fileName()
self.setWindowTitle(self.fname + "[*]")
self.statusBar().showMessage("File saved.")
self.setCurrentFile(self.filename)
self.editor.setFocus()
else: