Vim - change up to and including searched string - vim

Assuming I have the following code:
bool myCopiedFunc() {
Some code that I've written;
The cursor is on this line; <<<<<<<<<<<<<<
if (something) {
bool aValue;
some of this is inside braces;
return aValue;
}
if (somethingElse) {
this is also inside braces;
bool anotherValue;
{
more braces;
}
return anotherValue;
}
return false;
}
I decide I want to rewrite the remainder of the function, from the line with the cursor on it.
To replace up to a char on the same line, I can use ct<char> e.g. ct;
To replace up to and including a char on the same line I can use cf<char> e.g. cf;
To replace up to a string across multiple lines, I can use c/<string> e.g. c/return false
To replace up to and including a string across multiple lines, I can use... ?? e.g. ??
I can't just search for a semicolon, as there are an unknown number of them between the cursor and the end of the function, and counting them would be slow.
I can't just search for a closing brace, as there are several blocks between the cursor and the end of the function, and counting all closing braces would be slow.
With the help of code highlighting, I can easily see that the unique string I can search for is return false.
Is there an elegant solution to delete or change up to and including a string pattern?
I've already looked at a couple of related questions.
Make Vim treat forward search as "up to and including" has an accepted answer which doesn't answer my question.
In my case, I settled for deleting up to the search string, then separately deleting up to the semicolon, but it felt inefficient, and like it would have been quicker to just reach for the mouse. #firstworldproblems

To replace up to and including a string across multiple lines, I can
use... ?? e.g. ??
The / supports offsets.
In your case, you are gonna need the e offset, that is, c/foo/e.
You may want to know more details about "search offset":
:h offset

If you'll replace up to the closing brace associated to your current scope, you have c]}.
If you're looking for the end of the function, even if it means crossing to the upper scope, you'll need a plugin if the function may not be 0-indented as it's the case in C++, Java... See the related Q/A on vi.SE

Related

How to remove Letters AFTER-BEFORE specific Letters in dart

i found here many question about How to remove Letters AFTER specific Letters but did not find AFTER-BEFORE specific Letters
i don't know if it possible in dart ..
sample
String test = 'HelloAflutterBHello'
so how to outputs the following result
print(test) => 'flutter'
that's mean i want to delete everything before ('A') and everything after ('B')
i tried this
print(test.substring(0, test.indexOf('B')));
but this will delete only anything after ('B') but couldn't find a way to delete the Letters before ('A') too ..
i hope any good answer . thanks
You can use regular expressions to do the job. This way you can check for more than one character.
Consider this code:
void main() {
String test = 'HelloABCflutterDEFHello';
//regex match all characters between two (or more) specified characters
RegExp exp = RegExp(r"(?<=ABC).*(?=DEF)");
//store all results from searching within a string.
Iterable<RegExpMatch> matches = exp.allMatches(test);
// access the captured value
print(matches.first.group(0));
}

Counting the vowels in a string solution

I recently did a method to count the vowels in a given string and was able to solve it fairly simply, but my solution was compared to the best practices and this was the top one:
public class Vowels {
public static int getCount(String str) {
return str.replaceAll("(?i)[^aeiou]", "").length();
}
}
...which is much more elegant that what i wrote and i am trying to understand it. I don't get what exactly the "(?i)[^aeiou]" part is doing. I get that it is deleting all the characters that aren't vowels but I don't understand what the operators are doing or why they work in quotes shouldn't the program just see it as a string?
This is a regex and it is basically ignoring the case because we are only providing set of [aeiou] but it should also match with the capital ones [AEIOU]. Then ^ symbol is used to replace all the characters with empty string "" except for vowels(irrespective of their case).
(?i) - starts case-insensitive mode
(?-i) - turns off case-insensitive mode
[^...] - NOT ONE of these characters.

Implementing String Interpolation in Flex/Bison

I'm currently writing an interpreter for a language I have designed.
The lexer/parser (GLR) is written in Flex/Bison and the main interpreter in D - and everything working flawlessly so far.
The thing is I want to also add string interpolation, that is identify string literals that contain a specific pattern (e.g. "[some expression]") and convert the included expression. I think this should be done at parser level, from within the corresponding Grammar action.
My idea is converting/treating the interpolated string as what it would look like with simple concatenation (as it works right now).
E.g.
print "this is the [result]. yay!"
to
print "this is the " + result + ". yay!"
However, I'm a bit confused as to how I could do that in Bison: basically, how do I tell it to re-parse a specific string (while constructing the main AST)?
Any ideas?
You could reparse the string, if you really wanted you, by generating a reentrant parser. You would probably want a reentrant scanner, as well, although I suppose you could kludge something together with a default scanner, using flex's buffer stack. Indeed, it's worth learning how to build reentrant parsers and scanners on the general principle of avoiding unnecessary globals, whether or not you need them for this particular purpose.
But you don't really need to reparse anything; you can do the entire parse in one pass. You just need enough smarts in your scanner so that it knows about nested interpolations.
The basic idea is to let the scanner split the string literal with interpolations into a series of tokens, which can easily be assembled into an appropriate AST by the parser. Since the scanner may return more than one token out of a single string literal, we'll need to introduce a start condition to keep track of whether the scan is currently inside a string literal or not. And since interpolations can, presumably, be nested we'll use flex's optional start condition stack, enabled with %option stack, to keep track of the nested contexts.
So here's a rough sketch.
As mentioned, the scanner has extra start conditions: SC_PROGRAM, the default, which is in effect while the scanner is scanning regular program text, and SC_STRING, in effect while the scanner is scanning a string. SC_PROGRAM is only needed because flex does not provide an official interface to check whether the start condition stack is empty; aside from nesting, it is identical to the INITIAL top-level start condition. The start condition stack is used to keep track of interpolation markers ([ and ] in this example), and it is needed because an interpolated expression might use brackets (as array subscripts, for example) or might even include a nested interpolated string. Since SC_PROGRAM is, with one exception, identical to INITIAL, we'll make it an inclusive rule.
%option stack
%s SC_PROGRAM
%x SC_STRING
%%
Since we're using a separate start condition to analyse string literals, we can also normalise escape sequences as we parse. Not all applications will want to do this, but it's pretty common. But since that's not really the point of this answer, I've left out most of the details. More interesting is the way that embedded interpolation expressions are handled, particularly deeply nested ones.
The end result will be to turn string literals into a series of tokens, possibly representing a nested structure. In order to avoid actually parsing in the scanner, we don't make any attempt to create AST nodes or otherwise rewrite the string literal; instead, we just pass the quote characters themselves through to the parser, delimiting the sequence of string literal pieces:
["] { yy_push_state(SC_STRING); return '"'; }
<SC_STRING>["] { yy_pop_state(); return '"'; }
A very similar set of rules is used for interpolation markers:
<*>"[" { yy_push_state(SC_PROGRAM); return '['; }
<INITIAL>"]" { return ']'; }
<*>"]" { yy_pop_state(); return ']'; }
The second rule above avoids popping the start condition stack if it is empty (as it will be in the INITIAL state). It's not necessary to issue an error message in the scanner; we can just pass the unmatched close bracket through to the parser, which will then do whatever error recovery seems necessary.
To finish off the SC_STRING state, we need to return tokens for pieces of the string, possibly including escape sequences:
<SC_STRING>{
[^[\\"]+ { yylval.str = strdup(yytext); return T_STRING; }
\\n { yylval.chr = '\n'; return T_CHAR; }
\\t { yylval.chr = '\t'; return T_CHAR; }
/* ... Etc. */
\\x[[:xdigit]]{2} { yylval.chr = strtoul(yytext, NULL, 16);
return T_CHAR; }
\\. { yylval.chr = yytext[1]; return T_CHAR; }
}
Returning escaped characters like that to the parser is probably not the best strategy; normally I would use an internal scanner buffer to accumulate the entire string. But it was simple for illustrative purposes. (Some error handling is omitted here; there are various corner cases, including newline handling and the annoying case where the last character in the program is a backslash inside an unterminated string literal.)
In the parser, we just need to insert a concatenation node for interpolated strings. The only complication is that we don't want to insert such a node for the common case of a string literal without any interpolations, so we use two syntax productions, one for a string with exactly one contained piece, and one for a string with two or more pieces:
string : '"' piece '"' { $$ = $2; }
| '"' piece piece_list '"' { $$ = make_concat_node(
prepend_to_list($2, $3));
}
piece : T_STRING { $$ = make_literal_node($1); }
| '[' expr ']' { $$ = $2; }
piece_list
: piece { $$ = new_list($1); }
| piece_list piece { $$ = append_to_list($1, $2); }

Multiline string literal in Matlab?

Is there a multiline string literal syntax in Matlab or is it necessary to concatenate multiple lines?
I found the verbatim package, but it only works in an m-file or function and not interactively within editor cells.
EDIT: I am particularly after readbility and ease of modifying the literal in the code (imagine it contains indented blocks of different levels) - it is easy to make multiline strings, but I am looking for the most convenient sytax for doing that.
So far I have
t = {...
'abc'...
'def'};
t = cellfun(#(x) [x sprintf('\n')],t,'Unif',false);
t = horzcat(t{:});
which gives size(t) = 1 8, but is obviously a bit of a mess.
EDIT 2: Basically verbatim does what I want except it doesn't work in Editor cells, but maybe my best bet is to update it so it does. I think it should be possible to get current open file and cursor position from the java interface to the Editor. The problem would be if there were multiple verbatim calls in the same cell how would you distinguish between them.
I'd go for:
multiline = sprintf([ ...
'Line 1\n'...
'Line 2\n'...
]);
Matlab is an oddball in that escape processing in strings is a function of the printf family of functions instead of the string literal syntax. And no multiline literals. Oh well.
I've ended up doing two things. First, make CR() and LF() functions that just return processed \r and \n respectively, so you can use them as pseudo-literals in your code. I prefer doing this way rather than sending entire strings through sprintf(), because there might be other backslashes in there you didn't want processed as escape sequences (e.g. if some of your strings came from function arguments or input read from elsewhere).
function out = CR()
out = char(13); % # sprintf('\r')
function out = LF()
out = char(10); % # sprintf('\n');
Second, make a join(glue, strs) function that works like Perl's join or the cellfun/horzcat code in your example, but without the final trailing separator.
function out = join(glue, strs)
strs = strs(:)';
strs(2,:) = {glue};
strs = strs(:)';
strs(end) = [];
out = cat(2, strs{:});
And then use it with cell literals like you do.
str = join(LF, {
'abc'
'defghi'
'jklm'
});
You don't need the "..." ellipses in cell literals like this; omitting them does a vertical vector construction, and it's fine if the rows have different lengths of char strings because they're each getting stuck inside a cell. That alone should save you some typing.
Bit of an old thread but I got this
multiline = join([
"Line 1"
"Line 2"
], newline)
I think if makes things pretty easy but obviously it depends on what one is looking for :)

How do you select the entire PHP function definition?

In PHP, if I have a function such as:
function test($b) {
var $a = 0;
while ($a < b) {
$a += 3;
}
return $a;
}
and the cursor is on the $a += 3 line, is it possible to quickly select the entire function?
"v2aB" would select everything including the function braces but not the declaration function test($b)
Press V after the selection command you post, to convert the selection to line selection, and it will select the function declaration:
v2aBV
It's been a long time since this question was asked and answered, but I will add my own answer because it's the one I was looking for and none of the others work exactly like this one:
nnoremap vaf ?func.*\n*\s*{<cr>ma/{<cr>%mb`av`b
vmap af o<esc>kvaf
The first mapping, "Visual around function" or vaf, will jump back to the start of the function definition, regardless that the { is in the same line or the next one, and even if it's a lambda function, and visually select it characterwise to it's ending bracket. This works in PHP, Javascript and Go.
The user can then press V to turn to linewise select mode if she wants to.
The only problem that I found is that when I am in the body of a big function, but below a line that uses a lambda (let's say "small") function, this will stop searching at the beginning of the small function and select it's body instead of reaching the start of the big function and select all of its body.
function show_video_server(v_server) {
// this whole function should get selected
var something = function(){ /* this function gets selected */ };
// | the cursor is here when I type "vaf"
}
As a workaround I use the second mapping: vmap af o<esc>kvaf. It feels like a repetition or expansion of the selection. What it really does is abandon the selection and go to the line before it, and then try it agan. If the "big" function uses several lambda functions the user has to repeat the af several times to reach the big one.
Usually, vaf es enough. Sometimes vaf af or vaf af af is needed. Anyway, it's the closest I could get to what I wanted, so this is the version I'm using.
Here's a mapping that seems to work very well, no matter the nesting level.
:map t ? function <CR>f{vaBV
Here's another method that will work if you have function-level folding turned on: z c v
That closes the current fold and selects it, but it leaves it closed. If you want it to remain open: z c v $
If you have block-level folding turned on, you would have to close twice, since you're inside the while loop, so: 2 z c v
To enable PHP class/function folding: let php_folding = 1
simple way
nmap vaf va}V
I like this
nmap vaf [{?function<CR>:nohl<CR>vf{]}
if ‘{’ is in new line
nmap vaF [{?function<CR>:nohl<CR>v/{<CR>]}
Yet another way. This should select the entire function definition regardless of your cursor position within the definition, not just when you're at the $a += 3 line.
Use this in normal mode (<CR> means press enter)
?func<CR>V/{%
Explanation of each part:
?func search backward for the word "func" (the idea is to get to the first line of the function definition)
V go to visual line mode
/{ search forward for the opening brace (I didn't use f{ because the opening brace might be on a separate line)
% go to the matching brace
If you are using OOP programming this works (it looks for extra words before function[public, private, protected])
nmap vaf [{?\S* function<CR>:nohl<CR>v/{<CR>]}
As a bonus here is a wrapper around if
nmap vai [{?if<CR>:nohl<CR>v/{<CR>]}

Resources