python global function error

Asked by petobens

I have the following global function

global !p
def label(text):
    mydict = {"á" : "a",
                        "Á" : "A",
                        "é" : "e",
                        "É" : "E",
                         "í" : "i",
                         "Í" : "I",
                        "ó" : "o",
                        "Ó" : "O",
                         "ú" : "u",
                        "Ú" : "U",
                         "ñ" : "ni"}
    for k, v in mydict.items():
        text = text.replace(k, v)
    label = text.lower().split(' ')
    if len(label) >=10:
        return '_'.join(label[:10])
    else:
        return '_'.join(label)
endglobal

That I'm using with the following tex snippet:

snippet sec "Section" b
\section{${1:section name}}
\label{sec:${2:`!p snip.rv = label(t[1])`}}
${VISUAL}$0
endsnippet

The python code runs fine when I try it in my system (using python 2.7) but when I use it as a snippet it gives a series of errors. In particular something like

    Error detected while processing function UltiSnips_ExpandSnippet:
    vim.buffers[-1][:] = text.splitlines()
    Error detected while processing function UltiSnips_ExpandSnippet:
    ValueError: number bust be greater then zero

How should I write the global function and the snippet to work properly? Sorry for the trouble and thanks for the help.

Question information

Language:
English Edit question
Status:
Solved
For:
UltiSnips Edit question
Assignee:
No assignee Edit question
Solved by:
SirVer
Solved:
Last query:
Last reply:
Revision history for this message
Best SirVer (sirver) said :
#1

The error message is not very helpful I guess. That comes when Vim (which is bad with unicode) clashes into python (which is bad with unicode too). The problem you have here is the following: you get a text that is unicode, you have a dictionary of bytestrings which are utf-8 - later in the method call "bytestring".join(unicode objects) which is not valid in python. The easiest way to make work what you want to do is this:

global !p
def label(text):
 text = text.encode("utf-8")
 mydict = {"á" : "a",
         "Á" : "A",
         "é" : "e",
         "É" : "E",
        "í" : "i",
        "Í" : "I",
         "ó" : "o",
         "Ó" : "O",
        "ú" : "u",
         "Ú" : "U",
        "ñ" : "ni"}
 for k, v in mydict.items():
   text = text.replace(k, v)
 label = text.decode("utf-8").lower().split(' ')
 if len(label) >=10:
   return u'_'.join(label[:10])
 else:
   return u'_'.join(label)
endglobal

snippet sec "Section" b
\section{${1:section name}}
\label{sec:${2:`!p snip.rv = label(t[1])`}}
${VISUAL}$0
endsnippet

Revision history for this message
petobens (ferrari-pedro) said :
#2

Thanks SirVer, that solved my question.