Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Added python3 support #69

Open
wants to merge 3 commits into from

2 participants

@comutt

fixes: #57

(python|python3) switching is performed as follows:

  • if g:pyflakes_python_version is specified, use the specific version of python.
    • g:pyflakes_python_version supports 2 or 3 for major versions
  • else use the supported binding with order of: python2, python3

Note: To perform this, I'd moved out the internal python scripts to script1.py and script2.py.

comutt added some commits
@comutt comutt Added python3 support 800ccd3
@comutt comutt Modified exception handling for python3
* Python3's SyntaxError exception is different from python2's,
  so changed to obtain value by field names
b1ee1d3
ftplugin/python/pyflakes.vim
((43 lines not shown))
+ execute s:pyflakes_pyfile . " " . s:pyflakes_dir . "/script1.py"
@kevinw Owner
kevinw added a note

I think that "script1" and "script2" as filenames are too non-descriptive. What was your intent in splitting them up here?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
@comutt

@kevinw Thanks for reviewing, I've renamed that to be meaningful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Dec 3, 2013
  1. @comutt

    Added python3 support

    comutt authored
  2. @comutt

    Modified exception handling for python3

    comutt authored
    * Python3's SyntaxError exception is different from python2's,
      so changed to obtain value by field names
Commits on Dec 5, 2013
  1. @comutt
This page is out of date. Refresh to see the latest.
View
97 ftplugin/python/define_check_function.py
@@ -0,0 +1,97 @@
+# coding=utf-8
+import vim
+import os.path
+import sys
+
+if sys.version_info[:2] < (2, 5):
+ raise AssertionError('Vim must be compiled with Python 2.5 or higher; you have ' + sys.version)
+
+# get the directory this script is in: the pyflakes python module should be installed there.
+scriptdir = os.path.join(os.path.dirname(vim.eval('expand("<sfile>")')), 'pyflakes')
+if scriptdir not in sys.path:
+ sys.path.insert(0, scriptdir)
+
+import ast
+from pyflakes import checker, messages
+from operator import attrgetter
+import re
+
+class loc(object):
+ def __init__(self, lineno, col=None):
+ self.lineno = lineno
+ self.col_offset = col
+
+class SyntaxError(messages.Message):
+ message = 'could not compile: %s'
+ def __init__(self, filename, lineno, col, message):
+ messages.Message.__init__(self, filename, loc(lineno, col))
+ self.message_args = (message,)
+ # fix 某些情况缺少lineno导致异常
+ self.lineno = lineno
+
+class blackhole(object):
+ write = flush = lambda *a, **k: None
+
+def check(buffer):
+ filename = buffer.name
+ contents = buffer[:]
+
+ # shebang usually found at the top of the file, followed by source code encoding marker.
+ # assume everything else that follows is encoded in the encoding.
+ for n, line in enumerate(contents):
+ if n >= 2:
+ break
+ elif re.match(r'#.*coding[:=]\s*([-\w.]+)', line):
+ contents = ['']*(n+1) + contents[n+1:]
+ break
+
+ contents = '\n'.join(contents) + '\n'
+
+ if sys.version_info[0] < 3:
+ vimenc = vim.eval('&encoding')
+ if vimenc:
+ contents = contents.decode(vimenc)
+
+ builtins = set(['__file__'])
+ try:
+ builtins.update(set(eval(vim.eval('string(g:pyflakes_builtins)'))))
+ except Exception:
+ pass
+
+ try:
+ # TODO: use warnings filters instead of ignoring stderr
+ old_stderr, sys.stderr = sys.stderr, blackhole()
+ try:
+ tree = ast.parse(contents, filename or '<unknown>')
+ finally:
+ sys.stderr = old_stderr
+ except:
+ try:
+ value = sys.exc_info()[1]
+ if sys.version_info[0] < 3:
+ lineno, offset, line = value[1][1:]
+ else:
+ lineno, offset, line = value.lineno, value.offset, ''
+ except IndexError:
+ lineno, offset, line = 1, 0, ''
+ if line and line.endswith("\n"):
+ line = line[:-1]
+
+ return [SyntaxError(filename, lineno, offset, str(value))]
+ else:
+ # pyflakes looks to _MAGIC_GLOBALS in checker.py to see which
+ # UndefinedNames to ignore
+ old_globals = getattr(checker,' _MAGIC_GLOBALS', [])
+ checker._MAGIC_GLOBALS = set(old_globals) | builtins
+
+ filename = '(none)' if filename is None else filename
+ w = checker.Checker(tree, filename)
+
+ checker._MAGIC_GLOBALS = old_globals
+
+ w.messages.sort(key = attrgetter('lineno'))
+ return w.messages
+
+
+def vim_quote(s):
+ return s.replace("'", "''")
View
33 ftplugin/python/do_check.py
@@ -0,0 +1,33 @@
+# coding=utf-8
+for w in check(vim.current.buffer):
+ if not isinstance(w.lineno, int):
+ lineno = str(w.lineno.lineno)
+ else:
+ lineno = str(w.lineno)
+
+ vim.command('let s:matchDict = {}')
+ vim.command("let s:matchDict['lineNum'] = " + lineno)
+ vim.command("let s:matchDict['message'] = '%s'" % vim_quote(w.message % w.message_args))
+ vim.command("let b:matchedlines[" + lineno + "] = s:matchDict")
+
+ vim.command("let l:qf_item = {}")
+ vim.command("let l:qf_item.bufnr = bufnr('%')")
+ vim.command("let l:qf_item.filename = expand('%')")
+ vim.command("let l:qf_item.lnum = %s" % lineno)
+ vim.command("let l:qf_item.text = '%s'" % vim_quote(w.message % w.message_args))
+ vim.command("let l:qf_item.type = 'E'")
+
+ if getattr(w, 'col', None) is None or isinstance(w, SyntaxError):
+ # without column information, just highlight the whole line
+ # (minus the newline)
+ vim.command(r"let s:mID = matchadd('PyFlakes', '\%" + lineno + r"l\n\@!')")
+ else:
+ # with a column number, highlight the first keyword there
+ vim.command(r"let s:mID = matchadd('PyFlakes', '^\%" + lineno + r"l\_.\{-}\zs\k\+\k\@!\%>" + str(w.col) + r"c')")
+
+ vim.command("let l:qf_item.vcol = 1")
+ vim.command("let l:qf_item.col = %s" % str(w.col + 1))
+
+ vim.command("call add(b:matched, s:matchDict)")
+ vim.command("call add(b:qf_list, l:qf_item)")
+
View
163 ftplugin/python/pyflakes.vim
@@ -21,114 +21,43 @@ if !exists('g:pyflakes_builtins')
let g:pyflakes_builtins = []
endif
+let s:pyflakes_dir = expand("<sfile>:p:h")
if !exists("b:did_python_init")
let b:did_python_init = 0
- if !has('python')
- " the pyflakes.vim plugin requires Vim to be compiled with +python
+ if !has("python") && !has("python3")
+ echoerr "the pyflakes.vim plugin requires Vim to be compiled with +python or +python3"
finish
endif
-if !exists('g:pyflakes_use_quickfix')
- let g:pyflakes_use_quickfix = 1
-endif
+ if exists("g:pyflakes_python_version")
+ if g:pyflakes_python_version == 2
+ let s:pyflakes_pyfile = "pyfile"
+ if !has("python")
+ echoerr "the pyflakes.vim plugin requires Vim to be compiled with +python"
+ finish
+ endif
+ elseif g:pyflakes_python_version == 3
+ let s:pyflakes_pyfile = "py3file"
+ if !has("python3")
+ echoerr "the pyflakes.vim plugin requires Vim to be compiled with +python3"
+ finish
+ endif
+ endif
+ else
+ if has("python")
+ let s:pyflakes_pyfile = "pyfile"
+ elseif has("python3")
+ let s:pyflakes_pyfile = "py3file"
+ endif
+ endif
+
+ if !exists('g:pyflakes_use_quickfix')
+ let g:pyflakes_use_quickfix = 1
+ endif
+ execute s:pyflakes_pyfile . " " . s:pyflakes_dir . "/define_check_function.py"
- python << EOF
-import vim
-import os.path
-import sys
-
-if sys.version_info[:2] < (2, 5):
- raise AssertionError('Vim must be compiled with Python 2.5 or higher; you have ' + sys.version)
-
-# get the directory this script is in: the pyflakes python module should be installed there.
-scriptdir = os.path.join(os.path.dirname(vim.eval('expand("<sfile>")')), 'pyflakes')
-if scriptdir not in sys.path:
- sys.path.insert(0, scriptdir)
-
-import ast
-from pyflakes import checker, messages
-from operator import attrgetter
-import re
-
-class loc(object):
- def __init__(self, lineno, col=None):
- self.lineno = lineno
- self.col_offset = col
-
-class SyntaxError(messages.Message):
- message = 'could not compile: %s'
- def __init__(self, filename, lineno, col, message):
- messages.Message.__init__(self, filename, loc(lineno, col))
- self.message_args = (message,)
- # fix 某些情况缺少lineno导致异常
- self.lineno = lineno
-
-class blackhole(object):
- write = flush = lambda *a, **k: None
-
-def check(buffer):
- filename = buffer.name
- contents = buffer[:]
-
- # shebang usually found at the top of the file, followed by source code encoding marker.
- # assume everything else that follows is encoded in the encoding.
- encoding_found = False
- for n, line in enumerate(contents):
- if n >= 2:
- break
- elif re.match(r'#.*coding[:=]\s*([-\w.]+)', line):
- contents = ['']*(n+1) + contents[n+1:]
- break
-
- contents = '\n'.join(contents) + '\n'
-
- vimenc = vim.eval('&encoding')
- if vimenc:
- contents = contents.decode(vimenc)
-
- builtins = set(['__file__'])
- try:
- builtins.update(set(eval(vim.eval('string(g:pyflakes_builtins)'))))
- except Exception:
- pass
-
- try:
- # TODO: use warnings filters instead of ignoring stderr
- old_stderr, sys.stderr = sys.stderr, blackhole()
- try:
- tree = ast.parse(contents, filename or '<unknown>')
- finally:
- sys.stderr = old_stderr
- except:
- try:
- value = sys.exc_info()[1]
- lineno, offset, line = value[1][1:]
- except IndexError:
- lineno, offset, line = 1, 0, ''
- if line and line.endswith("\n"):
- line = line[:-1]
-
- return [SyntaxError(filename, lineno, offset, str(value))]
- else:
- # pyflakes looks to _MAGIC_GLOBALS in checker.py to see which
- # UndefinedNames to ignore
- old_globals = getattr(checker,' _MAGIC_GLOBALS', [])
- checker._MAGIC_GLOBALS = set(old_globals) | builtins
-
- filename = '(none)' if filename is None else filename
- w = checker.Checker(tree, filename)
-
- checker._MAGIC_GLOBALS = old_globals
-
- w.messages.sort(key = attrgetter('lineno'))
- return w.messages
-
-
-def vim_quote(s):
- return s.replace("'", "''")
-EOF
let b:did_python_init = 1
endif
@@ -237,39 +166,7 @@ if !exists("*s:RunPyflakes")
let b:qf_list = []
let b:qf_window_count = -1
- python << EOF
-for w in check(vim.current.buffer):
- if not isinstance(w.lineno, int):
- lineno = str(w.lineno.lineno)
- else:
- lineno = str(w.lineno)
-
- vim.command('let s:matchDict = {}')
- vim.command("let s:matchDict['lineNum'] = " + lineno)
- vim.command("let s:matchDict['message'] = '%s'" % vim_quote(w.message % w.message_args))
- vim.command("let b:matchedlines[" + lineno + "] = s:matchDict")
-
- vim.command("let l:qf_item = {}")
- vim.command("let l:qf_item.bufnr = bufnr('%')")
- vim.command("let l:qf_item.filename = expand('%')")
- vim.command("let l:qf_item.lnum = %s" % lineno)
- vim.command("let l:qf_item.text = '%s'" % vim_quote(w.message % w.message_args))
- vim.command("let l:qf_item.type = 'E'")
-
- if getattr(w, 'col', None) is None or isinstance(w, SyntaxError):
- # without column information, just highlight the whole line
- # (minus the newline)
- vim.command(r"let s:mID = matchadd('PyFlakes', '\%" + lineno + r"l\n\@!')")
- else:
- # with a column number, highlight the first keyword there
- vim.command(r"let s:mID = matchadd('PyFlakes', '^\%" + lineno + r"l\_.\{-}\zs\k\+\k\@!\%>" + str(w.col) + r"c')")
-
- vim.command("let l:qf_item.vcol = 1")
- vim.command("let l:qf_item.col = %s" % str(w.col + 1))
-
- vim.command("call add(b:matched, s:matchDict)")
- vim.command("call add(b:qf_list, l:qf_item)")
-EOF
+ execute s:pyflakes_pyfile . " " . s:pyflakes_dir . "/do_check.py"
if g:pyflakes_use_quickfix == 1
if exists("s:pyflakes_qf")
" if pyflakes quickfix window is already created, reuse it
Something went wrong with that request. Please try again.