How to get multiple copied texts lines using intellij api or java code.

Answered

Hello all,

I'm developing a plugin that get multiple copied text lines to get declaried variables and paste it into tuple form with some filteration using regex.

like, 

name = "Harshdeep"

age = 24

company = "XYZ"

username = "harshdeep007"

 

now I just copied all above code and I want to paste just variables as a tuple like,

fields = [ 'name', 'age', 'company', 'username' ]

 

I've doveloped a working prototype of this plugin.

but, got problem when I select the multiple lines with alt key. It paste only last selected line's variable.

example, 

I've selected whole ( name and company line ) from above given code.

Now, I got only tuple like, fields = [ 'company' ]

 

How to solve it..???

 

 

My code.

 

public class pycCopyDjangoModelFields extends AnAction {

@Override
public void actionPerformed(@NotNull final AnActionEvent e) {
StringBuilder fields = new StringBuilder();
Editor editor = e.getRequiredData(com.intellij.openapi.actionSystem.CommonDataKeys.EDITOR);
String SelectModel = editor.getSelectionModel().getSelectedText();
String regex = "(\\S+)\\s*=\\s*[^(]*\\(([^)]*)\\)";
Pattern pattern = Pattern.compile(regex);

if (SelectModel == null) {
return;
}

Matcher m = pattern.matcher(SelectModel);
boolean first = true;
while (m.find()) {
if (first) {
fields.append("fields = [ ");
first = false;
}
fields.append("'");
fields.append(m.group(1));
fields.append("', ");
}
if (!first) {
fields.append("]");
}
CopyPasteManager.getInstance().setContents(new StringSelection(fields.toString()));
}
}
0
1 comment

Harshdeep,

getSelectedText()

indeed returns only the selection for the latest caret. You should instead use:

getSelectedText(true)

which allows passing the boolean allCarets parameter.

0

Please sign in to leave a comment.