How to insert a comma in an array literal?
Hi,
I know this is a very specific question, but I can't figure it out. My situation is that I have a JavaScript array literal with line breaks like this:
[
'a',
'b',
'c'
].
I would like to add a new element to the end, so I need to add the code fragment ",\n'd'".
I add elements elsewhere in my plugin but those are complete expressions or statements. I don't know the best way to add this fragment. Any help is appreciated.
Please sign in to leave a comment.
Hi Chris,
do you mean something like this?
Greetings, Kay
Kay,
Let me clarify -- I'm trying to create PsiElements that represent the code fragment and insert that into the existing Psi tree that represents the array. There are methods to create the PsiElements for expressions and statements, but I'm trying to just create a 'fragment'.
Hi Chris,
You can insert text directly into the document if you like - find the element corresponding to your insertion point ('c' in this case) and then use Document.insertString(element.getTextRange().getEndOffset(), ",\n'd'"). You can then call PsiDocumentManager.commitDocument(document) to rebuild the PSI tree and reformat the whole block using CodeStyleManager.reformatText().
Cheers,
Colin
There are many ways. Here is one I used.
Given
and
You can also, just create a fragment Psi tree with your new code and replace it directly in the Psi tree using API's on the Psi clases.
Excerpt: (parent is some PsiElement)
Here is a real exmaple from my plugin: It takes an assignment statment that can have any number of expressions on either side, and equalizes it
a, b, c = 1
becomes
a, b, c, = 1, nil, nil
Notice I don't add any ',' and just add the 'nil' as an expression.
Here is where ',' gets added.
Sometimes it makes more sense to manipulate the Psi tree, and sometimes just using text makes sense. Learn both ways, but the whole semantic editor concepts rests fundamentally on being able to perform manipulations on the code structure and not the text itself. It may not make sense for your use case - but it is worth learning.
Thanks Jon, I didn't know you could just add leaf nodes like that in your last example. I was able to use that method to achieve what I needed.