" auxiliary vim script for kvim part
" Eray Ozkural (exa), (C) 2002
" updated by Mickael Marchand (Mikmak)

"open a file
function! OpenFile(text)
	bd!
	edit `=a:text`
endfunction

"set the current selection
function! SetSelection(sline, scol, eline, ecol)
	call cursor(a:sline, a:scol)
	normal v
	call cursor(a:eline, a:ecol)
endfunction

function! SetText(text)
	% delete
	call Insert(1,1,a:text)
endfunction

"clear undo history
function! ClearUndo()
	let s:oldlevels = &undolevels
	let &undolevels = 0
	call setline(".","blah")
	undo
	let &undolevels = s:oldlevels
endfunction

"added to force the exit by Mikmak 
function! ForceQuit()
  wall
  qall!
endfunction

function! Text(sline, scol, eline, ecol)
  map s:x <C-M>
  let newline = maparg("s:x")
  let s:i = a:sline
  let s:text = ""
  while s:i <= a:eline
    let s:text = s:text . getline(s:i) . "\n"
    let s:i = s:i + 1
  endwhile
  unmap s:x
  return s:text
endfunction

function! InsertLine (line, text)
"	if a:line == -1
"		normal Go
"		let s:lastline = line("$") 
"		call Insert(s:lastline,0,a:text)
"	else
		call cursor(a:line,1)
		normal O
		call Insert(a:line,1,a:text)
"	endif
endfunction

function! Insert(line, column, text)
  let pos = match(a:text, "\n")
  let fstline = getline(a:line)
  if pos == -1
    let nuline = strpart(fstline,0,a:column-1) . a:text . strpart(fstline,a:column-1)
    call setline(a:line, nuline)
  else
    let nuline = strpart(fstline,0,a:column-1) . strpart(a:text,0,pos)
    call setline(a:line, nuline)
    let i = 0
    while 1
      let pos = pos + 1
      let npos = match(a:text, "\n", pos)
      if npos == -1
        call append(a:line + i, strpart(a:text, pos))
        break
      endif
      call append(a:line + i,strpart(a:text, pos, npos-pos))
      let i = i + 1
      let pos = npos
    endwhile
  endif
endfunction
 
function! Remove(sline, scol, eline, ecol)
  let fstline = getline(a:sline)
  if a:sline == a:eline
    let nuline = strpart(fstline,0,a:scol-1) . strpart(fstline,a:ecol)
    call setline(a:sline, nuline)
  else
    let lstline = getline(a:eline)
    let nuline = strpart(fstline,0,a:scol-1) . strpart(lstline,a:ecol)
    execute a:sline . "," . a:eline . " delete"
    call append(a:sline-1, nuline)
  endif
endfunction

