Text Field with Standard PsiElement Auto Completion in IntelliJ Plugin - intellij-plugin

I'm trying to create a simple text field with auto completion for my IntelliJ plugin. I think this should be pretty simple but so far I've run into dead ends...
E.g. this should work as far as I understand:
EditorTextField format = new TextFieldWithCompletion(currentEditor.getProject(),
provider,
"",
true,
true,
true);
The problem is the provider. I'd expect to see a provider that isn't a list provider. I just want to show the completion matching the current line in the editor cursor so I'd like the full completion dialog and not just a short list of options.
I also looked at TextFieldWithAutoCompletion but it seems to be designed for hardcoded string values instead of free form completion.
I just want the standard Java/Kotlin completion. Not a custom list or anything like that. I saw some discussion with replacing the document of the text field but I couldn't get that to work either. I have a PsiExpressionCodeFragment and would expect there to be a completion provider that accepts that but I can't find it.
For reference what I want to do is something very similar to the conditional statement in the breakpoint dialog.
Another approach illustrated here is:
JavaCodeFragmentFactory jcff = JavaCodeFragmentFactory.getInstance(currentEditor.getProject());
PsiFile pf = PsiDocumentManager.getInstance(currentEditor.getProject()).getPsiFile(currentEditor.getDocument());
PsiElement psiElement = pf.findElementAt(currentEditor.getCaretModel().getOffset());
PsiExpressionCodeFragment fragment = jcff.createExpressionCodeFragment("", psiElement,null, false);
EditorTextField f = new EditorTextField(PsiDocumentManager.getInstance(currentEditor.getProject()).getDocument(fragment),
currentEditor.getProject(),
FileTypes.PLAIN_TEXT, false, true);
This loads the UI but doesn't popup code completion no matter what I type.

The trick is to create an editor that contains an instance of the Document. And this document refers to a language and a psi element context:
JPanel panel = new JPanel();
// Just detect an element under caret for context
PsiFile psiFile = PsiDocumentManager.getInstance(editor.getProject()).getPsiFile(editor.getDocument());
PsiElement element = psiFile.findElementAt(editor.getCaretModel().getOffset());
PsiExpressionCodeFragment code = JavaCodeFragmentFactory.getInstance(editor.getProject()).createExpressionCodeFragment("", element, null, true);
Document document = PsiDocumentManager.getInstance(editor.getProject()).getDocument(code);
EditorTextField myInput = new EditorTextField(document, editor.getProject(), JavaFileType.INSTANCE);
myInput.setPreferredWidth(300);
panel.add(myInput);
return panel;
Here the caret used to be located on dsa5, so the dsa5 variable is not yet visible for the completion.

Related

Google Docs script, return text value in the middle of specified text

[current result][1]
[1]: https://i.stack.imgur.com/O8AGa.png
The problem is that they all apply to the same line
I want to get the values individually from the same line
Rule
▶random text◁
→ Change only values between ▶ and ◁
Script currently in use
var body = DocumentApp.getActiveDocument().getBody();
var foundElement = body.findText('▶([^\S]+)◁');
while (foundElement != null) {
// Get the text object from the element
var foundText = foundElement.getElement().asText();
// Where in the element is the found text?
var start = foundElement.getStartOffset();
var end = foundElement.getEndOffsetInclusive();
// Set Bold
foundText.setBold(start, end, true);
// Change the Foreground color
foundText.setForegroundColor(start, end, "#ff326d");
// Find the next match
foundElement = body.findText('▶([^\S]+)◁', foundElement);
}
Some regular expressions are not fully supported
As per the documentation A subset of the JavaScript regular expression features are not fully supported, such as capture groups and mode modifiers.
I'd recommend to open a feature request on Google Issue Tracker as recommended here

Remove "MIME type" column from Filent Content List

I am Using a Script Adapter by passing payload to get contend for a Content List from "Search with values" event
When Contend get loaded to content list , i have a custom view to preview them. But if i clicked on MIME type column , It opens a separate view with the mapped viewer
So I need to remove this column or make it un-clickable
1) I am passing search values to content list's "Search with values" event , from where can i handle Content List's contend loading ,any Dojo Event i can use ?
2) With Script Adapter can i do this without going for a "response filter"
Edit :
As Nicely explained by "Ivo Jonker" (in his answer - "or try to specifically locate the widgets on your page" and with his example code)
responsed = page.ContentList8.ecmContentList.getResultSet();
var cols = responsed.structure.cells[0];
for (i=cols.length-1; i>0; i--){
var col = cols[i];
if (col.field=="mimeTypeIcon")
cols.splice(i,1);
}
page.ContentList78.ecmContentList.setResultSet(responsed);
I simply remove this row. Thanks Again and lovely blog , hope you keep posting more great articles.
The values passed through the Search With Values event will eventually be handled by the icm.pgwidget.contentlist.dijit.DocumentSearchHandler
that in turn creates a SearchTemplate to execute the search (ecm.model.SearchTemplate.prototype.search). One option would be to aspect/before/around the DocumentSearchHandler#query to manipulat the searchresults and by that way to remove the column.
The wiring however does not provide any handles to achieve this for a specific query-resultset combination leaving you to either fix this on a global scale (icm.pgwidget.contentlist.dijit.DocumentSearchHandler.prototype#query), or try to specifically locate the widgets on your page.
Personally, taking into account #2, i'd go for the responsefilter-option if you feel the global solution wouldn't be a problem, or alternatively i'd personally prefer to create a simple ICM widget that instantiates/implements a "plain" ecm.widget.listView.ContentList and exposes a wire to set the ecm.model.Resultset.
You'd then be able to create your own Searchquery in a scriptadapter, remove the column, and pass the resultset.
The script adapter could be something like:
var scriptadapter=this;
var queryParams={};
queryParams.query = "SELECT * FROM Document where id in /*your list*/";
queryParams.retrieveAllVersions = false;
queryParams.retrieveLatestVersion = true;
queryParams.repository = ecm.model.desktop.repositories[0];
queryParams.resultsDisplay = {
"sortBy": "{NAME}",
"sortAsc": true,
"columns": ["{NAME}"],
"honorNameProperty": true};
var searchQuery = new ecm.model.SearchQuery(queryParams);
searchQuery.search(function(response/*ecm.model.Resultset*/){
//remove the mimeTypeIcon
var cols = response.structure.cells[0];
for (i=cols.length-1; i>0; i--){
var col = cols[i];
if (col.field=="mimeTypeIcon")
cols.splice(i,1);
}
//emit the resultset to your new contentlist, be sure to block the regular synchrounous output of the scriptadapter
scriptadapter.onPublishEvent("icm.SendEventPayload",response);
//The contentlist wire would simply do contentlist.setResultSet(response);
});

How do you automate DevExpress Combo Boxes with Selenuim/Watir?

DevExpress builds combo boxes in a very odd way. The standard identification built in to Selenuim and Watir (including Page Objects) does not see it as a Select List.
So how can you automate these successfully?
So as it turns out, DevExpress builds combo boxes as a text box with several layered tables associated with it but not under the text box in the HTML tree.
interactions are all done via embedded scripts.
I found the simplest way to automate this object is to identify the text box and the lowest table containing the list of items (3rd table down).
for example (using Watir and Page Objects)
table(:list,:id => 'ComboBoxValue_DDD_L_LBT')
text_field(:state, :id => 'ComboBoxValue_I') #:name => 'State')
I have not found a way to get better IDs at these levels, but we are working that issue.
Then your select code looks like this:
self.state_element.click
row = list_element.find { |row| row[0].text == value }
row.click
Note that with Selenium, you can execute arbitrary javascript in the client to query and set the control's state (if the client-side is enabled for the control). Here's how I did so to extract (and set) the selected text from a combobox named localeSelectList:
// unit test code, c#
[TestMethod]
public void SomeTestMethod()
{
IWebDriver ff = new FirefoxDriver();
ff.Navigate().GoToUrl(homeUrl);
// find the element as an iWebElement
IWebElement localeBox = ff.FindElement(By.CssSelector("#localeSelectList"));
Assert.IsTrue(localeBox.Enabled);
// get the text from the control via javascript
var locale = Util.GetControlText(ff, localeSelectList);
Assert.IsTrue(locale == "English");
// set the text in the control via javascript
Util.SetControlText(ff, localeSelectList, "German");
// verify the text was set
locale = Util.GetControlText(ff, localeSelectList);
Assert.IsTrue(locale == "German");
}
// helper methods, Util class
static public string GetControlText(IWebDriver driver, string controlName)
{
string script = string.Format("return {0}.GetText();", controlName);
var controlText = ((IJavaScriptExecutor)driver).ExecuteScript(script);
return controlText.ToString();
}
static public void SetControlText(IWebDriver driver, string controlName, string controlText)
{
string script = string.Format("{0}.SetValue('{1}');", controlName, controlText);
((IJavaScriptExecutor)driver).ExecuteScript(script);
}
It's not quite the same thing as interacting with the extensions via primitives (clicks, keystrokes, etc) as it won't fire the event handlers for these events, but if your extension uses 'valueChanged' events instead of primitive handlers it's pretty close to the same.
Also note: you can use client-side javascript to find and return elements using jquery/css selectors and ids, as follows:
IWebElement element = (IWebElement) ((IJavaScriptExecutor)driver).ExecuteScript("return $('#.myElementId');")
That's right with several layered tables, but I would like to add that they are only visible when combobox is clicked. First
var cmbParameterGruppen = webDriver.FindElement(By.Id("phContent_ParameterGruppenComboBox_I"));
cmbParameterGruppen.Click();
and then
var tblItems = webDriver.FindElement(By.Id("phContent_ParameterGruppenComboBox_DDD_L_LBT"));
var parameterGruppen = tblItems.FindElements(By.XPath(".//*"));
var count = parameterGruppen.Count;
Debug.WriteLine($"Count = {count}");
if(count > 0)
parameterGruppen[count - 1].Click();
I select hier last row.

Eclipse plug-in: syntax recoloring

I have a costum editor for my own languages and I want to change from the property menu between them and recolor the syntax accordingly. I don't know if I have to use a reconciler or something else. The only way that the syntax is recolored, is by closing and opening the current file.
In your editor you need to listen for property change events from your preference store.
In your initializeEditor method call setPreferenceStore(preferenceStore)
Override the handlePreferenceStoreChanged method:
#Override
protected void handlePreferenceStoreChanged(PropertyChangeEvent event)
{
// TODO update settings affected by the event
// TODO If required invalidate the current presentation to update the colors
getSourceViewer().invalidateTextPresentation();
super.handlePreferenceStoreChanged(event);
}
You need to add code to look at the property change event to see if it is one that you need to handle. If the event changes something (such as changing the colors) that needs to text to be redrawn call getSourceViewer().invalidateTextPresentation().
To support all the normal text editor preferences you need to use a chained preference store in the setPreferenceStore call:
IPreferenceStore generalTextStore = EditorsUI.getPreferenceStore();
IPreferenceStore yourPreferenceStore = get your preference store
IPreferenceStore combinedPreferenceStore = new ChainedPreferenceStore(new IPreferenceStore[] {yourPreferenceStore, generalTextStore});
setPreferenceStore(combinedPreferenceStore);

Check Word Doc for Field Code before applying

So I've coded a VSTO addin using vb.net to add a header to a document in Word however from historical methods we have lots of templates with field codes. My addin does not account for these and simply strips the header to add xxxxx value you choose from the pop up.
I need my code to be smart enough to 'spot' the field code and append or if it does not exist e.g. a blank document then continue running as expected. I can append this field code using the below code:
wordDocument.Variables("fieldname").Value = "xxxx"
wordDocument.Fields.Update
However my tool then adds the header as normal and strips most the content from the template. So effectively my question is how would I code a check for this before proceeding. So in plain English I would need my addin to go from this:
Load pop up
Set xxxx value in header
Close
To this:
Load pop up
Check Document for existing "fieldname"
If "fieldname" exists then
wordDocument.Variables("fieldname").Value = "xxxx" (from pop up selection)
wordDocument.Fields.Update
However if "fieldname" doesn't exist then continue as normal....
Sorry if this is a little complex and/or long winded.
Thanks in advance.
Here is my code in C#, hope this might help you to code in VB.Net
foreach (Section sec in doc.Sections)
{
doc.ActiveWindow.View.set_SeekView(WdSeekView.wdSeekCurrentPageHeader);
foreach (HeaderFooter headerFooter in sec.GetHeadersFooters())
{
doc.ActiveWindow.View.set_SeekView(headerFooter.IsHeader ? WdSeekView.wdSeekCurrentPageHeader : WdSeekView.wdSeekCurrentPageFooter);
if (headerFooter.Range.Fields.Count > 0)
{
//Append to existing fields
UpdateFields(headerFooter.Range.Fields);
}
else
{
//Add field code
AddFieldCode(headerFooter.Range);
}
}
doc.ActiveWindow.View.set_SeekView(WdSeekView.wdSeekMainDocument);
}
Extension method to iterate through the header types
public static IEnumerable<HeaderFooter> GetHeadersFooters(this Section section)
{
List<HeaderFooter> headerFooterlist = new List<HeaderFooter>
{
section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary],
section.Headers[WdHeaderFooterIndex.wdHeaderFooterFirstPage],
section.Headers[WdHeaderFooterIndex.wdHeaderFooterEvenPages],
section.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary],
section.Footers[WdHeaderFooterIndex.wdHeaderFooterFirstPage],
section.Footers[WdHeaderFooterIndex.wdHeaderFooterEvenPages]
};
return headerFooterlist;
}