private IEnumerable<Declaration> GetParameters()
        {
            var targetSelection = new Selection(TargetDeclaration.Context.Start.Line,
                TargetDeclaration.Context.Start.Column,
                TargetDeclaration.Context.Stop.Line,
                TargetDeclaration.Context.Stop.Column);

            return Declarations.Where(d => d.DeclarationType == DeclarationType.Parameter
                                       && d.ComponentName == TargetDeclaration.ComponentName
                                       && d.ProjectId == TargetDeclaration.ProjectId
                                       && targetSelection.Contains(d.Selection))
                              .OrderBy(item => item.Selection.StartLine)
                              .ThenBy(item => item.Selection.StartColumn);
        }
        private List<RegexSearchResult> SearchCurrentBlock(string searchPattern)
        {
            var declarationTypes = new[]
                    {
                        DeclarationType.Event,
                        DeclarationType.Function,
                        DeclarationType.Procedure,
                        DeclarationType.PropertyGet,
                        DeclarationType.PropertyLet,
                        DeclarationType.PropertySet
                    };

            var parseResult = _parser.State;
            var results = GetResultsFromModule(_vbe.ActiveCodePane.CodeModule, searchPattern);

            var wrapper = _codePaneFactory.Create(_vbe.ActiveCodePane);
            var qualifiedSelection = new QualifiedSelection(new QualifiedModuleName(wrapper.CodeModule.Parent), wrapper.Selection);
            dynamic block = parseResult.AllDeclarations.FindTarget(qualifiedSelection, declarationTypes).Context.Parent;
            var selection = new Selection(block.Start.Line, block.Start.Column, block.Stop.Line, block.Stop.Column);
            return results.Where(r => selection.Contains(r.Selection)).ToList();
        }
        private Declaration FindDeclarationForIdentifier()
        {
            var values = _model.Declarations.Where(item => 
                _model.NewName == item.IdentifierName 
                && ((item.Scope.Contains(_model.Target.Scope)
                || (item.ParentScope == null && string.IsNullOrEmpty(_model.Target.ParentScope)) 
                || (item.ParentScope != null && _model.Target.ParentScope.Contains(item.ParentScope))))
                ).ToList();

            if (values.Any())
            {
                return values.FirstOrDefault();
            }

            foreach (var reference in _model.Target.References)
            {
                var targetReference = reference;
                var potentialDeclarations = _model.Declarations.Where(item => !item.IsBuiltIn
                                                         && item.ProjectId == targetReference.Declaration.ProjectId
                                                         && ((item.Context != null
                                                         && item.Context.Start.Line <= targetReference.Selection.StartLine
                                                         && item.Context.Stop.Line >= targetReference.Selection.EndLine)
                                                         || (item.Selection.StartLine <= targetReference.Selection.StartLine
                                                         && item.Selection.EndLine >= targetReference.Selection.EndLine))
                                                         && item.QualifiedName.QualifiedModuleName.ComponentName == targetReference.QualifiedModuleName.ComponentName);

                var currentSelection = new Selection(0, 0, int.MaxValue, int.MaxValue);

                Declaration target = null;
                foreach (var item in potentialDeclarations)
                {
                    var startLine = item.Context == null ? item.Selection.StartLine : item.Context.Start.Line;
                    var endLine = item.Context == null ? item.Selection.EndLine : item.Context.Stop.Column;
                    var startColumn = item.Context == null ? item.Selection.StartColumn : item.Context.Start.Column;
                    var endColumn = item.Context == null ? item.Selection.EndColumn : item.Context.Stop.Column;

                    var selection = new Selection(startLine, startColumn, endLine, endColumn);

                    if (currentSelection.Contains(selection))
                    {
                        currentSelection = selection;
                        target = item;
                    }
                }

                if (target == null) { continue; }

                values = _model.Declarations.Where(item => (item.Scope.Contains(target.Scope)
                                              || (item.ParentScope == null && string.IsNullOrEmpty(target.ParentScope))
                                              || (item.ParentScope != null && target.ParentScope.Contains(item.ParentScope)))
                                              && _model.NewName == item.IdentifierName).ToList();

                if (values.Any())
                {
                    return values.FirstOrDefault();
                }
            }

            return null;
        }
        public Declaration FindSelection(QualifiedSelection selection, DeclarationType[] validDeclarationTypes)
        {
            var target = Items
                .Where(item => !item.IsBuiltIn)
                .FirstOrDefault(item => item.IsSelectedDeclaration(selection)
                                     || item.References.Any(r => r.IsSelectedReference(selection)));

            if (target != null && validDeclarationTypes.Contains(target.DeclarationType))
            {
                return target;
            }

            target = null;

            var targets = Items
                .Where(item => !item.IsBuiltIn
                               && item.ComponentName == selection.QualifiedName.ComponentName
                               && validDeclarationTypes.Contains(item.DeclarationType));

            var currentSelection = new Selection(0, 0, int.MaxValue, int.MaxValue);

            foreach (var declaration in targets)
            {
                var activeSelection = new Selection(declaration.Context.Start.Line,
                                                    declaration.Context.Start.Column,
                                                    declaration.Context.Stop.Line,
                                                    declaration.Context.Stop.Column);

                if (currentSelection.Contains(activeSelection) && activeSelection.Contains(selection.Selection))
                {
                    target = declaration;
                    currentSelection = activeSelection;
                }

                foreach (var reference in declaration.References)
                {
                    var proc = (dynamic)reference.Context.Parent;
                    VBAParser.ArgsCallContext paramList;

                    // This is to prevent throws when this statement fails:
                    // (VBAParser.ArgsCallContext)proc.argsCall();
                    try { paramList = (VBAParser.ArgsCallContext)proc.argsCall(); }
                    catch { continue; }

                    if (paramList == null) { continue; }

                    activeSelection = new Selection(paramList.Start.Line,
                                                    paramList.Start.Column,
                                                    paramList.Stop.Line,
                                                    paramList.Stop.Column + paramList.Stop.Text.Length + 1);

                    if (currentSelection.Contains(activeSelection) && activeSelection.Contains(selection.Selection))
                    {
                        target = reference.Declaration;
                        currentSelection = activeSelection;
                    }
                }
            }
            return target;
        }
        public static Declaration FindInterface(this IEnumerable<Declaration> declarations, QualifiedSelection selection)
        {
            foreach (var declaration in declarations.FindInterfaces())
            {
                foreach (var reference in declaration.References)
                {
                    var implementsStmt = reference.Context.Parent as VBAParser.ImplementsStmtContext;

                    if (implementsStmt == null) { continue; }

                    var completeSelection = new Selection(implementsStmt.GetSelection().StartLine,
                        implementsStmt.GetSelection().StartColumn, reference.Selection.EndLine,
                        reference.Selection.EndColumn);

                    if (reference.QualifiedModuleName.Equals(selection.QualifiedName) &&
                        completeSelection.Contains(selection.Selection))
                    {
                        return declaration;
                    }
                }
            }

            return null;
        }
        /// <summary>
        /// Returns the variable which contains the passed-in QualifiedSelection.  Returns null if the selection is not on a variable.
        /// </summary>
        /// <param name="declarations"></param>
        /// <param name="selection"></param>
        /// <returns></returns>
        public static Declaration FindVariable(this IEnumerable<Declaration> declarations, QualifiedSelection selection)
        {
            var items = declarations.Where(d => !d.IsBuiltIn && d.DeclarationType == DeclarationType.Variable).ToList();

            var target = items
                .FirstOrDefault(item => item.IsSelected(selection) || item.References.Any(r => r.IsSelected(selection)));

            if (target != null) { return target; }

            var targets = items.Where(item => item.ComponentName == selection.QualifiedName.ComponentName);

            foreach (var declaration in targets)
            {
                var declarationSelection = new Selection(declaration.Context.Start.Line,
                                                    declaration.Context.Start.Column,
                                                    declaration.Context.Stop.Line,
                                                    declaration.Context.Stop.Column + declaration.Context.Stop.Text.Length);

                if (declarationSelection.Contains(selection.Selection) ||
                    !HasMultipleDeclarationsInStatement(declaration) && GetVariableStmtContextSelection(declaration).Contains(selection.Selection))
                {
                    return declaration;
                }

                var reference =
                    declaration.References.FirstOrDefault(r => r.Selection.Contains(selection.Selection));

                if (reference != null)
                {
                    return reference.Declaration;
                }
            }
            return null;
        }
        /// <summary>
        /// Returns the declaration contained in a qualified selection.
        /// To get the selection of a variable or field, use FindVariable(QualifiedSelection)
        /// </summary>
        /// <param name="declarations"></param>
        /// <param name="selection"></param>
        /// <param name="validDeclarationTypes"></param>
        /// <returns></returns>
        public static Declaration FindTarget(this IEnumerable<Declaration> declarations, QualifiedSelection selection, DeclarationType[] validDeclarationTypes)
        {
            var items = declarations.ToList();

            var target = items
                .Where(item => !item.IsBuiltIn && validDeclarationTypes.Contains(item.DeclarationType))
                .SingleOrDefault(item => item.IsSelected(selection)
                                     || item.References.Any(r => r.IsSelected(selection)));

            if (target != null)
            {
                return target;
            }

            var targets = items
                .Where(item => !item.IsBuiltIn
                               && item.ComponentName == selection.QualifiedName.ComponentName
                               && validDeclarationTypes.Contains(item.DeclarationType));

            var currentSelection = new Selection(0, 0, int.MaxValue, int.MaxValue);

            foreach (var declaration in targets.Where(item => item.Context != null))
            {
                var activeSelection = new Selection(declaration.Context.Start.Line,
                                                    declaration.Context.Start.Column,
                                                    declaration.Context.Stop.Line,
                                                    declaration.Context.Stop.Column);

                if (currentSelection.Contains(activeSelection) && activeSelection.Contains(selection.Selection))
                {
                    target = declaration;
                    currentSelection = activeSelection;
                }

                foreach (var reference in declaration.References)
                {
                    var proc = (dynamic)reference.Context.Parent;
                    var paramList = proc ;

                    // This is to prevent throws when this statement fails:
                    // (VBAParser.ArgsCallContext)proc.argsCall();
                    var method = ((Type) proc.GetType()).GetMethod("argsCall");
                    if (method != null)
                    {
                        try { paramList = method.Invoke(proc, null); }
                        catch { continue; }
                    }

                    if (paramList == null) { continue; }

                    activeSelection = new Selection(paramList.Start.Line,
                                                    paramList.Start.Column,
                                                    paramList.Stop.Line,
                                                    paramList.Stop.Column + paramList.Stop.Text.Length + 1);

                    if (currentSelection.Contains(activeSelection) && activeSelection.Contains(selection.Selection))
                    {
                        target = reference.Declaration;
                        currentSelection = activeSelection;
                    }
                }
            }
            return target;
        }