void deployBtn_Click(object sender, EventArgs e) { try { if (currentScript == null) { LoadCurrentDoc(); } if (currentScript != null) //may not necessarily be loaded successfully { using (var dialog = new DeploymentInput()) if (DialogResult.OK == dialog.ShowDialog()) { EditItem(currentScript); Npp.SaveDocuments(GetProjectDocuments()); string selectedTargetVersion = dialog.SelectedVersion.Version; string path = CSScriptHelper.Isolate(currentScript, dialog.AsScript, selectedTargetVersion, dialog.AsWindowApp); if (path != null) { string pluginClrVersion = "v" + Environment.Version.ToString(); if (dialog.AsScript && !pluginClrVersion.StartsWith(selectedTargetVersion)) //selectedTargetVersion may not include the build number { MessageBox.Show("Distribution package targets CLR version, which is different from the default version.\r\nPlease verify that the script is compatible with the selected CLR version.", "CS-Script"); } Process.Start("explorer.exe", path); } } } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "CS-Script"); } }
public static void ResetBreaksPointsFromContent() { // remove all active break point handles and read them again from the content var currFile = Npp.Editor.GetCurrentFilePath(); var document = Npp.GetCurrentDocument(); int[] actual_markers = document.LinesOfMarker(MARK_BREAKPOINT); var currentFileKeys = breakpoints.Keys.Where(k => k.StartsWith(currFile, StringComparison.OrdinalIgnoreCase)); foreach (string key in currentFileKeys.ToArray()) { //IMPORTANT: GetLineOfMarker returns line form the handle of the marker within a //current file. Value of handles are file specific and reused between the files/documents. //This is because marker handles are just marker indexes within a document. //Thus resolving a given handle for a non current document can in fact return a proper line //of the current doc if it has the marker with the same handle value. This already led to //the break points drifting. IntPtr marker = breakpoints[key]; if (marker != IntPtr.Zero) { document.DeleteMarker(marker); } breakpoints.Remove(key); } document.DeleteAllMarkers(MARK_BREAKPOINT); foreach (var line in actual_markers) { IntPtr marker = document.PlaceMarker(MARK_BREAKPOINT, line); string newKey = currFile + "|" + (line + 1); breakpoints[newKey] = marker; } if (OnBreakpointChanged != null) { OnBreakpointChanged(); } }
private static void PlaceBreakPointsForCurrentTab() { try { string file = Npp.GetCurrentFile(); string expectedkeyPrefix = file + "|"; string[] fileBreakpoints = breakpoints.Keys.Where(x => x.StartsWith(expectedkeyPrefix, StringComparison.OrdinalIgnoreCase)).ToArray(); foreach (var key in fileBreakpoints) { if (breakpoints[key] == IntPtr.Zero) //not placed yet { //key = <file>|<line + 1> //server debugger operates in '1-based' and NPP in '0-based' lines int line = int.Parse(key.Split('|').Last()) - 1; breakpoints[key] = Npp.PlaceMarker(MARK_BREAKPOINT, line); } } } catch { } }
void MembersList_MouseDoubleClick(object sender, MouseEventArgs e) { if (membersList.SelectedItem != null) { var info = (membersList.SelectedItem as MemberInfo); try { membersList.SelectedItem = null; if (info.Line != -1) { Npp.GrabFocus(); int currentLineNum = Npp.GetCaretLineNumber(); int prevLineEnd = Npp.GetLineStart(currentLineNum) - Environment.NewLine.Length; int topScrollOffset = currentLineNum - Npp.GetFirstVisibleLine(); Win32.SendMessage(Npp.CurrentScintilla, SciMsg.SCI_GOTOLINE, info.Line, 0); Npp.SetFirstVisibleLine(info.Line - topScrollOffset); } } catch { } //it is expected to fail if the line does not contain the file content position spec. This is also the reason for not validating any "IndexOf" results. } }
static public void NavigateToFileLocation(string sourceLocation) { var location = FileLocation.Parse(sourceLocation); location.Start = Npp.CharOffsetToPosition(location.Start, location.File); location.End = Npp.CharOffsetToPosition(location.End, location.File); TranslateCompiledLocation(location); if (File.Exists(location.File)) { if (Npp.GetCurrentFile().IsSameAs(location.File, true)) { ShowBreakpointSourceLocation(location); } else { OnNextFileOpenComplete = () => ShowBreakpointSourceLocation(location); Npp.OpenFile(location.File); //needs to by asynchronous } } }
// public static Dictionary<int, string> NoteBreakpoints() // { // var result = new Dictionary<int, string>(); // var document = Npp.GetCurrentDocument(); // string file = Npp.Editor.GetCurrentFilePath(); // string expectedkeyPrefix = file + "|"; // string[] fileBreakpoints = breakpoints.Keys.Where(x => x.StartsWith(expectedkeyPrefix, StringComparison.OrdinalIgnoreCase)).ToArray(); // foreach (var key in fileBreakpoints) // { // //key = <file>|<line + 1> //server debugger operates in '1-based' and NPP in '0-based' lines // int line = int.Parse(key.Split('|').Last()) - 1; // var linetText = document.GetLine(line); // result.Add(line, linetText.Replace(" ", "") // .Replace("\t", "") // .TrimEnd('}')); // } // return result; // } public static void RefreshBreakPointsInContent() { try { var document = Npp.GetCurrentDocument(); string file = Npp.Editor.GetCurrentFilePath(); //clear all document.ClearIndicator(INDICATOR_DEBUGSTEP, 0, -1); string expectedkeyPrefix = file + "|"; string[] fileBreakpoints = breakpoints.Keys.Where(x => x.StartsWith(expectedkeyPrefix, StringComparison.OrdinalIgnoreCase)).ToArray(); foreach (var key in fileBreakpoints) { //key = <file>|<line + 1> //server debugger operates in '1-based' and NPP in '0-based' lines int line = int.Parse(key.Split('|').Last()) - 1; breakpoints[key] = document.PlaceMarker(MARK_BREAKPOINT, line); Debug.WriteLine($@"Refresh BP Line: {line}"); } } catch { } }
static public void SaveDocuments(string[] files) { try { var filesToSave = files.Select(x => Path.GetFullPath(x)); var openFiles = Npp.Editor.GetOpenFilesSafe(); var document = Npp.GetCurrentDocument(); var current = Npp.Editor.GetCurrentFilePath(); // the "new" file is not saved so it has no root foreach (var item in openFiles.Where(Path.IsPathRooted)) { var path = Path.GetFullPath(item); if (filesToSave.Contains(path)) { Npp.Editor.Open(item) .SaveCurrentFile(); } } Npp.Editor.Open(current); } catch { } }
void Run(bool asExternal) { if (currentScript == null || (Config.Instance.ReloadActiveScriptOnRun && currentScript != Npp.Editor.GetCurrentFilePath())) { loadBtn.PerformClick(); } if (currentScript == null) { MessageBox.Show("Please load some script file first.", "CS-Script"); } else { try { if (!CurrentDocumentBelongsToProject()) { EditItem(currentScript); } npp.SaveDocuments(GetProjectDocuments()); if (asExternal) { try { CSScriptHelper.ExecuteAsynch(currentScript); } catch (Exception e) { Plugin.ShowOutputPanel() .ShowBuildOutput() .WriteLine(e.Message) .SetCaretAtStart(); } } else { OutputPanel outputPanel = Plugin.ShowOutputPanel(); if (Config.Instance.StartDebugMonitorOnScriptExecution) { outputPanel.AttachDebgMonitor(); } outputPanel.ClearAllDefaultOutputs(); Task.Factory.StartNew(() => { try { if (Config.Instance.InterceptConsole) { CSScriptHelper.ExecuteScript(currentScript, OnRunStart, OnConsoleObjectOut); } else { CSScriptHelper.ExecuteScript(currentScript, OnRunStart); } } catch (Exception e) { this.InUiThread(() => { outputPanel.ShowBuildOutput() .WriteLine(e.Message) .SetCaretAtStart(); }); } finally { this.InUiThread(() => { Plugin.RunningScript = null; RefreshControls(); Npp.GetCurrentDocument().GrabFocus(); }); } }); } } catch (Exception ex) { Plugin.ShowOutputPanel() .ShowBuildOutput() .WriteLine(ex.Message) .SetCaretAtStart(); } } }
public void LoadScript(string scriptFile) { if (!string.IsNullOrWhiteSpace(scriptFile) && File.Exists(scriptFile)) { if (!scriptFile.IsScriptFile()) { MessageBox.Show("The file type '" + Path.GetExtension(scriptFile) + "' is not supported.", "CS-Script"); } else { try { Npp.OpenFile(scriptFile); Project project = CSScriptHelper.GenerateProjectFor(scriptFile); /* * root * references * assembly_1 * assembly_2 * assembly_n * script_1 * script_2 * script_N */ treeView1.BeginUpdate(); treeView1.Nodes.Clear(); TreeNode root = treeView1.Nodes.Add("Script '" + Path.GetFileNameWithoutExtension(scriptFile) + "'"); TreeNode references = root.Nodes.Add("References"); root.SelectedImageIndex = root.ImageIndex = scriptFile.IsVbFile() ? scriptVbImage : scriptImage; references.SelectedImageIndex = references.ImageIndex = assemblyImage; references.ContextMenuStrip = itemContextMenu; root.ContextMenuStrip = solutionContextMenu; root.ToolTipText = "Script: " + scriptFile; Action <TreeNode, string[]> populateNode = (node, files) => { foreach (var file in files) { int imageIndex = includeImage; var info = new ProjectItem(file) { IsPrimary = (file == project.PrimaryScript) }; if (info.IsPrimary) { imageIndex = file.IsVbFile() ? scriptVbImage : scriptImage; } if (info.IsAssembly) { imageIndex = assemblyImage; } node.Nodes.Add(new TreeNode(info.Name) { ImageIndex = imageIndex, SelectedImageIndex = imageIndex, Tag = info, ToolTipText = file, ContextMenuStrip = itemContextMenu }); } ; }; populateNode(references, project.Assemblies); populateNode(root, project.SourceFiles); root.Expand(); treeView1.EndUpdate(); currentScript = scriptFile; CSScriptIntellisense.Plugin.EnsureCurrentFileParsed(); var history = Config.Instance.ScriptHistory.Split('|').ToList(); history.Remove(scriptFile); history.Insert(0, scriptFile); Config.Instance.ScriptHistory = string.Join("|", history.Take(Config.Instance.SciptHistoryMaxCount).ToArray()); Config.Instance.Save(); ReloadScriptHistory(); } catch (Exception e) { //it is not a major use-case so doesn't matter why we failed MessageBox.Show("Cannot load script.\nError: " + e.Message, "CS-Script"); e.LogAsError(); } } } else { MessageBox.Show("Script '" + scriptFile + "' does not exist.", "CS-Script"); } RefreshControls(); }
public void RefreshProjectStructure() { this.InUiThread(() => { if (Npp.GetCurrentFile() == currentScript) { try { Project project = CSScriptHelper.GenerateProjectFor(currentScript); treeView1.BeginUpdate(); /* * root * references * assembly_1 * assembly_2 * assembly_n * script_1 * script_2 * script_N */ TreeNode root = treeView1.Nodes[0]; TreeNode references = root.Nodes[0]; Action <TreeNode, string[]> updateNode = (node, files) => { string[] currentFiles = node.Nodes .Cast <TreeNode>() .Where(x => x.Tag is ProjectItem) .Select(x => (x.Tag as ProjectItem).File) .ToArray(); string[] newItems = files.Except(currentFiles).ToArray(); var orphantItems = node.Nodes .Cast <TreeNode>() .Where(x => x.Tag is ProjectItem) .Where(x => !files.Contains((x.Tag as ProjectItem).File)) .Where(x => x != root && x != references) .ToArray(); orphantItems.ForEach(x => node.Nodes.Remove(x)); newItems.ForEach(file => { int imageIndex = includeImage; var info = new ProjectItem(file) { IsPrimary = (file == project.PrimaryScript) }; if (info.IsAssembly) { imageIndex = assemblyImage; } node.Nodes.Add(new TreeNode(info.Name) { ImageIndex = imageIndex, SelectedImageIndex = imageIndex, Tag = info, ToolTipText = file, ContextMenuStrip = itemContextMenu }); }); }; updateNode(references, project.Assemblies); updateNode(root, project.SourceFiles); root.Expand(); treeView1.EndUpdate(); } catch (Exception e) { e.LogAsError(); } } }); }
void EditItem(string scriptFile) { Npp.OpenFile(scriptFile); }
void favoritesBtn_Click(object sender, EventArgs e) { tabControl1.SelectTabWith(favPanel); favPanel.Add(Npp.GetCurrentFile()); }
public void beNotified(IntPtr notifyCode) { try { CSScriptIntellisense.Interop.NppUI.OnNppTick(); ScNotification nc = (ScNotification)Marshal.PtrToStructure(notifyCode, typeof(ScNotification)); string contentFile = Npp.Editor.GetTabFile(nc.Header.IdFrom); //Debug.WriteLine(">>>>> ncnc.nmhdr.code={0}, {1}", nc.nmhdr.code, (int)nc.nmhdr.code); if (nc.Header.Code == (uint)NppMsg.NPPN_READY) { CSScriptIntellisense.Plugin.OnNppReady(); CSScriptNpp.Plugin.OnNppReady(); npp.SetCalltipTime(500); } else if (nc.Header.Code == (uint)NppMsg.NPPN_SHUTDOWN) { CSScriptNpp.Plugin.StopVBCSCompilers(); } else if (nc.Header.Code == (uint)NppMsg.NPPN_TBMODIFICATION) { CSScriptNpp.Plugin.OnToolbarUpdate(); } else if (nc.Header.Code == (uint)NppMsg.NPPM_SAVECURRENTFILEAS || (Config.Instance.HandleSaveAs && nc.Header.Code == (uint)SciMsg.SCN_SAVEPOINTREACHED)) //for some strange reason NPP doesn't fire NPPM_SAVECURRENTFILEAS but does 2002 instead. { if (Plugin.ProjectPanel != null) { var panel_visible = Plugin.ProjectPanel.Visible; } string file = Npp.Editor.GetCurrentFilePath(); if (file != lastActivatedBuffer) { CSScriptNpp.Plugin.OnFileSavedAs(lastActivatedBuffer, file); } } else if (nc.Header.Code == (uint)SciMsg.SCN_CHARADDED) { CSScriptIntellisense.Plugin.OnCharTyped(nc.Character); } else if (nc.Header.Code == (uint)SciMsg.SCN_MARGINCLICK) { if (nc.Margin == _SC_MARGE_SYBOLE && nc.Mmodifiers == SCI_CTRL) { var document = Npp.GetCurrentDocument(); int lineClick = document.LineFromPosition(nc.Position.Value); Debugger.ToggleBreakpoint(lineClick); } } else if (nc.Header.Code == (uint)SciMsg.SCN_DWELLSTART) //tooltip { //Npp.ShowCalltip(nc.position, "\u0001 1 of 3 \u0002 test tooltip " + Environment.TickCount); //Npp.ShowCalltip(nc.position, CSScriptIntellisense.Npp.GetWordAtPosition(nc.position)); //tooltip = @"Creates all directories and subdirectories as specified by path. npp.OnCalltipRequest(nc.Position.Value); } else if (nc.Header.Code == (uint)SciMsg.SCN_DWELLEND) { npp.CancelCalltip(); } else if (nc.Header.Code == (uint)NppMsg.NPPN_BUFFERACTIVATED) { string file = Npp.Editor.GetCurrentFilePath(); lastActivatedBuffer = file; if (file.EndsWith("npp.args")) { Win32.SendMessage(Npp.Editor.Handle, (uint)NppMsg.NPPM_MENUCOMMAND, 0, NppMenuCmd.IDM_FILE_CLOSE); string args = File.ReadAllText(file); Plugin.ProcessCommandArgs(args); try { File.Delete(file); } catch { } } else { CSScriptIntellisense.Plugin.OnCurrentFileChanegd(); CSScriptNpp.Plugin.OnCurrentFileChanged(); Debugger.OnCurrentFileChanged(); } } else if (nc.Header.Code == (uint)NppMsg.NPPN_FILEOPENED) { string file = Npp.Editor.GetTabFile(nc.Header.IdFrom); Debugger.LoadBreakPointsFor(file); } else if (nc.Header.Code == (uint)NppMsg.NPPN_FILESAVED) { Plugin.OnDocumentSaved(); Debugger.RefreshBreakPointsInContent(); } else if (nc.Header.Code == (uint)NppMsg.NPPN_FILEBEFORECLOSE) { SaveBreakpoints(contentFile); } else if (nc.Header.Code == (uint)NppMsg.NPPN_FILEBEFORESAVE) { CSScriptIntellisense.Plugin.OnBeforeDocumentSaved(); // Formatting may have shifted all breakpoints Debugger.ResetBreaksPointsFromContent(); } else if (nc.Header.Code == (uint)NppMsg.NPPN_SHUTDOWN) { Marshal.FreeHGlobal(_ptrPluginName); Plugin.CleanUp(); } if (nc.Header.Code == (uint)SciMsg.SCI_ENDUNDOACTION) { //CSScriptIntellisense.Plugin.OnSavedOrUndo(); } Plugin.OnNotification(nc); } catch { }//this is indeed the last line of defense as all CS-S calls have the error handling inside }
static public void OnCalltipRequest(int position) { if (position == -2) { Calltip.LastEval = Calltip.LastExpression = null; //if DBG frame is changed so clear the data } else { if (Calltip.IsShowing) { return; } Calltip.IsShowing = true; Task.Factory.StartNew(() => //must be asynch to allow processing other Debugger notifications { string underMouseExpression = Npp.GetCurrentDocument().GetStatementAtPosition(position); string document = Npp.Editor.GetCurrentFilePath(); string tooltip = null; //if (Debugger.IsInBreak) //The calltips are used to show the values of the variables only. For everything else (e.g. MemberInfo) modal borderless forms are used //{ if (!string.IsNullOrEmpty(underMouseExpression)) { //also need to check expression start position (if not debugging) as the same expression can lead to different tooltip //NOTE: if DBG frame is changed the LastExpression is cleared if (underMouseExpression == Calltip.LastExpression && Calltip.LastDocument == document) { if (Debugger.IsInBreak) { tooltip = Calltip.LastEval; } } //if (underMouseExpression != Calltip.LastExpression) //{ // System.Diagnostics.Debug.WriteLine("GetDebugTooltipValue -> expression is changed..."); // System.Diagnostics.Debug.WriteLine("old: " + Calltip.LastExpression); // System.Diagnostics.Debug.WriteLine("new: " + underMouseExpression); //} //if (Calltip.LastDocument != document) // System.Diagnostics.Debug.WriteLine("GetDebugTooltipValue -> document is changed..."); if (tooltip == null) { if (Debugger.IsInBreak) { tooltip = Debugger.GetDebugTooltipValue(underMouseExpression); } else if (CSScriptIntellisense.Config.Instance.ShowQuickInfoAsNativeNppTooltip) { tooltip = CSScriptIntellisense.Plugin.GetMemberUnderCursorInfo().FirstOrDefault(); } Calltip.LastDocument = document; Calltip.LastEval = tooltip.TruncateLines(Config.Instance.CollectionItemsInTooltipsMaxCount, "\n<Content was truncated. Use F12 to see the raw API documentation data.>"); Calltip.LastExpression = underMouseExpression; } if (tooltip != null) { npp.ShowCalltip(position, tooltip); return; } } Calltip.IsShowing = false; }); } }
/***********************************/ static public void CancelCalltip() { Npp.GetCurrentDocument().CallTipCancel(); Calltip.IsShowing = false; }
static IEnumerable <Keys> BindInteranalShortcuts() { var uniqueKeys = new Dictionary <Keys, int>(); AddInternalShortcuts("Build:F7", "Build (validate)", Build, uniqueKeys); AddInternalShortcuts("LoadCurrentDocument:Ctrl+F7", "Load Current Document", () => { InitProjectPanel(); ShowProjectPanel(); ProjectPanel.LoadCurrentDoc(); }, uniqueKeys); AddInternalShortcuts("Stop:Shift+F5", "Stop running script", Stop, uniqueKeys); AddInternalShortcuts("_Run:F5", "Run", Run, uniqueKeys); AddInternalShortcuts("_Debug:Alt+F5", "Debug", () => { if (!Debugger.IsRunning && Npp.IsCurrentScriptFile()) { DebugScript(); } }, uniqueKeys); AddInternalShortcuts("ToggleBreakpoint:F9", "Toggle Breakpoint", () => Debugger.ToggleBreakpoint(), uniqueKeys); AddInternalShortcuts("QuickWatch:Shift+F9", "Show QuickWatch...", QuickWatchPanel.PopupDialog, uniqueKeys); AddInternalShortcuts("StepInto:F11", "Step Into", Debugger.StepIn, uniqueKeys); AddInternalShortcuts("StepOut:Shift+F11", "Step Out", Debugger.StepOut, uniqueKeys); AddInternalShortcuts("StepOver:F10", "Step Over", StepOver, uniqueKeys); AddInternalShortcuts("SetNextIP:Ctrl+Shift+F10", "Set Next Statement", Debugger.SetInstructionPointer, uniqueKeys); AddInternalShortcuts("RunToCursor:Ctrl+F10", "Run To Cursor", Debugger.RunToCursor, uniqueKeys); AddInternalShortcuts("RunAsExternal:Ctrl+F5", "Run As External Process", () => { if (Npp.IsCurrentScriptFile()) { RunAsExternal(); } }, uniqueKeys); AddInternalShortcuts("ShowNextFileLocationFromOutput:F4", "Next File Location in Output", () => { OutputPanel.TryNavigateToFileReference(toNext: true); }, uniqueKeys); AddInternalShortcuts("ShowPrevFileLocationFromOutput:Shift+F4", "Previous File Location in Output", () => { OutputPanel.TryNavigateToFileReference(toNext: false); }, uniqueKeys); return(uniqueKeys.Keys); }