# From http://slobin.pp.ru/vim/_vimrc.html
# Adapted to python3 by Oleg Broytman <phd@phdru.name>

import sys, rlcompleter, unicodedata, vim
from itertools import *
vim_complete = rlcompleter.Completer().complete

def vim_comp_list():
  """Implementation of CompList() function"""
  arglead = vim.eval("a:ArgLead")
  fence = int(vim.eval("match(a:ArgLead, '\(\w\|\.\)*$')"))
  left, right = arglead[:fence], arglead[fence:]
  try:
    completions = (vim_complete(right, i) for i in count())
    candidates = list(takewhile(bool, completions))
  except NameError:
    candidates = []
  suggestions = [left + x for x in candidates]
  vim.command("return " + repr(suggestions))

def vim_calc(command):
  """Implementation of :Calc command"""
  global _
  try:
    result = eval(command)
  except SyntaxError:
    if sys.version_info[0] == 2:
      exec(command in globals(), locals())
    else:
      exec(command, globals(), locals())
  else:
    if result != None:
      print(result)
      _ = result
      xx = ''.join(['\\x%02x' % ord(x) for x in str(_)])
      vim.command('let @" = "%s"' % xx)

def vim_pydo(command):
  """Implementation of :Pydo command"""
  codeobj = compile(command, "command", "eval")
  line1 = vim.current.range.start
  line2 = vim.current.range.end
  delta = 0
  for numz in range(line1, line2+1):
    line = vim.current.buffer[numz-delta]
    if sys.version_info[0] == 2:
      uline = unicode(line, vim.eval('&fileencoding'))
    else:
      uline = line
    num = numz + 1
    words = line.split()
    result = eval(codeobj, globals(), locals())
    if result is None or result is False:
      del vim.current.buffer[numz-delta]
      delta += 1
      continue
    if isinstance(result, list) or isinstance(result, tuple):
      result = " ".join(map(str, result))
    else:
      result = str(result)
    vim.current.buffer[numz-delta] = result

def vim_unicode_name():
  try:
    char = vim.eval("matchstr(getline('.'), '.', col('.') - 1)")
    if sys.version_info[0] == 2:
        print(unicodedata.name(char.decode(vim.eval("&encoding"))))
    else:
        print(unicodedata.name(char))
  except (AttributeError, ValueError) as target:
    print("%s: %s" % (target.__class__.__name__, target))
