code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
def __init__(self, root, engine): """Create search dialog for finding and replacing text. Uses SearchDialogBase as the basis for the GUI and a searchengine instance to prepare the search. Attributes: replvar: StringVar containing 'Replace with:' value. replent: Entry widget for replvar. Created in create_entries(). ok: Boolean used in searchengine.search_text to indicate whether the search includes the selection. """ super().__init__(root, engine) self.replvar = StringVar(root)
Create search dialog for finding and replacing text. Uses SearchDialogBase as the basis for the GUI and a searchengine instance to prepare the search. Attributes: replvar: StringVar containing 'Replace with:' value. replent: Entry widget for replvar. Created in create_entries(). ok: Boolean used in searchengine.search_text to indicate whether the search includes the selection.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def open(self, text): """Make dialog visible on top of others and ready to use. Also, highlight the currently selected text and set the search to include the current selection (self.ok). Args: text: Text widget being searched. """ SearchDialogBase.open(self, text) try: first = text.index("sel.first") except TclError: first = None try: last = text.index("sel.last") except TclError: last = None first = first or text.index("insert") last = last or first self.show_hit(first, last) self.ok = True
Make dialog visible on top of others and ready to use. Also, highlight the currently selected text and set the search to include the current selection (self.ok). Args: text: Text widget being searched.
open
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def create_command_buttons(self): """Create base and additional command buttons. The additional buttons are for Find, Replace, Replace+Find, and Replace All. """ SearchDialogBase.create_command_buttons(self) self.make_button("Find", self.find_it) self.make_button("Replace", self.replace_it) self.make_button("Replace+Find", self.default_command, isdef=True) self.make_button("Replace All", self.replace_all)
Create base and additional command buttons. The additional buttons are for Find, Replace, Replace+Find, and Replace All.
create_command_buttons
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def replace_it(self, event=None): """Handle the Replace button. If the find is successful, then perform replace. """ if self.do_find(self.ok): self.do_replace()
Handle the Replace button. If the find is successful, then perform replace.
replace_it
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def default_command(self, event=None): """Handle the Replace+Find button as the default command. First performs a replace and then, if the replace was successful, a find next. """ if self.do_find(self.ok): if self.do_replace(): # Only find next match if replace succeeded. # A bad re can cause it to fail. self.do_find(False)
Handle the Replace+Find button as the default command. First performs a replace and then, if the replace was successful, a find next.
default_command
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def replace_all(self, event=None): """Handle the Replace All button. Search text for occurrences of the Find value and replace each of them. The 'wrap around' value controls the start point for searching. If wrap isn't set, then the searching starts at the first occurrence after the current selection; if wrap is set, the replacement starts at the first line. The replacement is always done top-to-bottom in the text. """ prog = self.engine.getprog() if not prog: return repl = self.replvar.get() text = self.text res = self.engine.search_text(text, prog) if not res: self.bell() return text.tag_remove("sel", "1.0", "end") text.tag_remove("hit", "1.0", "end") line = res[0] col = res[1].start() if self.engine.iswrap(): line = 1 col = 0 ok = True first = last = None # XXX ought to replace circular instead of top-to-bottom when wrapping text.undo_block_start() while True: res = self.engine.search_forward(text, prog, line, col, wrap=False, ok=ok) if not res: break line, m = res chars = text.get("%d.0" % line, "%d.0" % (line+1)) orig = m.group() new = self._replace_expand(m, repl) if new is None: break i, j = m.span() first = "%d.%d" % (line, i) last = "%d.%d" % (line, j) if new == orig: text.mark_set("insert", last) else: text.mark_set("insert", first) if first != last: text.delete(first, last) if new: text.insert(first, new) col = i + len(new) ok = False text.undo_block_stop() if first and last: self.show_hit(first, last) self.close()
Handle the Replace All button. Search text for occurrences of the Find value and replace each of them. The 'wrap around' value controls the start point for searching. If wrap isn't set, then the searching starts at the first occurrence after the current selection; if wrap is set, the replacement starts at the first line. The replacement is always done top-to-bottom in the text.
replace_all
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def do_find(self, ok=False): """Search for and highlight next occurrence of pattern in text. No text replacement is done with this option. """ if not self.engine.getprog(): return False text = self.text res = self.engine.search_text(text, None, ok) if not res: self.bell() return False line, m = res i, j = m.span() first = "%d.%d" % (line, i) last = "%d.%d" % (line, j) self.show_hit(first, last) self.ok = True return True
Search for and highlight next occurrence of pattern in text. No text replacement is done with this option.
do_find
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def show_hit(self, first, last): """Highlight text between first and last indices. Text is highlighted via the 'hit' tag and the marked section is brought into view. The colors from the 'hit' tag aren't currently shown when the text is displayed. This is due to the 'sel' tag being added first, so the colors in the 'sel' config are seen instead of the colors for 'hit'. """ text = self.text text.mark_set("insert", first) text.tag_remove("sel", "1.0", "end") text.tag_add("sel", first, last) text.tag_remove("hit", "1.0", "end") if first == last: text.tag_add("hit", first) else: text.tag_add("hit", first, last) text.see("insert") text.update_idletasks()
Highlight text between first and last indices. Text is highlighted via the 'hit' tag and the marked section is brought into view. The colors from the 'hit' tag aren't currently shown when the text is displayed. This is due to the 'sel' tag being added first, so the colors in the 'sel' config are seen instead of the colors for 'hit'.
show_hit
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/replace.py
MIT
def start_debugger(rpchandler, gui_adap_oid): """Start the debugger and its RPC link in the Python subprocess Start the subprocess side of the split debugger and set up that side of the RPC link by instantiating the GUIProxy, Idb debugger, and IdbAdapter objects and linking them together. Register the IdbAdapter with the RPCServer to handle RPC requests from the split debugger GUI via the IdbProxy. """ gui_proxy = GUIProxy(rpchandler, gui_adap_oid) idb = debugger.Idb(gui_proxy) idb_adap = IdbAdapter(idb) rpchandler.register(idb_adap_oid, idb_adap) return idb_adap_oid
Start the debugger and its RPC link in the Python subprocess Start the subprocess side of the split debugger and set up that side of the RPC link by instantiating the GUIProxy, Idb debugger, and IdbAdapter objects and linking them together. Register the IdbAdapter with the RPCServer to handle RPC requests from the split debugger GUI via the IdbProxy.
start_debugger
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/debugger_r.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/debugger_r.py
MIT
def start_remote_debugger(rpcclt, pyshell): """Start the subprocess debugger, initialize the debugger GUI and RPC link Request the RPCServer start the Python subprocess debugger and link. Set up the Idle side of the split debugger by instantiating the IdbProxy, debugger GUI, and debugger GUIAdapter objects and linking them together. Register the GUIAdapter with the RPCClient to handle debugger GUI interaction requests coming from the subprocess debugger via the GUIProxy. The IdbAdapter will pass execution and environment requests coming from the Idle debugger GUI to the subprocess debugger via the IdbProxy. """ global idb_adap_oid idb_adap_oid = rpcclt.remotecall("exec", "start_the_debugger",\ (gui_adap_oid,), {}) idb_proxy = IdbProxy(rpcclt, pyshell, idb_adap_oid) gui = debugger.Debugger(pyshell, idb_proxy) gui_adap = GUIAdapter(rpcclt, gui) rpcclt.register(gui_adap_oid, gui_adap) return gui
Start the subprocess debugger, initialize the debugger GUI and RPC link Request the RPCServer start the Python subprocess debugger and link. Set up the Idle side of the split debugger by instantiating the IdbProxy, debugger GUI, and debugger GUIAdapter objects and linking them together. Register the GUIAdapter with the RPCClient to handle debugger GUI interaction requests coming from the subprocess debugger via the GUIProxy. The IdbAdapter will pass execution and environment requests coming from the Idle debugger GUI to the subprocess debugger via the IdbProxy.
start_remote_debugger
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/debugger_r.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/debugger_r.py
MIT
def close_remote_debugger(rpcclt): """Shut down subprocess debugger and Idle side of debugger RPC link Request that the RPCServer shut down the subprocess debugger and link. Unregister the GUIAdapter, which will cause a GC on the Idle process debugger and RPC link objects. (The second reference to the debugger GUI is deleted in pyshell.close_remote_debugger().) """ close_subprocess_debugger(rpcclt) rpcclt.unregister(gui_adap_oid)
Shut down subprocess debugger and Idle side of debugger RPC link Request that the RPCServer shut down the subprocess debugger and link. Unregister the GUIAdapter, which will cause a GC on the Idle process debugger and RPC link objects. (The second reference to the debugger GUI is deleted in pyshell.close_remote_debugger().)
close_remote_debugger
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/debugger_r.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/debugger_r.py
MIT
def __init__(self, parent, title, message, *, text0='', used_names={}, _htest=False, _utest=False): """Create modal popup, return when destroyed. Additional subclass init must be done before this unless _utest=True is passed to suppress wait_window(). title - string, title of popup dialog message - string, informational message to display text0 - initial value for entry used_names - names already in use _htest - bool, change box location when running htest _utest - bool, leave window hidden and not modal """ self.parent = parent # Needed for Font call. self.message = message self.text0 = text0 self.used_names = used_names Toplevel.__init__(self, parent) self.withdraw() # Hide while configuring, especially geometry. self.title(title) self.transient(parent) self.grab_set() windowingsystem = self.tk.call('tk', 'windowingsystem') if windowingsystem == 'aqua': try: self.tk.call('::tk::unsupported::MacWindowStyle', 'style', self._w, 'moveableModal', '') except: pass self.bind("<Command-.>", self.cancel) self.bind('<Key-Escape>', self.cancel) self.protocol("WM_DELETE_WINDOW", self.cancel) self.bind('<Key-Return>', self.ok) self.bind("<KP_Enter>", self.ok) self.create_widgets() self.update_idletasks() # Need here for winfo_reqwidth below. self.geometry( # Center dialog over parent (or below htest box). "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) self.resizable(height=False, width=False) if not _utest: self.deiconify() # Unhide now that geometry set. self.wait_window()
Create modal popup, return when destroyed. Additional subclass init must be done before this unless _utest=True is passed to suppress wait_window(). title - string, title of popup dialog message - string, informational message to display text0 - initial value for entry used_names - names already in use _htest - bool, change box location when running htest _utest - bool, leave window hidden and not modal
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
MIT
def create_widgets(self, ok_text='OK'): # Do not replace. """Create entry (rows, extras, buttons. Entry stuff on rows 0-2, spanning cols 0-2. Buttons on row 99, cols 1, 2. """ # Bind to self the widgets needed for entry_ok or unittest. self.frame = frame = Frame(self, padding=10) frame.grid(column=0, row=0, sticky='news') frame.grid_columnconfigure(0, weight=1) entrylabel = Label(frame, anchor='w', justify='left', text=self.message) self.entryvar = StringVar(self, self.text0) self.entry = Entry(frame, width=30, textvariable=self.entryvar) self.entry.focus_set() self.error_font = Font(name='TkCaptionFont', exists=True, root=self.parent) self.entry_error = Label(frame, text=' ', foreground='red', font=self.error_font) entrylabel.grid(column=0, row=0, columnspan=3, padx=5, sticky=W) self.entry.grid(column=0, row=1, columnspan=3, padx=5, sticky=W+E, pady=[10,0]) self.entry_error.grid(column=0, row=2, columnspan=3, padx=5, sticky=W+E) self.create_extra() self.button_ok = Button( frame, text=ok_text, default='active', command=self.ok) self.button_cancel = Button( frame, text='Cancel', command=self.cancel) self.button_ok.grid(column=1, row=99, padx=5) self.button_cancel.grid(column=2, row=99, padx=5)
Create entry (rows, extras, buttons. Entry stuff on rows 0-2, spanning cols 0-2. Buttons on row 99, cols 1, 2.
create_widgets
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
MIT
def ok(self, event=None): # Do not replace. '''If entry is valid, bind it to 'result' and destroy tk widget. Otherwise leave dialog open for user to correct entry or cancel. ''' entry = self.entry_ok() if entry is not None: self.result = entry self.destroy() else: # [Ok] moves focus. (<Return> does not.) Move it back. self.entry.focus_set()
If entry is valid, bind it to 'result' and destroy tk widget. Otherwise leave dialog open for user to correct entry or cancel.
ok
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
MIT
def __init__(self, parent, title, *, menuitem='', filepath='', used_names={}, _htest=False, _utest=False): """Get menu entry and url/local file for Additional Help. User enters a name for the Help resource and a web url or file name. The user can browse for the file. """ self.filepath = filepath message = 'Name for item on Help menu:' super().__init__( parent, title, message, text0=menuitem, used_names=used_names, _htest=_htest, _utest=_utest)
Get menu entry and url/local file for Additional Help. User enters a name for the Help resource and a web url or file name. The user can browse for the file.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
MIT
def __init__(self, parent, title, *, cli_args=[], _htest=False, _utest=False): """cli_args is a list of strings. The list is assigned to the default Entry StringVar. The strings are displayed joined by ' ' for display. """ message = 'Command Line Arguments for sys.argv:' super().__init__( parent, title, message, text0=cli_args, _htest=_htest, _utest=_utest)
cli_args is a list of strings. The list is assigned to the default Entry StringVar. The strings are displayed joined by ' ' for display.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/query.py
MIT
def open_completions(self, args): """Find the completions and create the AutoCompleteWindow. Return True if successful (no syntax error or so found). If complete is True, then if there's nothing to complete and no start of completion, won't open completions and return False. If mode is given, will open a completion list only in this mode. """ evalfuncs, complete, wantwin, mode = args # Cancel another delayed call, if it exists. if self._delayed_completion_id is not None: self.text.after_cancel(self._delayed_completion_id) self._delayed_completion_id = None hp = HyperParser(self.editwin, "insert") curline = self.text.get("insert linestart", "insert") i = j = len(curline) if hp.is_in_string() and (not mode or mode==FILES): # Find the beginning of the string. # fetch_completions will look at the file system to determine # whether the string value constitutes an actual file name # XXX could consider raw strings here and unescape the string # value if it's not raw. self._remove_autocomplete_window() mode = FILES # Find last separator or string start while i and curline[i-1] not in "'\"" + SEPS: i -= 1 comp_start = curline[i:j] j = i # Find string start while i and curline[i-1] not in "'\"": i -= 1 comp_what = curline[i:j] elif hp.is_in_code() and (not mode or mode==ATTRS): self._remove_autocomplete_window() mode = ATTRS while i and (curline[i-1] in ID_CHARS or ord(curline[i-1]) > 127): i -= 1 comp_start = curline[i:j] if i and curline[i-1] == '.': # Need object with attributes. hp.set_index("insert-%dc" % (len(curline)-(i-1))) comp_what = hp.get_expression() if (not comp_what or (not evalfuncs and comp_what.find('(') != -1)): return None else: comp_what = "" else: return None if complete and not comp_what and not comp_start: return None comp_lists = self.fetch_completions(comp_what, mode) if not comp_lists[0]: return None self.autocompletewindow = self._make_autocomplete_window() return not self.autocompletewindow.show_window( comp_lists, "insert-%dc" % len(comp_start), complete, mode, wantwin)
Find the completions and create the AutoCompleteWindow. Return True if successful (no syntax error or so found). If complete is True, then if there's nothing to complete and no start of completion, won't open completions and return False. If mode is given, will open a completion list only in this mode.
open_completions
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete.py
MIT
def fetch_completions(self, what, mode): """Return a pair of lists of completions for something. The first list is a sublist of the second. Both are sorted. If there is a Python subprocess, get the comp. list there. Otherwise, either fetch_completions() is running in the subprocess itself or it was called in an IDLE EditorWindow before any script had been run. The subprocess environment is that of the most recently run script. If two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run. """ try: rpcclt = self.editwin.flist.pyshell.interp.rpcclt except: rpcclt = None if rpcclt: return rpcclt.remotecall("exec", "get_the_completion_list", (what, mode), {}) else: if mode == ATTRS: if what == "": namespace = {**__main__.__builtins__.__dict__, **__main__.__dict__} bigl = eval("dir()", namespace) bigl.sort() if "__all__" in bigl: smalll = sorted(eval("__all__", namespace)) else: smalll = [s for s in bigl if s[:1] != '_'] else: try: entity = self.get_entity(what) bigl = dir(entity) bigl.sort() if "__all__" in bigl: smalll = sorted(entity.__all__) else: smalll = [s for s in bigl if s[:1] != '_'] except: return [], [] elif mode == FILES: if what == "": what = "." try: expandedpath = os.path.expanduser(what) bigl = os.listdir(expandedpath) bigl.sort() smalll = [s for s in bigl if s[:1] != '.'] except OSError: return [], [] if not smalll: smalll = bigl return smalll, bigl
Return a pair of lists of completions for something. The first list is a sublist of the second. Both are sorted. If there is a Python subprocess, get the comp. list there. Otherwise, either fetch_completions() is running in the subprocess itself or it was called in an IDLE EditorWindow before any script had been run. The subprocess environment is that of the most recently run script. If two unrelated modules are being edited some calltips in the current module may be inoperative if the module was not the last to run.
fetch_completions
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete.py
MIT
def get_line_info(codeline): """Return tuple of (line indent value, codeline, block start keyword). The indentation of empty lines (or comment lines) is INFINITY. If the line does not start a block, the keyword value is False. """ spaces, firstword = get_spaces_firstword(codeline) indent = len(spaces) if len(codeline) == indent or codeline[indent] == '#': indent = INFINITY opener = firstword in BLOCKOPENERS and firstword return indent, codeline, opener
Return tuple of (line indent value, codeline, block start keyword). The indentation of empty lines (or comment lines) is INFINITY. If the line does not start a block, the keyword value is False.
get_line_info
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
MIT
def __init__(self, editwin): """Initialize settings for context block. editwin is the Editor window for the context block. self.text is the editor window text widget. self.context displays the code context text above the editor text. Initially None, it is toggled via <<toggle-code-context>>. self.topvisible is the number of the top text line displayed. self.info is a list of (line number, indent level, line text, block keyword) tuples for the block structure above topvisible. self.info[0] is initialized with a 'dummy' line which starts the toplevel 'block' of the module. self.t1 and self.t2 are two timer events on the editor text widget to monitor for changes to the context text or editor font. """ self.editwin = editwin self.text = editwin.text self._reset()
Initialize settings for context block. editwin is the Editor window for the context block. self.text is the editor window text widget. self.context displays the code context text above the editor text. Initially None, it is toggled via <<toggle-code-context>>. self.topvisible is the number of the top text line displayed. self.info is a list of (line number, indent level, line text, block keyword) tuples for the block structure above topvisible. self.info[0] is initialized with a 'dummy' line which starts the toplevel 'block' of the module. self.t1 and self.t2 are two timer events on the editor text widget to monitor for changes to the context text or editor font.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
MIT
def toggle_code_context_event(self, event=None): """Toggle code context display. If self.context doesn't exist, create it to match the size of the editor window text (toggle on). If it does exist, destroy it (toggle off). Return 'break' to complete the processing of the binding. """ if self.context is None: # Calculate the border width and horizontal padding required to # align the context with the text in the main Text widget. # # All values are passed through getint(), since some # values may be pixel objects, which can't simply be added to ints. widgets = self.editwin.text, self.editwin.text_frame # Calculate the required horizontal padding and border width. padx = 0 border = 0 for widget in widgets: info = (widget.grid_info() if widget is self.editwin.text else widget.pack_info()) padx += widget.tk.getint(info['padx']) padx += widget.tk.getint(widget.cget('padx')) border += widget.tk.getint(widget.cget('border')) context = self.context = tkinter.Text( self.editwin.text_frame, height=1, width=1, # Don't request more than we get. highlightthickness=0, padx=padx, border=border, relief=SUNKEN, state='disabled') self.update_font() self.update_highlight_colors() context.bind('<ButtonRelease-1>', self.jumptoline) # Get the current context and initiate the recurring update event. self.timer_event() # Grid the context widget above the text widget. context.grid(row=0, column=1, sticky=NSEW) line_number_colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'linenumber') self.cell00 = tkinter.Frame(self.editwin.text_frame, bg=line_number_colors['background']) self.cell00.grid(row=0, column=0, sticky=NSEW) menu_status = 'Hide' else: self.context.destroy() self.context = None self.cell00.destroy() self.cell00 = None self.text.after_cancel(self.t1) self._reset() menu_status = 'Show' self.editwin.update_menu_label(menu='options', index='* Code Context', label=f'{menu_status} Code Context') return "break"
Toggle code context display. If self.context doesn't exist, create it to match the size of the editor window text (toggle on). If it does exist, destroy it (toggle off). Return 'break' to complete the processing of the binding.
toggle_code_context_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
MIT
def get_context(self, new_topvisible, stopline=1, stopindent=0): """Return a list of block line tuples and the 'last' indent. The tuple fields are (linenum, indent, text, opener). The list represents header lines from new_topvisible back to stopline with successively shorter indents > stopindent. The list is returned ordered by line number. Last indent returned is the smallest indent observed. """ assert stopline > 0 lines = [] # The indentation level we are currently in. lastindent = INFINITY # For a line to be interesting, it must begin with a block opening # keyword, and have less indentation than lastindent. for linenum in range(new_topvisible, stopline-1, -1): codeline = self.text.get(f'{linenum}.0', f'{linenum}.end') indent, text, opener = get_line_info(codeline) if indent < lastindent: lastindent = indent if opener in ("else", "elif"): # Also show the if statement. lastindent += 1 if opener and linenum < new_topvisible and indent >= stopindent: lines.append((linenum, indent, text, opener)) if lastindent <= stopindent: break lines.reverse() return lines, lastindent
Return a list of block line tuples and the 'last' indent. The tuple fields are (linenum, indent, text, opener). The list represents header lines from new_topvisible back to stopline with successively shorter indents > stopindent. The list is returned ordered by line number. Last indent returned is the smallest indent observed.
get_context
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
MIT
def update_code_context(self): """Update context information and lines visible in the context pane. No update is done if the text hasn't been scrolled. If the text was scrolled, the lines that should be shown in the context will be retrieved and the context area will be updated with the code, up to the number of maxlines. """ new_topvisible = self.editwin.getlineno("@0,0") if self.topvisible == new_topvisible: # Haven't scrolled. return if self.topvisible < new_topvisible: # Scroll down. lines, lastindent = self.get_context(new_topvisible, self.topvisible) # Retain only context info applicable to the region # between topvisible and new_topvisible. while self.info[-1][1] >= lastindent: del self.info[-1] else: # self.topvisible > new_topvisible: # Scroll up. stopindent = self.info[-1][1] + 1 # Retain only context info associated # with lines above new_topvisible. while self.info[-1][0] >= new_topvisible: stopindent = self.info[-1][1] del self.info[-1] lines, lastindent = self.get_context(new_topvisible, self.info[-1][0]+1, stopindent) self.info.extend(lines) self.topvisible = new_topvisible # Last context_depth context lines. context_strings = [x[2] for x in self.info[-self.context_depth:]] showfirst = 0 if context_strings[0] else 1 # Update widget. self.context['height'] = len(context_strings) - showfirst self.context['state'] = 'normal' self.context.delete('1.0', 'end') self.context.insert('end', '\n'.join(context_strings[showfirst:])) self.context['state'] = 'disabled'
Update context information and lines visible in the context pane. No update is done if the text hasn't been scrolled. If the text was scrolled, the lines that should be shown in the context will be retrieved and the context area will be updated with the code, up to the number of maxlines.
update_code_context
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
MIT
def jumptoline(self, event=None): """ Show clicked context line at top of editor. If a selection was made, don't jump; allow copying. If no visible context, show the top line of the file. """ try: self.context.index("sel.first") except tkinter.TclError: lines = len(self.info) if lines == 1: # No context lines are showing. newtop = 1 else: # Line number clicked. contextline = int(float(self.context.index('insert'))) # Lines not displayed due to maxlines. offset = max(1, lines - self.context_depth) - 1 newtop = self.info[offset + contextline][0] self.text.yview(f'{newtop}.0') self.update_code_context()
Show clicked context line at top of editor. If a selection was made, don't jump; allow copying. If no visible context, show the top line of the file.
jumptoline
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/codecontext.py
MIT
def __init__(self, widget): '''Initialize attributes and setup redirection. _operations: dict mapping operation name to new function. widget: the widget whose tcl command is to be intercepted. tk: widget.tk, a convenience attribute, probably not needed. orig: new name of the original tcl command. Since renaming to orig fails with TclError when orig already exists, only one WidgetDirector can exist for a given widget. ''' self._operations = {} self.widget = widget # widget instance self.tk = tk = widget.tk # widget's root w = widget._w # widget's (full) Tk pathname self.orig = w + "_orig" # Rename the Tcl command within Tcl: tk.call("rename", w, self.orig) # Create a new Tcl command whose name is the widget's pathname, and # whose action is to dispatch on the operation passed to the widget: tk.createcommand(w, self.dispatch)
Initialize attributes and setup redirection. _operations: dict mapping operation name to new function. widget: the widget whose tcl command is to be intercepted. tk: widget.tk, a convenience attribute, probably not needed. orig: new name of the original tcl command. Since renaming to orig fails with TclError when orig already exists, only one WidgetDirector can exist for a given widget.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
MIT
def register(self, operation, function): '''Return OriginalCommand(operation) after registering function. Registration adds an operation: function pair to ._operations. It also adds a widget function attribute that masks the tkinter class instance method. Method masking operates independently from command dispatch. If a second function is registered for the same operation, the first function is replaced in both places. ''' self._operations[operation] = function setattr(self.widget, operation, function) return OriginalCommand(self, operation)
Return OriginalCommand(operation) after registering function. Registration adds an operation: function pair to ._operations. It also adds a widget function attribute that masks the tkinter class instance method. Method masking operates independently from command dispatch. If a second function is registered for the same operation, the first function is replaced in both places.
register
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
MIT
def unregister(self, operation): '''Return the function for the operation, or None. Deleting the instance attribute unmasks the class attribute. ''' if operation in self._operations: function = self._operations[operation] del self._operations[operation] try: delattr(self.widget, operation) except AttributeError: pass return function else: return None
Return the function for the operation, or None. Deleting the instance attribute unmasks the class attribute.
unregister
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
MIT
def dispatch(self, operation, *args): '''Callback from Tcl which runs when the widget is referenced. If an operation has been registered in self._operations, apply the associated function to the args passed into Tcl. Otherwise, pass the operation through to Tk via the original Tcl function. Note that if a registered function is called, the operation is not passed through to Tk. Apply the function returned by self.register() to *args to accomplish that. For an example, see colorizer.py. ''' m = self._operations.get(operation) try: if m: return m(*args) else: return self.tk.call((self.orig, operation) + args) except TclError: return ""
Callback from Tcl which runs when the widget is referenced. If an operation has been registered in self._operations, apply the associated function to the args passed into Tcl. Otherwise, pass the operation through to Tk via the original Tcl function. Note that if a registered function is called, the operation is not passed through to Tk. Apply the function returned by self.register() to *args to accomplish that. For an example, see colorizer.py.
dispatch
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
MIT
def __init__(self, redir, operation): '''Create .tk_call and .orig_and_operation for .__call__ method. .redir and .operation store the input args for __repr__. .tk and .orig copy attributes of .redir (probably not needed). ''' self.redir = redir self.operation = operation self.tk = redir.tk # redundant with self.redir self.orig = redir.orig # redundant with self.redir # These two could be deleted after checking recipient code. self.tk_call = redir.tk.call self.orig_and_operation = (redir.orig, operation)
Create .tk_call and .orig_and_operation for .__call__ method. .redir and .operation store the input args for __repr__. .tk and .orig copy attributes of .redir (probably not needed).
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/redirector.py
MIT
def expand_substates(states): '''For each item of states return a list containing all combinations of that item with individual bits reset, sorted by the number of set bits. ''' def nbits(n): "number of bits set in n base 2" nb = 0 while n: n, rem = divmod(n, 2) nb += rem return nb statelist = [] for state in states: substates = list(set(state & x for x in states)) substates.sort(key=nbits, reverse=True) statelist.append(substates) return statelist
For each item of states return a list containing all combinations of that item with individual bits reset, sorted by the number of set bits.
expand_substates
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/multicall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/multicall.py
MIT
def _parse_sequence(sequence): """Get a string which should describe an event sequence. If it is successfully parsed as one, return a tuple containing the state (as an int), the event type (as an index of _types), and the detail - None if none, or a string if there is one. If the parsing is unsuccessful, return None. """ if not sequence or sequence[0] != '<' or sequence[-1] != '>': return None words = sequence[1:-1].split('-') modifiers = 0 while words and words[0] in _modifier_names: modifiers |= 1 << _modifier_names[words[0]] del words[0] if words and words[0] in _type_names: type = _type_names[words[0]] del words[0] else: return None if _binder_classes[type] is _SimpleBinder: if modifiers or words: return None else: detail = None else: # _ComplexBinder if type in [_type_names[s] for s in ("KeyPress", "KeyRelease")]: type_re = _keysym_re else: type_re = _button_re if not words: detail = None elif len(words) == 1 and type_re.match(words[0]): detail = words[0] else: return None return modifiers, type, detail
Get a string which should describe an event sequence. If it is successfully parsed as one, return a tuple containing the state (as an int), the event type (as an index of _types), and the detail - None if none, or a string if there is one. If the parsing is unsuccessful, return None.
_parse_sequence
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/multicall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/multicall.py
MIT
def MultiCallCreator(widget): """Return a MultiCall class which inherits its methods from the given widget class (for example, Tkinter.Text). This is used instead of a templating mechanism. """ if widget in _multicall_dict: return _multicall_dict[widget] class MultiCall (widget): assert issubclass(widget, tkinter.Misc) def __init__(self, *args, **kwargs): widget.__init__(self, *args, **kwargs) # a dictionary which maps a virtual event to a tuple with: # 0. the function binded # 1. a list of triplets - the sequences it is binded to self.__eventinfo = {} self.__binders = [_binder_classes[i](i, widget, self) for i in range(len(_types))] def bind(self, sequence=None, func=None, add=None): #print("bind(%s, %s, %s)" % (sequence, func, add), # file=sys.__stderr__) if type(sequence) is str and len(sequence) > 2 and \ sequence[:2] == "<<" and sequence[-2:] == ">>": if sequence in self.__eventinfo: ei = self.__eventinfo[sequence] if ei[0] is not None: for triplet in ei[1]: self.__binders[triplet[1]].unbind(triplet, ei[0]) ei[0] = func if ei[0] is not None: for triplet in ei[1]: self.__binders[triplet[1]].bind(triplet, func) else: self.__eventinfo[sequence] = [func, []] return widget.bind(self, sequence, func, add) def unbind(self, sequence, funcid=None): if type(sequence) is str and len(sequence) > 2 and \ sequence[:2] == "<<" and sequence[-2:] == ">>" and \ sequence in self.__eventinfo: func, triplets = self.__eventinfo[sequence] if func is not None: for triplet in triplets: self.__binders[triplet[1]].unbind(triplet, func) self.__eventinfo[sequence][0] = None return widget.unbind(self, sequence, funcid) def event_add(self, virtual, *sequences): #print("event_add(%s, %s)" % (repr(virtual), repr(sequences)), # file=sys.__stderr__) if virtual not in self.__eventinfo: self.__eventinfo[virtual] = [None, []] func, triplets = self.__eventinfo[virtual] for seq in sequences: triplet = _parse_sequence(seq) if triplet is None: #print("Tkinter event_add(%s)" % seq, file=sys.__stderr__) widget.event_add(self, virtual, seq) else: if func is not None: self.__binders[triplet[1]].bind(triplet, func) triplets.append(triplet) def event_delete(self, virtual, *sequences): if virtual not in self.__eventinfo: return func, triplets = self.__eventinfo[virtual] for seq in sequences: triplet = _parse_sequence(seq) if triplet is None: #print("Tkinter event_delete: %s" % seq, file=sys.__stderr__) widget.event_delete(self, virtual, seq) else: if func is not None: self.__binders[triplet[1]].unbind(triplet, func) triplets.remove(triplet) def event_info(self, virtual=None): if virtual is None or virtual not in self.__eventinfo: return widget.event_info(self, virtual) else: return tuple(map(_triplet_to_sequence, self.__eventinfo[virtual][1])) + \ widget.event_info(self, virtual) def __del__(self): for virtual in self.__eventinfo: func, triplets = self.__eventinfo[virtual] if func: for triplet in triplets: try: self.__binders[triplet[1]].unbind(triplet, func) except tkinter.TclError as e: if not APPLICATION_GONE in e.args[0]: raise _multicall_dict[widget] = MultiCall return MultiCall
Return a MultiCall class which inherits its methods from the given widget class (for example, Tkinter.Text). This is used instead of a templating mechanism.
MultiCallCreator
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/multicall.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/multicall.py
MIT
def create_tag_opener(self, indices): """Highlight the single paren that matches""" self.text.tag_add("paren", indices[0]) self.text.tag_config("paren", self.HILITE_CONFIG)
Highlight the single paren that matches
create_tag_opener
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
MIT
def create_tag_parens(self, indices): """Highlight the left and right parens""" if self.text.get(indices[1]) in (')', ']', '}'): rightindex = indices[1]+"+1c" else: rightindex = indices[1] self.text.tag_add("paren", indices[0], indices[0]+"+1c", rightindex+"-1c", rightindex) self.text.tag_config("paren", self.HILITE_CONFIG)
Highlight the left and right parens
create_tag_parens
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
MIT
def create_tag_expression(self, indices): """Highlight the entire expression""" if self.text.get(indices[1]) in (')', ']', '}'): rightindex = indices[1]+"+1c" else: rightindex = indices[1] self.text.tag_add("paren", indices[0], rightindex) self.text.tag_config("paren", self.HILITE_CONFIG)
Highlight the entire expression
create_tag_expression
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
MIT
def set_timeout_none(self): """Highlight will remain until user input turns it off or the insert has moved""" # After CHECK_DELAY, call a function which disables the "paren" tag # if the event is for the most recent timer and the insert has changed, # or schedules another call for itself. self.counter += 1 def callme(callme, self=self, c=self.counter, index=self.text.index("insert")): if index != self.text.index("insert"): self.handle_restore_timer(c) else: self.editwin.text_frame.after(CHECK_DELAY, callme, callme) self.editwin.text_frame.after(CHECK_DELAY, callme, callme)
Highlight will remain until user input turns it off or the insert has moved
set_timeout_none
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
MIT
def set_timeout_last(self): """The last highlight created will be removed after FLASH_DELAY millisecs""" # associate a counter with an event; only disable the "paren" # tag if the event is for the most recent timer. self.counter += 1 self.editwin.text_frame.after( self.FLASH_DELAY, lambda self=self, c=self.counter: self.handle_restore_timer(c))
The last highlight created will be removed after FLASH_DELAY millisecs
set_timeout_last
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/parenmatch.py
MIT
def __init__(self, text): '''Initialize data attributes and bind event methods. .text - Idle wrapper of tk Text widget, with .bell(). .history - source statements, possibly with multiple lines. .prefix - source already entered at prompt; filters history list. .pointer - index into history. .cyclic - wrap around history list (or not). ''' self.text = text self.history = [] self.prefix = None self.pointer = None self.cyclic = idleConf.GetOption("main", "History", "cyclic", 1, "bool") text.bind("<<history-previous>>", self.history_prev) text.bind("<<history-next>>", self.history_next)
Initialize data attributes and bind event methods. .text - Idle wrapper of tk Text widget, with .bell(). .history - source statements, possibly with multiple lines. .prefix - source already entered at prompt; filters history list. .pointer - index into history. .cyclic - wrap around history list (or not).
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/history.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/history.py
MIT
def fetch(self, reverse): '''Fetch statement and replace current line in text widget. Set prefix and pointer as needed for successive fetches. Reset them to None, None when returning to the start line. Sound bell when return to start line or cannot leave a line because cyclic is False. ''' nhist = len(self.history) pointer = self.pointer prefix = self.prefix if pointer is not None and prefix is not None: if self.text.compare("insert", "!=", "end-1c") or \ self.text.get("iomark", "end-1c") != self.history[pointer]: pointer = prefix = None self.text.mark_set("insert", "end-1c") # != after cursor move if pointer is None or prefix is None: prefix = self.text.get("iomark", "end-1c") if reverse: pointer = nhist # will be decremented else: if self.cyclic: pointer = -1 # will be incremented else: # abort history_next self.text.bell() return nprefix = len(prefix) while 1: pointer += -1 if reverse else 1 if pointer < 0 or pointer >= nhist: self.text.bell() if not self.cyclic and pointer < 0: # abort history_prev return else: if self.text.get("iomark", "end-1c") != prefix: self.text.delete("iomark", "end-1c") self.text.insert("iomark", prefix) pointer = prefix = None break item = self.history[pointer] if item[:nprefix] == prefix and len(item) > nprefix: self.text.delete("iomark", "end-1c") self.text.insert("iomark", item) break self.text.see("insert") self.text.tag_remove("sel", "1.0", "end") self.pointer = pointer self.prefix = prefix
Fetch statement and replace current line in text widget. Set prefix and pointer as needed for successive fetches. Reset them to None, None when returning to the start line. Sound bell when return to start line or cannot leave a line because cyclic is False.
fetch
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/history.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/history.py
MIT
def get(root): '''Return the singleton SearchEngine instance for the process. The single SearchEngine saves settings between dialog instances. If there is not a SearchEngine already, make one. ''' if not hasattr(root, "_searchengine"): root._searchengine = SearchEngine(root) # This creates a cycle that persists until root is deleted. return root._searchengine
Return the singleton SearchEngine instance for the process. The single SearchEngine saves settings between dialog instances. If there is not a SearchEngine already, make one.
get
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
MIT
def __init__(self, root): '''Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs. ''' self.root = root # need for report_error() self.patvar = StringVar(root, '') # search pattern self.revar = BooleanVar(root, False) # regular expression? self.casevar = BooleanVar(root, False) # match case? self.wordvar = BooleanVar(root, False) # match whole word? self.wrapvar = BooleanVar(root, True) # wrap around buffer? self.backvar = BooleanVar(root, False) # search backwards?
Initialize Variables that save search state. The dialogs bind these to the UI elements present in the dialogs.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
MIT
def search_text(self, text, prog=None, ok=0): '''Return (lineno, matchobj) or None for forward/backward search. This function calls the right function with the right arguments. It directly return the result of that call. Text is a text widget. Prog is a precompiled pattern. The ok parameter is a bit complicated as it has two effects. If there is a selection, the search begin at either end, depending on the direction setting and ok, with ok meaning that the search starts with the selection. Otherwise, search begins at the insert mark. To aid progress, the search functions do not return an empty match at the starting position unless ok is True. ''' if not prog: prog = self.getprog() if not prog: return None # Compilation failed -- stop wrap = self.wrapvar.get() first, last = get_selection(text) if self.isback(): if ok: start = last else: start = first line, col = get_line_col(start) res = self.search_backward(text, prog, line, col, wrap, ok) else: if ok: start = first else: start = last line, col = get_line_col(start) res = self.search_forward(text, prog, line, col, wrap, ok) return res
Return (lineno, matchobj) or None for forward/backward search. This function calls the right function with the right arguments. It directly return the result of that call. Text is a text widget. Prog is a precompiled pattern. The ok parameter is a bit complicated as it has two effects. If there is a selection, the search begin at either end, depending on the direction setting and ok, with ok meaning that the search starts with the selection. Otherwise, search begins at the insert mark. To aid progress, the search functions do not return an empty match at the starting position unless ok is True.
search_text
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
MIT
def search_reverse(prog, chars, col): '''Search backwards and return an re match object or None. This is done by searching forwards until there is no match. Prog: compiled re object with a search method returning a match. Chars: line of text, without \\n. Col: stop index for the search; the limit for match.end(). ''' m = prog.search(chars) if not m: return None found = None i, j = m.span() # m.start(), m.end() == match slice indexes while i < col and j <= col: found = m if i == j: j = j+1 m = prog.search(chars, j) if not m: break i, j = m.span() return found
Search backwards and return an re match object or None. This is done by searching forwards until there is no match. Prog: compiled re object with a search method returning a match. Chars: line of text, without \\n. Col: stop index for the search; the limit for match.end().
search_reverse
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
MIT
def get_selection(text): '''Return tuple of 'line.col' indexes from selection or insert mark. ''' try: first = text.index("sel.first") last = text.index("sel.last") except TclError: first = last = None if not first: first = text.index("insert") if not last: last = first return first, last
Return tuple of 'line.col' indexes from selection or insert mark.
get_selection
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
MIT
def get_line_col(index): '''Return (line, col) tuple of ints from 'line.col' string.''' line, col = map(int, index.split(".")) # Fails on invalid index return line, col
Return (line, col) tuple of ints from 'line.col' string.
get_line_col
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchengine.py
MIT
def idle_formatwarning(message, category, filename, lineno, line=None): """Format warnings the IDLE way.""" s = "\nWarning (from warnings module):\n" s += ' File \"%s\", line %s\n' % (filename, lineno) if line is None: line = linecache.getline(filename, lineno) line = line.strip() if line: s += " %s\n" % line s += "%s: %s\n" % (category.__name__, message) return s
Format warnings the IDLE way.
idle_formatwarning
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def idle_showwarning_subproc( message, category, filename, lineno, file=None, line=None): """Show Idle-format warning after replacing warnings.showwarning. The only difference is the formatter called. """ if file is None: file = sys.stderr try: file.write(idle_formatwarning( message, category, filename, lineno, line)) except OSError: pass # the file (probably stderr) is invalid - this warning gets lost.
Show Idle-format warning after replacing warnings.showwarning. The only difference is the formatter called.
idle_showwarning_subproc
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def handle_tk_events(tcl=tcl): """Process any tk events that are ready to be dispatched if tkinter has been imported, a tcl interpreter has been created and tk has been loaded.""" tcl.eval("update")
Process any tk events that are ready to be dispatched if tkinter has been imported, a tcl interpreter has been created and tk has been loaded.
handle_tk_events
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def main(del_exitfunc=False): """Start the Python execution server in a subprocess In the Python subprocess, RPCServer is instantiated with handlerclass MyHandler, which inherits register/unregister methods from RPCHandler via the mix-in class SocketIO. When the RPCServer 'server' is instantiated, the TCPServer initialization creates an instance of run.MyHandler and calls its handle() method. handle() instantiates a run.Executive object, passing it a reference to the MyHandler object. That reference is saved as attribute rpchandler of the Executive instance. The Executive methods have access to the reference and can pass it on to entities that they command (e.g. debugger_r.Debugger.start_debugger()). The latter, in turn, can call MyHandler(SocketIO) register/unregister methods via the reference to register and unregister themselves. """ global exit_now global quitting global no_exitfunc no_exitfunc = del_exitfunc #time.sleep(15) # test subprocess not responding try: assert(len(sys.argv) > 1) port = int(sys.argv[-1]) except: print("IDLE Subprocess: no IP port passed in sys.argv.", file=sys.__stderr__) return capture_warnings(True) sys.argv[:] = [""] sockthread = threading.Thread(target=manage_socket, name='SockThread', args=((LOCALHOST, port),)) sockthread.daemon = True sockthread.start() while 1: try: if exit_now: try: exit() except KeyboardInterrupt: # exiting but got an extra KBI? Try again! continue try: request = rpc.request_queue.get(block=True, timeout=0.05) except queue.Empty: request = None # Issue 32207: calling handle_tk_events here adds spurious # queue.Empty traceback to event handling exceptions. if request: seq, (method, args, kwargs) = request ret = method(*args, **kwargs) rpc.response_queue.put((seq, ret)) else: handle_tk_events() except KeyboardInterrupt: if quitting: exit_now = True continue except SystemExit: capture_warnings(False) raise except: type, value, tb = sys.exc_info() try: print_exception() rpc.response_queue.put((seq, None)) except: # Link didn't work, print same exception to __stderr__ traceback.print_exception(type, value, tb, file=sys.__stderr__) exit() else: continue
Start the Python execution server in a subprocess In the Python subprocess, RPCServer is instantiated with handlerclass MyHandler, which inherits register/unregister methods from RPCHandler via the mix-in class SocketIO. When the RPCServer 'server' is instantiated, the TCPServer initialization creates an instance of run.MyHandler and calls its handle() method. handle() instantiates a run.Executive object, passing it a reference to the MyHandler object. That reference is saved as attribute rpchandler of the Executive instance. The Executive methods have access to the reference and can pass it on to entities that they command (e.g. debugger_r.Debugger.start_debugger()). The latter, in turn, can call MyHandler(SocketIO) register/unregister methods via the reference to register and unregister themselves.
main
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def flush_stdout(): """XXX How to do this now?"""
XXX How to do this now?
flush_stdout
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def exit(): """Exit subprocess, possibly after first clearing exit functions. If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any functions registered with atexit will be removed before exiting. (VPython support) """ if no_exitfunc: import atexit atexit._clear() capture_warnings(False) sys.exit(0)
Exit subprocess, possibly after first clearing exit functions. If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any functions registered with atexit will be removed before exiting. (VPython support)
exit
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def fix_scaling(root): """Scale fonts on HiDPI displays.""" import tkinter.font scaling = float(root.tk.call('tk', 'scaling')) if scaling > 1.4: for name in tkinter.font.names(root): font = tkinter.font.Font(root=root, name=name, exists=True) size = int(font['size']) if size < 0: font['size'] = round(-0.75*size)
Scale fonts on HiDPI displays.
fix_scaling
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def install_recursionlimit_wrappers(): """Install wrappers to always add 30 to the recursion limit.""" # see: bpo-26806 @functools.wraps(sys.setrecursionlimit) def setrecursionlimit(*args, **kwargs): # mimic the original sys.setrecursionlimit()'s input handling if kwargs: raise TypeError( "setrecursionlimit() takes no keyword arguments") try: limit, = args except ValueError: raise TypeError(f"setrecursionlimit() takes exactly one " f"argument ({len(args)} given)") if not limit > 0: raise ValueError( "recursion limit must be greater or equal than 1") return setrecursionlimit.__wrapped__(limit + RECURSIONLIMIT_DELTA) fixdoc(setrecursionlimit, f"""\ This IDLE wrapper adds {RECURSIONLIMIT_DELTA} to prevent possible uninterruptible loops.""") @functools.wraps(sys.getrecursionlimit) def getrecursionlimit(): return getrecursionlimit.__wrapped__() - RECURSIONLIMIT_DELTA fixdoc(getrecursionlimit, f"""\ This IDLE wrapper subtracts {RECURSIONLIMIT_DELTA} to compensate for the {RECURSIONLIMIT_DELTA} IDLE adds when setting the limit.""") # add the delta to the default recursion limit, to compensate sys.setrecursionlimit(sys.getrecursionlimit() + RECURSIONLIMIT_DELTA) sys.setrecursionlimit = setrecursionlimit sys.getrecursionlimit = getrecursionlimit
Install wrappers to always add 30 to the recursion limit.
install_recursionlimit_wrappers
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def uninstall_recursionlimit_wrappers(): """Uninstall the recursion limit wrappers from the sys module. IDLE only uses this for tests. Users can import run and call this to remove the wrapping. """ if ( getattr(sys.setrecursionlimit, '__wrapped__', None) and getattr(sys.getrecursionlimit, '__wrapped__', None) ): sys.setrecursionlimit = sys.setrecursionlimit.__wrapped__ sys.getrecursionlimit = sys.getrecursionlimit.__wrapped__ sys.setrecursionlimit(sys.getrecursionlimit() - RECURSIONLIMIT_DELTA)
Uninstall the recursion limit wrappers from the sys module. IDLE only uses this for tests. Users can import run and call this to remove the wrapping.
uninstall_recursionlimit_wrappers
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def handle_error(self, request, client_address): """Override RPCServer method for IDLE Interrupt the MainThread and exit server if link is dropped. """ global quitting try: raise except SystemExit: raise except EOFError: global exit_now exit_now = True thread.interrupt_main() except: erf = sys.__stderr__ print('\n' + '-'*40, file=erf) print('Unhandled server exception!', file=erf) print('Thread: %s' % threading.current_thread().name, file=erf) print('Client Address: ', client_address, file=erf) print('Request: ', repr(request), file=erf) traceback.print_exc(file=erf) print('\n*** Unrecoverable, server exiting!', file=erf) print('-'*40, file=erf) quitting = True thread.interrupt_main()
Override RPCServer method for IDLE Interrupt the MainThread and exit server if link is dropped.
handle_error
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def handle(self): """Override base method""" executive = Executive(self) self.register("exec", executive) self.console = self.get_remote_proxy("console") sys.stdin = StdInputFile(self.console, "stdin", iomenu.encoding, iomenu.errors) sys.stdout = StdOutputFile(self.console, "stdout", iomenu.encoding, iomenu.errors) sys.stderr = StdOutputFile(self.console, "stderr", iomenu.encoding, "backslashreplace") sys.displayhook = rpc.displayhook # page help() text to shell. import pydoc # import must be done here to capture i/o binding pydoc.pager = pydoc.plainpager # Keep a reference to stdin so that it won't try to exit IDLE if # sys.stdin gets changed from within IDLE's shell. See issue17838. self._keep_stdin = sys.stdin install_recursionlimit_wrappers() self.interp = self.get_remote_proxy("interp") rpc.RPCHandler.getresponse(self, myseq=None, wait=0.05)
Override base method
handle
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/run.py
MIT
def __init__(self, master, *, _htest=False, _utest=False): """ _htest - bool, change box location when running htest """ self.master = master self._htest = _htest self._utest = _utest self.init()
_htest - bool, change box location when running htest
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/pathbrowser.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/pathbrowser.py
MIT
def _binary_search(self, s): """Find the first index in self.completions where completions[i] is greater or equal to s, or the last index if there is no such. """ i = 0; j = len(self.completions) while j > i: m = (i + j) // 2 if self.completions[m] >= s: j = m else: i = m + 1 return min(i, len(self.completions)-1)
Find the first index in self.completions where completions[i] is greater or equal to s, or the last index if there is no such.
_binary_search
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
MIT
def _complete_string(self, s): """Assuming that s is the prefix of a string in self.completions, return the longest string which is a prefix of all the strings which s is a prefix of them. If s is not a prefix of a string, return s. """ first = self._binary_search(s) if self.completions[first][:len(s)] != s: # There is not even one completion which s is a prefix of. return s # Find the end of the range of completions where s is a prefix of. i = first + 1 j = len(self.completions) while j > i: m = (i + j) // 2 if self.completions[m][:len(s)] != s: j = m else: i = m + 1 last = i-1 if first == last: # only one possible completion return self.completions[first] # We should return the maximum prefix of first and last first_comp = self.completions[first] last_comp = self.completions[last] min_len = min(len(first_comp), len(last_comp)) i = len(s) while i < min_len and first_comp[i] == last_comp[i]: i += 1 return first_comp[:i]
Assuming that s is the prefix of a string in self.completions, return the longest string which is a prefix of all the strings which s is a prefix of them. If s is not a prefix of a string, return s.
_complete_string
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
MIT
def _selection_changed(self): """Call when the selection of the Listbox has changed. Updates the Listbox display and calls _change_start. """ cursel = int(self.listbox.curselection()[0]) self.listbox.see(cursel) lts = self.lasttypedstart selstart = self.completions[cursel] if self._binary_search(lts) == cursel: newstart = lts else: min_len = min(len(lts), len(selstart)) i = 0 while i < min_len and lts[i] == selstart[i]: i += 1 newstart = selstart[:i] self._change_start(newstart) if self.completions[cursel][:len(self.start)] == self.start: # start is a prefix of the selected completion self.listbox.configure(selectbackground=self.origselbackground, selectforeground=self.origselforeground) else: self.listbox.configure(selectbackground=self.listbox.cget("bg"), selectforeground=self.listbox.cget("fg")) # If there are more completions, show them, and call me again. if self.morecompletions: self.completions = self.morecompletions self.morecompletions = None self.listbox.delete(0, END) for item in self.completions: self.listbox.insert(END, item) self.listbox.select_set(self._binary_search(self.start)) self._selection_changed()
Call when the selection of the Listbox has changed. Updates the Listbox display and calls _change_start.
_selection_changed
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
MIT
def show_window(self, comp_lists, index, complete, mode, userWantsWin): """Show the autocomplete list, bind events. If complete is True, complete the text, and if there is exactly one matching completion, don't open a list. """ # Handle the start we already have self.completions, self.morecompletions = comp_lists self.mode = mode self.startindex = self.widget.index(index) self.start = self.widget.get(self.startindex, "insert") if complete: completed = self._complete_string(self.start) start = self.start self._change_start(completed) i = self._binary_search(completed) if self.completions[i] == completed and \ (i == len(self.completions)-1 or self.completions[i+1][:len(completed)] != completed): # There is exactly one matching completion return completed == start self.userwantswindow = userWantsWin self.lasttypedstart = self.start # Put widgets in place self.autocompletewindow = acw = Toplevel(self.widget) # Put it in a position so that it is not seen. acw.wm_geometry("+10000+10000") # Make it float acw.wm_overrideredirect(1) try: # This command is only needed and available on Tk >= 8.4.0 for OSX # Without it, call tips intrude on the typing process by grabbing # the focus. acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w, "help", "noActivates") except TclError: pass self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL) self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set, exportselection=False) for item in self.completions: listbox.insert(END, item) self.origselforeground = listbox.cget("selectforeground") self.origselbackground = listbox.cget("selectbackground") scrollbar.config(command=listbox.yview) scrollbar.pack(side=RIGHT, fill=Y) listbox.pack(side=LEFT, fill=BOTH, expand=True) acw.lift() # work around bug in Tk 8.5.18+ (issue #24570) # Initialize the listbox selection self.listbox.select_set(self._binary_search(self.start)) self._selection_changed() # bind events self.hideaid = acw.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) self.hidewid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) acw.event_add(HIDE_VIRTUAL_EVENT_NAME, HIDE_FOCUS_OUT_SEQUENCE) for seq in HIDE_SEQUENCES: self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq) self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME, self.keypress_event) for seq in KEYPRESS_SEQUENCES: self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq) self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME, self.keyrelease_event) self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE) self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE, self.listselect_event) self.is_configuring = False self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event) self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE, self.doubleclick_event) return None
Show the autocomplete list, bind events. If complete is True, complete the text, and if there is exactly one matching completion, don't open a list.
show_window
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/autocomplete_w.py
MIT
def __init__(self, parent, title, action, current_key_sequences, *, _htest=False, _utest=False): """ parent - parent of this dialog title - string which is the title of the popup dialog action - string, the name of the virtual event these keys will be mapped to current_key_sequences - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest _utest - bool, do not wait when running unittest """ Toplevel.__init__(self, parent) self.withdraw() # Hide while setting geometry. self.configure(borderwidth=5) self.resizable(height=False, width=False) self.title(title) self.transient(parent) self.grab_set() self.protocol("WM_DELETE_WINDOW", self.cancel) self.parent = parent self.action = action self.current_key_sequences = current_key_sequences self.result = '' self.key_string = StringVar(self) self.key_string.set('') # Set self.modifiers, self.modifier_label. self.set_modifiers_for_platform() self.modifier_vars = [] for modifier in self.modifiers: variable = StringVar(self) variable.set('') self.modifier_vars.append(variable) self.advanced = False self.create_widgets() self.update_idletasks() self.geometry( "+%d+%d" % ( parent.winfo_rootx() + (parent.winfo_width()/2 - self.winfo_reqwidth()/2), parent.winfo_rooty() + ((parent.winfo_height()/2 - self.winfo_reqheight()/2) if not _htest else 150) ) ) # Center dialog over parent (or below htest box). if not _utest: self.deiconify() # Geometry set, unhide. self.wait_window()
parent - parent of this dialog title - string which is the title of the popup dialog action - string, the name of the virtual event these keys will be mapped to current_key_sequences - list, a list of all key sequence lists currently mapped to virtual events, for overlap checking _htest - bool, change box location when running htest _utest - bool, do not wait when running unittest
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/config_key.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/config_key.py
MIT
def set_modifiers_for_platform(self): """Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys; it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering. """ if sys.platform == "darwin": self.modifiers = ['Shift', 'Control', 'Option', 'Command'] else: self.modifiers = ['Control', 'Alt', 'Shift'] self.modifier_label = {'Control': 'Ctrl'} # Short name.
Determine list of names of key modifiers for this platform. The names are used to build Tk bindings -- it doesn't matter if the keyboard has these keys; it matters if Tk understands them. The order is also important: key binding equality depends on it, so config-keys.def must use the same ordering.
set_modifiers_for_platform
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/config_key.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/config_key.py
MIT
def keys_ok(self, keys): """Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set. """ final_key = self.list_keys_final.get('anchor') modifiers = self.get_modifiers() title = self.keyerror_title key_sequences = [key for keylist in self.current_key_sequences for key in keylist] if not keys.endswith('>'): self.showerror(title, parent=self, message='Missing the final Key') elif (not modifiers and final_key not in FUNCTION_KEYS + MOVE_KEYS): self.showerror(title=title, parent=self, message='No modifier key(s) specified.') elif (modifiers == ['Shift']) \ and (final_key not in FUNCTION_KEYS + MOVE_KEYS + ('Tab', 'Space')): msg = 'The shift modifier by itself may not be used with'\ ' this key symbol.' self.showerror(title=title, parent=self, message=msg) elif keys in key_sequences: msg = 'This key combination is already in use.' self.showerror(title=title, parent=self, message=msg) else: return True return False
Validity check on user's 'basic' keybinding selection. Doesn't check the string produced by the advanced dialog because 'modifiers' isn't set.
keys_ok
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/config_key.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/config_key.py
MIT
def __init__(self, root, engine): '''Initialize root, engine, and top attributes. top (level widget): set in create_widgets() called from open(). text (Text searched): set in open(), only used in subclasses(). ent (ry): created in make_entry() called from create_entry(). row (of grid): 0 in create_widgets(), +1 in make_entry/frame(). default_command: set in subclasses, used in create_widgets(). title (of dialog): class attribute, override in subclasses. icon (of dialog): ditto, use unclear if cannot minimize dialog. ''' self.root = root self.bell = root.bell self.engine = engine self.top = None
Initialize root, engine, and top attributes. top (level widget): set in create_widgets() called from open(). text (Text searched): set in open(), only used in subclasses(). ent (ry): created in make_entry() called from create_entry(). row (of grid): 0 in create_widgets(), +1 in make_entry/frame(). default_command: set in subclasses, used in create_widgets(). title (of dialog): class attribute, override in subclasses. icon (of dialog): ditto, use unclear if cannot minimize dialog.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
MIT
def create_widgets(self): '''Create basic 3 row x 3 col search (find) dialog. Other dialogs override subsidiary create_x methods as needed. Replace and Find-in-Files add another entry row. ''' top = Toplevel(self.root) top.bind("<Return>", self.default_command) top.bind("<Escape>", self.close) top.protocol("WM_DELETE_WINDOW", self.close) top.wm_title(self.title) top.wm_iconname(self.icon) self.top = top self.row = 0 self.top.grid_columnconfigure(0, pad=2, weight=0) self.top.grid_columnconfigure(1, pad=2, minsize=100, weight=100) self.create_entries() # row 0 (and maybe 1), cols 0, 1 self.create_option_buttons() # next row, cols 0, 1 self.create_other_buttons() # next row, cols 0, 1 self.create_command_buttons() # col 2, all rows
Create basic 3 row x 3 col search (find) dialog. Other dialogs override subsidiary create_x methods as needed. Replace and Find-in-Files add another entry row.
create_widgets
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
MIT
def make_entry(self, label_text, var): '''Return (entry, label), . entry - gridded labeled Entry for text entry. label - Label widget, returned for testing. ''' label = Label(self.top, text=label_text) label.grid(row=self.row, column=0, sticky="nw") entry = Entry(self.top, textvariable=var, exportselection=0) entry.grid(row=self.row, column=1, sticky="nwe") self.row = self.row + 1 return entry, label
Return (entry, label), . entry - gridded labeled Entry for text entry. label - Label widget, returned for testing.
make_entry
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
MIT
def make_frame(self,labeltext=None): '''Return (frame, label). frame - gridded labeled Frame for option or other buttons. label - Label widget, returned for testing. ''' if labeltext: label = Label(self.top, text=labeltext) label.grid(row=self.row, column=0, sticky="nw") else: label = '' frame = Frame(self.top) frame.grid(row=self.row, column=1, columnspan=1, sticky="nwe") self.row = self.row + 1 return frame, label
Return (frame, label). frame - gridded labeled Frame for option or other buttons. label - Label widget, returned for testing.
make_frame
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
MIT
def create_option_buttons(self): '''Return (filled frame, options) for testing. Options is a list of searchengine booleanvar, label pairs. A gridded frame from make_frame is filled with a Checkbutton for each pair, bound to the var, with the corresponding label. ''' frame = self.make_frame("Options")[0] engine = self.engine options = [(engine.revar, "Regular expression"), (engine.casevar, "Match case"), (engine.wordvar, "Whole word")] if self.needwrapbutton: options.append((engine.wrapvar, "Wrap around")) for var, label in options: btn = Checkbutton(frame, variable=var, text=label) btn.pack(side="left", fill="both") return frame, options
Return (filled frame, options) for testing. Options is a list of searchengine booleanvar, label pairs. A gridded frame from make_frame is filled with a Checkbutton for each pair, bound to the var, with the corresponding label.
create_option_buttons
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
MIT
def create_other_buttons(self): '''Return (frame, others) for testing. Others is a list of value, label pairs. A gridded frame from make_frame is filled with radio buttons. ''' frame = self.make_frame("Direction")[0] var = self.engine.backvar others = [(1, 'Up'), (0, 'Down')] for val, label in others: btn = Radiobutton(frame, variable=var, value=val, text=label) btn.pack(side="left", fill="both") return frame, others
Return (frame, others) for testing. Others is a list of value, label pairs. A gridded frame from make_frame is filled with radio buttons.
create_other_buttons
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/searchbase.py
MIT
def get_end_linenumber(text): """Utility to get the last line's number in a Tk text widget.""" return int(float(text.index('end-1c')))
Utility to get the last line's number in a Tk text widget.
get_end_linenumber
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def get_widget_padding(widget): """Get the total padding of a Tk widget, including its border.""" # TODO: use also in codecontext.py manager = widget.winfo_manager() if manager == 'pack': info = widget.pack_info() elif manager == 'grid': info = widget.grid_info() else: raise ValueError(f"Unsupported geometry manager: {manager}") # All values are passed through getint(), since some # values may be pixel objects, which can't simply be added to ints. padx = sum(map(widget.tk.getint, [ info['padx'], widget.cget('padx'), widget.cget('border'), ])) pady = sum(map(widget.tk.getint, [ info['pady'], widget.cget('pady'), widget.cget('border'), ])) return padx, pady
Get the total padding of a Tk widget, including its border.
get_widget_padding
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def update_font(self): """Update the sidebar text font, usually after config changes.""" font = idleConf.GetFont(self.text, 'main', 'EditorWindow') self._update_font(font)
Update the sidebar text font, usually after config changes.
update_font
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def update_colors(self): """Update the sidebar text colors, usually after config changes.""" colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'normal') self._update_colors(foreground=colors['foreground'], background=colors['background'])
Update the sidebar text colors, usually after config changes.
update_colors
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def redirect_yscroll_event(self, *args, **kwargs): """Redirect vertical scrolling to the main editor text widget. The scroll bar is also updated. """ self.editwin.vbar.set(*args) self.sidebar_text.yview_moveto(args[0]) return 'break'
Redirect vertical scrolling to the main editor text widget. The scroll bar is also updated.
redirect_yscroll_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def redirect_focusin_event(self, event): """Redirect focus-in events to the main editor text widget.""" self.text.focus_set() return 'break'
Redirect focus-in events to the main editor text widget.
redirect_focusin_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def redirect_mousebutton_event(self, event, event_name): """Redirect mouse button events to the main editor text widget.""" self.text.focus_set() self.text.event_generate(event_name, x=0, y=event.y) return 'break'
Redirect mouse button events to the main editor text widget.
redirect_mousebutton_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def redirect_mousewheel_event(self, event): """Redirect mouse wheel events to the editwin text widget.""" self.text.event_generate('<MouseWheel>', x=0, y=event.y, delta=event.delta) return 'break'
Redirect mouse wheel events to the editwin text widget.
redirect_mousewheel_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def __init__(self, changed_callback): """ changed_callback - Callable, will be called after insert or delete operations with the current end line number. """ Delegator.__init__(self) self.changed_callback = changed_callback
changed_callback - Callable, will be called after insert or delete operations with the current end line number.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def drag_update_selection_and_insert_mark(y_coord): """Helper function for drag and selection event handlers.""" lineno = int(float(self.sidebar_text.index(f"@0,{y_coord}"))) a, b = sorted([start_line, lineno]) self.text.tag_remove("sel", "1.0", "end") self.text.tag_add("sel", f"{a}.0", f"{b+1}.0") self.text.mark_set("insert", f"{lineno if lineno == a else lineno + 1}.0")
Helper function for drag and selection event handlers.
bind_events.drag_update_selection_and_insert_mark
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def bind_events(self): # Ensure focus is always redirected to the main editor text widget. self.sidebar_text.bind('<FocusIn>', self.redirect_focusin_event) # Redirect mouse scrolling to the main editor text widget. # # Note that without this, scrolling with the mouse only scrolls # the line numbers. self.sidebar_text.bind('<MouseWheel>', self.redirect_mousewheel_event) # Redirect mouse button events to the main editor text widget, # except for the left mouse button (1). # # Note: X-11 sends Button-4 and Button-5 events for the scroll wheel. def bind_mouse_event(event_name, target_event_name): handler = functools.partial(self.redirect_mousebutton_event, event_name=target_event_name) self.sidebar_text.bind(event_name, handler) for button in [2, 3, 4, 5]: for event_name in (f'<Button-{button}>', f'<ButtonRelease-{button}>', f'<B{button}-Motion>', ): bind_mouse_event(event_name, target_event_name=event_name) # Convert double- and triple-click events to normal click events, # since event_generate() doesn't allow generating such events. for event_name in (f'<Double-Button-{button}>', f'<Triple-Button-{button}>', ): bind_mouse_event(event_name, target_event_name=f'<Button-{button}>') # This is set by b1_mousedown_handler() and read by # drag_update_selection_and_insert_mark(), to know where dragging # began. start_line = None # These are set by b1_motion_handler() and read by selection_handler(). # last_y is passed this way since the mouse Y-coordinate is not # available on selection event objects. last_yview is passed this way # to recognize scrolling while the mouse isn't moving. last_y = last_yview = None def b1_mousedown_handler(event): # select the entire line lineno = int(float(self.sidebar_text.index(f"@0,{event.y}"))) self.text.tag_remove("sel", "1.0", "end") self.text.tag_add("sel", f"{lineno}.0", f"{lineno+1}.0") self.text.mark_set("insert", f"{lineno+1}.0") # remember this line in case this is the beginning of dragging nonlocal start_line start_line = lineno self.sidebar_text.bind('<Button-1>', b1_mousedown_handler) def b1_mouseup_handler(event): # On mouse up, we're no longer dragging. Set the shared persistent # variables to None to represent this. nonlocal start_line nonlocal last_y nonlocal last_yview start_line = None last_y = None last_yview = None self.sidebar_text.bind('<ButtonRelease-1>', b1_mouseup_handler) def drag_update_selection_and_insert_mark(y_coord): """Helper function for drag and selection event handlers.""" lineno = int(float(self.sidebar_text.index(f"@0,{y_coord}"))) a, b = sorted([start_line, lineno]) self.text.tag_remove("sel", "1.0", "end") self.text.tag_add("sel", f"{a}.0", f"{b+1}.0") self.text.mark_set("insert", f"{lineno if lineno == a else lineno + 1}.0") # Special handling of dragging with mouse button 1. In "normal" text # widgets this selects text, but the line numbers text widget has # selection disabled. Still, dragging triggers some selection-related # functionality under the hood. Specifically, dragging to above or # below the text widget triggers scrolling, in a way that bypasses the # other scrolling synchronization mechanisms.i def b1_drag_handler(event, *args): nonlocal last_y nonlocal last_yview last_y = event.y last_yview = self.sidebar_text.yview() if not 0 <= last_y <= self.sidebar_text.winfo_height(): self.text.yview_moveto(last_yview[0]) drag_update_selection_and_insert_mark(event.y) self.sidebar_text.bind('<B1-Motion>', b1_drag_handler) # With mouse-drag scrolling fixed by the above, there is still an edge- # case we need to handle: When drag-scrolling, scrolling can continue # while the mouse isn't moving, leading to the above fix not scrolling # properly. def selection_handler(event): if last_yview is None: # This logic is only needed while dragging. return yview = self.sidebar_text.yview() if yview != last_yview: self.text.yview_moveto(yview[0]) drag_update_selection_and_insert_mark(last_y) self.sidebar_text.bind('<<Selection>>', selection_handler)
Helper function for drag and selection event handlers.
bind_events
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def update_colors(self): """Update the sidebar text colors, usually after config changes.""" colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'linenumber') self._update_colors(foreground=colors['foreground'], background=colors['background'])
Update the sidebar text colors, usually after config changes.
update_colors
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def update_sidebar_text(self, end): """ Perform the following action: Each line sidebar_text contains the linenumber for that line Synchronize with editwin.text so that both sidebar_text and editwin.text contain the same number of lines""" if end == self.prev_end: return width_difference = len(str(end)) - len(str(self.prev_end)) if width_difference: cur_width = int(float(self.sidebar_text['width'])) new_width = cur_width + width_difference self.sidebar_text['width'] = self._sidebar_width_type(new_width) self.sidebar_text.config(state=tk.NORMAL) if end > self.prev_end: new_text = '\n'.join(itertools.chain( [''], map(str, range(self.prev_end + 1, end + 1)), )) self.sidebar_text.insert(f'end -1c', new_text, 'linenumber') else: self.sidebar_text.delete(f'{end+1}.0 -1c', 'end -1c') self.sidebar_text.config(state=tk.DISABLED) self.prev_end = end
Perform the following action: Each line sidebar_text contains the linenumber for that line Synchronize with editwin.text so that both sidebar_text and editwin.text contain the same number of lines
update_sidebar_text
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/sidebar.py
MIT
def set_index(self, index): """Set the index to which the functions relate. The index must be in the same statement. """ indexinrawtext = (len(self.rawtext) - len(self.text.get(index, self.stopatindex))) if indexinrawtext < 0: raise ValueError("Index %s precedes the analyzed statement" % index) self.indexinrawtext = indexinrawtext # find the rightmost bracket to which index belongs self.indexbracket = 0 while (self.indexbracket < len(self.bracketing)-1 and self.bracketing[self.indexbracket+1][0] < self.indexinrawtext): self.indexbracket += 1 if (self.indexbracket < len(self.bracketing)-1 and self.bracketing[self.indexbracket+1][0] == self.indexinrawtext and not self.isopener[self.indexbracket+1]): self.indexbracket += 1
Set the index to which the functions relate. The index must be in the same statement.
set_index
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/hyperparser.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/hyperparser.py
MIT
def is_in_string(self): """Is the index given to the HyperParser in a string?""" # The bracket to which we belong should be an opener. # If it's an opener, it has to have a character. return (self.isopener[self.indexbracket] and self.rawtext[self.bracketing[self.indexbracket][0]] in ('"', "'"))
Is the index given to the HyperParser in a string?
is_in_string
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/hyperparser.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/hyperparser.py
MIT
def is_in_code(self): """Is the index given to the HyperParser in normal code?""" return (not self.isopener[self.indexbracket] or self.rawtext[self.bracketing[self.indexbracket][0]] not in ('#', '"', "'"))
Is the index given to the HyperParser in normal code?
is_in_code
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/hyperparser.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/hyperparser.py
MIT
def get_surrounding_brackets(self, openers='([{', mustclose=False): """Return bracket indexes or None. If the index given to the HyperParser is surrounded by a bracket defined in openers (or at least has one before it), return the indices of the opening bracket and the closing bracket (or the end of line, whichever comes first). If it is not surrounded by brackets, or the end of line comes before the closing bracket and mustclose is True, returns None. """ bracketinglevel = self.bracketing[self.indexbracket][1] before = self.indexbracket while (not self.isopener[before] or self.rawtext[self.bracketing[before][0]] not in openers or self.bracketing[before][1] > bracketinglevel): before -= 1 if before < 0: return None bracketinglevel = min(bracketinglevel, self.bracketing[before][1]) after = self.indexbracket + 1 while (after < len(self.bracketing) and self.bracketing[after][1] >= bracketinglevel): after += 1 beforeindex = self.text.index("%s-%dc" % (self.stopatindex, len(self.rawtext)-self.bracketing[before][0])) if (after >= len(self.bracketing) or self.bracketing[after][0] > len(self.rawtext)): if mustclose: return None afterindex = self.stopatindex else: # We are after a real char, so it is a ')' and we give the # index before it. afterindex = self.text.index( "%s-%dc" % (self.stopatindex, len(self.rawtext)-(self.bracketing[after][0]-1))) return beforeindex, afterindex
Return bracket indexes or None. If the index given to the HyperParser is surrounded by a bracket defined in openers (or at least has one before it), return the indices of the opening bracket and the closing bracket (or the end of line, whichever comes first). If it is not surrounded by brackets, or the end of line comes before the closing bracket and mustclose is True, returns None.
get_surrounding_brackets
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/hyperparser.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/hyperparser.py
MIT
def _eat_identifier(cls, str, limit, pos): """Given a string and pos, return the number of chars in the identifier which ends at pos, or 0 if there is no such one. This ignores non-identifier eywords are not identifiers. """ is_ascii_id_char = _IS_ASCII_ID_CHAR # Start at the end (pos) and work backwards. i = pos # Go backwards as long as the characters are valid ASCII # identifier characters. This is an optimization, since it # is faster in the common case where most of the characters # are ASCII. while i > limit and ( ord(str[i - 1]) < 128 and is_ascii_id_char[ord(str[i - 1])] ): i -= 1 # If the above loop ended due to reaching a non-ASCII # character, continue going backwards using the most generic # test for whether a string contains only valid identifier # characters. if i > limit and ord(str[i - 1]) >= 128: while i - 4 >= limit and ('a' + str[i - 4:pos]).isidentifier(): i -= 4 if i - 2 >= limit and ('a' + str[i - 2:pos]).isidentifier(): i -= 2 if i - 1 >= limit and ('a' + str[i - 1:pos]).isidentifier(): i -= 1 # The identifier candidate starts here. If it isn't a valid # identifier, don't eat anything. At this point that is only # possible if the first character isn't a valid first # character for an identifier. if not str[i:pos].isidentifier(): return 0 elif i < pos: # All characters in str[i:pos] are valid ASCII identifier # characters, so it is enough to check that the first is # valid as the first character of an identifier. if not _IS_ASCII_ID_FIRST_CHAR[ord(str[i])]: return 0 # All keywords are valid identifiers, but should not be # considered identifiers here, except for True, False and None. if i < pos and ( iskeyword(str[i:pos]) and str[i:pos] not in cls._ID_KEYWORDS ): return 0 return pos - i
Given a string and pos, return the number of chars in the identifier which ends at pos, or 0 if there is no such one. This ignores non-identifier eywords are not identifiers.
_eat_identifier
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/hyperparser.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/hyperparser.py
MIT
def get_expression(self): """Return a string with the Python expression which ends at the given index, which is empty if there is no real one. """ if not self.is_in_code(): raise ValueError("get_expression should only be called " "if index is inside a code.") rawtext = self.rawtext bracketing = self.bracketing brck_index = self.indexbracket brck_limit = bracketing[brck_index][0] pos = self.indexinrawtext last_identifier_pos = pos postdot_phase = True while 1: # Eat whitespaces, comments, and if postdot_phase is False - a dot while 1: if pos>brck_limit and rawtext[pos-1] in self._whitespace_chars: # Eat a whitespace pos -= 1 elif (not postdot_phase and pos > brck_limit and rawtext[pos-1] == '.'): # Eat a dot pos -= 1 postdot_phase = True # The next line will fail if we are *inside* a comment, # but we shouldn't be. elif (pos == brck_limit and brck_index > 0 and rawtext[bracketing[brck_index-1][0]] == '#'): # Eat a comment brck_index -= 2 brck_limit = bracketing[brck_index][0] pos = bracketing[brck_index+1][0] else: # If we didn't eat anything, quit. break if not postdot_phase: # We didn't find a dot, so the expression end at the # last identifier pos. break ret = self._eat_identifier(rawtext, brck_limit, pos) if ret: # There is an identifier to eat pos = pos - ret last_identifier_pos = pos # Now, to continue the search, we must find a dot. postdot_phase = False # (the loop continues now) elif pos == brck_limit: # We are at a bracketing limit. If it is a closing # bracket, eat the bracket, otherwise, stop the search. level = bracketing[brck_index][1] while brck_index > 0 and bracketing[brck_index-1][1] > level: brck_index -= 1 if bracketing[brck_index][0] == brck_limit: # We were not at the end of a closing bracket break pos = bracketing[brck_index][0] brck_index -= 1 brck_limit = bracketing[brck_index][0] last_identifier_pos = pos if rawtext[pos] in "([": # [] and () may be used after an identifier, so we # continue. postdot_phase is True, so we don't allow a dot. pass else: # We can't continue after other types of brackets if rawtext[pos] in "'\"": # Scan a string prefix while pos > 0 and rawtext[pos - 1] in "rRbBuU": pos -= 1 last_identifier_pos = pos break else: # We've found an operator or something. break return rawtext[last_identifier_pos:self.indexinrawtext]
Return a string with the Python expression which ends at the given index, which is empty if there is no real one.
get_expression
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/hyperparser.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/hyperparser.py
MIT
def coding_spec(data): """Return the encoding declaration according to PEP 263. When checking encoded data, only the first two lines should be passed in to avoid a UnicodeDecodeError if the rest of the data is not unicode. The first two lines would contain the encoding specification. Raise a LookupError if the encoding is declared but unknown. """ if isinstance(data, bytes): # This encoding might be wrong. However, the coding # spec must be ASCII-only, so any non-ASCII characters # around here will be ignored. Decoding to Latin-1 should # never fail (except for memory outage) lines = data.decode('iso-8859-1') else: lines = data # consider only the first two lines if '\n' in lines: lst = lines.split('\n', 2)[:2] elif '\r' in lines: lst = lines.split('\r', 2)[:2] else: lst = [lines] for line in lst: match = coding_re.match(line) if match is not None: break if not blank_re.match(line): return None else: return None name = match.group(1) try: codecs.lookup(name) except LookupError: # The standard encoding error does not indicate the encoding raise LookupError("Unknown encoding: "+name) return name
Return the encoding declaration according to PEP 263. When checking encoded data, only the first two lines should be passed in to avoid a UnicodeDecodeError if the rest of the data is not unicode. The first two lines would contain the encoding specification. Raise a LookupError if the encoding is declared but unknown.
coding_spec
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/iomenu.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/iomenu.py
MIT
def grep(text, io=None, flist=None): """Open the Find in Files dialog. Module-level function to access the singleton GrepDialog instance and open the dialog. If text is selected, it is used as the search phrase; otherwise, the previous entry is used. Args: text: Text widget that contains the selected text for default search phrase. io: iomenu.IOBinding instance with default path to search. flist: filelist.FileList instance for OutputWindow parent. """ root = text._root() engine = searchengine.get(root) if not hasattr(engine, "_grepdialog"): engine._grepdialog = GrepDialog(root, engine, flist) dialog = engine._grepdialog searchphrase = text.get("sel.first", "sel.last") dialog.open(text, searchphrase, io)
Open the Find in Files dialog. Module-level function to access the singleton GrepDialog instance and open the dialog. If text is selected, it is used as the search phrase; otherwise, the previous entry is used. Args: text: Text widget that contains the selected text for default search phrase. io: iomenu.IOBinding instance with default path to search. flist: filelist.FileList instance for OutputWindow parent.
grep
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/grep.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/grep.py
MIT
def findfiles(folder, pattern, recursive): """Generate file names in dir that match pattern. Args: folder: Root directory to search. pattern: File pattern to match. recursive: True to include subdirectories. """ for dirpath, _, filenames in os.walk(folder, onerror=walk_error): yield from (os.path.join(dirpath, name) for name in filenames if fnmatch.fnmatch(name, pattern)) if not recursive: break
Generate file names in dir that match pattern. Args: folder: Root directory to search. pattern: File pattern to match. recursive: True to include subdirectories.
findfiles
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/grep.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/grep.py
MIT
def __init__(self, root, engine, flist): """Create search dialog for searching for a phrase in the file system. Uses SearchDialogBase as the basis for the GUI and a searchengine instance to prepare the search. Attributes: flist: filelist.Filelist instance for OutputWindow parent. globvar: String value of Entry widget for path to search. globent: Entry widget for globvar. Created in create_entries(). recvar: Boolean value of Checkbutton widget for traversing through subdirectories. """ super().__init__(root, engine) self.flist = flist self.globvar = StringVar(root) self.recvar = BooleanVar(root)
Create search dialog for searching for a phrase in the file system. Uses SearchDialogBase as the basis for the GUI and a searchengine instance to prepare the search. Attributes: flist: filelist.Filelist instance for OutputWindow parent. globvar: String value of Entry widget for path to search. globent: Entry widget for globvar. Created in create_entries(). recvar: Boolean value of Checkbutton widget for traversing through subdirectories.
__init__
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/grep.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/grep.py
MIT
def open(self, text, searchphrase, io=None): """Make dialog visible on top of others and ready to use. Extend the SearchDialogBase open() to set the initial value for globvar. Args: text: Multicall object containing the text information. searchphrase: String phrase to search. io: iomenu.IOBinding instance containing file path. """ SearchDialogBase.open(self, text, searchphrase) if io: path = io.filename or "" else: path = "" dir, base = os.path.split(path) head, tail = os.path.splitext(base) if not tail: tail = ".py" self.globvar.set(os.path.join(dir, "*" + tail))
Make dialog visible on top of others and ready to use. Extend the SearchDialogBase open() to set the initial value for globvar. Args: text: Multicall object containing the text information. searchphrase: String phrase to search. io: iomenu.IOBinding instance containing file path.
open
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/grep.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/grep.py
MIT
def default_command(self, event=None): """Grep for search pattern in file path. The default command is bound to <Return>. If entry values are populated, set OutputWindow as stdout and perform search. The search dialog is closed automatically when the search begins. """ prog = self.engine.getprog() if not prog: return path = self.globvar.get() if not path: self.top.bell() return from idlelib.outwin import OutputWindow # leave here! save = sys.stdout try: sys.stdout = OutputWindow(self.flist) self.grep_it(prog, path) finally: sys.stdout = save
Grep for search pattern in file path. The default command is bound to <Return>. If entry values are populated, set OutputWindow as stdout and perform search. The search dialog is closed automatically when the search begins.
default_command
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/grep.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/grep.py
MIT
def grep_it(self, prog, path): """Search for prog within the lines of the files in path. For the each file in the path directory, open the file and search each line for the matching pattern. If the pattern is found, write the file and line information to stdout (which is an OutputWindow). Args: prog: The compiled, cooked search pattern. path: String containing the search path. """ folder, filepat = os.path.split(path) if not folder: folder = os.curdir filelist = sorted(findfiles(folder, filepat, self.recvar.get())) self.close() pat = self.engine.getpat() print(f"Searching {pat!r} in {path} ...") hits = 0 try: for fn in filelist: try: with open(fn, errors='replace') as f: for lineno, line in enumerate(f, 1): if line[-1:] == '\n': line = line[:-1] if prog.search(line): sys.stdout.write(f"{fn}: {lineno}: {line}\n") hits += 1 except OSError as msg: print(msg) print(f"Hits found: {hits}\n(Hint: right-click to open locations.)" if hits else "No hits.") except AttributeError: # Tk window has been closed, OutputWindow.text = None, # so in OW.write, OW.text.insert fails. pass
Search for prog within the lines of the files in path. For the each file in the path directory, open the file and search each line for the matching pattern. If the pattern is found, write the file and line information to stdout (which is an OutputWindow). Args: prog: The compiled, cooked search pattern. path: String containing the search path.
grep_it
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/grep.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/grep.py
MIT
def format_paragraph_event(self, event, limit=None): """Formats paragraph to a max width specified in idleConf. If text is selected, format_paragraph_event will start breaking lines at the max width, starting from the beginning selection. If no text is selected, format_paragraph_event uses the current cursor location to determine the paragraph (lines of text surrounded by blank lines) and formats it. The length limit parameter is for testing with a known value. """ limit = self.max_width if limit is None else limit text = self.editwin.text first, last = self.editwin.get_selection_indices() if first and last: data = text.get(first, last) comment_header = get_comment_header(data) else: first, last, comment_header, data = \ find_paragraph(text, text.index("insert")) if comment_header: newdata = reformat_comment(data, limit, comment_header) else: newdata = reformat_paragraph(data, limit) text.tag_remove("sel", "1.0", "end") if newdata != data: text.mark_set("insert", first) text.undo_block_start() text.delete(first, last) text.insert(first, newdata) text.undo_block_stop() else: text.mark_set("insert", last) text.see("insert") return "break"
Formats paragraph to a max width specified in idleConf. If text is selected, format_paragraph_event will start breaking lines at the max width, starting from the beginning selection. If no text is selected, format_paragraph_event uses the current cursor location to determine the paragraph (lines of text surrounded by blank lines) and formats it. The length limit parameter is for testing with a known value.
format_paragraph_event
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/format.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/format.py
MIT
def find_paragraph(text, mark): """Returns the start/stop indices enclosing the paragraph that mark is in. Also returns the comment format string, if any, and paragraph of text between the start/stop indices. """ lineno, col = map(int, mark.split(".")) line = text.get("%d.0" % lineno, "%d.end" % lineno) # Look for start of next paragraph if the index passed in is a blank line while text.compare("%d.0" % lineno, "<", "end") and is_all_white(line): lineno = lineno + 1 line = text.get("%d.0" % lineno, "%d.end" % lineno) first_lineno = lineno comment_header = get_comment_header(line) comment_header_len = len(comment_header) # Once start line found, search for end of paragraph (a blank line) while get_comment_header(line)==comment_header and \ not is_all_white(line[comment_header_len:]): lineno = lineno + 1 line = text.get("%d.0" % lineno, "%d.end" % lineno) last = "%d.0" % lineno # Search back to beginning of paragraph (first blank line before) lineno = first_lineno - 1 line = text.get("%d.0" % lineno, "%d.end" % lineno) while lineno > 0 and \ get_comment_header(line)==comment_header and \ not is_all_white(line[comment_header_len:]): lineno = lineno - 1 line = text.get("%d.0" % lineno, "%d.end" % lineno) first = "%d.0" % (lineno+1) return first, last, comment_header, text.get(first, last)
Returns the start/stop indices enclosing the paragraph that mark is in. Also returns the comment format string, if any, and paragraph of text between the start/stop indices.
find_paragraph
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/format.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/format.py
MIT
def reformat_paragraph(data, limit): """Return data reformatted to specified width (limit).""" lines = data.split("\n") i = 0 n = len(lines) while i < n and is_all_white(lines[i]): i = i+1 if i >= n: return data indent1 = get_indent(lines[i]) if i+1 < n and not is_all_white(lines[i+1]): indent2 = get_indent(lines[i+1]) else: indent2 = indent1 new = lines[:i] partial = indent1 while i < n and not is_all_white(lines[i]): # XXX Should take double space after period (etc.) into account words = re.split(r"(\s+)", lines[i]) for j in range(0, len(words), 2): word = words[j] if not word: continue # Can happen when line ends in whitespace if len((partial + word).expandtabs()) > limit and \ partial != indent1: new.append(partial.rstrip()) partial = indent2 partial = partial + word + " " if j+1 < len(words) and words[j+1] != " ": partial = partial + " " i = i+1 new.append(partial.rstrip()) # XXX Should reformat remaining paragraphs as well new.extend(lines[i:]) return "\n".join(new)
Return data reformatted to specified width (limit).
reformat_paragraph
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/format.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/format.py
MIT
def reformat_comment(data, limit, comment_header): """Return data reformatted to specified width with comment header.""" # Remove header from the comment lines lc = len(comment_header) data = "\n".join(line[lc:] for line in data.split("\n")) # Reformat to maxformatwidth chars or a 20 char width, # whichever is greater. format_width = max(limit - len(comment_header), 20) newdata = reformat_paragraph(data, format_width) # re-split and re-insert the comment header. newdata = newdata.split("\n") # If the block ends in a \n, we don't want the comment prefix # inserted after it. (Im not sure it makes sense to reformat a # comment block that is not made of complete lines, but whatever!) # Can't think of a clean solution, so we hack away block_suffix = "" if not newdata[-1]: block_suffix = "\n" newdata = newdata[:-1] return '\n'.join(comment_header+line for line in newdata) + block_suffix
Return data reformatted to specified width with comment header.
reformat_comment
python
sajjadium/ctf-archives
ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/format.py
https://github.com/sajjadium/ctf-archives/blob/master/ctfs/TyphoonCon/2022/pwn/beautifier_player/python3.7/lib/python3.7/idlelib/format.py
MIT