I’ve been using Kakoune for a number of months, and I’m starting to write my own customizations. I’m trying to understand the best way to take one action or another based on the face under the primary cursor. It doesn’t seem like there’s a built-in way to check this, so I’m guessing I’ll simply need to use the same regex that the highlighter is using to apply the face, but I’m a bit lost on what the best way to do this is. Are there good tools in Kakoune to do this, or should I be shelling out?
The specific goal is to have a command to “toggle” bolding in markdown: if the text under the primary cursor is not bolded, put 2 asterisks on either side of the current selection. If it is bolded, remove the double asterisks on both sides to remove the bolding. I know how to craft the command to add/remove these asterisks, but I’m not sure the best way to check whether the current text is bolded.
Not sure how to check the face under cursor, but in this case you probably should look for the asterisk pairing and work with that instead, since the face is just for the visuals while the asterisks affect the generated markdown document outcome.
Problem here would be disabling the bolding, since if you want the selection to be automatically resolved, it might find asterisks that don’t form a pair if you try to use the command on a substring that isn’t surrounded by asterisks.
I think it should work if you make a toggle command that assumes that asterisks should be at beginning and end of selection. Then have another shortcut, to select the surrounding asterisks. That two step process should be ergonomic enough and would be more robust.
To select surrounding asterisks: <a-a>*
Then use the command you mentioned for adding/removing asterisks.
1 Like
Congratulations on taking your first steps with customising Kakoune! It’s a very powerful tool, and a lot of custom automation can be surprisingly easy to write.
Unfortunately, you’ve chosen Hard Mode here - not only does Kakoune not provide any way to query the faces under the cursor, Markdown implementations often disagree about what counts as bold (Can you mix *
and _
? Can you begin or end in the middle of a word? Can you nest markup?) and so even if you could tell whether Kakoune thinks a particular character is bold, Kakoune might be wrong.
One way to do it might be:
- clear all selections:
,
- select to the beginning of the paragraph:
[p
- Split on
**
: S\*\*<ret>
- Check whether the number of selections (
%val{selection_count}
in Kakoune, $kak_selection_count
in shell) is odd or even. If it’s even, the cursor is in a bold area, otherwise not-bold
This is not completely reliable (for example, it does not require that **
appears at the beginning or end of a word, and it does not support nesting), but the alternative would be to write your own Markdown parser that can report the formatting of a particular source token.
1 Like