コード例 #1
0
        public override async void DoCommand(object sender, EventArgs args)
        {
            var view     = CommonPackage.GetActiveTextView(_serviceProvider);
            var analyzer = view.GetAnalyzer(_serviceProvider);

            await analyzer.RemoveImportsAsync(view.TextBuffer, view.Caret.Position.BufferPosition, _allScopes);
        }
コード例 #2
0
        public override void DoCommand(object sender, EventArgs args)
        {
            var activeView = CommonPackage.GetActiveTextView(_serviceProvider);
            var project    = activeView.TextBuffer.GetProject(_serviceProvider);
            var analyzer   = activeView.GetAnalyzer(_serviceProvider);

            ToolWindowPane window = (ToolWindowPane)ExecuteInReplCommand.EnsureReplWindow(_serviceProvider, analyzer, project);

            IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;

            ErrorHandler.ThrowOnFailure(windowFrame.Show());
            var repl = (IVsReplWindow)window;

#if DEV14_OR_LATER
            PythonReplEvaluator eval = repl.InteractiveWindow.Evaluator as PythonReplEvaluator;
#else
            PythonReplEvaluator eval = repl.Evaluator as PythonReplEvaluator;
#endif

            eval.EnsureConnected();
#if DEV14_OR_LATER
            repl.InteractiveWindow.Submit(GetActiveInputs(activeView, eval));
#else
            repl.Submit(GetActiveInputs(activeView, eval));
#endif

            repl.Focus();
        }
コード例 #3
0
        public override void DoCommand(object sender, EventArgs args)
        {
            if (!Utilities.SaveDirtyFiles())
            {
                // Abort
                return;
            }

            // Launch with project context if there is one and it contains the active document
            // Fallback to using default python project
            var file = CommonPackage.GetActiveTextView(_serviceProvider).GetFilePath();
            var pythonProjectNode = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;

            if ((pythonProjectNode != null) && (pythonProjectNode.FindNodeByFullPath(file) == null))
            {
                pythonProjectNode = null;
            }
            IPythonProject pythonProject = pythonProjectNode as IPythonProject ?? new DefaultPythonProject(_serviceProvider, file);

            var launcher = PythonToolsPackage.GetLauncher(_serviceProvider, pythonProject);

            try {
                launcher.LaunchFile(file, CommandId == CommonConstants.StartDebuggingCmdId);
            } catch (NoInterpretersException ex) {
                PythonToolsPackage.OpenNoInterpretersHelpPage(_serviceProvider, ex.HelpPage);
            }
        }
コード例 #4
0
        public override int?EditFilterQueryStatus(ref VisualStudio.OLE.Interop.OLECMD cmd, IntPtr pCmdText)
        {
            var activeView = CommonPackage.GetActiveTextView(_serviceProvider);

            InterpreterConfiguration config;

            if ((config = activeView?.GetInterpreterConfigurationAtCaret(_serviceProvider)) != null)
            {
                if (activeView.Selection.Mode == TextSelectionMode.Box ||
                    config?.IsRunnable() != true)
                {
                    cmd.cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED);
                }
                else
                {
                    cmd.cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED);
                }
            }
            else
            {
                cmd.cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE);
            }

            return(VSConstants.S_OK);
        }
コード例 #5
0
        private void QueryStatusMethod(object sender, EventArgs args)
        {
            var oleMenu = sender as OleMenuCommand;

            IWpfTextView textView;
            var          pyProj = CommonPackage.GetStartupProject() as PythonProjectNode;

            if (pyProj != null)
            {
                // startup project, enabled in Start in REPL mode.
                oleMenu.Visible   = true;
                oleMenu.Enabled   = true;
                oleMenu.Supported = true;
                oleMenu.Text      = "Execute Project in P&ython Interactive";
            }
            else if ((textView = CommonPackage.GetActiveTextView()) != null &&
                     textView.TextBuffer.ContentType == PythonToolsPackage.Instance.ContentType)
            {
                // enabled in Execute File mode...
                oleMenu.Visible   = true;
                oleMenu.Enabled   = true;
                oleMenu.Supported = true;
                oleMenu.Text      = "Execute File in P&ython Interactive";
            }
            else
            {
                oleMenu.Visible   = false;
                oleMenu.Enabled   = false;
                oleMenu.Supported = false;
            }
        }
コード例 #6
0
        public override async void DoCommand(object sender, EventArgs args)
        {
            var view     = CommonPackage.GetActiveTextView(_serviceProvider);
            var analyzer = view?.GetAnalyzerAtCaret(_serviceProvider);

            if (analyzer == null)
            {
                // Can sometimes race with initializing the analyzer (probably
                // only in tests), so delay slightly until we get an analyzer
                for (int retries = 10; retries > 0 && analyzer == null; --retries)
                {
                    await Task.Delay(10);

                    view     = CommonPackage.GetActiveTextView(_serviceProvider);
                    analyzer = view?.GetAnalyzerAtCaret(_serviceProvider);
                }
            }

            var pythonCaret = view?.GetPythonCaret();

            if (analyzer == null || !pythonCaret.HasValue)
            {
                Debug.Fail("Executed RemoveImportsCommand with invalid view");
                return;
            }

            await analyzer.RemoveImportsAsync(pythonCaret.Value, _allScopes);
        }
コード例 #7
0
        public override int?EditFilterQueryStatus(ref VisualStudio.OLE.Interop.OLECMD cmd, IntPtr pCmdText)
        {
            var activeView = CommonPackage.GetActiveTextView(_serviceProvider);
            var empty      = activeView.Selection.IsEmpty;

            Intellisense.VsProjectAnalyzer analyzer;
            if (activeView != null && (analyzer = activeView.GetAnalyzerAtCaret(_serviceProvider)) != null)
            {
                if (activeView.Selection.Mode == TextSelectionMode.Box ||
                    analyzer == null ||
                    !IsRealInterpreter(analyzer.InterpreterFactory))
                {
                    cmd.cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED);
                }
                else
                {
                    cmd.cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED);
                }
            }
            else
            {
                cmd.cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE);
            }

            return(VSConstants.S_OK);
        }
コード例 #8
0
ファイル: SendToReplCommand.cs プロジェクト: krus/PTVS
        public override int?EditFilterQueryStatus(ref VisualStudio.OLE.Interop.OLECMD cmd, IntPtr pCmdText)
        {
            var activeView = CommonPackage.GetActiveTextView(_serviceProvider);

            if (activeView != null && activeView.TextBuffer.ContentType.IsOfType(PythonCoreConstants.ContentType))
            {
                var analyzer = activeView.GetAnalyzer(_serviceProvider);

                if (activeView.Selection.IsEmpty ||
                    activeView.Selection.Mode == TextSelectionMode.Box ||
                    analyzer == null ||
                    !IsRealInterpreter(analyzer.InterpreterFactory))
                {
                    cmd.cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED);
                }
                else
                {
                    cmd.cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED);
                }
            }
            else
            {
                cmd.cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE);
            }

            return(VSConstants.S_OK);
        }
コード例 #9
0
ファイル: EditFilter.cs プロジェクト: krus/PTVS
 private void QueryStatusRename(OLECMD[] prgCmds, int i) {
     IWpfTextView activeView = CommonPackage.GetActiveTextView(_serviceProvider);
     if (_textView.TextBuffer.ContentType.IsOfType(PythonCoreConstants.ContentType)) {
         prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED);
     } else {
         prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE);
     }
 }
コード例 #10
0
        public override async void DoCommand(object sender, EventArgs args)
        {
            var view        = CommonPackage.GetActiveTextView(_serviceProvider);
            var analyzer    = view.GetAnalyzerAtCaret(_serviceProvider);
            var pythonCaret = view.GetPythonCaret().Value; // QueryStatus guarantees we have a valid caret

            await analyzer.RemoveImportsAsync(view, pythonCaret.Snapshot.TextBuffer, pythonCaret.Position, _allScopes);
        }
コード例 #11
0
        public override void DoCommand(object sender, EventArgs args)
        {
            if (!Utilities.SaveDirtyFiles())
            {
                // Abort
                return;
            }

            // Launch with project context if there is one and it contains the active document
            // Fallback to using default python project
            var         file = CommonPackage.GetActiveTextView(_serviceProvider).GetFilePath();
            var         sln  = (IVsSolution)_serviceProvider.GetService(typeof(SVsSolution));
            IEnumerable projects;

            try {
                projects = _serviceProvider.GetDTE().ActiveSolutionProjects as IEnumerable;
            } catch (COMException) {
                // ActiveSolutionProjects can fail if Solution Explorer has not been loaded
                projects = Enumerable.Empty <EnvDTE.Project>();
            }

            var pythonProject = (projects == null ? null : projects.OfType <EnvDTE.Project>()
                                 .Select(p => p.GetPythonProject())
                                 .FirstOrDefault(p => p != null && p.FindNodeByFullPath(file) != null) as IPythonProject)
                                ?? new DefaultPythonProject(_serviceProvider, file);

            var launcher = PythonToolsPackage.GetLauncher(_serviceProvider, pythonProject);

            try {
                var launcher2 = launcher as IProjectLauncher2;
                if (launcher2 != null)
                {
                    launcher2.LaunchFile(
                        file,
                        CommandId == CommonConstants.StartDebuggingCmdId,
                        new LaunchFileProperties(
                            null,
                            PathUtils.GetParent(file),
                            pythonProject.GetInterpreterFactory().Configuration.PathEnvironmentVariable,
                            pythonProject.GetWorkingDirectory()
                            )
                        );
                }
                else
                {
                    launcher.LaunchFile(file, CommandId == CommonConstants.StartDebuggingCmdId);
                }
            } catch (MissingInterpreterException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            } catch (NoInterpretersException ex) {
                PythonToolsPackage.OpenNoInterpretersHelpPage(_serviceProvider, ex.HelpPage);
            }
        }
コード例 #12
0
ファイル: ExecuteInReplCommand.cs プロジェクト: int19h/PTVS
        private void QueryStatusMethod(object sender, EventArgs args)
        {
            var oleMenu = sender as OleMenuCommand;

            if (oleMenu == null)
            {
                Debug.Fail("Unexpected command type " + sender == null ? "(null)" : sender.GetType().FullName);
                return;
            }

            var workspace = _serviceProvider.GetWorkspace();
            var pyProj    = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;
            var textView  = CommonPackage.GetActiveTextView(_serviceProvider);

            oleMenu.Supported = true;

            if (pyProj != null)
            {
                // startup project, so visible in Project mode
                oleMenu.Visible = true;
                oleMenu.Text    = Strings.ExecuteInReplCommand_ExecuteProject;

                // Only enable if runnable
                oleMenu.Enabled = pyProj.GetInterpreterFactory().IsRunnable();
            }
            else if (textView != null && textView.TextBuffer.ContentType.IsOfType(PythonCoreConstants.ContentType))
            {
                // active file, so visible in File mode
                oleMenu.Visible = true;
                oleMenu.Text    = Strings.ExecuteInReplCommand_ExecuteFile;

                // Only enable if runnable
                if (workspace != null)
                {
                    oleMenu.Enabled = workspace.CurrentFactory.IsRunnable();
                }
                else
                {
                    var interpreterService = _serviceProvider.GetComponentModel().GetService <IInterpreterOptionsService>();
                    oleMenu.Enabled = interpreterService != null && interpreterService.DefaultInterpreter.IsRunnable();
                }
            }
            else
            {
                // Python is not active, so hide the command
                oleMenu.Visible = false;
                oleMenu.Enabled = false;
            }
        }
コード例 #13
0
ファイル: ExecuteInReplCommand.cs プロジェクト: tk811/PTVS
        public override void DoCommand(object sender, EventArgs args)
        {
            var pyProj   = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;
            var textView = CommonPackage.GetActiveTextView(_serviceProvider);

            VsProjectAnalyzer analyzer;
            string            filename, dir = null;

            if (pyProj != null)
            {
                analyzer = pyProj.GetAnalyzer();
                filename = pyProj.GetStartupFile();
                dir      = pyProj.GetWorkingDirectory();
            }
            else if (textView != null)
            {
                var pyService = _serviceProvider.GetPythonToolsService();
                analyzer = pyService.DefaultAnalyzer;
                filename = textView.GetFilePath();
            }
            else
            {
                Debug.Fail("Should not be executing command when it is invisible");
                return;
            }
            if (string.IsNullOrEmpty(filename))
            {
                // TODO: Error reporting
                return;
            }
            if (string.IsNullOrEmpty(dir))
            {
                dir = PathUtils.GetParent(filename);
            }

            var window = EnsureReplWindow(_serviceProvider, analyzer, pyProj);

            window.Show(true);

            // The interpreter may take some time to startup, do this off the UI thread.
            ThreadPool.QueueUserWorkItem(x => {
                window.InteractiveWindow.Evaluator.ResetAsync().WaitAndUnwrapExceptions();

                window.InteractiveWindow.WriteLine(String.Format("Running {0}", filename));
                string scopeName = Path.GetFileNameWithoutExtension(filename);

                ((PythonReplEvaluator)window.InteractiveWindow.Evaluator).ExecuteFile(filename);
            });
        }
コード例 #14
0
ファイル: EditFilter.cs プロジェクト: krus/PTVS
        private void QueryStatusExtractMethod(OLECMD[] prgCmds, int i) {
            var activeView = CommonPackage.GetActiveTextView(_serviceProvider);

            if (_textView.TextBuffer.ContentType.IsOfType(PythonCoreConstants.ContentType)) {
                if (_textView.Selection.IsEmpty || 
                    _textView.Selection.Mode == TextSelectionMode.Box ||
                    String.IsNullOrWhiteSpace(_textView.Selection.StreamSelectionSpan.GetText())) {
                    prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED);
                } else {
                    prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED);
                }
            } else {
                prgCmds[i].cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE);
            }
        }
コード例 #15
0
        public override int?EditFilterQueryStatus(ref VisualStudio.OLE.Interop.OLECMD cmd, IntPtr pCmdText)
        {
            var activeView = CommonPackage.GetActiveTextView(_serviceProvider);

            if (activeView != null && activeView.TextBuffer.ContentType.IsOfType(PythonCoreConstants.ContentType))
            {
                cmd.cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED);
            }
            else
            {
                cmd.cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE);
            }

            return(VSConstants.S_OK);
        }
コード例 #16
0
        public override int?EditFilterQueryStatus(ref VisualStudio.OLE.Interop.OLECMD cmd, IntPtr pCmdText)
        {
            var view        = CommonPackage.GetActiveTextView(_serviceProvider);
            var analyzer    = view?.GetAnalyzerAtCaret(_serviceProvider);
            var pythonCaret = view?.GetPythonCaret();

            if (view != null && analyzer != null && pythonCaret.HasValue)
            {
                cmd.cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED);
            }
            else
            {
                cmd.cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE);
            }

            return(VSConstants.S_OK);
        }
コード例 #17
0
        private void QueryStatusMethod(object sender, EventArgs args)
        {
            var oleMenu = sender as OleMenuCommand;
            VsProjectAnalyzer analyzer;
            var    interpreterService = _serviceProvider.GetComponentModel().GetService <IInterpreterOptionsService>();
            string filename, dir;

            if (!PythonToolsPackage.TryGetStartupFileAndDirectory(_serviceProvider, out filename, out dir, out analyzer) ||
                interpreterService == null ||
                interpreterService.NoInterpretersValue == analyzer.InterpreterFactory)
            {
                // no interpreters installed, disable the command.
                oleMenu.Visible   = true;
                oleMenu.Enabled   = false;
                oleMenu.Supported = true;
            }
            else
            {
                IWpfTextView textView;
                var          pyProj = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;
                var          window = (IReplWindow)EnsureReplWindow(_serviceProvider, analyzer, pyProj);
                if (pyProj != null)
                {
                    // startup project, enabled in Start in REPL mode.
                    oleMenu.Visible   = true;
                    oleMenu.Enabled   = true;
                    oleMenu.Supported = true;
                    oleMenu.Text      = "Execute Project in P&ython Interactive";
                }
                else if ((textView = CommonPackage.GetActiveTextView(_serviceProvider)) != null &&
                         textView.TextBuffer.ContentType == _serviceProvider.GetPythonContentType())
                {
                    // enabled in Execute File mode...
                    oleMenu.Visible   = true;
                    oleMenu.Enabled   = true;
                    oleMenu.Supported = true;
                    oleMenu.Text      = "Execute File in P&ython Interactive";
                }
                else
                {
                    oleMenu.Visible   = false;
                    oleMenu.Enabled   = false;
                    oleMenu.Supported = false;
                }
            }
        }
コード例 #18
0
        public override void DoCommand(object sender, EventArgs args)
        {
            var activeView = CommonPackage.GetActiveTextView(_serviceProvider);
            var project    = activeView.TextBuffer.GetProject(_serviceProvider);
            var analyzer   = activeView.GetAnalyzer(_serviceProvider);

            var repl = ExecuteInReplCommand.EnsureReplWindow(_serviceProvider, analyzer, project);

            repl.Show(true);

            PythonReplEvaluator eval = repl.InteractiveWindow.Evaluator as PythonReplEvaluator;

            eval.EnsureConnected();
            repl.InteractiveWindow.Submit(GetActiveInputs(activeView, eval));

            repl.Show(true);
        }
コード例 #19
0
        public override void DoCommand(object sender, EventArgs args)
        {
            var window = ExecuteInReplCommand.EnsureReplWindow();

            IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;

            ErrorHandler.ThrowOnFailure(windowFrame.Show());

            var activeView = CommonPackage.GetActiveTextView();

            foreach (var span in activeView.Selection.SelectedSpans)
            {
                var text = span.GetText();
                ((IReplWindow)window).PasteText(text);
            }

            ((IReplWindow)window).Focus();
        }
コード例 #20
0
ファイル: DebugAsScriptCommand.cs プロジェクト: xNUTs/PTVS
        public override void DoCommand(object sender, EventArgs args)
        {
            var file = CommonPackage.GetActiveTextView().GetFilePath();

            // Launch with project context if there is one and it contains the active document
            // Fallback to using default python project
            var pythonProjectNode = CommonPackage.GetStartupProject() as PythonProjectNode;

            if ((pythonProjectNode != null) && (pythonProjectNode.FindNodeByFullPath(file) == null))
            {
                pythonProjectNode = null;
            }
            IPythonProject pythonProject = pythonProjectNode as IPythonProject ?? new DefaultPythonProject(file);

            var launcher = PythonToolsPackage.GetLauncher(pythonProject);

            launcher.LaunchFile(file, true);
        }
コード例 #21
0
        private async System.Threading.Tasks.Task DoCommand()
        {
            var pyProj   = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;
            var textView = CommonPackage.GetActiveTextView(_serviceProvider);

            LaunchConfiguration config = null;

            try {
                config = pyProj?.GetLaunchConfigurationOrThrow();
            } catch (MissingInterpreterException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle);
                return;
            }
            if (config == null && textView != null)
            {
                var interpreters = _serviceProvider.GetComponentModel().GetService <IInterpreterOptionsService>();
                config = new LaunchConfiguration(interpreters.DefaultInterpreter.Configuration)
                {
                    ScriptName       = textView.GetFilePath(),
                    WorkingDirectory = PathUtils.GetParent(textView.GetFilePath())
                };
            }
            if (config == null)
            {
                Debug.Fail("Should not be executing command when it is invisible");
                return;
            }

            var window = EnsureReplWindow(_serviceProvider, config.Interpreter, pyProj);

            window.Show(true);

            var eval = (IPythonInteractiveEvaluator)window.InteractiveWindow.Evaluator;

            // The interpreter may take some time to startup, do this off the UI thread.
            await ThreadHelper.JoinableTaskFactory.RunAsync(async() => {
                await((IInteractiveEvaluator)eval).ResetAsync();

                window.InteractiveWindow.WriteLine(Strings.ExecuteInReplCommand_RunningMessage.FormatUI(config.ScriptName));

                await eval.ExecuteFileAsync(config.ScriptName, config.ScriptArguments);
            });
        }
コード例 #22
0
        public override int?EditFilterQueryStatus(ref VisualStudio.OLE.Interop.OLECMD cmd, IntPtr pCmdText)
        {
            var activeView = CommonPackage.GetActiveTextView();

            if (activeView != null && activeView.TextBuffer.ContentType.IsOfType(RubyCoreConstants.ContentType))
            {
                if (activeView.Selection.IsEmpty || activeView.Selection.Mode == TextSelectionMode.Box)
                {
                    cmd.cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED);
                }
                else
                {
                    cmd.cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED);
                }
            }
            else
            {
                cmd.cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE);
            }

            return(VSConstants.S_OK);
        }
コード例 #23
0
        internal static bool TryGetStartupFileAndDirectory(System.IServiceProvider serviceProvider, out string fileName, out string directory)
        {
            var startupProject = GetStartupProject(serviceProvider);

            if (startupProject != null)
            {
                fileName  = startupProject.GetStartupFile();
                directory = startupProject.GetWorkingDirectory();
            }
            else
            {
                var textView = CommonPackage.GetActiveTextView(serviceProvider);
                if (textView == null)
                {
                    fileName  = null;
                    directory = null;
                    return(false);
                }
                fileName  = textView.GetFilePath();
                directory = Path.GetDirectoryName(fileName);
            }
            return(true);
        }
コード例 #24
0
        public override async void DoCommand(object sender, EventArgs e)
        {
            var pyProj   = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;
            var textView = CommonPackage.GetActiveTextView(_serviceProvider);

            var config = pyProj?.GetLaunchConfigurationOrThrow();

            if (config == null && textView != null)
            {
                var pyService = _serviceProvider.GetPythonToolsService();
                config = new LaunchConfiguration(pyService.DefaultInterpreterConfiguration)
                {
                    ScriptName       = textView.GetFilePath(),
                    WorkingDirectory = PathUtils.GetParent(textView.GetFilePath())
                };
            }
            if (config == null)
            {
                Debug.Fail("Should not be executing command when it is invisible");
                return;
            }

            var window = EnsureReplWindow(_serviceProvider, config.Interpreter, pyProj);

            window.Show(true);

            var eval = (IPythonInteractiveEvaluator)window.InteractiveWindow.Evaluator;

            // The interpreter may take some time to startup, do this off the UI thread.
            await ThreadHelper.JoinableTaskFactory.RunAsync(async() => {
                await eval.ResetAsync();

                window.InteractiveWindow.WriteLine(string.Format("Running {0}", config.ScriptName));

                await eval.ExecuteFileAsync(config.ScriptName, config.ScriptArguments);
            });
        }
コード例 #25
0
        public override async void DoCommand(object sender, EventArgs args)
        {
            var            activeView = CommonPackage.GetActiveTextView(_serviceProvider);
            var            project    = activeView.GetProjectAtCaret(_serviceProvider);
            var            analyzer   = activeView.GetAnalyzerAtCaret(_serviceProvider);
            ITextSelection selection  = activeView.Selection;
            ITextSnapshot  snapshot   = activeView.TextBuffer.CurrentSnapshot;

            IVsInteractiveWindow repl;

            try {
                repl = ExecuteInReplCommand.EnsureReplWindow(_serviceProvider, analyzer, project);
            } catch (MissingInterpreterException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle);
                return;
            }

            string input;
            bool   focusRepl = false, alwaysSubmit = false;

            if (selection.StreamSelectionSpan.Length > 0)
            {
                // Easy, just send the selection to the interactive window.
                input = activeView.Selection.StreamSelectionSpan.GetText();
                if (!input.EndsWithOrdinal("\n") && !input.EndsWithOrdinal("\r"))
                {
                    input += activeView.Options.GetNewLineCharacter();
                }
                focusRepl = true;
            }
            else if (!activeView.Properties.ContainsProperty(_executedLastLine))
            {
                // No selection, and we haven't hit the end of the file in line-by-line mode.
                // Send the current line, and then move the caret to the next non-blank line.
                ITextSnapshotLine targetLine = snapshot.GetLineFromPosition(selection.Start.Position);
                var targetSpan = targetLine.Extent;

                // If the line is inside a code cell, expand the target span to
                // contain the entire cell.
                var cellStart = CodeCellAnalysis.FindStartOfCell(targetLine);
                if (cellStart != null)
                {
                    var cellEnd = CodeCellAnalysis.FindEndOfCell(cellStart, targetLine);
                    targetSpan   = new SnapshotSpan(cellStart.Start, cellEnd.End);
                    targetLine   = CodeCellAnalysis.FindEndOfCell(cellEnd, targetLine, includeWhitespace: true);
                    alwaysSubmit = true;
                }
                input = targetSpan.GetText();

                bool moved = false;
                while (targetLine.LineNumber < snapshot.LineCount - 1)
                {
                    targetLine = snapshot.GetLineFromLineNumber(targetLine.LineNumber + 1);
                    // skip over blank lines, unless it's the last line, in which case we want to land on it no matter what
                    if (!string.IsNullOrWhiteSpace(targetLine.GetText()) ||
                        targetLine.LineNumber == snapshot.LineCount - 1)
                    {
                        activeView.Caret.MoveTo(new SnapshotPoint(snapshot, targetLine.Start));
                        activeView.Caret.EnsureVisible();
                        moved = true;
                        break;
                    }
                }

                if (!moved)
                {
                    // There's no where for the caret to go, don't execute the line if
                    // we've already executed it.
                    activeView.Caret.PositionChanged        += Caret_PositionChanged;
                    activeView.Properties[_executedLastLine] = _executedLastLine;
                }
            }
            else if ((repl.InteractiveWindow.CurrentLanguageBuffer?.CurrentSnapshot.Length ?? 0) != 0)
            {
                // We reached the end of the file but have some text buffered.  Execute it now.
                input = activeView.Options.GetNewLineCharacter();
            }
            else
            {
                // We've hit the end of the current text view and executed everything
                input = null;
            }

            if (input != null)
            {
                repl.Show(focusRepl);

                var inputs = repl.InteractiveWindow.Properties.GetOrCreateSingletonProperty(
                    () => new InteractiveInputs(repl.InteractiveWindow, _serviceProvider, alwaysSubmit)
                    );

                await inputs.EnqueueAsync(input);
            }

            // Take focus back if REPL window has stolen it and we're in line-by-line mode.
            if (!focusRepl && !activeView.HasAggregateFocus)
            {
                var adapterService = _serviceProvider.GetComponentModel().GetService <VisualStudio.Editor.IVsEditorAdaptersFactoryService>();
                var tv             = adapterService.GetViewAdapter(activeView);
                tv.SendExplicitFocus();
            }
        }
コード例 #26
0
 public override void DoCommand(object sender, EventArgs args)
 {
     FillCommentParagraph(CommonPackage.GetActiveTextView(_serviceProvider));
 }
コード例 #27
0
ファイル: RemoveImportsCommand.cs プロジェクト: wqhbuaa/PTVS
 public override void DoCommand(object sender, EventArgs args)
 {
     new ImportRemover(_serviceProvider, CommonPackage.GetActiveTextView(_serviceProvider), true).RemoveImports();
 }
コード例 #28
0
ファイル: ExecuteInReplCommand.cs プロジェクト: int19h/PTVS
        private async System.Threading.Tasks.Task DoCommand()
        {
            var workspace = _serviceProvider.GetWorkspace();
            var pyProj    = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;
            var textView  = CommonPackage.GetActiveTextView(_serviceProvider);

            var scriptName = textView?.GetFilePath();

            if (!string.IsNullOrEmpty(scriptName) && pyProj != null)
            {
                if (pyProj.FindNodeByFullPath(scriptName) == null)
                {
                    // Starting a script that isn't in the project.
                    // Try and find the project. If we fail, we will
                    // use the default environment.
                    pyProj = _serviceProvider.GetProjectFromFile(scriptName);
                }
            }

            LaunchConfiguration config = null;

            try {
                if (workspace != null)
                {
                    config = PythonCommonInteractiveEvaluator.GetWorkspaceLaunchConfigurationOrThrow(workspace);
                }
                else
                {
                    config = pyProj?.GetLaunchConfigurationOrThrow();
                }
            } catch (MissingInterpreterException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle);
                return;
            }
            if (config == null)
            {
                var interpreters = _serviceProvider.GetComponentModel().GetService <IInterpreterOptionsService>();
                config = new LaunchConfiguration(interpreters.DefaultInterpreter.Configuration);
            }
            else
            {
                config = config.Clone();
            }

            if (!string.IsNullOrEmpty(scriptName))
            {
                config.ScriptName = scriptName;
                // Only overwrite the working dir for a loose file, don't do it for workspaces
                if (workspace == null)
                {
                    config.WorkingDirectory = PathUtils.GetParent(scriptName);
                }
            }

            if (config == null)
            {
                Debug.Fail("Should not be executing command when it is invisible");
                return;
            }

            IVsInteractiveWindow window;

            try {
                window = EnsureReplWindow(_serviceProvider, config.Interpreter, pyProj, workspace);
            } catch (MissingInterpreterException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle);
                return;
            }

            window.Show(true);
            var eval = (IPythonInteractiveEvaluator)window.InteractiveWindow.Evaluator;

            // The interpreter may take some time to startup, do this off the UI thread.
            await _serviceProvider.GetPythonToolsService().UIThread.InvokeAsync(async() => {
                await((IInteractiveEvaluator)eval).ResetAsync();

                window.InteractiveWindow.WriteLine(Strings.ExecuteInReplCommand_RunningMessage.FormatUI(config.ScriptName));

                await eval.ExecuteFileAsync(config.ScriptName, config.ScriptArguments);
            });
        }