Ejemplo n.º 1
0
        public object Search(string keyWord, int pageIndex, int pageSize)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            string      indexPath = Directory.GetCurrentDirectory() + "/Index";
            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
            IndexReader reader    = IndexReader.Open(directory, true);
            //创建IndexSearcher准备进行搜索。
            IndexSearcher searcher = new IndexSearcher(reader);

            // 查询条件
            keyWord = GetKeyWordsSplitBySpace(keyWord, new PanGuTokenizer());
            //创建QueryParser查询解析器。用来对查询语句进行语法分析。
            //QueryParser调用parser进行语法分析,形成查询语法树,放到Query中。
            QueryParser msgQueryParser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "Content", new PanGuAnalyzer(true));
            Query       msgQuery       = msgQueryParser.Parse(keyWord);
            //TopScoreDocCollector:盛放查询结果的容器
            //numHits 获取条数
            TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);

            //IndexSearcher调用search对查询语法树Query进行搜索,得到结果TopScoreDocCollector。
            // 使用query这个查询条件进行搜索,搜索结果放入collector
            searcher.Search(msgQuery, null, collector);
            // 从查询结果中取出第n条到第m条的数据
            ScoreDoc[] docs = collector.TopDocs(0, 1000).scoreDocs;
            stopwatch.Stop();
            // 遍历查询结果
            List <ReturnModel> resultList = new List <ReturnModel>();
            var pm = new Page <ReturnModel>
            {
                PageIndex = pageIndex,
                PageSize  = pageSize,
                TotalRows = docs.Length
            };

            pm.TotalPages = pm.TotalRows / pageSize;
            if (pm.TotalRows % pageSize != 0)
            {
                pm.TotalPages++;
            }
            for (int i = (pageIndex - 1) * pageSize; i < pageIndex * pageSize && i < docs.Length; i++)
            {
                var doc     = searcher.Doc(docs[i].doc);
                var content = HighlightHelper.HighLight(keyWord, doc.Get("Content"));
                var result  = new ReturnModel
                {
                    Title   = doc.Get("Title"),
                    Content = content,
                    Count   = Regex.Matches(content, "<font").Count
                };
                resultList.Add(result);
            }

            pm.LsList = resultList;
            var elapsedTime = stopwatch.ElapsedMilliseconds + "ms";
            var list        = new { list = pm, ms = elapsedTime };

            return(list);
        }
Ejemplo n.º 2
0
        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                var result = e.Result as BackgroundWorkerResult;

                if (result?.CodeItems == null)
                {
                    LogHelper.Log($"CodeNav for '{DocumentHelper.GetName(_window)}' updated, no results");
                    return;
                }

                // Filter all null items from the code document
                SyntaxMapper.FilterNullItems(result.CodeItems);

                // Do we need to update the DataContext?
                var areEqual = AreDocumentsEqual(CodeDocumentViewModel.CodeDocument, result.CodeItems);
                if (result.ForceUpdate == false && areEqual)
                {
                    LogHelper.Log($"CodeNav for '{DocumentHelper.GetName(_window)}' updated, document did not change");

                    // Should the margin be shown and are there any items to show, if not hide the margin
                    VisibilityHelper.SetMarginWidth(_column, CodeDocumentViewModel.CodeDocument);

                    return;
                }

                // Set the new list of codeitems as DataContext
                CodeDocumentViewModel.CodeDocument = result.CodeItems;
                _cache = result.CodeItems;

                // Set currently active codeitem
                HighlightHelper.SetForeground(CodeDocumentViewModel.CodeDocument);

                // Should the margin be shown and are there any items to show, if not hide the margin
                VisibilityHelper.SetMarginWidth(_column, CodeDocumentViewModel.CodeDocument);

                // Apply current visibility settings to the document
                VisibilityHelper.SetCodeItemVisibility(CodeDocumentViewModel.CodeDocument);

                // Sync all regions
                OutliningHelper.SyncAllRegions(OutliningManager, TextView, CodeDocumentViewModel.CodeDocument);

                // Sort items
                CodeDocumentViewModel.SortOrder = Settings.Default.SortOrder;
                SortHelper.Sort(CodeDocumentViewModel);

                // Apply bookmarks
                LoadBookmarksFromStorage();
                BookmarkHelper.ApplyBookmarks(CodeDocumentViewModel, Dte?.Solution?.FileName);

                LogHelper.Log($"CodeNav for '{DocumentHelper.GetName(_window)}' updated");
            }
            catch (ObjectDisposedException ex)
            {
                LogHelper.Log($"CodeNav: RunWorkerCompleted exception: {ex.Message}");
                LogHelper.Log("RunWorkerCompleted exception", ex);
            }
        }
Ejemplo n.º 3
0
        public void HighlightPattern(ICancellable cnc, Highlights highlights, string pattern, int selectionStart, int selectionEnd, Segment visibleSegment)
        {
            int par_size     = 1;
            int bracket_size = 1;

            Regex regex = GetCachedHighlightingRegex( );

            HighlightHelper.CommonHighlighting(cnc, highlights, pattern, selectionStart, selectionEnd, visibleSegment, regex, par_size, bracket_size);
        }
        public void HighlightCurrentItem()
        {
            System.Windows.Threading.Dispatcher.CurrentDispatcher.VerifyAccess();

            HighlightHelper.HighlightCurrentItem(_window, CodeDocumentViewModel);

            // Force NotifyPropertyChanged
            CodeDocumentViewModel.CodeDocumentTop = null;
        }
Ejemplo n.º 5
0
        public void HighlightHelper_DateTime_Tests()
        {
            bool shouldHighlight = false;

            shouldHighlight = HighlightHelper.IsHighlighted(new DateTime(2016, 7, 13));
            shouldHighlight.Should().BeFalse();

            shouldHighlight = HighlightHelper.IsHighlighted(new DateTime(2016, 7, 14));
            shouldHighlight.Should().BeTrue();
        }
Ejemplo n.º 6
0
        public void HighlightHelper_Int_Tests()
        {
            bool shouldHighlight = false;

            shouldHighlight = HighlightHelper.IsHighlighted(3);
            shouldHighlight.Should().BeFalse();

            shouldHighlight = HighlightHelper.IsHighlighted(14);
            shouldHighlight.Should().BeTrue();
        }
Ejemplo n.º 7
0
        public void HighlightPattern(ICancellable cnc, Highlights highlights, string pattern, int selectionStart, int selectionEnd, Segment visibleSegment)
        {
            var helper = OptionsControl.CreateOnigurumaHelper( );

            int par_size     = helper.IsONIG_SYN_OP_ESC_LPAREN_SUBEXP ? 2 : 1;
            int bracket_size = 1;

            Regex regex = GetCachedHighlightingRegex(helper);

            HighlightHelper.CommonHighlighting(cnc, highlights, pattern, selectionStart, selectionEnd, visibleSegment, regex, par_size, bracket_size);
        }
Ejemplo n.º 8
0
        public void OnlyOneItemShouldBeHighlighted()
        {
            var document = SyntaxMapper.MapDocument(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\Files\\TestProperties.cs"));

            HighlightHelper.HighlightCurrentItem(document, 13, Brushes.Red, Brushes.Blue, Brushes.Green, Brushes.White);

            HighlightHelper.HighlightCurrentItem(document, 18, Brushes.Red, Brushes.Blue, Brushes.Green, Brushes.White);


            var highlightedItems = new List <CodeItem>();

            FindHighlightedItems(highlightedItems, document);

            Assert.AreEqual(1, highlightedItems.Count);
        }
Ejemplo n.º 9
0
        public void CurrentItemShouldBeHighlighted()
        {
            var document = SyntaxMapper.MapDocument(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\Files\\TestProperties.cs"));

            HighlightHelper.HighlightCurrentItem(document, 13, Brushes.Red, Brushes.Blue, Brushes.Green, Brushes.White);

            var highlightedClass = (document.First() as IMembers).Members.First() as CodeClassItem;
            var highlightedItem  = highlightedClass.Members[2];

            Assert.AreEqual(FontWeights.Bold, highlightedItem.FontWeight);
            Assert.AreEqual(Brushes.Red, highlightedItem.Foreground);
            Assert.AreEqual(Brushes.Blue, highlightedItem.HighlightBackground);

            Assert.AreEqual(Brushes.Green, highlightedClass.BorderBrush);
        }
Ejemplo n.º 10
0
        public void HighlightPattern(ICancellable cnc, Highlights highlights, string pattern, int selectionStart, int selectionEnd, Segment visibleSegment)
        {
            GrammarEnum grammar      = OptionsControl.GetGrammar( );
            int         par_size     = 1;
            int         bracket_size = 1;

            if (grammar == GrammarEnum.basic ||
                grammar == GrammarEnum.grep)
            {
                par_size = 2;
            }

            var regex = GetCachedHighlightingRegex(grammar);

            HighlightHelper.CommonHighlighting(cnc, highlights, pattern, selectionStart, selectionEnd, visibleSegment, regex, par_size, bracket_size);
        }
        /// <summary>
        /// 获取搜索结果
        /// </summary>
        protected void btnGetSearchResult_Click(object sender, EventArgs e)
        {
            string keyword = txtKeyWords.Text;

            string        indexPath = Context.Server.MapPath("~/Index"); // 索引文档保存位置
            FSDirectory   directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
            IndexReader   reader    = IndexReader.Open(directory, true);
            IndexSearcher searcher  = new IndexSearcher(reader);
            // 查询条件
            PhraseQuery query = new PhraseQuery();

            // 等同于 where contains("msg",kw)
            query.Add(new Term("msg", keyword));
            // 两个词的距离大于100(经验值)就不放入搜索结果,因为距离太远相关度就不高了
            query.SetSlop(100);
            // TopScoreDocCollector:盛放查询结果的容器
            TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);

            // 使用query这个查询条件进行搜索,搜索结果放入collector
            searcher.Search(query, null, collector);
            // 从查询结果中取出第m条到第n条的数据
            // collector.GetTotalHits()表示总的结果条数
            ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs;
            // 遍历查询结果
            IList <SearchResult> resultList = new List <SearchResult>();

            for (int i = 0; i < docs.Length; i++)
            {
                // 拿到文档的id,因为Document可能非常占内存(DataSet和DataReader的区别)
                int docId = docs[i].doc;
                // 所以查询结果中只有id,具体内容需要二次查询
                // 根据id查询内容:放进去的是Document,查出来的还是Document
                Document     doc    = searcher.Doc(docId);
                SearchResult result = new SearchResult();
                result.Id  = Convert.ToInt32(doc.Get("id"));
                result.Msg = HighlightHelper.HighLight(keyword, doc.Get("msg"));

                resultList.Add(result);
            }

            // 绑定到Repeater
            rptSearchResult.DataSource = resultList;
            rptSearchResult.DataBind();
        }
Ejemplo n.º 12
0
        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var result = e.Result as BackgroundWorkerResult;

            if (result?.CodeItems == null)
            {
                LogHelper.Log($"CodeNav for '{_window.Document.Name}' updated, no results");
                return;
            }

            // Filter all null items from the code document
            SyntaxMapper.FilterNullItems(result.CodeItems);

            // Do we need to update the DataContext?
            var areEqual = AreDocumentsEqual(CodeDocumentViewModel.CodeDocument, result.CodeItems);

            if (result.ForceUpdate == false && areEqual)
            {
                LogHelper.Log($"CodeNav for '{_window.Document.Name}' updated, document did not change");
                return;
            }

            // Set the new list of codeitems as DataContext
            CodeDocumentViewModel.CodeDocument = result.CodeItems;
            _cache = result.CodeItems;

            // Set currently active codeitem
            HighlightHelper.SetForeground(CodeDocumentViewModel.CodeDocument);

            // Are there any items to show, if not hide the margin
            VisibilityHelper.SetMarginWidth(_column, CodeDocumentViewModel.CodeDocument);

            // Apply current visibility settings to the document
            VisibilityHelper.SetCodeItemVisibility(CodeDocumentViewModel.CodeDocument);

            // Sync all regions
            OutliningHelper.SyncAllRegions(_outliningManager, _textView, CodeDocumentViewModel.CodeDocument);

            LogHelper.Log($"CodeNav for '{_window.Document.Name}' updated");
        }
Ejemplo n.º 13
0
        public void HighlightPattern(ICancellable cnc, Highlights highlights, string pattern, int selectionStart, int selectionEnd, Segment visibleSegment)
        {
            GrammarEnum grammar = OptionsControl.GetGrammar( );
            bool        mod_x   = OptionsControl.GetModX( );

            int par_size     = 1;
            int bracket_size = 1;

            bool is_POSIX_basic =
                grammar == GrammarEnum.basic ||
                grammar == GrammarEnum.sed ||
                grammar == GrammarEnum.grep ||
                grammar == GrammarEnum.emacs;

            if (is_POSIX_basic)
            {
                par_size = 2;
            }

            Regex regex = GetCachedHighlightingRegex(grammar, mod_x);

            HighlightHelper.CommonHighlighting(cnc, highlights, pattern, selectionStart, selectionEnd, visibleSegment, regex, par_size, bracket_size);
        }
        public async Task UpdateDocumentAsync(bool forceUpdate = false)
        {
            await Microsoft.VisualStudio.Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var activeDocument = DocumentHelper.GetActiveDocument(Dte);

            if (activeDocument == null)
            {
                return;
            }

            CodeDocumentViewModel.FilePath = activeDocument.FullName;

            // Do we need to change the side where the margin is displayed
            if (_margin?.MarginSide != null &&
                _margin?.MarginSide != Settings.Default.MarginSide &&
                Dte != null)
            {
                var filename = activeDocument.FullName;
                Dte.ExecuteCommand("File.Close");
                Dte.ExecuteCommand("File.OpenFile", filename);
            }

            try
            {
                if (forceUpdate)
                {
                    _cache = null;
                    CodeDocumentViewModel.CodeDocument.Clear();
                }

                // Do we have a cached version of this document
                if (_cache != null)
                {
                    CodeDocumentViewModel.CodeDocument = _cache;
                }

                // If not show a loading item
                if (!CodeDocumentViewModel.CodeDocument.Any())
                {
                    CodeDocumentViewModel.CodeDocument = CreateLoadingItem();
                }

                var codeItems = await SyntaxMapper.MapDocumentAsync(activeDocument, this, _workspace);

                if (codeItems == null)
                {
                    // CodeNav for document updated, no results
                    return;
                }

                // Filter all null items from the code document
                SyntaxMapper.FilterNullItems(codeItems);

                // Sort items
                CodeDocumentViewModel.SortOrder = Settings.Default.SortOrder;
                SortHelper.Sort(codeItems, Settings.Default.SortOrder);

                // Set currently active codeitem
                HighlightHelper.SetForeground(codeItems);

                // Set the new list of codeitems as DataContext
                CodeDocumentViewModel.CodeDocument = codeItems;
                _cache = codeItems;

                // Apply current visibility settings to the document
                VisibilityHelper.SetCodeItemVisibility(CodeDocumentViewModel);

                // Apply bookmarks
                LoadBookmarksFromStorage();
                BookmarkHelper.ApplyBookmarks(CodeDocumentViewModel, Dte?.Solution?.FileName);

                // Apply history items
                LoadHistoryItemsFromStorage();
                HistoryHelper.ApplyHistoryIndicator(CodeDocumentViewModel);
            }
            catch (Exception e)
            {
                LogHelper.Log("Error running UpdateDocument", e);
            }

            try
            {
                // Sync all regions
                OutliningHelper.SyncAllRegions(OutliningManagerService, TextView, CodeDocumentViewModel.CodeDocument);

                // Should the margin be shown and are there any items to show, if not hide the margin
                VisibilityHelper.SetMarginHeight(_row, CodeDocumentViewModel.CodeDocument);
            }
            catch (Exception e)
            {
                LogHelper.Log("Error finishing UpdateDocument", e);
            }
        }
Ejemplo n.º 15
0
 public void HighlightCurrentItem()
 {
     System.Windows.Threading.Dispatcher.CurrentDispatcher.VerifyAccess();
     HighlightHelper.HighlightCurrentItem(_window, CodeDocumentViewModel);
 }
 private void Highlight(IButton button, ButtonEventData eventData, Slot s)
 {
     HighlightHelper.FlashHighlight(s, null, HighlightColor, HighlightDuration);
 }
Ejemplo n.º 17
0
        private void BindSearchResult(string keyword, int startIndex, int pageSize, out int totalCount)
        {
            string        indexPath = Context.Server.MapPath("~/Index"); // 索引文档保存位置
            FSDirectory   directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
            IndexReader   reader    = IndexReader.Open(directory, true);
            IndexSearcher searcher  = new IndexSearcher(reader);

            #region v1.0 单条件查询
            //// 查询条件
            //PhraseQuery query = new PhraseQuery();
            //// 分词后加入查询
            //IEnumerable<string> keyList = SplitHelper.SplitWords(keyword);
            //foreach (var key in keyList)
            //{
            //    query.Add(new Term("msg", key));
            //}
            //// 两个词的距离大于100(经验值)就不放入搜索结果,因为距离太远相关度就不高了
            //query.SetSlop(100);
            #endregion

            #region v2.0 多条件查询
            IEnumerable <string> keyList = SplitHelper.SplitWords(keyword);

            PhraseQuery queryTitle = new PhraseQuery();
            foreach (var key in keyList)
            {
                queryTitle.Add(new Term("title", key));
            }
            queryTitle.SetSlop(100);

            PhraseQuery queryMsg = new PhraseQuery();
            foreach (var key in keyList)
            {
                queryMsg.Add(new Term("msg", key));
            }
            queryMsg.SetSlop(100);

            BooleanQuery query = new BooleanQuery();
            query.Add(queryTitle, BooleanClause.Occur.SHOULD); // SHOULD => 可以有,但不是必须的
            query.Add(queryTitle, BooleanClause.Occur.SHOULD); // SHOULD => 可以有,但不是必须的
            #endregion

            // TopScoreDocCollector:盛放查询结果的容器
            TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);
            // 使用query这个查询条件进行搜索,搜索结果放入collector
            searcher.Search(query, null, collector);
            // 首先获取总条数
            totalCount = collector.GetTotalHits();
            // 从查询结果中取出第m条到第n条的数据
            ScoreDoc[] docs = collector.TopDocs(startIndex, pageSize).scoreDocs;
            // 遍历查询结果
            IList <SearchResult> resultList = new List <SearchResult>();
            for (int i = 0; i < docs.Length; i++)
            {
                // 拿到文档的id,因为Document可能非常占内存(DataSet和DataReader的区别)
                int docId = docs[i].doc;
                // 所以查询结果中只有id,具体内容需要二次查询
                // 根据id查询内容:放进去的是Document,查出来的还是Document
                Document     doc    = searcher.Doc(docId);
                SearchResult result = new SearchResult();
                result.Url   = "ViewArticle.aspx?id=" + doc.Get("id");
                result.Title = HighlightHelper.HighLight(keyword, doc.Get("title"));
                result.Msg   = HighlightHelper.HighLight(keyword, doc.Get("msg")) + "......";

                resultList.Add(result);
            }

            // 绑定到Repeater
            rptSearchResult.DataSource = resultList;
            rptSearchResult.DataBind();
        }
Ejemplo n.º 18
0
 public void HighlightCurrentItem() => HighlightHelper.HighlightCurrentItem(_window, CodeDocumentViewModel);