private static void ImportKeywords(ConfLine conf) { Keywords.Import(); // Update autocompletion AutoComplete.RefreshStaticItems(); ParserHandler.ParseCurrentDocument(); }
/// <summary> /// Gets the list of functions/proto of interest /// </summary> private static int GetPrototypesLists(out List <ParsedImplementation> listOfOutDatedProto, out List <ParsedImplementation> listOfSoloImplementation, out List <ParsedPrototype> listOfUselessProto) { // make sure to parse the current document before checking anything ParserHandler.ParseCurrentDocument(true, true); // list the outdated proto listOfOutDatedProto = ParserHandler.AblParser.ParsedItemsList.Where(item => { var funcItem = item as ParsedImplementation; return(funcItem != null && funcItem.HasPrototype && !funcItem.PrototypeUpdated); }).Select(item => (ParsedImplementation)item).ToList(); // list the implementation w/o prototypes listOfSoloImplementation = ParserHandler.AblParser.ParsedItemsList.Where(item => { var funcItem = item as ParsedImplementation; return(funcItem != null && !funcItem.HasPrototype); }).Select(item => (ParsedImplementation)item).ToList(); // list the prototypes w/o implementation listOfUselessProto = ParserHandler.AblParser.ParsedPrototypes.Where(item => { // it's a prototype with no implementation var proto = item.Value as ParsedPrototype; return(proto != null && proto.SimpleForward && !ParserHandler.AblParser.ParsedItemsList.Exists(func => func is ParsedImplementation && func.Name.EqualsCi(item.Value.Name))); }).Select(item => (ParsedPrototype)item.Value).ToList(); return(listOfOutDatedProto.Count + listOfSoloImplementation.Count + listOfUselessProto.Count); }
static void Main(string[] args) { ParserHandler argsParser = new ParserHandler(); WebServices webServices = new WebServices(); DataServices dataServices = new DataServices(); OutputServices outputServices = new OutputServices(); //CommandLine NuGet package automātiski pārso Options objektu no lietotāja cmd input parametriem Options userInputData = argsParser.ParseArgs(args); //Default URL ir definēts Source field attribūtā Options klasē, kas ar pārseri automātiski tiek iekļauts, //gadījumos, ja lietotājs nav definējis savu URL string url = webServices.GenerateUrlFromDistrictId(userInputData.District, userInputData.Source); //Datu iegūšana no DeclaredPersons API, desiarelizēti no JSON string uz Value objektiem List <Value> response = webServices.FetchData(url); //Datu filtrēšana pēc lietotāja definētiem parametriem List <Value> filteredData = dataServices.FilterData(userInputData, response); //Atfiltrēto datu sagatavošana JSON serializācijai DataOutput outputData = outputServices.PrepareDataForOutput(filteredData); //Ģenerēta json string izvaddati string jsonString = outputServices.GenerateJsonString(outputData); //Dati tiek printēti konsolā ar ConsoleTable NuGet package palīdzību outputServices.PrintDataToConsole(outputData); //Text fails are json tiek saglabāts, ja lietotājs ir norādjis faila nosaukumu -out parametrā, //pēc saglabāšans tekst fails ar json tiek automātiski atvērts. Saglabātais fails atrodas projekta direktorijā outputServices.SaveJsonToFile(userInputData.Out, jsonString); }
/// <summary> /// Find a list of items in the completion and return it /// Uses the position to filter the list the same way the autocompletion form would /// </summary> /// <returns></returns> public static List <CompletionItem> FindInCompletionData(string keyword, int position, bool dontCheckLine = false) { var filteredList = AutoCompletionForm.ExternalFilterItems(SavedAllItems.ToList(), Npp.LineFromPosition(position), dontCheckLine); if (filteredList == null || filteredList.Count <= 0) { return(null); } var found = filteredList.Where(data => data.DisplayText.EqualsCi(keyword)).ToList(); if (found.Count > 0) { return(found); } // search in tables fields var tableFound = ParserHandler.FindAnyTableOrBufferByName(Npp.GetFirstWordRightAfterPoint(position)); if (tableFound == null) { return(null); } var listOfFields = DataBase.GetFieldsList(tableFound).ToList(); return(listOfFields.Where(data => data.DisplayText.EqualsCi(keyword)).ToList()); }
/// <summary> /// Called from CTRL + Space shortcut /// </summary> public static void OnShowCompleteSuggestionList() { ParserHandler.ParseCurrentDocument(); _openedFromShortCut = true; _openedFromShortCutPosition = Npp.CurrentPosition; UpdateAutocompletion(); }
/// <summary> /// Called when the text in scintilla is modified (added/deleted) by the user (called after UI update) /// </summary> public static void OnTextModified(SCNotification nc, bool insertedText, bool deletedText, bool singleCharModification, bool undo, bool redo) { ParserHandler.ParseDocumentAsap(); if (!singleCharModification) { ClosePopups(); } }
/// <summary> /// Called from CTRL + Space shortcut /// </summary> public static void OnShowCompleteSuggestionList() { ParserHandler.ParseDocumentNow(); _openedFromShortCut = true; _openedFromShortcutLine = Sci.Line.CurrentLine; _shownPosition = Sci.CurrentPosition; UpdateAutocompletion(); }
/// <summary> /// update the "selected" scope when the user click in scintilla /// </summary> public void UpdateCurrentScope() { if (!IsVisible) { return; } UpdateCurrentScope(Npp.CurrentFile.IsProgress ? ParserHandler.GetScopeOfLine(Sci.Line.CurrentLine) : null); }
private void ButtonFromIncludeOnButtonPressed(YamuiButtonImage sender, EventArgs e) { // change option and image Config.Instance.CodeExplorerDisplayItemsFromInclude = !Config.Instance.CodeExplorerDisplayItemsFromInclude; filterbox.ExtraButtonsList[4].UseGreyScale = !Config.Instance.CodeExplorerDisplayItemsFromInclude; // Parse the document ParserHandler.ParseDocumentNow(); Sci.GrabFocus(); }
/// <summary> /// called when the user scrolls.. /// </summary> public static void OnPageScrolled() { ClosePopups(); // parse the current part of the document if (!Npp.CurrentFileInfo.IsProgress) { ParserHandler.ParseDocumentAsap(); } }
public static void Main(string[] args) { var cfg = new CfgDocument(); ParserHandler pn = new ParserHandler(); // S -> a A a a cfg.Rules.Add(new CfgRule("S", "a", "A", "a", "a")); // S -> b A b a cfg.Rules.Add(new CfgRule("S", "b", "A", "b", "a")); // A -> cfg.Rules.Add(new CfgRule("A")); // A -> b cfg.Rules.Add(new CfgRule("A", "b")); Console.WriteLine(cfg.ToString()); cfg.RebuildCache(); // faster if we do it this way var msgs = cfg.TryValidate(); var hasErrors = false; foreach (var msg in msgs) { Console.Error.WriteLine(msg); if (ErrorLevel.Error == msg.ErrorLevel) { hasErrors = true; } } if (hasErrors) { return; } pn.statusText = "ok"; pn.cfg = cfg; pn.finish(); var tg = new TableGenerator(); tg.construct(cfg, 2); Debug.Assert(3 == tg.Tcounter, "Test failed"); Debug.Assert(string.Join(" ", tg.LLksf) == "T:S,{} T:A,{a:a} T:A,{b:a}", "Test failed"); Debug.Assert(string.Join(" ", tg.PT.fif) == "T0 T1 T2 :a :b |$", "Test failed"); Debug.Assert(string.Join(" ", tg.PT.sif) == "a:a a:b a b:a b:b b ", "Test failed"); Debug.Assert(6 == tg.PT.field.Count, "Test failed"); for (var i = 0; i < tg.PT.field.Count; ++i) { var fld = tg.PT.field[i]; Debug.Assert(7 == fld.Count, "Test failed"); } return; }
private void buttonSort_Click(YamuiButtonImage sender, EventArgs e) { Config.Instance.CodeExplorerSortingType++; if (Config.Instance.CodeExplorerSortingType > SortingType.Alphabetical) { Config.Instance.CodeExplorerSortingType = SortingType.NaturalOrder; } filterbox.ExtraButtonsList[2].BackGrndImage = Config.Instance.CodeExplorerSortingType == SortingType.Alphabetical ? ImageResources.Alphabetical_sorting : ImageResources.Numerical_sorting; ParserHandler.ParseDocumentNow(); Sci.GrabFocus(); }
private void buttonRefresh_Click(YamuiButtonImage sender, EventArgs e) { if (Refreshing) { return; } ParserHandler.ClearStaticData(); Npp.CurrentSci.Lines.Reset(); ParserHandler.ParseDocumentNow(); Sci.GrabFocus(); }
protected override void OnVisibilityChange(bool visible) { Config.Instance.CodeExplorerVisible = visible; if (visible) { if (NotificationsPublisher.PluginIsReady) { ParserHandler.ParseDocumentAsap(); } } }
/// <summary> /// this methods sorts the items to put the best match on top and then filter it with modelFilter /// </summary> private void ApplyFilter() { Keyword.Width = _normalWidth - (Config.Instance.AutoCompleteHideScrollBar ? 0 : 17); // save position in the list var curPos = new Point(fastOLV.SelectedIndex, fastOLV.TopItemIndex); // apply filter to each item in the list then set the list try { _initialObjectsList.ForEach(data => data.FilterApply(_filterByText)); } catch (Exception e) { if (!(e is NullReferenceException)) { ErrorHandler.LogError(e); } } if (String.IsNullOrEmpty(_filterByText)) { fastOLV.SetObjects(_initialObjectsList); } else { fastOLV.SetObjects(_initialObjectsList.OrderBy(data => data.FilterDispertionLevel).ToList()); } // apply the filter, need to match the filter + need to be an active type (Selector button activated) // + need to be in the right scope for variables _currentLineNumber = Npp.Line.CurrentLine; _currrentScope = ParserHandler.GetScopeOfLine(_currentLineNumber); if (!Config.Instance.AutoCompleteOnlyShowDefinedVar) { _currentLineNumber = -1; } _useTypeFiltering = true; _useTextFiltering = true; fastOLV.ModelFilter = new ModelFilter(FilterPredicate); // update total items TotalItems = ((ArrayList)fastOLV.FilteredObjects).Count; nbitems.Text = TotalItems + StrItems; if (TotalItems <= Config.Instance.AutoCompleteShowListOfXSuggestions) { Keyword.Width = _normalWidth; } // reposition the cursor in the list if (TotalItems > 0) { fastOLV.SelectedIndex = Math.Max(0, Math.Min(curPos.X, TotalItems - 1)); fastOLV.TopItemIndex = Math.Max(0, Math.Min(curPos.Y, TotalItems - 1)); } }
/// <summary> /// Applies the same sorting / filtering as the autocompletion form to a given list /// of items /// </summary> public static List <CompletionItem> ExternalFilterItems(List <CompletionItem> objectsList, int line, bool dontCheckLine = false) { objectsList.Sort(new CompletionDataSortingClass()); if (_displayedTypes == null) { _displayedTypes = new Dictionary <CompletionType, SelectorButton <CompletionType> >(); } _useTypeFiltering = false; _useTextFiltering = false; _currrentScope = ParserHandler.GetScopeOfLine(line); _currentLineNumber = (!Config.Instance.AutoCompleteOnlyShowDefinedVar || dontCheckLine) ? -1 : line; return(objectsList.Where(FilterPredicate).ToList()); }
/// <summary> /// Returns true if the conditions have changed /// </summary> public bool UpdateConditions(int currentLineNumber, bool checkLine = true) { if (currentLineNumber != _currentLineNumber) { _currentLineNumber = currentLineNumber; _currentScope = ParserHandler.GetScopeOfLine <ParsedScopeBlock>(currentLineNumber); if (!checkLine || !Config.Instance.AutoCompleteOnlyShowDefinedVar) { _currentLineNumber = -1; } return(true); } return(false); }
/// <summary> /// Returns a keyword from the autocompletion list with the correct case /// </summary> /// <param name="keyword"></param> /// <param name="lastWordPos"></param> /// <returns></returns> public static string CorrectKeywordCase(string keyword, int lastWordPos) { string output = null; if (!Config.Instance.DisableAutoCaseCompletly) { var found = FindInSavedItems(keyword, Npp.Line.CurrentLine); if (found != null) { RememberUseOf(found); int caseMode; if (found.FromParser) { caseMode = 4; // use displayText case } else if (found.Type == CompletionType.Database || found.Type == CompletionType.Field || found.Type == CompletionType.FieldPk || found.Type == CompletionType.Sequence || found.Type == CompletionType.Table) { caseMode = Config.Instance.DatabaseChangeCaseMode; } else { caseMode = Config.Instance.KeywordChangeCaseMode; } output = keyword.ConvertCase(caseMode, found.DisplayText); } else { // search in tables fields var tableFound = ParserHandler.FindAnyTableOrBufferByName(Npp.GetFirstWordRightAfterPoint(lastWordPos)); if (tableFound != null) { var fieldFound = DataBase.FindFieldByName(keyword, tableFound); if (fieldFound != null) { RememberUseOf(new CompletionItem { FromParser = false, DisplayText = fieldFound.Name, Type = CompletionType.Field, Ranking = 0 }); RememberUseOfDatabaseItem(fieldFound.Name); output = keyword.ConvertCase(tableFound.IsTempTable ? 4 : Config.Instance.DatabaseChangeCaseMode, fieldFound.Name); } } } } return(output); }
ParserResult <T> ParseInput <T>(ProjectInput input, ParserHandler <T> handler) { var result = new ParserResult <T> { Input = input }; if (!File.Exists(input.FullPath)) { result.Kind = ParserResultKind.FileNotFound; return(result); } handler(input, result); return(result); }
private void BuildFinisedEvent(SolutionEventsListener sender, System.EventArgs e) { if (!IsActive) { return; } var args = e as SolutionBuildFinishedEvent; var handler = new ParserHandler(string.Empty) { Model = this, Folder = args.ProjectFolder }; handler.Parse(); }
static void Main(string[] args) { var handler = new ParserHandler(); var parser = new HttpCombinedParser(handler); var bArray = Encoding.UTF8.GetBytes(TestReponse()); System.Console.WriteLine(parser.Execute(new ArraySegment <byte>(bArray, 0, bArray.Length)) == bArray.Length ? $"Reponse test succeed. Type identified is; {handler.MessageType}" : $"Response test failed"); bArray = Encoding.UTF8.GetBytes(TestRequest()); System.Console.WriteLine(parser.Execute(new ArraySegment <byte>(bArray, 0, bArray.Length)) == bArray.Length ? $"Request test succeed. Type identified is; {handler.MessageType}" : $"Request test failed"); System.Console.ReadKey(); }
/// <summary> /// this method should be called at the plugin's start and when we change the current database /// It refreshed the "static" items of the autocompletion : keywords, snippets, databases, tables, sequences /// </summary> public static void RefreshStaticItems() { if (_itemsListLock.TryEnterWriteLock(-1)) { try { _staticItems.Clear(); _staticItems = Keywords.GetList().ToList(); _staticItems.AddRange(Snippets.Keys.Select(x => new CompletionItem { DisplayText = x, Type = CompletionType.Snippet, Ranking = 0, FromParser = false, Flag = 0 }).ToList()); _staticItems.AddRange(DataBase.GetDbList()); _staticItems.AddRange(DataBase.GetSequencesList()); _staticItems.AddRange(DataBase.GetTablesList()); // we do the sorting (by type and then by ranking), doing it now will reduce the time for the next sort() _staticItems.Sort(new CompletionDataSortingClass()); } finally { _itemsListLock.ExitWriteLock(); } } // update parser? if (_initialized) { ParserHandler.ParseCurrentDocument(); } _initialized = true; // OnUpdatedStaticItems if (OnUpdatedStaticItems != null) { OnUpdatedStaticItems(); } // refresh the list of all the saved items (static + dynamic) RefreshDynamicItems(); }
public async Task CanReadAndWriteFromSocketFeatureInConnectionMiddleware() { var builder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { options.ListenAnyIP(0, lo => { lo.Use(next => { return(async connection => { var socket = connection.Features.Get <IConnectionSocketFeature>().Socket; Assert.NotNull(socket); var buffer = new byte[4096]; var read = await socket.ReceiveAsync(buffer, SocketFlags.None); static void ParseHttp(ReadOnlySequence <byte> data) { var parser = new HttpParser <ParserHandler>(); var handler = new ParserHandler(); var reader = new SequenceReader <byte>(data); // Assume we can parse the HTTP request in a single buffer Assert.True(parser.ParseRequestLine(handler, ref reader)); Assert.True(parser.ParseHeaders(handler, ref reader)); Assert.Equal(KestrelHttpMethod.Get, handler.HttpMethod); Assert.Equal(KestrelHttpVersion.Http11, handler.HttpVersion); } ParseHttp(new ReadOnlySequence <byte>(buffer[0..read])); await socket.SendAsync(Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n"), SocketFlags.None); }); }); });
public static void OnSciModified(SCNotification nc) { bool deletedText = (nc.modificationType & (int)SciMsg.SC_MOD_DELETETEXT) != 0; // if the text has changed if (deletedText || (nc.modificationType & (int)SciMsg.SC_MOD_INSERTTEXT) != 0) { // observe modifications to lines (MANDATORY) Npp.UpdateLinesInfo(nc, !deletedText); // parse ParserHandler.ParseCurrentDocument(); } // did the user supress 1 char? if (deletedText && nc.length == 1) { AutoComplete.UpdateAutocompletion(); } }
public ParserHandlerTests() { var mixers = new IMixer[] { new EqualLengthMixer(), new SingleVerseNumberMixer(), new LastMixer(), }; var booksJson = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Dictionary", "book-names.json")); var booksSettings = JsonConvert.DeserializeObject <BooksSettings>(booksJson); var books = Options.Create(booksSettings); var sectionsJson = File.ReadAllText(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Dictionary", "sections.json")); var sectionsSettings = JsonConvert.DeserializeObject <SectionsSettings>(sectionsJson); var sections = Options.Create(sectionsSettings); var bibleAnalyser = new BibleAnalyser(new Bible(books, sections)); _parserHandler = new ParserHandler(new MixerFactory(mixers), bibleAnalyser); }
static void Main(string[] args) { ParserHandler argsParser = new ParserHandler(); WebServices webServices = new WebServices(); DataServices dataServices = new DataServices(); OutputServices outputServices = new OutputServices(); Options userInputData = argsParser.ParseArgs(args); string url = webServices.GenerateUrlFromDistrictId(userInputData.District, userInputData.Source); List <Value> response = webServices.FetchData(url); List <Value> filteredData = dataServices.FilterData(userInputData, response); DataOutput outputData = outputServices.PrepareDataForOutput(filteredData); string jsonString = outputServices.GenerateJsonString(outputData); outputServices.PrintDataToConsole(outputData); outputServices.SaveJsonToFile(userInputData.Out, jsonString); }
public static void DeleteCode <T>() where T : ParsedScopeItem { // make sure to parse the current document before doing anything ParserHandler.ParseCurrentDocument(true, true); // make a list of existing items for this type var existingList = ParserHandler.AblParser.ParsedItemsList.Where(item => item.GetType() == typeof(T)).Cast <T>().ToList(); object nameToDelete = new ProCodeDelete { Value = string.Join("|", existingList.Select(arg => arg.Name)) }; if (string.IsNullOrEmpty(((ProCodeDelete)nameToDelete).Value)) { UserCommunication.Notify("Sorry, there was nothing to do!", MessageImg.MsgInfo, "Delete code", "Nothing to delete!", 5); return; } if (UserCommunication.Input(ref nameToDelete, "Please select which piece of code should be deleted", MessageImg.MsgQuestion, "Delete code", "Select the item to delete") != 0) { return; } var delete = (ProCodeDelete)nameToDelete; if (string.IsNullOrEmpty(delete.Value)) { return; } var toDelete = existingList.FirstOrDefault(item => item.Name.Equals(delete.Value)); if (toDelete != null) { DeleteCode(toDelete); } }
static void Main(string[] args) { byte[] bArray; using (var handler = new ParserHandler()) using (var parser = new HttpCombinedParser(handler)) { bArray = TestReponse(); System.Console.WriteLine(parser.Execute(new ArraySegment <byte>(bArray, 0, bArray.Length)) == bArray.Length ? $"Reponse test succeed. Type identified is; {handler.MessageType}" : $"Response test failed"); handler.HttpRequestReponse.Body.Position = 0; var reader = new StreamReader(handler.HttpRequestReponse.Body); var body = reader.ReadToEnd(); //bArray = Encoding.UTF8.GetBytes(TestRequest()); //System.Console.WriteLine(parser.Execute(new ArraySegment<byte>(bArray, 0, bArray.Length)) == bArray.Length // ? $"Request test succeed. Type identified is; {handler.MessageType}" // : $"Request test failed"); } using (var handler = new ParserHandler()) using (var parser = new HttpCombinedParser(handler)) { bArray = TestChunkedResponse(); System.Console.WriteLine(parser.Execute(new ArraySegment <byte>(bArray, 0, bArray.Length)) == bArray.Length ? $"Chunked Response test succeed. Type identified is; {handler.MessageType}." : $"Chunked Response test failed"); handler.HttpRequestReponse.Body.Position = 0; var reader = new StreamReader(handler.HttpRequestReponse.Body); var body = reader.ReadToEnd(); } System.Console.ReadKey(); }
public void SetAdvancedParser(ParserHandler parser) { this._advancedParser = parser; }
/// <summary> /// Sets the content of the tooltip (when we want to descibe something present in the completionData list) /// </summary> private static void SetToolTip() { var popupMinWidth = 250; var toDisplay = new StringBuilder(); GoToDefinitionFile = null; // only select one item from the list var data = GetCurrentlyDisplayedCompletionData(); if (data == null) { return; } CurrentWord = data.DisplayText; // general stuff toDisplay.Append("<div class='InfoToolTip' id='ToolTip'>"); toDisplay.Append(@" <table width='100%' class='ToolTipName'> <tr style='vertical-align: top;'> <td> <table width='100%' style='margin: 0; padding: 0;'> <tr> <td rowspan='2' style='width: 25px;'> <img src='" + data.Type + @"'> </td> <td> " + data.DisplayText + @" </td> </tr> <tr> <td> <span class='ToolTipSubString'>" + data.Type + @"</span> </td> </tr> </table> </td>"); if (_currentCompletionList.Count > 1) { toDisplay.Append(@" <td class='ToolTipCount'>" + (IndexToShow + 1) + "/" + _currentCompletionList.Count + @" </td>"); } toDisplay.Append(@" </tr> </table>"); // the rest depends on the item type try { switch (data.Type) { case CompletionType.TempTable: case CompletionType.Table: popupMinWidth = Math.Min(500, Npp.NppScreen.WorkingArea.Width / 2); // buffer if (data.FromParser) { if (data.ParsedItem is ParsedDefine) { toDisplay.Append(FormatRowWithImg(ParseFlag.Buffer.ToString(), "BUFFER FOR " + FormatSubString(data.SubString))); } if (data.ParsedItem is ParsedTable && !string.IsNullOrEmpty(data.SubString)) { toDisplay.Append(FormatRow("Is like", (data.SubString.Contains("?")) ? "Unknow table [" + ((ParsedTable)data.ParsedItem).LcLikeTable + "]" : data.SubString.Replace("Like ", ""))); } } var tbItem = ParserHandler.FindAnyTableOrBufferByName(data.DisplayText); if (tbItem != null) { if (!string.IsNullOrEmpty(tbItem.Description)) { toDisplay.Append(FormatRow("Description", tbItem.Description)); } if (tbItem.Fields.Count > 0) { toDisplay.Append(FormatSubtitle("FIELDS [x" + tbItem.Fields.Count + "]")); toDisplay.Append("<table width='100%;'>"); foreach (var parsedField in tbItem.Fields) { toDisplay.Append("<tr><td><img src='" + (parsedField.Flag.HasFlag(ParsedFieldFlag.Primary) ? CompletionType.FieldPk.ToString() : CompletionType.Field.ToString()) + "'></td><td style='padding-right: 4px'>" + (parsedField.Flag.HasFlag(ParsedFieldFlag.Mandatory) ? "<img src='Mandatory'>" : "") + "</td><td style='padding-right: 8px'>" + parsedField.Name + "</td><td style='padding-right: 8px'>" + parsedField.Type + "</td><td style='padding-right: 8px'> = " + (parsedField.Type == ParsedPrimitiveType.Character ? parsedField.InitialValue.ProQuoter() : parsedField.InitialValue) + "</td><td style='padding-right: 8px'>" + parsedField.Description + "</td></tr>"); } toDisplay.Append("</table>"); } if (tbItem.Triggers.Count > 0) { toDisplay.Append(FormatSubtitle("TRIGGERS [x" + tbItem.Triggers.Count + "]")); foreach (var parsedTrigger in tbItem.Triggers) { toDisplay.Append(FormatRow(parsedTrigger.Event, "<a class='ToolGotoDefinition' href='trigger#" + parsedTrigger.ProcName + "'>" + parsedTrigger.ProcName + "</a>")); } } if (tbItem.Indexes.Count > 0) { toDisplay.Append(FormatSubtitle("INDEXES [x" + tbItem.Indexes.Count + "]")); foreach (var parsedIndex in tbItem.Indexes) { toDisplay.Append(FormatRow(parsedIndex.Name, ((parsedIndex.Flag != ParsedIndexFlag.None) ? parsedIndex.Flag + " - " : "") + parsedIndex.FieldsList.Aggregate((i, j) => i + ", " + j))); } } } break; case CompletionType.Sequence: toDisplay.Append(FormatRow("Database logical name", data.SubString)); break; case CompletionType.Database: var dbItem = DataBase.GetDb(data.DisplayText); toDisplay.Append(FormatRow("Logical name", dbItem.LogicalName)); toDisplay.Append(FormatRow("Physical name", dbItem.PhysicalName)); toDisplay.Append(FormatRow("Progress version", dbItem.ProgressVersion)); toDisplay.Append(FormatRow("Number of Tables", dbItem.Tables.Count.ToString())); break; case CompletionType.Field: case CompletionType.FieldPk: // find field var fieldFound = DataBase.FindFieldByName(data.DisplayText, (ParsedTable)data.ParsedItem); if (fieldFound != null) { if (fieldFound.AsLike == ParsedAsLike.Like) { toDisplay.Append(FormatRow("Is LIKE", fieldFound.TempType)); } toDisplay.Append(FormatRow("Type", FormatSubString(data.SubString))); toDisplay.Append(FormatRow("Owner table", ((ParsedTable)data.ParsedItem).Name)); if (!string.IsNullOrEmpty(fieldFound.Description)) { toDisplay.Append(FormatRow("Description", fieldFound.Description)); } if (!string.IsNullOrEmpty(fieldFound.Format)) { toDisplay.Append(FormatRow("Format", fieldFound.Format)); } if (!string.IsNullOrEmpty(fieldFound.InitialValue)) { toDisplay.Append(FormatRow("Initial value", fieldFound.InitialValue)); } toDisplay.Append(FormatRow("Order", fieldFound.Order.ToString())); } break; case CompletionType.Procedure: // find its parameters toDisplay.Append(FormatSubtitle("PARAMETERS")); var paramList = ParserHandler.FindProcedureParameters(data); if (paramList.Count > 0) { foreach (var parameter in paramList) { var defItem = (ParsedDefine)parameter.ParsedItem; toDisplay.Append(FormatRowParam(defItem.LcFlagString, parameter.DisplayText + " as <span class='ToolTipSubString'>" + defItem.PrimitiveType + "</span>")); } } else { toDisplay.Append("None"); } break; case CompletionType.Function: var funcItem = (ParsedFunction)data.ParsedItem; toDisplay.Append(FormatSubtitle("RETURN TYPE")); toDisplay.Append(FormatRowParam("output", "Returns " + FormatSubString(funcItem.ReturnType.ToString()))); toDisplay.Append(FormatSubtitle("PARAMETERS")); var param2List = ParserHandler.FindProcedureParameters(data); if (param2List.Count > 0) { foreach (var parameter in param2List) { var defItem = (ParsedDefine)parameter.ParsedItem; toDisplay.Append(FormatRowParam(defItem.LcFlagString, parameter.DisplayText + " as " + FormatSubString(defItem.PrimitiveType.ToString()))); } } else { toDisplay.Append("None"); } var funcImplem = data.ParsedItem as ParsedImplementation; if (funcImplem != null) { toDisplay.Append(FormatSubtitle("PROTOTYPE")); if (funcImplem.HasPrototype) { toDisplay.Append(FormatRowWithImg("Prototype", "<a class='ToolGotoDefinition' href='proto#" + funcItem.FilePath + "#" + funcImplem.PrototypeLine + "#" + funcImplem.PrototypeColumn + "'>Go to prototype</a>")); } else { toDisplay.Append("Has none"); } } else { toDisplay.Append(FormatSubtitle("DEFINED IN")); toDisplay.Append("Function defined in an external procedure or is a web service operation"); } break; case CompletionType.Keyword: case CompletionType.KeywordObject: toDisplay.Append(FormatRow("Type of keyword", FormatSubString(data.SubString))); // for abbreviations, find the complete keyword first string keyword = data.DisplayText; if (data.KeywordType == KeywordType.Abbreviation) { keyword = Keywords.GetFullKeyword(keyword); var associatedKeyword = AutoComplete.FindInCompletionData(keyword, 0); if (associatedKeyword != null && associatedKeyword.Count > 0) { data = associatedKeyword.First(); } } string keyToFind = null; // for the keywords define and create, we try to match the second keyword that goes with it if (data.KeywordType == KeywordType.Statement && (keyword.EqualsCi("define") || keyword.EqualsCi("create"))) { var lineStr = Npp.GetLine(Npp.LineFromPosition(Npp.GetPositionFromMouseLocation())).Text; var listOfSecWords = new List <string> { "ALIAS", "BROWSE", "BUFFER", "BUTTON", "CALL", "CLIENT-PRINCIPAL", "DATA-SOURCE", "DATABASE", "DATASET", "EVENT", "FRAME", "IMAGE", "MENU", "PARAMETER", "PROPERTY", "QUERY", "RECTANGLE", "SAX-ATTRIBUTES", "SAX-READER", "SAX-WRITER", "SERVER", "SERVER-SOCKET", "SOAP-HEADER", "SOAP-HEADER-ENTRYREF", "SOCKET", "STREAM", "SUB-MENU", "TEMP-TABLE", "VARIABLE", "WIDGET-POOL", "WORK-TABLE", "WORKFILE", "X-DOCUMENT", "X-NODEREF" }; foreach (var word in listOfSecWords) { if (lineStr.ContainsFast(word)) { keyToFind = string.Join(" ", keyword, word, data.SubString); break; } } } if (keyToFind == null) { keyToFind = string.Join(" ", keyword, data.SubString); } var dataHelp = Keywords.GetKeywordHelp(keyToFind); if (dataHelp != null) { toDisplay.Append(FormatSubtitle("DESCRIPTION")); toDisplay.Append(dataHelp.Description); // synthax if (dataHelp.Synthax.Count >= 1 && !string.IsNullOrEmpty(dataHelp.Synthax[0])) { toDisplay.Append(FormatSubtitle("SYNTAX")); toDisplay.Append(@"<div class='ToolTipcodeSnippet'>"); var i = 0; foreach (var synthax in dataHelp.Synthax) { if (i > 0) { toDisplay.Append(@"<br>"); } toDisplay.Append(synthax); i++; } toDisplay.Append(@"</div>"); } } else { toDisplay.Append(FormatSubtitle("404 NOT FOUND")); if (data.KeywordType == KeywordType.Option) { toDisplay.Append("<i><b>Sorry, this keyword doesn't have any help associated</b><br>Since this keyword is an option, try to hover the first keyword of the statement or refer to the 4GL help</i>"); } else { toDisplay.Append("<i><b>Sorry, this keyword doesn't have any help associated</b><br>Please refer to the 4GL help</i>"); } } CurrentWord = keyToFind; break; case CompletionType.Label: break; case CompletionType.Preprocessed: var preprocItem = (ParsedPreProc)data.ParsedItem; if (preprocItem.UndefinedLine > 0) { toDisplay.Append(FormatRow("Undefined line", preprocItem.UndefinedLine.ToString())); } toDisplay.Append(FormatSubtitle("VALUE")); toDisplay.Append(@"<div class='ToolTipcodeSnippet'>"); toDisplay.Append(preprocItem.Value); toDisplay.Append(@"</div>"); break; case CompletionType.Snippet: // TODO break; case CompletionType.VariableComplex: case CompletionType.VariablePrimitive: case CompletionType.Widget: var varItem = (ParsedDefine)data.ParsedItem; toDisplay.Append(FormatRow("Define type", FormatSubString(varItem.Type.ToString()))); if (!string.IsNullOrEmpty(varItem.TempPrimitiveType)) { toDisplay.Append(FormatRow("Variable type", FormatSubString(varItem.PrimitiveType.ToString()))); } if (varItem.AsLike == ParsedAsLike.Like) { toDisplay.Append(FormatRow("Is LIKE", varItem.TempPrimitiveType)); } if (!string.IsNullOrEmpty(varItem.ViewAs)) { toDisplay.Append(FormatRow("Screen representation", varItem.ViewAs)); } if (!string.IsNullOrEmpty(varItem.LcFlagString)) { toDisplay.Append(FormatRow("Define flags", varItem.LcFlagString)); } if (!string.IsNullOrEmpty(varItem.Left)) { toDisplay.Append(FormatSubtitle("END OF DECLARATION")); toDisplay.Append(@"<div class='ToolTipcodeSnippet'>"); toDisplay.Append(varItem.Left); toDisplay.Append(@"</div>"); } break; } } catch (Exception e) { toDisplay.Append("Error when appending info :<br>" + e + "<br>"); } // parsed item? if (data.FromParser) { toDisplay.Append(FormatSubtitle("ORIGINS")); toDisplay.Append(FormatRow("Scope name", data.ParsedItem.Scope.Name)); if (!Plug.CurrentFilePath.Equals(data.ParsedItem.FilePath)) { toDisplay.Append(FormatRow("Owner file", "<a class='ToolGotoDefinition' href='gotoownerfile#" + data.ParsedItem.FilePath + "'>" + data.ParsedItem.FilePath + "</a>")); } } // Flags var flagStrBuilder = new StringBuilder(); data.DoForEachFlag((name, flag) => { flagStrBuilder.Append(FormatRowWithImg(name, "<b>" + name + "</b>")); }); if (flagStrBuilder.Length > 0) { toDisplay.Append(FormatSubtitle("FLAGS")); toDisplay.Append(flagStrBuilder); } toDisplay.Append(@"<div class='ToolTipBottomGoTo'> [HIT CTRL ONCE] Prevent auto-close"); // parsed item? if (data.FromParser) { toDisplay.Append(@"<br>[" + Config.Instance.GetShortcutSpecFromName("Go_To_Definition").ToUpper() + "] <a class='ToolGotoDefinition' href='gotodefinition'>Go to definition</a>"); GoToDefinitionPoint = new Point(data.ParsedItem.Line, data.ParsedItem.Column); GoToDefinitionFile = data.ParsedItem.FilePath; } if (_currentCompletionList.Count > 1) { toDisplay.Append("<br>[CTRL + <span class='ToolTipDownArrow'>" + (char)242 + "</span>] <a class='ToolGotoDefinition' href='nexttooltip'>Read next tooltip</a>"); } toDisplay.Append("</div>"); toDisplay.Append("</div>"); _form.SetText(toDisplay.ToString(), popupMinWidth); }
public void addCommand(string com, ParserHandler handler) { commands.Add(com.ToLower(), handler); }