Sublime Forum

How to insert newlines while keeping indentation

#1

Hi,

I want to insert a string including newline characters. When i called insert method it puts the string but newlines are put at the beginning of the new line. Is there a way to insert new lines while keeping indent level.

Example:

<Line this
is simple 
insert

<Line this
  is
  expected

Thanks.

0 Likes

#2

You could insert one line at a time, or determine the current indent level and replace newlines in your string-to-insert with the newline followed by the correct indentation level

0 Likes

#3

Paste a code block with a working sample of your code.

1 Like

#4

yes, it would be helpful to see your code to be able to properly make suggestions :slight_smile:

0 Likes

#5

Sorry for the late response.
I want to insert JSX proptypes for React and i want to do it according to this convention:

<Button onClick={}
  kind={}
  foo={}

For the example above i am trying to insert lines with this code: (i am running command when cursor is at the end of “Button” keyword)

selections = self.view.sel()
cursor = selections[0];
self.view.insert(edit, cursor.begin(), "onClick={}\nkind={}\nfoo={}\n")

What is the correct way to insert newlines while keeping indentation level. I think it can be done since “doc” plugins can insert comment lines on the correct level, while writing this i realized i can look at the source of my jsdoc plugin :slightly_smiling: still any quick suggestion would be great

Thanks!

0 Likes

#6

Instead of view.insert, you can try paste_and_indent

From Docs/Commands:

paste_and_indent
Inserts the clipboard contents after the caret and indents contextually.

Also, try:
"onClick={}\n\tkind={}\n\tfoo={}\n"
( your version did not include \t for the tab character of the 2nd & 3rd lines )
 



 
If that doesn’t work for you, you could also dynamically calculate the indentation level.
 

Check out:
#Indentation.py

 

It’s part of a dependency I’m working on.   It’s not ready for release yet, but the Indentation module is fully functional.

You can use get_Level to find the current line’s indentation level, and then get_IndentationString to return a string of the files proper indentation characters for your desired indentation level.

1 Like