code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
paths = set()
for loader in self.get_loaders():
try:
module = import_module(loader.__module__)
get_template_sources = getattr(
module, 'get_template_sources', loader.get_template_sources)
template_sources = get_template_sources('')
paths.update([t.name if isinstance(t, Origin) else t for t in template_sources])
except (ImportError, AttributeError):
pass
if not paths:
raise CommandError(
"No template paths found. None of the configured template loaders provided template paths")
templates = set()
for path in paths:
for root, _, files in os.walk(str(path)):
templates.update(os.path.join(root, name)
for name in files if not name.startswith('.') and
any(name.endswith(ext) for ext in self.template_exts))
if not templates:
raise CommandError(
"No templates found. Make sure your TEMPLATE_LOADERS and TEMPLATE_DIRS settings are correct.")
return templates | def find_templates(self) | Look for templates and extract the nodes containing the SASS file. | 3.009801 | 3.001488 | 1.00277 |
compile_kwargs = {
'filename': sass_filename,
'include_paths': SassProcessor.include_paths + APPS_INCLUDE_DIRS,
'custom_functions': get_custom_functions(),
}
if self.sass_precision:
compile_kwargs['precision'] = self.sass_precision
if self.sass_output_style:
compile_kwargs['output_style'] = self.sass_output_style
content = sass.compile(**compile_kwargs)
self.save_to_destination(content, sass_filename, sass_fileurl)
self.processed_files.append(sass_filename)
if self.verbosity > 1:
self.stdout.write("Compiled SASS/SCSS file: '{0}'\n".format(sass_filename)) | def compile_sass(self, sass_filename, sass_fileurl) | Compile the given SASS file into CSS | 2.798906 | 2.818488 | 0.993052 |
if self.use_static_root:
destpath = os.path.join(self.static_root, os.path.splitext(sass_fileurl)[0] + '.css')
else:
destpath = os.path.splitext(sass_filename)[0] + '.css'
if os.path.isfile(destpath):
os.remove(destpath)
self.processed_files.append(sass_filename)
if self.verbosity > 1:
self.stdout.write("Deleted '{0}'\n".format(destpath)) | def delete_file(self, sass_filename, sass_fileurl) | Delete a *.css file, but only if it has been generated through a SASS/SCSS file. | 2.397057 | 2.363651 | 1.014133 |
try:
# try with django-compressor<2.1
nodelist = self.parser.get_nodelist(node, original=original)
except TypeError:
nodelist = self.parser.get_nodelist(node, original=original, context=None)
for node in nodelist:
if isinstance(node, SassSrcNode):
if node.is_sass:
yield node
else:
for node in self.walk_nodes(node, original=original):
yield node | def walk_nodes(self, node, original) | Iterate over the nodes recursively yielding the templatetag 'sass_src' | 3.825614 | 3.254719 | 1.175406 |
def get_setting(*args):
try:
return getattr(settings, args[0])
except AttributeError as e:
raise TemplateSyntaxError(str(e))
if hasattr(get_custom_functions, '_custom_functions'):
return get_custom_functions._custom_functions
get_custom_functions._custom_functions = {sass.SassFunction('get-setting', ('key',), get_setting)}
for name, func in getattr(settings, 'SASS_PROCESSOR_CUSTOM_FUNCTIONS', {}).items():
try:
if isinstance(func, six.string_types):
func = import_string(func)
except Exception as e:
raise TemplateSyntaxError(str(e))
else:
if not inspect.isfunction(func):
raise TemplateSyntaxError("{} is not a Python function".format(func))
if six.PY2:
func_args = inspect.getargspec(func).args
else:
func_args = inspect.getfullargspec(func).args
sass_func = sass.SassFunction(name, func_args, func)
get_custom_functions._custom_functions.add(sass_func)
return get_custom_functions._custom_functions | def get_custom_functions() | Return a dict of function names, to be used from inside SASS | 2.385624 | 2.34684 | 1.016526 |
df = load_datasets()
if number > -1:
row = df.iloc[[number]]
elif name:
row = df.loc[df["Name"] == name]
url = ''.join(row.URL)
if not url:
print('The word vector you specified was not found. Please specify correct name.')
widgets = ['Test: ', Percentage(), ' ', Bar(marker=RotatingMarker()), ' ', ETA(), ' ', FileTransferSpeed()]
pbar = ProgressBar(widgets=widgets)
def dlProgress(count, blockSize, totalSize):
if pbar.max_value is None:
pbar.max_value = totalSize
pbar.start()
pbar.update(min(count * blockSize, totalSize))
file_name = url.split('/')[-1]
if not os.path.exists(save_dir):
os.makedirs(save_dir)
save_path = os.path.join(save_dir, file_name)
path, _ = urlretrieve(url, save_path, reporthook=dlProgress)
pbar.finish()
return path | def download(number=-1, name="", save_dir='./') | Download pre-trained word vector
:param number: integer, default ``None``
:param save_dir: str, default './'
:return: file path for downloaded file | 2.61664 | 2.622287 | 0.997846 |
df = load_datasets()
if lang == '':
print(df[['Name', 'Dimension', 'Corpus', 'VocabularySize', 'Method', 'Language', 'Author']])
else:
rows = df[df.Language==lang]
print(rows[['Name', 'Dimension', 'Corpus', 'VocabularySize', 'Method', 'Language', 'Author']]) | def search(lang='') | Search pre-trained word vectors by their language
:param lang: str, default ''
:return: None
print search result as pandas DataFrame | 3.774585 | 3.944093 | 0.957022 |
business_path = BUSINESS_PATH.format(business_id=business_id)
response = self.client._make_request(business_path, url_params=url_params)
return Business(response) | def get_by_id(self, business_id, **url_params) | Make a request to the business details endpoint. More info at
https://www.yelp.com/developers/documentation/v3/business
Args:
business_id (str): The business alias (i.e. yelp-san-francisco) or
ID (i.e. 4kMBvIEWPxWkWKFN__8SxQ.
**url_params: Dict corresponding to business API params
https://www.yelp.com/developers/documentation/v3/business
Returns:
yelp.obj.business.Business object that wraps the response. | 3.541843 | 3.899704 | 0.908234 |
json_response = raw_response.json()
error_info = json_response["error"]
code = error_info["code"]
try:
error_cls = _error_map[code]
except KeyError:
raise NotImplementedError(
"Unknown error code '{}' returned in Yelp API response. "
"This code may have been newly added. Please ensure you are "
"using the latest version of the yelp-python library, and if "
"so, create a new issue at https://github.com/Yelp/yelp-python "
"to add support for this error.".format(code)
)
else:
return error_cls(raw_response, **error_info) | def from_response(raw_response) | The Yelp Fusion API returns error messages with a json body
like:
{
'error': {
'code': 'ALL_CAPS_CODE',
'description': 'Human readable description.'
}
}
Some errors may have additional fields. For example, a
validation error:
{
'error': {
'code': 'VALIDATION_ERROR',
'description': "'en_USS' does not match '^[a-z]{2,3}_[A-Z]{2}$'",
'field': 'locale',
'instance': 'en_USS'
}
} | 3.575453 | 3.416196 | 1.046618 |
pin = pin if is_differential else pin + 0x04
return self._read(pin) | def read(self, pin, is_differential=False) | I2C Interface for ADS1x15-based ADCs reads.
params:
:param pin: individual or differential pin.
:param bool is_differential: single-ended or differential read. | 5.889837 | 8.850366 | 0.665491 |
config = _ADS1X15_CONFIG_OS_SINGLE
config |= (pin & 0x07) << _ADS1X15_CONFIG_MUX_OFFSET
config |= _ADS1X15_CONFIG_GAIN[self.gain]
config |= self.mode
config |= self.rate_config[self.data_rate]
config |= _ADS1X15_CONFIG_COMP_QUE_DISABLE
self._write_register(_ADS1X15_POINTER_CONFIG, config)
while not self._conversion_complete():
time.sleep(0.01)
return self.get_last_result() | def _read(self, pin) | Perform an ADC read. Returns the signed integer result of the read. | 3.176577 | 3.001554 | 1.058311 |
self.buf[0] = reg
self.buf[1] = (value >> 8) & 0xFF
self.buf[2] = value & 0xFF
with self.i2c_device as i2c:
i2c.write(self.buf) | def _write_register(self, reg, value) | Write 16 bit value to register. | 2.054473 | 1.833171 | 1.120721 |
self.buf[0] = reg
with self.i2c_device as i2c:
i2c.write(self.buf, end=1, stop=False)
i2c.readinto(self.buf, end=2)
return self.buf[0] << 8 | self.buf[1] | def _read_register(self, reg) | Read 16 bit register value. | 2.159737 | 1.937687 | 1.114595 |
return self._ads.read(self._pin_setting, is_differential=self.is_differential) | def value(self) | Returns the value of an ADC pin as an integer. | 22.29599 | 12.423217 | 1.794703 |
raw = self.value
volts = raw * (_ADS1X15_PGA_RANGE[self._ads.gain] / (2**(self._ads.bits-1) - 1))
return volts | def voltage(self) | Returns the voltage from the ADC pin as a floating point value. | 8.663602 | 7.744204 | 1.118721 |
if client.client_id not in self._sequential_ids:
id_ = sequential_id("e:{0}:users".format(self.name), client.client_id)
self._sequential_ids[client.client_id] = id_
return self._sequential_ids[client.client_id] | def sequential_id(self, client) | Return the sequential id for this test for the passed in client | 3.772659 | 3.708878 | 1.017197 |
if self.is_archived() or self.is_paused():
return self.control
if self.is_client_excluded(client):
return self.control
chosen_alternative = self.existing_alternative(client)
if not chosen_alternative:
chosen_alternative, participate = self.choose_alternative(client)
if participate and not prefetch:
chosen_alternative.record_participation(client, dt=dt)
return chosen_alternative | def get_alternative(self, client, dt=None, prefetch=False) | Returns and records an alternative according to the following
precedence:
1. An existing alternative
2. A server-chosen alternative | 4.653794 | 4.356222 | 1.06831 |
if dt is None:
date = datetime.now()
else:
date = dt
experiment_key = self.experiment.name
pipe = self.redis.pipeline()
pipe.sadd(_key("p:{0}:years".format(experiment_key)), date.strftime('%Y'))
pipe.sadd(_key("p:{0}:months".format(experiment_key)), date.strftime('%Y-%m'))
pipe.sadd(_key("p:{0}:days".format(experiment_key)), date.strftime('%Y-%m-%d'))
pipe.execute()
keys = [
_key("p:{0}:_all:all".format(experiment_key)),
_key("p:{0}:_all:{1}".format(experiment_key, date.strftime('%Y'))),
_key("p:{0}:_all:{1}".format(experiment_key, date.strftime('%Y-%m'))),
_key("p:{0}:_all:{1}".format(experiment_key, date.strftime('%Y-%m-%d'))),
_key("p:{0}:{1}:all".format(experiment_key, self.name)),
_key("p:{0}:{1}:{2}".format(experiment_key, self.name, date.strftime('%Y'))),
_key("p:{0}:{1}:{2}".format(experiment_key, self.name, date.strftime('%Y-%m'))),
_key("p:{0}:{1}:{2}".format(experiment_key, self.name, date.strftime('%Y-%m-%d'))),
]
msetbit(keys=keys, args=([self.experiment.sequential_id(client), 1] * len(keys))) | def record_participation(self, client, dt=None) | Record a user's participation in a test along with a given variation | 2.005418 | 2.018281 | 0.993627 |
key = _key(k)
return int(monotonic_zadd(keys=[key], args=[identifier])) | def sequential_id(k, identifier) | Map an arbitrary string identifier to a set of sequential ids | 19.344812 | 19.415228 | 0.996373 |
registry = Registry()
registry.add_binding(Keys.ControlX, Keys.ControlE,
filter=EmacsMode() & ~HasSelection())(
get_by_name('edit-and-execute-command'))
return registry | def load_emacs_open_in_editor_bindings() | Pressing C-X C-E will open the buffer in an external editor. | 13.997669 | 11.896982 | 1.176573 |
registry = ConditionalRegistry(Registry(), EmacsMode())
handle = registry.add_binding
handle(Keys.ControlV)(scroll_page_down)
handle(Keys.PageDown)(scroll_page_down)
handle(Keys.Escape, 'v')(scroll_page_up)
handle(Keys.PageUp)(scroll_page_up)
return registry | def load_extra_emacs_page_navigation_bindings() | Key bindings, for scrolling up and down through pages.
This are separate bindings, because GNU readline doesn't have them. | 5.03956 | 4.723698 | 1.066868 |
for match_variable in match.end_nodes():
varname = match_variable.varname
start = match_variable.start
completer = self.completers.get(varname)
if completer:
text = match_variable.value
# Unwrap text.
unwrapped_text = self.compiled_grammar.unescape(varname, text)
# Create a document, for the completions API (text/cursor_position)
document = Document(unwrapped_text, len(unwrapped_text))
# Call completer
for completion in completer.get_completions(document, complete_event):
new_text = unwrapped_text[:len(text) + completion.start_position] + completion.text
# Wrap again.
yield Completion(
text=self.compiled_grammar.escape(varname, new_text),
start_position=start - len(match.string),
display=completion.display,
display_meta=completion.display_meta) | def _get_completions_for_match(self, match, complete_event) | Yield all the possible completions for this input string.
(The completer assumes that the cursor position was at the end of the
input string.) | 4.237385 | 4.148358 | 1.021461 |
result = []
for i in items:
if i not in result:
result.append(i)
return result | def _remove_duplicates(self, items) | Remove duplicates, while keeping the order.
(Sometimes we have duplicates, because the there several matches of the
same grammar, each yielding similar completions.) | 2.604449 | 2.218605 | 1.173913 |
assert style_dict is None or isinstance(style_dict, dict)
assert style_cls is None or issubclass(style_cls, pygments_Style)
styles_dict = {}
if style_cls is not None:
styles_dict.update(style_cls.styles)
if style_dict is not None:
styles_dict.update(style_dict)
return style_from_dict(styles_dict, include_defaults=include_defaults) | def style_from_pygments(style_cls=pygments_DefaultStyle,
style_dict=None,
include_defaults=True) | Shortcut to create a :class:`.Style` instance from a Pygments style class
and a style dictionary.
Example::
from prompt_toolkit.styles.from_pygments import style_from_pygments
from pygments.styles import get_style_by_name
style = style_from_pygments(get_style_by_name('monokai'))
:param style_cls: Pygments style class to start from.
:param style_dict: Dictionary for this style. `{Token: style}`.
:param include_defaults: (`bool`) Include prompt_toolkit extensions. | 1.841041 | 2.213892 | 0.831586 |
" Deprecated. "
return style_from_pygments(
style_cls=pygments_style_cls,
style_dict=style_dict,
include_defaults=include_extensions) | def from_defaults(cls, style_dict=None,
pygments_style_cls=pygments_DefaultStyle,
include_extensions=True) | Deprecated. | 5.765607 | 5.048484 | 1.142047 |
arrtype = HANDLE * len(handles)
handle_array = arrtype(*handles)
ret = windll.kernel32.WaitForMultipleObjects(
len(handle_array), handle_array, BOOL(False), DWORD(timeout))
if ret == WAIT_TIMEOUT:
return None
else:
h = handle_array[ret]
return h | def _wait_for_handles(handles, timeout=-1) | Waits for multiple handles. (Similar to 'select') Returns the handle which is ready.
Returns `None` on timeout.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx | 3.133105 | 3.147524 | 0.995419 |
return windll.kernel32.CreateEventA(pointer(SECURITY_ATTRIBUTES()), BOOL(True), BOOL(False), None) | def _create_event() | Creates a Win32 unnamed Event .
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx | 7.504528 | 5.689472 | 1.31902 |
handles = [self._event, self._console_input_reader.handle]
handles.extend(self._read_fds.keys())
return _wait_for_handles(handles, timeout) | def _ready_for_reading(self, timeout=None) | Return the handle that is ready for reading or `None` on timeout. | 7.952047 | 6.361577 | 1.250012 |
# Append to list of pending callbacks.
self._calls_from_executor.append(callback)
# Set Windows event.
windll.kernel32.SetEvent(self._event) | def call_from_executor(self, callback, _max_postpone_until=None) | Call this function in the main event loop.
Similar to Twisted's ``callFromThread``. | 7.594365 | 7.7974 | 0.973961 |
" Start watching the file descriptor for read availability. "
h = msvcrt.get_osfhandle(fd)
self._read_fds[h] = callback | def add_reader(self, fd, callback) | Start watching the file descriptor for read availability. | 9.613029 | 5.981134 | 1.607225 |
" Stop watching the file descriptor for read availability. "
h = msvcrt.get_osfhandle(fd)
if h in self._read_fds:
del self._read_fds[h] | def remove_reader(self, fd) | Stop watching the file descriptor for read availability. | 6.305904 | 4.614396 | 1.366572 |
current_row = buffer.document.cursor_position_row
line_range = range(from_row, to_row)
# Apply transformation.
new_text = buffer.transform_lines(line_range, lambda l: ' ' * count + l)
buffer.document = Document(
new_text,
Document(new_text).translate_row_col_to_index(current_row, 0))
# Go to the start of the line.
buffer.cursor_position += buffer.document.get_start_of_line_position(after_whitespace=True) | def indent(buffer, from_row, to_row, count=1) | Indent text of a :class:`.Buffer` object. | 3.513752 | 3.427304 | 1.025224 |
current_row = buffer.document.cursor_position_row
line_range = range(from_row, to_row)
def transform(text):
remove = ' ' * count
if text.startswith(remove):
return text[len(remove):]
else:
return text.lstrip()
# Apply transformation.
new_text = buffer.transform_lines(line_range, transform)
buffer.document = Document(
new_text,
Document(new_text).translate_row_col_to_index(current_row, 0))
# Go to the start of the line.
buffer.cursor_position += buffer.document.get_start_of_line_position(after_whitespace=True) | def unindent(buffer, from_row, to_row, count=1) | Unindent text of a :class:`.Buffer` object. | 3.314995 | 3.332924 | 0.994621 |
lines = buffer.text.splitlines(True)
lines_before = lines[:from_row]
lines_after = lines[to_row + 1:]
lines_to_reformat = lines[from_row:to_row + 1]
if lines_to_reformat:
# Take indentation from the first line.
length = re.search(r'^\s*', lines_to_reformat[0]).end()
indent = lines_to_reformat[0][:length].replace('\n', '')
# Now, take all the 'words' from the lines to be reshaped.
words = ''.join(lines_to_reformat).split()
# And reshape.
width = (buffer.text_width or 80) - len(indent)
reshaped_text = [indent]
current_width = 0
for w in words:
if current_width:
if len(w) + current_width + 1 > width:
reshaped_text.append('\n')
reshaped_text.append(indent)
current_width = 0
else:
reshaped_text.append(' ')
current_width += 1
reshaped_text.append(w)
current_width += len(w)
if reshaped_text[-1] != '\n':
reshaped_text.append('\n')
# Apply result.
buffer.document = Document(
text=''.join(lines_before + reshaped_text + lines_after),
cursor_position=len(''.join(lines_before + reshaped_text))) | def reshape_text(buffer, from_row, to_row) | Reformat text, taking the width into account.
`to_row` is included.
(Vi 'gq' operator.) | 2.376552 | 2.370608 | 1.002507 |
def _handler(cli, buffer):
cli.run_in_terminal(lambda: handler(cli, buffer), render_cli_done=render_cli_done)
return AcceptAction(handler=_handler) | def run_in_terminal(cls, handler, render_cli_done=False) | Create an :class:`.AcceptAction` that runs the given handler in the
terminal.
:param render_cli_done: When True, render the interface in the 'Done'
state first, then execute the function. If False, erase the
interface instead. | 6.288141 | 5.007276 | 1.255801 |
if buffer.validate():
if self.handler:
self.handler(cli, buffer)
buffer.append_to_history() | def validate_and_handle(self, cli, buffer) | Validate buffer and handle the accept action. | 7.447022 | 6.267721 | 1.188155 |
return CompletionState(self.original_document, self.current_completions, complete_index=index) | def go_to_index(self, index) | Create a new :class:`.CompletionState` object with the new index. | 19.007662 | 7.832496 | 2.42677 |
if self.complete_index is None:
return self.original_document.text, self.original_document.cursor_position
else:
original_text_before_cursor = self.original_document.text_before_cursor
original_text_after_cursor = self.original_document.text_after_cursor
c = self.current_completions[self.complete_index]
if c.start_position == 0:
before = original_text_before_cursor
else:
before = original_text_before_cursor[:c.start_position]
new_text = before + c.text + original_text_after_cursor
new_cursor_position = len(before) + len(c.text)
return new_text, new_cursor_position | def new_text_and_position(self) | Return (new_text, new_cursor_position) for this completion. | 2.267662 | 1.985817 | 1.141929 |
assert initial_document is None or isinstance(initial_document, Document)
if append_to_history:
self.append_to_history()
initial_document = initial_document or Document()
self.__cursor_position = initial_document.cursor_position
# `ValidationError` instance. (Will be set when the input is wrong.)
self.validation_error = None
self.validation_state = ValidationState.UNKNOWN
# State of the selection.
self.selection_state = None
# Multiple cursor mode. (When we press 'I' or 'A' in visual-block mode,
# we can insert text on multiple lines at once. This is implemented by
# using multiple cursors.)
self.multiple_cursor_positions = []
# When doing consecutive up/down movements, prefer to stay at this column.
self.preferred_column = None
# State of complete browser
self.complete_state = None # For interactive completion through Ctrl-N/Ctrl-P.
# State of Emacs yank-nth-arg completion.
self.yank_nth_arg_state = None # for yank-nth-arg.
# Remember the document that we had *right before* the last paste
# operation. This is used for rotating through the kill ring.
self.document_before_paste = None
# Current suggestion.
self.suggestion = None
# The history search text. (Used for filtering the history when we
# browse through it.)
self.history_search_text = None
# Undo/redo stacks
self._undo_stack = [] # Stack of (text, cursor_position)
self._redo_stack = []
#: The working lines. Similar to history, except that this can be
#: modified. The user can press arrow_up and edit previous entries.
#: Ctrl-C should reset this, and copy the whole history back in here.
#: Enter should process the current command and append to the real
#: history.
self._working_lines = self.history.strings[:]
self._working_lines.append(initial_document.text)
self.__working_index = len(self._working_lines) - 1 | def reset(self, initial_document=None, append_to_history=False) | :param append_to_history: Append current input to history first. | 6.891005 | 6.821626 | 1.01017 |
working_index = self.working_index
working_lines = self._working_lines
original_value = working_lines[working_index]
working_lines[working_index] = value
# Return True when this text has been changed.
if len(value) != len(original_value):
# For Python 2, it seems that when two strings have a different
# length and one is a prefix of the other, Python still scans
# character by character to see whether the strings are different.
# (Some benchmarking showed significant differences for big
# documents. >100,000 of lines.)
return True
elif value != original_value:
return True
return False | def _set_text(self, value) | set text at current working_index. Return whether it changed. | 6.894087 | 6.008198 | 1.147447 |
original_position = self.__cursor_position
self.__cursor_position = max(0, value)
return value != original_position | def _set_cursor_position(self, value) | Set cursor position. Return whether it changed. | 6.612969 | 4.793636 | 1.379531 |
assert isinstance(value, six.text_type), 'Got %r' % value
assert self.cursor_position <= len(value)
# Don't allow editing of read-only buffers.
if self.read_only():
raise EditReadOnlyBuffer()
changed = self._set_text(value)
if changed:
self._text_changed()
# Reset history search text.
self.history_search_text = None | def text(self, value) | Setting text. (When doing this, make sure that the cursor_position is
valid for this text. text/cursor_position should be consistent at any time,
otherwise set a Document instead.) | 5.338372 | 4.807059 | 1.110528 |
assert isinstance(value, int)
assert value <= len(self.text)
changed = self._set_cursor_position(value)
if changed:
self._cursor_position_changed() | def cursor_position(self, value) | Setting cursor position. | 4.258545 | 4.207578 | 1.012113 |
return self._document_cache[
self.text, self.cursor_position, self.selection_state] | def document(self) | Return :class:`~prompt_toolkit.document.Document` instance from the
current text, cursor position and selection state. | 13.915237 | 5.979327 | 2.327225 |
assert isinstance(value, Document)
# Don't allow editing of read-only buffers.
if not bypass_readonly and self.read_only():
raise EditReadOnlyBuffer()
# Set text and cursor position first.
text_changed = self._set_text(value.text)
cursor_position_changed = self._set_cursor_position(value.cursor_position)
# Now handle change events. (We do this when text/cursor position is
# both set and consistent.)
if text_changed:
self._text_changed()
if cursor_position_changed:
self._cursor_position_changed() | def set_document(self, value, bypass_readonly=False) | Set :class:`~prompt_toolkit.document.Document` instance. Like the
``document`` property, but accept an ``bypass_readonly`` argument.
:param bypass_readonly: When True, don't raise an
:class:`.EditReadOnlyBuffer` exception, even
when the buffer is read-only. | 3.918383 | 3.450055 | 1.135745 |
# Safe if the text is different from the text at the top of the stack
# is different. If the text is the same, just update the cursor position.
if self._undo_stack and self._undo_stack[-1][0] == self.text:
self._undo_stack[-1] = (self._undo_stack[-1][0], self.cursor_position)
else:
self._undo_stack.append((self.text, self.cursor_position))
# Saving anything to the undo stack, clears the redo stack.
if clear_redo_stack:
self._redo_stack = [] | def save_to_undo_stack(self, clear_redo_stack=True) | Safe current state (input text and cursor position), so that we can
restore it by calling undo. | 2.984449 | 2.794093 | 1.068128 |
# Split lines
lines = self.text.split('\n')
# Apply transformation
for index in line_index_iterator:
try:
lines[index] = transform_callback(lines[index])
except IndexError:
pass
return '\n'.join(lines) | def transform_lines(self, line_index_iterator, transform_callback) | Transforms the text on a range of lines.
When the iterator yield an index not in the range of lines that the
document contains, it skips them silently.
To uppercase some lines::
new_text = transform_lines(range(5,10), lambda text: text.upper())
:param line_index_iterator: Iterator of line numbers (int)
:param transform_callback: callable that takes the original text of a
line, and return the new text for this line.
:returns: The new text. | 2.86228 | 3.357715 | 0.852449 |
document = self.document
a = document.cursor_position + document.get_start_of_line_position()
b = document.cursor_position + document.get_end_of_line_position()
self.text = (
document.text[:a] +
transform_callback(document.text[a:b]) +
document.text[b:]) | def transform_current_line(self, transform_callback) | Apply the given transformation function to the current line.
:param transform_callback: callable that takes a string and return a new string. | 2.804049 | 2.89067 | 0.970034 |
assert from_ < to
self.text = ''.join([
self.text[:from_] +
transform_callback(self.text[from_:to]) +
self.text[to:]
]) | def transform_region(self, from_, to, transform_callback) | Transform a part of the input string.
:param from_: (int) start position.
:param to: (int) end position.
:param transform_callback: Callable which accepts a string and returns
the transformed string. | 3.355039 | 3.346968 | 1.002412 |
original_column = self.preferred_column or self.document.cursor_position_col
self.cursor_position += self.document.get_cursor_up_position(
count=count, preferred_column=original_column)
# Remember the original column for the next up/down movement.
self.preferred_column = original_column | def cursor_up(self, count=1) | (for multiline edit). Move cursor to the previous line. | 5.536909 | 4.643679 | 1.192354 |
original_column = self.preferred_column or self.document.cursor_position_col
self.cursor_position += self.document.get_cursor_down_position(
count=count, preferred_column=original_column)
# Remember the original column for the next up/down movement.
self.preferred_column = original_column | def cursor_down(self, count=1) | (for multiline edit). Move cursor to the next line. | 5.591929 | 4.783225 | 1.169071 |
if self.complete_state:
self.complete_previous(count=count)
elif self.document.cursor_position_row > 0:
self.cursor_up(count=count)
elif not self.selection_state:
self.history_backward(count=count)
# Go to the start of the line?
if go_to_start_of_line_if_history_changes:
self.cursor_position += self.document.get_start_of_line_position() | def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False) | If we're not on the first line (of a multiline input) go a line up,
otherwise go back in history. (If nothing is selected.) | 3.053856 | 2.756234 | 1.107981 |
if self.complete_state:
self.complete_next(count=count)
elif self.document.cursor_position_row < self.document.line_count - 1:
self.cursor_down(count=count)
elif not self.selection_state:
self.history_forward(count=count)
# Go to the start of the line?
if go_to_start_of_line_if_history_changes:
self.cursor_position += self.document.get_start_of_line_position() | def auto_down(self, count=1, go_to_start_of_line_if_history_changes=False) | If we're not on the last line (of a multiline input) go a line down,
otherwise go forward in history. (If nothing is selected.) | 2.936874 | 2.638226 | 1.1132 |
assert count >= 0
deleted = ''
if self.cursor_position > 0:
deleted = self.text[self.cursor_position - count:self.cursor_position]
new_text = self.text[:self.cursor_position - count] + self.text[self.cursor_position:]
new_cursor_position = self.cursor_position - len(deleted)
# Set new Document atomically.
self.document = Document(new_text, new_cursor_position)
return deleted | def delete_before_cursor(self, count=1) | Delete specified number of characters before cursor and return the
deleted text. | 2.914019 | 2.862136 | 1.018128 |
if self.cursor_position < len(self.text):
deleted = self.document.text_after_cursor[:count]
self.text = self.text[:self.cursor_position] + \
self.text[self.cursor_position + len(deleted):]
return deleted
else:
return '' | def delete(self, count=1) | Delete specified number of characters and Return the deleted text. | 3.086661 | 2.708498 | 1.139621 |
if not self.document.on_last_line:
self.cursor_position += self.document.get_end_of_line_position()
self.delete()
# Remove spaces.
self.text = (self.document.text_before_cursor + separator +
self.document.text_after_cursor.lstrip(' ')) | def join_next_line(self, separator=' ') | Join the next line to the current one by deleting the line ending after
the current line. | 5.115054 | 4.601035 | 1.111718 |
assert self.selection_state
# Get lines.
from_, to = sorted([self.cursor_position, self.selection_state.original_cursor_position])
before = self.text[:from_]
lines = self.text[from_:to].splitlines()
after = self.text[to:]
# Replace leading spaces with just one space.
lines = [l.lstrip(' ') + separator for l in lines]
# Set new document.
self.document = Document(text=before + ''.join(lines) + after,
cursor_position=len(before + ''.join(lines[:-1])) - 1) | def join_selected_lines(self, separator=' ') | Join the selected lines. | 3.918531 | 3.793503 | 1.032958 |
pos = self.cursor_position
if pos >= 2:
a = self.text[pos - 2]
b = self.text[pos - 1]
self.text = self.text[:pos-2] + b + a + self.text[pos:] | def swap_characters_before_cursor(self) | Swap the last two characters before the cursor. | 2.520977 | 2.267565 | 1.111755 |
if index < len(self._working_lines):
self.working_index = index
self.cursor_position = len(self.text) | def go_to_history(self, index) | Go to this item in the history. | 6.822362 | 6.234735 | 1.094251 |
if self.complete_state:
completions_count = len(self.complete_state.current_completions)
if self.complete_state.complete_index is None:
index = 0
elif self.complete_state.complete_index == completions_count - 1:
index = None
if disable_wrap_around:
return
else:
index = min(completions_count-1, self.complete_state.complete_index + count)
self.go_to_completion(index) | def complete_next(self, count=1, disable_wrap_around=False) | Browse to the next completions.
(Does nothing if there are no completion.) | 2.906862 | 2.650987 | 1.096521 |
if self.complete_state:
if self.complete_state.complete_index == 0:
index = None
if disable_wrap_around:
return
elif self.complete_state.complete_index is None:
index = len(self.complete_state.current_completions) - 1
else:
index = max(0, self.complete_state.complete_index - count)
self.go_to_completion(index) | def complete_previous(self, count=1, disable_wrap_around=False) | Browse to the previous completions.
(Does nothing if there are no completion.) | 2.99307 | 2.608763 | 1.147314 |
assert not (go_to_first and go_to_last)
# Generate list of all completions.
if completions is None:
if self.completer:
completions = list(self.completer.get_completions(
self.document,
CompleteEvent(completion_requested=True)
))
else:
completions = []
# Set `complete_state`.
if completions:
self.complete_state = CompletionState(
original_document=self.document,
current_completions=completions)
if go_to_first:
self.go_to_completion(0)
elif go_to_last:
self.go_to_completion(len(completions) - 1)
else:
self.go_to_completion(None)
else:
self.complete_state = None | def set_completions(self, completions, go_to_first=True, go_to_last=False) | Start completions. (Generate list of completions and initialize.) | 2.491054 | 2.397691 | 1.038939 |
found_completions = set()
completions = []
# For every line of the whole history, find matches with the current line.
current_line = self.document.current_line_before_cursor.lstrip()
for i, string in enumerate(self._working_lines):
for j, l in enumerate(string.split('\n')):
l = l.strip()
if l and l.startswith(current_line):
# When a new line has been found.
if l not in found_completions:
found_completions.add(l)
# Create completion.
if i == self.working_index:
display_meta = "Current, line %s" % (j+1)
else:
display_meta = "History %s, line %s" % (i+1, j+1)
completions.append(Completion(
l,
start_position=-len(current_line),
display_meta=display_meta))
self.set_completions(completions=completions[::-1]) | def start_history_lines_completion(self) | Start a completion based on all the other lines in the document and the
history. | 3.388073 | 3.339862 | 1.014435 |
assert index is None or isinstance(index, int)
assert self.complete_state
# Set new completion
state = self.complete_state.go_to_index(index)
# Set text/cursor position
new_text, new_cursor_position = state.new_text_and_position()
self.document = Document(new_text, new_cursor_position)
# (changing text/cursor position will unset complete_state.)
self.complete_state = state | def go_to_completion(self, index) | Select a completion from the list of current completions. | 5.209245 | 5.072391 | 1.02698 |
assert isinstance(completion, Completion)
# If there was already a completion active, cancel that one.
if self.complete_state:
self.go_to_completion(None)
self.complete_state = None
# Insert text from the given completion.
self.delete_before_cursor(-completion.start_position)
self.insert_text(completion.text) | def apply_completion(self, completion) | Insert a given completion. | 5.613108 | 5.112276 | 1.097967 |
if self.enable_history_search():
if self.history_search_text is None:
self.history_search_text = self.document.text_before_cursor
else:
self.history_search_text = None | def _set_history_search(self) | Set `history_search_text`. | 3.347142 | 2.688776 | 1.244858 |
return (self.history_search_text is None or
self._working_lines[i].startswith(self.history_search_text)) | def _history_matches(self, i) | True when the current entry matches the history search.
(when we don't have history search, it's also True.) | 7.850138 | 4.620221 | 1.699083 |
self._set_history_search()
# Go forward in history.
found_something = False
for i in range(self.working_index + 1, len(self._working_lines)):
if self._history_matches(i):
self.working_index = i
count -= 1
found_something = True
if count == 0:
break
# If we found an entry, move cursor to the end of the first line.
if found_something:
self.cursor_position = 0
self.cursor_position += self.document.get_end_of_line_position() | def history_forward(self, count=1) | Move forwards through the history.
:param count: Amount of items to move forward. | 4.003173 | 4.295058 | 0.932042 |
self._set_history_search()
# Go back in history.
found_something = False
for i in range(self.working_index - 1, -1, -1):
if self._history_matches(i):
self.working_index = i
count -= 1
found_something = True
if count == 0:
break
# If we move to another entry, move cursor to the end of the line.
if found_something:
self.cursor_position = len(self.text) | def history_backward(self, count=1) | Move backwards through history. | 4.510936 | 4.161162 | 1.084057 |
assert n is None or isinstance(n, int)
if not len(self.history):
return
# Make sure we have a `YankNthArgState`.
if self.yank_nth_arg_state is None:
state = YankNthArgState(n=-1 if _yank_last_arg else 1)
else:
state = self.yank_nth_arg_state
if n is not None:
state.n = n
# Get new history position.
new_pos = state.history_position - 1
if -new_pos > len(self.history):
new_pos = -1
# Take argument from line.
line = self.history[new_pos]
words = [w.strip() for w in _QUOTED_WORDS_RE.split(line)]
words = [w for w in words if w]
try:
word = words[state.n]
except IndexError:
word = ''
# Insert new argument.
if state.previous_inserted_word:
self.delete_before_cursor(len(state.previous_inserted_word))
self.insert_text(word)
# Save state again for next completion. (Note that the 'insert'
# operation from above clears `self.yank_nth_arg_state`.)
state.previous_inserted_word = word
state.history_position = new_pos
self.yank_nth_arg_state = state | def yank_nth_arg(self, n=None, _yank_last_arg=False) | Pick nth word from previous history entry (depending on current
`yank_nth_arg_state`) and insert it at current position. Rotate through
history if called repeatedly. If no `n` has been given, take the first
argument. (The second word.)
:param n: (None or int), The index of the word from the previous line
to take. | 3.103639 | 2.897579 | 1.071115 |
self.selection_state = SelectionState(self.cursor_position, selection_type) | def start_selection(self, selection_type=SelectionType.CHARACTERS) | Take the current cursor position as the start of this selection. | 6.270576 | 4.25056 | 1.475235 |
new_document, clipboard_data = self.document.cut_selection()
if _cut:
self.document = new_document
self.selection_state = None
return clipboard_data | def copy_selection(self, _cut=False) | Copy selected text and return :class:`.ClipboardData` instance. | 6.095995 | 4.618227 | 1.319986 |
assert isinstance(data, ClipboardData)
assert paste_mode in (PasteMode.VI_BEFORE, PasteMode.VI_AFTER, PasteMode.EMACS)
original_document = self.document
self.document = self.document.paste_clipboard_data(data, paste_mode=paste_mode, count=count)
# Remember original document. This assignment should come at the end,
# because assigning to 'document' will erase it.
self.document_before_paste = original_document | def paste_clipboard_data(self, data, paste_mode=PasteMode.EMACS, count=1) | Insert the data from the clipboard. | 4.299321 | 4.160561 | 1.033351 |
if copy_margin:
self.insert_text('\n' + self.document.leading_whitespace_in_current_line)
else:
self.insert_text('\n') | def newline(self, copy_margin=True) | Insert a line ending at the current position. | 4.491732 | 3.837907 | 1.17036 |
if copy_margin:
insert = self.document.leading_whitespace_in_current_line + '\n'
else:
insert = '\n'
self.cursor_position += self.document.get_start_of_line_position()
self.insert_text(insert)
self.cursor_position -= 1 | def insert_line_above(self, copy_margin=True) | Insert a new line above the current one. | 3.562657 | 3.386284 | 1.052085 |
if copy_margin:
insert = '\n' + self.document.leading_whitespace_in_current_line
else:
insert = '\n'
self.cursor_position += self.document.get_end_of_line_position()
self.insert_text(insert) | def insert_line_below(self, copy_margin=True) | Insert a new line below the current one. | 3.858293 | 3.670837 | 1.051066 |
# Original text & cursor position.
otext = self.text
ocpos = self.cursor_position
# In insert/text mode.
if overwrite:
# Don't overwrite the newline itself. Just before the line ending,
# it should act like insert mode.
overwritten_text = otext[ocpos:ocpos + len(data)]
if '\n' in overwritten_text:
overwritten_text = overwritten_text[:overwritten_text.find('\n')]
self.text = otext[:ocpos] + data + otext[ocpos + len(overwritten_text):]
else:
self.text = otext[:ocpos] + data + otext[ocpos:]
if move_cursor:
self.cursor_position += len(data)
# Fire 'on_text_insert' event.
if fire_event:
self.on_text_insert.fire() | def insert_text(self, data, overwrite=False, move_cursor=True, fire_event=True) | Insert characters at cursor position.
:param fire_event: Fire `on_text_insert` event. This is mainly used to
trigger autocompletion while typing. | 3.235568 | 3.238836 | 0.998991 |
# Don't call the validator again, if it was already called for the
# current input.
if self.validation_state != ValidationState.UNKNOWN:
return self.validation_state == ValidationState.VALID
# Validate first. If not valid, set validation exception.
if self.validator:
try:
self.validator.validate(self.document)
except ValidationError as e:
# Set cursor position (don't allow invalid values.)
cursor_position = e.cursor_position
self.cursor_position = min(max(0, cursor_position), len(self.text))
self.validation_state = ValidationState.INVALID
self.validation_error = e
return False
self.validation_state = ValidationState.VALID
self.validation_error = None
return True | def validate(self) | Returns `True` if valid. | 3.65458 | 3.458324 | 1.056749 |
# Validate first. If not valid, set validation exception.
if not self.validate():
return
# Save at the tail of the history. (But don't if the last entry the
# history is already the same.)
if self.text and (not len(self.history) or self.history[-1] != self.text):
self.history.append(self.text) | def append_to_history(self) | Append the current input to the history.
(Only if valid input.) | 7.163072 | 6.26654 | 1.143067 |
assert isinstance(search_state, SearchState)
assert isinstance(count, int) and count > 0
text = search_state.text
direction = search_state.direction
ignore_case = search_state.ignore_case()
def search_once(working_index, document):
if direction == IncrementalSearchDirection.FORWARD:
# Try find at the current input.
new_index = document.find(
text, include_current_position=include_current_position,
ignore_case=ignore_case)
if new_index is not None:
return (working_index,
Document(document.text, document.cursor_position + new_index))
else:
# No match, go forward in the history. (Include len+1 to wrap around.)
# (Here we should always include all cursor positions, because
# it's a different line.)
for i in range(working_index + 1, len(self._working_lines) + 1):
i %= len(self._working_lines)
document = Document(self._working_lines[i], 0)
new_index = document.find(text, include_current_position=True,
ignore_case=ignore_case)
if new_index is not None:
return (i, Document(document.text, new_index))
else:
# Try find at the current input.
new_index = document.find_backwards(
text, ignore_case=ignore_case)
if new_index is not None:
return (working_index,
Document(document.text, document.cursor_position + new_index))
else:
# No match, go back in the history. (Include -1 to wrap around.)
for i in range(working_index - 1, -2, -1):
i %= len(self._working_lines)
document = Document(self._working_lines[i], len(self._working_lines[i]))
new_index = document.find_backwards(
text, ignore_case=ignore_case)
if new_index is not None:
return (i, Document(document.text, len(document.text) + new_index))
# Do 'count' search iterations.
working_index = self.working_index
document = self.document
for _ in range(count):
result = search_once(working_index, document)
if result is None:
return # Nothing found.
else:
working_index, document = result
return (working_index, document.cursor_position) | def _search(self, search_state, include_current_position=False, count=1) | Execute search. Return (working_index, cursor_position) tuple when this
search is applied. Returns `None` when this text cannot be found. | 2.432217 | 2.352975 | 1.033677 |
search_result = self._search(search_state, include_current_position=True)
if search_result is None:
return self.document
else:
working_index, cursor_position = search_result
# Keep selection, when `working_index` was not changed.
if working_index == self.working_index:
selection = self.selection_state
else:
selection = None
return Document(self._working_lines[working_index],
cursor_position, selection=selection) | def document_for_search(self, search_state) | Return a :class:`~prompt_toolkit.document.Document` instance that has
the text/cursor position for this search, if we would apply it. This
will be used in the
:class:`~prompt_toolkit.layout.controls.BufferControl` to display
feedback while searching. | 4.47011 | 4.247327 | 1.052453 |
search_result = self._search(
search_state, include_current_position=include_current_position, count=count)
if search_result is None:
return self.cursor_position
else:
working_index, cursor_position = search_result
return cursor_position | def get_search_position(self, search_state, include_current_position=True, count=1) | Get the cursor position for this search.
(This operation won't change the `working_index`. It's won't go through
the history. Vi text objects can't span multiple items.) | 3.403858 | 2.511692 | 1.355205 |
if self.read_only():
raise EditReadOnlyBuffer()
# Write to temporary file
descriptor, filename = tempfile.mkstemp(self.tempfile_suffix)
os.write(descriptor, self.text.encode('utf-8'))
os.close(descriptor)
# Open in editor
# (We need to use `cli.run_in_terminal`, because not all editors go to
# the alternate screen buffer, and some could influence the cursor
# position.)
succes = cli.run_in_terminal(lambda: self._open_file_in_editor(filename))
# Read content again.
if succes:
with open(filename, 'rb') as f:
text = f.read().decode('utf-8')
# Drop trailing newline. (Editors are supposed to add it at the
# end, but we don't need it.)
if text.endswith('\n'):
text = text[:-1]
self.document = Document(
text=text,
cursor_position=len(text))
# Clean up temp file.
os.remove(filename) | def open_in_editor(self, cli) | Open code in editor.
:param cli: :class:`~prompt_toolkit.interface.CommandLineInterface`
instance. | 4.451326 | 4.28844 | 1.037983 |
# If the 'VISUAL' or 'EDITOR' environment variable has been set, use that.
# Otherwise, fall back to the first available editor that we can find.
visual = os.environ.get('VISUAL')
editor = os.environ.get('EDITOR')
editors = [
visual,
editor,
# Order of preference.
'/usr/bin/editor',
'/usr/bin/nano',
'/usr/bin/pico',
'/usr/bin/vi',
'/usr/bin/emacs',
]
for e in editors:
if e:
try:
# Use 'shlex.split()', because $VISUAL can contain spaces
# and quotes.
returncode = subprocess.call(shlex.split(e) + [filename])
return returncode == 0
except OSError:
# Executable does not exist, try the next one.
pass
return False | def _open_file_in_editor(self, filename) | Call editor executable.
Return True when we received a zero return code. | 3.492577 | 3.3693 | 1.036588 |
# Note: We cannot use "yield from", because this package also
# installs on Python 2.
assert isinstance(callbacks, EventLoopCallbacks)
if self.closed:
raise Exception('Event loop already closed.')
timeout = AsyncioTimeout(INPUT_TIMEOUT, callbacks.input_timeout, self.loop)
self.running = True
try:
while self.running:
timeout.reset()
# Get keys
try:
g = iter(self.loop.run_in_executor(None, self._console_input_reader.read))
while True:
yield next(g)
except StopIteration as e:
keys = e.args[0]
# Feed keys to input processor.
for k in keys:
callbacks.feed_key(k)
finally:
timeout.stop() | def run_as_coroutine(self, stdin, callbacks) | The input 'event loop'. | 6.067854 | 5.735118 | 1.058017 |
# Cache, because this one is reused very often.
if self._cache.lines is None:
self._cache.lines = _ImmutableLineList(self.text.split('\n'))
return self._cache.lines | def lines(self) | Array of all the lines. | 8.825977 | 8.104761 | 1.088987 |
# Cache, because this is often reused. (If it is used, it's often used
# many times. And this has to be fast for editing big documents!)
if self._cache.line_indexes is None:
# Create list of line lengths.
line_lengths = map(len, self.lines)
# Calculate cumulative sums.
indexes = [0]
append = indexes.append
pos = 0
for line_length in line_lengths:
pos += line_length + 1
append(pos)
# Remove the last item. (This is not a new line.)
if len(indexes) > 1:
indexes.pop()
self._cache.line_indexes = indexes
return self._cache.line_indexes | def _line_start_indexes(self) | Array pointing to the start indexes of all the lines. | 5.623251 | 5.39821 | 1.041688 |
current_line = self.current_line
length = len(current_line) - len(current_line.lstrip())
return current_line[:length] | def leading_whitespace_in_current_line(self) | The leading whitespace in the left margin of the current line. | 3.068158 | 2.46315 | 1.245624 |
# (Don't use self.text_before_cursor to calculate this. Creating
# substrings and doing rsplit is too expensive for getting the cursor
# position.)
_, line_start_index = self._find_line_start_index(self.cursor_position)
return self.cursor_position - line_start_index | def cursor_position_col(self) | Current column. (0-based.) | 9.098372 | 8.695313 | 1.046354 |
indexes = self._line_start_indexes
pos = bisect.bisect_right(indexes, index) - 1
return pos, indexes[pos] | def _find_line_start_index(self, index) | For the index of a character at a certain line, calculate the index of
the first character on that line.
Return (row, index) tuple. | 5.154681 | 5.370384 | 0.959835 |
# Find start of this line.
row, row_index = self._find_line_start_index(index)
col = index - row_index
return row, col | def translate_index_to_position(self, index) | Given an index for the text, return the corresponding (row, col) tuple.
(0-based. Returns (0, 0) for index=0.) | 6.767431 | 4.514558 | 1.499024 |
try:
result = self._line_start_indexes[row]
line = self.lines[row]
except IndexError:
if row < 0:
result = self._line_start_indexes[0]
line = self.lines[0]
else:
result = self._line_start_indexes[-1]
line = self.lines[-1]
result += max(0, min(col, len(line)))
# Keep in range. (len(self.text) is included, because the cursor can be
# right after the end of the text as well.)
result = max(0, min(result, len(self.text)))
return result | def translate_row_col_to_index(self, row, col) | Given a (row, col) tuple, return the corresponding index.
(Row and col params are 0-based.)
Negative row/col values are turned into zero. | 3.571857 | 3.476476 | 1.027436 |
return self.text.find(sub, self.cursor_position) == self.cursor_position | def has_match_at_current_position(self, sub) | `True` when this substring is found at the cursor position. | 4.954324 | 3.748143 | 1.321808 |
assert isinstance(ignore_case, bool)
if in_current_line:
text = self.current_line_after_cursor
else:
text = self.text_after_cursor
if not include_current_position:
if len(text) == 0:
return # (Otherwise, we always get a match for the empty string.)
else:
text = text[1:]
flags = re.IGNORECASE if ignore_case else 0
iterator = re.finditer(re.escape(sub), text, flags)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
if include_current_position:
return match.start(0)
else:
return match.start(0) + 1
except StopIteration:
pass | def find(self, sub, in_current_line=False, include_current_position=False,
ignore_case=False, count=1) | Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance. | 2.745114 | 2.78927 | 0.984169 |
flags = re.IGNORECASE if ignore_case else 0
return [a.start() for a in re.finditer(re.escape(sub), self.text, flags)] | def find_all(self, sub, ignore_case=False) | Find all occurances of the substring. Return a list of absolute
positions in the document. | 2.49013 | 2.464592 | 1.010362 |
if in_current_line:
before_cursor = self.current_line_before_cursor[::-1]
else:
before_cursor = self.text_before_cursor[::-1]
flags = re.IGNORECASE if ignore_case else 0
iterator = re.finditer(re.escape(sub[::-1]), before_cursor, flags)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return - match.start(0) - len(sub)
except StopIteration:
pass | def find_backwards(self, sub, in_current_line=False, ignore_case=False, count=1) | Find `text` before the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance. | 2.679794 | 2.564982 | 1.044761 |
if self.text_before_cursor[-1:].isspace():
return ''
else:
return self.text_before_cursor[self.find_start_of_previous_word(WORD=WORD):] | def get_word_before_cursor(self, WORD=False) | Give the word before the cursor.
If we have whitespace before the cursor this returns an empty string. | 3.837114 | 3.53759 | 1.084669 |
# Reverse the text before the cursor, in order to do an efficient
# backwards search.
text_before_cursor = self.text_before_cursor[::-1]
regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
iterator = regex.finditer(text_before_cursor)
try:
for i, match in enumerate(iterator):
if i + 1 == count:
return - match.end(1)
except StopIteration:
pass | def find_start_of_previous_word(self, count=1, WORD=False) | Return an index relative to the cursor position pointing to the start
of the previous word. Return `None` if nothing was found. | 4.767371 | 4.321896 | 1.103074 |
text_before_cursor = self.current_line_before_cursor[::-1]
text_after_cursor = self.current_line_after_cursor
def get_regex(include_whitespace):
return {
(False, False): _FIND_CURRENT_WORD_RE,
(False, True): _FIND_CURRENT_WORD_INCLUDE_TRAILING_WHITESPACE_RE,
(True, False): _FIND_CURRENT_BIG_WORD_RE,
(True, True): _FIND_CURRENT_BIG_WORD_INCLUDE_TRAILING_WHITESPACE_RE,
}[(WORD, include_whitespace)]
match_before = get_regex(include_leading_whitespace).search(text_before_cursor)
match_after = get_regex(include_trailing_whitespace).search(text_after_cursor)
# When there is a match before and after, and we're not looking for
# WORDs, make sure that both the part before and after the cursor are
# either in the [a-zA-Z_] alphabet or not. Otherwise, drop the part
# before the cursor.
if not WORD and match_before and match_after:
c1 = self.text[self.cursor_position - 1]
c2 = self.text[self.cursor_position]
alphabet = string.ascii_letters + '0123456789_'
if (c1 in alphabet) != (c2 in alphabet):
match_before = None
return (
- match_before.end(1) if match_before else 0,
match_after.end(1) if match_after else 0
) | def find_boundaries_of_current_word(self, WORD=False, include_leading_whitespace=False,
include_trailing_whitespace=False) | Return the relative boundaries (startpos, endpos) of the current word under the
cursor. (This is at the current line, because line boundaries obviously
don't belong to any word.)
If not on a word, this returns (0,0) | 2.745028 | 2.73328 | 1.004298 |
start, end = self.find_boundaries_of_current_word(WORD=WORD)
return self.text[self.cursor_position + start: self.cursor_position + end] | def get_word_under_cursor(self, WORD=False) | Return the word, currently below the cursor.
This returns an empty string when the cursor is on a whitespace region. | 3.995656 | 3.525816 | 1.133257 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.