I've been trying Vim for any text editing work for almost a week now. I want to know the fastest way to select a C function definition.
For example, if I have a function like this:
void helloworlds( int num )
{
int n;
for ( n = 0; n < num; ++n ) {
printf( "Hello World!\n" );
}
}
How would I be able to delete the whole definition including the function name?
As is common in Vim, there are a bunch of ways!
Note that the first two solutions depend on an absence of blank lines.
If your cursor is on the line with the function name, try d}. It will delete everything to the next block (i.e. your function body).
Within the function body itself, dap will delete the 'paragraph'.
You can delete a curly brace block with da}. (If you like this syntax, I recommend Tim Pope's fantastic surround.vim, which adds more features with a similar feel).
You could also try using regular expressions to delete until the next far left-indented closing curly brace: d/^}Enter
]] and [[ move to the next/previous first-column curly brace (equivalent to using / and ? with that regex I mentioned above. Combine with the d motion, and you acheive the same effect. In addons like Python-mode, these operators are redefined to mean exactly what you're looking for: move from function to function.
How to delete the whole block, header included
If you're on the header/name, or the line before the block, da} should do the trick.
If you're below a block, you can also make use of the handy 'offset' feature of a Vim search. d?^{?-1 will delete backwards to one line before the first occurrence of a first-column opening curly brace. This command's a bit tricky to type. Maybe you could make a <leader> shortcut out of it.
Plugins
I don't do much C programming in Vim, but there are surely plugins to help with such a thing. Try Vim Scripts or their mirror at GitHub.
To delete an entire function, including its definition, such as:
function tick() {
// ...
}
Move to the line with the function name.
Move the cursor to the opening brace, f{ should do it, or simply $.
Press V%d (Visual line, move to matching pair, delete)
If your functions look like this:
function tick()
{
// ...
}
Move to the line with the function name.
Press J (join the current line with line bellow. This also puts your cursor at the last character on the resulting line, {, just the one we need for the next command.)
Press V%d (Visual line, move to matching pair, delete.)
or
Move to the line with the function name.
Press V[Down]%d (Visual line, move one line down, move to matching pair, delete.)
If you are willing to install plugins vim-textobj-function will give you vif for Visual select Inside Function and vaf for Visual select A Function.
daf will delete the function, both the line with the signature and the function body ({})
The text object defined by this plugin are more specific and they don't rely on the function body being a contiguous block of text or { being placed at the first character on the line.
The drawback is that you depend on an external plugin.
You can use this shortcut to delete not only the function, also the lines between curly braces, i.e the code between if-else statements,while,for loops ,etc.
Press Shitf + v [Will get you in visual Mode] at the curly brace start/end.
Then Press ] + } i.e ] + Shitf ] - If you are in start brace.
Then Press [ + { i.e [ + Shitf [ - If you are in end brace.
Then DEL to delete the lines selected.
The simplest and most direct way way is as follows (works anywhere inside function):
v enter visual mode
{ move to first brace in function (may have to press more than once)
o exchange cursor from top to bottom of selection
} extend selection to bottom of function
d delete selected text
The complete command sequence would be v{o}d. Note that you can do other operations besides delete the same way. For example, to copy the function, use y (yank) instead of d.
Use this simple way
1.Go to the function definition
2.dd - delete function definition
3.d -start delete operation
4.shift+5(%) - delete the lines between { to }
If your function were separated by the blank lines, just type:
dip
which means "delete inner paragraph".
Another way is to go to the line of the start of your function and hit: Vj% (or V%% if your style puts the opening brace on the same line). This puts you into Visual-Line mode and the percent takes you to the matching closing brace. In the second style, the first % takes you to the opening brace on the line that you selected and the second to its matching closing brace.
Also works for parentheses, brackets, C-style multi-line comments and preprocessor directives.
See the manual for more info.
Pre-condition: be somewhere inside the function.
Go to the previous closing curly bracket on the first line using
[]
Then delete down to the next closing curly bracket on the first line using
d][
Most posted methods have a downside or two. Usually, when working withing a class definition of some object oriented language, you might not have an empty line after the function body, because many code formatters put the closing braces of last method and class on consecutive lines. Also, you might have annotations on top of the function. To make matters worse, there might be empty lines within your function body. Additionally you'd prefer a method that works with the cursor anywhere within the function, because having to move it to a specific line or worse, character, takes valuable time. Imagine something like
public class Test {
/* ... */
#Test
public void testStuff() {
// given
doSetup();
// when
doSomething();
// then
assertSomething();
}
}
In this scenario, vap won't do you any good, since it stops at the first empty line within your function. v{o} is out for the same reason. va{V is better but doesn't catch the annotation on top of the method. So what I would do in the most general case is va{o{. va{ selects the whole function body (caveat: if your cursor is within a nested block, for instance an inner if statement, then you'll only get that block), o puts the cursor to the beginning of the selection and { selects the whole paragraph prepending your selection. This means you'll get the function definition, all annotations and doc comments.
the most easy way I found is:
Get to the line where the function starts and do this: ^^vf{% to mark the entire function and then whatever you like.
^^ - start of the line
v - start visual mode
f - jump to the next search character
{ - this is the search character
% - jump to the closing brackets
This is also very logical after you have used it a few times.
non-visual way:
d/^}/e
... delete by searching for } at line beining, including it for deletion.
without /e (not mentioned in above answers), solution is incomplete.
with /e - searching goes to end of match, so closing bracket is included, and command is well for yanking too:
y/^}/e
if you use neovim version :>0.5
the modern way is to use treesitter and build your model, then you can be selected or yanked or deleted...
Tree-sitter is a parser generator tool and an incremental parsing library. It can build a concrete syntax tree for a source file and efficiently update the syntax tree as the source file is edited
I suggested this video on youtube to learn how to use treesitter to build your model : Let's create a Neovim plugin using Treesitter and Lua
I tried all the top answers here, but none of them works except the one by Nick which suggests to press f{ to get to the opening curly brace. Then V%d to delete the whole function.
Note that, the whole function gets yanked, so you can paste it elsewhere. I come across this use-case frequently, especially when moving if blocks inside another.
I use this map. It work for me
"delete function definition
"only support function body surround by {}
nnoremap <LEADER>df {v/{<cr>%d
Related
I am making a console like program where you input text, and when you press enter, that text gets turned into the variable "code" which gets read by the if/elseif command to direct it to a certain frame.
When I did this though, actionscript completely ignored the if and just executed what was inside of the if.
There are no errors, but there is a warning. This is my full code
import flash.events.KeyboardEvent;
stop();
stage.focus=textbox;
var code:String=textbox.text;
textbox.addEventListener(KeyboardEvent.KEY_DOWN,thefunction);
function thefunction(event:KeyboardEvent){
if(event.charCode == 13){
code=textbox.text;
trace(code);
page();
}
}
function page(){
if(code="red"){
gotoAndPlay(19)
}
else{
gotoAndStop(1)
}
}
The warning is here=
function page(){
if(code="red"){
gotoAndPlay(19)
}
else{
gotoAndStop(1)
}
}
It says: Warning: 1100: Assignment within conditional. Did you mean == instead of =?
I then tried doing what it said, and nothing happens when I type in anything and press enter (charCode 13).
I have tried doing this with textbox.textinstead of the variable code, and still nothing happens. (trace(code) works fine, so it must be something with the bottom portion, but I'm not sure)
I am new to actionscript, so I do not know how to fix this (my excuse :D). If anybody knows how, I would love to figure out how to fix it.
first of all, as a general rule, you should never use the assignment operator (single =) in an if statement, always use the equality operator (double =)
what you're saying right now is "if you assigned the value 'red' to code without errors, then..." which of course is always true
then, to debug your problem, try to use trace("'" + code + "'"); to see exactly what your textfield contains. if you're still in doubt, convert your text in character codes and print those. Why? if there's a non-printable or non-visible character in your textfield, your if statement wouldn't match (think "red " == "red" > false)
my guess is that your textfield is set to multiline, so your enter key would be added to the text and break your check. set it to single line to avoid possible problems (if you do need a multiline input field, you need a smarter way to compare text, like using regular expressions and such ...)
In my sass code, I have inline comments and I wish to remove these in sublime text. Is it possible to permanently delete all comment content alone?
#function emCalc($values) {
$emValues: '';
$max: length($values); //Get the total number of parameters passed
#for $i from 1 through $max {
$value: (nth($values, $i)); //Take the individual parameter
$value: $value / ($value * 0 + 1); //Doing this gets you one unit (1px)
$value: $value / $em-base * 1em; //Divide the px value by emBase and return the value as em
$emValues: #{$emValues + $value}; //Append to array
#if $i < $max {
$emValues: #{$emValues + " "}; //Adding space between parameters (except last), if there are multiple parameters
}
}
#return $emValues; //Call emCalc like so emCalc(10, 20, 30, 40) it should return margin: 0.625em 1.25em 1.875em 2.5em
}
You'll need to double check this (have a backup handy!), but the following regular expression should work in the "replace" window, with regular expressions enabled (the * icon):
Open the "replace" window (ctrl + h / cmd + option + f)
Enable regular expression matching by making sure the * icon is selected
Enter the following in the "Find What?" box
\/\/.*
Leave the "replace with" box empty to delete found text.
Click "Replace All"
Edit
as #ollie noted, this also will delete any urls prefixed with //. The following (lightly tested) regex should serve to better target comments: (^\/\/.*)|(\s+\/\/.*)
Edit v2
A solution for single and multi-line comments (^\/\/.*)|(\s+\/\/.*)|((\/\*)(.|\n)+?(\*\/))
If you have no other possibility, you could select every // (Select first // then CtrlD while there's comments left if my memory is correct).
Then press ShiftEnd to select every end of line with a // and Del ! :)
(There's probably a plugin for that, but this is the simplest method I think. This suggest that all your // refers to the beginning of a comment, of course)
None of the answers here seem to take advantage of the fact that the syntax highlighting has already determined where all the comments are - just execute this in the Python console (View menu -> Show Console) to select all comments:
view.sel().clear(); view.sel().add_all(view.find_by_selector('comment'))
(press Enter after typing/pasting it to execute it)
then press Delete to delete all the selections and Esc to go back to single selection mode
None of the other answers cover all cases (multi-line comments, single line comments, double-slash comments and slash-star/star-slash comments).
In order to match all possible cases (without matching URLs), use the following:
(^[\s]*?\/\/.*)|(/\*[\s\S]+?\*/)
Here is what I do in ST3 in HTML to strip all comments, especially nasty comments embedded within <p> body text, for example ...
package control install SelectUntil
quit and restart sublime
ctrl+f <!--
alt+enter to select all instances of <!--
ctrl+shift+s will pull up an input field, where
you can type: -->
hit delete!
Well well, there is an easy way to do it in mac Sublime Text if you are sure there are no // in print statements.
search for // and hit that cmd+ctrl+G and then to select the whole line which has hit cmd+shift+Arrow and delete it. Assuming you have used only single line comments
I'm using a keyboard shortcut bound to:
er/expand-region, which is an interactive Lisp function in `expand-region-core.el'.
to expand the region.
For example when I want to select a function and move it around.
My problem is that if I want to select any function like, say:
;; some comment related to the function
(defn foo [x]
...)
I cannot "expand" to include ";; some comment". As soon as I expand more than the function (without the comment) it expends the full buffer.
While I'd like it to first expand to include the function and the comment and then the full buffer.
It's bothering me so much that I'm temporarily doing this as a workaround:
(defn foo [x]
;; some comment
...)
How can I modify er/expand-region (or another function) so that after expanding to the full function it expands the comments right above the function before expanding to the whole buffer?
From Magnar Sveen, the creator of the package expand-region, taken from his github:
Example:
Let's say you want expand-region to also mark paragraphs and pages in
text-mode. Incidentally Emacs already comes with mark-paragraph and
mark-page. To add it to the try-list, do this:
(defun er/add-text-mode-expansions () (make-variable-buffer-local
'er/try-expand-list) (setq er/try-expand-list (append
er/try-expand-list
'(mark-paragraph
mark-page))))
(add-hook 'text-mode-hook 'er/add-text-mode-expansions)
Add that to
its own file, and add it to the expand-region.el-file, where it says
"Mode-specific expansions"
Warning: Badly written expansions might slow down expand-region
dramatically. Remember to exit quickly before you start traversing the
entire document looking for constructs to mark.
I would say you could add "er/mark-paragraph" to the expand-region list, that should do it.
Following user Dualinity's advice, I added the following to clojure-mode-expansions.el (can be done for other modes than Clojure of course) :
;; added this line at the beginning of the file
(require 'org-mode-expansions)
Then I added the line er/mark-paragraph to the expand list inside the er/add-clojure-mode-expansions method:
(defun er/add-clojure-mode-expansions ()
"Adds clojure-specific expansions for buffers in clojure-mode"
(set (make-local-variable 'er/try-expand-list) (append
er/try-expand-list
'(er/mark-clj-word
er/mark-clj-regexp-literal
er/mark-paragraph ; added this line
er/mark-clj-function-literal))))
I restarted Emacs (not too sure as to what was needed to be sure it was taken into account so I restarted the whole thing).
And that's it: now expanding selects "outer" function comments too.
$_POST['daily_limit'];
$whatever = $_POST['smoke'];
$_POST['soup'] + $_POST['cake'];
to
$this->input->post('daily_limit');
$whatever = $this->input->post('smoke');
$this->input->post('soup') + $this->input->post('cake');
In this example, is there any faster way to switch from $_POST[] to $this->input->post() without writing up a regular expression find and replace? I don't care if it takes multiple steps. Writing the regex for this (find: \$_POST\[(.*?)\] replace: \$this->input->post\($1\)) takes longer than changing them all manually (maybe I'm just not good at regex). Any ideas?
I'm making a brash assumption here, that you have only one variable within each pair of brackets and that the variables only contain alphanumeric characters. ['soup'+'bacon'] will break this trick, as will ['soup-with-bacon'].
With your cursor, highlight an instance of $_POST[ - nothing else.
Hit Alt+F3 if you're on Windows/Linux (Cmd+ShiftG in Mac?)
Try to scroll through and see if everything that's selected is everything you want to replace.
Type $this->input->post( - nothing else.
Press → to move all cursors to the right of the first quote.
Press Ctrl+→ (this is the only remotely wtfh4xxy part of the process, and only if you're not used to navigating by word with the cursor) to navigate over the variable.
Press → twice to move all cursors to the right of the next quote.
Replace the ]with a ).
#nnnn I did a variation of your version to remove the wtfh4xxy part.
select:$_POST
altf3
type: $this->input->post(
ctrlshiftm
ctrlx
ctrlshiftm
ctrlv
type: )
Sublime text ftw!
I'm writing some folding functions and I am at a point where I need to check if the current line is actually a fold.
The reason for this is because it is a custom fold method that depends on searching/matching certain lines.
For example, if the current line is folded and looks like:
-FOO------------------------
If you do something like:
getline('.')
You would basically get FOO so there is no way (that I know of) to know if I am at a fold or not.
Is there a helper function for this?
I would think it would have to be something like:
is_folded('.')
I could probably mess with the foldtext to assign a special title for the fold but I want to avoid this.
From :help eval.txt
foldclosed({lnum})
The result is a Number. If the line {lnum} is in a closed
fold, the result is the number of the first line in that fold.
If the line {lnum} is not in a closed fold, -1 is returned.
You can check for a given line if it returns -1 or a line number, you can probably implement your isfolded() function this way.
If you are looking for Vim script function or feature , it is a good idea to start by searching in eval.txt which contains lots of relevant information.