def run(self, edit): selection = [] nwsOffset = self.prev_non_whitespace() # do formatting and replacement replaceRegion = None formatSelection = False replaceRegion = sublime.Region(0, self.view.size()) file_in = StringIO.StringIO() file_in.write(self.view.substr(replaceRegion)) file_in.seek(0) file_out = StringIO.StringIO() PythonTidy.tidy_up(file_in, file_out) file_out.seek(0) res = file_out.read() self.view.replace(edit, replaceRegion, res) # re-place cursor offset = self.get_nws_offset( nwsOffset, self.view.substr(sublime.Region(0, self.view.size()))) rc = self.view.rowcol(offset) pt = self.view.text_point(rc[0], rc[1]) sel = self.view.sel() sel.clear() self.view.sel().add(sublime.Region(pt)) self.view.show_at_center(pt)
def run(self, edit): selection = [] nwsOffset = self.prev_non_whitespace() # do formatting and replacement replaceRegion = None formatSelection = False replaceRegion = sublime.Region(0, self.view.size()) file_in = StringIO.StringIO() file_in.write(self.view.substr(replaceRegion)) file_in.seek(0) file_out = StringIO.StringIO() PythonTidy.tidy_up(file_in, file_out) file_out.seek(0) res = file_out.read() self.view.replace(edit, replaceRegion, res) # re-place cursor offset = self.get_nws_offset(nwsOffset, self.view.substr(sublime.Region(0, self.view.size()))) rc = self.view.rowcol(offset) pt = self.view.text_point(rc[0], rc[1]) sel = self.view.sel() sel.clear() self.view.sel().add(sublime.Region(pt)) self.view.show_at_center(pt)
def run(self, edit): setup() view = self.view region = Region(0L, view.size()) source = StringIO(view.substr(region)) output = StringIO() PythonTidy.tidy_up(source, output) view.replace(edit, region, output.getvalue())
def tidy(self, name): test_name = os.path.join(PATH_TESTS, '%s.py' % name) back_name = os.path.join(PATH_TESTS, '%s.bak' % name) if os.path.exists(back_name): pass else: os.rename(test_name, back_name) print 'Converting', name PythonTidy.tidy_up(file_in=back_name, file_out=test_name) return self
def run(self, edit): setup() view = self.view region = Region(0L, view.size()) encoding = view.encoding() if not encoding or encoding == u'Undefined': encoding = view.settings().get('default_encoding') source = StringIO(view.substr(region).encode(encoding)) output = StringIO() PythonTidy.tidy_up(source, output) view.replace(edit, region, output.getvalue().decode(encoding))
def run(self, edit): setup() view = self.view region = Region(0L, view.size()) sourcestr = view.substr(region) encoding = view.encoding() if encoding == 'undefined': encoding = 'utf-8' source = StringIO(sourcestr.encode(encoding)) output = StringIO() PythonTidy.tidy_up(source, output) view.replace(edit, region, output.getvalue().decode(encoding))
def format_files(files=None, from_git=True): """ Executes PythonTidy on the provided list of files, optionally calling git add for each file that changed due to formatting. """ for file_in in files: file_in = os.path.abspath(file_in) print 'checking %s' % file_in if not os.path.exists(file_in): print 'missing file %s' % file_in continue file_out = tempfile.mktemp() try: import PythonTidy reload(PythonTidy) # monkeypach constants # TODO: make this more configurable PythonTidy.COL_LIMIT = 120 PythonTidy.MAX_SEPS_FUNC_DEF = 8 PythonTidy.MAX_SEPS_FUNC_REF = 8 PythonTidy.tidy_up(file_in=file_in, file_out=file_out) # overwrite original file only if hash differs if hashfile(file_in) != hashfile(file_out): print ' tidying %s' % file_in shutil.copymode(file_in, file_out) shutil.copy(file_out, file_in) # re-add modified file to git if required if from_git: execute('git add %s' % file_in) finally: os.remove(file_out)
def tidy_clean(dirname): for ff in os.listdir(dirname): name = os.path.join(dirname, ff) if os.path.isdir(name): dirname2 = os.path.join(dirname, ff) tidy_clean(dirname2) else: if name[-3:] == '.py': try: PythonTidy.tidy_up(file_in=name, file_out=name+".clean") except: if name[-11:] == '__init__.py': try: f = open(name,"r") buf = f.read() f.close() f2 = open(name+".clean", "w") f2.write(buf) f2.close() except: print(name) else: f = open(name,"r") buf = f.read() f.close() f2 = open(name+".clean", "w") f2.write(buf) f2.close() print(name) f = open(name,"r") buf = f.read() f.close() f2 = open(name+".bak", "w") f2.write(buf) f2.close() f = open(name+".clean","r") buf = f.read() f.close() f2 = open(name, "w") f2.write(buf) f2.close()
def main(): PARSER = optparse.OptionParser(usage='%prog [options] [input [output]]', description=__doc__) PARSER.add_option( '-u', '--ini_file', help='''Read configuration parameters from an ini_file.''', default=None) PARSER.add_option( '-U', '--dump', help= '''Dump default PythonTidy configuration parameters out to a file.''', default=None) (OPTS, ARGS) = PARSER.parse_args() if len(ARGS) > 2: PARSER.error('At most, only two arguments are allowed.') if len(ARGS) > 1: FILE_OUTPUT = ARGS[1] else: FILE_OUTPUT = '-' if FILE_OUTPUT in ['-']: FILE_OUTPUT = sys.stdout if len(ARGS) > ZERO: FILE_INPUT = ARGS[ZERO] else: FILE_INPUT = '-' if FILE_INPUT in ['-']: FILE_INPUT = sys.stdin if OPTS.dump is None: pass else: CONFIG = Config() CONFIG.from_pythontidy_namespace() CONFIG.write(file=OPTS.dump) sys.exit('Dump complete!') if OPTS.ini_file is None: pass else: CONFIG = Config(file=OPTS.ini_file) CONFIG.to_pythontidy_namespace() del CONFIG PythonTidy.tidy_up(FILE_INPUT, FILE_OUTPUT)
def main(): PARSER = optparse.OptionParser(usage='%prog [options] [input [output]]' , description=__doc__) PARSER.add_option('-u', '--ini_file', help='''Read configuration parameters from an ini_file.''' , default=None) PARSER.add_option('-U', '--dump', help='''Dump default PythonTidy configuration parameters out to a file.''' , default=None) (OPTS, ARGS) = PARSER.parse_args() if len(ARGS) > 2: PARSER.error('At most, only two arguments are allowed.') if len(ARGS) > 1: FILE_OUTPUT = ARGS[1] else: FILE_OUTPUT = '-' if FILE_OUTPUT in ['-']: FILE_OUTPUT = sys.stdout if len(ARGS) > ZERO: FILE_INPUT = ARGS[ZERO] else: FILE_INPUT = '-' if FILE_INPUT in ['-']: FILE_INPUT = sys.stdin if OPTS.dump is None: pass else: CONFIG = Config() CONFIG.from_pythontidy_namespace() CONFIG.write(file=OPTS.dump) sys.exit('Dump complete!') if OPTS.ini_file is None: pass else: CONFIG = Config(file=OPTS.ini_file) CONFIG.to_pythontidy_namespace() del CONFIG PythonTidy.tidy_up(FILE_INPUT, FILE_OUTPUT)
def run(self, edit): ''' Gathers all selections, runs it thru PythonTidy and replaces the selections. @type edit: sublime.Edit @param edit: Object used for replacement actions. @return: None ''' regions = [] PythonTidy.SHEBANG = '' PythonTidy.CODING_SPEC = '' PythonTidy.COL_LIMIT = 78 PythonTidy.KEEP_UNASSIGNED_CONSTANTS = True PythonTidy.ADD_BLANK_LINES_AROUND_COMMENTS = False for region in self.view.sel(): self._debug('region =', region, type(region)) line_begin = self.view.rowcol(region.begin())[0] + 1 line_end = self.view.rowcol(region.end())[0] + 1 self._debug('line_begin =', line_begin) self._debug('line_end =', line_end) if line_end - line_begin == 0: self._debug('single line') region = self.view.line(region) else: self._debug('multi line') row, col = self.view.rowcol(region.end()) point = self.view.text_point(row, col) region = sublime.Region(region.begin(), point) line_contents = self.view.substr(region) whitespace = re.compile('^(\s*)') smallest_indent = None for line in line_contents.split('\n'): if len(line.strip()) == 0: continue match = whitespace.match(line) indent = match.group(1) self._debug('match = "%s"' % indent) indent = indent.replace('\t', ' ' * 4) if smallest_indent is not None: smallest_indent = min(len(indent), smallest_indent) else: smallest_indent = len(indent) self._debug('=', line_contents.__repr__()) line_contents = textwrap.dedent(line_contents) has_trailing_newline = len(line_contents) and \ line_contents[-1] == '\n' self._debug('=', line_contents.__repr__()) self._debug('smallest_indent =', smallest_indent) file_in = StringIO.StringIO() file_in.write(line_contents) file_in.seek(0) file_out = StringIO.StringIO() try: PythonTidy.tidy_up(file_in, file_out) except IndentationError: msg = 'Unexpected indent in region with line from %d to %d' % ( line_begin, line_end) print msg sublime.status_message(msg) continue except Exception, excp: msg = '%s within line from %d to %d' % (excp, line_begin, line_end) print msg sublime.status_message(msg) continue file_out.seek(0) output = file_out.read().lstrip('\n') if smallest_indent is not None: self._debug('output =', output.__repr__()) output = output.rstrip('\n') output = output.split('\n') for row, line in enumerate(output): output[row] = ' ' * smallest_indent + line output = '\n'.join(output) if has_trailing_newline: output += '\n' self._debug('output =', output.__repr__()) self.view.replace(edit, region, output) line = sublime.Region(region.begin(), region.begin() + len(output)) regions.append(line)