From e103ebfa583a5eaccc56e0704403f7f94e6448b5 Mon Sep 17 00:00:00 2001 From: Erik Osheim Date: Mon, 31 Aug 2020 20:58:27 -0400 Subject: [PATCH] seems to be working in python 3 --HG-- branch : pmacs2 --- aesutil.py | 14 +++++---- application.py | 68 +++++++++++++++++++++++--------------------- buffer/__init__.py | 23 ++++++++------- buffer/colors.py | 4 +-- buffer/emul.py | 6 ++-- buffer/fs.py | 10 +++---- buffer/pipe.py | 10 +++---- bufferlist.py | 15 ++++++---- color.py | 6 ++-- completer.py | 2 +- context.py | 10 +++---- ctags.py | 8 +++--- dirutil.py | 6 ++-- etags.py | 10 +++---- gdb.py | 8 +++--- highlight.py | 42 +++++++++++++-------------- ispell.py | 8 +++--- keyinput.py | 16 ++++++----- lex.py | 40 +++++++++++++------------- method/__init__.py | 20 ++++++------- method/buffers.py | 10 +++---- method/cvs.py | 2 +- method/git.py | 8 +++--- method/help.py | 4 +-- method/hg.py | 2 +- method/introspect.py | 8 +++--- method/move.py | 2 +- method/search.py | 2 +- method/svn.py | 18 ++++++------ method/utf8.py | 2 +- method/vc.py | 4 +-- miniparse.py | 2 +- mode/__init__.py | 24 ++++++++-------- mode/bosatsu.py | 2 +- mode/colortest.py | 2 +- mode/consolemini.py | 20 ++++++------- mode/dir.py | 6 ++-- mode/erlang.py | 2 +- mode/hex.py | 8 +++--- mode/html.py | 4 +-- mode/ipythonmini.py | 2 +- mode/lua.py | 4 +-- mode/mbox.py | 10 +++---- mode/mp3.py | 6 ++-- mode/ocaml.py | 2 +- mode/perl.py | 4 +-- mode/pipe.py | 4 +-- mode/python.py | 18 ++++++------ mode/scala.py | 2 +- mode/sh.py | 4 +-- mode/shellmini.py | 10 +++---- mode/sql.py | 4 +-- mode/text.py | 4 +-- mode/which.py | 2 +- mode/yacc.py | 2 +- parse.py | 4 +-- render.py | 2 +- searchutil.py | 4 +-- tab.py | 36 +++++++++++------------ util.py | 4 +-- window.py | 21 ++++++++++---- 61 files changed, 313 insertions(+), 294 deletions(-) diff --git a/aesutil.py b/aesutil.py index 8e76ffc..482d9d2 100644 --- a/aesutil.py +++ b/aesutil.py @@ -16,7 +16,8 @@ class Crypter(object): raise CrypterInitError("pycrypto not installed") self.password = password self.salt = salt - self.hash = Crypto.Hash.SHA256.new(password + salt) + pdata = (password + salt).encode('UTF-8') + self.hash = Crypto.Hash.SHA256.new(pdata) self.cipher = Crypto.Cipher.AES.new(self.hash.digest()) self.alignment = alignment @@ -24,21 +25,22 @@ class Crypter(object): '''Add NULL padding to create aligned data''' xtra = len(s) % self.alignment if xtra: - return s + '\x00' * (self.alignment - xtra) + return s + b'\x00' * (self.alignment - xtra) #FIX3 else: return s - + def unpad(self, s): '''Remove NULL padding to restore original data''' l = len(s) - while l > 0 and s[l - 1] == '\x00': + assert type(s) == type(b'') + while l > 0 and s[l - 1] == 0: #FIX3 l -= 1 return s[:l] - + def encrypt(self, data): '''Creates encrypted data string from original input''' return self.cipher.encrypt(self.pad(data)) - + def decrypt(self, data): '''Creates original data string from encrypted input''' return self.unpad(self.cipher.decrypt(self.pad(data))) diff --git a/application.py b/application.py index f63357c..39e1450 100755 --- a/application.py +++ b/application.py @@ -1,4 +1,4 @@ -#!/usr/local/bin/python +#!/usr/local/bin/python3 import curses from getpass import getpass @@ -54,34 +54,34 @@ class Application(object): self.error_timestamp = None self.need_draw = True self.input = keyinput.Handler() - + # white is for delimiters, operators, numbers default = ('default', 'default') - + # magenta is for keywords/builtins, translation, globs #lo_magenta = ('magenta202', 'default') hi_magenta = ('magenta505', 'default') - + # red is for comments, pods, endblocks #lo_red = ('red300', 'default') hi_red = ('red511', 'default') - + # orange are for arrays and hashes #hi_orange = ('yellow531', 'default') #lo_orange = ('yellow520', 'default') - + # yellow is for scalars and prototypes #hi_yellow = ('yellow551', 'default') #lo_yellow = ('yellow330', 'default') - + # green is for strings and hash keys lo_green = ('green030', 'default') hi_green = ('green050', 'default') - + # cyan is for quotes, evals, regexes, subs #lo_cyan = ('cyan033', 'default') hi_cyan = ('cyan155', 'default') - + # blue is unused #lo_blue = ('blue113', 'default') hi_blue = ('blue225', 'default') @@ -328,10 +328,10 @@ class Application(object): # understand. i encourage someone else to write something better. numcols = max(self.bufferlist.slots[n].width // (maxlen + 2), 1) numrows = clen - ((clen // numcols) * (numcols - 1)) - for i in xrange(0, numrows): + for i in range(0, numrows): names = [] index = i * numcols - for j in xrange(0, numcols): + for j in range(0, numcols): if index + j < clen: names.append('%-*s' % (maxlen, candidates[index + j])) else: @@ -407,7 +407,7 @@ class Application(object): blist.remove_buffer(b) b.close() active_slot = blist.slots[self.active_slot] - for i in xrange(0, len(blist.slots)): + for i in range(0, len(blist.slots)): if blist.slots[i].is_empty(): if blist.hidden_buffers: blist.set_slot(i, blist.hidden_buffers[0]) @@ -430,7 +430,7 @@ class Application(object): # auxname = '%s/%d' % (name, i) # name = auxname #return name - + def open_path(self, path, binary=False, cipher=None, password=None): path = util.literal_path(path) b = self.get_buffer_by_path(path) @@ -493,7 +493,7 @@ class Application(object): self.arg_history.setdefault(queue, []) self.arg_history[queue].append(startvalue or '') self.mini_buffer.hindex = len(self.arg_history[queue]) - 1 - + self.mini_active = True except MiniBufferError: self.mini_buffer = None @@ -610,9 +610,9 @@ class Application(object): self.error_timestamp = time.time() def set_error(self, s): self.set_msg(s) - self.log.append_lines([s, u""], act=buffer.ACT_NONE, force=True) + self.log.append_lines([s, ""], act=buffer.ACT_NONE, force=True) def clear_error(self): - self.error_string = u"" + self.error_string = "" self.error_timestamp = None def try_manual_resize(self): y, x = self.stdscr.getmaxyx() @@ -655,12 +655,12 @@ class Application(object): def undo(self): try: self.window().undo() - except Exception, e: + except Exception as e: self.set_error("%s" % (e)) def redo(self): try: self.window().redo() - except Exception, e: + except Exception as e: self.set_error("%s" % (e)) # action creating methods @@ -708,6 +708,8 @@ class Application(object): # UTF-8 aware way to write to the screen def addstr(self, y, x, s, attr=curses.A_NORMAL): + assert type(y) == type(0) + assert type(x) == type(0) self.win.addstr(y, x, s.encode('utf-8'), attr) # the mighty run-loop! @@ -728,7 +730,7 @@ class Application(object): # add the keycodes to our input handler try: self.input.parse(i) - except Exception, e: + except Exception as e: self.set_error(str(e)) # if the mode has parsed keycodes into a key, we (possibly) handle @@ -796,7 +798,7 @@ class Application(object): try: pipe = Popen(args) pipe.wait() - except OSError, e: + except OSError as e: self.set_error("%s: %s" % (args[0], e)) curses.reset_prog_mode() self.win.redrawwin() @@ -846,7 +848,7 @@ class Application(object): vx = 0 vy += 1 break - + if y >= blen or x + swidth >= l: x = 0 y += 1 @@ -889,11 +891,11 @@ class Application(object): # sub-drawing methods def draw_slots(self): self.win.erase() - for i in xrange(0, len(self.bufferlist.slots)): + for i in range(0, len(self.bufferlist.slots)): #slot = self.bufferlist.slots[i] self.draw_slot(i) self.draw_status_bar(i) - + def highlight_char(self, sy, sx, fg='default', bg='default'): junk = self.win.inch(sy, sx) char = chr(junk & 255) @@ -907,7 +909,7 @@ class Application(object): def highlight_chars(self, sy, sx1, sx2, fg='default', bg='default'): assert sx2 < self.x, "%d < %d" % (sx2, self.x) - for x in xrange(sx1, sx2): + for x in range(sx1, sx2): self.highlight_char(sy, x, fg, bg) def highlight_simple_range(self, slot, y1, x1, x2, fg, bg): @@ -989,7 +991,7 @@ class Application(object): if w.mode.header: rstrs = w.mode.get_header() assert len(rstrs) >= w.mode.header - for j in xrange(0, w.mode.header): + for j in range(0, w.mode.header): k = 0 for rstr in rstrs[j]: #rstr.draw(self.win, slot.y_offset + j, slot.x_offset + k, slot.width) @@ -1026,14 +1028,14 @@ class Application(object): shade = util.get_margin_color(w, 'blue') limit = util.get_margin_limit(w, 80) if limit < self.x: - for j in xrange(0, slot.height): + for j in range(0, slot.height): #char = chr(self.win.inch(j + slot.y_offset, limit) & 255) #attr = color.build('default', shade, 'bold') #self.addstr(j + slot.y_offset, limit + w.mode.lmargin, char, attr) self.highlight_char(j + slot.y_offset, limit + w.mode.lmargin, fg='default', bg=shade) - + def _draw_slot(self, i): slot = self.bufferlist.slots[i] w = slot.window @@ -1054,7 +1056,7 @@ class Application(object): rlines = w.render_line_lit(y, swidth) else: rlines = w.render_line_raw(y, swidth) - for j in xrange(k, len(rlines)): + for j in range(k, len(rlines)): y2 = slot.y_offset + count if lm: i = 0 @@ -1095,7 +1097,7 @@ class Application(object): attr = color.build('default', 'default') if self.error_string: attr = color.build('default', 'default') - for i in xrange(0, len(lines)): + for i in range(0, len(lines)): line = lines[i] try: self.addstr(self.y - len(lines) + i, 0, line, attr) @@ -1105,7 +1107,7 @@ class Application(object): return pattr = color.build('cyan', 'default', 'bold') plines = self.get_minibuffer_x_lines(self.mini_prompt) - for i in xrange(0, len(plines)): + for i in range(0, len(plines)): pline = plines[i] try: self.addstr(self.y - len(lines) + i, 0, pline, pattr) @@ -1142,7 +1144,7 @@ def open_aes_file(path, name=None, binary=False): p = getpass("Please enter the AES password: ") return buffer.aes.AesBuffer(path, p, name) else: - raise Exception, "can't open %r; unsupported file type" % path + raise Exception("can't open %r; unsupported file type" % path) def open_plain_file(path, name=None, binary=False): if os.path.isfile(path) or not os.path.exists(path): @@ -1153,7 +1155,7 @@ def open_plain_file(path, name=None, binary=False): elif os.path.isdir(path): return buffer.fs.DirBuffer(path, name) else: - raise Exception, "can't open %r; unsupported file type" % path + raise Exception("can't open %r; unsupported file type" % path) def run_app(stdscr, buffers, **kwargs): curses.def_shell_mode() @@ -1272,7 +1274,7 @@ if __name__ == "__main__": try: b = f(path, name, opts.binary) b.open() - except buffer.BinaryDataException, e: + except buffer.BinaryDataException as e: if not opts.mode: opts.mode = 'hex' b = f(path, name, True) diff --git a/buffer/__init__.py b/buffer/__init__.py index ee4eed5..1094121 100644 --- a/buffer/__init__.py +++ b/buffer/__init__.py @@ -112,7 +112,7 @@ class Buffer(object): raise Exception("Path '%s' does not exist" % (path)) if not os.access(path, os.R_OK): raise Exception("Path '%s' cannot be read" % (path)) - f = open(path, 'r') + f = open(path, 'rb') return f def _open_file_w(self, path): if os.path.isfile(path): @@ -122,7 +122,7 @@ class Buffer(object): raise Exception("Dir '%s' cannot be read" % (path)) if not os.access(d, os.W_OK): raise Exception("Dir '%s' cannot be written" % (path)) - f = open(path, 'w') + f = open(path, 'wb') return f def _temp_path(self, path): (dirname, basename) = os.path.split(path) @@ -303,7 +303,7 @@ class Buffer(object): assert p1 <= p2, "p1.x (%d) > p2.x (%d)" % (p1.x, p2.x) lines = [] x = p1.x - for i in xrange(p1.y, p2.y): + for i in range(p1.y, p2.y): lines.append(self.lines[i][x:]) x = 0 lines.append(self.lines[p2.y][x:p2.x]) @@ -344,7 +344,7 @@ class Buffer(object): self.lines.insert(p.y + 1, []) self.lines[p.y + 1] = lines[-1] + self.lines[p.y][p.x:] self.lines[p.y] = self.lines[p.y][:p.x] + lines[0] - for i in xrange(1, llen - 1): + for i in range(1, llen - 1): self.lines.insert(p.y + i, lines[i]) else: self.lines[p.y] = self.lines[p.y][:p.x] + lines[-1] + self.lines[p.y][p.x:] @@ -395,7 +395,7 @@ class Buffer(object): return m.end() def detect_indent_level(self, y1, y2): x = None - for y in xrange(y1, y2): + for y in range(y1, y2): if self.is_whitespace(y): continue c = self.count_leading_whitespace(y) @@ -597,7 +597,7 @@ class FileBuffer(Buffer): raise Exception("Path '%s' does not exist" % (path)) if not os.access(path, os.R_OK): raise Exception("Path '%s' cannot be read" % (path)) - f = open(path, 'r') + f = open(path, 'rb') return f def _open_file_w(self, path=None, preserve=True): if path is None: @@ -609,7 +609,7 @@ class FileBuffer(Buffer): raise Exception("Dir '%s' cannot be read" % (path)) if not os.access(d, os.W_OK): raise Exception("Dir '%s' cannot be written" % (path)) - f = open(path, 'w') + f = open(path, 'wb') return f def _temp_path(self, path=None): if path is None: @@ -635,7 +635,7 @@ class FileBuffer(Buffer): codec = chardet.detect(data).get('encoding') or 'utf-8' self.codec = codec.lower() else: - data = '' + data = b'' self.codec = 'utf-8' if self.codec == 'utf-8' and data.startswith(codecs.BOM_UTF8): @@ -643,6 +643,7 @@ class FileBuffer(Buffer): elif self.codec.startswith('utf-16'): self.codec = 'utf-16' + #data = data.decode(self.codec) data = data.decode(self.codec) if '\t' in data: @@ -660,7 +661,7 @@ class FileBuffer(Buffer): self.nl = self._detect_nl_type(data) if '\x00' in data[:8192]: - raise BinaryDataException("binary files are not supported") + raise BinaryDataException("binary files are not supported: %r" % data[:8192]) return data @@ -672,7 +673,7 @@ class FileBuffer(Buffer): self.set_data(data) def changed_on_disk(self): assert self.checksum is not None - f = open(self.path) + f = open(self.path, 'rb') data = f.read() f.close() m = hasher(data) @@ -700,7 +701,7 @@ class FileBuffer(Buffer): f2 = self._open_file_w(self.path, preserve=False) f2.write(data) f2.close() - except NameError, e: + except NameError as e: if exists: shutil.copyfile(temp_path, self.path) raise e else: diff --git a/buffer/colors.py b/buffer/colors.py index fb55e27..85761eb 100644 --- a/buffer/colors.py +++ b/buffer/colors.py @@ -25,7 +25,7 @@ class ColorHighlighter(Highlighter): def delete_token(self, y, i): del self.tokens[y][i] def relex(self, lines, y1, x1, y2, x2, token=None): - for y in xrange(y1, y2 + 1): + for y in range(y1, y2 + 1): self.highlight_line(y, lines[y]) def highlight_line(self, y, line): @@ -52,7 +52,7 @@ class ColorHighlighter(Highlighter): if self.tokens: return self.tokens = [None] * len(lines) - for y in xrange(0, len(lines)): + for y in range(0, len(lines)): self.highlight_line(y, lines[y]) class ColorDataBuffer(DataBuffer): diff --git a/buffer/emul.py b/buffer/emul.py index 06bb699..046c163 100644 --- a/buffer/emul.py +++ b/buffer/emul.py @@ -183,9 +183,9 @@ class XTermBuffer(Buffer, XTerm): def name(self): return self._name def changed(self): return False def readonly(self): return True - def undo(self, move, act): raise Exception, "invalid" - def redo(self, move, act): raise Exception, "invalid" - def reload(self): raise Exception, "invalid" + def undo(self, move, act): raise Exception("invalid") + def redo(self, move, act): raise Exception("invalid") + def reload(self): raise Exception("invalid") def close(self): self._done = True self._thread.join() diff --git a/buffer/fs.py b/buffer/fs.py index 66385d1..d82cad3 100644 --- a/buffer/fs.py +++ b/buffer/fs.py @@ -31,7 +31,7 @@ class DirBuffer(Buffer): def get_names(self): if not self.path_exists(): - raise Exception, "directory %r does not exists" % self.path + raise Exception("directory %r does not exists" % self.path) names = os.listdir(self.path) if self.path != '/': names.insert(0, '..') @@ -58,11 +58,11 @@ class DirBuffer(Buffer): continue path = self._make_path(name) fields = dirutil.path_fields(path, name) - for i in xrange(0, 5): + for i in range(0, 5): try: maxlens[i] = max(maxlens[i], len(fields[i])) except: - raise Exception, '%d %r' % (i, fields[i]) + raise Exception('%d %r' % (i, fields[i])) fieldlines.append(fields) if self.settings.get('type-sort'): @@ -82,9 +82,9 @@ class DirBuffer(Buffer): lines = self._get_lines() self.set_lines(lines, force=True) def save(self, force=False): - raise Exception, "can't save a directory buffer" + raise Exception("can't save a directory buffer") def save_as(self, path): - raise Exception, "can't save a directory buffer" + raise Exception("can't save a directory buffer") class ArchiveBuffer(DirBuffer): btype = 'archive' diff --git a/buffer/pipe.py b/buffer/pipe.py index 8430a74..a5d3d28 100644 --- a/buffer/pipe.py +++ b/buffer/pipe.py @@ -83,7 +83,7 @@ class PipeBuffer(Buffer): self._towrite = self._towrite[n:] self._lock.release() if efd: - raise Exception, "exception is ready: %s" % repr(efd) + raise Exception("exception is ready: %s" % repr(efd)) except (OSError, TypeError): pass os.close(fd) @@ -107,7 +107,7 @@ class PipeBuffer(Buffer): self.lines.insert(p.y + 1, []) self.lines[p.y + 1] = lines[-1] + self.lines[p.y][p.x:] self.lines[p.y] = self.lines[p.y][:p.x] + lines[0] - for i in xrange(1, llen - 1): + for i in range(1, llen - 1): self.lines.insert(p.y + i, lines[i]) else: self.lines[p.y] = self.lines[p.y][:p.x] + lines[-1] + self.lines[p.y][p.x:] @@ -117,6 +117,6 @@ class PipeBuffer(Buffer): def name(self): return self._name def changed(self): return False def readonly(self): return True - def undo(self, move, act): raise Exception, "invalid" - def redo(self, move, act): raise Exception, "invalid" - def reload(self): raise Exception, "invalid" + def undo(self, move, act): raise Exception("invalid") + def redo(self, move, act): raise Exception("invalid") + def reload(self): raise Exception("invalid") diff --git a/bufferlist.py b/bufferlist.py index ca19bd1..1af48b7 100644 --- a/bufferlist.py +++ b/bufferlist.py @@ -7,6 +7,7 @@ class Slot(object): def is_empty(self): return self.window is None def resize(self, height, width, y_offset=0, x_offset=0): + assert type(height) == type(0) self.height = height self.width = width self.y_offset = y_offset @@ -28,6 +29,7 @@ class Slot(object): class BufferList(object): def __init__(self, height, width, buffers=()): + assert type(height) == type(0) self.height = height self.width = width self.buffers = set() @@ -42,18 +44,19 @@ class BufferList(object): self.add_buffer(b) def fit_slots(self): total = self.height - len(self.slots) + 1 - self.mini_height - heights = [total / len(self.slots)] * len(self.slots) - for i in xrange(0, total % len(self.slots)): + heights = [total // len(self.slots)] * len(self.slots) + for i in range(0, total % len(self.slots)): heights[i] += 1 offsets = [0] - for i in xrange(1, len(self.slots)): + for i in range(1, len(self.slots)): offsets.insert(i, offsets[i - 1] + heights[i - 1] + 1) - for i in xrange(0, len(self.slots)): + for i in range(0, len(self.slots)): self.slots[i].resize(heights[i], self.width, offsets[i]) def resize_mini(self, n): self.mini_height = n self.fit_slots() def resize(self, height, width): + assert type(height) == type(0) self.height = height self.width = width self.fit_slots() @@ -128,13 +131,13 @@ class BufferList(object): return b return None def close_buffer(self, b): - for i in xrange(0, len(self.slots)): + for i in range(0, len(self.slots)): slot = self.slots[i] if slot.window is not None and slot.window.buffer is b: self.unset_slot(i) def remove_buffer(self, b): assert b in self.buffers, "buffer %s does not exist" % (b.name()) - for i in xrange(0, len(self.slots)): + for i in range(0, len(self.slots)): slot = self.slots[i] if slot.window is not None and slot.window.buffer is b: self.unset_slot(i) diff --git a/color.py b/color.py index ca2275f..6af0156 100644 --- a/color.py +++ b/color.py @@ -53,7 +53,7 @@ def iter256(): else: continue yield (name, r, g, b) - raise StopIteration + return # if we can support 256 colors, create all of the color names and map them to # the correct RGB value. @@ -90,13 +90,13 @@ def init(): rev_ascii_map['default'] = 'd' # add in hex aliases to 256 colors; used by color-data buffers - for i in xrange(0, 256): + for i in range(0, 256): name = 'f%02x' % i abbrev = 'f%02x' % i add_color(name, i, abbrev) # create the 24 flavors of grey in 256 colors - for i in xrange(0, 24): + for i in range(0, 24): name2 = 'grey%d' % i abbrev2 = 'G%d' % i if curses.COLORS == 256: diff --git a/completer.py b/completer.py index 2211298..a1bd902 100644 --- a/completer.py +++ b/completer.py @@ -127,7 +127,7 @@ class TokenCompleter(Completer): continue elif t2.string.startswith(s): candidates[t2.string] = 1 - return candidates.keys() + return list(candidates.keys()) class MethodCompleter(Completer): def get_candidates(self, s, w=None): diff --git a/context.py b/context.py index eb80a18..fc14423 100644 --- a/context.py +++ b/context.py @@ -20,12 +20,12 @@ class Context(object): elif delta > 0: self.namelines.extend([(None, None)] * delta) l = len(self.mode.window.buffer.lines) - for i in reversed(xrange(p.y + 1, l)): + for i in reversed(range(p.y + 1, l)): self.namelines[i] = self.namelines[i - delta] - for i in xrange(p.y, p.y + delta): + for i in range(p.y, p.y + delta): self.namelines[i] = (None, None) else: - for i in xrange(p.y + 1, len(self.mode.window.buffer.lines)): + for i in range(p.y + 1, len(self.mode.window.buffer.lines)): self.namelines[i + delta] = self.namelines[i] def _init_name_map(self): @@ -57,7 +57,7 @@ class Context(object): return stack def rebuild_name_map(self, y1, y2): - for y in xrange(y1, y2): + for y in range(y1, y2): (name, info) = self.namelines[y] self._del_name(y, name) @@ -70,7 +70,7 @@ class Context(object): self._build_name_map(y1, y2, last, curr, stack) def _build_name_map(self, y1, y2, last, curr, stack): - raise Exception, 'unimplemented' + raise Exception('unimplemented') def get_line_name(self, y): if self.namelines is None: diff --git a/ctags.py b/ctags.py index dd1ea69..b44f184 100755 --- a/ctags.py +++ b/ctags.py @@ -51,7 +51,7 @@ class TagManager(object): mtime = os.stat(self.path)[ST_MTIME] itr = self._walk(mtime) try: - itr.next() + next(itr) return True except StopIteration: return False @@ -70,7 +70,7 @@ class TagManager(object): continue else: yield os.path.join(root, f) - raise StopIteration + return def _match(self, path): return os.path.splitext(path)[1] in self.exts @@ -120,8 +120,8 @@ if __name__ == '__main__': ctags.parse() if len(sys.argv) > 2: - print "records for %r:" % sys.argv[2] + print("records for %r:" % sys.argv[2]) for r in ctags.get(sys.argv[2]): - print r + print(r) else: pprint(ctags.records) diff --git a/dirutil.py b/dirutil.py index 97bdae5..9aab1d8 100644 --- a/dirutil.py +++ b/dirutil.py @@ -61,7 +61,7 @@ def path_sort(a, b): if x != 0: return -x return cmp(a[5], b[5]) except: - raise Exception, repr(a) + ' ' + repr(b) + raise Exception(repr(a) + ' ' + repr(b)) def path_sort2(a, b): try: @@ -69,7 +69,7 @@ def path_sort2(a, b): if x != 0: return x return cmp(b[0][0], a[0][0]) except: - raise Exception, repr(a) + ' ' + repr(b) + raise Exception(repr(a) + ' ' + repr(b)) def path_fields(path, name): # let's escape some troublesome characters @@ -94,7 +94,7 @@ def path_fields(path, name): for bundle in ((stat.S_IRUSR, stat.S_IWUSR, stat.S_IXUSR), (stat.S_IRGRP, stat.S_IWGRP, stat.S_IXGRP), (stat.S_IROTH, stat.S_IWOTH, stat.S_IXOTH)): - for j in xrange(0, 3): + for j in range(0, 3): if info.st_mode & bundle[j]: perm[i] = symbols[j] else: diff --git a/etags.py b/etags.py index 5734352..47b7c6c 100644 --- a/etags.py +++ b/etags.py @@ -55,7 +55,7 @@ class TagManager(object): mtime = os.stat(self.path)[ST_MTIME] itr = self._walk(mtime) try: - itr.next() + next(itr) return True except StopIteration: return False @@ -74,7 +74,7 @@ class TagManager(object): continue else: yield os.path.join(root, f) - raise StopIteration + return def _match(self, path): _, ext = os.path.splitext(path) @@ -123,7 +123,7 @@ class Etags(object): l = data[i:n] try: filename, size = l.split(',') - except ValueError, e: + except ValueError as e: raise Exception("parse failed(%s): %r %r %r" % (i, l, e, data)) size = int(size) subblock = data[n+1:n+size+1] @@ -139,7 +139,7 @@ class Etags(object): try: defn, rest = lineitem.split(chr(0x7f)) except ValueError: - print lineitem + print(lineitem) raise name = None if chr(0x01) in rest: @@ -179,6 +179,6 @@ if __name__ == '__main__': etags.parse() if len(sys.argv) > 2: - print etags.get(sys.argv[2]) + print(etags.get(sys.argv[2])) else: pprint(etags.records) diff --git a/gdb.py b/gdb.py index 1856487..d1d0274 100755 --- a/gdb.py +++ b/gdb.py @@ -71,18 +71,18 @@ class Debugger(object): self.char = int(fields[2]) self.middle = fields[3] self.addr = fields[4] - print "SOURCE %r, line %d (%s)" % (self.path, self.line, self.addr) + print("SOURCE %r, line %d (%s)" % (self.path, self.line, self.addr)) elif line == '\032\032pre-prompt': self.prompt = self._readline() - print 'PROMPT: %r' % self.prompt + print('PROMPT: %r' % self.prompt) self._assertline('\032\032prompt') self.pipe.stdin.write(sys.stdin.readline()) self._assertline('') self._assertline('\032\032post-prompt') else: - print 'CMD %r' % line + print('CMD %r' % line) elif line: - print line + print(line) if __name__ == "__main__": args = sys.argv[1:] diff --git a/highlight.py b/highlight.py index d728dc9..a570bde 100644 --- a/highlight.py +++ b/highlight.py @@ -12,10 +12,10 @@ color_names = [ color_dict ={} def setup(): - color_list.extend(['\033[3%dm' % x for x in xrange(0, 8)]) - color_list.extend(['\033[3%d;1m' % x for x in xrange(0, 8)]) + color_list.extend(['\033[3%dm' % x for x in range(0, 8)]) + color_list.extend(['\033[3%d;1m' % x for x in range(0, 8)]) color_list.extend(['\033[0m']) - for i in xrange(0, len(color_list)): + for i in range(0, len(color_list)): color_dict[color_names[i]] = color_list[i] setup() @@ -25,19 +25,19 @@ class Highlighter(object): self.tokens = [] def dump(self, fmt='(%3s, %2s) | %s'): - print fmt % ('y', 'x', 'string') - for i in xrange(0, len(self.tokens)): + print(fmt % ('y', 'x', 'string')) + for i in range(0, len(self.tokens)): group = self.tokens[i] - print 'LINE %d' % i + print('LINE %d' % i) for token in group: - print fmt % (token.y, token.x, token.string) + print(fmt % (token.y, token.x, token.string)) def display(self, token_colors={}, debug=False): for group in self.tokens: for token in group: color_name = None name_parts = token.name.split('.') - for i in xrange(0, len(name_parts)): + for i in range(0, len(name_parts)): if '.'.join(name_parts[i:]) in token_colors: color_name = token_colors['.'.join(name_parts[i:])] break @@ -45,7 +45,7 @@ class Highlighter(object): sys.stdout.write(color_dict[color_name]) pass elif debug: - raise Exception, "no highlighting for %r" % token.name + raise Exception("no highlighting for %r" % token.name) else: color_name = 'white' sys.stdout.write(color_dict[color_name]) @@ -66,8 +66,8 @@ class Highlighter(object): elif self.tokens[y][i].parent is deleted[-1]: deleted.append(self.tokens[y].pop(i)) else: - raise Exception, "huh?? %r %r" % (self.tokens[y][i].parent, - deleted) + raise Exception("huh?? %r %r" % (self.tokens[y][i].parent, + deleted)) i = 0 y += 1 @@ -99,12 +99,12 @@ class Highlighter(object): # if we need another new_token, then try to get it. if getnext: try: - new_token = gen.next() + new_token = next(gen) getnext = False except StopIteration: # ok, so this means that ALL the rest of the tokens didn't # show up, because we're done. so delete them and exit - for j in xrange(y, len(lines)): + for j in range(y, len(lines)): del self.tokens[j][i:] i = 0 break @@ -152,7 +152,7 @@ class Highlighter(object): getnext = True else: # this should never happen - raise Exception, "this isn't happening" + raise Exception("this isn't happening") # deletion # ====================== @@ -188,9 +188,9 @@ class Highlighter(object): # ok, so now we need to "adjust" the (x,y) coordinates of all the tokens # after the change. first we will copy over the pre-deletion tokens. - newtokens = [[] for _ in xrange(0, len(self.tokens) - y2 + y1)] + newtokens = [[] for _ in range(0, len(self.tokens) - y2 + y1)] - for y in xrange(0, y1): + for y in range(0, y1): for token in self.tokens[y]: newtokens[y].append(token) @@ -205,7 +205,7 @@ class Highlighter(object): newtokens[y1].append(token) # finally, we will copy over the tokens from subsequent lines - for y in xrange(y2 + 1, len(self.tokens)): + for y in range(y2 + 1, len(self.tokens)): for token in self.tokens[y]: token.y = token.y - y2 + y1 newtokens[y - y2 + y1].append(token) @@ -242,11 +242,11 @@ class Highlighter(object): # construct a new token data structure, with the right number of lines newtokens = [] - for i in xrange(0, len(self.tokens) + ydelta): + for i in range(0, len(self.tokens) + ydelta): newtokens.append([]) # copy the tokens that show up before the changed line - for y in xrange(0, y1): + for y in range(0, y1): newtokens[y] = self.tokens[y] # process the tokens that show up on the changed line @@ -276,7 +276,7 @@ class Highlighter(object): # add in the new data newtokens[y1].append(Token('new', '', y1, x1, newlines[0])) - for i in xrange(1, len(newlines)): + for i in range(1, len(newlines)): yi = y1 + i newtokens[yi].append(Token('new', '', yi, 0, newlines[i])) @@ -285,7 +285,7 @@ class Highlighter(object): newtokens[y2].append(t) # for each subsequent line, fix it's tokens' y coordinates - for y in xrange(y1 + 1, len(self.tokens)): + for y in range(y1 + 1, len(self.tokens)): for t in self.tokens[y]: t.y += ydelta newtokens[t.y].append(t) diff --git a/ispell.py b/ispell.py index d718d36..5fb2b96 100644 --- a/ispell.py +++ b/ispell.py @@ -89,16 +89,16 @@ if __name__ == "__main__": sys.stdout.write('enter a word: ') line = sys.stdin.readline() if not line: - print + print() break elif line == '\n': continue elif ' ' in line: - print 'please enter a single world' + print('please enter a single world') continue for word in line.split('-'): word = word.strip() if s.check(word): - print '%s: ok' % word + print('%s: ok' % word) else: - print '%s: misspelled' % word + print('%s: misspelled' % word) diff --git a/keyinput.py b/keyinput.py index 7effa15..6ada72c 100644 --- a/keyinput.py +++ b/keyinput.py @@ -85,7 +85,7 @@ def setup(): MAP[27][key] = "M-%s" % (MAP[key]) # add meta character stuff - for i in xrange(33, 126): + for i in range(33, 126): if i == 79 or i == 91: # these keys are used in other sequences continue @@ -99,21 +99,23 @@ setup() def disable_control_chars(): # terminal settings are for chumps attr = termios.tcgetattr(sys.stdin) + old = termios.tcgetattr(sys.stdin) # don't listen to allow input START/STOP (C-s,C-q) attr[0] = attr[0] & ~(termios.IXON | termios.IXOFF) - + + #FIX3 + # remove as many signal handlers as we can; we want to leave C-d and C-z # probably - for pos in xrange(0, len(attr[6])): + for pos in range(0, len(attr[6])): if pos == termios.VEOF or pos == termios.VSUSP: continue - attr[6][pos] = '\x00' - + attr[6][pos] = b'\x00' + # write the attributes back termios.tcsetattr(sys.stdin, termios.TCSANOW, attr) - class Handler(object): def __init__(self): self.tokens = [] @@ -150,4 +152,4 @@ class Handler(object): self.tokens.append(chr(i)) else: # this shouldn't really happen - raise Exception, "strange keycode recieved: %d" % (i) + raise Exception("strange keycode recieved: %d" % (i)) diff --git a/lex.py b/lex.py index 93f4c0a..6c3a808 100755 --- a/lex.py +++ b/lex.py @@ -101,9 +101,9 @@ class Rule(object): def __init__(self, name): self.name = name def match(self, lexer, parent): - raise Exception, "not implemented" + raise Exception("not implemented") def lex(self, lexer, parent, match): - raise Exception, "not implemented" + raise Exception("not implemented") def make_token(self, lexer, s, name, parent=None, matchd={}, link=None): t = Token(name, self, lexer.y, lexer.x, s, None, parent, matchd, link) t.color = lexer.get_color(t) @@ -128,7 +128,7 @@ class PatternRule(Rule): def lex(self, lexer, parent, m): if m: yield self.make_token(lexer, m.group(0), self.name, parent, m.groupdict()) - raise StopIteration + return class NocasePatternRule(PatternRule): reflags = re.IGNORECASE @@ -149,12 +149,12 @@ class PatternMatchRule(PatternRule): return self.re.match(self.get_line(lexer), lexer.x) def lex(self, lexer, parent, m): if not m: - raise StopIteration + return for group, name in zip(m.groups(), self.names): if not group: continue yield self.make_token(lexer, group, name, parent, m.groupdict()) - raise StopIteration + return class NocasePatternMatchRule(PatternMatchRule): reflags = re.IGNORECASE @@ -183,7 +183,7 @@ class OverridePatternRule(PatternRule): #raise pass yield self.make_token(lexer, m.group(0), self.name, parent, d) - raise StopIteration + return class ContextPatternRule(PatternRule): def __init__(self, name, pattern, fallback): @@ -217,7 +217,7 @@ class LazyPatternRule(Rule): def lex(self, lexer, parent, m): if m: yield self.make_token(lexer, m.group(0), self.name, parent, m.groupdict()) - raise StopIteration + return class PatternGroupRule(PatternRule): def __init__(self, name, *args): @@ -252,7 +252,7 @@ class PatternGroupRule(PatternRule): if matches: for (tokname, m) in matches: yield self.make_token(lexer, m.group(0), tokname, parent, m.groupdict()) - raise StopIteration + return class NocasePatternGroupRule(PatternGroupRule): reflags = re.IGNORECASE @@ -279,7 +279,7 @@ class RegionRule(Rule): # ok, so since we had a match, we need to create our start token, who # will be the ancestor to all other tokens matched in this region matchd = m.groupdict() - for (key, val) in matchd.iteritems(): + for (key, val) in matchd.items(): matchd[key] = escape(val) parent = self.make_token(lexer, m.group(0), 'start', parent, matchd, 'start') yield parent @@ -288,7 +288,7 @@ class RegionRule(Rule): # this region, and return the resulting token; we start at 0 for tok in self._lex_loop(lexer, [parent], matchd, 0): yield tok - raise StopIteration + return def resume(self, lexer, toresume): assert toresume, "can't resume without tokens to resume!" # ok, so we need to figure out in which of the grammars of our region @@ -313,7 +313,7 @@ class RegionRule(Rule): #for tok in self._lex_loop(lexer, toresume, toresume[0].matchd, i): for tok in self._lex_loop(lexer, toresume, matchd, i): yield tok - raise StopIteration + return def _lex_loop(self, lexer, toresume, matchd, i): # we need to loop over our grammar/stop-pattern pairs while i < len(self.pairs): @@ -351,8 +351,8 @@ class RegionRule(Rule): if self.pairs[i][1]: try: stopre = re.compile(self.pairs[i][1] % matchd, self.reflags) - except Exception, e: - raise Exception, "%r\n%r\n%r\n%r" % (e, self.pairs[i][1], matchd, self.reflags) + except Exception as e: + raise Exception("%r\n%r\n%r\n%r" % (e, self.pairs[i][1], matchd, self.reflags)) else: stopre = None if i == len(self.pairs) - 1: @@ -373,13 +373,13 @@ class RegionRule(Rule): toresume = [tok] matchd.update(tok.matchd) else: - raise StopIteration + return # this should have already gotten done by _lex #lexer.mstack.pop(-1) i += 1 # assuming we make it through all our grammars, and find the end-token, # then we need to signal that we are done. - raise StopIteration + return def _lex(self, lexer, toresume, stopname, stopre, grammar): assert toresume parent = toresume[0] @@ -402,7 +402,7 @@ class RegionRule(Rule): # since we might have changed our x/y coordinates, we need to # do some checks here, and maybe finish or change our coordintes if lexer.y >= len(lexer.lines): - raise StopIteration + return elif lexer.x >= len(line): lexer.y += 1 lexer.x = 0 @@ -459,7 +459,7 @@ class RegionRule(Rule): if not done and old_y == lexer.y: lexer.y += 1 lexer.x = 0 - raise StopIteration + return class NocaseRegionRule(RegionRule): reflags = re.IGNORECASE @@ -515,7 +515,7 @@ class Lexer(object): for t in self._lex(): yield t del self.action - raise StopIteration + return def resume(self, lines, y, x, token): self.action = 'resume' self.y = y @@ -539,7 +539,7 @@ class Lexer(object): #t._debug = True yield t del self.action - raise StopIteration + return def _lex(self): parent = None @@ -572,7 +572,7 @@ class Lexer(object): yield null_t self.y += 1 self.x = 0 - raise StopIteration + return def get_color(self, token): app = self.mode.window.application diff --git a/method/__init__.py b/method/__init__.py index 6242093..453606c 100644 --- a/method/__init__.py +++ b/method/__init__.py @@ -1,5 +1,5 @@ import codecs -import os, commands, re, tempfile +import os, subprocess, re, tempfile from subprocess import Popen, PIPE, STDOUT import buffer, completer, default, dirutil, regex, util, window @@ -31,7 +31,7 @@ class Argument(object): try: return int(value, 0) except: - raise Exception, "expected int; got %s" % (repr(value)) + raise Exception("expected int; got %s" % (repr(value))) else: return value @@ -89,7 +89,7 @@ class Method(object): def execute(self, w, **vargs): try: self._pre_execute(w, **vargs) - except MethodError, e: + except MethodError as e: w.set_error(str(e)) return for arg in self.args: @@ -100,7 +100,7 @@ class Method(object): self._execute(w, **vargs) w.buffer.undo_id += 1 def _execute(self, w, **vargs): - raise Exception, "Unimplemented Method: %s %r" % (self.name, vargs) + raise Exception("Unimplemented Method: %s %r" % (self.name, vargs)) class RelexBuffer(Method): '''Relex the buffer; this resets syntax highlighting''' @@ -526,7 +526,7 @@ class TabBuffer(Method): def _execute(self, w, **vargs): y = w.logical_cursor().y it = InsertTab() - for i in xrange(0, len(w.buffer.lines)): + for i in range(0, len(w.buffer.lines)): w.goto_line(i + 1) it.execute(w) w.goto_line(y + 1) @@ -559,7 +559,7 @@ class CommentRegion(Method): c = w.mode.commentc or '#' lvl = w.buffer.detect_indent_level(p1.y, p2.y) or 0 - for y in xrange(p1.y, p2.y): + for y in range(p1.y, p2.y): if len(w.buffer.lines[y]) < lvl: pad = lvl - len(w.buffer.lines[y]) x = lvl - pad @@ -585,7 +585,7 @@ class UncommentRegion(Method): commentc = w.mode.commentc or '#' commentre = re.compile('^( *)(%s)' % commentc) - for y in xrange(p1.y, p2.y): + for y in range(p1.y, p2.y): line = w.buffer.lines[y] m = commentre.match(line) if not m: @@ -859,7 +859,7 @@ class UnindentBlock(Method): lines = w.buffer.lines[p1.y:p2.y] - for i in xrange(0, len(lines)): + for i in range(0, len(lines)): if lines[i].startswith(tstr): lines[i] = lines[i][lvl:] w.buffer.delete(Point(0, p1.y), Point(0, p2.y)) @@ -885,7 +885,7 @@ class IndentBlock(Method): else: tstr = ' ' * w.mode.tabwidth - for i in xrange(0, len(lines)): + for i in range(0, len(lines)): lines[i] = tstr + lines[i] w.buffer.delete(Point(0, p1.y), Point(0, p2.y)) w.buffer.insert_string(Point(0, p1.y), '\n'.join(lines) + '\n') @@ -1145,7 +1145,7 @@ class ViewTokenColors(Method): def _execute(self, w, **vargs): a = w.application - keys = sorted([x for x in a.token_colors.keys()]) + keys = sorted([x for x in list(a.token_colors.keys())]) l = 0 for key in keys: l = max(l, len(key)) diff --git a/method/buffers.py b/method/buffers.py index a32d7f7..09c6419 100644 --- a/method/buffers.py +++ b/method/buffers.py @@ -1,4 +1,4 @@ -import os, commands, re, tempfile +import os, subprocess, re, tempfile from subprocess import Popen, PIPE, STDOUT import buffer, default, dirutil, regex, util, window @@ -41,7 +41,7 @@ class SwitchBuffer(Method): def _pre_execute(self, w, **vargs): a = w.application if len(a.bufferlist.buffers) < 1: - raise Exception, "No other buffers" + raise Exception("No other buffers") def _execute(self, w, **vargs): name = vargs['buffername'] buf = None @@ -123,10 +123,10 @@ class SaveBuffer(Method): try: w.buffer.save() w.set_error("Wrote %s" % (w.buffer.path)) - except buffer.FileGoneError, e: + except buffer.FileGoneError as e: w.buffer.save(force=True) w.set_error("File had disappeared! Wrote %s" % (w.buffer.path)) - except buffer.FileChangedError, e: + except buffer.FileChangedError as e: self._old_window = w self._prompt = "File changed on-disk; reload(r), overwrite(o) or diff(d)? " a.open_mini_buffer(self._prompt, self._callback) @@ -199,7 +199,7 @@ class SetBufferCodec(Method): def _execute(self, w, **vargs): codec = vargs['codec'] try: - u''.encode(codec) + ''.encode(codec) except: w.set_error('%r is not a valid codec' % codec) return diff --git a/method/cvs.py b/method/cvs.py index 123d899..d46556b 100644 --- a/method/cvs.py +++ b/method/cvs.py @@ -1,4 +1,4 @@ -import os, commands, re, tempfile +import os, subprocess, re, tempfile from subprocess import Popen, PIPE, STDOUT import buffer, default, dirutil, lex, regex, util, window diff --git a/method/git.py b/method/git.py index 4144675..4736c9e 100644 --- a/method/git.py +++ b/method/git.py @@ -1,4 +1,4 @@ -import os, commands, re, tempfile +import os, subprocess, re, tempfile from subprocess import Popen, PIPE, STDOUT import buffer, default, dirutil, lex, regex, util, window @@ -29,7 +29,7 @@ class GitStatus(VcBase): path = self._get_path(w) cmd = "git status --porcelain %r" % path - status, data = commands.getstatusoutput(cmd) + status, data = subprocess.getstatusoutput(cmd) status = status >> 8 if status != 0: @@ -66,7 +66,7 @@ class GitLog(Method): return self._e(m.group(i)) def _execute(self, w, **vargs): cmd = "git log %r" % w.buffer.path - status, data = commands.getstatusoutput(cmd) + status, data = subprocess.getstatusoutput(cmd) entries = [] for line in data.split('\n'): m = self._commit_re.match(line) @@ -98,7 +98,7 @@ class GitDiff(Method): return cmd = "git diff %r" % w.buffer.path - status, data = commands.getstatusoutput(cmd) + status, data = subprocess.getstatusoutput(cmd) if status == 0: if data: diff --git a/method/help.py b/method/help.py index 06735ef..0b71ac7 100644 --- a/method/help.py +++ b/method/help.py @@ -1,4 +1,4 @@ -import os, commands, re, tempfile +import os, subprocess, re, tempfile from subprocess import Popen, PIPE, STDOUT import buffer, buffer.about @@ -86,7 +86,7 @@ class ShowBindingsBuffer(Method): lines.append(format_str % ('BINDINGS', 'ACTIONS', 'HELP')) - names = names_to_sequences.keys() + names = list(names_to_sequences.keys()) names.sort() for name in names: sequences = names_to_sequences[name] diff --git a/method/hg.py b/method/hg.py index b2459a0..51b2437 100644 --- a/method/hg.py +++ b/method/hg.py @@ -84,7 +84,7 @@ class HgDiff(Method, HgBase): 'unified': c.get('hg.diff.unified'), } hgc.diff(ui_imp, repo, w.buffer.path, rev=revs, **opts) - except Exception, e: + except Exception as e: w.set_error(str(e)) return s = ''.join(ui_imp.popbuffer()) diff --git a/method/introspect.py b/method/introspect.py index 72a6fa7..3491138 100644 --- a/method/introspect.py +++ b/method/introspect.py @@ -1,4 +1,4 @@ -import os, commands, re, tempfile +import os, subprocess, re, tempfile from subprocess import Popen, PIPE, STDOUT import buffer, buffer.console @@ -13,7 +13,7 @@ class DumpContext(Method): def _execute(self, w, **vargs): lines = [] if w.mode.context: - for i in xrange(0, len(w.mode.context.namelines)): + for i in range(0, len(w.mode.context.namelines)): lines.append("LINE %d: %r" % (i + 1, repr(w.mode.context.namelines[i]))) else: lines.append("no context") @@ -35,7 +35,7 @@ class DumpMarkers(Method): def _execute(self, w, **vargs): lines = [] if w.mode.tabber: - keys = w.mode.tabber.lines.keys() + keys = list(w.mode.tabber.lines.keys()) keys.sort() for i in keys: line = w.mode.tabber.lines[i] @@ -52,7 +52,7 @@ class DumpTokens(Method): lines = [] if w.mode.name in w.buffer.highlights: tokens = w.buffer.highlights[w.mode.name].tokens - for i in xrange(0, len(tokens)): + for i in range(0, len(tokens)): lines.append("LINE %d" % (i + 1)) group = tokens[i] for token in group: diff --git a/method/move.py b/method/move.py index b88464a..c1819aa 100644 --- a/method/move.py +++ b/method/move.py @@ -1,4 +1,4 @@ -import os, commands, re, tempfile +import os, subprocess, re, tempfile from subprocess import Popen, PIPE, STDOUT import buffer, default, dirutil, regex, util, window diff --git a/method/search.py b/method/search.py index 919bd4b..fb6d18e 100644 --- a/method/search.py +++ b/method/search.py @@ -1,4 +1,4 @@ -import os, commands, re, tempfile +import os, subprocess, re, tempfile from subprocess import Popen, PIPE, STDOUT import buffer, default, dirutil, regex, util, window diff --git a/method/svn.py b/method/svn.py index bee52f2..ee634b8 100644 --- a/method/svn.py +++ b/method/svn.py @@ -1,4 +1,4 @@ -import os, commands, re, tempfile +import os, subprocess, re, tempfile from subprocess import Popen, PIPE, STDOUT import buffer, default, dirutil, lex, regex, util, window @@ -35,7 +35,7 @@ def get_status(path, base=None): if path.startswith(base): path = path[len(base):] cmd = "svn status -v %r" % path - status, data = commands.getstatusoutput(cmd) + status, data = subprocess.getstatusoutput(cmd) status = status >> 8 if status != 0: @@ -48,7 +48,7 @@ def get_status(path, base=None): try: rrev, lrev, lauthor, filename = fields except: - raise Exception, '%r %r' % (fields, data[6:]) + raise Exception('%r %r' % (fields, data[6:])) return { 'svn-filename': filename, @@ -73,7 +73,7 @@ class SvnCommit(Method): path = path[len(cwd):] cmd = "svn ci -m %r %r" % (vargs['msg'], path) - (status, data) = commands.getstatusoutput(cmd) + (status, data) = subprocess.getstatusoutput(cmd) status = status >> 8 lines = data.split('\n') @@ -116,7 +116,7 @@ class SvnStatus(Method): if path.startswith(cwd): path = path[len(cwd):] cmd = "svn status -v %r" % path - (status, data) = commands.getstatusoutput(cmd) + (status, data) = subprocess.getstatusoutput(cmd) status = status >> 8 if status != 0: @@ -155,7 +155,7 @@ class SvnLog(Method): return '[b:d:*]' + log_data + '\n' + mesg_data def _execute(self, w, **vargs): cmd = "svn log %r" % w.buffer.path - (status, data) = commands.getstatusoutput(cmd) + (status, data) = subprocess.getstatusoutput(cmd) entries = [] log_line, mesg_lines = None, [] @@ -191,7 +191,7 @@ class SvnDiff(Method): return cmd = "svn diff %r" % w.buffer.path - (status, data) = commands.getstatusoutput(cmd) + (status, data) = subprocess.getstatusoutput(cmd) if status == 0: if data: @@ -221,7 +221,7 @@ class SvnDiff2(Method): path = path[len(cwd):] cmd = "svn diff -r %s %r" % (rev, path) - (status, data) = commands.getstatusoutput(cmd) + (status, data) = subprocess.getstatusoutput(cmd) status = status >> 8 if data: @@ -255,7 +255,7 @@ class SvnDiff3(Method): path = path[len(cwd):] cmd = "svn diff -r %s:%s %r" % (rev1, rev2, path) - (status, data) = commands.getstatusoutput(cmd) + (status, data) = subprocess.getstatusoutput(cmd) status = status >> 8 if data: diff --git a/method/utf8.py b/method/utf8.py index 269c3f1..3548f7f 100644 --- a/method/utf8.py +++ b/method/utf8.py @@ -124,7 +124,7 @@ def unicodeget(u, fname, fallback): class Utf8Describe(Method): '''get detailed utf-8 data about a particular utf-8 code point''' args = [arg("code", t=type(""), p="Code Point: ", h="UTF-8 code point to use")] - cpt_re = re.compile('^\\u(?:[0-9a-fA-F]{2})+$') + #cpt_re = re.compile('^\\u(?:[0-9a-fA-F]{2})+$') #FIX3 format = ''' Glyph %s Name %s diff --git a/method/vc.py b/method/vc.py index 1de5bef..4d64fd4 100644 --- a/method/vc.py +++ b/method/vc.py @@ -39,7 +39,7 @@ class VcBlame(Method): gsizes = [0] * self.num_fields for line in pipe.stdout: d = self._filter(line) - for i in xrange(0, self.num_fields): + for i in range(0, self.num_fields): gsizes[i] = max(gsizes[i], len(d['fields'][i])) groups.append(d) status = pipe.wait() >> 8 @@ -75,7 +75,7 @@ class VcBlame(Method): try: groups, gsizes = self._build_groups(w, **vargs) - except Exception, e: + except Exception as e: w.set_error(str(e)) return diff --git a/miniparse.py b/miniparse.py index 93908db..ee0e93c 100644 --- a/miniparse.py +++ b/miniparse.py @@ -13,7 +13,7 @@ def proc(asttup): elif node[0] in token.tok_name: pairs.append((token.tok_name[node[0]], node[1])) else: - for i in xrange(0, len(node) - 1): + for i in range(0, len(node) - 1): queue.insert(i, node[i + 1]) return pairs diff --git a/mode/__init__.py b/mode/__init__.py index 544c525..5167662 100644 --- a/mode/__init__.py +++ b/mode/__init__.py @@ -32,7 +32,7 @@ class Handler(object): def del_action(self, name): if self.window is None: return - for binding in self.bindings.keys(): + for binding in list(self.bindings.keys()): if self.bindings[binding] == name: del self.bindings[binding] def add_binding(self, name, sequence): @@ -130,27 +130,27 @@ class Fundamental(Handler): app.setmode(cls.name.lower(), cls, paths=cls.paths, bases=cls.basenames, exts=cls.extensions, detection=cls.detection) - for (key, val) in cls.colors.iteritems(): + for (key, val) in cls.colors.items(): if key in app.token_colors: s = 'token_colors: name %r conflict in %r' % (key, cls.name) - raise Exception, s + raise Exception(s) else: app.token_colors[key] = val # install configuration stuff - for (key, val) in cls.config.iteritems(): + for (key, val) in cls.config.items(): assert key not in app.config, "config conflict: %r" % key app.config[key] = val - for (key, val) in cls.lconfig.iteritems(): + for (key, val) in cls.lconfig.items(): app.config.setdefault(key, []) for val2 in val: app.config[key].append(val2) - for (key, val) in cls.sconfig.iteritems(): + for (key, val) in cls.sconfig.items(): app.config.setdefault(key, set()) app.config[key].add(val) - for (key, d) in cls.dconfig.iteritems(): + for (key, d) in cls.dconfig.items(): app.config.setdefault(key, {}) - for (subkey, val) in d.iteritems(): + for (subkey, val) in d.items(): app.config[key][subkey] = val for mcls in cls.actions: @@ -160,7 +160,7 @@ class Fundamental(Handler): else: app.methods[m.name] = m - for (datatype, completer) in cls.completers.iteritems(): + for (datatype, completer) in cls.completers.items(): app.set_completer(datatype, completer) install = classmethod(install) @@ -274,7 +274,7 @@ class Fundamental(Handler): self.add_binding('insert-string-%s' % c, c) # per-mode bindings - for (name, sequences) in self._bindings.iteritems(): + for (name, sequences) in self._bindings.items(): self.add_bindings(name, sequences) # lexing for highlighting, etc. @@ -453,13 +453,13 @@ class Fundamental(Handler): act.execute(self.window) self.window.application.post_action_hook(act) #self.window.application.last_action = act.name - except ActionError, e: + except ActionError as e: #XYZ: HACK--should fix if t in ('C-]', 'C-g'): self.window.set_msg('Cancelled') else: self.window.set_error(str(e)) - except Exception, e: + except Exception as e: if DEBUG: raise exc_type, exc_value, exc_traceback = sys.exc_info() diff --git a/mode/bosatsu.py b/mode/bosatsu.py index 1cc3925..c4ca4ba 100644 --- a/mode/bosatsu.py +++ b/mode/bosatsu.py @@ -1,4 +1,4 @@ -import commands, os.path, re, string, sys, traceback +import subprocess, os.path, re, string, sys, traceback import color, completer, context, default, mode, method, regex, tab from lex import Grammar, PatternRule, RegionRule, OverridePatternRule diff --git a/mode/colortest.py b/mode/colortest.py index 148fd62..73232be 100644 --- a/mode/colortest.py +++ b/mode/colortest.py @@ -8,7 +8,7 @@ from lex import Grammar, PatternRule class ColortestGrammar(Grammar): rules = [] - for i in xrange(0, 256): + for i in range(0, 256): c = '%02x' % i rules.append(PatternRule('z' + c, c)) diff --git a/mode/consolemini.py b/mode/consolemini.py index 6dd5601..1009268 100644 --- a/mode/consolemini.py +++ b/mode/consolemini.py @@ -1,6 +1,6 @@ import code import re -import StringIO +import io import sys import traceback @@ -26,7 +26,7 @@ class ConsoleExec(Method): a = w.application if not a.has_buffer_name('*Console*'): - raise Exception, "No console found!" + raise Exception("No console found!") b = a.bufferlist.get_buffer_by_name('*Console*') if a.window().buffer is not b: a.switch_buffer(b) @@ -45,12 +45,12 @@ class ConsoleExec(Method): else: w.mode.saved_input = '' a.set_mini_buffer_prompt('>>> ') - sys.stdout = code_out = StringIO.StringIO() - sys.stderr = code_err = StringIO.StringIO() + sys.stdout = code_out = io.StringIO() + sys.stderr = code_err = io.StringIO() ok = True try: - exec code_obj in w.mode.globals, w.mode.locals - except Exception, e: + exec(code_obj, w.mode.globals, w.mode.locals) + except Exception as e: ok = False output = str(e) + '\n' sys.stdout = sys.__stdout__ @@ -60,9 +60,9 @@ class ConsoleExec(Method): code_out.close() code_err.close() #except (SyntaxError, OverflowError, ValueError), e: - except Exception, e: + except Exception as e: a.set_mini_buffer_prompt('>>> ') - t = sys.exc_traceback + t = sys.exc_info()[2] output = str(e) + traceback.format_exc() limit = min([w.width for w in b.windows]) - len(PAD) @@ -122,7 +122,7 @@ class ConsoleTab(Method): curr_t = None curr_i = None - for i in xrange(0, len(tokens)): + for i in range(0, len(tokens)): t = tokens[i] if t.x < x and t.end_x() >= x: curr_i = i @@ -198,7 +198,7 @@ class ConsoleBase(Method): def _execute(self, w, **vargs): a = w.application if not a.has_buffer_name(self.subbuf): - raise Exception, "No console found!" + raise Exception("No console found!") w2 = a.bufferlist.get_buffer_by_name(self.subbuf).windows[0] self.submethod.execute(w2, **vargs) diff --git a/mode/dir.py b/mode/dir.py index 170de20..067a8a6 100644 --- a/mode/dir.py +++ b/mode/dir.py @@ -1,4 +1,4 @@ -import commands, dirutil, grp, method, mode, os.path, pwd, re +import subprocess, dirutil, grp, method, mode, os.path, pwd, re import util import buffer, buffer.fs from window import Window @@ -100,7 +100,7 @@ class DirGrep(Method): args = [Argument('pattern', datatype="str", prompt="Pattern: ")] def _execute(self, w, **vargs): cmd = 'grep -rEl -- "%s" %r' % (vargs['pattern'], w.buffer.path) - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) paths = [] suffixes = w.application.config['ignore_suffix'] @@ -125,7 +125,7 @@ class DirCmd(Method): basename = dirutil.resolve_name(w) path = os.path.join(w.buffer.path, basename) cmd = self._make_cmd(w, path, **vargs) - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if status != 0: w.set_error("%s failed (exit %d)" % (self.name, status)) dirutil.find_name(w, basename) diff --git a/mode/erlang.py b/mode/erlang.py index 8e4282b..efb8d19 100644 --- a/mode/erlang.py +++ b/mode/erlang.py @@ -1,4 +1,4 @@ -import commands, os.path, string, sys, traceback +import subprocess, os.path, string, sys, traceback import color, completer, default, mode, regex, tab from point import Point from lex import Grammar, PatternRule, RegionRule, OverridePatternRule diff --git a/mode/hex.py b/mode/hex.py index 66f7bf2..c847b41 100644 --- a/mode/hex.py +++ b/mode/hex.py @@ -41,12 +41,12 @@ class HexBackward(Method): class HexForwardWord(Method): def _execute(self, w, **vargs): hf = w.application.methods['hex-forward'] - for i in xrange(0, w.buffer.wordsize * 2): + for i in range(0, w.buffer.wordsize * 2): hf.execute(w, **vargs) class HexBackwardWord(Method): def _execute(self, w, **vargs): hb = w.application.methods['hex-backward'] - for i in xrange(0, w.buffer.wordsize * 2): + for i in range(0, w.buffer.wordsize * 2): hb.execute(w, **vargs) class HexStartOfLine(Method): @@ -93,7 +93,7 @@ class HexRead(Method): else: end = '%s-endian' % w.mode.byteorder w.set_error("%s %s at 0x%08x: %r" % (end, self.type_, addr, v)) - except Exception, e: + except Exception as e: w.set_error("%s could not be read at 0x%08x" % (self.type_, addr)) class HexReadAligned(HexRead): _is_method = False @@ -192,7 +192,7 @@ class ShowX86Instruction(Method): size = int(m.group(1)) data = data[:size] w.set_error("%s %s" % (data, lines[1])) - except Exception, e: + except Exception as e: w.set_error("there was an error") class GotoAddress(Method): diff --git a/mode/html.py b/mode/html.py index 0b39780..d079f4c 100644 --- a/mode/html.py +++ b/mode/html.py @@ -1,5 +1,5 @@ import os -import urllib +import urllib.request, urllib.parse, urllib.error import default import method from mode import Fundamental @@ -57,7 +57,7 @@ class HtmlValidatePage(method.Method): viewbg = viewcmd.endswith('&') if viewbg: viewcmd = viewcmd[:-1] - urlarg = urllib.urlencode({'uri': w.mode.url}) + urlarg = urllib.parse.urlencode({'uri': w.mode.url}) argv = (viewcmd, self.base + urlarg) if viewbg: if os.fork() == 0: diff --git a/mode/ipythonmini.py b/mode/ipythonmini.py index 14fcc8e..a90efe6 100644 --- a/mode/ipythonmini.py +++ b/mode/ipythonmini.py @@ -1,4 +1,4 @@ -import code, re, string, StringIO, sys +import code, re, string, io, sys import buffer, color, completer, lex, method, mode, mode.mini, mode.consolemini, window from subprocess import Popen, PIPE, STDOUT from mode.python import PythonGrammar diff --git a/mode/lua.py b/mode/lua.py index b00e243..4a09299 100644 --- a/mode/lua.py +++ b/mode/lua.py @@ -1,4 +1,4 @@ -import commands +import subprocess import time from tab import StackTabber from method import Method @@ -46,7 +46,7 @@ class LuaCheckSyntax(Method): def _execute(self, w, **vargs): app = w.application cmd = "luac -p %r" % (w.buffer.path) - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if status == 0: app.set_error("Syntax OK") app.data_buffer("*Lua-Check-Syntax*", output, switch_to=False) diff --git a/mode/mbox.py b/mode/mbox.py index aea1f11..3430138 100644 --- a/mode/mbox.py +++ b/mode/mbox.py @@ -37,8 +37,8 @@ class MboxMsgBuffer(Buffer): def readonly(self): return True def path_exists(self): raise Exception def _make_path(self, name): raise Exception - def save(self, force=False): raise Exception, "can't save an mbox message" - def save_as(self, path): raise Exception, "can't save an mbox message" + def save(self, force=False): raise Exception("can't save an mbox message") + def save_as(self, path): raise Exception("can't save an mbox message") def name(self): return 'mbox:%s:%s' % (self.base, self.lineno) def _get_msg_lines(self, msg): if msg.is_multipart(): @@ -92,8 +92,8 @@ class MboxListBuffer(Buffer): def readonly(self): return True def path_exists(self): raise Exception def _make_path(self, name): raise Exception - def save(self, force=False): raise Exception, "can't save an mbox" - def save_as(self, path): raise Exception, "can't save an mbox" + def save(self, force=False): raise Exception("can't save an mbox") + def save_as(self, path): raise Exception("can't save an mbox") def name(self): return 'mbox:%s' % (self.base) def open(self): self.lines = self._get_lines() @@ -121,7 +121,7 @@ class MboxListBuffer(Buffer): def _create_msg_dict(self, pos, msg): d = {} - for key in msg.keys(): + for key in list(msg.keys()): d[key.lower()] = msg[key] d['fromname'], d['fromaddr'] = self._parse_msg_from(msg) diff --git a/mode/mp3.py b/mode/mp3.py index 768238b..39b6626 100644 --- a/mode/mp3.py +++ b/mode/mp3.py @@ -1,4 +1,4 @@ -import commands, dirutil, grp, mailbox, method, mode, os.path, pwd, re, sys +import subprocess, dirutil, grp, mailbox, method, mode, os.path, pwd, re, sys import buffer, default, util, window from mode.mutt import MuttGrammar from lex import Grammar, PatternRule, RegionRule @@ -58,8 +58,8 @@ class Mp3Buffer(Buffer): def readonly(self): return True def path_exists(self): raise Exception def _make_path(self, name): raise Exception - def save(self, force=False): raise Exception, "can't save an mbox" - def save_as(self, path): raise Exception, "can't save an mbox" + def save(self, force=False): raise Exception("can't save an mbox") + def save_as(self, path): raise Exception("can't save an mbox") def name(self): return 'mp3:%s' % (self.base) def open(self): self.lines = self._get_lines() def reload(self): self.set_lines(self._get_lines(), force=True) diff --git a/mode/ocaml.py b/mode/ocaml.py index 9572628..8de8aa2 100644 --- a/mode/ocaml.py +++ b/mode/ocaml.py @@ -1,4 +1,4 @@ -import commands, os.path, string, sys, traceback +import subprocess, os.path, string, sys, traceback import color, completer, default, mode, method, regex, tab from point import Point from lex import Grammar, PatternRule, RegionRule, NocasePatternRule diff --git a/mode/perl.py b/mode/perl.py index 97de67d..874d046 100644 --- a/mode/perl.py +++ b/mode/perl.py @@ -547,7 +547,7 @@ class PerlHashCleanup(Method): key_w = max([len(groups_by_line[k][1]) for k in groups_by_line]) # for each line, format it correctly - keys = groups_by_line.keys() + keys = list(groups_by_line.keys()) keys.sort() data = '' for i in keys: @@ -735,7 +735,7 @@ class PerlFunctionCompleter(completer.Completer): return [n for n in functions if n.startswith(s)] class PerlContext(context.Context): - sub_match = And(Optional(Name('spaces')), + sub_match = And(Optional(Name('spaces')), Match('perl.keyword', 'sub'), Name('spaces'), Name('perl.sub')) diff --git a/mode/pipe.py b/mode/pipe.py index 52a0641..5786bcf 100644 --- a/mode/pipe.py +++ b/mode/pipe.py @@ -23,7 +23,7 @@ class Pipe(Fundamental): def __init__(self, w): Fundamental.__init__(self, w) - keys = self.bindings.keys() + keys = list(self.bindings.keys()) # page-up/page-down/goto-start/goto-end, C-x and M-x should still work for key in keys: @@ -33,7 +33,7 @@ class Pipe(Fundamental): continue del self.bindings[key] - for i in xrange(0, 128): + for i in range(0, 128): if i in (22, 24, 27): continue sym = keyinput.MAP.get(i, chr(i)) diff --git a/mode/python.py b/mode/python.py index 097051c..ecb9fa9 100644 --- a/mode/python.py +++ b/mode/python.py @@ -1,4 +1,4 @@ -import commands, os.path, re, string, sys, traceback +import subprocess, os.path, re, string, sys, traceback import color, completer, context, default, mode, method, regex, tab import method.introspect from point import Point @@ -137,7 +137,7 @@ class PythonTabber(tab.StackTabber): self.popped = True # ok, having done all that, we can now process each token # on the line - for i in xrange(0, len(tokens)): + for i in range(0, len(tokens)): currlvl = self._handle_token(currlvl, y, i) # so let's store the level for this line, as well as some debugging self.lines[y] = currlvl @@ -217,7 +217,7 @@ class PythonCheckSyntax(Method): try: code = compile(source, w.buffer.path, 'exec') w.set_error("Syntax OK") - except Exception, e: + except Exception as e: output = traceback.format_exc() w.application.data_buffer("*PythonSyntax*", output, switch_to=True, @@ -245,7 +245,7 @@ class PythonDictCleanup(Method): myregex = r if myregex is None: - raise Exception, "Not a python dict line" + raise Exception("Not a python dict line") groups_by_line[cursor.y] = myregex.match(line).groups() @@ -282,7 +282,7 @@ class PythonDictCleanup(Method): key_w = max([len(groups_by_line[k][1]) for k in groups_by_line]) # for each line, format it correctly - keys = groups_by_line.keys() + keys = list(groups_by_line.keys()) keys.sort() data = '' for i in keys: @@ -319,7 +319,7 @@ class PythonInsertTripleSquotes(Method): _q = "'''" def _execute(self, w, **vargs): w.insert_string_at_cursor('%s%s' % (self._q, self._q)) - for i in xrange(0, 3): + for i in range(0, 3): w.backward() class PythonInsertTripleDquotes(PythonInsertTripleSquotes): @@ -511,7 +511,7 @@ class PythonContext(context.Context): if last is not None: curr = '.'.join([x[1] for x in stack]) if curr: - for k in xrange(last, i): + for k in range(last, i): self.namelines[k] = (curr, None) last = None @@ -526,7 +526,7 @@ class PythonContext(context.Context): curr = '.'.join([x[1] for x in stack]) self.names[curr] = i - for k in xrange(1, len(stack)): + for k in range(1, len(stack)): curr = '.'.join(x[1] for x in stack[k:]) if curr not in abbrev: abbrev[curr] = i @@ -550,7 +550,7 @@ class PythonContext(context.Context): n = len(self.namelines[y2][0].split('.')) curr = '.'.join([x[1] for x in stack[:n]]) if curr: - for k in xrange(last, y2): + for k in range(last, y2): self.namelines[k] = (curr, None) class PythonTagManager(TagManager): diff --git a/mode/scala.py b/mode/scala.py index 6ffba95..cdff5cb 100644 --- a/mode/scala.py +++ b/mode/scala.py @@ -7,7 +7,7 @@ from mode.pipe import Pipe from method.shell import Interact from method import Method, arg import default -import urllib2 +import urllib.request, urllib.error, urllib.parse import os import re from subprocess import Popen, PIPE, STDOUT diff --git a/mode/sh.py b/mode/sh.py index e83d709..8135b9c 100644 --- a/mode/sh.py +++ b/mode/sh.py @@ -1,6 +1,6 @@ import re -import commands +import subprocess from tab import StackTabber from mode import Fundamental from lex import Grammar, PatternRule, RegionRule, PatternMatchRule, OverridePatternRule @@ -176,7 +176,7 @@ class ShCheckSyntax(Method): def _execute(self, w, **vargs): app = w.application cmd = "bash -n %r" % w.buffer.path - (status, output) = commands.getstatusoutput(cmd) + (status, output) = subprocess.getstatusoutput(cmd) if status == 0: app.set_error("Syntax OK") app.data_buffer("*Sh-Check-Syntax*", output, switch_to=False) diff --git a/mode/shellmini.py b/mode/shellmini.py index 45232c7..dc67d59 100644 --- a/mode/shellmini.py +++ b/mode/shellmini.py @@ -1,4 +1,4 @@ -import code, os, re, string, StringIO, sys, traceback +import code, os, re, string, io, sys, traceback import buffer, buffer.pipe, buffer.emul import color, completer, lex, method, mode, window from lex import Grammar, PatternRule, RegionRule @@ -26,7 +26,7 @@ class ShellExec(Method): w.mode.hindex = len(w.mode.history) - 1 if not a.has_buffer_name('*Shell*'): - raise Exception, "No shell found!" + raise Exception("No shell found!") b = a.bufferlist.get_buffer_by_name('*Shell*') if a.window().buffer is not b: a.switch_buffer(b) @@ -41,7 +41,7 @@ class ShellClear(Method): def execute(self, w, **vargs): a = w.application if not a.has_buffer_name('*Shell*'): - raise Exception, "No shell found!" + raise Exception("No shell found!") b = a.bufferlist.get_buffer_by_name('*Shell*') class ShellHistoryPrev(Method): @@ -75,7 +75,7 @@ class ShellTab(Method): curr_t = None curr_i = None - for i in xrange(0, len(tokens)): + for i in range(0, len(tokens)): t = tokens[i] if t.x < x and t.end_x() >= x: curr_i = i @@ -104,7 +104,7 @@ class ShellBaseMethod(Method): def _execute(self, w, **vargs): a = w.application if not a.has_buffer_name(self.subbuf): - raise Exception, "No shell found!" + raise Exception("No shell found!") w2 = a.bufferlist.get_buffer_by_name(self.subbuf).windows[0] self.submethod.execute(w2, **vargs) diff --git a/mode/sql.py b/mode/sql.py index 8f8108c..279c10e 100644 --- a/mode/sql.py +++ b/mode/sql.py @@ -89,14 +89,14 @@ class SqlTabber(StackTabber): token = self.get_token(y, i) s1 = token.string if not self.markers: - raise Exception, "unmatched closing token %r" % s1 + raise Exception("unmatched closing token %r" % s1) s2 = self.markers[-1].name if self.mode.closetags[s1] == s2: self._pop() if self.is_leftmost_token(y, i): currlvl = self.get_curr_level() else: - raise Exception, "mismatched closing tag %r vs %r" % (s2, s1) + raise Exception("mismatched closing tag %r vs %r" % (s2, s1)) return currlvl def _handle_other_token(self, currlvl, y, i): w = self.mode.tabwidth diff --git a/mode/text.py b/mode/text.py index 76b7364..3c2e277 100644 --- a/mode/text.py +++ b/mode/text.py @@ -17,11 +17,11 @@ class WordRule(PatternRule): if self._spelled_ok(s): token = Token('text.word', self, lexer.y, lexer.x, s, None, parent, {}) else: - token = Token('text.misspelled', self, lexer.y, lexer.x, s, None, parent, {}) + token = Token('text.misspelled', self, lexer.y, lexer.x, s, None, parent, {}) token.color = lexer.get_color(token) lexer.x += len(s) yield token - raise StopIteration + return class ContinuedRule(RegionRule): def __init__(self): diff --git a/mode/which.py b/mode/which.py index 58576ec..822ea37 100644 --- a/mode/which.py +++ b/mode/which.py @@ -18,7 +18,7 @@ class Which(mode.Fundamental): s = '%r is %r: %s' % (self.last_sequence, act.name, act.help) self.window.application.set_error(s) self._end() - except Exception, e: + except Exception as e: if mode.DEBUG: raise else: diff --git a/mode/yacc.py b/mode/yacc.py index 56c21a4..286b4b0 100644 --- a/mode/yacc.py +++ b/mode/yacc.py @@ -16,7 +16,7 @@ class TrueDict(dict): def __contains__(self, k): return True def __getitem__(self, k): return True def __setitem__(self, k): pass - def __delitem__(self, k): raise Exception, 'not possible' + def __delitem__(self, k): raise Exception('not possible') def __len__(self): return 1 def __repr__(self): return '' def get(self, k): return True diff --git a/parse.py b/parse.py index 1126eea..973a12f 100644 --- a/parse.py +++ b/parse.py @@ -113,12 +113,12 @@ class Repeat(Rule): self.maximum = maximum def match(self, tokens): n = 0 - for _ in xrange(0, self.minimum): + for _ in range(0, self.minimum): result = self.rule.match(tokens[n:]) if not result: return [] n += result[0] - for _ in xrange(self.minimum, self.maximum): + for _ in range(self.minimum, self.maximum): result = self.rule.match(tokens[n:]) if not result: return [n] diff --git a/render.py b/render.py index d78ff78..b035a86 100644 --- a/render.py +++ b/render.py @@ -37,7 +37,7 @@ class RenderString(object): def draw(self, cwin, y, x): try: s = self.string.encode('utf-8') - assert '\t' not in s, repr(s) + assert b'\t' not in s, repr(s) #FIX3 cwin.addstr(self.y + y, x, s, self.attrs) except curses.error: raise diff --git a/searchutil.py b/searchutil.py index 72e2f8f..7afbebf 100644 --- a/searchutil.py +++ b/searchutil.py @@ -46,7 +46,7 @@ def find(r, w, move=False, direction='next', start=None, end=None): c = w.logical_cursor() newc = None ranges = find_ranges(r, w, start, end) - indices = list(xrange(0, len(ranges))) + indices = list(range(0, len(ranges))) (x, y) = c.xy() if move: offset = 1 @@ -63,7 +63,7 @@ def find(r, w, move=False, direction='next', start=None, end=None): break indices.reverse() else: - raise Exception, 'blech' + raise Exception('blech') for i in indices: if (direction == 'next' and ranges[i].p1 > limit or direction == 'previous' and ranges[i].p2 < limit): diff --git a/tab.py b/tab.py index 54fa48b..e5ea7fc 100644 --- a/tab.py +++ b/tab.py @@ -38,14 +38,14 @@ class Tabber(object): def get_next_left_token(self, y, i): tokens = self.get_tokens(y) assert i >= 0 and i < len(tokens) - for j in xrange(1, i): + for j in range(1, i): if not self.token_is_whitespace(y, i - j): return tokens[i - j] return None def get_next_right_token(self, y, i): tokens = self.get_tokens(y) assert i >= 0 and i < len(tokens) - for j in xrange(i + 1, len(tokens)): + for j in range(i + 1, len(tokens)): if not self.token_is_whitespace(y, j): return tokens[j] return None @@ -58,30 +58,30 @@ class Tabber(object): def get_leftmost_token(self, y): tokens = self.get_tokens(y) - for i in xrange(0, len(tokens)): + for i in range(0, len(tokens)): if not self.token_is_whitespace(y, i): return tokens[i] return None def get_rightmost_token(self, y): tokens = self.get_tokens(y) i = len(tokens) - 1 - for j in xrange(0, len(tokens)): + for j in range(0, len(tokens)): if not self.token_is_whitespace(y, i - j): return tokens[i - j] return None def get_nonws_tokens(self, y): tokens = self.get_tokens(y) - for i in xrange(0, len(tokens)): + for i in range(0, len(tokens)): if not self.token_is_whitespace(y, i): yield tokens[i] - raise StopIteration + return def get_nons_tokens(self, y): tokens = self.get_tokens(y) - for i in xrange(0, len(tokens)): + for i in range(0, len(tokens)): if not self.token_is_space(y, i): yield tokens[i] - raise StopIteration + return def region_added(self, p, newlines): self.lines = {} @@ -136,7 +136,7 @@ class StackTabber(Tabber): while y <= target: currlvl = self.get_curr_level() tokens = self.get_tokens(y) - for i in xrange(0, len(tokens)): + for i in range(0, len(tokens)): currlvl = self._handle_token(currlvl, y, i) self.lines[y] = currlvl self.record[y] = tuple(self.markers) @@ -168,14 +168,14 @@ class StackTabber(Tabber): token = self.get_token(y, i) s1 = token.string if not self.markers: - raise Exception, "unmatched closing token %r" % s1 + raise Exception("unmatched closing token %r" % s1) s2 = self.markers[-1].name if self.mode.closetags[s1] == s2: self._pop() if self.is_leftmost_token(y, i): currlvl = self.get_curr_level() else: - raise Exception, "mismatched closing tag %r vs %r" % (s2, s1) + raise Exception("mismatched closing tag %r vs %r" % (s2, s1)) return currlvl def _handle_other_token(self, currlvl, y, i): return currlvl @@ -192,7 +192,7 @@ class StackTabber(Tabber): else: return None def _peek_until(self, *names): - for i in xrange(1, len(self.markers) + 1): + for i in range(1, len(self.markers) + 1): x = self.markers[-i] if x.name in names: return x @@ -332,7 +332,7 @@ class StackTabber2(Tabber): else: return None def _peek_until(self, *names): - for i in xrange(1, len(self.stack) + 1): + for i in range(1, len(self.stack) + 1): x = self.stack[-i] if x.name in names: return x @@ -349,7 +349,7 @@ class StackTabber2(Tabber): while end > 0 and self._is_ignored(tokens[end]): end -= 1 - for i in xrange(0, end + 1 - start): + for i in range(0, end + 1 - start): t = tokens[start + i] if self._is_ignored(t): pass @@ -372,7 +372,7 @@ class StackTabber2(Tabber): def _handle_close_token(self, y, tokens, start, end, i, t): while True: if not self.stack: - raise Exception, "unmatched %r, line %d" % (t.string, y) + raise Exception("unmatched %r, line %d" % (t.string, y)) marker = self.stack[-1] if marker.name in ('control', 'continue', 'pre-control'): self.stack.pop() @@ -390,11 +390,11 @@ class StackTabber2(Tabber): break else: msg = "mismatched %r, line %d (expected %r)" - raise Exception, msg % (t.string, y, s) + raise Exception(msg % (t.string, y, s)) elif marker.name == 'pre-case': self.stack.pop() else: - raise Exception, "what? %r (%r)" % (marker, t) + raise Exception("what? %r (%r)" % (marker, t)) # if we start a line with a closing token (e.g. "}") we may want to # shift the indentation left to "close" the indent. if we're using @@ -404,7 +404,7 @@ class StackTabber2(Tabber): self._save_curr_level() elif self.fixed_indent: all_closed = True - for j in xrange(0, i): + for j in range(0, i): if self._is_ignored(tokens[j]) or self._is_close_token(tokens[j]): pass else: diff --git a/util.py b/util.py index b41caec..2935d31 100644 --- a/util.py +++ b/util.py @@ -123,7 +123,7 @@ except: args = tuple() else: args = self.default_factory, - return type(self), args, None, None, self.items() + return type(self), args, None, None, list(self.items()) def copy(self): return self.__copy__() def __copy__(self): @@ -131,7 +131,7 @@ except: def __deepcopy__(self, memo): import copy return type(self)(self.default_factory, - copy.deepcopy(self.items())) + copy.deepcopy(list(self.items()))) def __repr__(self): return 'defaultdict(%s, %s)' % (self.default_factory, dict.__repr__(self)) diff --git a/window.py b/window.py index fde4efe..72590a7 100644 --- a/window.py +++ b/window.py @@ -67,7 +67,7 @@ class Window(object): elif regex.auto_mode_vi.search(firstline): mode_name = regex.auto_mode_vi.search(firstline).group(1) else: - for (r, name) in a.mode_detection.items(): + for (r, name) in list(a.mode_detection.items()): if r.match(b.lines[0]): mode_name = name break @@ -162,10 +162,14 @@ class Window(object): # redrawing def redraw(self): self._calc_last() - + def set_size(self, width, height): assert type(width) == type(0), width - assert type(height) == type(0), height + #assert type(height) == type(0), height #FIX3 + h = int(height) + assert h == height + height = h + self.width = width - self.mode.lmargin - self.mode.rmargin self.height = height - self.mode.header - self.mode.footer self.redraw() @@ -219,7 +223,12 @@ class Window(object): self.assure_visible_cursor() def point_is_visible(self, p): - return self.first <= p and p <= self.last + if self.last is None: + return False + elif self.first is None: + return p <= self.last + else: + return self.first <= p and p <= self.last def cursor_is_visible(self): return self.point_is_visible(self.logical_cursor()) def first_is_visible(self): @@ -455,7 +464,7 @@ class Window(object): self.goto(Point(0, y)) def forward_chars(self, n): (x, y) = self.logical_cursor().xy() - for _ in xrange(0, n): + for _ in range(0, n): if x == len(self.buffer.lines[y]): y += 1 x = 0 @@ -480,7 +489,7 @@ class Window(object): # TODO: multi-byte characters!!! def point_byte_offset(self, p): n = 0 - for i in xrange(0, p.y): + for i in range(0, p.y): n += len(self.buffer.lines[i]) + 1 return n + p.x def cursor_byte_offset(self):