def find_controls(self): find_dialog_hwnd = self.FindWindow(None, self.replace_tab_caption) if find_dialog_hwnd: self.EnumChildWindows(find_dialog_hwnd, self.WNDENUMPROC(self.enum_callback), 0) else: notepad.messageBox('Error: Bad value for find_dialog_hwnd')
def show(self): msg = '' notepad.menuCommand(MENUCOMMAND.SEARCH_REPLACE) if (self.findwhat_handle is None) or (self.replacewith_handle is None): self.find_controls() if editor.getSelections() == 2: if (editor.getSelectionMode() == SELECTIONMODE.STREAM) and (not editor.getSelectionEmpty()): _find_what = editor.getTextRange(editor.getSelectionNStart(0), editor.getSelectionNEnd(0)) _replace_with = editor.getTextRange(editor.getSelectionNStart(1), editor.getSelectionNEnd(1)) if len(_find_what) > 2046: _find_what = _find_what[:2046] msg += 'Warning: Selected text too long for find-what box; truncating to 2046 characters.\n' if len(_replace_with) > 2046: _replace_with = _replace_with[:2046] msg += 'Warning: Selected text too long for replace-with box; truncating to 2046 characters.' if self.SetWindowText(self.findwhat_handle, self.return_proper_string(_find_what)) == 0: msg += 'Error: Problem setting find-what text\n' if self.SetWindowText(self.replacewith_handle, self.return_proper_string(_replace_with)) == 0: msg += 'Error: Problem setting replace-with text' else: msg = 'Error: Either empty selection or unsupported selection mode detected' if len(msg) > 0: notepad.messageBox(msg)
def __init__(self): ''' Initialize the class, should be called once only. ''' current_version = notepad.getPluginVersion() if current_version < '1.5.4.0': notepad.messageBox( 'It is needed to run PythonScript version 1.5.4.0 or higher', 'Unsupported PythonScript verion: {}'.format(current_version)) return self.INDICATOR_ID = 0 self.registered_lexers = _dict() self.document_is_of_interest = False self.regexes = None self.excluded_styles = None editor1.indicSetStyle(self.INDICATOR_ID, INDICATORSTYLE.TEXTFORE) editor1.indicSetFlags(self.INDICATOR_ID, INDICFLAG.VALUEFORE) editor2.indicSetStyle(self.INDICATOR_ID, INDICATORSTYLE.TEXTFORE) editor2.indicSetFlags(self.INDICATOR_ID, INDICFLAG.VALUEFORE) editor.callbackSync(self.on_updateui, [SCINTILLANOTIFICATION.UPDATEUI]) editor.callbackSync(self.on_marginclick, [SCINTILLANOTIFICATION.MARGINCLICK]) notepad.callback(self.on_langchanged, [NOTIFICATION.LANGCHANGED]) notepad.callback(self.on_bufferactivated, [NOTIFICATION.BUFFERACTIVATED])
def start_regex_tester(): if REGEX_TESTER_FILE_NAME == '': notepad.messageBox('You need to indicate, in the REGEX_TESTER_FILE_NAME variable,\n' + 'the fully qualified file name of the TEXT file containing ' + 'the REGEX(ES) to test', 'REGEX_TESTER_FILE_NAME is not set') return False current_document = 0 if notepad.getCurrentView() == 1 else notepad.getCurrentBufferID() global REGEX_TESTER_INPUT_TAB REGEX_TESTER_INPUT_TAB = regex_tester_doc_already_exists() if REGEX_TESTER_INPUT_TAB == 0 : notepad.open(REGEX_TESTER_FILE_NAME) if notepad.getCurrentFilename().upper() == REGEX_TESTER_FILE_NAME.upper(): REGEX_TESTER_INPUT_TAB = notepad.getCurrentBufferID() else: notepad.messageBox('Could not open specified file\n' + '{0}'.format(REGEX_TESTER_FILE_NAME), 'Regex Tester Startup Failed', 0) return False else: notepad.activateBufferID(REGEX_TESTER_INPUT_TAB) if notepad.getCurrentView() != 1: notepad.menuCommand(MENUCOMMAND.VIEW_GOTO_ANOTHER_VIEW) STATUS_LINE = 'RegexTester isActive [] flags:sitpr' current_status_line = editor2.getLine(0) if 'RegexTester' in current_status_line: editor2.replace('RegexTester inActive', 'RegexTester isActive') else: editor2.insertText(0, STATUS_LINE) global REGEX_TESTER_IS_RUNNING REGEX_TESTER_IS_RUNNING = True color_regex_tester_status() set_current_buffer_id() global PREVIOUS_REGEX PREVIOUS_REGEX[CURRENT_BUFFER_ID] = '' editor.callbackSync(regex_tester_updateui_callback, [SCINTILLANOTIFICATION.UPDATEUI]) if current_document != 0: notepad.activateBufferID(current_document) editor2.setFocus(True) editor2.gotoLine(0) notepad.save() notepad.callback(regex_tester_file_before_close_callback, [NOTIFICATION.FILEBEFORECLOSE]) notepad.callback(regex_tester_buffer_activated_callback, [NOTIFICATION.BUFFERACTIVATED]) return True
def find_correspondig_marker(next_marker_line, searching_marker_mask): start_marker_count = 0 end_marker_count = 0 # to avoid having two functions, markerNext or markerPrevious # gets assigned to find_marker variable if searching_marker_mask == MARK_HIDELINESEND_MASK: find_marker = editor.markerNext add_to_line_value = 1 start_marker_count = 1 else: find_marker = editor.markerPrevious add_to_line_value = -1 end_marker_count = 1 # the idea is to search as long for start and end markers # until we get the same amount for both while (start_marker_count != end_marker_count): next_marker_line = find_marker(next_marker_line + add_to_line_value, MARK_COMBINED_MASK) if (next_marker_line != -1): if (editor.markerGet(next_marker_line) & MARK_COMBINED_MASK) == MARK_COMBINED_MASK: if searching_marker_mask == MARK_HIDELINESEND_MASK: end_marker_count += 1 if end_marker_count == start_marker_count: break # found the matching marker start_marker_count += 1 else: start_marker_count += 1 if end_marker_count == start_marker_count: break # found the matching marker end_marker_count += 1 elif editor.markerGet(next_marker_line) & MARK_HIDELINESBEGIN_MASK: start_marker_count += 1 elif editor.markerGet(next_marker_line) & MARK_HIDELINESEND_MASK: end_marker_count += 1 else: msg = 'Now we are in trouble - should not happen !! ??' notepad.messageBox(msg, 'ERROR') list_all_markers() # only used for debugging purpose next_marker_line = -1 break return next_marker_line
def run_demo(): demo_message = ('Running in demo mode\n' 'By commenting run_demo() line or by commenting/deleting the whole tag it is ready to be used') notepad.messageBox(demo_message,'Demo Mode') import random _number_of_lines = 100000 _s = 50 _line_split_separator = ',' _data = ['{0}{3}{1}{3}{2}\r\n'.format('a'*random.randint(0,_s),'b'*random.randint(0,_s),'c'*random.randint(0,_s),_line_split_separator) for i in xrange(_number_of_lines)] notepad.new() editor.setText(''.join(_data)) del _data
def run_demo(): demo_message = ( 'Running in demo mode\n' 'By commenting run_demo() line or by commenting/deleting the whole tag it is ready to be used' ) notepad.messageBox(demo_message, 'Demo Mode') import random _number_of_lines = 100000 _s = 50 _line_split_separator = ',' _data = [ '{0}{3}{1}{3}{2}\r\n'.format('a' * random.randint(0, _s), 'b' * random.randint(0, _s), 'c' * random.randint(0, _s), _line_split_separator) for i in xrange(_number_of_lines) ] notepad.new() editor.setText(''.join(_data)) del _data
Run script to see how it works Note: By commenting or deleting everything, including, the <comment_or_delete> tags it is ready to be used """ from Npp import editor, notepad, console, MESSAGEBOXFLAGS from itertools import izip_longest try: import Tkinter as tk import ttk except ImportError as e: notepad.messageBox(('Unable to import Tkinter libraries,\n' 'these are needed for the UI.\n\n' 'Check your installation.\n\n' '{}'.format(e.message)), 'Missing Library', MESSAGEBOXFLAGS.ICONERROR) console.show() raise def main(): list_of_separators = [('Comma', 0), ('Semicolon', 1), ('Space', 2), ('Clipboard', 3)] separator_dict = {0: ',', 1: ';', 2: ' ', 3: 'clipboard'} list_of_areas = [('Whole document', 0), ('Selection only', 1), ('Visible lines only', 2)]
MESSAGEBOXFLAGS.RESULTYES: u'D:\\ProgramData\\Python\\Python37_64\\python.exe', MESSAGEBOXFLAGS.RESULTNO: u'D:\\ProgramData\\Python\\Python27_64\\python.exe' } def run_command(command, __cwd): _startupinfo = subprocess.STARTUPINFO() _startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW process = subprocess.Popen(shlex.split(command), startupinfo=_startupinfo, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=__cwd) _stdout, _stderr = process.communicate() console.show() if _stdout: console.write(_stdout) if _stderr: console.write(_stderr) file = notepad.getCurrentFilename() _cwd, _ = os.path.split(file) answer = notepad.messageBox(('Yes = Python 37_64\n\n' 'No = Python 27_64\n\n' 'Cancel = No execution'), 'Select python interpreter', 3) if answer != MESSAGEBOXFLAGS.RESULTCANCEL: run_command('"{}" -u "{}"'.format(python_interpreter[answer], file), _cwd)
Usage: Run script to see how it works Note: By commenting or deleting everything, including, the <comment_or_delete> tags it is ready to be used """ from Npp import editor, notepad, console, MESSAGEBOXFLAGS from itertools import izip_longest try: import Tkinter as tk import ttk except ImportError as e: notepad.messageBox(('Unable to import Tkinter libraries,\n' 'these are needed for the UI.\n\n' 'Check your installation.\n\n' '{}'.format(e.message)),'Missing Library', MESSAGEBOXFLAGS.ICONERROR) console.show() raise def main(): list_of_separators = [('Comma',0),('Semicolon',1),('Space',2),('Clipboard', 3)] separator_dict = {0:',', 1:';', 2:' ', 3:'clipboard'} list_of_areas = [('Whole document',0),('Selection only',1),('Visible lines only',2)] format_types_dict = {0:'\r\n',1:'\r',2:'\n'}
def main(): if editor.getSelectionEmpty(): # user hasn't selected anything, hide cursor line start_line = end_line = editor.lineFromPosition(editor.getCurrentPos()) else: start_line, end_line = editor.getUserLineSelection() total_number_less_one_line = editor.getLineCount() - 1 # zero-based # recalculate which lines to hide as first and last line cannot be hide start_line = start_line if start_line > 0 else 1 end_line = end_line if total_number_less_one_line > end_line else end_line - 1 # calculate at which lines marker need to be placed marker_start_line = start_line - 1 if start_line > 0 else start_line marker_end_line = end_line + 1 if end_line < total_number_less_one_line else end_line # recalculate in case that marker(start/end)lines are not visible # either because they are part of a folding tree or already hidden while not editor.getLineVisible(marker_start_line): marker_start_line -= 1 if not editor.getLineVisible(marker_end_line): visible_line = editor.visibleFromDocLine(marker_end_line) marker_end_line = editor.docLineFromVisible(visible_line) # check if there is already a marker set at those lines marker_at_marker_start_line = editor.markerGet(marker_start_line) marker_at_marker_end_line = editor.markerGet(marker_end_line) marker_already_set = False if (marker_at_marker_start_line & MARK_HIDELINESBEGIN_MASK) == MARK_HIDELINESBEGIN_MASK: marker_type = 'start' marker_already_set = True elif (marker_at_marker_end_line & MARK_HIDELINESEND_MASK) == MARK_HIDELINESEND_MASK: marker_type = 'end' marker_already_set = True # already markers set - inform user if marker_already_set: if EXTEND_AUTOMATICALLY is False: answer = notepad.messageBox(( 'There can only be one {} marker per line\r\n' 'Should it be extended instead?\r\n' "If it shouldn't, it doesn't do anything").format(marker_type), 'Info!', 4) if EXTEND_AUTOMATICALLY or answer == MESSAGEBOXFLAGS.RESULTYES: if marker_type == 'start': _matching_marker_line = find_correspondig_marker( marker_start_line, MARK_HIDELINESEND_MASK) _start_marker_line_to_delete = marker_start_line _end_marker_line_to_delete = _matching_marker_line else: _matching_marker_line = find_correspondig_marker( marker_end_line, MARK_HIDELINESBEGIN_MASK) _start_marker_line_to_delete = _matching_marker_line _end_marker_line_to_delete = marker_end_line editor.markerDelete(_start_marker_line_to_delete, MARK_HIDELINESBEGIN) editor.markerDelete(_start_marker_line_to_delete, MARK_HIDELINESUNDERLINE) editor.markerDelete(_end_marker_line_to_delete, MARK_HIDELINESEND) else: return editor.hideLines(start_line, end_line) editor.markerAdd(marker_start_line, MARK_HIDELINESBEGIN) editor.markerAdd(marker_start_line, MARK_HIDELINESUNDERLINE) editor.markerAdd(marker_end_line, MARK_HIDELINESEND) editor.gotoLine(marker_start_line)
import os import sys from Npp import notepad filePathSrc = "D:/training/twg_copy/Contract Detail 5/" #print "ashu" for root, dirs, files in os.walk(filePathSrc): for fn in files: if (fn[-4:] == '.csv'): notepad.open (root + "/" + fn) notepad.runMenuCommand("Macro", "convert") #notepad.save() notepad.runMenuCommand("Encoding", "Convert to UTF-8") notepad.save() #notepad.messageBox("{}{}".format(root+"\\"+fn[:-4],'_trans.csv'),0,"Done") notepad.messageBox("File: %s " % (fn)) notepad.close() #notepad.saveAs("{}{}".format(root+"\\"+fn[:-4],'_trans.csv')) #notepad.close()
import subprocess import shlex import os python_interpreter = { MESSAGEBOXFLAGS.RESULTYES : u'D:\\ProgramData\\Python\\Python37_64\\python.exe', MESSAGEBOXFLAGS.RESULTNO : u'D:\\ProgramData\\Python\\Python27_64\\python.exe'} def run_command(command, __cwd): _startupinfo = subprocess.STARTUPINFO() _startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW process = subprocess.Popen(shlex.split(command), startupinfo=_startupinfo, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=__cwd) _stdout, _stderr = process.communicate() console.show() if _stdout: console.write(_stdout) if _stderr: console.write(_stderr) file = notepad.getCurrentFilename() _cwd, _ = os.path.split(file) answer = notepad.messageBox(('Yes = Python 37_64\n\n' 'No = Python 27_64\n\n' 'Cancel = No execution'),'Select python interpreter',3) if answer != MESSAGEBOXFLAGS.RESULTCANCEL: run_command('"{}" -u "{}"'.format(python_interpreter[answer], file), _cwd)
def start(config_file=None): ''' Starts the notepad++ lsp client implementation and configures the logging behavior Args: config_file: expected full path to the config file which must be a valid json file the specification of the file must meet the requirements as shown below Returns: True Raises: file error if config_file cannot be found or is invalid config_file format must be at least like this, if one of these keys is missing it is treated as invalid format { "version": "0.3", "loglevel": "info", "logpath": "C:\\temp\\npplsplog.txt", "lspservers": [ { "PYTHON": { "pipe": "tcp", "tcpretries" : 3, "executable": "C:\\Python\\Python38_64\\Scripts\\pyls.exe", "args": ["--tcp", "--check-parent-process", "--log-file", "C:\\temp\\log.txt", "-v"] } }, { "RUST": { "pipe": "io", "executable": "C:\\Users\\USERNAME\\.cargo\\bin\\rls.exe" } }, { "TEMPLATE_IO": { "pipe": "io", "executable": "SOMEDRIVE:\\SOMEPATH\\SOME.exe", "args": ["empty, string or comma delimited strings"] } }, { "TEMPLATE_TCP": { "pipe": "tcp", "port": 2087, "tcpretries" : 3, "executable": "SOMEDRIVE:\\SOMEPATH\\SOME.exe", "args": ["empty, string or comma delimited strings"] } } ] } ''' global single_instance if config_file is None: raise ValueError('start method is missing config_file parameter') else: config = __check_config(config_file) if config: lsp_server_config = __check_lsp_server_config(config['lspservers']) if lsp_server_config: logging.basicConfig( filename=config['logpath'], level={ 'notset': logging.NOTSET, 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'fatal': logging.FATAL, 'critical': logging.CRITICAL, }.get(config['loglevel'], 'notset'), format= '[%(asctime)-15s] [%(thread)-5d] [%(levelname)-10s] %(funcName)-20s %(message)s' ) logging.info(config) if logging.root.level == logging.NOTSET: logging.disable() single_instance = LSPCLIENT(lsp_server_config) args = {'bufferID': notepad.getCurrentBufferID()} single_instance.on_buffer_activated(args) else: notepad.messageBox( 'There seems to be an issue with the configuration file!', 'LSP start error')
if prev_level == get_level(lines[current_line]): found_additional_filters = [ lines[current_line].count(x) for x in combined_filters ] found_unique_filters = [ lines[current_line].count(u) for u in unique_filters ] level_stack[-1][0].add(sum(found_additional_filters), found_unique_filters) # create a list of all Node objects results = [x[0].result() for x in level_stack] results.extend([x[0].result() for x in save_popped_levels]) # reformat the resulting content if notepad.messageBox('Should additional filtering be applied?', '', MESSAGEBOXFLAGS.YESNO) == MESSAGEBOXFLAGS.RESULTYES: for line, _sum, _additional_filters, _unique_filters in sorted(results): __unique_filters = ', '.join([str(x) for x in _unique_filters]) __unique_filters = ', ' + __unique_filters if __unique_filters else '' lines[line] = '{0:<{1}}({2}{3}{4}{5})'.format(lines[line][:80], 80, _sum, ', ', _additional_filters, __unique_filters) else: for line, _sum, _ in sorted(results): lines[line] = '{0:<{1}}({2})'.format(lines[line][:80], 80, _sum) # set the new content editor.setText('\r\n'.join(lines))