Conditional Parts in snippets

Sven Brauch mail at
Tue Dec 8 16:41:38 GMT 2020


you can do something like this:

class ${thename} ${oparen(parent)} ${parent=""} ${cparen(parent)}:
     """ ${doc} """

and then in the scripts tab, do this:

function oparen(x) { return x.length > 0 ? '(' : ''; }
function cparen(x) { return x.length > 0 ? ')' : ''; }

This works fine, you can edit the name, press tab, and if you enter 
something it adds the parentheses, otherwise not.

Turns out apparently though that you cannot have two variable fields 
without space in between, which limits the usefulness of this approach 
... :/

That could be fixed, though.


On 12/8/20 2:00 PM, Yannick Gingras wrote:
> Hi,
> I am trying to write snippets for Python that would have conditional
> sections.  For example:
> class ${Name}($parent="object"):
>      """ ${doc} """
>      ${cursor}
> In the above, if parent is not edited, we don't event need the
> parentheses, and we can write "class Name:", which is less explicit,
> but perfectly in line with the most popular coding style.  Similarly,
> if the documentation string is unedited or left empty, it would be
> better to remove the enclosing quotes.
> I was hoping to use view.cursorPosition to detect when a place holder
> has been dealt with then delete the offending characters/line if the
> values is empty or unchanged.  Unfortunately, cursorPosition is not set
> when expanding a snippet.
> Is there another way to know which placeholders have been covered?  Is
> there a better way implement conditional sections in snippets?
> By the way, I'm not subscribed to the mailing list so please CC me in
> answers.
> Thanks!

More information about the KWrite-Devel mailing list