How to jump to first uncommented out statement in vim? - regex

I'm using /print to search for my uncommented-out print statements as I want to comment them out. I know I could use search and replace to first remove all the comments, and then apply them, but I simply want to find the next uncommented out print statement, and I can't work out how to.
E.g. I have :
#print fooVal
#... do stuff
#print barF
#... more stuff
print gold # <-- I want to use vim to jump straight to this line
I want to match this so I don't have to cycle through all the print statements (even the commented-out ones) just to find the one print statement that is without #.
I've tried using :s/^\s+print and /^print but vim does not like it. Also, I looked here, but I could not find the info.

In your case no spaces before print. So try to use '*' instead of '+'.
This works for me: /^\s*print
Less convenient pattern should highlight uncommented lines with print: /^[^#]*\s*print

In your case #Taky's solution is the best I think, but I noticed some comments on vim's regexp. I've studied this the last days, so perhaps it's a good idea to write it down.
In vimworld the use of e.g. *, ^ and $ as regexp special characters is called "magic" (set magic is default). As default + is not a regexp character and has to be used as \+ to mean "regexp +". However with small changes it can be "magic" too, read this: vim help - search patterns (the same as in vim editor, but as HTML, and with a good search function at the top).
See also vim help - pattern
Here is a little short guide (rules are overruling down the list):
settings:
:set ignorecase to ignore case in search and replace,
:set smartcase for ignoring case as long as no upper case letter is used (ignorecase must be on for it to work).
:set magic to be able to use some characters as regexp special characters, e.g. *, without having to precede them with \. This is default (I think).
Rules in search pattern (overrules settings)
\c ignore case, \C case sensitive
Use as e.g. /\cxxx for "ignore case", /\Cxxx for case sensitive (\c is the same as flag i in replace syntax as s/xxx/yyy/i.
\m use "magic" (same as setting magic), \M no "magic".
Here is the interesting part, to use + in vim patterns:
\v described as "very magic", that is what we all are used to when using regexp I think.
\V "very nomagic", ALL is literal, only \ has a special meaning.
Now, + can be used directly as in /\v\s+print (but for you it's better to use * in that particular case, + won't find "plugin" that starts the line).
E.g. also { expressions must have \ if \v isn't used.
Tip: do these mappings in .vimrc to always use \v in search patterns:
" To get 'normal' behavior for regexps (use "\V" to avoid)
nnoremap / /\v
vnoremap / /\v
(And it's very easy to just "backspace" away the \vwhen it's unwanted).

Related

In vim is it possible to use the same regex escaping rules for :substitute and search?

If I do a search (with magic) like: /\v\$[^ ]+\$ I get matches in my file, however if I substitute with the same search pattern: :%smagic/\$[^ ]+\$//, I need to escape the +.
Is it possible to make the escaping behave in the same way for magic search and magic substitute?
:smagic is like :s with 'magic' on, which is the default (and should not be changes for plugin portability, as its :help notes). The \v special atom specifies very magic, so additional atoms (like \+) do not need the preceding backslash.
There's no corresponding :s command variant, but why don't you just keep the \v in the pattern:
:%s/\v\$[^ ]+\$//
(Also, if you've previously searched for that, you can leave off the pattern completely: :%s///.)
use \v instead of magic
:%s/\v\$[^ ]+\$//

Vim: Incsearch for replace queries

I noticed I could use regex functions with search in vim, and I could see hilights while I typed by setting incsearch. But that didn't work for search and replace queries like this one:
:%s/std::regex\s\([_a-zA-Z]*\)(/regex_t \1 = dregc(/gc
That one surprised me when it actually worked.
Are there settings or plugins for vim that, like incsearch but better, will highlight your replace query as you type? Just highlighting the matches would be pretty neat, but putting the old and new strings next to eachother in different highlighting colors would be a godsend, because I might not be sure about the backreference.
Not a direct answer to your question, but traditionally in Vim you craft your search regex first, as in:
/regex
Then you hit enter to execute it. The settings :set hlsearch and :set incsearch make this easy to see visually. Then you can just do:
:%s//replace
With no search specified, :%s (substitute acting on %, a shorctut meaning all lines in the file) will use the last search term you specified.
Going one step further, you could then do
:%s/~/replace2
Which replaces your last substitution (in this case, replace1) with replace2.
Unrelated, it may be useful for you to put this in your .vimrc:
set gdefault
Which will make all replaces global by default, so you don't need the /g flag after every :%s command.
You might be looking for vim-over?
This is a plugin that: (to clarify, let's say we're doing :%s/foo/bar/g.) i) highlights matches for substitutions in the buffer (foo) and optionally ii) previews what's after replacement (bar).

How many backslashes are required to escape regexps in emacs' "Customize" mode?

I'm trying to use emacs' customize-group packages to tweak some parts of my setup, and I'm stymied. I see things like this in my .emacs file after I make changes with customize:
'(tramp-backup-directory-alist (quote (("\\\\`.*\\\\'" . "~/.emacs.d/autobackups"))))
This was the result of putting the following into the customize text field:
Regexp matching filename: \\`.*\\'
This is a representative sample: I'm actually trying to change several things that want a regexp, and they all show this same problem. How many layers of quoting are there, really? I can't seem to find the magic number of backslashes to get the gosh-dang thing to do what I'm asking it to, even for the simplest regular expressions like .*. Right now, the given customization produces - nothing. It makes no change from emacs' default behavior.
Better yet, where on earth is this documented? It's a little difficult to Google for, but I've been trying quite a few things there as well as in the official documentation and the Emacs wiki. Where is an authoritative source for how many dang backslashes one needs to make a regular expression in customize-mode actually work - or at the very least, to fail with some kind of warning instead of failing silently?
EDIT: As so often happens with questions asked in anger, I was asking the wrong question. Fortunately the answers below, led me to the answer to the question that I needed, which was about quoting rules. I'm going to try to write down what I learned here, because I find the documentation and Googleable resources to be maddeningly obscure about this. So here are the quoting rules I found by trial and error, and I hope that they help someone else, inspire correction, or both.
When an emacs customize-mode buffer asks you for a "Regexp matching filename", it is being, as emacs often is, both terse and idiosyncratic (how often the creator's personality is imparted to the creation!). It means, for one thing, a regexp that will be compared to the whole path of the file in search of a match, not just to the name of the file itself as you might assume from the term "filename". This is the same sense of "filename" used in emacs' buffer-file-name function, for example.
Further, although if you put foo in the field, you'll see "foo" (with double-quotes) written to the actual file, that's not enough quoting and not the right quoting. You need to quote your regexp with the quoting style that, as far as I can tell, only emacs uses: the ``backtick-foo-single-quote'`scheme. And then you need to escape that, making it \`backslash-backtick-foo-backslash-single-quote\' (and if you think that's a headache to input in Markdown, it's more so in emacs).
On top of this, emacs appears to have a rule that the . regexp special character does not match a / at the beginning of filenames, so, as was happening to me above, the classic .* pattern will appear to match nothing: to match "all files", you actually need the regexp /.*, which then you stuff into the quote format of customize-mode to produce \`/.*\', after which customize paints another layer of escaping onto it and writes it to the customization file.
The final result for one of my efforts - a setting such that #autosave# files don't gunk up the directory you're working in, but instead all live in one place:
(custom-set variables
'(auto-save-file-name-transforms (quote (
("\\`/[^/]*:\\([^/]*/\\)*\\([^/]*\\)\\'" "~/.emacs.d/autobackups/\\2" t)
("\\`/.*/\\(.*?\\)\\'" "~/.emacs.d/autobackups/\\1" t)
))))
Backslashes in elisp are a far greater threat to your sanity than parentheses.
EDIT 2: Time for me to be wrong again. I finally found the relevant documentation (through reading another Stack Overflow question, of course!): Regexp Backslash Constructs. The crucial point of confusion for me: the backtick and single quote are not quoting in this context: they're the equivalent of perl's ^ and $ special characters. The backslash-backtick construct matches an empty string anchored at the beginning of the string being checked for a match, and the backslash-single-quote construct matches the empty string at the end of the string-under-consideration. And by "string under consideration," I mean "buffer, which just happens to contain only a file path in this case, but you need to match the whole dang thing if you want a match at all, since this is elisp's global regexp behavior."
Swear to god, it's like dealing with an alien civilization.
EDIT 3: In order to avoid confusing future readers -
\` is the emacs regex for "the beginning of the buffer." (cf Perl's \A)
\' is the emacs regex for "the end of the buffer." (cf Perl's \Z)
^ is the common-idiom regex for "the beginning of the line." It can be used in emacs.
$ is the common-idiom regex for "the end of the line." It can be used in emacs.
Because regex searches across multi-line bodies of text are more common in emacs than elsewhere (e.g. M-x occur), the backtick and single-quote special characters are used in emacs, and as best as I can tell, they're used in the context of customize-mode because if you are considering generic unknown input to a customize-mode field, it could contain newlines, and therefore you want to use the beginning-of-buffer and end-of-buffer special characters because the beginning and end of the input are not guaranteed to be the beginning and end of a line.
I am not sure whether to regret hijacking my own Stack Overflow question and essentially turning it into a blog post.
In the customize field, you'd enter the regexp according to the syntax described here. When customize writes the regexp into a string, any backslashes or double-quote chars in the regexp will be escaped, as per regular string escaping conventions.
So in short, just enter single backslashes in the regexp field, and they'll get correctly doubled up in the resulting custom-set-variables clause written to your .emacs.
Also: since your regexp is for matching filenames, you might try opening up a directory containing files you'd like to match, and then run M-x re-builder RET. You can then enter the regexp in string-escaped format to confirm that it matches those files. By typing % m in a dired buffer, you can enter a regexp in unescaped format (ie. just like in the customize field), and dired will mark matching filenames.

Perform a non-regex search/replace in vim

When doing search/replace in vim, I almost never need to use regex, so it's a pain to constantly be escaping everything, Is there a way to make it default to not using regex or is there an alternative command to accomplish this?
As an example, if I want to replace < with <, I'd like to just be able to type s/</</g instead of s/\</\&lt\;/g
For the :s command there is a shortcut to disable or force magic. To turn off magic use :sno like:
:sno/search_string/replace_string/g
Found here: http://vim.wikia.com/wiki/Simplifying_regular_expressions_using_magic_and_no-magic
Use this option:
set nomagic
See :help /magic
The problem is primarily caused by confusion about the role of the & in the replacement string. The replacement string is not a reg-ex, although it has some special characters, like &. You can read about role of & in replacement string here: :h sub-replace-special .
I suspect the main problem for OP is not necessarily typing the extra backslashes, but rather remembering when a backslash is needed and when not. One workaround may be to start making use of "replacement expressions" when unsure. ( See :h sub-replace-expression.) This requires putting a `\=' in replacement string but for some people it may give you more natural control over what's being substituted, since putting a string literal in single quotes will give you the replacement string you want. For example, this substitute does what OP wants:
:s/</\='<'/g
If you want to search literally, you can use the \V regex atom. This almost does what you want, except that you also need to escape the backslash. You could define your own search command, that would search literally. Something like this:
:com! -nargs=1 Search :let #/='\V'.escape(<q-args>, '\/')| normal! n
And then use :Search /foobar/baz
For Substitute, you could then after a :Search command simply use
:%s//replace/g
since then Vim would implicitly pick up the last search item and use the for replacing.
(Just want to give you some ideas)
Here’s how to disable regular expression search/replace only in command mode:
autocmd CmdWinEnter * set nomagic
autocmd CmdWinLeave * set magic
All plugins that depends on regular expression such as white-space remover should works as usual.
Have you enabled magic?
:set magic
Try the Edit Find and replace on the menu bar.

Regex search and replace in VI

I have a document with lots of <swf...>.....</swf> in it. I would like to remove all these. Using vi when i type
:%s/\<swf[^\/swf>]+\/swf\>//g
I was hoping this would work, but it doesn't match anything.
You can remove all those from the buffer with this command:
:%s!<swf.\{-}/swf>!!
if you also have tags that might be split on two lines, you can add the \_ modifier to make . match newlines too:
:%s!<swf\_.\{-}/swf>!!
this assuming you want to remove both the tags and what they contain, if you just want to get rid of the tags and keep the content
:%s!</\?swf.\{-}>!!
Notes:
you don't need to escape < or >
you can choose whatever pattern delimiter you wish: Vim will use the first character you put after the s in the substitute command: this takes away the need to escape forward slashes in your pattern
EDIT: extending my answer after your comment
this is exactly like /STRING/REPLACE/g I only used a ! instead of / so that I don't have to quote the backslash in the pattern (see my second point above)
I didn't add the g modifier at the end since I have :set gdefault in my .vimrc since forever (it means that by default Vim will substitute all matches in a line instead of just the first, thus reverting the meaning of /g)
\{-} is the "ungreedy" version of the * quantifier, i.e. it matches 0 or more of the preceding atom but take as few as possible -- this helps you make sure that your search pattern will extend to the first "closing tag" instead of the last.
HTH
The problem here is that the [] is a character class, so you are telling it that between the swf opening and closing tags, the letters s, w and f cannot appear anywhere, in any order.
You could try a non-greedy match instead:
\<swf.\{-}\/swf\>
Note that . does not allow newline by default.
I don't use Vim though, so I used this guide to discover the syntax. I hope it is correct.