public override void GetAttributeCompletions (CompletionDataList list, IAttributedXObject attributedOb, Dictionary<string, string> existingAtts)
		{
			var required = new NodeCompletionCategory ("Required", 0);
			var optional = new NodeCompletionCategory ("Optional", 1);

			foreach (NodeTypeAttribute att in info.Attributes) {
				if (!existingAtts.ContainsKey (att.Name)) {
					var data = new NodeTypeAttributeCompletionData (att) {
						CompletionCategory = att.Required ? required : optional
					};
					list.Add (data);
				}
			}

			var ordering = new NodeCompletionCategory ("Ordering", 2);
			if (!existingAtts.ContainsKey ("id")) {
				list.Add (new CompletionData ("id", null, "ID for the extension, unique in this extension point.") { CompletionCategory = ordering });
			}
			if (!existingAtts.ContainsKey ("insertbefore")) {
				list.Add (new CompletionData ("insertbefore", null, "ID of an existing extension before which to insert this.") { CompletionCategory = ordering });
			}
			if (!existingAtts.ContainsKey ("insertafter")) {
				list.Add (new CompletionData ("insertafter", null, "ID of an existing extension after which to insert this.") { CompletionCategory = ordering });
			}
		}
示例#2
0
        Task <ICompletionDataList> GetSdkCompletions(int triggerLength, CancellationToken token)
        {
            var list = new CompletionDataList {
                TriggerWordLength = triggerLength
            };
            var doc = GetDocument();

            if (doc == null)
            {
                return(null);
            }

            var sdks = new HashSet <string> ();

            foreach (var sdk in doc.RuntimeInformation.GetRegisteredSdks())
            {
                if (sdks.Add(sdk.Name))
                {
                    list.Add(Path.GetFileName(sdk.Name));
                }
            }

            //TODO: how can we find SDKs in the non-default locations?
            return(Task.Run <ICompletionDataList> (() => {
                foreach (var d in Directory.GetDirectories(doc.RuntimeInformation.GetSdksPath()))
                {
                    string name = Path.GetFileName(d);
                    if (sdks.Add(name))
                    {
                        list.Add(name);
                    }
                }
                return list;
            }, token));
        }
示例#3
0
        void AddControlMembers(CompletionDataList list, ProjectDom database, IType controlClass,
                               Dictionary <string, string> existingAtts)
        {
            //add atts only if they're not already in the tag
            foreach (var prop in GetUniqueMembers <IProperty> (GetAllProperties(database, controlClass)))
            {
                if (prop.IsPublic && (existingAtts == null || !existingAtts.ContainsKey(prop.Name)))
                {
                    if (GetPersistenceMode(prop) == System.Web.UI.PersistenceMode.Attribute)
                    {
                        list.Add(prop.Name, prop.StockIcon, prop.Documentation);
                    }
                }
            }

            //similarly add events
            foreach (var eve in GetUniqueMembers <IEvent> (GetAllEvents(database, controlClass)))
            {
                string eveName = "On" + eve.Name;
                if (eve.IsPublic && (existingAtts == null || !existingAtts.ContainsKey(eveName)))
                {
                    list.Add(eveName, eve.StockIcon, eve.Documentation);
                }
            }
        }
 public void Add(string ModuleName, IAbstractSyntaxTree Module = null, string PathOverride = null)
 {
     CompletionDataList.Add(new NamespaceCompletionData(ModuleName, Module)
     {
         ExplicitModulePath = PathOverride
     });
 }
		protected override  Task<CompletionDataList> GetElementCompletions (CancellationToken token)
		{
			var list = new CompletionDataList ();

			AddMiscBeginTags (list);

			var path = GetCurrentPath ();

			if (path.Count == 0) {
				list.Add (new XmlCompletionData ("Project", XmlCompletionData.DataType.XmlElement));
				return Task.FromResult (list);
			}

			var rr = ResolveElement (path);
			if (rr == null)
				return Task.FromResult (list);

			foreach (var c in rr.BuiltinChildren)
				list.Add (new XmlCompletionData (c, XmlCompletionData.DataType.XmlElement));

			var inferredChildren = GetInferredChildren (rr);
			if (inferredChildren != null)
				foreach (var c in inferredChildren)
					list.Add (new XmlCompletionData (c, XmlCompletionData.DataType.XmlElement));
			return Task.FromResult (list);
		}
        public override void GetAttributeCompletions(CompletionDataList list, IAttributedXObject attributedOb, Dictionary <string, string> existingAtts)
        {
            if (!existingAtts.ContainsKey("type"))
            {
                list.Add("Gettext", null, "Localizes the add-in with a Gettext catalog.");
                list.Add("StringResource", null, "Localizes the add-in with .NET string resources.");
                list.Add("StringTable", null, "Localizes the add-in with string table defined in the manifest.");
                return;
            }

            string type;

            if (!existingAtts.TryGetValue("type", out type))
            {
                return;
            }

            if (type == "Gettext")
            {
                if (!existingAtts.ContainsKey("catalog"))
                {
                    list.Add("catalog", null, "Name of the catalog which contains the strings.");
                }
                if (!existingAtts.ContainsKey("location"))
                {
                    list.Add("location", null, "Relative path to the location of the catalog. This path must be relative to the add-in location..");
                }
            }
        }
        protected override void GetElementCompletions(CompletionDataList list)
        {
            AddMiscBeginTags(list);

            var path = GetCurrentPath();

            if (path.Count == 0)
            {
                list.Add(new XmlCompletionData("Project", XmlCompletionData.DataType.XmlElement));
                return;
            }

            var rr = ResolveElement(path);

            if (rr == null)
            {
                return;
            }

            foreach (var c in rr.BuiltinChildren)
            {
                list.Add(new XmlCompletionData(c, XmlCompletionData.DataType.XmlElement));
            }

            var inferredChildren = GetInferredChildren(rr);

            if (inferredChildren != null)
            {
                foreach (var c in inferredChildren)
                {
                    list.Add(new XmlCompletionData(c, XmlCompletionData.DataType.XmlElement));
                }
            }
        }
示例#8
0
        void AddControlMembers(CompletionDataList list, IType controlClass,
                               Dictionary <string, string> existingAtts)
        {
            //add atts only if they're not already in the tag
            foreach (var prop in GetUniqueMembers <IProperty> (controlClass.GetProperties()))
            {
                if (prop.Accessibility == Accessibility.Public && (existingAtts == null || !existingAtts.ContainsKey(prop.Name)))
                {
                    if (GetPersistenceMode(prop) == System.Web.UI.PersistenceMode.Attribute)
                    {
                        list.Add(prop.Name, prop.GetStockIcon(), AmbienceService.GetSummaryMarkup(prop));
                    }
                }
            }

            //similarly add events
            foreach (var eve in GetUniqueMembers <IEvent> (controlClass.GetEvents()))
            {
                string eveName = "On" + eve.Name;
                if (eve.Accessibility == Accessibility.Public && (existingAtts == null || !existingAtts.ContainsKey(eveName)))
                {
                    list.Add(eveName, eve.GetStockIcon(), AmbienceService.GetSummaryMarkup(eve));
                }
            }
        }
		protected static void AddCloseTag (CompletionDataList completionList, NodeStack stack)
		{
			//FIXME: search forward to see if tag's closed already
			var elements = new List<XElement> ();
			foreach (XObject ob in stack) {
				var el = ob as XElement;
				if (el == null)
					continue;
				if (!el.IsNamed || el.IsClosed)
					return;
				
				if (elements.Count == 0) {
					string name = el.Name.FullName;
					completionList.Add ("/" + name + ">", Gtk.Stock.GoBack,
					                    GettextCatalog.GetString ("Closing tag for '{0}'", name));
				} else {
					foreach (XElement listEl in elements) {
						if (listEl.Name == el.Name)
							return;
					}
					completionList.Add (new XmlMultipleClosingTagCompletionData (el, elements.ToArray ()));
				}
				elements.Add (el);
			}
		}
示例#10
0
        public static void AddRazorDirectives(CompletionDataList list, RazorHostKind kind)
        {
            string icon = "md-keyword";

            list.Add("helper", icon, GettextCatalog.GetString("Defines a helper"));
            list.Add("functions", icon, GettextCatalog.GetString("Defines a region of class members"));
            list.Add("using", icon, GettextCatalog.GetString("Imports a namespace"));

            if (kind == RazorHostKind.WebCode)
            {
                return;
            }

            list.Add("inherits", icon, GettextCatalog.GetString("Defines a base class of the view"));
            list.Add("model", icon, GettextCatalog.GetString("References a strongly-typed model"));

            if (kind == RazorHostKind.WebPage)
            {
                list.Add("layout", icon, GettextCatalog.GetString("Defines a layout file to use in this view"));
                list.Add("sessionstate", icon, GettextCatalog.GetString("Defines a sessionstate mode"));
                list.Add("section", icon, GettextCatalog.GetString("Defines a section"));
            }
            else if (kind == RazorHostKind.Template)
            {
                list.Add("__class", icon, GettextCatalog.GetString("Customizes the generated class"));
                list.Add("__property", icon, GettextCatalog.GetString("Adds a property"));
            }
        }
示例#11
0
        public static void AddRazorBeginExpressions(CompletionDataList list)
        {
            string icon = "md-literal";

            list.Add("{", icon, GettextCatalog.GetString("Razor code block"));
            list.Add("*", icon, GettextCatalog.GetString("Razor comment"));
            list.Add("(", icon, GettextCatalog.GetString("Razor explicit expression"));
        }
        public ICompletionDataList GetPathCompletions(string subPath)
        {
            var paths  = new HashSet <string> ();
            var cp     = new CompletionDataList();
            var addins = GetReferencedAddins().ToList();

            foreach (var addin in addins)
            {
                foreach (ExtensionPoint ep in addin.Description.ExtensionPoints)
                {
                    if (ep.Path.StartsWith(subPath, System.StringComparison.Ordinal))
                    {
                        string spath = ep.Path.Substring(subPath.Length);
                        int    i     = spath.IndexOf('/');
                        if (i != -1)
                        {
                            spath = spath.Substring(0, i);
                        }
                        if (paths.Add(spath))
                        {
                            if (i == -1)
                            {
                                cp.Add(spath, null, ep.Name + "\n" + ep.Description);
                            }
                            else
                            {
                                cp.Add(spath);
                            }
                        }
                    }
                    if (ep.Path == subPath.TrimEnd('/'))
                    {
                        var extensions = ExtensionNodeElement.GetExtensions(project, ep).ToList();
                        foreach (ExtensionNodeType nodeType in ep.NodeSet.GetAllowedNodeTypes())
                        {
                            var allowedChildren = nodeType.GetAllowedNodeTypes();
                            if (allowedChildren.Count == 0)
                            {
                                continue;
                            }
                            foreach (var ext in extensions)
                            {
                                foreach (ExtensionNodeDescription node in ext.ExtensionNodes)
                                {
                                    if (node.GetNodeType() == nodeType && !string.IsNullOrEmpty(node.Id))
                                    {
                                        cp.Add(node.Id);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(cp);
        }
        public override async Task <ICompletionDataList> HandleCodeCompletionAsync(CodeCompletionContext completionContext, CompletionTriggerInfo triggerInfo, CancellationToken token)
        {
            if (inactive)
            {
                return(await base.HandleCodeCompletionAsync(completionContext, triggerInfo, token));
            }

            if (!IdeApp.Preferences.EnableAutoCodeCompletion)
            {
                return(null);
            }
            if (triggerInfo.CompletionTriggerReason != CompletionTriggerReason.CharTyped)
            {
                return(null);
            }
            char completionChar    = triggerInfo.TriggerCharacter.Value;
            int  triggerWordLength = 0;

            if (char.IsLetterOrDigit(completionChar) || completionChar == '_')
            {
                if (completionContext.TriggerOffset > 1 && char.IsLetterOrDigit(Editor.GetCharAt(completionContext.TriggerOffset - 2)))
                {
                    return(null);
                }
                triggerWordLength = 1;
            }
            else
            {
                return(null);
            }

            var result = new CompletionDataList();

            result.TriggerWordLength                  = triggerWordLength;
            result.AutoSelect                         = false;
            result.AutoCompleteEmptyMatch             = false;
            result.AutoCompleteUniqueMatch            = false;
            result.AutoCompleteEmptyMatchOnCurlyBrace = false;

            foreach (var ct in await CodeTemplateService.GetCodeTemplatesAsync(Editor, token))
            {
                if (string.IsNullOrEmpty(ct.Shortcut) || ct.CodeTemplateContext != CodeTemplateContext.Standard)
                {
                    continue;
                }
                result.Add(new CodeTemplateCompletionData(this, ct));
            }

            foreach (var word in await GetAllWords(Editor.CreateSnapshot(), Editor.CaretOffset))
            {
                result.Add(new CompletionData(word));
            }

            return(result);
        }
		protected override void GetElementCompletions (CompletionDataList list)
		{
			AddMiscBeginTags (list);

			var path = GetCurrentPath ();

			if (path.Count == 0) {
				list.Add (new XmlCompletionData ("Project", XmlCompletionData.DataType.XmlElement));
			} else {
				var el = GetMSBuildElement (path);
				if (el != null && el.Children != null)
					foreach (var c in el.Children)
						list.Add (new XmlCompletionData (c, XmlCompletionData.DataType.XmlElement));
			}
		}
        protected override void GetElementCompletions(CompletionDataList list)
        {
            base.GetElementCompletions(list);
            var database = GetDb();

            if (database == null)
            {
                return;
            }

            IType type = database.LookupType("System.Windows", "DependencyObject");

            if (type == null)
            {
                return;
            }

            foreach (string namespc in namespaces)
            {
                INamespace ns = database.RootNamespace;
                foreach (var sn in namespc.Split('.'))
                {
                    ns = ns.GetChildNamespace(sn);
                }
                foreach (IType t in ListControlClasses(database, ns))
                {
                    list.Add(t.Name, Gtk.Stock.GoForward, t.GetDefinition().Documentation);
                }
            }
        }
示例#16
0
        public virtual void AddCompletionData(CompletionDataList provider)
        {
            if (action == CompletionAction.AttributeValue)
            {
                currentCollection = new List <ItemData> ();
                OnAddAttributeValues(attNameForValue);
            }
            else if (action == CompletionAction.ElementStart)
            {
                currentCollection = ElementData;
            }
            else
            {
                currentCollection = AttributeData;
            }

            foreach (ItemData data in currentCollection)
            {
                CompletionData cd = new CompletionData(data.Name, "md-literal", data.Description);
                if (data.CompletionString != null)
                {
                    cd.CompletionText = data.CompletionString;
                }
                provider.Add(cd);
            }
        }
 public override void GetAttributeCompletions(CompletionDataList list, IAttributedXObject attributedOb, Dictionary <string, string> existingAtts)
 {
     if (!existingAtts.ContainsKey("path"))
     {
         list.Add("path", null, "The path of the extension");
     }
 }
 public HaxeTextEditorCompletion()
 {
     foreach (string keyword in keywords)
     {
         keywordslist.Add(keyword);
     }
 }
 public override void GetElementCompletions(CompletionDataList list, XElement element)
 {
     foreach (ExtensionNodeType n in info.GetAllowedNodeTypes())
     {
         list.Add(n.NodeName, null, n.Description);
     }
 }
        public virtual ICompletionDataList ShowCodeSurroundingsCommand(CodeCompletionContext completionContext)
        {
            CompletionDataList list = new CompletionDataList();

            list.AutoSelect              = true;
            list.AutoCompleteEmptyMatch  = true;
            list.CompletionSelectionMode = CompletionSelectionMode.OwnTextField;
            var templateWidget      = DocumentContext.GetContent <ICodeTemplateContextProvider> ();
            CodeTemplateContext ctx = CodeTemplateContext.Standard;

            if (templateWidget != null)
            {
                ctx = templateWidget.GetCodeTemplateContext();
            }
            foreach (CodeTemplate template in CodeTemplateService.GetCodeTemplatesAsync(Editor).WaitAndGetResult(CancellationToken.None))
            {
                if ((template.CodeTemplateType & CodeTemplateType.SurroundsWith) == CodeTemplateType.SurroundsWith)
                {
                    if (ctx == template.CodeTemplateContext)
                    {
                        list.Add(new CodeTemplateCompletionData(this, template));
                    }
                }
            }
            return(list);
        }
示例#21
0
        public virtual ICompletionDataList ShowCodeSurroundingsCommand(CodeCompletionContext completionContext)
        {
            CompletionDataList list = new CompletionDataList();

            list.AutoSelect              = true;
            list.AutoCompleteEmptyMatch  = true;
            list.CompletionSelectionMode = CompletionSelectionMode.OwnTextField;
            var templateWidget      = Document.GetContent <ICodeTemplateContextProvider> ();
            CodeTemplateContext ctx = CodeTemplateContext.Standard;

            if (templateWidget != null)
            {
                ctx = templateWidget.GetCodeTemplateContext();
            }
            foreach (CodeTemplate template in CodeTemplateService.GetCodeTemplatesForFile(Document.FileName))
            {
                if ((template.CodeTemplateType & CodeTemplateType.SurroundsWith) == CodeTemplateType.SurroundsWith)
                {
                    if (ctx == template.CodeTemplateContext)
                    {
                        list.Add(new CodeTemplateCompletionData(Document, template));
                    }
                }
            }
            return(list);
        }
        protected virtual ICompletionDataList ClosingTagCompletion(IEditableTextBuffer buf, TextLocation currentLocation)
        {
            //get name of current node in document that's being ended
            XElement el = tracker.Engine.Nodes.Peek() as XElement;

            if (el != null && el.Region.End >= currentLocation && !el.IsClosed && el.IsNamed)
            {
                string tag = String.Concat("</", el.Name.FullName, ">");
                if (XmlEditorOptions.AutoCompleteElements)
                {
                    //						//make sure we have a clean atomic undo so the user can undo the tag insertion
                    //						//independently of the >
                    //						bool wasInAtomicUndo = this.Editor.Document.IsInAtomicUndo;
                    //						if (wasInAtomicUndo)
                    //							this.Editor.Document.EndAtomicUndo ();

                    using (var undo = buf.OpenUndoGroup()) {
                        buf.InsertText(buf.CursorPosition, tag);
                        buf.CursorPosition -= tag.Length;
                    }

                    //						if (wasInAtomicUndo)
                    //							this.Editor.Document.BeginAtomicUndo ();

                    return(null);
                }
                else
                {
                    CompletionDataList cp = new CompletionDataList();
                    cp.Add(new XmlTagCompletionData(tag, 0, true));
                    return(cp);
                }
            }
            return(null);
        }
示例#23
0
        protected override void GetElementCompletions(CompletionDataList list)
        {
            base.GetElementCompletions(list);
            ProjectDom database = GetDb();

            if (database == null)
            {
                return;
            }

            IType type = database.GetType("System.Windows.DependencyObject");

            if (type == null)
            {
                return;
            }

            foreach (string namespc in namespaces)
            {
                foreach (IType t in ListControlClasses(database, namespc))
                {
                    list.Add(t.Name, Gtk.Stock.GoForward, t.Documentation);
                }
            }
        }
        //recreating the list is over 2x as fast as using remove operations, saves typically 10ms
        static CompletionDataList FilterCSharpTemplates(CompletionDataList list)
        {
            var newList = new CompletionDataList()
            {
                AutoCompleteEmptyMatch  = list.AutoCompleteEmptyMatch,
                AutoCompleteUniqueMatch = list.AutoCompleteUniqueMatch,
                AutoSelect              = list.AutoSelect,
                CloseOnSquareBrackets   = list.CloseOnSquareBrackets,
                CompletionSelectionMode = list.CompletionSelectionMode,
                DefaultCompletionString = list.DefaultCompletionString,
                IsSorted          = list.IsSorted,
                TriggerWordLength = list.TriggerWordLength,
                TriggerWordStart  = list.TriggerWordStart,
            };

            foreach (var l in list)
            {
                var c = l as CompletionData;
                if (c == null || (c.Icon.Name != "md-template" && c.Icon.Name != "md-template-surroundwith"))
                {
                    newList.Add(c);
                }
            }
            return(newList);
        }
示例#25
0
        public void Add(INode Node)
        {
            DCompletionData dc;

            if (overloadCheckDict.TryGetValue(Node.NameHash, out dc))
            {
                dc.AddOverload(Node);
            }
            else
            {
                CompletionDataList.Add(overloadCheckDict[Node.NameHash] = new DCompletionData(categoryCache, Node, Node.Parent == scopedBlock));
            }
        }
示例#26
0
            public override Task <ICompletionDataList> HandleCodeCompletionAsync(CodeCompletionContext completionContext, char completionChar, System.Threading.CancellationToken token)
            {
                CompletionRun = true;
                var list = new CompletionDataList();

                list.Add("foo");
                return(Task.FromResult <CodeCompletion.ICompletionDataList> (list));
            }
示例#27
0
 public static void AddEnum <T> (CompletionDataList list, T defaultValue)
 {
     foreach (string name in Enum.GetNames(typeof(T)))
     {
         list.Add(name, "md-literal");
     }
     list.DefaultCompletionString = defaultValue.ToString();
 }
示例#28
0
        CompletionDataList GetPathCompletion(string subPath)
        {
            CompletionContext ctx = GetCompletionContext(1);

            if (!(ctx is ExtensionCompletionContext))
            {
                return(null);
            }
            ModuleCompletionContext mc = (ModuleCompletionContext)ctx.GetParentContext(typeof(ModuleCompletionContext));

            Set <string>       paths = new Set <string> ();
            CompletionDataList cp    = new CompletionDataList();

            foreach (AddinDependency adep in mc.Module.Dependencies)
            {
                Addin addin = registry.GetAddin(adep.FullAddinId);
                if (addin != null && addin.Description != null)
                {
                    foreach (ExtensionPoint ep in addin.Description.ExtensionPoints)
                    {
                        if (ep.Path.StartsWith(subPath))
                        {
                            string spath = ep.Path.Substring(subPath.Length);
                            int    i     = spath.IndexOf('/');
                            if (i != -1)
                            {
                                spath = spath.Substring(0, i);
                            }
                            if (paths.Add(spath))
                            {
                                if (i == -1)                                 // Full match. Add the documentation
                                {
                                    cp.Add(spath, "md-extension-point", ep.Name + "\n" + ep.Description);
                                }
                                else
                                {
                                    cp.Add(spath, "md-literal");
                                }
                            }
                        }
                    }
                }
            }
            return(cp);
        }
        public override void GetElementCompletions(CompletionDataList list, XElement element)
        {
            var type = GetTypeAttributeValue(element);

            if (type == "StringTable")
            {
                list.Add(localeItem.Name, null, localeItem.Description);
            }
        }
		public virtual void GetElementCompletions (CompletionDataList list, XElement element)
		{
			if (children == null) {
				return;
			}

			foreach (var c in children) {
				list.Add (c.Key, null, c.Value.Description);
			}
		}
示例#31
0
 /// <summary>
 /// Adds completion data for children to a list
 /// </summary>
 /// <param name="list">
 /// The list to which completion data will be added
 /// <see cref="CompletionDataList"/>
 /// </param>
 /// <param name="items">
 /// A list of items to search
 /// <see cref="IEnumerable"/>
 /// </param>
 /// <param name="parent">
 /// The parent that will be matched
 /// </param>
 public static void AddItemsWithParent(CompletionDataList list, IEnumerable <LanguageItem> items, LanguageItem parent)
 {
     foreach (LanguageItem li in items)
     {
         if (li.Parent != null && li.Parent.Equals(parent))
         {
             list.Add(new CompletionData(li));
         }
     }
 }
示例#32
0
        public virtual ICompletionDataList ShowCodeTemplatesCommand()
        {
            CompletionDataList list = new CompletionDataList();

            list.CompletionSelectionMode = CompletionSelectionMode.OwnTextField;

            foreach (CodeTemplate template in CodeTemplateService.Templates) //GetCodeTemplates("text/moscrif"))
                list.Add(new CodeTemplateCompletionData(template,this.editor));
            return list;
        }
示例#33
0
 /// <summary>
 /// Adds completion data for children to a list
 /// </summary>
 /// <param name="list">
 /// The list to which completion data will be added
 /// <see cref="CompletionDataList"/>
 /// </param>
 /// <param name="items">
 /// A list of items to search
 /// <see cref="IEnumerable"/>
 /// </param>
 /// <param name="parentName">
 /// The name of the parent that will be matched
 /// <see cref="System.String"/>
 /// </param>
 public static void AddMembersWithParent(CompletionDataList list, IEnumerable <LanguageItem> items, string parentName)
 {
     foreach (LanguageItem li in items)
     {
         if (li.Parent != null && li.Parent.Name.EndsWith(parentName))
         {
             list.Add(new CompletionData(li));
         }
     }
 }
示例#34
0
 static void ExclusiveAdd(CompletionDataList list, Dictionary <string, string> existingAtts,
                          IEnumerable <string> values)
 {
     foreach (string s in values)
     {
         if (!existingAtts.ContainsKey(s))
         {
             list.Add(s);
         }
     }
 }
        public override void GetAttributeCompletions(CompletionDataList list, IAttributedXObject attributedOb, Dictionary <string, string> existingAtts)
        {
            var required = new NodeCompletionCategory("Required", 0);
            var optional = new NodeCompletionCategory("Optional", 1);

            foreach (NodeTypeAttribute att in info.Attributes)
            {
                if (!existingAtts.ContainsKey(att.Name))
                {
                    var data = new NodeTypeAttributeCompletionData(att)
                    {
                        CompletionCategory = att.Required ? required : optional
                    };
                    list.Add(data);
                }
            }

            var ordering = new NodeCompletionCategory("Ordering", 2);

            if (!existingAtts.ContainsKey("id"))
            {
                list.Add(new CompletionData("id", null, "ID for the extension, unique in this extension point.")
                {
                    CompletionCategory = ordering
                });
            }
            if (!existingAtts.ContainsKey("insertbefore"))
            {
                list.Add(new CompletionData("insertbefore", null, "ID of an existing extension before which to insert this.")
                {
                    CompletionCategory = ordering
                });
            }
            if (!existingAtts.ContainsKey("insertafter"))
            {
                list.Add(new CompletionData("insertafter", null, "ID of an existing extension after which to insert this.")
                {
                    CompletionCategory = ordering
                });
            }
        }
		public override void GetAttributeValueCompletions (CompletionDataList list, IAttributedXObject attributedOb, XAttribute att)
		{
			if (att.Name.FullName != "path") {
				return;
			}

			foreach (var addin in GetReferencedAddins ()) {
				foreach (ExtensionPoint ep in addin.Description.ExtensionPoints) {
					list.Add (ep.Path, null, ep.Name + "\n" + ep.Description);
				}
			}
		}
示例#37
0
		public static void AddRazorDirectives (CompletionDataList list)
		{
			string icon = "md-keyword";
			list.Add ("inherits", icon, "Defines a base class of the view");
			list.Add ("layout", icon, "Defines a layout file to use in this view");
			list.Add ("model", icon, "References a strongly-typed model");
			list.Add ("sessionstate", icon, "Defines a sessionstate mode");
			list.Add ("helper", icon, "Defines a helper");
			list.Add ("section", icon, "Defines a section");
			list.Add ("functions", icon, "Enables to define functions in this view");
		}
		public override void GetAttributeCompletions (CompletionDataList list, IAttributedXObject attributedOb, Dictionary<string, string> existingAtts)
		{
			if (!existingAtts.ContainsKey ("type")) {
				list.Add ("Gettext", null, "Localizes the add-in with a Gettext catalog.");
				list.Add ("StringResource", null, "Localizes the add-in with .NET string resources.");
				list.Add ("StringTable", null, "Localizes the add-in with string table defined in the manifest.");
				return;
			}

			string type;
			if (!existingAtts.TryGetValue ("type", out type)) {
				return;
			}

			if (type == "Gettext") {
				if (!existingAtts.ContainsKey ("catalog")) {
					list.Add ("catalog", null, "Name of the catalog which contains the strings.");
				}
				if (!existingAtts.ContainsKey ("location")) {
					list.Add ("location", null, "Relative path to the location of the catalog. This path must be relative to the add-in location..");
				}
			}
		}
		public static void AddRazorDirectives (CompletionDataList list, RazorHostKind kind)
		{
			string icon = "md-keyword";

			list.Add ("helper", icon, GettextCatalog.GetString ("Defines a helper"));
			list.Add ("functions", icon, GettextCatalog.GetString ("Defines a region of class members"));
			list.Add ("using", icon, GettextCatalog.GetString ("Imports a namespace"));

			if (kind == RazorHostKind.WebCode)
				return;

			list.Add ("inherits", icon, GettextCatalog.GetString ("Defines a base class of the view"));
			list.Add ("model", icon, GettextCatalog.GetString ("References a strongly-typed model"));

			if (kind == RazorHostKind.WebPage) {
				list.Add ("layout", icon, GettextCatalog.GetString ("Defines a layout file to use in this view"));
				list.Add ("sessionstate", icon, GettextCatalog.GetString ("Defines a sessionstate mode"));
				list.Add ("section", icon, GettextCatalog.GetString ("Defines a section"));
			} else if (kind == RazorHostKind.Template) {
				list.Add ("__class", icon, GettextCatalog.GetString ("Customizes the generated class"));
				list.Add ("__property", icon, GettextCatalog.GetString ("Adds a property"));
			}
		}
		protected override void GetElementCompletions (CompletionDataList list)
		{
			AddMiscBeginTags (list);

			var path = GetCurrentPath ();

			if (path.Count == 0) {
				list.Add (new XmlCompletionData ("Project", XmlCompletionData.DataType.XmlElement));
				return;
			}

			var rr = ResolveElement (path);
			if (rr == null)
				return;

			foreach (var c in rr.BuiltinChildren)
				list.Add (new XmlCompletionData (c, XmlCompletionData.DataType.XmlElement));

			var inferredChildren = GetInferredChildren (rr);
			if (inferredChildren != null)
				foreach (var c in inferredChildren)
					list.Add (new XmlCompletionData (c, XmlCompletionData.DataType.XmlElement));
		}
		protected override CompletionDataList GetAttributeCompletions (IAttributedXObject attributedOb,
			Dictionary<string, string> existingAtts)
		{
			var el = GetMSBuildElement (GetCurrentPath ());

			if (el != null && el.Attributes != null) {
				var list = new CompletionDataList ();
				foreach (var a in el.Attributes)
					if (!existingAtts.ContainsKey (a))
						list.Add (new XmlCompletionData (a, XmlCompletionData.DataType.XmlElement));
				return list;
			}

			return null;
		}
示例#42
0
		private static void AddRazorTemplates (CompletionDataList list)
		{
			string icon = "md-template";
			list.Add ("inherits", icon, "Template for inherits directive");
			list.Add ("model", icon, "Template for model directive");
			list.Add ("helper", icon, "Template for helper directive");
			list.Add ("section", icon, "Template for section directive");
			list.Add ("functions", icon, "Template for functions directive");
			list.Add ("using", icon, "Template for using statement");
		}
		static void AddRazorTemplates (CompletionDataList list, RazorHostKind kind)
		{
			string icon = "md-template";
			list.Add ("inherits", icon, GettextCatalog.GetString ("Template for inherits directive"));
			list.Add ("model", icon, GettextCatalog.GetString ("Template for model directive"));
			list.Add ("helper", icon, GettextCatalog.GetString ("Template for helper directive"));
			list.Add ("functions", icon, GettextCatalog.GetString ("Template for functions directive"));
			list.Add ("using", icon, GettextCatalog.GetString ("Template for using statement"));

			if (kind == RazorHostKind.WebPage) {
				list.Add ("section", icon, GettextCatalog.GetString ("Template for section directive"));
			}
		}
示例#44
0
		protected override void GetElementCompletions(CompletionDataList list)
		{
			var currentPath = GetCurrentPath();
			var path = GetPath(currentPath);
			var namespaces = GetNamespaces(currentPath);
			var completions = Completion.GetCompletions(namespaces).ToList();
			var filter = completions.Select(r => r.GetFilter(path)).FirstOrDefault(r => r != null);
			foreach (var completion in completions)
			{
				foreach (var item in completion.GetClasses(path, filter))
				{
					var xmlCompletion = new XmlCompletionData(item.Name, item.Description, XmlCompletionData.DataType.XmlElement);
					xmlCompletion.Icon = Stock.Class;
					list.Add(xmlCompletion);
				}
			}
			BaseXmlEditorExtension.AddMiscBeginTags(list);
			base.GetElementCompletions(list);
		}
示例#45
0
        /// <summary>
        /// Vrati autokompletion pre include,
        /// </summary>
        /// <returns>
        /// Zoznam autoCompletion slov pre include
        /// </returns>
        public static ICompletionDataList GetCompletionData(this TextEditor editor ,string baseWord,string fullWord)
        {
            /*
                lib - ms a adresare z framevorku
                app - ms adresare z projektu

             */
            List<string> libsDefine = new List<string>();
            GetAllFiles(ref libsDefine,MainClass.Settings.LibDirectory);
            //GetAllFiles(ref libsDefine,MainClass.Workspace.ActualProject.AbsolutProjectDir);

            CompletionDataList listComplete = new CompletionDataList();
            foreach (string str in libsDefine){
                CompletionData cd = new CompletionData(str,null,"","\""+str+"\"");
                listComplete.Add(cd);
            }

            //listComplete.AddRange(MainClass.CompletedCache.IncludeCompletion);
            return listComplete;
        }
		public ICompletionDataList GetPathCompletions (string subPath)
		{
			var paths = new HashSet<string> ();
			var cp = new CompletionDataList ();
			var addins = GetReferencedAddins ().ToList ();
			foreach (var addin in addins) {
				foreach (ExtensionPoint ep in addin.Description.ExtensionPoints) {
					if (ep.Path.StartsWith (subPath, System.StringComparison.Ordinal)) {
						string spath = ep.Path.Substring (subPath.Length);
						int i = spath.IndexOf ('/');
						if (i != -1)
							spath = spath.Substring (0, i);
						if (paths.Add (spath)) {
							if (i == -1)
								cp.Add (spath, null, ep.Name + "\n" + ep.Description);
							else
								cp.Add (spath);
						}
					}
					if (ep.Path == subPath.TrimEnd ('/')) {
						var extensions = ExtensionNodeElement.GetExtensions (project, ep).ToList ();
						foreach (ExtensionNodeType nodeType in ep.NodeSet.GetAllowedNodeTypes ()) {
							var allowedChildren = nodeType.GetAllowedNodeTypes ();
							if (allowedChildren.Count == 0)
								continue;
							foreach (var ext in extensions) {
								foreach (ExtensionNodeDescription node in ext.ExtensionNodes) {
									if (node.GetNodeType () == nodeType && !string.IsNullOrEmpty (node.Id)) {
										cp.Add (node.Id);
									}
								}
							}
						}
					}
				}
			}
			return cp;
		}
		public void AddEnumMembers (CompletionDataList completionList, IType resolvedType)
		{
			if (resolvedType == null || resolvedType.ClassType != MonoDevelop.Projects.Dom.ClassType.Enum)
				return;
			string typeString = Document.CompilationUnit.ShortenTypeName (new DomReturnType (resolvedType), new DomLocation (Document.Editor.Caret.Line, Document.Editor.Caret.Column)).ToInvariantString ();
			if (typeString.Contains ("."))
				completionList.Add (typeString, resolvedType.StockIcon);
			foreach (var field in resolvedType.Fields) {
				if (field.IsConst || field.IsStatic)
					completionList.Add (typeString + "." + field.Name, field.StockIcon);
			}
			completionList.DefaultCompletionString = typeString;
		}
		public virtual ICompletionDataList ShowCodeSurroundingsCommand (CodeCompletionContext completionContext)
		{
			CompletionDataList list = new CompletionDataList ();
			list.AutoSelect = true;
			list.AutoCompleteEmptyMatch = true;
			list.CompletionSelectionMode = CompletionSelectionMode.OwnTextField;
			var templateWidget = DocumentContext.GetContent<ICodeTemplateContextProvider> ();
			CodeTemplateContext ctx = CodeTemplateContext.Standard;
			if (templateWidget != null)
				ctx = templateWidget.GetCodeTemplateContext ();
			foreach (CodeTemplate template in CodeTemplateService.GetCodeTemplatesForFile (DocumentContext.Name)) {
				if ((template.CodeTemplateType & CodeTemplateType.SurroundsWith) == CodeTemplateType.SurroundsWith) {
					if (ctx == template.CodeTemplateContext)
						list.Add (new CodeTemplateCompletionData (this, template));
				}
			}
			return list;
		}
		public static void AddCompletionDataForMime (string mimeType, CompletionDataList list)
		{
			foreach (CodeTemplate ct in GetCodeTemplates (mimeType)) {
				if (string.IsNullOrEmpty (ct.Shortcut) || ct.CodeTemplateContext != CodeTemplateContext.Standard)
					continue;
				list.Remove (ct.Shortcut);
				list.Add (new CompletionData (ct.Shortcut, ct.Icon , ct.Shortcut + Environment.NewLine + GettextCatalog.GetString (ct.Description)));
			}
		}
		public ICompletionDataList HandleKeywordCompletion (CodeCompletionContext completionContext, ExpressionResult result, int wordStart, string word)
		{
			if (stateTracker.Engine.IsInsideDocLineComment || stateTracker.Engine.IsInsideOrdinaryCommentOrString)
				return null;
			DomLocation location = new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset);
			switch (word) {
			case "using":
				if (result.ExpressionContext != ExpressionContext.NamespaceNameExcepted)
					return null;
				return CreateCompletionData (location, new NamespaceResolveResult (""), result, null);
			case "namespace":
				result.ExpressionContext = ExpressionContext.NamespaceNameExcepted;
				return CreateCompletionData (location, new NamespaceResolveResult (""), result, null);
			case "case":
				return CreateCaseCompletionData (location, result);
			case ",":
			case ":":
				if (result.ExpressionContext == ExpressionContext.InheritableType) {
					IType cls = NRefactoryResolver.GetTypeAtCursor (Document.CompilationUnit, Document.FileName, new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
					CompletionDataList completionList = new ProjectDomCompletionDataList ();
					List<string> namespaceList = GetUsedNamespaces ();
					CSharpTextEditorCompletion.CompletionDataCollector col = new CSharpTextEditorCompletion.CompletionDataCollector (dom, completionList, Document.CompilationUnit, null, location);
					bool isInterface = false;
					HashSet<string> baseTypeNames = new HashSet<string> ();
					if (cls != null) {
						baseTypeNames.Add (cls.Name);
						if (cls.ClassType == ClassType.Struct)
							isInterface = true;
					}
					int tokenIndex = completionContext.TriggerOffset;

										// Search base types " : [Type1, ... ,TypeN,] <Caret>"
					string token = null;
					do {
						token = GetPreviousToken (ref tokenIndex, false);
						if (string.IsNullOrEmpty (token))
							break;
						token = token.Trim ();
						if (Char.IsLetterOrDigit (token[0]) || token[0] == '_') {
							IType baseType = dom.SearchType (Document.CompilationUnit, Document.CompilationUnit, token);
							if (baseType != null) {
								if (baseType.ClassType != ClassType.Interface)
									isInterface = true;
								baseTypeNames.Add (baseType.Name);
							}
						}
					} while (token != ":");
					foreach (object o in dom.GetNamespaceContents (namespaceList, true, true)) {
						IType type = o as IType;
						if (type != null && (type.IsStatic || type.IsSealed || baseTypeNames.Contains (type.Name) || isInterface && type.ClassType != ClassType.Interface)) {
							continue;
						}
						if (o is Namespace && !namespaceList.Any (ns => ns.StartsWith (((Namespace)o).FullName)))
							continue;
						col.Add (o);
					}
					// Add inner classes
					Stack<IType> innerStack = new Stack<IType> ();
					innerStack.Push (cls);
					while (innerStack.Count > 0) {
						IType curType = innerStack.Pop ();
						if (curType == null)
							continue;
						foreach (IType innerType in curType.InnerTypes) {
							if (innerType != cls)
								// don't add the calling class as possible base type
								col.Add (innerType);
						}
						if (curType.DeclaringType != null)
							innerStack.Push (curType.DeclaringType);
					}
					return completionList;
				}
				break;
			case "is":
			case "as":
				
				{
					CompletionDataList completionList = new ProjectDomCompletionDataList ();
					ExpressionResult expressionResult = FindExpression (dom, completionContext, wordStart - textEditorData.Caret.Offset);
					NRefactoryResolver resolver = CreateResolver ();
					ResolveResult resolveResult = resolver.Resolve (expressionResult, new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
					if (resolveResult != null && resolveResult.ResolvedType != null) {
						CompletionDataCollector col = new CompletionDataCollector (dom, completionList, Document.CompilationUnit, resolver.CallingType, location);
						IType foundType = null;
						if (word == "as") {
							ExpressionContext exactContext = new NewCSharpExpressionFinder (dom).FindExactContextForAsCompletion (textEditorData, Document.CompilationUnit, Document.FileName, resolver.CallingType);
							if (exactContext is ExpressionContext.TypeExpressionContext) {
								foundType = resolver.SearchType (((ExpressionContext.TypeExpressionContext)exactContext).Type);
								AddAsCompletionData (col, foundType);
							}
						}
					
						if (foundType == null)
							foundType = resolver.SearchType (resolveResult.ResolvedType);
					
						if (foundType != null) {
							if (foundType.ClassType == ClassType.Interface)
								foundType = resolver.SearchType (DomReturnType.Object);
						
							foreach (IType type in dom.GetSubclasses (foundType)) {
								if (type.IsSpecialName || type.Name.StartsWith ("<"))
									continue;
								AddAsCompletionData (col, type);
							}
						}
						List<string> namespaceList = GetUsedNamespaces ();
						foreach (object o in dom.GetNamespaceContents (namespaceList, true, true)) {
							if (o is IType) {
								IType type = (IType)o;
								if (type.ClassType != ClassType.Interface || type.IsSpecialName || type.Name.StartsWith ("<"))
									continue;
//								if (foundType != null && !dom.GetInheritanceTree (foundType).Any (x => x.FullName == type.FullName))
//									continue;
								AddAsCompletionData (col, type);
								continue;
							}
							if (o is Namespace)
								continue;
							col.Add (o);
						}
						return completionList;
					}
					result.ExpressionContext = ExpressionContext.TypeName;
					return CreateCtrlSpaceCompletionData (completionContext, result);
				}
			case "override":
				// Look for modifiers, in order to find the beginning of the declaration
				int firstMod = wordStart;
				int i = wordStart;
				for (int n = 0; n < 3; n++) {
					string mod = GetPreviousToken (ref i, true);
					if (mod == "public" || mod == "protected" || mod == "private" || mod == "internal" || mod == "sealed") {
						firstMod = i;
					} else if (mod == "static") {
						// static methods are not overridable
						return null;
					} else
						break;
				}
				IType overrideCls = NRefactoryResolver.GetTypeAtCursor (Document.CompilationUnit, Document.FileName, new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
				if (overrideCls == null)
					overrideCls = NRefactoryResolver.GetTypeAtCursor (Document.CompilationUnit, Document.FileName, new DomLocation (completionContext.TriggerLine - 1, 1));
				if (overrideCls != null && (overrideCls.ClassType == ClassType.Class || overrideCls.ClassType == ClassType.Struct)) {
					string modifiers = textEditorData.GetTextBetween (firstMod, wordStart);
					return GetOverrideCompletionData (completionContext, overrideCls, modifiers);
				}
				return null;
			case "partial":
				// Look for modifiers, in order to find the beginning of the declaration
				firstMod = wordStart;
				i = wordStart;
				for (int n = 0; n < 3; n++) {
					string mod = GetPreviousToken (ref i, true);
					if (mod == "public" || mod == "protected" || mod == "private" || mod == "internal" || mod == "sealed") {
						firstMod = i;
					} else if (mod == "static") {
						// static methods are not overridable
						return null;
					} else
						break;
				}
				overrideCls = NRefactoryResolver.GetTypeAtCursor (Document.CompilationUnit, Document.FileName, new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
				if (overrideCls != null && (overrideCls.ClassType == ClassType.Class || overrideCls.ClassType == ClassType.Struct)) {
					string modifiers = textEditorData.GetTextBetween (firstMod, wordStart);
					return GetPartialCompletionData (completionContext, overrideCls, modifiers);
				}
				return null;
				
			case "new":
				IType callingType = NRefactoryResolver.GetTypeAtCursor (Document.CompilationUnit, Document.FileName, new DomLocation (textEditorData.Caret.Line, textEditorData.Caret.Column));
				ExpressionContext newExactContext = new NewCSharpExpressionFinder (dom).FindExactContextForNewCompletion (textEditorData, Document.CompilationUnit, Document.FileName, callingType);
				if (newExactContext is ExpressionContext.TypeExpressionContext)
					return CreateTypeCompletionData (location, callingType, newExactContext, ((ExpressionContext.TypeExpressionContext)newExactContext).Type, ((ExpressionContext.TypeExpressionContext)newExactContext).UnresolvedType);
				if (newExactContext == null) {
					int j = completionContext.TriggerOffset - 4;
					string token = GetPreviousToken (ref j, true);
					string yieldToken = GetPreviousToken (ref j, true);
					if (token == "return") {
						NRefactoryResolver resolver = CreateResolver ();
						resolver.SetupResolver (new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
						IReturnType returnType = resolver.CallingMember.ReturnType;
						if (yieldToken == "yield" && returnType.GenericArguments.Count > 0)
							returnType = returnType.GenericArguments[0];
						if (resolver.CallingMember != null)
							return CreateTypeCompletionData (location, callingType, newExactContext, null, returnType);
					}
				}
				return CreateCtrlSpaceCompletionData (completionContext, null);
			case "if":
			case "elif":
				if (stateTracker.Engine.IsInsidePreprocessorDirective) 
					return GetDefineCompletionData ();
				return null;
			case "yield":
				CompletionDataList yieldDataList = new CompletionDataList ();
				yieldDataList.DefaultCompletionString = "return";
				yieldDataList.Add ("break", "md-keyword");
				yieldDataList.Add ("return", "md-keyword");
				return yieldDataList;
			case "where":
				CompletionDataList whereDataList = new CompletionDataList ();
				NRefactoryResolver constraintResolver = CreateResolver ();
				constraintResolver.SetupResolver (new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
				if (constraintResolver.CallingMember is IMethod) {
					foreach (ITypeParameter tp in ((IMethod)constraintResolver.CallingMember).TypeParameters) {
						whereDataList.Add (tp.Name, "md-keyword");
					}
				} else {
					if (constraintResolver.CallingType != null) {
						foreach (ITypeParameter tp in constraintResolver.CallingType.TypeParameters) {
							whereDataList.Add (tp.Name, "md-keyword");
						}
					}
				}

				return whereDataList;
			}
			if (IsInLinqContext (result)) {
				if (linqKeywords.Contains (word)) {
					if (word == "from") // after from no auto code completion.
						return null;
					result.Expression = "";
					return CreateCtrlSpaceCompletionData (completionContext, result);
				}
				CompletionDataList dataList = new ProjectDomCompletionDataList ();
				CompletionDataCollector col = new CompletionDataCollector (dom, dataList, Document.CompilationUnit, null, new DomLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset));
				foreach (string kw in linqKeywords) {
					col.Add (kw, "md-keyword");
				}
				return dataList;
			}
			return null;
		}
		public virtual ICompletionDataList ShowCodeTemplatesCommand (CodeCompletionContext completionContext)
		{
			CompletionDataList list = new CompletionDataList ();
			list.AutoSelect = true;
			list.AutoCompleteEmptyMatch = true;
			list.CompletionSelectionMode = CompletionSelectionMode.OwnTextField;
			foreach (CodeTemplate template in CodeTemplateService.GetCodeTemplatesForFile (DocumentContext.Name)) {
				if (template.CodeTemplateType != CodeTemplateType.SurroundsWith) {
					list.Add (new CodeTemplateCompletionData (this, template));
				}
			}
			return list;
		}
		/// <summary>
		/// Adds CDATA and comment begin tags.
		/// </summary>
		protected static void AddMiscBeginTags (CompletionDataList list)
		{
			list.Add ("!--",  "md-literal", GettextCatalog.GetString ("Comment"));
			list.Add ("![CDATA[", "md-literal", GettextCatalog.GetString ("Character data"));
		}
		protected virtual ICompletionDataList ClosingTagCompletion (TextEditor buf, DocumentLocation currentLocation)

		{

			//get name of current node in document that's being ended

			var el = tracker.Engine.Nodes.Peek () as XElement;

			if (el != null && el.Region.End >= currentLocation && !el.IsClosed && el.IsNamed) {

				string tag = String.Concat ("</", el.Name.FullName, ">");

				if (XmlEditorOptions.AutoCompleteElements) {



					//						//make sure we have a clean atomic undo so the user can undo the tag insertion

					//						//independently of the >

					//						bool wasInAtomicUndo = this.Editor.Document.IsInAtomicUndo;

					//						if (wasInAtomicUndo)

					//							this.Editor.Document.EndAtomicUndo ();



					using (var undo = buf.OpenUndoGroup ()) {

						buf.InsertText (buf.CaretOffset, tag);

						buf.CaretOffset -= tag.Length;

					}



					//						if (wasInAtomicUndo)

					//							this.Editor.Document.BeginAtomicUndo ();



					return null;

				} else {

					var cp = new CompletionDataList ();

					cp.Add (new XmlTagCompletionData (tag, 0, true));

					return cp;

				}

			}

			return null;
		}
		string AddDelegateHandlers (CompletionDataList completionList, IType delegateType, bool addSemicolon = true, bool addDefault = true)
		{
			IMethod delegateMethod = delegateType.Methods.First ();
			string delegateEndString = Document.Editor.EolMarker + stateTracker.Engine.ThisLineIndent + "}" + (addSemicolon ? ";" : "");
			bool containsDelegateData = completionList.Any (d => d.DisplayText.StartsWith ("delegate("));
			if (addDefault)
				completionList.Add ("delegate", "md-keyword", GettextCatalog.GetString ("Creates anonymous delegate."), "delegate {" + Document.Editor.EolMarker + stateTracker.Engine.ThisLineIndent + TextEditorProperties.IndentString + "|" + delegateEndString);
			
			StringBuilder sb = new StringBuilder ("(");
			StringBuilder sbWithoutTypes = new StringBuilder ("(");
			for (int k = 0; k < delegateMethod.Parameters.Count; k++) {
				if (k > 0) {
					sb.Append (", ");
					sbWithoutTypes.Append (", ");
				}
				IType parameterType = dom.GetType (delegateMethod.Parameters [k].ReturnType);
				IReturnType returnType = parameterType != null ? new DomReturnType (parameterType) : delegateMethod.Parameters [k].ReturnType;
				sb.Append (CompletionDataCollector.ambience.GetString (Document.CompilationUnit.ShortenTypeName (returnType, textEditorData.Caret.Line, textEditorData.Caret.Column), OutputFlags.ClassBrowserEntries | OutputFlags.UseFullName | OutputFlags.UseFullInnerTypeName));
				sb.Append (" ");
				sb.Append (delegateMethod.Parameters [k].Name);
				sbWithoutTypes.Append (delegateMethod.Parameters [k].Name);
			}
			sb.Append (")");
			sbWithoutTypes.Append (")");
			completionList.Add ("delegate" + sb, "md-keyword", GettextCatalog.GetString ("Creates anonymous delegate."), "delegate" + sb + " {" + Document.Editor.EolMarker + stateTracker.Engine.ThisLineIndent + TextEditorProperties.IndentString + "|" + delegateEndString);
			if (!completionList.Any (data => data.DisplayText == sbWithoutTypes.ToString ()))
				completionList.Add (sbWithoutTypes.ToString (), "md-keyword", GettextCatalog.GetString ("Creates lambda expression."), sbWithoutTypes + " => |" + (addSemicolon ? ";" : ""));
			
			// It's  needed to temporarly disable inserting auto matching bracket because the anonymous delegates are selectable with '('
			// otherwise we would end up with () => )
			if (!containsDelegateData) {
				var savedValue = MonoDevelop.SourceEditor.DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket;
				MonoDevelop.SourceEditor.DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket = false;
				completionList.CompletionListClosed += delegate {
					MonoDevelop.SourceEditor.DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket = savedValue;
				};
			}
			return sb.ToString ();
		}
		protected virtual async Task<ICompletionDataList> HandleCodeCompletion (
			CodeCompletionContext completionContext, bool forced, CancellationToken token)
		{
			var buf = this.Editor;

			// completionChar may be a space even if the current char isn't, when ctrl-space is fired t
			var currentLocation = new DocumentLocation (completionContext.TriggerLine, completionContext.TriggerLineOffset);
			char currentChar = completionContext.TriggerOffset < 1? ' ' : buf.GetCharAt (completionContext.TriggerOffset - 1);
			char previousChar = completionContext.TriggerOffset < 2? ' ' : buf.GetCharAt (completionContext.TriggerOffset - 2);

			LoggingService.LogDebug ("Attempting completion for state '{0}'x{1}, previousChar='{2}'," 
				+ " currentChar='{3}', forced='{4}'", tracker.Engine.CurrentState,
				tracker.Engine.CurrentStateLength, previousChar, currentChar, forced);
			
			//closing tag completion
			if (tracker.Engine.CurrentState is XmlRootState && currentChar == '>')
				return ClosingTagCompletion (buf, currentLocation);
			
			// Auto insert '>' when '/' is typed inside tag state (for quick tag closing)
			//FIXME: avoid doing this when the next non-whitespace char is ">" or ignore the next ">" typed
			if (XmlEditorOptions.AutoInsertFragments && tracker.Engine.CurrentState is XmlTagState && currentChar == '/') {
				buf.InsertAtCaret (">");
				return null;
			}
			
			//entity completion
			if (currentChar == '&' && (tracker.Engine.CurrentState is XmlRootState ||
			                           tracker.Engine.CurrentState is XmlAttributeValueState))
			{
				var list = new CompletionDataList ();
				
				//TODO: need to tweak semicolon insertion
				list.Add ("apos").Description = "'";
				list.Add ("quot").Description = "\"";
				list.Add ("lt").Description = "<";
				list.Add ("gt").Description = ">";
				list.Add ("amp").Description = "&";
				
				//not sure about these "completions". they're more like
				//shortcuts than completions but they're pretty useful
				list.Add ("'").CompletionText = "apos;";
				list.Add ("\"").CompletionText = "quot;";
				list.Add ("<").CompletionText = "lt;";
				list.Add (">").CompletionText = "gt;";
				list.Add ("&").CompletionText = "amp;";
				
				var ecList = await GetEntityCompletions (token);
				list.AddRange (ecList);
				return list;
			}
			
			//doctype completion
			if (tracker.Engine.CurrentState is XmlDocTypeState) {
				if (tracker.Engine.CurrentStateLength == 1) {
					CompletionDataList list = await GetDocTypeCompletions (token);
					if (list != null && list.Count > 0)
						return list;
				}
				return null;
			}

			//attribute value completion
			//determine whether to trigger completion within attribute values quotes
			if ((Tracker.Engine.CurrentState is XmlAttributeValueState)
			    //trigger on the opening quote
			    && ((Tracker.Engine.CurrentStateLength == 1 && (currentChar == '\'' || currentChar == '"'))
			    //or trigger on first letter of value, if unforced
			    || (forced || Tracker.Engine.CurrentStateLength == 2))) {
				var att = (XAttribute)Tracker.Engine.Nodes.Peek ();

				if (att.IsNamed) {
					var attributedOb = Tracker.Engine.Nodes.Peek (1) as IAttributedXObject;
					if (attributedOb == null)
						return null;

					//if triggered by first letter of value or forced, grab those letters

					var result = await GetAttributeValueCompletions (attributedOb, att, token);
					if (result != null) {
						result.TriggerWordLength = Tracker.Engine.CurrentStateLength - 1;
						return result;
					}
					return null;
				}
			}
			
			//attribute name completion
			if ((forced && Tracker.Engine.Nodes.Peek () is IAttributedXObject && !tracker.Engine.Nodes.Peek ().IsEnded)
			     || ((Tracker.Engine.CurrentState is XmlNameState
			    && Tracker.Engine.CurrentState.Parent is XmlAttributeState) ||
			    Tracker.Engine.CurrentState is XmlTagState)
			    && (Tracker.Engine.CurrentStateLength == 1 || forced)) {
				IAttributedXObject attributedOb = (Tracker.Engine.Nodes.Peek () as IAttributedXObject) ?? 
					Tracker.Engine.Nodes.Peek (1) as IAttributedXObject;
				if (attributedOb == null)
					return null;
				
				//attributes
				if (attributedOb.Name.IsValid && (forced ||
					(char.IsWhiteSpace (previousChar) && char.IsLetter (currentChar))))
				{
					var existingAtts = new Dictionary<string,string> (StringComparer.OrdinalIgnoreCase);
					
					foreach (XAttribute att in attributedOb.Attributes) {
						existingAtts [att.Name.FullName] = att.Value ?? string.Empty;
					}
					var result = await GetAttributeCompletions (attributedOb, existingAtts, token);
					if (result != null) {
						if (!forced)
							result.TriggerWordLength = 1;
						return result;
					}
					return null;
				}
			}
			
//			if (Tracker.Engine.CurrentState is XmlRootState) {
//				if (line < 3) {
//				cp.Add ("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
//			}

			//element completion
			if (currentChar == '<' && tracker.Engine.CurrentState is XmlRootState ||
				(tracker.Engine.CurrentState is XmlNameState && forced)) {
				var list = await GetElementCompletions (token);
				AddCloseTag (list, Tracker.Engine.Nodes);
				return list.Count > 0 ? list : null;
			}

			if (forced && Tracker.Engine.CurrentState is XmlRootState) {
				var list = new CompletionDataList ();
				MonoDevelop.Ide.CodeTemplates.CodeTemplateService.AddCompletionDataForFileName (DocumentContext.Name, list);
				return list.Count > 0? list : null;
			}
			
			return null;
		}
		void AddVirtuals (CodeCompletionContext ctx, Dictionary<string, bool> alreadyInserted, CompletionDataList completionList, IType type, string modifiers, IReturnType curType)
		{
			if (curType == null)
				return;
			IType searchType = dom.SearchType (Document.CompilationUnit, (MonoDevelop.Projects.Dom.INode)type ?? Document.CompilationUnit, curType);
			//System.Console.WriteLine("Add Virtuals for:" + searchType + " / " + curType);
			if (searchType == null)
				return;
			bool isInterface      = type.ClassType == ClassType.Interface;
			bool includeOverriden = false;
		
			int declarationBegin = ctx.TriggerOffset;
			int j = declarationBegin;
			for (int i = 0; i < 3; i++) {
				switch (GetPreviousToken (ref j, true)) {
					case "public":
					case "protected":
					case "private":
					case "internal":
					case "sealed":
					case "override":
						declarationBegin = j;
						break;
					case "static":
						return; // don't add override completion for static members
				}
			}
			CompletionDataCollector col = new CompletionDataCollector (dom, completionList, Document.CompilationUnit, searchType, DomLocation.Empty);
			
			List<IType> inheritanceTree = new List<IType> (this.dom.GetInheritanceTree (searchType));
			inheritanceTree.Sort ((l, r) => l.ClassType == r.ClassType ? 0 : (l.ClassType == ClassType.Interface ? 1 : (r.ClassType == ClassType.Interface ? -1 : 0)));
			foreach (IType t in inheritanceTree) {
				foreach (IMember m in t.Members) {
					if (!m.IsAccessibleFrom (dom, type, type, true) || m.IsSpecialName)
						continue;
					//System.Console.WriteLine ("scan:" + m);
					//if (m.IsSpecialName || (m.IsInternal && !m.IsProtectedOrInternal) || && searchType.SourceProject != Document.Project)
					//	continue;
					if (t.ClassType == ClassType.Interface || (isInterface || m.IsVirtual || m.IsAbstract) && !m.IsSealed && (includeOverriden || !type.HasOverriden (m))) {
						// filter out the "Finalize" methods, because finalizers should be done with destructors.
						if (m is IMethod && m.Name == "Finalize")
							continue;
					
						//System.Console.WriteLine("add");
						NewOverrideCompletionData data = new NewOverrideCompletionData (dom, textEditorData, declarationBegin, type, m);
						string text = CompletionDataCollector.ambience.GetString (m, OutputFlags.ClassBrowserEntries);
						// check if the member is already implemented
						bool foundMember = false;
						foreach (IMember member in type.Members) {
							if (text == CompletionDataCollector.ambience.GetString (member, OutputFlags.ClassBrowserEntries)) {
								foundMember = true;
								break;
							}
						}
						
						if (!foundMember && !alreadyInserted.ContainsKey (text)) {
							alreadyInserted[text] = true;
							data.CompletionCategory = col.GetCompletionCategory (t);
							completionList.Add (data);
						}
					}
				}
			}
		}
		protected static void AddCloseTag (CompletionDataList completionList, NodeStack stack)
		{
			//FIXME: search forward to see if tag's closed already
			var elements = new List<XElement> ();
			foreach (XObject ob in stack) {
				var el = ob as XElement;
				if (el == null)
					continue;
				if (!el.IsNamed || el.IsClosed)
					return;
				
				if (elements.Count == 0) {
					string name = el.Name.FullName;
					completionList.Add ("/" + name + ">", Gtk.Stock.GoBack,
					                    GettextCatalog.GetString ("Closing tag for '{0}'", name));
				} else {
					foreach (XElement listEl in elements) {
						if (listEl.Name == el.Name)
							return;
					}
					completionList.Add (new XmlMultipleClosingTagCompletionData (el, elements.ToArray ()));
				}
				elements.Add (el);
			}
		}
		CompletionDataList GetDirectiveCompletionData ()
		{
			CompletionDataList cp = new CompletionDataList ();
			string lit = "md-literal";
			cp.Add ("if", lit);
			cp.Add ("else", lit);
			cp.Add ("elif", lit);
			cp.Add ("endif", lit);
			cp.Add ("define", lit);
			cp.Add ("undef", lit);
			cp.Add ("warning", lit);
			cp.Add ("error", lit);
			cp.Add ("pragma", lit);
			cp.Add ("line", lit);
			cp.Add ("line hidden", lit);
			cp.Add ("line default", lit);
			cp.Add ("region", lit);
			cp.Add ("endregion", lit);
			return cp;
		}
		protected override void Run ()
		{
			var doc = IdeApp.Workbench.ActiveDocument;
			if (doc == null || doc.FileName == FilePath.Null || doc.ParsedDocument == null)
				return;
			ITextEditorExtension ext = doc.EditorExtension;
			while (ext != null && !(ext is CompletionTextEditorExtension))
				ext = ext.Next;
			if (ext == null)
				return;
		
			var dom = doc.Compilation;
			ImportSymbolCache cache = new ImportSymbolCache ();
			
			List<ImportSymbolCompletionData> typeList = new List<ImportSymbolCompletionData> ();
			foreach (var type in dom.GetAllTypeDefinitions ()) {
				typeList.Add (new ImportSymbolCompletionData (doc, cache, type));
			}
			
			typeList.Sort (delegate (ImportSymbolCompletionData left, ImportSymbolCompletionData right) {
				return left.Type.Name.CompareTo (right.Type.Name);
			});
			
			
			CompletionDataList completionList = new CompletionDataList ();
			completionList.IsSorted = true;
			typeList.ForEach (cd => completionList.Add (cd));
			
			((CompletionTextEditorExtension)ext).ShowCompletion (completionList);
		}
		CompletionDataList GetXmlDocumentationCompletionData ()
		{
			CompletionDataList cp = new CompletionDataList ();
			cp.Add ("c", "md-literal", GettextCatalog.GetString ("Set text in a code-like font"));
			cp.Add ("code", "md-literal", GettextCatalog.GetString ("Set one or more lines of source code or program output"));
			cp.Add ("example", "md-literal", GettextCatalog.GetString ("Indicate an example"));
			cp.Add ("exception", "md-literal", GettextCatalog.GetString ("Identifies the exceptions a method can throw"), "exception cref=\"|\"></exception>");
			cp.Add ("include", "md-literal", GettextCatalog.GetString ("Includes comments from a external file"), "include file=\"|\" path=\"\">");
			cp.Add ("list", "md-literal", GettextCatalog.GetString ("Create a list or table"), "list type=\"|\">");
			
			cp.Add ("listheader", "md-literal", GettextCatalog.GetString ("Define the heading row"));
			cp.Add ("item", "md-literal", GettextCatalog.GetString ("Defines list or table item"));
			cp.Add ("term", "md-literal", GettextCatalog.GetString ("A term to define"));
			cp.Add ("description", "md-literal", GettextCatalog.GetString ("Describes a list item"));
			cp.Add ("para", "md-literal", GettextCatalog.GetString ("Permit structure to be added to text"));

			cp.Add ("param", "md-literal", GettextCatalog.GetString ("Describe a parameter for a method or constructor"), "param name=\"|\">");
			cp.Add ("paramref", "md-literal", GettextCatalog.GetString ("Identify that a word is a parameter name"), "paramref name=\"|\"/>");
			
			cp.Add ("permission", "md-literal", GettextCatalog.GetString ("Document the security accessibility of a member"), "permission cref=\"|\"");
			cp.Add ("remarks", "md-literal", GettextCatalog.GetString ("Describe a type"));
			cp.Add ("returns", "md-literal", GettextCatalog.GetString ("Describe the return value of a method"));
			cp.Add ("see", "md-literal", GettextCatalog.GetString ("Specify a link"), "see cref=\"|\"/>");
			cp.Add ("seealso", "md-literal", GettextCatalog.GetString ("Generate a See Also entry"), "seealso cref=\"|\"/>");
			cp.Add ("summary", "md-literal", GettextCatalog.GetString ("Describe a member of a type"));
			cp.Add ("typeparam", "md-literal", GettextCatalog.GetString ("Describe a type parameter for a generic type or method"));
			cp.Add ("typeparamref", "md-literal", GettextCatalog.GetString ("Identify that a word is a type parameter name"));
			cp.Add ("value", "md-literal", GettextCatalog.GetString ("Describe a property"));
			
			return cp;
		}