Which editors out of Emacs, Vim and JEdit support multiple simultaneous text insertion points? - vim

Background: JEdit (and some other text editors as well) support a feature called Multiple simultaneous text insertion points. (at least that's what I'm calling it here).
To understand what this means, take a look at the link.
Out of all the features in use in modern text editors, initial research seems to indicate that this is one feature that both Emacs and Vim do not actually support. If correct, this would be pretty exceptional since it's quite difficult to find a text editor feature that has not made its way into at least one of these two old-school editors.
Question: Has anyone ever seen or implemented this feature in either Emacs, Vim, or both? If so, please point me to a link, script, reference or summary that explains the details.
If you know an alternate way to do the same (or similar) thing, please let me know.

The vim way to do this is the . command which repeats the last change. So, for instance, if I change a pointer to a reference and I have a bunch of
obj->func
that I want to change to
obj.func
then I search for obj->, do 2cw to change the obj-> to obj., then do n.n.n. until all the instances are changed.
Perhaps not a flexible as what you're talking about, but it works frequently and is very intuitive and fast when it does.

moccur-edit.el almost does what you want. All the locations matching the regexp are displayed, and the editing the matches makes changes in the corresponding source. However, the editing is done on a single instance of the occurrence.
I imagine it'd be straight forward to extend it to allow you to edit them all simultaneously (at least in the simple case).
There is a demo of it found here.
Turns out, the newest versions of moccur-edit don't apply changes in real-time - you must apply the changes. The changes are also now undoable (nice win).

In EMACS, you could/would do it with M-x find-grep and a macro. If you really insist that it be fully automatic, then you'd include the find-next in the macro.
But honestly, this strikes me as a sort of Microsoft-feature: yes, it adds to the feature list, but why bother? And would you remember it existed in six months, when you want to use it again?

For emacs, multiple-cursors does exactly that.
Have a look at emacsrocks episode 13, by the author of the module.

I don't think this feature has a direct analogue in either Emacs or Vim, which is not to say that everything achievable with this feature is not possible in some fashion with the two 'old-school' editors. And like most things Emacs and Vim, power-users would probably be able to achieve such a task exceedingly quickly, even if mere mortals like myself could spend five minutes figuring out the correct grep search and replace with appropriate back-references, for example.

YASnippet package for Emacs uses it. See 2:13 and 2:44 in the screencast.

Another slight similarity: In Emacs, the rectangle editing features provided by cua-selection-mode (or cua-mode) automatically gives you multiple insertion points down the left or right edge of the marked rectangle, so that you can type a common prefix or suffix to all of those lines.
e.g.:
M-x cua-selection-mode RET (enable the global minor mode, if you don't already use this or cua-mode)
C-RET down down down (marks a 1x3 character rectangle)
type prefix here
C-RET (unmark the rectangle to return to normal editing)

It should be something like this in vim:
%s/paint.\((.*),/\1.paint(/
Or something like that, I am really bad at "mock" regular expressions.
The idea is substitute the pattern:
/paint(object,/
with
/object.paint(/
So, yes, it is "supported"

It seemed simple to do a basic version of this in Emacs lisp. This is for when you just want two places to insert text in parallel:
(defun cjw-multi-insert (text)
"insert text at both point and mark"
(interactive "sText:")
(insert-before-markers text)
(save-excursion
(exchange-point-and-mark)
(insert-before-markers text)))
When you run it, it prompts for text and inserts it at both point (current position) and mark. You can set the mark with C-SPC. This could be easily extended for N different positions. A function like set-insert-point would record current position (stored as an Emacs marker) into a list and then when you run the multi-insert command, it just iterates through the list adding text at each.
I'm not sure about what would a simple way to handle a more general "multi-editing" feature.

Nope. This would be quite difficult to do with a primarily console-based UI.
That said, there is similar features in vim (and emacs, although I've not used it nearly as much) - search and replace, as people have said, and more similarly, column insert mode: http://pivotallabs.com/users/brian/blog/articles/350-column-edit-mode-in-vi

Related

Is there a less fantastically kludgy way to do one-off highlights in Vim?

i. The Problem
My goal is something like the following:
I have a line of text like
Who left the dead mouse in the fridge?
and I want to highlight the first the in green, just this one occurrence. That is, I don't want to syn match ThisMagicWord "\<the\>" or anything that will overzealously highlight other thes.
There is one other requirement, which is that if the user edits the other text on the line, say to
Who on earth left the delicious dead mouse in the fridge?
the highlighting will track with the word the, so long as the user doesn't edit that one particular word.
ii. The Kludge
Now, I have a solution to this. In fact, I am proud of my solution, because it was tricky to think up. But it is not, by any stretch of the imagination, a good solution.
It turns out that the Unicode character Combining Grapheme Joiner is effectively a no-op in Vim. It produces no glyph, and takes up no width. It is the only such character that I have discovered. So what I do is, I surreptitiously edit the line in question to be
Who left the<CGJ> dead mouse in the fridge?
and then define a rule
syn match ThisMagicWord "the<CGJ>"
I will additionally trigger on BufWritePre and BufWritePost to strip the CGJs out of the file on disk.
iii. The Questions
Is there a no-op character in Vim (or a way to produce one) other than CGJ? Ideally a non-combining character, since the<CGJ> will not match a search for /the, due to the way Vim regexes handle combining characters.
Is there a better way to get at the behavior that I want?
You're right that there's currently no good way to mark static matches and keep them up-to-date when edits are done nearby. My approach would have been worse than your kludge: Include the line / column information in the match (via the \%l and \%v special atoms), and attempting to update those with a combination of marks (works for line changes) and intra-line custom diffing.
Though your use of special Unicode characters is clever, it's (as you admit) a hack. I've asked you for uses in the comments, and am still not completely satisfied / convinced. If you can come up with good, real use cases and current pain points, please direct them to the vim_dev mailing list (best with a functional draft patch attached). The functionality to keep track of such text is basically there (in the Vim internals), it's just not yet tracked and exposed to users / Vimscript. Though Vim development has been (often frustratingly) slow, with a compelling argument on your side, new functionality can and does happen.
How about using marks?
Move the cursor to the word you want, set a lowercase letter mark (e.g. mz), then add highlighting for the word like \%'zthe

VIM Delete Standard Scripting Word Groups

How would you use VIM to delete a word group, which includes white space characters, but is a standard grouping you would want to access when scripting? Specifically, when you have your cursor over some part of the following text, how would delete help="initialize, lines, h2, derivs, tt, history", from below. Maybe one would need to create specific mappings. But on the other hand, it seems pretty natural to want to access text like this if you are using VIM to edit scripting programs.
parser = argparse.ArgumentParser()
parser.add_argument("task", help="initialize, lines, h2, derivs, tt, history", default='yes')
Vim has a variety of text objects built-in, e.g. da" deletes quoted text (including the quotes; di" keeps the quotes). See :help text-objects for more information.
There are some plugins, e.g. textobj-user - Support for user-defined text objects and my own CountJump plugin that make it easy to define your own, "special" text objects. Also, you'll find many such text objects on vim.org. Based on your example, argtextobj.vim - Text-object like motion for arguments may be exactly what you need here.
If you are inside the " you want to delete, I would use:
di"diW
If you were above help=, I would use something like:
d/defEnter
to remove everything until you encounter default, followed by a few x, and left-wise motion, to remove the remaining characters.
I don't really think a new mapping is needed, but your experience may vary.
What makes sense from Vim's perspective and according to its design goals is to provide small and generic elements and a few rules to combine them in order to achieve higher level tasks. It does quite a good job, I'd say, with its numerous text-objects and motions but we always have to repeat domain-specific tasks and that's exactly where Vim's extensibility comes into play. It is where users and plugin authors fill the gap with custom mappings/object/functions and… plugins.
It is fairly easy, for example, to record a macro and map it for later reuse. Or create a quick and dirty custom text-object…
The following snippet should work with your sample.
xnoremap aa /\v["'][,)]/e<CR>o?\v\s+\w+\=<CR>
onoremap aa :normal vaa<CR>
With it, you can do daa, caa, yaa and vaa from anywhere within that argument.
Obviously, this solution is extremely specific and making it more generic would most certainly involve a bit more thought but there are already relatively smart solutions floating around, as in Ingo's answer.

Vim Repeat dot (".") command buffer?

I really like the behavior of YankRing, which lets me access the last several things I've yanked or deleted or changed without thinking.
However a complementary feature like this is completely missing for the . repeat command, most often when I type something I really want to repeat, then accidentally overwriting that edit by pressing x to clean something up.
Often it's possible to get back some time still by visual-mode yanking what I just typed, but this is not ideal.
It should be really easy to remember the past few commands.
The question is how possible is it to extract from Vim the representation of the last command contained in whatever stores what . will do before it gets blown away?
If it is as I fear, the only way is to get a plugin to bind to every single command that could edit something, and instrument it in such a way as to store our own repeat-buffer. This is really not practical because I can already imagine how many other plugins that will break. But, I would still really really want this feature if it is possible in any way.
Unfortunately, there's no way to get and replay the command behind the . command. The only workaround is to be perpetually in macro recording mode, and use the macro register as a replacement for the . command.
This tactic is employed by the RepeatLast plugin, which might offer what you want.
Keyword completion and/or ctrl-a in insert mode should cover your needs.
A more yankring-like solution should be possible but, as you say, probably a little too intrusive. Did you look on vim.org by yourself before asking others to do it for you?

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.

What is the most convincing command in Vim

I want to ditch my current editor. I feel I need something else. That do not expose my hands to the risk of RSI. I need to see why I should change editor. And it would be nice to believe, that I will be coding when I'm 80 years old.
All the big guys out there are using Vim. The only Emacs guy I know are RMS. Paul Graham is a Vi dude.
. (dot) - repeats the last editing action. Really handy when you need to perform a few similar edits.
:help usr_12.txt
That'll bring up a section in the help system that discusses "Clever Tricks". If those don't get you excited I don't know what will!
Recording macros
The asterisk.
*
Its effect: Immediately search for the next instance of the word under the cursor.
The best thing is the efficiency with which you can edit code (which is done a lot in programming). The commands such as
cw to change a word
dw to delete a word
ct, to change all text until the next comma
ci( to change the contents of the parentheses you're currently in
xp to correct spelling mistakes ("spleling" -> cursor on l -> xp -> "spelling")
o to insert a new line below and start editing
O to insert a new line above
Then there is the possibility to work with named registers very quickly. To move a block, just select it, press d, then move to it's new location and press p. Much faster than Ctrl-C and Ctrl-V. Use "ud to delete text and move it to register u (I use this one for the commenting template).
And also Vim has all the scripting support you need (either using it's native scripting language or using Python, Ruby, ...)
the numbers.
in command mode
type a number ( any number of digits )
type a command.
that command will be executed $number times
ie:
99dd
erases the next 99 lines.
The fast startup time.
The sharp distinction between editing and viewing. (you know when you edit)
The only way you ever find what you are looking for is with search "/" and that is good, since it much faster than your eyes.
But the best command(s) are:
/ - search string
ZZ - quit
. - repeat last insert (I think)
%! - insert unix command
Handling multi line regexps in search strings with "\_.". While checking over 4GB text files of various formats, it had saved my life several times.
Why are you looking to be convinced to start using a different editor? If you're happy with what you have now, stick. If not, perhaps ask about editors with features that you lack.
Even if you are using Visual Studio there is the wonderful vsvim.
I love the speed of Vim but I find it lacks the features of a modern IDE for C++ development. Eclipse CDT with the viPlugin is a good compromise.
You get the power and source overview provided by Eclipse CDT with the speed and flexibility of Vim for coding.
The lovely built in regular expression evaluator.
Maybe reading "Come home to vim" by Steve Losh article is a good start, or
a series of videos about interesting plugins. And be sure to see some articles on the site vimcasts.org
You should map Caps Lock to Esc. It will make getting out of insert mode feel natural as opposed to the awkward move you must make to press the ESC key. Besides, who uses Caps Lock anyway?
\v
Make your regular expressions mostly Perl compatible.
See very magic section here for more information.
To be truly inspired, you must see a vim guru in action. If you do not have a local guru, here is a video to inspire you.
http://www.youtube.com/watch?v=jDWBJOXs_iI&feature=related
If you don't already know vim, the speed at which code is navigated, sliced, and diced will be indistinguishable from magic. After a few months of studying vim, the same editing speed will seem commonplace.

Resources