Using lpeg to only capture on word boundaries
<p>I've been working on <a href="https://github.com/skx/kilua/" rel="nofollow">a text editor</a> that uses LPEG to implement syntax highlighting support.  Getting things up and running was pretty simple, but I've only done the minimum required.</p>

<p>I've defined a bunch of patterns like this:</p>

<pre><code> -- Keywords
 local keyword = C(
    P"auto" +
    P"break" +
    P"case" +
    P"char" + 
    P"int" 
    -- more ..
  ) / function() add_syntax( RED, ... )
</code></pre>

<p>This correctly handles input, but unfortunately matches too much.  For example <code>int</code> matches in the middle of <code>printf</code>, which is expected because I'm using "<code>P</code>" for a literal match.</p>

<p>Obviously to perform "proper" highlighting I need to match on word-boundaries, such that "int" matches "int", but not "printf", "vsprintf", etc.</p>

<p>I tried to use this to limit the match to only occurring after "<code>&lt;[{ \n</code>", but this didn't do what I want:</p>

<pre><code>  -- space, newline, comma, brackets followed by the keyword
  S(" \n(&lt;{,")^1 * P"auto"  + 
</code></pre>

<p>Is there a simple, obvious, solution I'm missing here to match only keywords/tokens that are surrounded by whitespace or other characters that you'd expect in C-code?  I do need the captured token so I can highlight it, but otherwise I'm not married to any particular approach.</p>

<p>e.g.  These should match:</p>

<pre><code> int foo;
 void(int argc,std::list&lt;int,int&gt; ) { .. };
</code></pre>

<p>But this should not:</p>

<pre><code> fprintf(stderr, "blah.  patterns are hard\n");
</code></pre>