This question is on how to have useful mappings for select ours or theirs on a conflict block like
<<<<<<< HEAD
ours code
=======
theirs code
>>>>>>> branch
Just paste the following code into your ~/.vimrc and use ,fc, ,so and ,st.
(complete .vimrc at https://github.com/brauliobo/gitconfig)
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Find Nearest
" Source: http://vim.1045645.n5.nabble.com/find-closest-occurrence-in-both-directions-td1183340.html
""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! FindNearest(pattern)
let #/=a:pattern
let b:prev = search(a:pattern, 'bncW')
if b:prev
let b:next = search(a:pattern, 'ncW')
if b:next
let b:cur = line('.')
if b:cur - b:prev == b:next - b:cur
" on a match
elseif b:cur - b:prev < b:next - b:cur
?
else
/
endif
else
?
endif
else
/
endif
endfunction
command! -nargs=1 FN call FindNearest(<q-args>)
nmap \ :FN<space>
""" Select between conflict blocks
" select ours
nmap <leader>so \<<<<<<<<CR>dd/=======<CR>V/>>>>>>><CR>d
" select theirs
nmap <leader>st \<<<<<<<<CR>V/=======<CR>dk/>>>>>>><CR>dd
" find next conflict
nmap <leader>fc /<<<<<<<<CR>
I have written a plugin for that: ConflictMotions. It offers the following mappings:
]x Go to [count] next start of a conflict.
]X Go to [count] next end of a conflict.
[x Go to [count] previous start of a conflict.
[X Go to [count] previous end of a conflict.
]z Go to [count] next conflict marker.
[z Go to [count] previous conflict marker.
ax "a conflict" text object, select [count] conflicts,
including the conflict markers.
az "a conflict section" text object, select [count]
sections (i.e. either ours, theirs, or base) including
the conflict marker above, and in the case of "theirs"
changes, also the ending conflict marker below.
iz "inner conflict section" text object, select current
section (i.e. either ours, theirs, or base) without
the surrounding conflict markers.
Related
suppose you have a path like this
/home/user/dev/project
I want to get the index of any / I want
like if I want the one before dev or the one before user
I don't get lua string patterns if there is a good documentation for it please link it
There are several ways to do this. Perhaps the simplest is using the () pattern element which yields a match position combined with string.gmatch:
for index in ("/home/user/dev/project"):gmatch"()/" do
print(index)
end
which prints
1
6
11
15
as expected. Another way to go (which requires some more code) would be repeatedly invoking string.find, always passing a start index.
Assuming that you probably want to split a string by slashes, that's about as simple using string.gmatch:
for substr in ("/home/user/dev/project"):gmatch"[^/]+" do
print(substr)
end
(the pattern finds all substrings of nonzero, maximal length that don't contain a slash)
Documentation for patterns is here. You might want to have a look at the subsection "Captures".
There are many ways to do so.
Also its good to know that Lua has attached all string functions on datatype string as methods.
Thats what #LMD demonstrates with the : directly on a string.
My favorite place for experimenting with such complicated/difficult things like pattern and their captures is the Lua Standalone Console maked with: make linux-readline
So lets play with the pattern '[%/\\][%u%l%s]+'
> _VERSION
Lua 5.4
> -- Lets set up a path
> path='/home/dev/project/folder with spaces mixed with one OR MORE Capitals in should not be ignored'
> -- I am curious /home exists so trying to have a look into
> os.execute('/bin/ls -Ah ' .. ('"%s"'):format(path:match('[%/\\][%u%l%s]+')));
knoppix koyaanisqatsi
> -- OK now lets see if i can capture the last folder with the $
> io.stdout:write(('"%s"\n'):format(path:match('[%/\\][%u%l%s]+$'))):flush();
"/folder with spaces mixed with one OR MORE Capitals in should not be ignored"
> -- Works too so now i want to know whats the depth is
> do local str, count = path:gsub('[%/\\][%u%l%s%_%-]+','"%1"\n') print(str) return count end
"/home"
"/dev"
"/project"
"/folder with spaces mixed with one OR MORE Capitals in should not be ignored"
4
> -- OK seems usefull lets check a windows path with it
> path='C:\\tmp\\Some Folder'
> do local str, count = path:gsub('[%/\\][%u%l%s]+','<%1>') print(str) return count end
C:<\tmp><\Some Folder>
2
> -- And that is what i mean with "many"
> -- But aware that only lower upper and space chars are handled
> -- So _ - and other chars has to be included by the pattern
> -- Like: '[%/\\][%u%l%s%_%-]+'
> path='C:\\tmp\\Some_Folder'
> do local str, count = path:gsub('[%/\\][%u%l%s%_%-]+','<%1>') print(str) return count end
C:<\tmp><\Some_Folder>
2
> path='C:\\tmp\\Some-Folder'
> do local str, count = path:gsub('[%/\\][%u%l%s%_%-]+','<%1>') print(str) return count end
C:<\tmp><\Some-Folder>
2
What I'm trying to do is to get the names of all TV shows on this Wikipedia page.
Ok, so I did this first:
property showsWebList : {}
tell application "Safari"
set loadDelay to 2 -- in seconds; test for your system
make new document at end of every document
set URL of document 1 to "http://en.wikipedia.org/wiki/List_of_television_programs_by_name"
delay loadDelay
set nrOfUls to do JavaScript "document.getElementById('mw-content-text').querySelectorAll('ul').length;" in document 1
set nrOfUls to nrOfUls - 1 as number
log nrOfUls
repeat with ws from 1 to nrOfUls
delay loadDelay
set nrOfLis to do JavaScript "document.getElementById('mw-content-text').getElementsByTagName('UL')[" & ws & "].querySelectorAll('li').length;" in document 1
set nrOfLis to nrOfLis - 1 as number
log nrOfLis
repeat with rs from 0 to nrOfLis
delay 0.3
set aShow to do JavaScript "document.getElementById('mw-content-text').getElementsByTagName('UL')[" & ws & "].getElementsByTagName('LI')[" & rs & "].getElementsByTagName('I')[0].getElementsByTagName('A')[0].innerHTML;" in document 1
if aShow is not "" or "missing value" then
copy aShow to end of showsWebList
end if
end repeat
end repeat
end tell
And this works exactly how I want it to. The problem is that it takes 15 minutes until it's done and you gotta have the safari document in front the whole time. So my thought was to pick up the whole code and parse it. Not that easy. This is how my code looks now:
tell application "Safari"
make new document at end of every document
set URL of document 1 to "http://en.wikipedia.org/wiki/List_of_television_programs_by_name"
delay 4
set orgHTML to do JavaScript "document.getElementById('mw-content-text').innerHTML;" in document 1
set orgHTML to orgHTML as text
set readyText to my extractBetween(orgHTML, "<li><i><a ", "</a></i></li>")
log (item 0 of readyText)
set removeArray to my extractBetween(readyText, "href", ">")
set completeArray to {}
repeat with rt from 0 to (count readyText)
repeat with ra from 0 to (count removeArray)
if (item ra of removeArray) is in (item rt of readyText) then
set completeName to trim_line((item rt of readyText), (item ra of removeArray), 1)
set end of completeArray to completeName
end if
end repeat
end repeat
log completeArray
end tell
on extractBetween(SearchText, startText, endText)
set tid to AppleScript's text item delimiters -- save them for later.
set AppleScript's text item delimiters to startText -- find the first one.
set liste to text items of SearchText
set AppleScript's text item delimiters to endText -- find the end one.
set extracts to {}
repeat with subText in liste
if subText contains endText then
copy text item 1 of subText to end of extracts
end if
end repeat
set AppleScript's text item delimiters to tid -- back to original values.
return extracts
end extractBetween
on trim_line(this_text, trim_chars, trim_indicator)
-- 0 = beginning, 1 = end, 2 = both
set x to the length of the trim_chars
-- TRIM BEGINNING
if the trim_indicator is in {0, 2} then
repeat while this_text begins with the trim_chars
try
set this_text to characters (x + 1) thru -1 of this_text as string
on error
-- the text contains nothing but the trim characters
return ""
end try
end repeat
end if
-- TRIM ENDING
if the trim_indicator is in {1, 2} then
repeat while this_text ends with the trim_chars
try
set this_text to characters 1 thru -(x + 1) of this_text as string
on error
-- the text contains nothing but the trim characters
return ""
end try
end repeat
end if
return this_text
end trim_line
Not that smooth and not working. Somehow it seems like I can't get the items out of the list, because it doesn't see it as a list item. Can someone help me out?
Cheers
I would recommend a different approach. DL the source, and then just grab the title between tags. The whole script takes under two seconds. Start with:
property baseURL : "http://en.wikipedia.org/wiki/List_of_television_programs_by_name"
set rawHTML to do shell script "curl '" & baseURL & "'"
set preTag to "\" title=\"" -- " title="
set otid to AppleScript's text item delimiters
set AppleScript's text item delimiters to preTag
set rawList to text items of rawHTML
set nameList to {}
repeat with eachLine in rawList
set theOff to offset of ">" in eachLine
set thisName to text 1 thru (theOff - 2) of eachLine
-- add some error checking here to skip the opening non-title hits, and to fine-tune the precise title string
set nameList to nameList & return & thisName
end repeat
set AppleScript's text item delimiters to otid
return nameList
Add a little error checking, and tweak which preTag and postTag fits best.
I suggest you make use of a specialized 3rd-party tool for this task, which can greatly speed things up.
Here's a solution using the multi-platform web-scraping CLI xidel:
A shell command to demonstrate its brevity and speed (takes less than 1 sec. on my system) - extracts all show names from the page:
xidel -e '//*[#id="mw-content-text"]/ul/li/i/a' https://en.wikipedia.org/wiki/List_of_television_programs_by_name
An equivalent AppleScript snippet - be sure to fill in the path to where you place xidel on your system below:
set targetUrl to "https://en.wikipedia.org/wiki/List_of_television_programs_by_name"
set xPathExpr to "//*[#id=\"mw-content-text\"]/ul/li/i/a"
# Fill in the path to `xidel` on your system here:
set xidelPath to "/path/to/xidel"
# Perform scraping and convert result into an AppleScript list.
set showNames to paragraphs of ¬
(do shell script ¬
quoted form of xidelPath & " -e " & quoted form of xPathExpr & " " & ¬
quoted form of targetUrl)
Here's another solution, use javascript to get the names without any AppleScript loop.
The javascript script takes less than one second to get the names.
tell application "Safari"
make new document at end of every document with properties {URL:"http://en.wikipedia.org/wiki/List_of_television_programs_by_name"}
delay 2 -- in seconds; test for your system
set showsWebList to do JavaScript "var a=new Array();var ul=document.getElementById('mw-content-text').querySelectorAll('UL'); for (var i=1;i<ul.length;i++){li=ul[i].querySelectorAll('LI'); for (var j=0; j< li.length; j++){try {var t=li[j].getElementsByTagName('I')[0].getElementsByTagName('A')[0].innerText; a.push(t)} catch(e) {}}} a;" in document 1
end tell
curl/sed/perl solution:
do shell script "curl 'http://en.wikipedia.org/wiki/List_of_television_programs_by_name' | sed -n '/0-9/,/NewPP/p' | sed -n '/^<li/ s/^.*title=.\\([^\"]*\\).*$/\\1/p' | perl -n -mHTML::Entities -e ' ; print HTML::Entities::decode_entities($_);'"
Here another solution using awk using a very simple script. If the line begins with <li><i> then remove html tags (gsub) and then print it. Then by using every paragraph of the return separated output is converted into a list.
set theURL to "http://en.wikipedia.org/wiki/List_of_television_programs_by_name"
every paragraph of (do shell script "curl " & theURL & " | awk '/^\\<li\\>\\<i\\>/{gsub(\"<[^>]*>\", \"\");print}'")
I am using TeXnicCenter to edit a LaTeX document.
I now want to remove a certain tag (say, emph{blabla}} which occurs multiple times in my document , but not tag's content (so in this example, I want to remove all emphasization).
What is the easiest way to do so?
May also be using another program easily available on Windows 7.
Edit: In response to regex suggestions, it is important that it can deal with nested tags.
Edit 2: I really want to remove the tag from the text file, not just disable it.
Using a regular expression do something like s/\\emph\{([^\}]*)\}/\1/g. If you are not familiar with regular expressions this says:
s -- replace
/ -- begin match section
\\emph\{ -- match \emph{
( -- begin capture
[^\}]* -- match any characters except (meaning up until) a close brace because:
[] a group of characters
^ means not or "everything except"
\} -- the close brace
and * means 0 or more times
) -- end capture, because this is the first (in this case only) capture, it is number 1
\} -- match end brace
/ -- begin replace section
\1 -- replace with captured section number 1
/ -- end regular expression, begin extra flags
g -- global flag, meaning do this every time the match is found not just the first time
This is with Perl syntax, as that is what I am familiar with. The following perl "one-liners" will accomplish two tasks
perl -pe 's/\\emph\{([^\}]*)\}/\1/g' filename will "test" printing the file to the command line
perl -pi -e 's/\\emph\{([^\}]*)\}/\1/g' filename will change the file in place.
Similar commands may be available in your editor, but if not this will (should) work.
Crowley should have added this as an answer, but I will do that for him, if you replace all \emph{ with { you should be able to do this without disturbing the other content. It will still be in braces, but unless you have done some odd stuff it shouldn't matter.
The regex would be a simple s/\\emph\{/\{/g but the search and replace in your editor will do that one too.
Edit: Sorry, used the wrong brace in the regex, fixed now.
\renewcommand{\emph}[1]{#1}
any reasonably advanced editor should let you do a search/replace using regular expressions, replacing emph{bla} by bla etc.
I'm trying to set up Vim to detect when a .tex file contains the command '\usepackage{sagemath}', and run a command accordingly. I've gotten to
:au BufReadPost,BufWritePost *.tex TTarget sagepdf
but that will fire for all .tex files, which isn't what I want.
Theres an example in my filetype.vim on how to destinguish html types. You can easily modify to suit your logic. Note the getline(n) =~ lines
" HTML (.shtml and .stm for server side)
au BufNewFile,BufRead *.html,*.htm,*.shtml,*.stm call s:FThtml()
" Distinguish between HTML, XHTML and Django
fun! s:FThtml()
let n = 1
while n < 10 && n < line("$")
if getline(n) =~ '\<DTD\s\+XHTML\s'
setf xhtml
return
endif
if getline(n) =~ '{%\s*\(extends\|block\)\>'
setf html.django_template
" setf htmldjango
return
endif
let n = n + 1
endwhile
setf html
endfun
First, you should consider using a modeline.
If you can't get what you want with a modeline, you can use your own function in autocmd, like this:
function! MyFunction()
...
endfunction
autocmd BufReadPost,BufWritePost *.tex call MyFunction()
and you probably can write a function that checks whether a certain pattern matches, and then runs whatever you want.
Given this line of code in C:
printf("%3.0f\t%6.1f\n", fahr, ((5.0/9.0) * (fahr-32)));
Is there a way to delete or yank from the first bold parenthesis to its matching parenthesis? I thought about df), but that only will get you to just after the 9.0.
Is there a similar way to get vim to grab everything between matching braces, regardless of newlines?
What about dib or di(.
It will delete the inner (...) block where the cursor is.
I love text-object motions and selections!
Various Motions: %
The % command jumps to the match of the item under the cursor. Position the cursor on the opening (or closing) paren and use y% for yanking or d% for deleting everything from the cursor to the matching paren.
This works because % is a "motion command", so it can be used anywhere vim expects such a command. From :help y:
["x]y{motion} Yank {motion} text [into register x]. When no
characters are to be yanked (e.g., "y0" in column 1),
this is an error when 'cpoptions' includes the 'E'
flag.
By default, "item" includes brackets, braces, parens, C-style comments and various precompiler statements (#ifdef, etc.).
There is a plugin for "extended % matching" that you can find on the Vim homepage.
You can read the documentation on % and related motion commands by entering :help various-motions in command mode.
object-select
There is another set of motion commands that you can use in Visual mode to select various text objects.
To solve your specific problem you would do the following:
printf("%3.0f\t%6.1f\n", fahr, ((5.0/9.0) * (fahr-32)));
^
Let's say your cursor is positioned at ^. Enter the following sequence to select the part you are looking for:
v2a)
First v enters Visual mode, then you specify that you want to go 2 levels of parens up. Finally the a) selects "a block". After that you can use d or x to delete, etc.
If you don't want to include the outer parens, you can use "inner block" instead:
v2i)
See :help object-select for the complete list of related commands.
To delete all that is inside a pair of parentheses, you can always issue di( and its derivatives.
Note :
As #porglezomb suggested in his comment, you can use a ("along with") instead of i ("inside") to include the parentheses. So, using da( deletes everything inside ( and ) including ( and ).
Deleting text inside the immediate outer pair of parentheses :
So, for this line of code
printf("%3.0f\t%6.1f\n", fahr, ((5.0/9.0) * (fahr-32)));
^ ^
| |
\_______\___---> Cursor range
assuming that your cursor is inside the above mentioned cursor range, you can issue the following commands :
di( --> Deletes '5.0/9.0'
ci( --> Substitutes '5.0/9.0'
yi( --> Yanks '5.0/9.0'
Deleting text inside the n-th outer pair of parentheses :
To grab everything inside the n-th outer pair of parentheses, just add n before the above command. So, with the same cursor position as above,
2di( --> Deletes '(5.0/9.0) * (fahr-32)'
2ci( --> Substitutes '(5.0/9.0) * (fahr-32)'
2yi( --> Yanks '(5.0/9.0) * (fahr-32)'
3di( --> Deletes '"%3.0f\t%6.1f\n", fahr, ((5.0/9.0) * (fahr-32))'
3ci( --> Substitutes '"%3.0f\t%6.1f\n", fahr, ((5.0/9.0) * (fahr-32))'
3yi( --> Yanks '"%3.0f\t%6.1f\n", fahr, ((5.0/9.0) * (fahr-32))'
You can use d% for deleting and y% for yanking.
Place your cursor on the first parenthesis, then press v%y or v%d.
Try ci[block-surrounder]
In your case, place the cursor anywhere between the 2 parenthesis that you highlighed and try the keys: ci(
As answer of David Norman says,
Place your cursor on the first parenthesis, then press v%y or v%d.
Explanation from http://vimdoc.sourceforge.net/htmldoc/vimindex.html:
tag char note action in Normal mode
------------------------------------------------------------------------------
|v| v start characterwise Visual mode
|%| % 1 find the next (curly/square) bracket on
this line and go to its match, or go to
matching comment bracket, or go to matching
|d| ["x]d{motion} 2 delete Nmove text [into buffer x]
This means it will select everything between and including the two brackets (%) while showing the selection to you visually (v) and then yank/copy y or delete/cut d it. (To the default buffer.)
You can put/paste with p.
Made this answer to "teach myself to fish".