c# - How do I format code selection and maintain leading trivia with Roslyn? -
i want format code modified roslyn. modifying code inside method. don't want reformat entire file. original formatting looks following:
mynamespace { class codebasictests { int operationorder_0() { int = 20; int b = 10; int sum = + b; return (int) sum; } } } after format body of method, gets aligned border, not method signature.
mynamespace { class codebasictests { int operationorder_0() { int = 20; int b = 10; int c = 30; //new instruction int sum = + b + c; return (int) sum; } } } i have tried following inside method visitor (csharpsyntaxrewriter):
methoddeclarationsyntax method = visited method node; updatedmethod = method.replacenode(method.body, newbody); updatedmethod = updatedmethod.normalizewhitespace().withtriviafrom(method); return updatedmethod; or selecting method body
newbody = (blocksyntax) formatter.format(oldbody, texts, visualstudiosolutionhandler.workspace); i have tried work text spans of formatter, don't manage make work @ at all.
i don't want/know write visitor insert right tab every element in newbody because statements insert more complex, , use autoformatting feature updated method only.
i don't know hot keep original method indentation.
replace trivia current trivia list new trivia inserted in place.
here's example of extension method created add newlines annotated nodes.
public static tnode addnewlinetoannotated<tnode>(this tnode node, string annotationkind) tnode : csharpsyntaxnode => node.replacenodes(node.getannotatednodes(annotationkind), (_, n) => n.withleadingtrivia(n.getleadingtrivia() .insert(0, syntaxtree.elasticendofline(environment.newline)) ) ); getting leading trivia gives syntaxtrivialist , can add(), insert() or otherwise modify trivia list give new trivia list.
Comments
Post a Comment