示例#1
0
    public override void HandleTextEntered(CodeEditor control, string insertText)
    {
      switch (insertText)
      {
        case "\\":
          ShowCompletions(control);
          break;
        case "{":
        case "(":
        case "[":
          if (_currentInsight != null)
            _currentInsight.Hide();

          var overload = new OverloadInsightWindow(control.Editor.TextArea);
          if (insertText == "{")
            overload.Provider = _quantifiers;
          else if (insertText == "(")
            overload.Provider = _groups;
          else
            overload.Provider = _charClass;
          overload.Show();
          _currentInsight = overload;
          break;
        case "}":
        case ")":
        case "]":
          if (_currentInsight != null)
            _currentInsight.Hide();

          _currentInsight = null;
          break;
      }
    }
示例#2
0
        private async Task ShowCompletion(TriggerMode triggerMode)
        {
            if (CompletionProvider == null)
            {
                return;
            }

            int offset;
            GetCompletionDocument(out offset);
            var completionChar = triggerMode == TriggerMode.Text ? Document.GetCharAt(offset - 1) : (char?)null;
            var results = await CompletionProvider.GetCompletionData(offset, completionChar,
                        triggerMode == TriggerMode.SignatureHelp).ConfigureAwait(true);
            if (results.OverloadProvider != null)
            {
                results.OverloadProvider.Refresh();

                if (_insightWindow != null && _insightWindow.IsVisible)
                {
                    _insightWindow.Provider = results.OverloadProvider;
                }
                else
                {
                    _insightWindow = new OverloadInsightWindow(TextArea)
                    {
                        Provider = results.OverloadProvider,
                        Background = CompletionBackground,
                        Style = TryFindResource(typeof(InsightWindow)) as Style
                    };
                    _insightWindow.Show();
                    _insightWindow.Closed += (o, args) => _insightWindow = null;
                }
                return;
            }

            if (_completionWindow == null && results.CompletionData?.Any() == true)
            {
                _insightWindow?.Close();

                // Open code completion after the user has pressed dot:
                _completionWindow = new CompletionWindow(TextArea)
                {
                    MinWidth = 200,
                    Background = CompletionBackground,
                    CloseWhenCaretAtBeginning = triggerMode == TriggerMode.Completion
                };
                if (completionChar != null && char.IsLetterOrDigit(completionChar.Value))
                {
                    _completionWindow.StartOffset -= 1;
                }

                var data = _completionWindow.CompletionList.CompletionData;
                ICompletionDataEx selected = null;
                foreach (var completion in results.CompletionData) //.OrderBy(item => item.SortText))
                {
                    if (completion.IsSelected)
                    {
                        selected = completion;
                    }
                    data.Add(completion);
                }
                if (selected != null)
                {
                    _completionWindow.CompletionList.SelectedItem = selected;
                }
                _completionWindow.Show();
                _completionWindow.Closed += (o, args) => { _completionWindow = null; };
            }
        }
示例#3
0
        void textEditor_TextArea_TextEntered(object sender, TextCompositionEventArgs e)
        {
            completionWindow = new CompletionWindow(editor.TextArea);

            data = completionWindow.CompletionList.CompletionData;
            data.Clear();

            if (e.Text == "." && e.Text == ";")
            {
                return;
            }
            else if (e.Text == "(")
            {
                insightWindow = new OverloadInsightWindow(editor.TextArea);
                insightWindow.Provider = new OverloadProvider();

                insightWindow.Show();
                insightWindow.Closed += (o, args) => insightWindow = null;
            }

            else
            {
                foreach (var func in Functions)
                {
                    data.Add(new MyCompletionData(func.Name, Properties.Resources.Method_636));
                }
                data.AddRange("function|delete|break|continue");

                foreach (var obj in objects)
                {
                    if(obj is Delegate)
                    {
                        data.Add(new MyCompletionData(obj.Key, Properties.Resources.Method_636));
                    }
                    else
                    {
                        data.Add(new MyCompletionData(obj.Key, Properties.Resources.Object_554));
                    }
                }
            }

            if (data.Any())
            {
                completionWindow.Show();
            }

            completionWindow.Closed += delegate
            {
                completionWindow = null;
            };
        }
示例#4
0
 void insightWindow_Closed(object sender, EventArgs e)
 {
     insightWindow = null;
 }
示例#5
0
        public void CloseCompletionPopups()
        {
            if (completionWindow != null)
            {
                completionWindow.Close();
                completionWindow = null;
            }

            if (insightWindow != null)
            {
                insightWindow.Close();
                insightWindow = null;
            }
        }
示例#6
0
        /// <summary>
        /// Shows the popup that displays the currently accessed function and its parameters
        /// </summary>
        /// <param name="EnteredText"></param>
        void ShowInsightWindow(string EnteredText)
        {
            if (!DSettings.Instance.UseMethodInsight ||
                (EnteredText == "," && insightWindow != null && insightWindow.IsVisible))
                return;

            try
            {
                var data = D_IDE.D.CodeCompletion.DMethodOverloadProvider.Create(this);

                if (data == null)
                    return;

                insightWindow = new OverloadInsightWindow(Editor.TextArea);
                insightWindow.Provider = data;
                insightWindow.Closed += new EventHandler(insightWindow_Closed);

                var tt = new ToolTip();
                (insightWindow as Control).Background = tt.Background;

                insightWindow.Show();

                // Reposition the popup window to stick directly under the identifier expression
                if (data.ParameterData.MethodIdentifier is ISyntaxRegion)
                {
                    var loc = ((ISyntaxRegion)data.ParameterData.MethodIdentifier).Location;
                    var visPos = Editor.TextArea.TextView.GetVisualPosition(new TextViewPosition(loc.Line, loc.Column), ICSharpCode.AvalonEdit.Rendering.VisualYPosition.LineBottom);

                    visPos = Editor.TextArea.TextView.PointToScreen(visPos);

                    //insightWindow.Top = visPos.Y;
                    insightWindow.Left = visPos.X;
                }
            }
            catch (Exception ex) { ErrorLogger.Log(ex); }
        }
        private void ShowCompletion(string enteredText, bool controlSpace)
        {
            if (!controlSpace)
                Debug.WriteLine("Code Completion: TextEntered: " + enteredText);
            else
                Debug.WriteLine("Code Completion: Ctrl+Space");

            //only process csharp files
            if (String.IsNullOrEmpty(textEditor.Document.FileName))
                return;
            var fileExtension = Path.GetExtension(textEditor.Document.FileName);
            fileExtension = fileExtension != null ? fileExtension.ToLower() : null;
            //check file extension to be a c# file (.cs, .csx, etc.)
            if (fileExtension == null || (!fileExtension.StartsWith(".cs")))
                return;

            if (completionWindow == null)
            {
                CodeCompletionResult results = null;
                try
                {
                    results = CSharpCompletion.GetCompletions(textEditor.Document, textEditor.CaretOffset, controlSpace);
                }
                catch (Exception exception)
                {
                    Debug.WriteLine("Error in getting completion: " + exception);
                }
                if (results == null)
                    return;

                if (insightWindow == null && results.OverloadProvider != null)
                {
                    insightWindow = new OverloadInsightWindow(textEditor.TextArea);
                    insightWindow.Provider = results.OverloadProvider;
                    insightWindow.Show();
                    insightWindow.Closed += (o, args) => insightWindow = null;
                    return;
                }

                if (completionWindow == null && results != null && results.CompletionData.Any())
                {
                    // Open code completion after the user has pressed dot:
                    completionWindow = new CompletionWindow(textEditor.TextArea);
                    completionWindow.CloseWhenCaretAtBeginning = controlSpace;
                    completionWindow.StartOffset -= results.TriggerWordLength;
                    //completionWindow.EndOffset -= results.TriggerWordLength;

                    IList<ICompletionData> data = completionWindow.CompletionList.CompletionData;
                    foreach (var completion in results.CompletionData.OrderBy(item => item.Text))
                    {
                        data.Add(completion);
                    }
                    if (results.TriggerWordLength > 0)
                    {
                        //completionWindow.CompletionList.IsFiltering = false;
                        completionWindow.CompletionList.SelectItem(results.TriggerWord);
                    }
                    completionWindow.Show();
                    completionWindow.Closed += (o, args) => completionWindow = null;
                }
            }//end if

            //update the insight window
            if (!string.IsNullOrEmpty(enteredText) && insightWindow != null)
            {
                //whenver text is entered update the provider
                var provider = insightWindow.Provider as CSharpOverloadProvider;
                if (provider != null)
                {
                    //since the text has not been added yet we need to tread it as if the char has already been inserted
                    provider.Update(textEditor.Document, textEditor.CaretOffset);
                    //if the windows is requested to be closed we do it here
                    if (provider.RequestClose)
                    {
                        insightWindow.Close();
                        insightWindow = null;
                    }
                }
            }
        }
示例#8
0
        private async Task ShowCompletion(bool controlSpace)
        {
            if (CompletionProvider == null)
            {
                return;
            }

            if (_completionWindow == null)
            {
                int offset;
                GetCompletionDocument(out offset);
                var completionChar = controlSpace ? (char?)null : Document.GetCharAt(offset - 1);
                var results = await CompletionProvider.GetCompletionData(offset + PreText.Length, completionChar).ConfigureAwait(true);
                if (_insightWindow == null && results.OverloadProvider != null)
                {
                    _insightWindow = new OverloadInsightWindow(TextArea)
                    {
                        Provider = results.OverloadProvider,
                        Background = CompletionBackground,
                    };
                    _insightWindow.Show();
                    _insightWindow.Closed += (o, args) => _insightWindow = null;
                    return;
                }

                if (_completionWindow == null && results.CompletionData.Any())
                {
                    // Open code completion after the user has pressed dot:
                    _completionWindow = new CompletionWindow(TextArea)
                    {
                        Background = CompletionBackground,
                        CloseWhenCaretAtBeginning = controlSpace
                    };
                    if (completionChar != null && char.IsLetterOrDigit(completionChar.Value))
                    {
                        _completionWindow.StartOffset -= 1;
                    }

                    var data = _completionWindow.CompletionList.CompletionData;
                    ICompletionDataEx selected = null;
                    foreach (var completion in results.CompletionData) //.OrderBy(item => item.SortText))
                    {
                        if (completion.IsSelected)
                        {
                            selected = completion;
                        }
                        data.Add(completion);
                    }
                    if (selected != null)
                    {
                        _completionWindow.CompletionList.SelectedItem = selected;
                    }
                    _completionWindow.Show();
                    _completionWindow.Closed += (o, args) =>
                    {
                        _completionWindow = null;
                    };
                }
            }

            //if (!string.IsNullOrEmpty(enteredText) && _insightWindow != null)
            //{
            //    //whenver text is entered update the provider
            //    var provider = _insightWindow.Provider as CSharpOverloadProvider;
            //    if (provider != null)
            //    {
            //        //since the text has not been added yet we need to tread it as if the char has already been inserted
            //        var offset = 0;
            //        var doc = GetCompletionDocument(out offset);
            //        provider.Update(doc, offset);
            //        //if the windows is requested to be closed we do it here
            //        if (provider.RequestClose)
            //        {
            //            _insightWindow.Close();
            //            _insightWindow = null;
            //        }
            //    }
            //}
        }
示例#9
0
        private void ShowOverloadInsightWindow(FunctionCompletionData function)
        {
            // Close all existing IntelliSense windows.
            _overloadInsightWindow?.Close();
            _completionWindow?.Close();

            // Abort if we have no info to show.
            if (function == null || function.Signatures == null || function.Signatures.Length == 0)
                return;

            // Create new OverloadInsightWindow with data.
            _overloadInsightWindow = new OverloadInsightWindow(_textEditor.TextArea);
            OverloadProvider provider = new OverloadProvider();
            for (int i = 0; i < function.Signatures.Length; i++)
            {
                provider.Overloads.Add(new OverloadDescription(
                  string.Format(CultureInfo.InvariantCulture, "{0}/{1}", i + 1, function.Signatures.Length),
                  function.Signatures[i],
                  function.Description));
            }
            _overloadInsightWindow.Provider = provider;

            // Auto-delete instance when window is closed.
            _overloadInsightWindow.Closed += delegate { _overloadInsightWindow = null; };

            // Show window.
            _overloadInsightWindow.Show();
        }
        public void EditorKeyUp(ICSharpCode.AvalonEdit.TextEditor editor, DepthScanner scanner, System.Windows.Input.KeyEventArgs e)
        {
            Globals g = GetGlobals();
            if (g == null)
                return;
            // These keys halt and terminate intellisense
            switch (e.Key)
            {
                case Key.Home:
                case Key.End:
                case Key.Left:
                case Key.Right:
                case Key.Escape:
                case Key.LWin:
                case Key.RWin:
                case Key.Space:
                    if (currentComp != null)
                        currentComp.Close();
                    return;
            }
            // These keys halt further checks
            switch (e.Key)
            {
                case Key.Up:
                case Key.Down:
                case Key.PageDown:
                case Key.PageUp:
                case Key.LeftShift:
                case Key.RightShift:
                case Key.LeftAlt:
                case Key.RightAlt:
                case Key.LeftCtrl:
                case Key.RightCtrl:
                case Key.Scroll:
                case Key.Capital:
                case Key.CrSel:
                case Key.Clear:
                case Key.Insert:
                case Key.PrintScreen:
                case Key.Print:
                    return;
            }

            char KEY = KeyHelpers.GetCharFromKey(e.Key);
            if (KEY == ')' || KEY == ';')
            {
                if (currentComp != null)
                    currentComp.Close();
                return;
            }
            int curOfs = editor.TextArea.Caret.Offset;
            int line = editor.TextArea.Caret.Line;

            // Do not attempt intellisense inside of comments
            string txt = editor.Document.GetText(editor.Document.Lines[editor.TextArea.Caret.Line - 1]);
            if (txt.Trim().StartsWith("//"))
                return;

            // Check for anything to display in response to a potential namespace, scope, or dot
            if (e.Key == Key.OemPeriod || KEY == ':')
            {
                //IntellisenseHelper.ResemblesDotPath(editor.Document, curOfs-1, line-1)) {
                int ofs = TextUtilities.GetNextCaretPosition(editor.Document, curOfs, LogicalDirection.Backward, CaretPositioningMode.WordStart);
                ofs = TextUtilities.GetNextCaretPosition(editor.Document, ofs, LogicalDirection.Backward, CaretPositioningMode.WordStart);
                string word = "";
                for (; ofs < curOfs; ++ofs)
                {
                    if (editor.Document.Text[ofs] != '.')
                        word += editor.Document.Text[ofs];
                }

                NameResolver reso = new NameResolver(GetGlobals(), scanner);
                BaseTypeInfo info = null;
                string[] words = IntellisenseHelper.DotPath(editor.Document, curOfs - 1, line - 1);
                if (words.Length > 0)
                {
                    for (int i = 0; i < words.Length; ++i)
                    {
                        if (info == null)
                        {
                            info = reso.GetClassType(editor.Document, editor.TextArea.Caret.Line, words[i]);
                            if (info == null && GetGlobals().ContainsProperty(words[i]))
                                info = GetGlobals().GetProperty(words[i], true);
                        }
                        else if (info != null)
                        {
                            info = info.ResolvePropertyPath(GetGlobals(), words[i]);
                        }
                    }
                }

                bool functionsOnly = false;
                //attempt to resolve it locally
                if (info == null)
                    info = reso.GetClassType(editor.Document, editor.TextArea.Caret.Line, word);
                //attempt to resolve it from globals
                if (info == null && GetGlobals() != null && GetGlobals().ContainsProperty(word))
                    info = GetGlobals().GetProperty(word, true);
                if (info == null && word.Contains("::"))
                {
                    if (GetGlobals() == null)
                        return;
                    if (word.Length > 2)
                    {
                        string ns = word.Replace("::", "");
                        if (GetGlobals().ContainsTypeInfo(ns))
                        {
                            EnumInfo ti = GetGlobals().GetTypeInfo(word.Replace("::", "")) as EnumInfo;
                            if (ti != null)
                            {
                                currentComp = new CompletionWindow(editor.TextArea);
                                IList<ICompletionData> data = currentComp.CompletionList.CompletionData;
                                foreach (string str in ti.Values)
                                    data.Add(new BaseCompletionData(null, str));
                                currentComp.Show();
                                currentComp.Closed += comp_Closed;
                                return;
                            }
                            else
                            {
                                TypeInfo ty = GetGlobals().GetTypeInfo(word.Replace("::", ""));
                                if (ty != null)
                                {
                                    info = ty;
                                    functionsOnly = true;
                                }
                            }
                        }
                        else
                        { //list global functions because we've received "::" only
                            Globals globs = GetGlobals();
                            bool asNS = false;
                            if (globs.ContainsNamespace(ns))
                            {
                                asNS = true;
                                globs = globs.GetNamespace(ns);
                            }
                            currentComp = new CompletionWindow(editor.TextArea);
                            IList<ICompletionData> data = currentComp.CompletionList.CompletionData;
                            foreach (string str in globs.GetPropertyNames())
                            {
                                TypeInfo ti = globs.GetProperty(str, !asNS) as TypeInfo;
                                if (ti != null)
                                    data.Add(new PropertyCompletionData(ti, str));
                            }
                            foreach (FunctionInfo fi in globs.GetFunctions(null, false))
                                data.Add(new FunctionCompletionData(fi));
                            if (asNS) //Include classes
                            {
                                foreach (TypeInfo ti in globs.TypeInfo)
                                    data.Add(new ClassCompletionData(ti));
                            }
                            currentComp.Show();
                            currentComp.Closed += comp_Closed;
                            return;
                        }
                    }
                }

                //build the list
                if (info != null && info is TypeInfo)
                {
                    TypeInfo ti = info as TypeInfo;
                    currentComp = new CompletionWindow(editor.TextArea);
                    IList<ICompletionData> data = currentComp.CompletionList.CompletionData;
                    if (!functionsOnly)
                    {
                        foreach (string str in ti.Properties.Keys)
                        {
                            data.Add(new PropertyCompletionData(ti.Properties[str], str,
                                ti.ReadonlyProperties.Contains(str) ? PropertyAccess.Readonly :
                                (ti.ProtectedProperties.Contains(str) ? PropertyAccess.Protected : PropertyAccess.Public)));
                        }
                        foreach (TypeInfo t in ti.BaseTypes)
                        {
                            foreach (string str in t.Properties.Keys)
                            {
                                if (!t.PrivateProperties.Contains(str))
                                {
                                    data.Add(new PropertyCompletionData(t.Properties[str], str,
                                        t.ReadonlyProperties.Contains(str) ? PropertyAccess.Readonly :
                                        (t.ProtectedProperties.Contains(str) ? PropertyAccess.Protected : PropertyAccess.Public)));
                                }
                            }
                        }
                    }
                    foreach (FunctionInfo fi in ti.Functions)
                        data.Add(new FunctionCompletionData(fi));
                    foreach (TypeInfo t in ti.BaseTypes)
                    {
                        foreach (FunctionInfo fi in t.Functions)
                        {
                            if (!fi.IsPrivate)
                                data.Add(new FunctionCompletionData(fi));
                        }
                    }
                    currentComp.Show();
                    currentComp.Closed += comp_Closed;
                }
            }
            else if (KEY == '(' && IntellisenseHelper.ResemblesDotPath(editor.Document, curOfs - 2, line - 1))
            {

                NameResolver reso = new NameResolver(GetGlobals(), scanner);
                BaseTypeInfo info = null;
                FunctionInfo func = null;
                string[] words = IntellisenseHelper.DotPath(editor.Document, curOfs - 2, line - 1);
                if (words.Length > 1)
                {
                    for (int i = 0; i < words.Length; ++i)
                    {
                        if (i == words.Length - 1 && info != null)
                        {
                            if (info is TypeInfo)
                                func = ((TypeInfo)info).Functions.FirstOrDefault(f => f.Name.Equals(words[i]));
                        }
                        else
                        {
                            if (info == null)
                            {
                                info = reso.GetClassType(editor.Document, editor.TextArea.Caret.Line, words[i]);
                            }
                            else if (info != null && info is TypeInfo)
                            {
                                if (((TypeInfo)info).Properties.ContainsKey(words[i]))
                                    info = ((TypeInfo)info).Properties[words[i]];
                            }
                        }
                    }
                }
                if (func != null && info != null)
                {
                    List<FunctionInfo> data = new List<FunctionInfo>();
                    if (info is TypeInfo)
                    {
                        TypeInfo ti = (TypeInfo)info;
                        foreach (FunctionInfo fi in ti.Functions.Where(f => { return f.Name.Equals(func.Name); }))
                            data.Add(fi);
                        if (data.Count > 0)
                        {
                            OverloadInsightWindow window = new OverloadInsightWindow(editor.TextArea);
                            window.Provider = new OverloadProvider(ti, data.ToArray());
                            window.Show();
                            //compWindow.Closed += comp_Closed;
                        }
                    }
                }
                else if (func == null && info == null) // Found nothing
                {
                    List<FunctionInfo> data = new List<FunctionInfo>();
                    foreach (FunctionInfo fi in GetGlobals().GetFunctions(words[0], true))
                        data.Add(fi);
                    if (data.Count > 0)
                    {
                        OverloadInsightWindow window = new OverloadInsightWindow(editor.TextArea);
                        window.Provider = new OverloadProvider(null, data.ToArray());
                        window.Show();
                        //compWindow.Closed += comp_Closed;
                    }
                }
            }
            else if (Char.IsLetter(KEY))
            {
                if (currentComp != null || editor.TextArea.Caret.Line == 1)
                    return;

                int ofs = TextUtilities.GetNextCaretPosition(editor.Document, curOfs, LogicalDirection.Backward, CaretPositioningMode.WordStart);
                int nextOfs = TextUtilities.GetNextCaretPosition(editor.Document, ofs, LogicalDirection.Backward, CaretPositioningMode.WordStart);
                if (nextOfs > 0)
                {
                    if (editor.Document.Text[nextOfs] == '.')
                        return;
                }
                string word = "";
                if (ofs < 0)
                    return;
                for (; ofs < curOfs; ++ofs)
                {
                    if (editor.Document.Text[ofs] != '.')
                        word += editor.Document.Text[ofs];
                }
                if (word.Contains("."))
                {
                    if (currentComp != null)
                        currentComp.Close();
                    //editor_KeyUp(sender, e);
                    return;
                }

                NameResolver reso = new NameResolver(GetGlobals(), scanner);
                List<string> suggestions = new List<string>();
                reso.GetNameMatch(editor.Document, editor.TextArea.Caret.Line - 2, word, ref suggestions);

                CompletionWindow compWindow = new CompletionWindow(editor.TextArea);
                compWindow.StartOffset = TextUtilities.GetNextCaretPosition(editor.Document, curOfs, LogicalDirection.Backward, CaretPositioningMode.WordStart);
                IList<ICompletionData> data = compWindow.CompletionList.CompletionData;
                //attempt local name resolution first
                if (suggestions.Count > 0)
                {
                    foreach (string str in suggestions) //text suggestions are of lower priority
                        data.Add(new BaseCompletionData(null, str) { Priority = 0.5 });
                }
                //Scan globals
                if (GetGlobals() != null)
                {
                    foreach (string str in GetGlobals().GetTypeInfoNames())
                    {
                        if (str.StartsWith(word))
                            data.Add(new ClassCompletionData(GetGlobals().GetTypeInfo(str)));
                    }
                    foreach (FunctionInfo fun in GetGlobals().GetFunctions(null, true))
                    {
                        if (fun.Name.StartsWith(word))
                            data.Add(new FunctionCompletionData(fun));
                    }
                }
                if (data.Count > 0)
                {
                    currentComp = compWindow;
                    currentComp.Show();
                    currentComp.Closed += comp_Closed;
                }
                else if (currentComp != null)
                {
                    currentComp.Close();
                }
            }
        }
示例#11
0
        private void ShowAutoComplete(bool autoOpening, string text)
        {
            if (autoCompletePopup == null)
            {
                IEnumerable<CompletionData> completionData = null;
                int startPosition, wordLength = 0;
                string word = string.Empty;

                try
                {
                    string filename = "filename.csx";
                    int offset = CaretOffset + ScriptStart.Length;
                    string newSourceCode = CorrectSource(Text);
                    var document = new ICSharpCode.NRefactory.Editor.ReadOnlyDocument(new ICSharpCode.NRefactory.Editor.StringTextSource(newSourceCode), filename);
                    var syntaxTree = new ICSharpCode.NRefactory.CSharp.CSharpParser().Parse(document, document.FileName);
                    syntaxTree.Freeze();
                    var unresolvedFile = syntaxTree.ToTypeSystem();
                    var projectContent = this.projectContent.AddOrUpdateFiles(unresolvedFile);
                    var compilation = projectContent.CreateCompilation();
                    var location = document.GetLocation(offset);
                    var resolver = unresolvedFile.GetResolver(compilation, location);
                    var typeResolveContextAtCaret = unresolvedFile.GetTypeResolveContext(compilation, location);
                    var completionContextProvider = new ICSharpCode.NRefactory.CSharp.Completion.DefaultCompletionContextProvider(document, unresolvedFile);
                    var completionDataFactory = new CompletionDataFactory();
                    var cce = new ICSharpCode.NRefactory.CSharp.Completion.CSharpCompletionEngine(document, completionContextProvider, completionDataFactory, projectContent, typeResolveContextAtCaret);
                    cce.EolMarker = Environment.NewLine;
                    cce.FormattingPolicy = ICSharpCode.NRefactory.CSharp.FormattingOptionsFactory.CreateSharpDevelop();
                    var completionChar = document.GetCharAt(offset - 1);

                    if (!autoOpening)
                    {
                        if (!cce.TryGetCompletionWord(offset, out startPosition, out wordLength))
                        {
                            startPosition = offset;
                            wordLength = 0;
                        }

                        completionData = cce.GetCompletionData(startPosition, true).Cast<CompletionData>();
                    }
                    else
                    {
                        startPosition = offset;
                        if (char.IsLetterOrDigit(completionChar) || completionChar == '_')
                        {
                            if (!(startPosition > 1 && char.IsLetterOrDigit(document.GetCharAt(startPosition - 2))))
                            {
                                completionData = cce.GetCompletionData(startPosition, false).Cast<CompletionData>();
                                startPosition--;
                                wordLength = 1;
                            }
                        }
                        else
                        {
                            completionData = cce.GetCompletionData(startPosition, false).Cast<CompletionData>();
                            wordLength = 0;
                        }
                    }

                    if (wordLength > 0)
                        word = document.GetText(offset - wordLength, wordLength);

                    if (functionCallPopup == null)
                    {
                        var parameterCompletionDataFactory = new ParameterCompletionDataFactory();
                        var pce = new ICSharpCode.NRefactory.CSharp.Completion.CSharpParameterCompletionEngine(
                            document,
                            completionContextProvider,
                            parameterCompletionDataFactory,
                            projectContent,
                            typeResolveContextAtCaret
                        );
                        var parameterDataProvider = pce.GetParameterDataProvider(offset, completionChar);

                        if (functionCallPopup == null && parameterDataProvider != null)
                        {
                            var ppd = parameterDataProvider as ParameterDataProvider;

                            if (ppd.Methods.Length > 0)
                            {
                                functionCallPopup = new OverloadInsightWindow(TextArea);
                                functionCallPopup.Provider = ppd;
                                functionCallPopup.Show();
                                functionCallPopup.Closed += (o, args) => functionCallPopup = null;
                            }

                            return;
                        }
                    }
                }
                catch
                {
                }

                if (completionData != null && completionData.Any())
                {
                    autoCompletePopup = new CompletionWindow(TextArea);
                    autoCompletePopup.CloseWhenCaretAtBeginning = true;
                    autoCompletePopup.StartOffset -= wordLength;
                    var data = autoCompletePopup.CompletionList.CompletionData;

                    if (completionData != null)
                    {
                        foreach (var cd in completionData.GroupBy(c => c.Content).Select(g => g.OrderBy(c => c.CompletionText).First()).OrderBy(c => c.Content))
                        {
                            data.Add(cd);
                        }

                        if (wordLength > 0)
                        {
                            autoCompletePopup.CompletionList.SelectItem(word);
                        }
                    }
                    autoCompletePopup.Show();
                    autoCompletePopup.Closed += (o, args) => autoCompletePopup = null;
                }
            }

            if (!string.IsNullOrEmpty(text) && functionCallPopup != null)
            {
                var provider = functionCallPopup.Provider as ParameterDataProvider;
                if (provider != null)
                {
                    string filename = "filename.csx";
                    int offset = CaretOffset + ScriptStart.Length;
                    string newSourceCode = CorrectSource(Text);
                    var document = new ICSharpCode.NRefactory.Editor.ReadOnlyDocument(new ICSharpCode.NRefactory.Editor.StringTextSource(newSourceCode), filename);
                    var syntaxTree = new ICSharpCode.NRefactory.CSharp.CSharpParser().Parse(document, document.FileName);
                    syntaxTree.Freeze();
                    var unresolvedFile = syntaxTree.ToTypeSystem();
                    var projectContent = this.projectContent.AddOrUpdateFiles(unresolvedFile);
                    var compilation = projectContent.CreateCompilation();
                    var location = document.GetLocation(offset);
                    var typeResolveContextAtCaret = unresolvedFile.GetTypeResolveContext(compilation, location);
                    var completionContextProvider = new ICSharpCode.NRefactory.CSharp.Completion.DefaultCompletionContextProvider(document, unresolvedFile);
                    var parameterCompletionDataFactory = new ParameterCompletionDataFactory();
                    var completionChar = document.GetCharAt(offset - 1);
                    var pce = new ICSharpCode.NRefactory.CSharp.Completion.CSharpParameterCompletionEngine(
                        document,
                        completionContextProvider,
                        parameterCompletionDataFactory,
                        projectContent,
                        typeResolveContextAtCaret
                    );
                    int parameterIndex = pce.GetCurrentParameterIndex(provider.StartOffset, offset);
                    if (parameterIndex < 0)
                    {
                        functionCallPopup.Close();
                        functionCallPopup = null;
                    }
                    else
                    {
                        provider.CurrentParameter = parameterIndex - 1;
                    }
                }
            }
        }
    public IPromise<CompletionContext> Completions(string prefix, ITextSource all, int caret, string termCharacter
      , bool tableNameColumnPrefix = false)
    {
      try
      {
        _tableNameColumnPrefix = tableNameColumnPrefix;
        var lastIndex = string.IsNullOrEmpty(termCharacter) ? -1 : all.IndexOf(termCharacter, caret, all.TextLength - caret, StringComparison.Ordinal);
        var sql = prefix + (lastIndex < 0 ? all.GetText(caret, all.TextLength - caret) : all.GetText(caret, lastIndex - caret));
        if (sql.StartsWith("(") && sql.EndsWith(")"))
          sql = sql.Substring(1, sql.Length - 2);
        var parseTree = new SqlTokenizer(sql).Parse();
        if (!parseTree.Any())
          return Promises.Resolved(new CompletionContext());

        var currNode = parseTree.NodeByOffset(prefix.Length);
        var literal = currNode as SqlLiteral;

        if (literal != null)
        {
          var parGroup = literal.Parent as SqlGroup;
          if (_overloadWin != null && (parGroup == null || !parGroup.First().TextEquals(_overloadName)))
            _overloadWin.Close();

          if (SqlTokenizer.KeywordPrecedesTable(literal))
          {
            var context = new SqlContext(parGroup);
            return ContextFromData(Tables(null).Concat(Schemas())
              .Concat(context.Definitions.Select(d => new SqlGeneralCompletionData() {
                Text = d,
                Description = "Locally defined table",
                Image = WpfImages.Class16
              }))
              .OrderBy(i => i.Text));
          }
          else if (literal.Text == "(")
          {

            var prev = literal.PreviousLiteral();

            if (prev != null)
            {
              if (CurrentTextArea != null)
              {
                var overloads = from f in _coreFunctions
                                where string.Equals(f.Name, prev.Text, StringComparison.OrdinalIgnoreCase)
                                select new Overload(f.Usage, f.Description);
                if (overloads.Any())
                {
                  _overloadWin = new OverloadInsightWindow(CurrentTextArea);
                  _overloadWin.StartOffset = caret;
                  _overloadWin.EndOffset = caret + 1;
                  _overloadWin.Provider = new OverloadList().AddRange(overloads);
                  _overloadWin.Show();
                  _overloadWin.Closed += (s, e) => {
                    _overloadWin = null;
                    _overloadName = null;
                  };
                  _overloadName = prev.Text;
                }
              }

              switch (prev.Text.ToUpperInvariant())
              {
                case "DATEADD":
                case "DATEDIFF":
                case "DATEDIFF_BIG":
                case "DATEFROMPARTS":
                case "DATENAME":
                case "DATEPART":
                  return ContextFromData(_datePartNames.Select(n => new SqlGeneralCompletionData()
                    {
                      Text = n[0] + (n[1] == n[0] ? "" : " (" + n[1] + ")"),
                      Description = n[1],
                      Image = WpfImages.EnumValue16,
                      Action = () => n[0]
                    })
                    .OrderBy(i => i.Text));
              }
            }
          }
          else if (literal.Text == ".")
          {
            var name = literal.Parent as SqlName;
            if (name != null)
            {
              if (name.IsTable)
              {
                var idx = name.IndexOf(literal);
                var schema = name[idx - 1].Text;
                if (_provider.GetSchemaNames().Contains(schema, StringComparer.OrdinalIgnoreCase))
                {
                  return ContextFromData(Tables(schema).Concat(Functions(true, schema))
                    .OrderBy(i => i.Text));
                }
              }
              else
              {
                var group = name.Parent as SqlGroup;
                if (group != null)
                {
                  var idx = name.IndexOf(literal);
                  var context = new SqlContext(group);
                  SqlTableInfo info;
                  if (idx > 0 && name[idx - 1] is SqlLiteral
                    && context.TryByName(((SqlLiteral)name[idx - 1]).Text.ToLowerInvariant(), out info))
                  {
                    return Columns(info, false).ToPromise().Convert(c => new CompletionContext()
                    {
                      Items = c
                    });
                  }
                }
              }
            }
          }
          else if (literal.Type == SqlType.Keyword
            || literal.Type == SqlType.Operator)
          {
            switch (literal.Text.ToLowerInvariant())
            {
              case "union":
                return ContextFromData(MatchCase(literal.Text, "all", "select")
                  .GetCompletions<SqlGeneralCompletionData>());
              case "group":
              case "order":
              case "partition":
                return ContextFromData(MatchCase(literal.Text, "by")
                  .GetCompletions<SqlGeneralCompletionData>());
              case "insert":
                return ContextFromData(MatchCase(literal.Text, "into")
                  .GetCompletions<SqlGeneralCompletionData>());
              case "delete":
                return ContextFromData(MatchCase(literal.Text, "from")
                  .GetCompletions<SqlGeneralCompletionData>());
            }

            var group = literal.Parent as SqlGroup;
            if (group != null)
            {
              // List of sql specific constructs for the context
              var sqlOthers = new List<string>();

              switch (literal.Text.ToLowerInvariant())
              {
                case "select":
                  sqlOthers.Add("*");
                  sqlOthers.Add("distinct");
                  sqlOthers.Add("top");
                  break;
              }

              // Table aliases and functions
              var context = new SqlContext(group);
              var others = context.Tables
                .Where(t => !string.IsNullOrEmpty(t.Alias))
                .Select(t => t.Alias)
                .Distinct()
                .Select(t => new SqlGeneralCompletionData()
                {
                  Text = t,
                  Image = WpfImages.Class16
                })
                .Concat(Functions(false, null));

              // Table columns
              return Promises.All(context.Tables.Select(t => Columns(t).ToPromise()).ToArray())
                .Convert(l => new CompletionContext()
                {
                  Items = l.OfType<IEnumerable<ICompletionData>>()
                    .SelectMany(p => p)
                    .Concat(MatchCase(literal.Text, sqlOthers).Select(o => new SqlGeneralCompletionData()
                    {
                      Text = o,
                      Image = WpfImages.Operator16
                    }))
                    .Concat(others)
                    .Concat(Schemas())
                    .OrderBy(i => i.Text, StringComparer.OrdinalIgnoreCase)
                });
            }
          }
        }

        return Promises.Resolved(new CompletionContext());
      }
      catch (Exception ex)
      {
        return Promises.Rejected<CompletionContext>(ex);
      }
    }