I’m attempting to create a Visual Studio Code extension that counts the number of lines in the currently open file. However, I’ve hit a roadblock in implementing the line counting functionality.
I tried going through each line of text one by one and counting them using a basic loop, but it was really slow and often gave the wrong count, especially with big files. Then I thought about using regular expressions to find line breaks, but that got messy with multiline text and comments, so it wasn’t reliable. I even looked into using existing libraries or modules that could do the counting for me, but none of them fit smoothly into my custom text editor project. It’s been a bit of a struggle.
here is my code *i removed my line counting logic:
`import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTextEdit, QAction, QFileDialog, QVBoxLayout, QWidget
class Notepad(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Notepad")
self.setGeometry(100, 100, 600, 400)
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
layout = QVBoxLayout()
layout.setContentsMargins(10, 10, 10, 10) # Add margin around the central widget
layout.setSpacing(10) # Add spacing between the menu bar and text box
self.central_widget.setLayout(layout)
self.text_edit = QTextEdit()
self.text_edit.setStyleSheet(
"QTextEdit { background-color: #282828; color: purple; border: none; }"
"QTextEdit:hover { background-color: #282828; }"
)
layout.addWidget(self.text_edit)
self.central_widget.setStyleSheet(
"background-color: #282828;" # Set the background color of the central widget
)
self.create_menu()
def create_menu(self):
main_menu = self.menuBar()
main_menu.setStyleSheet(
"QMenuBar { background-color: #1d1f21; color: #FFFFFF; }"
)
file_menu = main_menu.addMenu("File")
file_menu.setStyleSheet(
"QMenu { background-color: #1d1f21; color: #FFFFFF; }"
)
save_action = QAction("Save", self)
save_action.triggered.connect(self.save_file)
file_menu.addAction(save_action)
open_action = QAction("Open", self)
open_action.triggered.connect(self.open_file)
file_menu.addAction(open_action)
def save_file(self):
file_path, _ = QFileDialog.getSaveFileName(self, "Save File", "", "Text Files (*.txt)")
if file_path:
with open(file_path, "w") as file:
text = self.text_edit.toPlainText()
file.write(text)
def open_file(self):
file_path, _ = QFileDialog.getOpenFileName(self, "Open File", "", "Text Files (*.txt)")
if file_path:
with open(file_path, "r") as file:
text = file.read()
self.text_edit.setPlainText(text)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Notepad()
window.show()
sys.exit(app.exec_())
https://ibb.co/JsdWgSL the intended functionality
HOW-DO-I-CENTER-A-DIV is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.