def xrange(*args, **kwargs):
major_version = sys.version_info.major
if major_version == 3:
import builtins
return builtins.range(*args, **kwargs)
elif major_version == 2:
import __builtin__
return __builtin__.xrange(*args, **kwargs)
else:
raise RuntimeError("Unsupported version of Python.")
python类xrange()的实例源码
def visual_range(pl, segment_info, CTRL_V_text='{rows} x {vcols}', v_text_oneline='C:{vcols}', v_text_multiline='L:{rows}', V_text='L:{rows}'):
'''Return the current visual selection range.
:param str CTRL_V_text:
Text to display when in block visual or select mode.
:param str v_text_oneline:
Text to display when in charaterwise visual or select mode, assuming
selection occupies only one line.
:param str v_text_multiline:
Text to display when in charaterwise visual or select mode, assuming
selection occupies more then one line.
:param str V_text:
Text to display when in linewise visual or select mode.
All texts are format strings which are passed the following parameters:
========= =============================================================
Parameter Description
========= =============================================================
sline Line number of the first line of the selection
eline Line number of the last line of the selection
scol Column number of the first character of the selection
ecol Column number of the last character of the selection
svcol Virtual column number of the first character of the selection
secol Virtual column number of the last character of the selection
rows Number of lines in the selection
cols Number of columns in the selection
vcols Number of virtual columns in the selection
========= =============================================================
'''
sline, scol, soff = [int(v) for v in vim_funcs['getpos']('v')[1:]]
eline, ecol, eoff = [int(v) for v in vim_funcs['getpos']('.')[1:]]
svcol = vim_funcs['virtcol']([sline, scol, soff])
evcol = vim_funcs['virtcol']([eline, ecol, eoff])
rows = abs(eline - sline) + 1
cols = abs(ecol - scol) + 1
vcols = abs(evcol - svcol) + 1
return {
'^': CTRL_V_text,
's': v_text_oneline if rows == 1 else v_text_multiline,
'S': V_text,
'v': v_text_oneline if rows == 1 else v_text_multiline,
'V': V_text,
}.get(segment_info['mode'][0], '').format(
sline=sline, eline=eline,
scol=scol, ecol=ecol,
svcol=svcol, evcol=evcol,
rows=rows, cols=cols, vcols=vcols,
)
def trailing_whitespace(pl, segment_info):
'''Return the line number for trailing whitespaces
It is advised not to use this segment in insert mode: in Insert mode it will
iterate over all lines in buffer each time you happen to type a character
which may cause lags. It will also show you whitespace warning each time you
happen to type space.
Highlight groups used: ``trailing_whitespace`` or ``warning``.
'''
global trailing_whitespace_cache
if trailing_whitespace_cache is None:
trailing_whitespace_cache = register_buffer_cache(defaultdict(lambda: (0, None)))
bufnr = segment_info['bufnr']
changedtick = getbufvar(bufnr, 'changedtick')
if trailing_whitespace_cache[bufnr][0] == changedtick:
return trailing_whitespace_cache[bufnr][1]
else:
buf = segment_info['buffer']
bws = b' \t'
sws = str(' \t') # Ignore unicode_literals and use native str.
for i in range(len(buf)):
try:
line = buf[i]
except UnicodeDecodeError: # May happen in Python 3
if hasattr(vim, 'bindeval'):
line = vim.bindeval('getbufline({0}, {1})'.format(
bufnr, i + 1))
has_trailing_ws = (line[-1] in bws)
else:
line = vim.eval('strtrans(getbufline({0}, {1}))'.format(
bufnr, i + 1))
has_trailing_ws = (line[-1] in bws)
else:
has_trailing_ws = (line and line[-1] in sws)
if has_trailing_ws:
break
if has_trailing_ws:
ret = [{
'contents': str(i + 1),
'highlight_groups': ['trailing_whitespace', 'warning'],
}]
else:
ret = None
trailing_whitespace_cache[bufnr] = (changedtick, ret)
return ret
def iwait(objects, timeout=None, count=None):
"""
Iteratively yield *objects* as they are ready, until all (or *count*) are ready
or *timeout* expired.
:param objects: A sequence (supporting :func:`len`) containing objects
implementing the wait protocol (rawlink() and unlink()).
:keyword int count: If not `None`, then a number specifying the maximum number
of objects to wait for. If ``None`` (the default), all objects
are waited for.
:keyword float timeout: If given, specifies a maximum number of seconds
to wait. If the timeout expires before the desired waited-for objects
are available, then this method returns immediately.
.. seealso:: :func:`wait`
.. versionchanged:: 1.1a1
Add the *count* parameter.
.. versionchanged:: 1.1a2
No longer raise :exc:`LoopExit` if our caller switches greenlets
in between items yielded by this function.
"""
# QQQ would be nice to support iterable here that can be generated slowly (why?)
if objects is None:
yield get_hub().join(timeout=timeout)
return
count = len(objects) if count is None else min(count, len(objects))
waiter = _MultipleWaiter()
switch = waiter.switch
if timeout is not None:
timer = get_hub().loop.timer(timeout, priority=-1)
timer.start(switch, _NONE)
try:
for obj in objects:
obj.rawlink(switch)
for _ in xrange(count):
item = waiter.get()
waiter.clear()
if item is _NONE:
return
yield item
finally:
if timeout is not None:
timer.stop()
for obj in objects:
unlink = getattr(obj, 'unlink', None)
if unlink:
try:
unlink(switch)
except:
traceback.print_exc()
def visual_range(pl, segment_info, CTRL_V_text='{rows} x {vcols}', v_text_oneline='C:{vcols}', v_text_multiline='L:{rows}', V_text='L:{rows}'):
'''Return the current visual selection range.
:param str CTRL_V_text:
Text to display when in block visual or select mode.
:param str v_text_oneline:
Text to display when in charaterwise visual or select mode, assuming
selection occupies only one line.
:param str v_text_multiline:
Text to display when in charaterwise visual or select mode, assuming
selection occupies more then one line.
:param str V_text:
Text to display when in linewise visual or select mode.
All texts are format strings which are passed the following parameters:
========= =============================================================
Parameter Description
========= =============================================================
sline Line number of the first line of the selection
eline Line number of the last line of the selection
scol Column number of the first character of the selection
ecol Column number of the last character of the selection
svcol Virtual column number of the first character of the selection
secol Virtual column number of the last character of the selection
rows Number of lines in the selection
cols Number of columns in the selection
vcols Number of virtual columns in the selection
========= =============================================================
'''
sline, scol, soff = [int(v) for v in vim_funcs['getpos']('v')[1:]]
eline, ecol, eoff = [int(v) for v in vim_funcs['getpos']('.')[1:]]
svcol = vim_funcs['virtcol']([sline, scol, soff])
evcol = vim_funcs['virtcol']([eline, ecol, eoff])
rows = abs(eline - sline) + 1
cols = abs(ecol - scol) + 1
vcols = abs(evcol - svcol) + 1
return {
'^': CTRL_V_text,
's': v_text_oneline if rows == 1 else v_text_multiline,
'S': V_text,
'v': v_text_oneline if rows == 1 else v_text_multiline,
'V': V_text,
}.get(segment_info['mode'][0], '').format(
sline=sline, eline=eline,
scol=scol, ecol=ecol,
svcol=svcol, evcol=evcol,
rows=rows, cols=cols, vcols=vcols,
)
def trailing_whitespace(pl, segment_info):
'''Return the line number for trailing whitespaces
It is advised not to use this segment in insert mode: in Insert mode it will
iterate over all lines in buffer each time you happen to type a character
which may cause lags. It will also show you whitespace warning each time you
happen to type space.
Highlight groups used: ``trailing_whitespace`` or ``warning``.
'''
global trailing_whitespace_cache
if trailing_whitespace_cache is None:
trailing_whitespace_cache = register_buffer_cache(defaultdict(lambda: (0, None)))
bufnr = segment_info['bufnr']
changedtick = getbufvar(bufnr, 'changedtick')
if trailing_whitespace_cache[bufnr][0] == changedtick:
return trailing_whitespace_cache[bufnr][1]
else:
buf = segment_info['buffer']
bws = b' \t'
sws = str(' \t') # Ignore unicode_literals and use native str.
for i in range(len(buf)):
try:
line = buf[i]
except UnicodeDecodeError: # May happen in Python 3
if hasattr(vim, 'bindeval'):
line = vim.bindeval('getbufline({0}, {1})'.format(
bufnr, i + 1))
has_trailing_ws = (line[-1] in bws)
else:
line = vim.eval('strtrans(getbufline({0}, {1}))'.format(
bufnr, i + 1))
has_trailing_ws = (line[-1] in bws)
else:
has_trailing_ws = (line and line[-1] in sws)
if has_trailing_ws:
break
if has_trailing_ws:
ret = [{
'contents': str(i + 1),
'highlight_groups': ['trailing_whitespace', 'warning'],
}]
else:
ret = None
trailing_whitespace_cache[bufnr] = (changedtick, ret)
return ret
def iwait(objects, timeout=None, count=None):
"""
Iteratively yield *objects* as they are ready, until all (or *count*) are ready
or *timeout* expired.
:param objects: A sequence (supporting :func:`len`) containing objects
implementing the wait protocol (rawlink() and unlink()).
:keyword int count: If not `None`, then a number specifying the maximum number
of objects to wait for. If ``None`` (the default), all objects
are waited for.
:keyword float timeout: If given, specifies a maximum number of seconds
to wait. If the timeout expires before the desired waited-for objects
are available, then this method returns immediately.
.. seealso:: :func:`wait`
.. versionchanged:: 1.1a1
Add the *count* parameter.
.. versionchanged:: 1.1a2
No longer raise :exc:`LoopExit` if our caller switches greenlets
in between items yielded by this function.
"""
# QQQ would be nice to support iterable here that can be generated slowly (why?)
if objects is None:
yield get_hub().join(timeout=timeout)
return
count = len(objects) if count is None else min(count, len(objects))
waiter = _MultipleWaiter()
switch = waiter.switch
if timeout is not None:
timer = get_hub().loop.timer(timeout, priority=-1)
timer.start(switch, _NONE)
try:
for obj in objects:
obj.rawlink(switch)
for _ in xrange(count):
item = waiter.get()
waiter.clear()
if item is _NONE:
return
yield item
finally:
if timeout is not None:
timer.stop()
for obj in objects:
unlink = getattr(obj, 'unlink', None)
if unlink:
try:
unlink(switch)
except:
traceback.print_exc()