how to insert new line in vimscript substitiute function - function

I want this sentence:
My, sentence.
To be like this:
My,
sentence.
My function is:
function! ParseLine()
let line = getline(".")
echom line
let parsedLine = substitute(line, ",", "\v\\v\\0\\r\r\\n\r\\<cr>\<cr><cr>\\^M\r&\^#\\^#", "g")
call setline(".", parsedLine)
endfunction
What I get when running this function:
Myvv,^M^M^#^M<cr>^M<cr>^M^M,^#^# sentence.

The easiest way:
function! ParseLine()
exec 's/,\s*/,\r/g'
endfunction
Or if you want to first call substitute() then "set" that line:
function! ParseLine()
let parsedLine = substitute(getline('.'), ',\s*', ',\n', "g")
let o = #o
let #o = parsedLine
normal! V"op
let #o=o
endfunction

The way you are trying to do it is never going to work because you can't use newlines in the setline function.
If you try to use setline on a string that contains a newline you will get an error. However, you could do this with an execute "normal! ..." command:
function! ParseLine()
execute "normal! 0f,a\n"
endfunction
That should find the , and insert a newline after it, giving you the result you want.
Note that you have to use execute "normal! ..." as opposed to normal! ... because normal won't understand that \n is a special character and you would get:
My,\n Sentence

Related

Brackets For Function Name

Hey guys This is my first lua script, its a speedhack for a game (offline dont worry) and i keep getting an error with the function name, im not sure what to fix exactly.
function Speedhack1()
boost = 1.5
if (readbytes{'[_speed]') `- nil) then
writeFloat ('[_speed]+DC', readFloat('[_speed]+DC')*boost)
writeFloat ('[_speed]+E0', readFloat('[_speed]+E0')*boost)
writeFloat ('[_speed]+E4', readFloat('[_speed]+E4')*boost)
end
end
createHotkey(speedhack1, VK_UP)
function Speedhack2()
boost = 0.5
if (readbytes{'[_speed]') `- nil) then
writeFloat ('[_speed]+DC', readFloat('[_speed]+DC')*boost)
writeFloat ('[_speed]+E0', readFloat('[_speed]+E0')*boost)
writeFloat ('[_speed]+E4', readFloat('[_speed]+E4')*boost)
end
end
createHotkey(speedhack2, VK_DOWN)
This is the error it throws back at me when trying to execute:
Error in script Script 1 : [string "function Speedhack1()
..."]:3: '}' expected near ')'
when i try to replace ")" with "}" it just yells at me the reverse. very confused lol
I think the issue is the curly braces in "readbytes{". Could you please try to replace that with "("?
The code that causes the error here is in line 3
if (readbytes{'[_speed]') `- nil) then
In Lua the argument you pass for a function must have an opening and ending of ( and ) respectively. Therefore as you can note in line 3 the argument you have passed for readbytes has an opening of { which is the cause of the error. In order to resolve this replace { with (

function in vim to fix quotations

I'm trying to create a function in vim to be activated by a shortcut and go through my document and re-quote the strings using Python-like syntax. That is:
"something" -> 'something'
'''docstring''' -> """docstring"""
"'" -> "'" (stays the same)
'"' -> '"' (stays the same)
Given my limited knowledge of python functions I came up with this in my .vimrc:
function! Fixquotes()
:silent! %s/"\([^"]*\)"/'\1'/g
:silent! %s/'""/"""/
:silent! %s/""'/"""/
:silent! %s/'''/"""/g
endfunction
inoremap <C-f> <esc>mk:call Fixquotes()<CR>`kli
noremap <C-f> mk:call Fixquotes()<CR>`k
It kinda work, except for the case where I have "'" since the first substitution will turn it into ''' and the last will turn it into """.
Does anyone have any recommendation?
give this a try:
function! Fixquotes()
:silent! %s/\v([^'"]|\_^)\zs"([^"']*)"\ze([^'"]|\_$)/'\2'/g
:silent! %s/'''/"""/g
endfunction

Why this method's return part is not working

I am trying to write a method which returns a new value. Following code is modified from here:
| stripChars |
stripChars := [ :string :chars |
str := string reject: [ :c | chars includes: c ].
str displayNl. "THIS WORKS."
^ str "THIS DOES NOT WORK."
].
newstr := stripChars
value: 'She was a soul stripper. She took my heart!'
value: 'aei'.
newstr displayNl.
Although above function creates new string and displays it, there is error in returning or receiving returned new string:
$ gst make_fn_ques.st
Sh ws soul strppr. Sh took my hrt!
Object: 'Sh ws soul strppr. Sh took my hrt!' error: return from a dead method context
SystemExceptions.BadReturn(Exception)>>signal (ExcHandling.st:254)
SystemExceptions.BadReturn class(Exception class)>>signal (ExcHandling.st:151)
String(Object)>>badReturnError (Object.st:1389)
UndefinedObject>>executeStatements (make_fn_ques.st:10)
nil
Where is the problem and how can this be solved? Thanks for your help.
The
^ str
does not return from the block (stripChars), but from the enclosing method instead (non-local return).
Apparently GNU Smalltalk does not allow you to return from the script that you pass to gst in this way.
Just drop the ^, and keep only str as the last expression of the block. That will cause str to be the return value of the block.

vimscript: commands that work in mappings, but not in functions

How can I rewrite these 2 commands, which work fine in a mapping, so that they will work in a function?
:if has_key(glos,#g)==1<cr>:let #j=eval('glos.'.#g)<cr>
The function concerned is executed by vim without comment, but #j remains unchanged, as if they had failed, but no message/error is generated.
Here is the complete code involved, the command that loads the dictionary, the function that does not work, and the mapping from that function that does.
" read the glossary into the dictionary, glos
let glos=eval(join(readfile("glossary.dict")))
" 2click item of interest and this will
" send image filepath to xv
" if item all-caps find same at start of its line
" If capitalized at eol find same at start of its line
" if all lower-case at eol find next occurrence of same
" look lower-case or capitalized word up in glossary.txt
" find _\d\+ (page no.) alone on its line in text
com! F call F()
function! F()
normal "ayiw"cyE"by$
let #c=substitute(#c,"[,.?':;!]\+","","g")
if #c=~'images\/ss\d\d\d*'
let #i='!display -geometry +0+0 '.#c.' &'
pkill display
#i
elseif #c==toupper(#c)
let #n=search('^'.#c,'sw')
elseif #c!=#b
let #f=3
let #g=tolower(#c)
while #f>0
try
let #j=eval('glos.'.#g)
catch
let #f=#f-1
let #g=strpart(#g,0,strlen(#g)-1)
continue
endtry
break
endwh
if #f>0
let #h=substitute(#j," glosimgs.*",'','')
if #h!=#j
let #i='!xv -geometry +0+380 '.substitute(#j,'^.\{-}\( glosimgs.*\)$','\1','').' &'
!pkill xv
#i
endif
echo #h
else
echo 'No matching entry for '.#c
endif
elseif #c=~'\u\l\+$'
let #n=search('^'.#c,'sw')
elseif #c=~'\l\+$'
norm *
elseif #c=~'^_\w\+$'
let #/='^'.#c.'$'
norm nzz
endif
endfunction
map <silent> <2-LeftMouse> "ayiw"cyE"by$:let #c=substitute(#c,"[,.?':;!]\+","","g")<cr>:if #c=~'images\/ss\d\d\d*'<cr>:let #i='!display -geometry +0+0 '.#c.' &'<cr>:pkill display<cr>:#i<cr>:elseif #c==toupper(#c)<cr>:let #n=search('^'.#c,'sw')<cr>:elseif #c!=#b<cr>:let #f=3<cr>:let #g=tolower(#c)<cr>:while #f>0<cr>:try<cr>:let #j=eval('glos["'.#g.'"]')<cr>:catch<cr>:let #f=#f-1<cr>:let #g=strpart(#g,0,strlen(#g)-1)<cr>:continue<cr>:endtry<cr>:break<cr>:endwh<cr>:if #f>0<cr>:let #h=substitute(#j," glosimgs.*",'','')<cr>:if #h!=#j<cr>:let #i='!xv -geometry +0+380 '.substitute(#j,'^.\{-}\( glosimgs.*\)$','\1','').' &'<cr>:!pkill xv<cr>:#i<cr>:endif<cr><cr<cr>>:echo #h<cr>:else<cr>:echo 'No matching entry for '.#c<cr>:endif<cr>:elseif #c=~'\u\l\+$'<cr>:let #n=search('^'.#c,'sw')<cr>:elseif #c=~'\l\+$'<cr>:norm *<cr>:elseif #c=~'^_\w\+$'<cr>:let #/='^'.#c.'$'<cr>:norm nzz<cr>:endif<cr>
Specifically, I should have written:
:if has_key(**g:**glos,#g)==1:let #j=eval('**g:**glos.'.#g)
:h g: goes straight to the heart of the matter; in a function all references are local to that function, so references to any variable outside the function must be global, by prepending 'g:' to the variable name. As I created the dictionary independent of the function, the function must reference it as a global item.
Of course, if you are not aware of 'g:', it is rather difficult to find that help reference, but that's a frequent problem using help.
And, of course, the ** surrounding g: aren't required, that's what this site gives you in lieu of bolded text, apparently.

including internally created strings in octave system/unix command?

I have a script like:
#!/opt/bin/octave -qf
xin = dlmread(argv(){1},",");
tim = dlmread("Time");
fileout = [argv(){1} "-" "avg"];
## calcs to create xtemp and time matrices
dlmwrite("Time-avg",time);
dlmwrite(fileout,xtemp,",");
## ?? unix("paste -d',' Time-avg fileout > DATCOARSE");
This all works fine until the last line. I create fileout inside the script to correlate with the input datafile, and fileout prints out fine.
Is there some kind of dereferencing operator in octave to use "fileout" in the unix or system command?
You can use sprintf to create the command string:
cmd_str = sprintf ("paste -d',' Time-avg %s > DATCOARSE", fileout);
unix (cmd_str)
But you don't have to use "paste" at all. You can just concatenate the matrices in octave
dlmwrite ("DATCOARSE", [time, xtemp], ",");