<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
</head>
<body bgcolor="#FFFFFF" text="#000000">
<br>
Hi,<br>
<br>
I'm trying to figure out how to programmatically invoke clang-format
to format code. I would like to get from a declaration ("Decl *") to
a plain string containing the reformatted source code.<br>
<br>
Here's my feeble initial attempt:<br>
<br>
<br>
/*<br>
* Non-functioning attempt att trying to extract the source code of<br>
* 'decl' formatted using LLVM style.<br>
*/<br>
std::string get_formatted_source(SourceManager &mgr, const Decl
*decl)<br>
{<br>
StringRef code = get_source(mgr, decl); // implemented elsewhere<br>
std::vector<Range> ranges;<br>
LangOptions lo;<br>
Rewriter rw(mgr, lo);<br>
<br>
Range range(0, src.size());<br>
ranges.push_back(range);<br>
<br>
// Do the reformat<br>
auto repl = reformat(getLLVMStyle(), code, ranges);<br>
<br>
// Apply the replacements<br>
for (auto it = repl.begin(); it != repl.end(); ++it) {<br>
it->apply(rw);<br>
}<br>
<br>
// Extract the reformatted source code.<br>
auto formatted_source =
rw.getRewrittenText(decl->getSourceRange());<br>
<br>
// I would have expected 'formatted_source' to be the formatted
source<br>
// here, but it is always the same as the original, as if the <br>
// replacements where never applied.<br>
}<br>
<br>
<br>
<div class="moz-signature">-- <br>
<span style="color: #a6a6a6; font-family:
arial,helvetica,sans-serif; font-size: 10pt;"><strong>Jesper
Eskilson</strong></span>
<span style="color: #fdb913; font-family:
arial,helvetica,sans-serif; font-size: 10pt;"><em>Development
Engineer</em></span><br>
<span style="color: #808080; font-family:
arial,helvetica,sans-serif; font-size: 10pt;">IAR Systems AB<br>
Box 23051, Strandbodgatan 1<br>
SE-750 23 Uppsala, SWEDEN<br>
E-mail: <a href="mailto:jesper.eskilson@iar.com">
<span style="color: #808080; font-family:
arial,helvetica,sans-serif; font-size: 10pt;">jesper.eskilson@iar.com</span></a>
Website: <a href="http://www.iar.com">
<span style="color: #808080; font-family:
arial,helvetica,sans-serif; font-size: 10pt;">www.iar.com<br>
</span></a>
Twitter: <a href="http://www.twitter.com/iarsystems">
<span style="color: #808080; font-family:
arial,helvetica,sans-serif; font-size: 10pt;">www.twitter.com/iarsystems</span></a>
</span>
</div>
</body>
</html>