/// <summary> /// Simple click handler that opens any link as a file (either in notepad++ if the extension is known, /// or with the default program, or as a folder in the explorer) /// </summary> /// <param name="sender"></param> /// <param name="htmlLinkClickedEventArgs"></param> public static void OpenPathClickHandler(object sender, HtmlLinkClickedEventArgs htmlLinkClickedEventArgs) { if (htmlLinkClickedEventArgs.Link.Contains("|")) { var splitted = htmlLinkClickedEventArgs.Link.Split('|'); if (splitted.Length == 2) { Npp.Goto(splitted[0], int.Parse(splitted[1])); } else { Npp.Goto(splitted[0], int.Parse(splitted[1]), int.Parse(splitted[2])); } htmlLinkClickedEventArgs.Handled = true; } else { htmlLinkClickedEventArgs.Handled = OpenAnyLink(htmlLinkClickedEventArgs.Link); } }
/// <summary> /// If no selection, comment the line of the caret /// If selection, comment the selection as a block /// </summary> public static void ToggleComment() { Npp.BeginUndoAction(); // for each selection (limit selection number) for (var i = 0; i < Npp.Selection.Count; i++) { var selection = Npp.GetSelection(i); int startPos; int endPos; bool singleLineComm = false; if (selection.Caret == selection.Anchor) { // comment line var thisLine = new Npp.Line(Npp.LineFromPosition(selection.Caret)); startPos = thisLine.IndentationPosition; endPos = thisLine.EndPosition; singleLineComm = true; } else { startPos = selection.Start; endPos = selection.End; } var toggleMode = ToggleCommentOnRange(startPos, endPos); if (toggleMode == 3) { selection.SetPosition(startPos + 3); } // correct selection... if (!singleLineComm && toggleMode == 2) { selection.End += 2; } } Npp.EndUndoAction(); }
protected override void OnActivated(EventArgs e) { // Activate the window that previously had focus if (!_focusAllowed) { if (GiveFocusBackToScintilla) { Npp.GrabFocus(); } else { WinApi.SetForegroundWindow(CurrentForegroundWindow); } } else { IsActivated = true; Opacity = FocusedOpacity; } base.OnActivated(e); }
public NppDockableDialogForm(Form formToCover) : this() { _masterForm = formToCover; _masterForm.VisibleChanged += Cover_OnVisibleChanged; _masterForm.Closed += MasterFormOnClosed; _masterForm.SizeChanged += Cover_OnVisibleChanged; _masterForm.Paint += Cover_OnVisibleChanged; ClientSize = _masterForm.ClientSize; Show(_masterForm); // Disable Aero transitions, the plexiglass gets too visible if (Environment.OSVersion.Version.Major >= 6) { int value = 1; WinApi.DwmSetWindowAttribute(Owner.Handle, WinApi.DwmwaTransitionsForcedisabled, ref value, 4); } // register to Npp Npp.RegisterToNpp(Owner.Handle); }
/// <summary> /// Delete the given ParsedScopeItem whose name is qualified through proCode.Name /// </summary> public static bool DeleteCode <T>(T toDelete) where T : ParsedScopeItem { string preProcBlockType = null; if (typeof(ParsedImplementation) == typeof(T)) { preProcBlockType = @"_FUNCTION"; } else if (typeof(ParsedPrototype) == typeof(T)) { preProcBlockType = @"_FUNCTION-FORWARD"; } else if (typeof(ParsedProcedure) == typeof(T)) { preProcBlockType = @"_PROCEDURE"; } // find a pre proc block that surrounds it var protoPreProcBlock = GetPreProcBlock(toDelete, preProcBlockType); // we also want to delete the trailing new lines int endPosition = (protoPreProcBlock != null ? protoPreProcBlock.EndBlockPosition : toDelete.EndPosition); while (Npp.GetTextByRange(endPosition, endPosition + 2).Equals(Npp.GetEolString)) { endPosition += 2; } if (protoPreProcBlock != null) { Npp.DeleteTextByRange(protoPreProcBlock.Position, endPosition); } else { // if not found, we just delete the proto statement Npp.DeleteTextByRange(toDelete.Position, endPosition); } return(true); }
/// <summary> /// Toggle the docked form on and off, can be called first and will initialize the form /// </summary> public void Toggle() { try { // initialize if not done if (_fakeForm == null) { // register fake form to Npp _fakeForm = new NppDockableDialogFakeForm(); NppTbData nppTbData = new NppTbData { hClient = _fakeForm.Handle, pszName = AssemblyInfo.AssemblyProduct + " - " + _dialogDescription, dlgID = DockableCommandIndex, uMask = _formDefaultPos | NppTbMsg.DWS_ICONTAB | NppTbMsg.DWS_ICONBAR, hIconTab = (uint)Utils.GetIconFromImage(_iconImage).Handle, pszModuleName = AssemblyInfo.AssemblyProduct }; Npp.RegisterDockableDialog(nppTbData); _fakeForm.OnDockableDialogClose += FormOnOnDockableDialogClose; InitForm(); IsVisible = true; } else { if (IsVisible) { Npp.HideDockableDialog(_fakeForm.Handle); IsVisible = false; } else { Npp.ShowDockableDialog(_fakeForm.Handle); IsVisible = true; } } Form.RefreshPosAndLoc(); } catch (Exception e) { ErrorHandler.ShowErrors(e, "Error loading " + _dialogDescription); } }
public override void Run() { if (Npp.Editor.GetCurrentFilePath().EndsWith(".dsl")) { string hint = Editor.GetSuggestionHint(); string[] suggestions = Parser.GetSuggestions(hint); Point caretPoint = Npp.GetCaretScreenLocation(); Form form; if (suggestions.Length > 0) { form = new SuggestionList(suggestions, caretPoint, Editor.ApplySuggestion); } else { form = new SuggestionList(new[] { "< no suggestions >" }, caretPoint); } form.Show(); } }
/// <summary> /// Shows an error to the user /// </summary> /// <param name="e"></param> /// <param name="message"></param> public static void ShowErrors(Exception e, string message = null) { if (LogError(e, message)) { if (UserCommunication.Ready) { // show it to the user UserCommunication.Notify("The last action you started has triggered an error and has been cancelled.<div class='ToolTipcodeSnippet'>" + e.Message + "</div><br>1. If you didn't ask anything from 3P then you can probably ignore this message.<br>2. Otherwise, you might want to check out the error log below for more details :" + (File.Exists(Config.FileErrorLog) ? "<br>" + Config.FileErrorLog.ToHtmlLink("Link to the error log") : "no .log found!") + "<br>Consider opening an issue on GitHub :<br>" + Config.IssueUrl.ToHtmlLink() + "<br><br>If needed, try to restart Notepad++ and see if things are better!</b>", MessageImg.MsgPoison, "An error has occured", message, args => { if (args.Link.EndsWith(".log")) { Npp.Goto(args.Link); args.Handled = true; } }); } else { // show an old school message MessageBox.Show("An error has occurred and we couldn't display a notification.\n\nThis very likely happened during the plugin loading; hence there is a hugh probability that it will cause the plugin to not operate normally.\n\nCheck the log at the following location to learn more about this error : " + Config.FileErrorLog.ProQuoter() + "\n\nTry to restart Notepad++, consider opening an issue on : " + Config.IssueUrl + " if the problem persists.", AssemblyInfo.AssemblyProduct + " error message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
/// <summary> /// Shows a Messagebox informing the user that something went wrong with a file, /// renames said file with the suffix "_errors" /// </summary> public static void ShowErrors(Exception e, string message, string fileName) { if (UserCommunication.Ready) { UserCommunication.Notify("An error has occurred while loading the following file :<div>" + (fileName + "_errors").ToHtmlLink() + "</div><br>The file has been suffixed with '_errors' to avoid further problems.", MessageImg.MsgPoison, "File load error", message, args => { if (args.Link.EndsWith(".log")) { Npp.Goto(args.Link); args.Handled = true; } }); } else { MessageBox.Show("An error has occurred while loading the following file :" + "\n\n" + fileName + "\n\n" + "The file has been suffixed with '_errors' to avoid further problems.", AssemblyInfo.AssemblyProduct + " error message", MessageBoxButtons.OK, MessageBoxIcon.Error); } Utils.DeleteFile(fileName + "_errors"); Utils.MoveFile(fileName, fileName + "_errors"); ShowErrors(e, message); }
static public void FinalizeCurrent() { var indic = Npp.GetIndicator(SnippetContext.IndicatorId); var indicators = indic.FindRanges().ToArray(); foreach (var range in indicators) { indic.Clear(range.X, range.Y); } var caretPoint = indicators.Where(point => { string text = Npp.GetTextBetween(point); return(text == " " || text == "|"); }) .FirstOrDefault(); if (caretPoint.X != caretPoint.Y) { Npp.SetTextByRange(caretPoint.X, caretPoint.Y, ""); Npp.SetSelection(caretPoint.X, caretPoint.X); } LocSnippetContext = null; }
/// <summary> /// Allows the user to surround its selection with custom modification tags /// </summary> public static void SurroundSelectionWithTag() { CommonTagAction(fileInfo => { var output = new StringBuilder(); Npp.TargetFromSelection(); var indent = new String(' ', Npp.GetLine(Npp.LineFromPosition(Npp.TargetStart)).Indentation); var opener = FileTag.ReplaceTokens(fileInfo, Config.Instance.TagModifOpener); var eol = Npp.GetEolString; output.Append(opener); output.Append(eol); output.Append(indent); output.Append(Npp.SelectedText); output.Append(eol); output.Append(indent); output.Append(FileTag.ReplaceTokens(fileInfo, Config.Instance.TagModifCloser)); Npp.TargetFromSelection(); Npp.ReplaceTarget(output.ToString()); Npp.SetSel(Npp.TargetStart + opener.Length + eol.Length); }); }
public AppliForm() { InitializeComponent(); // create the tabs / content CreateContent(new List <YamuiMainMenu> { new YamuiMainMenu("Home", null, false, new List <YamuiSecMenu> { new YamuiSecMenu("WELCOME", PageNames.Welcome.ToString(), new HomePage()) }), new YamuiMainMenu("Set", null, false, new List <YamuiSecMenu> { new YamuiSecMenu("ENVIRONMENT", PageNames.SetEnvironment.ToString(), new SetEnvironment()), new YamuiSecMenu("DEPLOYMENT RULES", PageNames.DeploymentRules.ToString(), new SetDeploymentRules()), new YamuiSecMenu("FILE INFORMATION", PageNames.FileInfo.ToString(), new SetFileCustomInfo()) //new YamuiSecMenu("PERSISTENT PROCEDURES", null, new template()) }), new YamuiMainMenu("Actions", null, false, new List <YamuiSecMenu> { // new YamuiSecMenu("CUSTOM SCRIPTS", null, new template()), new YamuiSecMenu("DEPLOY YOUR APPLICATION", PageNames.MassCompiler.ToString(), new DoDeployPage()) }), new YamuiMainMenu("Options", null, false, new List <YamuiSecMenu> { new YamuiSecMenu("GENERAL", PageNames.OptionsGeneral.ToString(), new OptionPage(new List <string> { "General", "Compilation" })), new YamuiSecMenu("COLOR SCHEMES", "colors", new SettingAppearance()), new YamuiSecMenu("UPDATES", PageNames.OptionsUpdate.ToString(), new OptionPage(new List <string> { "Updates" })), new YamuiSecMenu("AUTOCOMPLETION", "autocompletion", new OptionPage(new List <string> { "Autocompletion", "Progress autocompletion", "Default autocompletion replacement" })), new YamuiSecMenu("CODE EDITION", "code_edition", new OptionPage(new List <string> { "Code edition" })), new YamuiSecMenu("MISC", PageNames.OptionsMisc.ToString(), new OptionPage(new List <string> { "File explorer", "Code explorer", "Tooltip", "Switch encoding" })), new YamuiSecMenu("SHORTCUTS", null, new ShortCutsPage()), new YamuiSecMenu("SHARE/EXPORT CONFIG", PageNames.ExportShareConf.ToString(), new ExportPage()) }) }); CreateTopLinks(new List <string> { "FEEDBACK", "REPORT A BUG", "HELP" }, (sender, tabArgs) => { switch (tabArgs.SelectedIndex) { case 0: Process.Start(@"https://github.com/jcaillon/3P/issues/3"); break; case 1: Process.Start(@"" + Config.UrlIssues + ""); break; case 2: Process.Start(@"http://jcaillon.github.io/3P/"); break; } }, 110, 8); // title string strongBold = "<span class='AccentColor'>"; labelTitle.Text = @"<img src='" + HtmlHelper.GetLogo + @"' style='padding-right: 10px'><span class='AppliTitle'>" + strongBold + @"P</span>rogress " + strongBold + @"P</span>rogrammers " + strongBold + @"P</span>al</span> <span style='padding-left: 6px; font-size: 12px;' class='SubTextColor'><b>" + AssemblyInfo.Version + (Environment.Is64BitProcess ? " x64" : "") + (AssemblyInfo.IsPreRelease ? " (beta)" : "") + (Config.IsDeveloper ? " (debug)" : "") + @"</b></span>"; // register to Npp Npp.RegisterToNpp(Handle); }
/// <summary> /// Call this method instead of Close() to really close this form /// </summary> public new void ForceClose() { Npp.UnRegisterToNpp(Handle); _forcingClose = true; base.ForceClose(); }
/// <summary> /// This method allows the user to GOTO a word definition, if a tooltip is opened then it tries to /// go to the definition of the displayed word, otherwise it tries to find the declaration of the parsed word under the /// caret. At last, it tries to find a file in the propath /// </summary> public static void GoToDefinition(bool fromMouseClick) { // if a tooltip is opened, try to execute the "go to definition" of the tooltip first if (InfoToolTip.InfoToolTip.IsVisible) { if (!string.IsNullOrEmpty(InfoToolTip.InfoToolTip.GoToDefinitionFile)) { Npp.Goto(InfoToolTip.InfoToolTip.GoToDefinitionFile, InfoToolTip.InfoToolTip.GoToDefinitionPoint.X, InfoToolTip.InfoToolTip.GoToDefinitionPoint.Y); InfoToolTip.InfoToolTip.Close(); return; } InfoToolTip.InfoToolTip.Close(); } // try to go to the definition of the selected word var position = fromMouseClick ? Npp.GetPositionFromMouseLocation() : Npp.CurrentPosition; if (fromMouseClick && position <= 0) { return; } var curWord = Npp.GetAblWordAtPosition(position); // match a word in the autocompletion? go to definition var data = AutoComplete.FindInCompletionData(curWord, position, true); if (data != null && data.Count > 0) { var nbFound = data.Count(data2 => data2.FromParser); // only one match, then go to the definition if (nbFound == 1) { var completionData = data.First(data1 => data1.FromParser); Npp.Goto(completionData.ParsedItem.FilePath, completionData.ParsedItem.Line, completionData.ParsedItem.Column); return; } if (nbFound > 1) { // otherwise, list the items and notify the user var output = new StringBuilder(@"Found several matching items, please choose the correct one :<br>"); foreach (var cData in data.Where(data2 => data2.FromParser)) { output.Append("<div>" + (cData.ParsedItem.FilePath + "|" + cData.ParsedItem.Line + "|" + cData.ParsedItem.Column).ToHtmlLink("In " + Path.GetFileName(cData.ParsedItem.FilePath) + " (line " + cData.ParsedItem.Line + ")")); cData.DoForEachFlag((s, flag) => { output.Append("<img style='padding-right: 0px; padding-left: 5px;' src='" + s + "' height='15px'>"); }); output.Append("</div>"); } UserCommunication.NotifyUnique("GoToDefinition", output.ToString(), MessageImg.MsgQuestion, "Question", "Go to the definition", args => { Utils.OpenPathClickHandler(null, args); UserCommunication.CloseUniqueNotif("GoToDefinition"); }, 0, 500); return; } } // last resort, try to find a matching file in the propath // if in a string, read the whole string // try to read all the . and \ // first look in the propath var fullPaths = ProEnvironment.Current.FindFiles(curWord, Config.Instance.KnownProgressExtension); if (fullPaths.Count > 0) { if (fullPaths.Count > 1) { var output = new StringBuilder(@"Found several files matching this name, please choose the correct one :<br>"); foreach (var fullPath in fullPaths) { output.Append("<div>" + fullPath.ToHtmlLink() + "</div>"); } UserCommunication.NotifyUnique("GoToDefinition", output.ToString(), MessageImg.MsgQuestion, "Question", "Open a file", args => { Npp.Goto(args.Link); UserCommunication.CloseUniqueNotif("GoToDefinition"); args.Handled = true; }, 0, 500); } else { Npp.Goto(fullPaths[0]); } return; } UserCommunication.Notify("Sorry pal, couldn't go to the definition of <b>" + curWord + "</b>", MessageImg.MsgInfo, "information", "Failed to find an origin", 5); }
/// <summary> /// Open folder or open in npp /// </summary> private void OpenFileOnButtonPressed(object sender, EventArgs eventArgs) { var associatedTextBox = GetTextBoxByName(((Control)sender).Name); if (associatedTextBox == null) { return; } string tag = (string)(associatedTextBox.Tag ?? string.Empty); var ext = Path.GetExtension(associatedTextBox.Text) ?? ""; var hasOpened = tag.Equals("true") ? Utils.OpenFolder(associatedTextBox.Text) : (!ext.Equals(".exe") ? Npp.OpenFile(associatedTextBox.Text) : Utils.OpenFileInFolder(associatedTextBox.Text)); if (!hasOpened) { BlinkTextBox(associatedTextBox, ThemeManager.Current.GenericErrorColor); } }
/// <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); }
private void BtClearAllErrorsOnButtonPressed(object sender, EventArgs buttonPressedEventArgs) { FilesInfo.ClearAllErrors(Plug.CurrentFilePath); Npp.GrabFocus(); }
public static void EditTemplate() { Export(); Npp.OpenFile(Config.FileModificationTags); }
/// <summary> /// Gives focus back to the owner window /// </summary> public void GiveFocusBack() { //WinApi.SetForegroundWindow(CurrentForegroundWindow); Npp.GrabFocus(); Opacity = Config.Instance.AppliOpacityUnfocused; }
static public void EditSnippetsConfig() { Npp.OpenFile(Config.FileSnippets); }
static public bool NavigateToNextParam() { var indic = Npp.GetIndicator(SnippetContext.IndicatorId); indic.Style = IndicatorStyle.Box; indic.ForeColor = Color.Blue; var indicators = indic.FindRanges().ToArray(); if (!indicators.Any()) { return(false); } if (LocSnippetContext.CurrentParameter != null) { Point currentParam = LocSnippetContext.CurrentParameter.Value; string currentParamOriginalText = LocSnippetContext.CurrentParameterValue; Npp.SetSelection(currentParam.X, currentParam.X); string currentParamDetectedText = Npp.GetAblWordAtPosition(Npp.CurrentPosition); if (currentParamOriginalText != currentParamDetectedText) { //current parameter is modified, indicator is destroyed so restore the indicator first indic.Add(currentParam.X, currentParam.X + currentParamDetectedText.Length); indicators = indic.FindRanges().ToArray(); //needs refreshing as the document is modified var paramsInfo = indicators.Select(p => new { Index = indicators.IndexOf(p), Text = Npp.GetTextBetween(p), Range = p, Pos = p.X }) .OrderBy(x => x.Pos) .ToArray(); var paramsToUpdate = paramsInfo.Where(item => item.Text == currentParamOriginalText).ToArray(); foreach (var param in paramsToUpdate) { ReplaceTextAtIndicator(currentParamDetectedText, indicators[param.Index]); indicators = indic.FindRanges().ToArray();//needs refreshing as the document is modified } } Point?nextParameter = null; int currentParamIndex = indicators.FindIndex(x => x.X >= currentParam.X); //can also be logical 'next' var prevParamsValues = indicators.Take(currentParamIndex).Select(p => Npp.GetTextBetween(p)).ToList(); prevParamsValues.Add(currentParamOriginalText); prevParamsValues.Add(currentParamDetectedText); prevParamsValues.Add(" "); prevParamsValues.Add("|"); foreach (var range in indicators.ToArray()) { if (currentParam.X < range.X && !prevParamsValues.Contains(Npp.GetTextBetween(range))) { nextParameter = range; break; } } if (!nextParameter.HasValue) { nextParameter = indicators.FirstOrDefault(); } LocSnippetContext.CurrentParameter = nextParameter; } if (LocSnippetContext.CurrentParameter.HasValue) { Npp.SetSelection(LocSnippetContext.CurrentParameter.Value.X, LocSnippetContext.CurrentParameter.Value.Y); LocSnippetContext.CurrentParameterValue = Npp.GetTextBetween(LocSnippetContext.CurrentParameter.Value); } return(true); }
/// <summary> /// returns the number of chars between two lines in the current document /// </summary> private static int NbExtraCharBetweenLines(int startLine, int endLine) { return((Npp.StartBytePosOfLine(endLine) - Npp.StartBytePosOfLine(startLine)) - Config.Instance.GlobalMaxNbCharInBlock); }
/// <summary> /// Displays the errors for the current file (if any) /// display an annotation with the message below the line + display a marker in the margin /// </summary> public static void UpdateErrorsInScintilla() { // Updates the number of errors in the FileExplorer form and the file status UpdateFileStatus(); var currentFilePath = Plug.CurrentFilePath; var marginError = Npp.GetMargin(ErrorMarginNumber); // need to clear scintilla for this file? if (_sessionInfo.ContainsKey(currentFilePath) && _sessionInfo[currentFilePath].NeedToCleanScintilla) { ClearAnnotationsAndMarkers(); _sessionInfo[currentFilePath].NeedToCleanScintilla = false; } // check if current file is a progress and if we got info on it if (!Plug.IsCurrentFileProgress || !_sessionInfo.ContainsKey(currentFilePath) || _sessionInfo[currentFilePath].FileErrors == null || _sessionInfo[currentFilePath].FileErrors.Count == 0) { if (marginError.Width > 0) { marginError.Width = 1; marginError.Width = 0; } // reset annotation to default Npp.AnnotationVisible = Plug.AnnotationMode; return; } // activate annotation (if not already done) Plug.AnnotationMode = Annotation.Indented; // show margin if (marginError.Sensitive == false) { marginError.Sensitive = true; } if (marginError.Type != MarginType.Symbol) { marginError.Type = MarginType.Symbol; } if (marginError.Mask != EveryMarkersMask) { marginError.Mask = EveryMarkersMask; } // only show the new errors if (_sessionInfo[currentFilePath].HasErrorsNotDisplayed) { _sessionInfo[currentFilePath].HasErrorsNotDisplayed = false; StylerHelper stylerHelper = new StylerHelper(); int lastLine = -2; StringBuilder lastMessage = new StringBuilder(); foreach (var fileError in _sessionInfo[currentFilePath].FileErrors) { // new line if (lastLine != fileError.Line) { stylerHelper.Clear(); lastMessage.Clear(); // set marker style now (the first error encountered for a given line is the highest anyway) if (!((int)Npp.GetLine(fileError.Line).MarkerGet()).IsBitSet((int)fileError.Level)) { Npp.GetLine(fileError.Line).MarkerAdd((int)fileError.Level); } } else { // append to existing annotation stylerHelper.Style("\n", (byte)fileError.Level); lastMessage.Append("\n"); } lastLine = fileError.Line; var mess = fileError.FromProlint ? "Prolint (level " + fileError.ErrorNumber : ("Compilation " + (fileError.Level == ErrorLevel.Critical ? "error" : "warning") + " (n°" + fileError.ErrorNumber); mess += fileError.FromProlint ? "): " : ", col " + fileError.Column + "): "; stylerHelper.Style(mess, (byte)(Style.ErrorAnnotBoldStyleOffset + fileError.Level)); lastMessage.Append(mess); mess = fileError.Message.BreakText(140); stylerHelper.Style(mess, (byte)(Style.ErrorAnnotStandardStyleOffset + fileError.Level)); lastMessage.Append(mess); if (Config.Instance.GlobalShowDetailedHelpForErrors && !string.IsNullOrEmpty(fileError.Help)) { mess = "\nDetailed help: " + fileError.Help.BreakText(140); stylerHelper.Style(mess, (byte)(Style.ErrorAnnotItalicStyleOffset + fileError.Level)); lastMessage.Append(mess); } if (fileError.Times > 0) { mess = "\nThis message above appeared " + fileError.Times + " times in the compiler log"; stylerHelper.Style(mess, (byte)(Style.ErrorAnnotBoldStyleOffset + fileError.Level)); lastMessage.Append(mess); } // set annotation Npp.GetLine(lastLine).AnnotationText = lastMessage.ToString(); Npp.GetLine(lastLine).AnnotationStyles = stylerHelper.GetStyleArray(); } } marginError.Width = ErrorMarginWidth + 1; marginError.Width = ErrorMarginWidth; }
/// <summary> /// Update the information of the conf list, using the given share directory /// </summary> public static void UpdateList(string distantShareDirectory) { try { // We get the latest info for each line bool sharedDirOk = false; if (!string.IsNullOrEmpty(distantShareDirectory) && Directory.Exists(distantShareDirectory)) { sharedDirOk = true; Config.Instance.SharedConfFolder = distantShareDirectory; } StringBuilder updateMessage = new StringBuilder(); // update each line of the list foreach (var confLine in List) { // read the autoupdate status from the config confLine.AutoUpdate = Config.Instance.AutoUpdateConfList.ContainsFast(confLine.Label); confLine.LocalPath = confLine.HandledItem; confLine.DistantPath = sharedDirOk ? Path.Combine(distantShareDirectory, confLine.HandledItem.Replace(Npp.GetConfigDir(), "").Trim('\\')) : ""; confLine.LocalTime = DateTime.Now; confLine.DistantTime = DateTime.Now; if (confLine.IsDir) { confLine.LocalExists = Directory.Exists(confLine.LocalPath); confLine.DistantExists = !string.IsNullOrEmpty(confLine.DistantPath) && Directory.Exists(confLine.DistantPath); if (confLine.LocalExists) { confLine.LocalNbFiles = 0; foreach (var file in Directory.GetFiles(confLine.LocalPath)) { if (confLine.LocalNbFiles == 0) { confLine.LocalTime = File.GetLastWriteTime(file); } else if (File.GetLastWriteTime(file).CompareTo(confLine.LocalTime) > 0) { confLine.LocalTime = File.GetLastWriteTime(file); } confLine.LocalNbFiles++; } } if (!string.IsNullOrEmpty(confLine.DistantPath) && confLine.DistantExists) { confLine.DistantNbFiles = 0; foreach (var file in Directory.GetFiles(confLine.DistantPath)) { if (confLine.DistantNbFiles == 0) { confLine.DistantTime = File.GetLastWriteTime(file); } else if (File.GetLastWriteTime(file).CompareTo(confLine.DistantTime) > 0) { confLine.DistantTime = File.GetLastWriteTime(file); } confLine.DistantNbFiles++; } } } else { confLine.LocalExists = !string.IsNullOrEmpty(confLine.LocalPath) && File.Exists(confLine.LocalPath); confLine.DistantExists = !string.IsNullOrEmpty(confLine.DistantPath) && File.Exists(confLine.DistantPath); if (confLine.LocalExists) { confLine.LocalTime = File.GetLastWriteTime(confLine.LocalPath); } if (!string.IsNullOrEmpty(confLine.DistantPath) && confLine.DistantExists) { confLine.DistantTime = File.GetLastWriteTime(confLine.DistantPath); } } // if the difference between the two dates are small, correct it (it sometimes happen, even when the files are strictly identical) if (Math.Abs(confLine.LocalTime.Subtract(confLine.DistantTime).TotalSeconds) < 2) { confLine.LocalTime = confLine.DistantTime; } confLine.NeedUpdate = confLine.OnFetch != null && ((confLine.DistantExists && !confLine.LocalExists) || (confLine.LocalExists && confLine.DistantExists && confLine.DistantTime.CompareTo(confLine.LocalTime) > 0)); // the line needs to be autoupdated if (confLine.AutoUpdate && confLine.NeedUpdate && confLine.OnFetch != null) { _silentUpdate = true; confLine.OnFetch(confLine); confLine.LocalExists = true; confLine.LocalTime = confLine.DistantTime; confLine.LocalNbFiles = confLine.DistantNbFiles; confLine.NeedUpdate = false; _silentUpdate = false; if (updateMessage.Length == 0) { updateMessage.Append("The following configuration files have been updated from the shared folder:<br><br>"); } updateMessage.Append("<div><b>" + confLine.Label + "</b></div>"); } } if (updateMessage.Length > 0) { updateMessage.Append("<br><br><i>You can set which config file gets auto-updated in <a href='go'>the option page</a></i>"); UserCommunication.NotifyUnique("ExportConfUpdate", updateMessage.ToString(), MessageImg.MsgInfo, "Update notification", "Configuration auto-update", args => { Appli.Appli.GoToPage(PageNames.ExportShareConf); UserCommunication.CloseUniqueNotif("ExportConfUpdate"); args.Handled = true; }, 10); } } catch (Exception e) { ErrorHandler.ShowErrors(e, "Error while fetching info on the distant files"); } }
private AppliMenu() { // List of item that can be assigned to a shortcut ShortcutableItemList = new List <MenuItem> { // add the main menu here, so it can appear in the list of shortcut to set new MenuItem(null, "Open main menu", ImageResources.Logo20x20, item => ShowMainMenu(), "Show_main_menu_", "Alt+C") { Generic = true } }; #region Progress tools _progressTools = new List <MenuItem> { new MenuItem(this, "Progress desktop", ImageResources.ProDesktop, item => ProMisc.OpenProDesktop(), "Pro_desktop", "") { Generic = true }, new MenuItem(this, "Open in the AppBuilder", ImageResources.SendToAppbuilder, item => ProMisc.OpenCurrentInAppbuilder(), "Send_appbuilder", "Alt+O"), new MenuItem(true) { Generic = true }, // -------------------------- new MenuItem(this, "PROLINT code", ImageResources.ProlintCode, item => ProMisc.StartProgressExec(ExecutionType.Prolint), "Prolint", "F12"), new MenuItem(this, "Deploy current file", ImageResources.Deploy, item => ProMisc.DeployCurrentFile(), "Deploy", "Ctrl+Alt+Prior") { Generic = true }, new MenuItem(this, "Generate DEBUG-LIST", ImageResources.ExtDbg, item => ProMisc.StartProgressExec(ExecutionType.GenerateDebugfile, compilation => compilation.CompileWithDebugList = true), "Generate_debug-list", null), new MenuItem(this, "Generate LISTING", ImageResources.ExtLis, item => ProMisc.StartProgressExec(ExecutionType.GenerateDebugfile, compilation => compilation.CompileWithListing = true), "Generate_listing", null), new MenuItem(this, "Generate XREF", ImageResources.ExtXrf, item => ProMisc.StartProgressExec(ExecutionType.GenerateDebugfile, compilation => compilation.CompileWithXref = true), "Generate_xref", null), new MenuItem(this, "Generate XREF-XML", ImageResources.ExtXml, item => ProMisc.StartProgressExec(ExecutionType.GenerateDebugfile, compilation => { compilation.CompileWithXref = true; compilation.UseXmlXref = true; }), "Generate_xrefxml", null), }; #endregion #region Generate code _generateCodeMenuList = new List <MenuItem> { new MenuItem(this, "Insert new internal procedure", ImageResources.Procedure, item => ProGenerateCode.Factory.InsertCode <ParsedProcedure>(), "Insert_new_procedure", "Alt+P"), new MenuItem(this, "Insert new function", ImageResources.Function, item => ProGenerateCode.Factory.InsertCode <ParsedImplementation>(), "Insert_new_function", "Alt+F"), new MenuItem(true), // -------------------------- new MenuItem(this, "Delete existing internal procedure", ImageResources.DeleteProcedure, item => ProGenerateCode.Factory.DeleteCode <ParsedProcedure>(), "Delete_procedure", ""), new MenuItem(this, "Delete existing function", ImageResources.DeleteFunction, item => ProGenerateCode.Factory.DeleteCode <ParsedImplementation>(), "Delete_function", ""), new MenuItem(true), // -------------------------- new MenuItem(this, "Synchronize function prototypes", ImageResources.Synchronize, item => ProGenerateCode.Factory.UpdateFunctionPrototypesIfNeeded(), "Synchronize_prototypes", "Alt+S") }; #endregion #region Edit code _editCodeList = new List <MenuItem> { new MenuItem(this, "Display parser errors", ImageResources.DisplayParserResults, item => ProCodeFormat.DisplayParserErrors(), "Check_parser_errors", null), new MenuItem(this, "Toggle comment line", ImageResources.ToggleComment, item => ProMisc.ToggleComment(), "Toggle_Comment", "Ctrl+Q"), new MenuItem(this, "Correct indentation (selection or all)", ImageResources.IndentCode, item => ProCodeFormat.CorrectCodeIndentation(), "Reindent_document", "Ctrl+I") //new MenuItem(this, "Format document", ImageResources.FormatCode, CodeBeautifier.CorrectCodeIndentation, "Format_document", "Ctrl+I"), }; #endregion #region Misc _modificationTagMenuList = new List <MenuItem> { new MenuItem(this, "Edit current file info", ImageResources.FileInfo, item => Appli.Appli.GoToPage(PageNames.FileInfo), "Edit_file_info", "Ctrl+Shift+M"), new MenuItem(this, "Insert title block", ImageResources.TitleBlock, item => ModificationTag.AddTitleBlockAtCaret(), "Insert_title_block", "Ctrl+Alt+M"), new MenuItem(this, "Surround with modification tags", ImageResources.ModificationTag, item => ModificationTag.SurroundSelectionWithTag(), "Modif_tags", "Ctrl+M") //new MenuItem(this, "Insert mark", ImageResources.InsertMark, null, "Insert_mark", "Ctrl+T"), }; #endregion #region database tools _databaseTools = new List <MenuItem> { new MenuItem(this, "Open data administration", ImageResources.DataAdmin, item => ProMisc.OpenDbAdmin(), "Data_admin", "") { Generic = true }, new MenuItem(this, "Open progress dictionary", ImageResources.Dictionary, item => ProMisc.OpenDictionary(), "Data_dictionary", "") { Generic = true }, new MenuItem(true) { Generic = true }, // -------------------------- new MenuItem(this, "Explore and modify your data", ImageResources.DataDigger, item => ProMisc.OpenDataDigger(), "Data_digger", "") { Generic = true }, new MenuItem(this, "Explore (read-only) your data", ImageResources.DataReader, item => ProMisc.OpenDataReader(), "Data_reader", "") { Generic = true } }; #endregion #region Main menu var goToDefItem = new MenuItem(this, "Go to definition", ImageResources.GoToDefinition, item => ProMisc.GoToDefinition(false), "Go_To_Definition", "Ctrl+B") { Generic = true }; goToDefItem.SubText = "Middle click / " + goToDefItem.SubText; var goToPreviousJump = new MenuItem(this, "Go to previous jump point", ImageResources.GoBackward, item => Npp.GoBackFromDefinition(), "Go_Backwards", "Ctrl+Shift+B") { Generic = true }; goToPreviousJump.SubText = "Ctrl + Middle click / " + goToPreviousJump.SubText; MainMenuList = new List <MenuItem> { new MenuItem(this, "Show main window", ImageResources.MainWindow, item => Appli.Appli.ToggleView(), "Open_main_window", "Alt+Space") { Generic = true }, new MenuItem(this, "Show autocompletion at caret", ImageResources.Autocompletion, item => AutoCompletion.OnShowCompleteSuggestionList(), "Show_Suggestion_List", "Ctrl+Space") { Generic = true }, new MenuItem(this, "Toggle current file as progress", ImageResources.Progress, item => ProMisc.ReadCurrentFileAsProgress(), "Read_as_progress", null) { Generic = true }, new MenuItem(true) { Generic = true }, // -------------------------- new MenuItem(this, "Open 4GL help", ImageResources.ProgressHelp, item => ProMisc.Open4GlHelp(), "Open_4GL_help", "F1") { Generic = true }, new MenuItem(this, "Check syntax", ImageResources.CheckCode, item => ProMisc.StartProgressExec(ExecutionType.CheckSyntax), "Check_syntax", "Shift+F1"), new MenuItem(this, "Run program", ImageResources.RunCode, item => ProMisc.StartProgressExec(ExecutionType.Run), "Run_program", "Ctrl+F1"), new MenuItem(this, "Compile", ImageResources.CompileCode, item => ProMisc.StartProgressExec(ExecutionType.Compile), "Compile", "Alt+F1"), new MenuItem(this, "Compile options", ImageResources.CompileOptions, item => ProMisc.OpenCompilationOptions(), "Compile_options", null), new MenuItem(this, "Progress tools", ImageResources.ProgressTools, item => ShowProgressToolsMenu(), "Progress_tools", "Alt+T") { Generic = true, Children = _progressTools.Cast <FilteredTypeTreeListItem>().ToList() }, new MenuItem(true) { Generic = true }, // -------------------------- new MenuItem(this, "Start searching files", ImageResources.Search, item => FileExplorer.FileExplorer.Instance.StartSearch(), "Search_file", "Alt+Q") { Generic = true }, goToDefItem, goToPreviousJump, //new MenuItem(this, "New 4GL file", ImageResources.GenerateCode, ShowNewFileAtCursor, "New_file", "Ctrl+Shift+N") { // Children = GenerateCodeMenuList.Select(item => (YamuiMenuItem)item).ToList(), //}, new MenuItem(true) { Generic = true }, // -------------------------- new MenuItem(this, "Switch environment", ImageResources.Env, item => ShowEnvMenu(), "Switch_env", "Ctrl+E") { Generic = true }, new MenuItem(this, "Database tools", ImageResources.DatabaseTools, item => ShowDatabaseToolsMenu(), "DatabaseTools", "Alt+D") { Generic = true, Children = _databaseTools.Cast <FilteredTypeTreeListItem>().ToList() }, new MenuItem(this, "Generate and revise code", ImageResources.GenerateCode, item => ShowGenerateCodeMenu(), "Generate_code", "Alt+Insert") { Generic = true, Children = _generateCodeMenuList.Cast <FilteredTypeTreeListItem>().ToList() }, new MenuItem(this, "Edit code", ImageResources.EditCode, item => ShowEditCodeMenu(), "Edit_code", "Alt+E") { Generic = true, Children = _editCodeList.Cast <FilteredTypeTreeListItem>().ToList() }, new MenuItem(this, "Modification tag", ImageResources.ModificationTagMenu, item => ShowMiscMenu(), "Modification_tag", "Alt+M") { Generic = true, Children = _modificationTagMenuList.Cast <FilteredTypeTreeListItem>().ToList() }, new MenuItem(true) { Generic = true }, // -------------------------- new MenuItem(this, "Options", ImageResources.ShowOptions, item => Appli.Appli.GoToPage(PageNames.OptionsGeneral), "Go_to_options", null) { Generic = true } }; #endregion #region special dev if (Config.IsDeveloper) { MainMenuList.Add( new MenuItem(this, "Tests", ImageResources.Tests, null, null, null, new List <MenuItem> { new MenuItem(this, "DebugTest1", ImageResources.TestTube, item => PlugDebug.DebugTest1(), "DebugTest1", "Ctrl+OemQuotes") { Generic = true }, new MenuItem(this, "DebugTest2", ImageResources.TestTube, item => PlugDebug.DebugTest2(), "DebugTest2", "Alt+OemQuotes") { Generic = true }, new MenuItem(this, "DebugTest3", ImageResources.TestTube, item => PlugDebug.DebugTest3(), "DebugTest3", "Shift+OemQuotes") { Generic = true }, new MenuItem(this, "Parse current file", ImageResources.TestTube, item => PlugDebug.ParseCurrentFile(), "ParseCurrentFile", "") { Generic = false }, new MenuItem(this, "GetCurrentFileParsedDebugfile", ImageResources.TestTube, item => PlugDebug.GetCurrentFileParsedDebugfile(), "GetCurrentFileParsedDebugfile", "") { Generic = false }, new MenuItem(this, "Parse reference file", ImageResources.TestTube, item => PlugDebug.ParseReferenceFile(), "ParseReferenceFile", "") { Generic = true }, new MenuItem(this, "Parse all files", ImageResources.TestTube, item => PlugDebug.ParseAllFiles(), "ParseAllFiles", "") { Generic = true } }) { Generic = true }); } #endregion }
/// <summary> /// This method checks if the current document contains function prototypes that are not updated /// and correct them if needed /// </summary> /// <remarks>This method is costly because we parse everything potentially X times, but it's much simpler this way...</remarks> private void UpdateFunctionPrototypes(bool silent) { try { List <ParsedImplementation> listOfOutDatedProto; List <ParsedImplementation> listOfSoloImplementation; List <ParsedPrototype> listOfUselessProto; StringBuilder outputMessage = new StringBuilder(); var nbLoop = 0; var nbNotCreated = 0; var nbThingsDone = 0; var nbToDo = GetPrototypesLists(out listOfOutDatedProto, out listOfSoloImplementation, out listOfUselessProto); // if there is at least 1 thing to do if (nbToDo > 0) { Sci.BeginUndoAction(); // Add proto if (listOfSoloImplementation.Count > 0 && string.IsNullOrEmpty(_parser.ParseErrorsInHtml)) { var tempMes = new StringBuilder("The following function prototypes have been created :"); while (listOfSoloImplementation.Count > nbNotCreated && nbLoop < nbToDo) { if (AddPrototypes(ref tempMes, listOfSoloImplementation[nbNotCreated])) { nbThingsDone++; } else { nbNotCreated++; } ParseNow(); GetPrototypesLists(out listOfOutDatedProto, out listOfSoloImplementation, out listOfUselessProto); nbLoop++; } tempMes.Append("<br><br>"); if (nbThingsDone > 0) { outputMessage.Append(tempMes); } } // delete proto if (listOfUselessProto.Count > 0) { outputMessage.Append("The following prototypes have been deleted :"); while (listOfUselessProto.Count > 0 && nbLoop < nbToDo) { if (DeletePrototypes(ref outputMessage, listOfUselessProto[0])) { nbThingsDone++; } ParseNow(); GetPrototypesLists(out listOfOutDatedProto, out listOfSoloImplementation, out listOfUselessProto); nbLoop++; } outputMessage.Append("<br><br>"); } // update proto if (listOfOutDatedProto.Count > 0) { outputMessage.Append("The following functions have had their prototype synchronized :"); while (listOfOutDatedProto.Count > 0 && nbLoop < nbToDo) { if (UpdatePrototypes(ref outputMessage, listOfOutDatedProto[0])) { nbThingsDone++; } ParseNow(); GetPrototypesLists(out listOfOutDatedProto, out listOfSoloImplementation, out listOfUselessProto); nbLoop++; } outputMessage.Append("<br><br>"); } Sci.EndUndoAction(); } if (nbThingsDone == 0) { if (!silent) { if (nbToDo == 0) { UserCommunication.Notify("There was nothing to be done :<br>All the prototypes match their implementation", MessageImg.MsgInfo, "Function prototypes", "Everything is synchronized", 5); } else { UserCommunication.Notify("Failed to find the prototype for " + nbNotCreated + " function implementations<br>Your document is not correctly formatted for 3P to automatically create them :<br><i>The block _UIB-PREPROCESSOR-BLOCK is missing or the procedure can't be opened in the appbuilder!</i><br><br>Please correct your document manually, then they will all be updated correctly" + _parser.ParseErrorsInHtml, MessageImg.MsgHighImportance, "Function prototypes", "Failed to create prototypes"); } } } else { outputMessage.Append("<i>"); outputMessage.Append("CTRL + Z will cancel the above-mentioned modifications<br>"); outputMessage.Append(Npp.CurrentFileInfo.Path.ToHtmlLink("Click here to stop auto-updating the prototypes for this file")); outputMessage.Append("</i>"); UserCommunication.NotifyUnique("Prototype_synchro", outputMessage.ToString(), MessageImg.MsgOk, "Function prototypes", "Synchronization done", args => { var split = args.Link.Split('#'); if (split.Length == 2) { Npp.GotoPos(split[0], int.Parse(split[1])); args.Handled = true; } else { if (!_ignoredFiles.Contains(args.Link)) { _ignoredFiles.Add(args.Link); UserCommunication.NotifyUnique("Prototype_synchro", "Automatic prototype updates stopped for the file :<br>" + Npp.CurrentFileInfo.Path + "<br><br><i>This is effective until you restart Notepad++<br>You can also trigger an update manually to restart the auto-update</i>", MessageImg.MsgInfo, "Function prototypes", "Synchronization stopped", null, 5); args.Handled = true; } } }, 5); } } catch (Exception e) { ErrorHandler.ShowErrors(e, "Error updating prototypes"); } }
private bool OnKeyDown(Keys key) { bool handled = true; // down and up change the selection if (key == Keys.Up) { if (fastOLV.SelectedIndex > 0) { fastOLV.SelectedIndex--; } else { fastOLV.SelectedIndex = (TotalItems - 1); } if (fastOLV.SelectedIndex >= 0) { fastOLV.EnsureVisible(fastOLV.SelectedIndex); } } else if (key == Keys.Down) { if (fastOLV.SelectedIndex < (TotalItems - 1)) { fastOLV.SelectedIndex++; } else { fastOLV.SelectedIndex = 0; } if (fastOLV.SelectedIndex >= 0) { fastOLV.EnsureVisible(fastOLV.SelectedIndex); } // escape close } else if (key == Keys.Escape) { Npp.GrabFocus(); // left and right keys } else if (key == Keys.Left) { handled = LeftRight(true); } else if (key == Keys.Right) { handled = LeftRight(false); // enter and tab accept the current selection } else if (key == Keys.Enter) { OnActivateItem(); } else if (key == Keys.Tab) { OnActivateItem(); GiveFocustoTextBox(); // else, any other key is unhandled } else { handled = false; } // down and up activate the display of tooltip if (key == Keys.Up || key == Keys.Down) { // TODO //InfoToolTip.InfoToolTip.ShowToolTipFromAutocomplete(GetCurrentSuggestion(), new Rectangle(new Point(Location.X, Location.Y), new Size(Width, Height)), _isReversed); } return(handled); }
/// <summary> /// Called after the execution of run/compile/check/prolint /// </summary> public static void OnSingleExecutionOk(ProExecution lastExec) { try { var treatedFile = lastExec.ListToCompile.First(); CurrentOperation currentOperation; if (!Enum.TryParse(lastExec.ExecutionType.ToString(), true, out currentOperation)) { currentOperation = CurrentOperation.Run; } var isCurrentFile = treatedFile.InputPath.EqualsCi(Plug.CurrentFilePath); var otherFilesInError = false; int nbWarnings = 0; int nbErrors = 0; // Read log info var errorList = lastExec.LoadErrorLog(); if (!errorList.Any()) { // the compiler messages are empty var fileInfo = new FileInfo(lastExec.LogPath); if (fileInfo.Length > 0) { // the .log is not empty, maybe something went wrong in the runner, display errors UserCommunication.Notify( "Something went wrong while " + currentOperation.GetAttribute <CurrentOperationAttr>().ActionText + " the following file:<br>" + treatedFile.InputPath.ToHtmlLink() + "<br>The progress compiler didn't return any errors but the log isn't empty, here is the content :" + Utils.ReadAndFormatLogToHtml(lastExec.LogPath), MessageImg.MsgError, "Critical error", "Action failed"); return; } } else { // count number of warnings/errors, loop through files > loop through errors in each file foreach (var keyValue in errorList) { foreach (var fileError in keyValue.Value) { if (fileError.Level <= ErrorLevel.StrongWarning) { nbWarnings++; } else { nbErrors++; } } otherFilesInError = otherFilesInError || !treatedFile.InputPath.EqualsCi(keyValue.Key); } } // Prepare the notification content var notifTitle = currentOperation.GetAttribute <CurrentOperationAttr>().Name; var notifImg = (nbErrors > 0) ? MessageImg.MsgError : ((nbWarnings > 0) ? MessageImg.MsgWarning : MessageImg.MsgOk); var notifTimeOut = (nbErrors > 0) ? 0 : ((nbWarnings > 0) ? 10 : 5); var notifSubtitle = lastExec.ExecutionType == ExecutionType.Prolint ? (nbErrors + nbWarnings) + " problem" + ((nbErrors + nbWarnings) > 1 ? "s" : "") + " detected" : (nbErrors > 0) ? nbErrors + " error" + (nbErrors > 1 ? "s" : "") + " found" : ((nbWarnings > 0) ? nbWarnings + " warning" + (nbWarnings > 1 ? "s" : "") + " found" : "Syntax correct"); // build the error list var errorsList = new List <FileError>(); foreach (var keyValue in errorList) { errorsList.AddRange(keyValue.Value); } // when compiling, transfering .r/.lst to compilation dir var listTransferFiles = new List <FileToDeploy>(); if (lastExec.ExecutionType == ExecutionType.Compile) { listTransferFiles = lastExec.CreateListOfFilesToDeploy(); listTransferFiles = lastExec.ProEnv.Deployer.DeployFiles(listTransferFiles); } // Notify the user, or not if (Config.Instance.CompileAlwaysShowNotification || !isCurrentFile || !Npp.GetFocus() || otherFilesInError) { UserCommunication.NotifyUnique(treatedFile.InputPath, "Was " + currentOperation.GetAttribute <CurrentOperationAttr>().ActionText + " :<br>" + ProCompilation.FormatCompilationResult(treatedFile.InputPath, errorsList, listTransferFiles), notifImg, notifTitle, notifSubtitle, null, notifTimeOut); } } catch (Exception e) { ErrorHandler.ShowErrors(e, "Error in OnExecutionOk"); } }
public static void EditRules() { Export(); Npp.OpenFile(Config.FileDeploymentRules); }
private void BtDbViewOnButtonPressed(object sender, EventArgs eventArgs) { Npp.OpenFile(DataBase.GetCurrentDumpPath); }