How can I add /* at the beginning and */ at the end of a line in Vim? - linux

I want to do something like commenting a line like follows,
/*commented line*/
How can I do it? Is there any short cut command to achieve this task?

There's no built-in command (even though Vim has a 'commentstring' option to define the syntax). Toggling comments is a solved problem; don't try to invent your (poor) alternative. The most popular plugins (that I know) are:
The NERD Commenter
EnhCommentify.vim - comment lines in a program
tComment - An extensible & universal comment plugin
commentary.vim : Comment stuff out; takes a motion as a target

You can use :s/^\(.*\)$/\/*\1*\//.
If you want to create a macro, then something like qa^i/*<ESC>A*/<ESC>q associates to the name a the commands that comments the current line. If you want to use the macro you can type #a.

Related

some simple vim commands

sorry if this isn't exactly a programming question.
I mainly use Vim to edit my programs. So my question to all the Vim experts out there is:
is there a way to select and scroll in Vim? I want to copy a bunch of code, and in the pass I have always copied everything I can view on the vim screen then paste it to where-ever, then scroll down then copy and paste..repeat..until done. Is there a way I can efficiently copy a large block of code?
Formatting lines of code- you know when you copy and paste some code sometime 10 lines of code turn into 30 really messy lines of code? well, is there a command to reformat the code? In the pass I manually go back and properly indent everything which sometime is super repetitive when you got 500 lines. I saw on other sites something about the command being 1G = G can someone confirm that? when I try it in my command line, I get a error E464: ambiguous use of user-command line which I have no idea what that even means.
I do know there is a help command in Vim,but I have no idea where to even start when there is something like 200 txt files and frankly this is faster :)
Your questions are around basic use of vi / Vim. Do yourself a favor and go through a Vim tutorial; you'll find many on the web, and Vim comes with it's own introduction, vimtutor.
On Unix, if Vim has been properly installed, you can start it from the shell:
vimtutor
On MS-Windows you can find it in the Program/Vim menu. Or execute
vimtutor.bat in the $VIMRUNTIME directory.
Also, learn how to look up commands and navigate the built-in :help; it is comprehensive and offers many tips. You won't learn Vim as fast as other editors, but if you commit to continuous learning, it'll prove a very powerful and efficient editor.
The vim way is to entirely forget selection using the mouse for more than a screenful, but to set a mark, move to the other end of the desired text, then yank to mark:
Set mark m at beginning of text with mm
Move to end of text
Yank to mark with y'm
Paste with P or p
This whole answer is only helpful if you can use register + as clipboard. Try "+yy in VIM, try to paste it in another application to see if you can use the clipboard, if you can:
You should really read the manuals and other help:
To yank lines (simple) : http://vim.wikia.com/wiki/Moving_lines_up_or_down
To address lines: Addressing in VIM
That is to start with.
Some examples of what you can do:
:.,+50y a yank 50 lines from current and 50 ahead to register a, use A instead to append to register A.
:.,/some pattern/y A yank (append) from current to first line that match /some pattern/ to register a.
"Ay/some pattern<CR> will do the same thing.
Once you learn how you should address, it's easy to combine commands with addressing, e.g. the "indenting command" =:
=} auto indent to the end of current paragraph
=/some pattern<CR> auto indent to line matching /some pattern/
Mark something in Visual mode and type = it will auto indent the selected text.
And so on... So read manuals, you will have a great use of it.
In the above examples you can use register + to "yank" to the clipboard instead of register a.

Is there a "verbatim" mode for the vim map command?

I am trying to set up some useful coding templates in vim, for example I have mapped
map `cl iclass <+CLASSNAME+><CR>{<CR><Esc>Iprotected:<CR><+PROTECTED MEMBERS+><CR><Esc>Ipublic:<CR><+PUBLIC INTERFACE+><CR>};<CR><++><CR><Esc>3kv<0v3k<2k
so that when I type `cl in vim I get
class <+CLASSNAME+>
{
protected:
<+PROTECTED MEMBERS+>
public:
<+PUBLIC INTERFACE+>
};
<++>
(so that I can jump between the <+ +> tags with C-j). This works fine, but I find the above remap pretty obscure. Is there a way to enter what I want vim to type in "verbatim mode"? So I would want to write something like
map `cl i{VERBATIMSTART}class <+CLASSNAME+>
{
protected:
<+PROTECTED MEMBERS+>
public:
<+PUBLIC INTERFACE+>
};
<++>{VERBATIMEND}
?
Thank you
Paul
I don't know if there is such a "verbatim"-mode for mappings.
I, personally, would use one of the snippet-plugins to do this.
See www.vim.org and search
for "snippet". I have not tried all of them (just SnippetsMgr ;-) ),
but I suppose that they are handier to define multi-line-snippets.
Some of the available snippet-plugins on vim.org: snippets.vim ,
snippetsEmu, snipMate, SnippetsMgr, etc.
As Habi has mentioned, one way to go about this is with a snippet plugin.
Another way is to copy that snippet of code into its own file and set up your mapping to insert that file below the cursor:
map `cl :r /path/to/code_snippet<CR>
Kind of obvious (and probably not what you want) is:
map `cl iclass <+CLASSNAME+>
\<CR>{
\<CR>protected:
\<CR> <+PROTECTED MEMBERS+>
\<CR>public:
\<CR> <+PUBLIC INTERFACE+>
\<CR>};
\<CR><++>
\<CR>
\ in beginning of line tells that the line is the continuation of the previous one. But this is rather literal continuation: it doesn't add new lines so one has to add them manually. Since it uses the insert mode, the operation would be also affected by the current indentation mode. (Though one can try to work that around with :set paste/:set nopaste.)
I would have tried to put the text into a temp variable or register then Pput (or :put) it into the buffer. E.g. setreg() allows one to tell that the content of a register are lines and thus Putting it would work regardless of indentation.
Otherwise, looking in :help line-continuation or :help variables I see no way how one can specify a multi-line string or text.

Is it possible to format C++ code with VIM?

I am rather new to VIM. I got some source code and this is a mess. At a first sight I would like at least to get a clear and organised view of the code, so I like to get it rightly formatted, I mean indented depending on the depth of the functions and so.
I wonder if it can be done with VIM, and otherwise which other commandline tools for that can you recommend.
Thanks
While vim is a true Swiss-knife I still prefer external tools for some jobs. This approach is some times much more intuitive and easy to remember than using the built-in equivalent.
In the case of indenting, I filter the whole file buffer through astyle. The astyle parameters are much easier to grasp in a couple of minutes, especially if you are not a vim guru. Also astyle provides much more flexibility in fine-tuning the output.
First install astyle:# apt-get install astyle
Then inside vim:
:%!astyle (simple case - astyle default mode is C/C++)
or
:%!astyle --mode=c --style=ansi -s2 (ansi C++ style, use two spaces per indent level)
or
:1,40!astyle --mode=c --style=ansi (ansi C++ style, filter only lines 1-40)
you can do the following:
gg=G
I would highly recommend clang-format nowadays. It allows simple integration of clang-format into Vim, once you have clang-format installed:
http://clang.llvm.org/docs/ClangFormat.html#vim-integration
It is the only code beautifier that really understands your C++ code, and it is really intelligent to beautify the code more like a human being than a machine. E.g.:
void TestFunction(int argument1, int argument2,
int argument3);
void TestFunctionVeryLongName(int argument1,
int argument2,
int argument3);
void TestFunctionWithRidiculouslyLongName(
int argument1, int argument2, int argument3);
Vim will definitely do this, although the results may not be perfect:
First, select the entire file in visual mode: ggVG
Then hit = to reindent everything.
You can learn more about the equal command with: :help =
There is also a Vim plugin relying on clang-format: vim-clang-format
Then you can simply map the formatting command to whatever suits you.
There is a vim plugin that enables formatting on your code from within vim. It's called vim-autoformat and you can download it here:
https://github.com/vim-autoformat/vim-autoformat
It integrates external code-formatting programs into vim. For example, if you want to format C, C++, C# or Java code, you need to install the program astyle, and vim sets it as the format program automatically.
I don't write C++ code, but I write some Java code.
Instead, Vim supports the formatting of some common languages.
I have set up a short cut for me to format the whole code in the buffer.
It will return to the line I just edited :)
" format the file
map <leader>fm gg=G'.
A generic solution along the lines of m000's idea is to use UniversalIndentGUI as an external tool.
Just had to solve this exact problem, so I thought I'd contribute to save others some time.
You can use gg=G to indent your code. But things get hard to understand the moment you want to tweak how that auto-indenting happens. Therefore, if you only care that errant whitespace is removed and don't really care about formatting style, gg=G is the quickest way to go about it, because its built-in.
If you do want to control the style (for example, you're trying to make your code conform to a style guide), then you're going to need an external tool to process your file. You can invoke that tool from within vim with: :%!<toolname> <options>. This pipes the file through the tool and re-loads the processed result. (You can obviously use this for anything else you want to do to your file too)
So the next question is, what external tool should you choose? Regardless, the method is the same:
Install the tool of choice
Make sure its in your path
Add a line to your vimrc file that creates a shortcut key to use so you save time
Use it.
Now, which tool you use depends on the style you're trying to replicate. If you're trying to replicate a widely used style, then chances are astyle is all you need.
If you're trying to replicate a custom style, then you will need two things:
UniversalIndentGui - a front end that lets you play around with various options and live-preview their effect on the source file
A set of source code formatting tools installed and in your path
Between uncrustify and greatcode, you should be able to completely replicate the style you want.
Actually, I lied. There is another way and its called clang-format. However, you're going to want to read the documentation on it and its still in early stages so some options don't work very well. It is a beautiful tool though (definitely the smartest of the lot because constructs an AST of your code) and it is even available for Windows.
If you're going to take the time to read the manual, you also want to check out GNU Indent.
Of course, there is the last way, which is actually taking the time to learn vim's indent rules and writing one for your style. It will take time, but it will work with gg=G.
Some notes on astyle vs uncrustify vs greatcode:
Astyle is good for general formatting, but can't do things like align the declaration of variables and re-style comments very well.
Uncrustify can do a LOT of stuff that astyle can't, but be prepared to spend an hour playing around until you've found the correct combination of options you need. (Or if you feel like wasting a lot of time, use genetic algorithms to figure out the best combination of options for your style and when you do share the code and give me a link so I can use it too :) )
Note that you don't have to choose one tool. With vim, you can map one keystroke to execute several commands in succession, so theoretically you could use a combination of these tools to get exactly what you're looking for.
Last but not least, here's an excerpt from my .vimrc file, where I have mapped F12 to invoke astyle with some options:
"A2 = attached brackets
"-s8 indent 8 spaces
"-xc attached braces to class declarations
"-xj remove braces for single statement ifs and elses
"-c convert tabs to spaces in the non-indentation part of the line
map <F12> :%!astyle -A2 -s8 -xc -xj -c<CR>
Don't judge me on the style. Just use the tool to reproduce what you want.

Does Vim have an auto-comment feature based on the file's syntax?

I'm not sure this is possible, but I'm interesting in making this happen.
Ideally, I would like to map this feature to SHIFT+CTRL+3.
I'm looking for a way to have Vim enter a comment (single line) which corresponds to the syntax of the file I'm editing. If there are multiple single-line comment styles, Vim could either automatically pick one, or give me the choice. If the single-line comment has two parts (e.g. /* and */), then pressing SHIFT+CTRL+3 the first time will start the comment, and the second time will close the comment.
Examples:
Python: #
JavaScript: //
C, C++: /* with */ or //
I know there are scripts which will insert comments for you, but I haven't seen any that will do this based on the syntax of the file.
I highly recommend NERD Commenter.
Sort of! I don't believe vim will do this out of the box, but you can install plugins that will do fairly intelligent commenting (using movement keys, visual line highlighting, etc) that are specific to the filetype being edited. You can get these plugins off of vim.org, and you should be able to make your own key mappings in your .vimrc file if you don't like the ones they come with.
tComment is pretty well regarded, and has worked for me.
I've heard that EnhCommentify might be better, but I haven't used it myself.
Seems like a similar question to this:
How to comment in vim while respecting the indent?
Use the nerd commenter plugin:
http://www.vim.org/scripts/script.php?script_id=1218
See: this script which provides a function to commented a highlighted area in visual mode.
You want to start a comment in insert mode so your function would look more like:
fun CommentLines()
exe ":s#^#".g:Comment."#g"
endfun
Not quite what you're looking for, but efficient, and I suppose you know which comment to use.
(all this in command mode)
Put your cursor to the first line you want to comment. We willl then set a marker called a (valid names are a-z, single character) by typing
ma
put the cursor to the last line, then set a marker called b by typing
mb
Then comment the whole block (by searching for a newline and inserting the comment character (note the use of "#" as search delimiter because otherwise wee have to escape the "/")
:'a,'bs#^#//#
or for Python:
:'a,'bs/^/#/
To uncomment:
:'a,'bs#^//##
As we do line comments, it doesn't matter if we have other comments already in the file, they will be preserved.

How do I get Vim to automatically put ending braces?

While editing .scm files it would be great if Vim would automatically put the ending brace ) as soon as I start (. How do I do this?
You can map the opening brace to your liking:
:imap ( ()<left>
Try to use AutoClose plugin.
The simplest answer is to include a map. Eg.:
:inoremap ( ()<left>
The problem is that you would need to add one entry for each symbol you want automatically closed ('{','[','"',etc). Besides, plugins are normally more smart, providing things like detecting the "closing" character and not repeating it.
The problem with the solution above and most plugins, is that they tend break the undo sequence (gundo anyone?), as explained in:help ins-special-special.
Here is list of plugins that do what you ask (from vimtips):
delimitMate by Israel Chauca Fuentes (configurable, and doesn't break undo/redo/repeat, but - break iabbr) also on GitHub
AutoClose by Karl Guertin (auto-closes specific hard-coded characters, but doesn't break undo/redo/repeat)
AutoClose by Thiago Alves (configurable, but breaks undo/redo/repeat)
auto-pairs Auto Pairs by Miao Jiang (configurable, but breaks undo/redo/repeat)
ClosePairs by Edoardo Vacchi (configurable, but breaks undo/redo/repeat)
smartinput by Kana Natsuno (configurable, but breaks undo/redo/repeat)
Besides vimtips, there is another nice explanation of the issue on the web.
I needed one too, and I already tried a few of the plug-ins:
AutoClose, http://www.vim.org/scripts/script.php?script_id=1849, is a bit aggressive.
simple pairs, http://www.vim.org/scripts/script.php?script_id=2339, depends on Python. If you are on Linux it is not a problem, but on Windows it can be a trouble to match the Vim version to the Python interpreter you have.
My advice would be ClosePairs, that you can find at http://www.vim.org/scripts/script.php?script_id=2373 which has been working perfectly for me. It is simple and useful.
There are many tips and plugins on the subject. Have a look at the relevant entry in the vimtips site.
I'm presently using auto-pairs and it works quite very well.
The issues of the the plugin breaking undo/redo/repeat seem to persist among some of the plugins listed above but i don't think its much of an issue (well, at least not to me at the moment).
Just one caveat though, i wasn't able to use :helptags to generate the help file with this plugin as at the time of writing this.
Check out this new plugin: vim-autoclose by Townk. The previously mentioned AutoClose was to aggressive, sometimes behaving in an undesirable way.
There is a problem with using this (via the imap or one of the scripts). You won't be able to repeat the complete edit by using the . command.
e.g. (foo) with . only gets you foo, without the brackets.
It works fine if you insert the brackets normally, as two characters.
You can try downloading the following plugin
AutoClose : Inserts matching bracket, paren, brace or quote
https://github.com/vim-scripts/Auto-Pairs
Tested this plugin for undu redo. 2013 It just works. Also with python-mode plugin.
There is a new plugin by cohama:
lexima.vim (github)
(not yet on vim.org)
This plugin supports the .command!
Afaik, this is the only plugin supporting this.
Also the undo/redo sequence works.

Resources