Git Product home page Git Product logo

braceless.vim's Introduction

Braceless Build Status

Text objects, folding, and more for Python and other indented languages. CoffeeScript support is already baked in, but mainly as an incomplete proof of concept.

Usage

Use your favorite plugin plugin of choice to install tweekmonster/braceless.vim, then add a line like this to your vimrc file:

autocmd FileType python BracelessEnable +indent

The command arguments are:

Option Description
+indent Enable indent handling
+fold Enable folding
+fold-slow Enable indentexpr folding, which is depreciated and slow
+highlight Enable indent guide
+highlight-cc Enable indent guide, but use colorcolumn
+highlight-cc2 Enable indent guide and use colorcolumn

The default motion of interest is P. It can be used for things like vaP, ciP, >iP, etc. :h braceless Covers the details of this plugin.

Text objects

Braceless doesn't give you similarly indented blocks as text objects. You get actual code blocks using iP and aP.

braceless-motions

Object motions

Moving to recognized blocks is done with [[ and ]]. In Python, [m and ]m moves to def and class blocks, while [M and ]M moves to the end of those blocks.

braceless-movement

Folding

Get useful code folding by adding +fold. Unfortunately, this can be a little slow on large scripts. Folding is now much faster! Read the boring exciting details in :h braceless-folds!

braceless-fold

Indent guide

See what indent level you're operating on with +highlight. You can also enable colorcolumn so the guide can span the height of the window. If you would like this kind of indent highlighting in other files that don't need Braceless, take a look at local-indent.vim

braceless-highlight

Somewhat intelligent auto-indent

Ever wished for autoindent that didn't make you fix the indent? Wish no more, pal. Just add +indent. It's not perfect, but it's definitely better. There is even PEP 8 indentation built in, and if you use delimitMate with the expand_cr option enabled, Braceless will disable it temporarily when you're messing with block arguments.

braceless-autoindent

(The backspace key was never used in the image above)

EasyMotion

Built-in support for EasyMotion.

braceless-easymotion

Not just Python!

Braceless can simply recognize indentation.

braceless-others

The above GIF was using:

autocmd FileType haml,yaml,coffee BracelessEnable +indent +fold +highlight

You can extend Braceless to give full support to other indented languages. See :h braceless-custom

License

MIT

braceless.vim's People

Contributors

sgur avatar tweekmonster avatar zhuangya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

braceless.vim's Issues

Block indent calculated incorrectly for complex block

I think this was introduced in one of the very recent changes (I can verify this in the morning):

screenshot

    @property
    def request_sources_access_names(self):
        # pylint: disable=not-an-iterable
        return [app_label_to_verbose_name(label)
                for label in self.request_sources_access]

    request_message_permission = models.BooleanField(
        choices=BOOL_CHOICES,
        help_text=('Permission to send messages to the member. This does not '
                   'grant access to their email address.'),
        verbose_name='Are you requesting permission to message users?')

    request_username_access = models.BooleanField(
        choices=BOOL_CHOICES,
        help_text=("Access to the member's username. This implicitly enables "
                   'access to anything the user is publicly sharing on Open '
                   'Humans. Note that this is potentially sensitive and/or '
                   'identifying.'),
        verbose_name='Are you requesting Open Humans usernames?')

    coordinator = models.ForeignKey(Member, on_delete=models.PROTECT)
    approved = models.BooleanField(default=False)
    created = models.DateTimeField(auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True)

    api_access_secret = models.CharField(max_length=64)

    def __unicode__(self):
        return '{}: {}, {}'.format(self.name, self.coordinator.name,
                                   self.leader)

Once selected a text object, expand the selection?

Let's say I have a code block like this:

1.    def decr(d, a):
2.       r = {}
3.        for key, value in d.items():
4.           if key == a:
5.               value -= 1 #### my cursor is here
6.          r[key] = value
7.        return r

…and my cursor is on value -= 1 line. Once I press vaP, I get the if structure selected. But is it possible then to expand the selection somehow? Or, is it possible to pass some numeric argument before the selecting may be?

Disable PEP8 style indenting?

Is there a way of disabling the PEP8-style of indenting arguments when they are split across multiple lines?

In case I'm not completely clear: the indentation style whereby the callable arguments are aligned under the opening parenthesis when the arguments are split across multiple lines like so:

x =  my_function(one, two, three,
                 four, five)

is what I'd like to avoid, due to our internal company coding style guidelines. I attempted to locate a setting of sorts within the vimscript of Braceless, but came up short.

Thanks for the great plugin!

Mapping/command to move to beginning/end of blocks, parent blocks?

Is there such? If not, would it be possible to request it?

Nice movements would be:

  • end of current block
  • beginning of current block
  • beginning of parent block
  • beginning of next block at higher level

E.g.,
Given:

1:  class A(object):
.
.       
2:      def func1():
.           [main func1 body]
.
3:          if x:
4:              [stuff]
.
.
5:          else:
.               [stuff]             
.
6:          [more main func1 body]
.
.
7:      def func2()
.
.

(1) If the cursor is between line 4 (inclusive) and 5 (exclusive), then would move to the line just before [5].

(2) If the cursor is between line 4 (inclusive) and 5 (exclusive), then would move to [4]

(3) If the cursor is between line 4 (inclusive) and 5 (exclusive), then would move to [3]

(4) If the cursor is between line 4 (inclusive) and 5 (exclusive), then would move to [7]

<CR> not working

Whenever I press <CR>, braceless#python#override_cr() gets pasted into my code over and over and over again until I press <C-c>. This is a bit unusable...

The first time this happened there was an error clipboard: error: Error: target STRING not available.

I am using neovim.

braceless make "o" in normal node very slow

Hello. I noticed that in my set up pressing o in normal mode (filetype python) adds a significant delay. I'm not sure how to provide a minimal example, I'm rather open to your instructions on how to narrow the scope, though I barely speak vimscript.

I'm using only autocmd FileType python BracelessEnable +indent, neovim 0.1.7, latest version of braceless.
Thanks.

Add note re: `filetype indent off`?

I had to add filetype indent off to my Python-specific .vimrc file to get the braceless.vim indentation to work; maybe that should be added to the docs?

Continuation slash added inside parenthesis block

When editing python, it seems like backslashes are being added sometimes for code that already exists within parentheses. I've tried tracking down the exact scenario that triggers the issue but was mostly unsuccessful. I know that I've seen it occur when trying to break up long lines of code or attempting to return a tuple from a function.

For example, if I start with the following:

from foo import x, y, z

Then try to move each import unto a separate line, I end up with:

from foo import (x, \
                 y, \
                 z)

Is this the expected behavior?

Multiline string that's parsed incorrectly

I have this multiline string in a file:

post_sharing_url_help_text = """If provided, after authorizing sharing the
member will be taken to this URL. If this URL includes "OH_PROJECT_MEMBER_CODE"
within it, we will replace that with the member's project-specific
project_member_code. This allows you to direct them to an external survey you
operate (e.g. using Google Forms) where a pre-filled project_member_code
field allows you to connect those responses to corresponding data in Open
Humans."""

Braceless thinks that a block starts mid-string:

screenshot

And selecting the whole string and executing gq results in this:

screenshot

zf is unconditionally mapped to a notification

Hi there,

I have a mapping for zf that doesn't change the fold state.
braceless#fold#enable_fast() unconditionally sets zf to call no_manual_msg().

Could you add a conditional to that action please?

If you could figure out a way to check the maparg() of that key sequence I guess automatically would be best, but that seems like it would be flaky, and I'd be happy with a global variable like g:braceless_nomap_zf or the like.

Thanks.

Bad fold interaction with sessions

Hi, thanks for the plugin!

I use vim-session, and unfortunately Braceless's folding seems to result in some undesirable interaction with it. vim-session persists manual folds in its session files, so I'm guessing that's the crux of the problem. Actually, standard :mksession does too, so similar problems might crop up with usage of the native session support.

Basically, the annoying behavior is this:

  1. Open a session for the first time with BracelessEnable +fold in effect.
  2. Invoke closing a fold (I think this is necessary once, to trigger computation of the manual folds).
  3. Save and close the session, with no folds closed in the file.
  4. Open it again. All the folds are closed. Or at least most of them, maybe the scope of the one block that had been folded, I can't quite tell exactly.

So now I have to manually zR everything every time I re-open a session. I have set foldlevelstart=99 as a default in my config, but I'm assuming that Braceless's fold approach doesn't or can't support that. Or maybe the manual folds saved in the session subvert it upon restore.

If I disable Braceless, re-open the session, zE on the buffers, save session and re-open it, all is well again. Until Braceless is enabled again… I could try to bufdo zE when closing sessions with an autocommand or something, but Braceless won't allow that.

Any ideas about how this situation could be improved?

No auto-indent for coroutines

Indent level never seems to be correct inside the body of py35+ coroutines:

async def my_coro():||<ENTER>
||

This hold true for any line inside the function body.

Feature Request: Highlight Toggle

It seems like it'd be useful to have one map to toggle +highlight. I find myself only wanting it when viewing particularly hairy areas - otherwise it's too noisy for my taste.

I'm not well versed in vimscript to pull this off myself. Perhaps I'm overlooking an easy way to make it happen?

GVim window view moving on `o` or `O` with option +indent

For some reason, setting autocmd FileType python BracelessEnable +indent makes gvim's view move up as far as possible to encompass the current function definition on pressing o or O. It happens when the window is too small to contain both the cursor and the definition, and so moves the view so that the cursor is at the bottom of the screen, and it happens when the window is expanded, showing as much as possible up to and including the definition.

This doesn't happen if I only set +highlight, and it doesn't happen if I comment out the entire autocmd.

Thanks!

Non greedy folding ?

Is it possible to use braceless with a folding that would operate only on def, class and markers {{{ }}} instead of all indentations ?

Found a pathological case for indenting

class NewRx(ScriptMessageToSurescripts):
    """
    The NewRx messages to be transmitted have been developed using the NCPDP SCRIPT standard. A
    Status, Error, or Verify response is always sent after a NewRx message.
    """

    def surescripts_medication(self, med_id, quantity_value, directions, days_supply,
                               written_date, refills, substitutions_allowed):
        # 38 = Original Qty
        # QS = Quantity Sufficient (The service level for the pharmacy must be enabled for LTC for
        #      all QS orders.
        #
        # For NewRx:
        # - If Value = "0" (zero), then DRU- 020-03 value must be "QS" and the receiver must be
        #   setup as LTC.
        # - If Value is greater than "0" (zero), then CodeListQualifier value must be "38".
        quantity.CodeListQualifier = '38'

        # Where possible, quantities should reflect the actual metric quantity to be dispensed.
        # Example: Use "Amoxicillin 250mg/5ml, 150 ml" instead of "Amoxicillin 250mg/5ml, 1
        # bottle".  The use of "C38046-Unspecified" should be limited to instances in which none of
        # the available qualifiers in the Units of Measure table can be applied. Examples of
        # improper use: Drug description— Amoxicillin 500 mg Oral Capsule, Quantity 30 and Potency
        # Unit Code sent "C38046-Unspecified, "instead of "C48480 - Capsule Dosage Form".
        #
        # For a list of FMT codes, go to: http://evs.nci.nih.gov/ftp1/NCPDP/About.html. This list
        # should be updated on a monthly basis. Use the NCPDP QuantityUnitOfMeasure Terminology
        # rows from the downloaded data.
        #
        # Example rows:
        #
        # C48473  Ampule   Ampule Dosing Unit   A dosing unit equal to the amount of active ingredient(s) contained in an ampule.
        # C48474  Bag      Bag Dosing Unit      A dosing unit equal to the amount of active ingredient(s) contained in a bag.
        # C48477  Bottle   Bottle Dosing Unit   A dosing unit equal to the amount of active ingredient(s) contained in a bottle.
        # C48478  Box      Box Dosing Unit      A dosing unit equal to the amount of active ingredient(s) contained in a box.
        # C48480  Capsule  Capsule Dosing Unit  A dosing unit equal to the amount of active ingredient(s) contained in a capsule.
        quantity.PotencyUnitCode = ''

For some reason every line including and after the comment line containing "C48478" will be indented to column 37 (can you test this by saving the code above to a file, then executing ggVG= ).

All sorts of problems with `o` command

Somewhat pertains to #50.

  • after a method (async) def func(<o> -> jumps one to many indents in
  • after any return value type annotation: ) -> Type:<o> -> should be one more indentation level in

g] doesn't work?

The binding of g] to :tselect doesn't seem to work after installing this plugin?

Is this expected?
I'd love to have both since I use tags quite often.

Statement continuation slash inserted when a row of text in a docstring ends in 'and'.

When editing an existing docstring of a function, having a line end in an and word causes the / line continuation operator to be inserted when adding a carriage return at the end of said line, most likely because Braceless believes itself to be within a conditional statement:

    def do_something():
        """
        Attempt to do something.

        When I get to the end of the line then hit enter to continue to the next line and \
            a slash character for statement continuations is inserted.
        """

Is it possible to tune dedenting by Enter key?

Hi!

braceless works great but I want to tune it a bit for my own need. Is it possible to dedent if I press Enter 2 times, not 1?

An example: usually I write functions like this, with blocks, separated by 1 empty lines:

def unique(elements):
    already_met = set()
    items = []

    for element in elements:
        if element not in already_met:
            items.append(element)
            already_met.add(element)

    return items

If I type items = [] then it is not possible to press Enter 2 times to input for elements in elements, because, well, after first keypress I dedent. But as a workaround, if I enter return at the start, it works as expected.

Do I need to set anything in my vimrc to support such behavior? Or how can I tune braceless to work as I want?

Thanks!

Incorrect auto-indenting after decorator line?

Whenever I write out a decorator line and then hit enter braceless seems to increase the indent level:

@mydecorator<ENTER>
    def myfunc(...

This seems wrong; there should be not indent added - maybe I'm also wrong in guessing this is braceless's doing?
It seems to go away when I disable the plugin though...

ViP behavior is strange

While viP do what is expected, when using ViP (which I happen to do a lot because the text-objects are linewise objects and my mind uses V in that case) the line selected are the one from the next indent level. This is a really strange behaviour that I think is worth some documentation (or maybe even a workaround).

Somewhat intelligent auto-indent - is it possible to turn it off?

Auto indent is based on recognized blocks instead of simply using the previous line's indent level. If you enter two blank lines, you'll drop back a level.

Don't know, if it's just me, but right now if you press an Enter on a zero-indented line, you got an indent on the next one. As I understand from the description, that seems to be a feat. Then, is it possible to turn it off?

Incorrectly adds \ at end of line

I currently use these options for braceless:

let g:braceless_block_key = 'i'
augroup MyBraceless
  autocmd!
  autocmd User BracelessInit nunmap J
  autocmd User BracelessInit iunmap <cr>
  autocmd FileType python BracelessEnable +indent
augroup END

Given this python code:

if (test == 0

Inserting <cr>and at end of line now gives:

if (test == 0 \
        and

instead of what I would expect:

if (test == 0
    and

I'm curious if this is by design or if I am doing something wrong, or if this is a bug.

Removal of whitepsace surround operators on 'J'oin lines

Back again with another odd interaction! Test code:

test = [x + 1 for x in range(
    2 * 2)]

Move the cursor to the first line and press J to join the line below. On my machine, it removes all whitespace surrounding the + and * operators:

test = [x+1 for x in range(2*2)]

This also happens with - and /. If I disable the plugin, this behavior disappears. Just to be sure, I left braceless.vim enabled and tried disabling every other plugin I have install one at a time, and braceless.vim is the only one that seems to interact with this.

Thanks!

Folding functions inconsistent depending on indent

with this sample code, folding myfunction leaves the two blank lines above the def in line 7, while folding myotherfunction also folds the blank lines above the if statement.

Is there any way to always leave the blanks or always fold blank lines ?

def myfunction():
    print("going")
    for i in range(10):
        print("loop {}".format(i))


def myotherfunction():
    print("going")
    for i in range(10):
        print("loop {}".format(i))
    return 


if __name__ == '__main__':
    myfunction()
    myotherfunction()

BracelessEnable in ftplugin works but raises error while opening files

I'm setting BracelessEnable +indent +fold from ftplugin/python.vim.

Error detected while processing path_to_file/nvim/ftplugin/python.vim:
line #num
E492: Not an editor command: BracelessEnable +indent +fold

While it does not affect performance, it's rather annoying. Is this expected behaviour?

Minimal init.vim

if &compatible
  set nocompatible
endif
filetype plugin indent on
syntax enable

call plug#begin('~/.local/share/nvim/plugged')
Plug 'tweekmonster/braceless.vim', {'for': 'python'}
call plug#end()

Braceless settings in python.vim

let g:braceless_generate_scripts = 1
let g:braceless_enable_easymotion = 0
let g:braceless_block_key = 'p'
let g:braceless_enable_jump_indent = 0
let g:braceless_segment_prev_key = ''
let g:braceless_segment_next_key = ''
let g:braceless_format = {}
BracelessEnable +indent +fold
setlocal fillchars=fold:\ 

NVIM v0.3.1

Custum popup handling for <cr> mapping

Hi @tweekmonster, thanks for the great plugin.

I was wondering if you could supply a method to handling popup menu in <cr> mapping.
Something like the following code at the beginning of function braceless#python#override_cr(...).

if pumvisible() && get(g:, 'braceless_pum_handling', "") != ""
    let Fn = function(g:braceless_pum_handling)
    return Fn()
  endif

So we could use let g:braceless_pum_handling = "g:Custom_Fn" to make things work.

Or could you adding a variable to not mapping the override_cr, like following in function! braceless#python#init()

  if get(g:, 'braceless_python_override_cr', 0)
    silent! inoremap <expr><unique><silent><buffer> <cr> braceless#python#override_cr()
  endif

So we could use custom <cr> mapping like inoremap <silent> <expr><buffer><cr> pumvisible()? g:Custom_Fn() : braceless#python#override_ce() without losing any benefit from braceless.

Thanks for the great plugin again.

Losing backslash and double quotes when joining two lines together

Example joining (J) two lines together:

["Foo \"bar\"", 
"foobar"]

Result:

["Foo \"bar , "foobar"]

If I set in my vimrc this:

let g:braceless_format = {
	\ 'clean_collections': 0,
	\ 'clean_commas': 0,
	\ 'clean_slices': 0,
	\ 'clean_dot': 0,
	\ 'join_string': 0,
	\ 'clean_whitespace': 0,
	\ 'clean_string': 0
\ }

then the result is this:

["Foo \"bar ", "foobar"]

Still missing backslash... :-(

`:` key dedents incorrectly

In a blank file, if I type this:

def foo(bar,
        baz,
        buzz)

and then hit the : key, I end up with this:

def foo(bar,
        baz,
    buzz):

(it dedents the last line incorrectly)

Indent mode gets confused by brackets in docstrings.

Consider the following function:

def print_bracket():
    """
    Prints a bracket.

    Here's an example:

        >>> print_bracket()
        (

    """
    print "("

Everywhere after the unmatched bracket in the docstring, Braceless' indent mode gets confused about what the new indent level should be. If you delete that line, it's fine. Notet hat Braceless is not confused by the unmatch bracket in the print statement, just the one in the docstring.

Jumping between classes?

In the docs you write:

In Python, ]m, ]M, [m, and [M are available to move to def or               
class blocks.  They are analogous to what's described in various-motions,   
except the part about braces.

I understood this as [M/]M would move the same as [[/]] normally do without the plugin installed?

Maybe i'm misunderstanding but how does one jump between top level definitions?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.