Formatting a replacement expression
If I'm replacing a an expression how can I make sure the replacement expression is formatted with the correct spacing & newlines etc?
I have something similar to the following inside a PSI manager transaction and I want to make the sure formatting is correct for the replacementExpression variable.
var replacementExpression = elementFactory.CreateExpressionAsIs(replacementExpressionText);
newExpression = ModificationUtil.ReplaceChild(_expression, replacementExpression);
ta
Ollie
Please sign in to leave a comment.
Matt,
I have code formatted similar to below:
When I use ModificationUtil.ReplaceChild to replace the expression it is reformatted as follows:
I want to be formatted like this first example, e.g.:
ta
Ollie
it cleans the code as expected, can this be run programmatically without define a code-cleanup plugin?
ta
Ollie
Actually, should have asked, what happens if you try to format the second code snippet? As in, is the replace formatting the code as it would be formatted if you ran the code cleanup on it?
And yes, I think you can invoke the formatter programmatically, but as far as I understand it, you do that by getting an instance of ICodeFormatter, and using the same set of methods that the ModificationUtil will do.
Matt,
The code before the call to ModificationUtil.ReplaceChild is:
After the quick fix calls ModificationUtil.ReplaceChild the code is formatted as:
When I select this code and then apply 'Code Cleanup' it's then formatted as (required):
I couldn't workout how to programmatically call the 'Code Cleanup' formatter to get the above results,
Do you know how to do this?
I'm trying to do this all from inside the action passed tp 'DoTransaction' method on the PsiManager.
ta
Ollie
Hi Ollie. Sorry, dropped the ball on the swift reply.
I think what's happening here is that the new expression is being formatted, but not the surrounding nodes. So, you're replacing Select().Merge() with SelectMany(), and I think the nodes that make up the SelectMany() call are being formatted with the code formatter, but not the surrounding nodes. You can do this yourself by walking up the tree to the top-level expression (the return statement would probably be best) then get a code formatter by calling node.Language.LanguageService().CodeFormatter. There are a bunch of methods on this interface - you could probably get away with calling FormatInsertedNodes(node, node, true), as I think it will just format the nodes in that range (i.e. all sub-nodes) as though they were just inserted. Or you could call Format(node, CodeFormatProfile.DEFAULT) which should just do a default format of the statement.
Matt