Sublime Text Tab Indentation Indenting Entire Paragraph? - sublimetext3

I've recently discovered Sublime Text and since I'm new to using text editors like this, I had a question about indentation. When I'm not using Sublime for code, I type up my writing with it before taking it to a word processor for further processing. I've been having a little bit of trouble with the indentation regarding paragraphs. When I tab a paragraph, it seems to tab the entire paragraph rather than just the first line. It looks like the first paragraph in this picture.
I've tried using the wrap paragraph function which seems to allow me to tab just the first line but when I paste it in Microsoft Word, it retains its wrap setting. Is there anyway that I can just indent just the first line without having to wrap it? Or am I approaching it all wrong?

For a global effect you can add this to Preferences > Settings-User:
"indent_subsequent_lines": false
Because I code too, I add it to Preferences > Settings-More > Syntax Specific-User.
To do this properly, open a .txt file (or your preferred file type) and it will open/create a settings file for the specific file type. Then paste in this and save:
{
"indent_subsequent_lines": false,
"tab_size": 4,
"translate_tabs_to_spaces": false
}

Sublime is a code editor, not a word processor. Although you may use it to type any kind of (plain) text, it's focused on editing code.
Sublime indents lines in a way that makes sense for a programming language. If you're looking for a tool to write anything like a report or a novel, maybe you should consider another tool.

Related

How to remove tabs on multiple rows at once

This is not a programming question but an inconvenience in the android-studio editor.
If you have an unwanted tab before all your lines, how can you remove them all at once? Now I have to manually go over 50 lines to remove all the tabs to make my code look clean.
If you want to add multiple tabs at once you just select all your code and press the tab button. So I'm looking for the reverse of that.
If I understood you right, you want to beautify the code itself. Fortunately, you don't have to do that manually - at all.
There's a keybinding for it, which may vary by your OS and which layout you use by default. Go to file -> settings -> Keymap and search for auto-indent. Here's what I get on Windows 10 with the default keymap:
Again, which you have may depend on OS (I'm assuming that mainly applies to Mac though) and your keymap, but you can automatically indent your code as per language standards using Ctrl+Alt+I.
Note that this mainly does indentation. If you chose to golf code and want to ungolf it, this will not work. At least it doesn't for Java.
However: This only works with code files the IDE or plugins support. This won't work for i.e. a .txt file out of the box.
If I misunderstood you and you only want to remove tabs without doing the auto-indent, there's at least two other options.
The first option is using multiple cursors. You can add an additional cursor with shift+alt+a mouse click where you want the cursor, or holding the mouse wheel and moving the cursor with the mouse wheel held down. There might be other methods as well, but those are the two I know of.
Once you have multiple cursors, delete the tabs just like normal. But be careful! Doing so might delete the entire line itself. If it does, you can do 1 tab/n units per indent level to the left, and press delete instead.
There's (AFAIK) no limit to how many cursors you can have at once, but you can theoretically do it with 50 lines at once if you want to. But general advice - don't add more cursors than you can see at once. These do run in parallel and it's easy to lose track if you're not careful, and you might end up deleting stuff you didn't want to delete.
And finally, the regex solution:
Note: Be careful with this. If you use it incorrectly, you might get unwanted results.
If you only want to do this in a limited area, highlight it first. Then CTRL+R and you'll be presented with the regular replace menu. Make sure Regex and In Selection are selected.
A base regex to go off is ^([\s]{2,4}|\t). Explanation just for reference:
^ - At the start of the line
(
\s{4} - Match 4 spaces
|\t - Or a tab character
)
Replace with nothing and click "replace all" (or just use the regular "replace" button if you want to double-check before you do anything). This will replace one occurrence of 4 spaces or a single tab character. If you use indentation that isn't based on 4, change the number.
This is only useable and useful if you've found yourself with incorrect indentation that's the same across all the relevant lines - it will not fix indentation mistakes and/or inconsistencies such as 3-space indentation when you want 4, or random indetation for the same block. Use the first or alternatively second method for that instead.

How to format "one line html" as a pretty document in sublime? [duplicate]

This question already has answers here:
How do I reformat HTML code using Sublime Text 2?
(16 answers)
Closed 9 years ago.
I have a html source file containing only one line like the following:
<html><head>test</head><body>wow</body></html>
, and I want to format it as following:
<html>
<head>
test
</head>
<body>
wow
</body>
</html>
, I have used the command: Edit-> Line-> Reindent but it doesn't work.
In Sublime Text try this:
Highlight the last character in the first tag: ">"
Use Find > Quick Add Next (Command+D on Mac or Ctrl+D on PC)
You'll now have all occurrences highlighted in multiple selections, move the caret to the end of the tag and hit return to insert all the new lines you require.
Good luck
I was under the impression that Sublime provided this ability as well. When I found out that it wasn't, I had the idea of using regular expressions. Even though regex are usually considered inappropriate for parsing XML/HTML, I found this approach to be acceptable in this case. Sublime is also said to be highly customizable by plugins, so I think this would be a way.
Sublime Plugins
To be honest, I could have thought of tidy or at least suspect that there must be plugins out there dealing with your issue. Instead I ended up writing my first sublime plugin. I have only tested it with your input and expected output, which it satisfied, but it is most certainly far from working reliably. However, I post it here to share what I've learned and it's still an answer to the problem.
Opening a new buffer (Ctrl+n) and choosing the 'New Plugin...' entry in the Menu 'Tools' generously generates a little 'Hello World!' example plugin (as a Python module), which gives a great template for implementing a sublime_plugin.TextCommand subclass. A TextCommand provides access to an active buffer/currently open file. Like its relatives WindowCommand and ApplicationCommand, it is required to overwrite a run-method.
The official API Reference suggests learning by reading the example sources distributed with the Sublime builds and located in Packages/Default relative to the Sublime config path. Further examples can be found on the website. There's more on the internet.
Processing selected text
To get to a solution for your issue, we primarily need access to a View object which represents an active text buffer. Fortunately, the TextCommand subclass we are about to implement has one, and we can conveniently ask it for the currently selected regions and their selection contents, process selected text conforming our needs and replace the selected text with our preference afterwards.
To sum up the string operations: There are four regular expressions, each of which matches one of the element classes <start-tag>, <empty-tag/>, </close-tag> and text-node. Assuming that all of our markup text is covered by these, we did each line in selection into matching substrings. These are then realigned one-per-line. Having done this, we apply simple indentation by remembering to indent every line whose predecessor contains a start tag. Lines containing end tags are unindented immediately.
Using the group addressing features of Python regex, we can determine the indentation of every line and align the next one accordingly. This, with no further ado, will result in internally consistent indented markup, but with no consideration of the lines outside the selection. By extending the selection to an enclosing element, or at least complying with the indentation levels of the adjacent lines, one could easily improve the results. Its always possible to make use of the default commands.
Another thing to take care of is binding keys to the plugin command and contributing menu entries. It is probably possible somehow, and the default .sublime-menuand .sublime-commands files in Packages/Default at least give an idea. Anyway, here's some code. It has to be saved under Packages/User/whatever.py and can be called from the Sublime Python Console (Ctrl+`) like this: view.run_command('guess_indentation').
Code
import sublime
import sublime_plugin
import re
class GuessIndentationCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
#view.begin_edit()
# patterns
start_tag = '<\w+(?:\s+[^>\/]+)*\s*>' # tag_start
node_patterns = [start_tag,
start_tag[:-1]+'\/\s*>', # tag_empty
'<\/\s?\w+\s?>', # tag_close
'[^>\s][^<>]*[^<\s]'] # text_node
patterns = '(?:{0})'.format('|'.join(node_patterns))
indentors = re.compile('[ \t]*({0})'.format('|'.join(node_patterns[:1])))
unindentors=re.compile('[ \t]*({0})'.format(node_patterns[2]))
# process selected text
for region in view.sel():
# if selection contains text:
if not region.empty():
selection = view.substr(region)
expanded = []
# divide selected lines into XML elements, if it contains more than one
for line in selection.split('\n'):
elements = re.findall(patterns, line)
if len(elements)>0:
expanded += elements
else:
expanded.append(line)
# indent output
indent=0
indented = []
for line in expanded:
match = unindentors.match(line)
if match:
indent = max(0, indent-1)
# append line to output, unindented if closing tag
indented.append('\t'*indent+line)
if match:
continue
# test for possible indentation candidate
# indentation applies to the NEXT line
match = indentors.match(line)
if match:
indent+=1
# replace selection with aligned output
view.replace(edit, region, '\n'.join(indented))
if its for something simple, i was able to record a macro (tools -> record macro) indenting the tags and then save it and reuse this macro. not sure if that helps any though.

Paste within line in macvim

I started to use macvim not only for code, but also for editing a wiki and academic writing in LaTeX. After several honeymoon moments ;-) and first customization efforts, I found a problem I can't solve:
How do I paste content from the system clipboard within a line, no matter where this content is copied from? (I use LaunchBar’s multi clipboard feature quite excessively and store mostly > 20 strings from different applications I will paste sooner or later. It works well with macvim, but not when it comes to "linewise" content.) p or P create newlines, cmd-v as well.
I neither want to add strings between tags, nor focus on other specialised settings.
I don't know how Launchbar works in this regard but all the clipboard managers I've used send a Cmd-v when you hit Enter.
MacVim, being very well integrated in the system, supports many default Mac OS X shortcuts like Cmd-o, Cmd-s or Cmd-v so… simply selecting the item in Launchbar's list and hitting Enter should work.
If your pasted content ends up on a line of its own (presumably above the current line) instead of in the middle of your sentence that means that the pasted text contains a new line, plain and simple. Because MacVim maps Cmd-v to P, the pasted content is pasted before the cursor: inline if there's no newline in sight, above the current line if there are newlines.
That's normal behavior.
At that point, either you find a way to clean Launchbar's content up before Cmd-v or you edit the pasted text afterward with something like ^v$y"_d<movement>P.
p and P only create new lines if the clipboard contains a newline character.
I just pasted one-line content from my clipboard into vim and it worked fine (in-line).
The issue may be with the way LaunchBar is copying to its clipboards.

In Vim, how to keep characters concealed even when cursor enters that line

I may have a unique situation here. I want gVim (gui version, in Linux) to keep concealed characters concealed no matter what, even when the cursor is on that line or that character gets selected. (It should be as close to if the characters never existed as possible.) Currently the concealed characters show themselves when the cursor enters that line, which causes text to jump around when scrolling and when selecting text.
We are using gView (read-only gVim) to view logs, so as to take advantage of its robust syntax highlighting. Problem is, these logs contain lots of escape characters and TTY color codes, that make reading difficult. (^[33mSomeText^[0m)
I'm using this line to hide them:
syntax match Ignore /\%o33\[[0-9]\{0,5}m/ conceal
Since the files are viewed by non-vim-experts, it looks glitchy and broken when the text un-conceals itself. (And also looks glitchy and broken if the color codes are present, and also looks glitchy and broken if the color codes are blacked-out to become invisible, but still show when selected and appear after copy/paste.)
This should be fine because these files are opened read-only in gview, with an extra set nomodifiable making it even more difficult to save the file. While it's possible to edit and attempt to save the logs, doing so is considered both an invalid thing to do, and a harmless thing to do, and requires enough Vim skills that if someone manages to edit a file they know what they're doing. The problem with being able to edit a line with concealed text does not apply.
If 'conceal' can't be configured to keep hidden text hidden no matter what, an acceptable alternative would be to replace the TTY color codes with whitespace when the file gets opened. But, this has to be done in read-only mode, and we can't have gview throwing up a save dialog on closing the window because the file has been modified by its .vimrc.
Note: I am in full control of the .vim script file sourced when these are read, but cannot control the existence of the TTY color codes or the code that opens the log files in gview. (i.e. I can't pass it through sed or anything like that.) The ideal solution is anything that can transparently nuke the color codes from within a .vimrc, but I'll hear any suggestions. The 'conceal' feature is just my most promising lead.
So, any ideas how to permanently get rid of these on file view without dialogs popping up on close?
:help conceal
When the "conceal" argument is given, the item is marked as concealable.
Whether or not it is actually concealed depends on the value of the
'conceallevel' option. The 'concealcursor' option is used to decide whether
concealable items in the current line are displayed unconcealed to be able to
edit the line.
:help concealcursor
Sets the modes in which text in the cursor line can also be concealed.
When the current mode is listed then concealing happens just like in
other lines.
n Normal mode
v Visual mode
i Insert mode
c Command line editing, for 'incsearch'
'v' applies to all lines in the Visual area, not only the cursor.
A useful value is "nc". This is used in help files. So long as you
are moving around text is concealed, but when starting to insert text
or selecting a Visual area the concealed text is displayed, so that
you can see what you are doing.
Keep in mind that the cursor position is not always where it's
displayed. E.g., when moving vertically it may change column.
Also, :help conceallevel
Determine how text with the "conceal" syntax attribute |:syn-conceal|
is shown:
Value Effect ~
0 Text is shown normally
1 Each block of concealed text is replaced with one
character. If the syntax item does not have a custom
replacement character defined (see |:syn-cchar|) the
character defined in 'listchars' is used (default is a
space).
It is highlighted with the "Conceal" highlight group.
2 Concealed text is completely hidden unless it has a
custom replacement character defined (see
|:syn-cchar|).
3 Concealed text is completely hidden.
Only one command is needed: set concealcursor=n
I might have a better idea—you can pass it through sed (using %!sed) or really do a bunch of other :substitute commands—whatever edits you need to get rid of the color codes.
When you’re done, make sure to set nomodified—this forces vim to think there haven’t been any changes!

VIM: Respect only current code block

I have started working on a huge PHP application that has thousands of lines of code in each file, with lots of huge if blocks, classes, and functions all existing in the same file. I'm not the only dev working on it, so I cannot refactor!
I have tried using the Tags List plugin but it does not really help. Is there any way to have VIM respect only a particular code block, and ignore the rest of the file? I am hoping for some or all of these features:
Enable line numbering only for the current code block, starting from 1 at the line containing the opening {, and showing no numbering for lines preceding it or after the closing }.
Searching with / would be restricted only to the block in question.
I am thinking along the lines of selecting the current block and editing it in a new buffer when enabling the mode, then replacing the existing block with the edited block when exiting the mode. However, I am having trouble actually implementing this feature. My current version is this:
map <F7> <Esc>mO<C-V>aBy:new<Return>p:set nu<Return>:set ft=php<Return>ggi<?php<Return><Esc>
map <F8> <Esc>ggdd<C-V>aBx:bp<Return>`O<C-V>aBp
However, this has several issues, such as the inability to perform incremental saves.
I would be very surprised if Vim allows the kind of line numbering you ask for.
This plugin (and 1 or 2 similar ones IIRC) allows you to visually select a region of your current file, work on it in another buffer and put everything back in its place in the original file on :w.
Even if it's not the solution you are wanting, I think the following can help you to solve your problem.
You can use phpfolding plugin, which folds by PHP syntax (functions, classes, methods, PhpDoc...)
You can then select a fold by pressing v$ over the closed fold and execute whatever you want with :whatever. For example, :s/this/self/g to substitute all this for self in the fold. When you press :, vim will automatically add '<,'> to denote following command it's only for the visually selected text.

Resources