Exemple #1
0
        public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments) {
            var finder = new FileFinder(arguments);

            var eval = window.GetPythonEvaluator();
            if (eval != null) {
                finder.Search(eval.Configuration.WorkingDirectory);
                foreach (var p in eval.Configuration.SearchPaths) {
                    finder.Search(p);
                }
            }

            finder.ThrowIfNotFound();
            string commandPrefix = "$";
            string lineBreak = window.TextView.Options.GetNewLineCharacter();

            IEnumerable<string> lines = File.ReadLines(finder.Filename);
            IEnumerable<string> submissions;

            if (eval != null) {
                submissions = ReplEditFilter.JoinToCompleteStatements(lines, eval.LanguageVersion).Where(CommentPrefixPredicate);
            } else {
                // v1 behavior, will probably never be hit, but if someone was developing their own IReplEvaluator
                // and using this class it would be hit.
                var submissionList = new List<string>();
                var currentSubmission = new List<string>();

                foreach (var line in lines) {
                    if (line.StartsWith(_commentPrefix)) {
                        continue;
                    }

                    if (line.StartsWith(commandPrefix)) {
                        AddSubmission(submissionList, currentSubmission, lineBreak);

                        submissionList.Add(line);
                        currentSubmission.Clear();
                    } else {
                        currentSubmission.Add(line);
                    }
                }

                AddSubmission(submissionList, currentSubmission, lineBreak);

                submissions = submissionList;
            }

            window.SubmitAsync(submissions);
            return ExecutionResult.Succeeded;
        }
        private async Task ResetInteractiveAsync(
            IInteractiveWindow interactiveWindow,
            ImmutableArray<string> referencePaths,
            ImmutableArray<string> referenceSearchPaths,
            ImmutableArray<string> sourceSearchPaths,
            ImmutableArray<string> namespacesToImport,
            string projectDirectory,
            IWaitContext waitContext)
        {
            // First, open the repl window.
            IInteractiveEvaluator evaluator = interactiveWindow.Evaluator;

            // If the user hits the cancel button on the wait indicator, then we want to stop the
            // build.
            waitContext.CancellationToken.Register(() =>
                CancelBuildProject(), useSynchronizationContext: true);

            // First, start a build.
            // If the build fails do not reset the REPL.
            var builtSuccessfully = await BuildProject().ConfigureAwait(true);
            if (!builtSuccessfully)
            {
                return;
            }

            // Then reset the REPL
            waitContext.Message = InteractiveEditorFeaturesResources.ResettingInteractive;
            await interactiveWindow.Operations.ResetAsync(initialize: true).ConfigureAwait(true);

            // TODO: load context from an rsp file.

            // Now send the reference paths we've collected to the repl.
            // The SetPathsAsync method is not available through an Interface.
            // Execute the method only if the cast to a concrete InteractiveEvaluator succeeds.
            InteractiveEvaluator interactiveEvaluator = evaluator as InteractiveEvaluator;
            if (interactiveEvaluator != null)
            {
                await interactiveEvaluator.SetPathsAsync(referenceSearchPaths, sourceSearchPaths, projectDirectory).ConfigureAwait(true);
            }

            await interactiveWindow.SubmitAsync(new[]
            {
                referencePaths.Select(_createReference).Join("\r\n"),
                namespacesToImport.Select(_createImport).Join("\r\n")
            }).ConfigureAwait(true);
        }
Exemple #3
0
        private static async Task PasteReplCode(
            IInteractiveWindow window,
            string pasting,
            PythonLanguageVersion version
        ) {
            // there's some text in the buffer...
            var view = window.TextView;
            var caret = view.Caret;

            if (view.Selection.IsActive && !view.Selection.IsEmpty) {
                foreach (var span in view.Selection.SelectedSpans) {
                    foreach (var normalizedSpan in view.BufferGraph.MapDownToBuffer(span, SpanTrackingMode.EdgeInclusive, window.CurrentLanguageBuffer)) {
                        normalizedSpan.Snapshot.TextBuffer.Delete(normalizedSpan);
                    }
                }
            }

            var curBuffer = window.CurrentLanguageBuffer;
            var inputPoint = view.BufferGraph.MapDownToBuffer(
                caret.Position.BufferPosition,
                PointTrackingMode.Positive,
                curBuffer,
                PositionAffinity.Successor
            );


            // if we didn't find a location then see if we're in a prompt, and if so, then we want
            // to insert after the prompt.
            if (caret.Position.BufferPosition != window.TextView.TextBuffer.CurrentSnapshot.Length) {
                for (int i = caret.Position.BufferPosition + 1;
                    inputPoint == null && i <= window.TextView.TextBuffer.CurrentSnapshot.Length;
                    i++) {
                    inputPoint = view.BufferGraph.MapDownToBuffer(
                        new SnapshotPoint(window.TextView.TextBuffer.CurrentSnapshot, i),
                        PointTrackingMode.Positive,
                        curBuffer,
                        PositionAffinity.Successor
                    );
                }
            }

            if (inputPoint == null) {
                // we didn't find a point to insert, insert at the beginning.
                inputPoint = new SnapshotPoint(curBuffer.CurrentSnapshot, 0);
            }

            // we want to insert the pasted code at the caret, but we also want to
            // respect the stepping.  So first grab the code before and after the caret.
            string startText = curBuffer.CurrentSnapshot.GetText(0, inputPoint.Value);

            string endText = curBuffer.CurrentSnapshot.GetText(
                inputPoint.Value,
                curBuffer.CurrentSnapshot.Length - inputPoint.Value);


            var splitCode = JoinToCompleteStatements(SplitAndDedent(startText + pasting + endText), version).ToList();
            curBuffer.Delete(new Span(0, curBuffer.CurrentSnapshot.Length));

            bool supportMultiple = await window.GetSupportsMultipleStatements();

            if (supportMultiple) {
                await window.SubmitAsync(new[] { string.Join(Environment.NewLine, splitCode) });
            } else if (splitCode.Count == 1) {
                curBuffer.Insert(0, splitCode[0]);
                var viewPoint = view.BufferGraph.MapUpToBuffer(
                    new SnapshotPoint(curBuffer.CurrentSnapshot, Math.Min(inputPoint.Value.Position + pasting.Length, curBuffer.CurrentSnapshot.Length)),
                    PointTrackingMode.Positive,
                    PositionAffinity.Successor,
                    view.TextBuffer
                );

                if (viewPoint != null) {
                    view.Caret.MoveTo(viewPoint.Value);
                }
            } else if (splitCode.Count != 0) {
                var lastCode = splitCode[splitCode.Count - 1];
                splitCode.RemoveAt(splitCode.Count - 1);

                while (splitCode.Any()) {
                    var code = splitCode[0];
                    splitCode.RemoveAt(0);
                    await window.SubmitAsync(new[] { code });

                    supportMultiple = await window.GetSupportsMultipleStatements();
                    if (supportMultiple) {
                        // Might have changed while we were executing
                        break;
                    }
                }

                if (supportMultiple) {
                    // Submit all remaning lines of code
                    await window.SubmitAsync(new[] { string.Join(Environment.NewLine, splitCode) });
                } else {
                    window.CurrentLanguageBuffer.Insert(0, lastCode);
                }
            } else {
                window.CurrentLanguageBuffer.Insert(0, startText + pasting + endText);
            }
        }
Exemple #4
0
        private async Task ResetInteractiveAsync(
            IInteractiveWindow interactiveWindow,
            ImmutableArray<string> referencePaths,
            ImmutableArray<string> referenceSearchPaths,
            ImmutableArray<string> sourceSearchPaths,
            ImmutableArray<string> projectNamespaces,
            string projectDirectory,
            IWaitContext waitContext)
        {
            // First, open the repl window.
            IInteractiveEvaluator evaluator = interactiveWindow.Evaluator;

            // If the user hits the cancel button on the wait indicator, then we want to stop the
            // build.
            using (waitContext.CancellationToken.Register(() =>
                CancelBuildProject(), useSynchronizationContext: true))
            {
                // First, start a build.
                // If the build fails do not reset the REPL.
                var builtSuccessfully = await BuildProject().ConfigureAwait(true);
                if (!builtSuccessfully)
                {
                    return;
                }
            }

            // Then reset the REPL
            waitContext.Message = InteractiveEditorFeaturesResources.Resetting_Interactive;
            await interactiveWindow.Operations.ResetAsync(initialize: true).ConfigureAwait(true);

            // TODO: load context from an rsp file.

            // Now send the reference paths we've collected to the repl.
            // The SetPathsAsync method is not available through an Interface.
            // Execute the method only if the cast to a concrete InteractiveEvaluator succeeds.
            InteractiveEvaluator interactiveEvaluator = evaluator as InteractiveEvaluator;
            if (interactiveEvaluator != null)
            {
                await interactiveEvaluator.SetPathsAsync(referenceSearchPaths, sourceSearchPaths, projectDirectory).ConfigureAwait(true);
            }

            var editorOptions = _editorOptionsFactoryService.GetOptions(interactiveWindow.CurrentLanguageBuffer);
            var importReferencesCommand = referencePaths.Select(_createReference);
            await interactiveWindow.SubmitAsync(importReferencesCommand).ConfigureAwait(true);

            // Project's default namespace might be different from namespace used within project.
            // Filter out namespace imports that do not exist in interactive compilation.
            IEnumerable<string> namespacesToImport = await GetNamespacesToImportAsync(projectNamespaces, interactiveWindow).ConfigureAwait(true);
            var importNamespacesCommand = namespacesToImport.Select(_createImport).Join(editorOptions.GetNewLineCharacter());

            if (!string.IsNullOrWhiteSpace(importNamespacesCommand))
            {
                await interactiveWindow.SubmitAsync(new[] { importNamespacesCommand }).ConfigureAwait(true);
            }
        }
Exemple #5
0
 public void SubmitText(string text)
 {
     using var cts = new CancellationTokenSource(Helper.HangMitigatingTimeout);
     _interactiveWindow.SubmitAsync(new[] { text }).WithCancellation(cts.Token).Wait();
 }
Exemple #6
0
        private static async Task PasteReplCode(
            IInteractiveWindow window,
            string pasting,
            PythonLanguageVersion version
            )
        {
            // there's some text in the buffer...
            var view  = window.TextView;
            var caret = view.Caret;

            if (view.Selection.IsActive && !view.Selection.IsEmpty)
            {
                foreach (var span in view.Selection.SelectedSpans)
                {
                    foreach (var normalizedSpan in view.BufferGraph.MapDownToBuffer(span, SpanTrackingMode.EdgeInclusive, window.CurrentLanguageBuffer))
                    {
                        normalizedSpan.Snapshot.TextBuffer.Delete(normalizedSpan);
                    }
                }
            }

            var curBuffer  = window.CurrentLanguageBuffer;
            var inputPoint = view.BufferGraph.MapDownToBuffer(
                caret.Position.BufferPosition,
                PointTrackingMode.Positive,
                curBuffer,
                PositionAffinity.Successor
                );


            // if we didn't find a location then see if we're in a prompt, and if so, then we want
            // to insert after the prompt.
            if (caret.Position.BufferPosition != window.TextView.TextBuffer.CurrentSnapshot.Length)
            {
                for (int i = caret.Position.BufferPosition + 1;
                     inputPoint == null && i <= window.TextView.TextBuffer.CurrentSnapshot.Length;
                     i++)
                {
                    inputPoint = view.BufferGraph.MapDownToBuffer(
                        new SnapshotPoint(window.TextView.TextBuffer.CurrentSnapshot, i),
                        PointTrackingMode.Positive,
                        curBuffer,
                        PositionAffinity.Successor
                        );
                }
            }

            if (inputPoint == null)
            {
                // we didn't find a point to insert, insert at the beginning.
                inputPoint = new SnapshotPoint(curBuffer.CurrentSnapshot, 0);
            }

            // we want to insert the pasted code at the caret, but we also want to
            // respect the stepping.  So first grab the code before and after the caret.
            string startText = curBuffer.CurrentSnapshot.GetText(0, inputPoint.Value);

            string endText = curBuffer.CurrentSnapshot.GetText(
                inputPoint.Value,
                curBuffer.CurrentSnapshot.Length - inputPoint.Value);


            var splitCode = JoinToCompleteStatements(SplitAndDedent(startText + pasting + endText), version).ToList();

            curBuffer.Delete(new Span(0, curBuffer.CurrentSnapshot.Length));

            bool supportMultiple = window.GetPythonEvaluator()?.SupportsMultipleStatements ?? false;

            if (supportMultiple)
            {
                await window.SubmitAsync(new[] { string.Join(Environment.NewLine, splitCode) });
            }
            else if (splitCode.Count == 1)
            {
                curBuffer.Insert(0, splitCode[0]);
                var viewPoint = view.BufferGraph.MapUpToBuffer(
                    new SnapshotPoint(curBuffer.CurrentSnapshot, Math.Min(inputPoint.Value.Position + pasting.Length, curBuffer.CurrentSnapshot.Length)),
                    PointTrackingMode.Positive,
                    PositionAffinity.Successor,
                    view.TextBuffer
                    );

                if (viewPoint != null)
                {
                    view.Caret.MoveTo(viewPoint.Value);
                }
            }
            else if (splitCode.Count != 0)
            {
                var lastCode = splitCode[splitCode.Count - 1];
                splitCode.RemoveAt(splitCode.Count - 1);

                while (splitCode.Any())
                {
                    var code = splitCode[0];
                    splitCode.RemoveAt(0);
                    await window.SubmitAsync(new[] { code });

                    supportMultiple = window.GetPythonEvaluator()?.SupportsMultipleStatements ?? false;
                    if (supportMultiple)
                    {
                        // Might have changed while we were executing
                        break;
                    }
                }

                if (supportMultiple)
                {
                    // Submit all remaning lines of code
                    await window.SubmitAsync(new[] { string.Join(Environment.NewLine, splitCode) });
                }
                else
                {
                    window.CurrentLanguageBuffer.Insert(0, lastCode);
                }
            }
            else
            {
                window.CurrentLanguageBuffer.Insert(0, startText + pasting + endText);
            }
        }
Exemple #7
0
        public Task <ExecutionResult> Execute(IInteractiveWindow window, string arguments)
        {
            var finder = new FileFinder(arguments);

            var eval = window.GetPythonEvaluator();

            if (eval != null)
            {
                finder.Search(eval.Configuration.WorkingDirectory);
                foreach (var p in eval.Configuration.SearchPaths)
                {
                    finder.Search(p);
                }
            }

            finder.ThrowIfNotFound();
            string commandPrefix = "$";
            string lineBreak     = window.TextView.Options.GetNewLineCharacter();

            IEnumerable <string> lines = File.ReadLines(finder.Filename);
            IEnumerable <string> submissions;

            if (eval != null)
            {
                submissions = ReplEditFilter.JoinToCompleteStatements(lines, eval.LanguageVersion).Where(CommentPrefixPredicate);
            }
            else
            {
                // v1 behavior, will probably never be hit, but if someone was developing their own IReplEvaluator
                // and using this class it would be hit.
                var submissionList    = new List <string>();
                var currentSubmission = new List <string>();

                foreach (var line in lines)
                {
                    if (line.StartsWith(_commentPrefix))
                    {
                        continue;
                    }

                    if (line.StartsWith(commandPrefix))
                    {
                        AddSubmission(submissionList, currentSubmission, lineBreak);

                        submissionList.Add(line);
                        currentSubmission.Clear();
                    }
                    else
                    {
                        currentSubmission.Add(line);
                    }
                }

                AddSubmission(submissionList, currentSubmission, lineBreak);

                submissions = submissionList;
            }

            window.SubmitAsync(submissions);
            return(ExecutionResult.Succeeded);
        }
Exemple #8
0
        private async Task ResetInteractiveAsync(
            IInteractiveWindow interactiveWindow,
            ImmutableArray <string> referencePaths,
            ImmutableArray <string> referenceSearchPaths,
            ImmutableArray <string> sourceSearchPaths,
            ImmutableArray <string> projectNamespaces,
            string projectDirectory,
            InteractiveHostPlatform?platform,
            IWaitContext waitContext
            )
        {
            // First, open the repl window.
            var evaluator = (IResettableInteractiveEvaluator)interactiveWindow.Evaluator;

            // If the user hits the cancel button on the wait indicator, then we want to stop the
            // build.
            using (
                waitContext.CancellationToken.Register(
                    () => CancelBuildProject(),
                    useSynchronizationContext: true
                    )
                )
            {
                // First, start a build.
                // If the build fails do not reset the REPL.
                var builtSuccessfully = await BuildProjectAsync().ConfigureAwait(true);

                if (!builtSuccessfully)
                {
                    return;
                }
            }

            // Then reset the REPL
            waitContext.Message    = EditorFeaturesWpfResources.Resetting_Interactive;
            evaluator.ResetOptions = new InteractiveEvaluatorResetOptions(platform);
            await interactiveWindow.Operations.ResetAsync(initialize : true).ConfigureAwait(true);

            // TODO: load context from an rsp file.

            // Now send the reference paths we've collected to the repl.
            await evaluator
            .SetPathsAsync(referenceSearchPaths, sourceSearchPaths, projectDirectory)
            .ConfigureAwait(true);

            var editorOptions = _editorOptionsFactoryService.GetOptions(
                interactiveWindow.CurrentLanguageBuffer
                );
            var importReferencesCommand = referencePaths.Select(_createReference);
            await interactiveWindow.SubmitAsync(importReferencesCommand).ConfigureAwait(true);

            // Project's default namespace might be different from namespace used within project.
            // Filter out namespace imports that do not exist in interactive compilation.
            var namespacesToImport = await GetNamespacesToImportAsync(
                projectNamespaces,
                interactiveWindow
                )
                                     .ConfigureAwait(true);

            var importNamespacesCommand = namespacesToImport
                                          .Select(_createImport)
                                          .Join(editorOptions.GetNewLineCharacter());

            if (!string.IsNullOrWhiteSpace(importNamespacesCommand))
            {
                await interactiveWindow
                .SubmitAsync(new[] { importNamespacesCommand })
                .ConfigureAwait(true);
            }
        }
Exemple #9
0
 public void SubmitText(string text)
 {
     _interactiveWindow.SubmitAsync(new[] { text }).Wait();
 }