Function to open a file and navigate to a specified line number - function

I have the output of recursive grep (actually ag) in a buffer, which is of the form filename:linenumber: ... [match] ..., and I want to be able to go to the occurrence (file and line number) currently under the cursor. This told me that I could execute normal-mode movements, so after extracting the file:line portion, I wrote this function:
function OpenFileNewTab(name)
let l:pair=split(a:name, ":")
execute "tabnew" get(l:pair, 0)
execute "normal!" get(l:pair, 1) . "G"
endfunction
It is supposed to open the specified file in a tab and then do <lineno>G, like I am able to do manually, to go to the specified line number. However, the cursor just stays on line 1. What am I doing wrong?
This question, by title alone, would be an exact duplicate, but it talks locating symbols in other files, while I already have the locations at hand.
Edit: My mappings for grep / ag are as follows:
nnoremap <Leader>ag :execute "new \| read !ag --literal -w" "<C-r><C-w>" g:repo \| :set filetype=c<CR>
nnoremap <Leader>gf ^v2t:"zy :execute OpenFileNewTab("<C-r>z")<CR>
To get my grep / ag results, I put the cursor on the word I want to search and enter <leader>ag, then, in the new buffer, I put the cursor on a line and enter <leader>gf - it selects from the start up to the second colon and calls OpenFileNewTab.
Edit 2: I'm on Cygwin, if it is of any importance - I doubt it.

Why don't you set &grepprg to call ag ?
" according to man ag
set grepprg=ag\ --vimgrep\ $*
set grepformat=%f:%l:%c:%m
" And then (not tested)
nnoremap <Leader>ag :grep -w <c-r><c-w><cr>
As others have said in the comments, you are just trying to emulate what the quickfix windows already provides. And, we are lucky vim can call grep, and it has a variation point to let us specify which grep program we wish to use: 'grepprg'.

Use file-line plugin. Pressing Enter on a line in the quicklist will normally open that file; file-line will make any filename of the form file:line:column (and several other formats) to open file and position to line and column.

I only found this (old) thread after I posted the exact same question on vi.stackexchange: https://vi.stackexchange.com/q/39557/44764. To help anyone who comes looking, I post the best answer to my question below as an alternative to the answers already given.
The gF command, like gf, opens the file in a new tab but additionally it also positions the cursor on the line after the colon. (I note the OP defines <leader>gf so maybe vim/neovim didn't auto-define gf or gF at the time this thread was originally created.)

Related

How to add html attributes and values for all lines quickly with vim and plugins?

My os:debian8.
uname -a
Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.39-1+deb8u2 (2017-03-07) x86_64 GNU/Linux
Here is my base file.
home
help
variables
compatibility
modelines
searching
selection
markers
indenting
reformatting
folding
tags
makefiles
mapping
registers
spelling
plugins
etc
I want to create a html file as bellow.
home
help
variables
compatibility
modelines
searching
selection
markers
indenting
reformatting
folding
tags
makefiles
mapping
registers
spelling
plugins
etc
Every line was added href and id attributes,whose values are line content pasted .html and line content itself correspondingly.
How to add html attributes and values for all lines quickly with vim and plugins?
sed,awk,sublime text 3 are all welcomed to solve the problem.
$ sed 's:.*:&:' file
home
help
variables
compatibility
modelines
searching
selection
markers
indenting
reformatting
folding
tags
makefiles
mapping
registers
spelling
plugins
etc
if you want to do this in vi itself, no plug-in neccessary
Open the file, type : and insert this line as the command
%s:.*:&
it will make all the substitutions in the file.
sed is the best solution (simple and pretty fast here) if your are sure of the content, if not it need a bit of complexity that is better treated by awk:
awk '
{
# change special char for HTML constraint
Org = URL = HTML = $0
# sample of modification
gsub( / /, "%20", URL)
gsub( /</, "%3C", HTML)
printf( "%s\n", URL, Org, HTML)
}
' YourFile
To complete this easily in Sublime Text, without any plugins added:
Open the base file in Sublime Text
Type Ctrl+Shift+P and in the fuzzy search input type syn html to set the file syntax to HTML.
In the View menu, make sure Word Wrap is toggled off.
Ctrl+A to select all.
Ctrl+Shift+L to break selection into multi-line edit.
Ctrl+C to copy selection into clipboard as multiple lines.
Alt+Shift+W to wrap each line with a tag-- then tap a to convert the default <p> tag into an <a> tag (hit esc to quit out of any context menus that might pop up)
Type a space then href=" -- you should see this being added to every line as they all have cursors. Also you should note that Sublime has automatically closed your quotes for you, so you have href="" with the cursor between the quotes.
ctrl+v -- this is where the magic happens-- your clipboard contains every lines worth of contents, so it will paste each appropriate value into the quotes where the cursor is lying. Then you simply type .html to add the extension.
Use the right arrow to move the cursors outside of the quotes for the href attribute and follow the two previous steps to similarly add an id attribute with the intended ids pasted in.
Voila! You're done.
Multi-line editing is very powerful as you learn how to combine it with other keyboard shortcuts. It has been a huge improvement in my workflow. If you have any questions please feel free to comment and I'll adjust as needed.
With bash one-liner:
while read v; do printf '%s\n' "$v" "$v" "$v"; done < file
(OR)
while read v; do echo "$v"; done < file
Try this -
awk '{print a$1b$1c$1d}' a='' d='' file
home
help
variables
compatibility
modelines
searching
selection
markers
indenting
reformatting
folding
tags
makefiles
mapping
registers
spelling
plugins
etc
Here I have created 4 variable a,b,c & d which you can edit as per your choice.
OR
while read -r i;do echo ""$i";done < f
home
help
variables
compatibility
To execute it directly in vim:
!sed 's:.*:&:' %
In awk, no regex, no nothing, just print strings around $1s, escaping "s:
$ awk '{print "" $1 ""}' file
home
help
If you happen to have empty lines in there just add /./ before the {:
/./{print ...
list=$(cat basefile.txt)
for val in $list
do
echo ""$val"" >> newfile.html
done
Using bash, you can always make a script or type this into the command line.
This vim replacement pattern handles your base file:
s#^\s*\(.\{-}\)\s*$#\1#
^\s* matches any leading spaces, then
.\{-} captures everything after that, non-greedily — allowing
\s$ to match any trailing spaces.
This avoids giving you stuff like home .
You can also process several base files with vim at once:
vim -c 'bufdo %s#^\s*\(.\{-}\)\s*$#\1# | saveas! %:p:r.html' some.txt more.txt`
bufdo %s#^\s*\(.\{-}\)\s*$#\1# runs the replacement on each buffer loaded into vim,
saveas! %:p:r.html saves each buffer with an html extension, overwriting if necessary,
vim will open and show you the saved more.html, which you can correct as needed, and
you can use :n and :prev to visit some.html.
Something like sed’s probably best for big jobs, but this lets you tweak the conversions in vim right after it’s made them, use :u to undo, etc. Enjoy!

IF and ! = ns2 error

I have a problem with path in a tcl file. I tried to use
source " /tmp/mob.tcl "
and this path in bash file :
/opt/ns-allinone-2.35/ns-2.35/indep-utils/cmu-scen-gen/setdest/setdest -v 1 -n $n -p 10 -M 64 -t 100 -x 250 -y 250 >> /tmp/mob.tcl
The terminal give me this output:
..."
(procedure "source" line 8)
invoked from within
"source "/tmp/mob.tcl" "
(file "mobilita_source.tcl" line 125)
How I can do this?
Firstly, this:
source " /tmp/mob.tcl "
is very unlikely to be correct. The spaces around the filename inside the quotes will confuse the source command. (It could be correct, but only if you have a directory in your current directory whose name is a single space. That's really unlikely, unless you're a great deal more evil than I am.)
It really helps a lot if you stop making this error.
Secondly, the error message is both
Incomplete, with just an ellipsis instead of a full error on the first line
Really worrying, with source claimed to be a procedure (second line of that short trace).
It's legal to make a procedure called source, and sometimes the right thing to do, but if you're doing it then you have to be ever so careful to duplicate the semantics of the standard Tcl command or odd things will happen.
Thirdly, you've got a file of what is apparently generated code, and you're hitting a problem in it, and you're not telling us what is on/around line 125 of the file (the error trace is pretty clear on that front) or in the contents of the source procedure (which is non-standard; the standard source is implemented in C) and you're expecting us to guess what's going wrong for you??? Seriously?
Tcl error traces are usually quite clear enough for you to figure out what went wrong and where. If there's an unclear error, and it didn't come from user code (by calling error or return -code error) then let us know; we'll help (or possibly even change Tcl to make things clearer in the future). But right now, there's a complete shortage of information.
Here's an example of what a normal source error looks like:
% source /tmp/foo/bar/boo
couldn't read file "/tmp/foo/bar/boo": no such file or directory
% puts $errorInfo
couldn't read file "/tmp/foo/bar/boo": no such file or directory
while executing
"source /tmp/foo/bar/boo"
If a script generates an error directly, it's encouraged to be as clear as that, but we cannot enforce it. Sometimes you have to be a bit of a detective yourself…

EMACS find-grep command switching windows

I have the following in my .emacs
(defun find-in-workspace(term)
(interactive "sSearchInWorkspace: \n")
(grep-find (concat "grep -rnH --include=\*.{c,cpp,h} --include=-e '" term "' /home/workspaces/*")))
which is just a wrapper around grep-find so that it can search all the files in my workspace.
My problem is with the grep buffer. I would like to keep my cursor in the grep buffer's window when I select items from it so that I can quickly browse through the code, but selecting a line will automatically moves my cursor to the other window, which adds up in keystrokes when I have a list of over 5 items. Is there anyway I can build this functionality into this function, or change a setting for grep-find? I've been searching but haven't found a solution.
See the functions next-error and previous-error. They leave the grep buffer, but they work from anywhere, so, for example, if you bind next-error to a convenient a key then you can keep pressing it and it will iterate over the grep buffer.
There might be some options of grep behavior, that you might find if you dig in the lisp/progmodes/grep.el from the source, but I really think it might be better and easier to have a look of GrepPlus library which bring many enhancement of emacs grep.
Otherwise you could also use occur and see how you could customize it. In occur, when you are in the match buffer, you can it C-o instead of Ret, which will show in the other buffer the match you selected, keeping your cursor in the match buffer. Difference with grep, is that it only works with opened buffer. I'm rather sure grep+ might have the equivalent. You should have a look
There are two functions for doing exactly what you want: previous-error-no-select and next-error-no-select.
Also, you may find useful next-error-follow-minor-mode.

Seeking a vim function to insert the text behind a hyperlink

I'm writing a book. I have a large notes file, with hyperlinks of interest. I'd like to be able to move the cursor over a hyperlink, execute a command, and have the text of the webpage inserted for reading, cutting, and modifying. Ideally, it would only be the readable text rather than the full HTML, but I'll take what I can get (or what I can wget, if that's the right shell function).
Surely such a thing has already been put together, but searches for "vim insert text hyperlink" and such are not very helpful. Have you seen this function?
With your mouse cursor on a hyperlink, execute
:rC-rC-aEnter
This will insert the raw contents on the following line.
To preprocess:
:r !links -dumpC-rC-aEnter
Of course, you can map this to a key:
:nnoremap <F6> :r !links -dump <C-r><C-a><CR>
Various notes:
If you have quoted urls, you might not be happy about C-rC-a because the quotes will get included. Consider doing
:se iskeyword+=/,:,.
And use C-rC-w instead. Alternatively,
:se isfname-="
allows you to use C-rC-f instead.
If you don't want to tinker with any of your settings, consider creating a function that saves and restores the value of &iskeyword or &isfname. To bring out the big gun, write a regex for URLs and use that:
func! ReadFromUrl()
let url = substitute(getline('.'), '\c\v^.*((https?|ftp|file)://[a-z0-9.:/%+()]+).*$', '\1', '')
exec 'r! links -dump "' . url . '"'
endf
command! ReadFromUrl call ReadFromUrl()
nnoremap! <F6> ReadFromUrl<CR>
Move the cursor to the hype-link, and type this command:
:exec 'r!wget -q -O- ' getline('.') ' | html2text'
It'll append the content of the hype-link after the hype-link.
To make this command work, you need install html2text.
Good luck!

Vim execute in function behaving differently

I am playing around with a small Vim function that will highlight whitespace.
But the execute command is behaving differently than when its called directly.
So the function looks like this:
function! ShowWhitespace()
execute "/\\s\\+$"
endfunction
And it is mapped as:
command! SW call ShowWhitespace()
When :SW is executed it simply searches and gets the cursor to where whitespace exists.
However, when I do this in the command line:
:exe "/\\s\\+$"
It highlights correctly the whitespace. I am also making sure that highlightsearch is always on, so this is not an issue of having it on or off.
As a side note, I need to have this in a function because I want to have other things that have not yet been added to it for flexibility (like toggling for example).
Why would this behave differently in a function than executing it directly? I've written a wealth of functions in Vim and never seen this work different.
EDIT & Solution:
So it seems Vim doesn't like having functions altering searches. As soon as a function exits the search patterns are cleared (as pointed out by :help function-search-undo.
This might look ugly but does what I was looking to do in the first place:
command! -bang Ws let orig_line = line('.') | exe ((<bang>0)?":set hls!":":set hls") | exe '/\s\+$' | exe orig_line
Explained bit by bit:
Maps the (bang-accepting) Ws command to the following actions:
saves the original line where cursor is located
depending on bang or no bang (e.g. :Ws! or :Ws) it sets highlightsearch
Executes the search to find whitespace
Goes back to the original line if it changed
If you don't wish to move the cursor (and never do it), just set #/ to the correct search pattern, i.e.:
let #/ = '\s\+$'
NB: the function should have moved the cursor.