tdf#147583 sw find: fix backwards search for emptyPara/endOfPara
[LibreOffice.git] / sw / source / core / crsr / findtxt.cxx
blobe87e4d6ff5c1580e40f4870d7f08b83bf6dc2055
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <memory>
22 #include <com/sun/star/util/SearchFlags.hpp>
23 #include <com/sun/star/util/SearchResult.hpp>
24 #include <comphelper/lok.hxx>
25 #include <o3tl/safeint.hxx>
26 #include <rtl/ustrbuf.hxx>
27 #include <svx/svdview.hxx>
28 #include <svl/srchitem.hxx>
29 #include <sfx2/sfxsids.hrc>
30 #include <editeng/outliner.hxx>
31 #include <osl/diagnose.h>
33 #include <wrtsh.hxx>
34 #include <txatritr.hxx>
35 #include <fldbas.hxx>
36 #include <fmtfld.hxx>
37 #include <txtfld.hxx>
38 #include <txtfrm.hxx>
39 #include <rootfrm.hxx>
40 #include <swcrsr.hxx>
41 #include <redline.hxx>
42 #include <doc.hxx>
43 #include <IDocumentUndoRedo.hxx>
44 #include <IDocumentState.hxx>
45 #include <IDocumentDrawModelAccess.hxx>
46 #include <IDocumentRedlineAccess.hxx>
47 #include <dcontact.hxx>
48 #include <pamtyp.hxx>
49 #include <ndtxt.hxx>
50 #include <swundo.hxx>
51 #include <UndoInsert.hxx>
52 #include <breakit.hxx>
53 #include <docsh.hxx>
54 #include <PostItMgr.hxx>
55 #include <view.hxx>
57 using namespace ::com::sun::star;
58 using namespace util;
60 namespace {
62 /// because the Find may be called on the View or the Model, we need an index
63 /// afflicted by multiple personality disorder
64 struct AmbiguousIndex
66 private:
67 sal_Int32 m_value;
69 #ifndef NDEBUG
70 enum class tags : char { Any, Frame, Model };
71 tags m_tag;
72 #endif
74 public:
75 AmbiguousIndex() : m_value(-1)
76 #ifndef NDEBUG
77 , m_tag(tags::Any)
78 #endif
80 explicit AmbiguousIndex(sal_Int32 const value
81 #ifndef NDEBUG
82 , tags const tag
83 #endif
84 ) : m_value(value)
85 #ifndef NDEBUG
86 , m_tag(tag)
87 #endif
90 sal_Int32 & GetAnyIndex() { return m_value; } ///< for arithmetic
91 sal_Int32 const& GetAnyIndex() const { return m_value; } ///< for arithmetic
92 TextFrameIndex GetFrameIndex() const
94 assert(m_tag != tags::Model);
95 return TextFrameIndex(m_value);
97 sal_Int32 GetModelIndex() const
99 assert(m_tag != tags::Frame);
100 return m_value;
102 void SetFrameIndex(TextFrameIndex const value)
104 #ifndef NDEBUG
105 m_tag = tags::Frame;
106 #endif
107 m_value = sal_Int32(value);
109 void SetModelIndex(sal_Int32 const value)
111 #ifndef NDEBUG
112 m_tag = tags::Model;
113 #endif
114 m_value = value;
117 bool operator ==(AmbiguousIndex const& rOther) const
119 assert(m_tag == tags::Any || rOther.m_tag == tags::Any || m_tag == rOther.m_tag);
120 return m_value == rOther.m_value;
122 bool operator <=(AmbiguousIndex const& rOther) const
124 assert(m_tag == tags::Any || rOther.m_tag == tags::Any || m_tag == rOther.m_tag);
125 return m_value <= rOther.m_value;
127 bool operator < (AmbiguousIndex const& rOther) const
129 assert(m_tag == tags::Any || rOther.m_tag == tags::Any || m_tag == rOther.m_tag);
130 return m_value < rOther.m_value;
132 AmbiguousIndex operator - (AmbiguousIndex const& rOther) const
134 assert(m_tag == tags::Any || rOther.m_tag == tags::Any || m_tag == rOther.m_tag);
135 return AmbiguousIndex(m_value - rOther.m_value
136 #ifndef NDEBUG
137 , std::max(m_tag, rOther.m_tag)
138 #endif
143 class MaybeMergedIter
145 std::optional<sw::MergedAttrIter> m_oMergedIter;
146 SwTextNode const*const m_pNode;
147 size_t m_HintIndex;
149 public:
150 MaybeMergedIter(SwTextFrame const*const pFrame, SwTextNode const*const pNode)
151 : m_pNode(pNode)
152 , m_HintIndex(0)
154 if (pFrame)
156 m_oMergedIter.emplace(*pFrame);
160 SwTextAttr const* NextAttr(SwTextNode const*& rpNode)
162 if (m_oMergedIter)
164 return m_oMergedIter->NextAttr(&rpNode);
166 if (SwpHints const*const pHints = m_pNode->GetpSwpHints())
168 if (m_HintIndex < pHints->Count())
170 rpNode = m_pNode;
171 return pHints->Get(m_HintIndex++);
174 return nullptr;
180 static OUString
181 lcl_CleanStr(const SwTextNode& rNd,
182 SwTextFrame const*const pFrame,
183 SwRootFrame const*const pLayout,
184 AmbiguousIndex const nStart, AmbiguousIndex & rEnd,
185 std::vector<AmbiguousIndex> &rArr,
186 bool const bRemoveSoftHyphen, bool const bRemoveCommentAnchors)
188 OUStringBuffer buf(pLayout ? pFrame->GetText() : rNd.GetText());
189 rArr.clear();
191 MaybeMergedIter iter(pLayout ? pFrame : nullptr, pLayout ? nullptr : &rNd);
193 AmbiguousIndex nSoftHyphen = nStart;
194 AmbiguousIndex nHintStart;
195 bool bNewHint = true;
196 bool bNewSoftHyphen = true;
197 const AmbiguousIndex nEnd = rEnd;
198 std::vector<AmbiguousIndex> aReplaced;
199 SwTextNode const* pNextHintNode(nullptr);
200 SwTextAttr const* pNextHint(iter.NextAttr(pNextHintNode));
204 if ( bNewHint )
206 if (pLayout)
208 nHintStart.SetFrameIndex(pNextHint
209 ? pFrame->MapModelToView(pNextHintNode, pNextHint->GetStart())
210 : TextFrameIndex(-1));
212 else
214 nHintStart.SetModelIndex(pNextHint ? pNextHint->GetStart() : -1);
218 if ( bNewSoftHyphen )
220 if (pLayout)
222 nSoftHyphen.SetFrameIndex(TextFrameIndex(bRemoveSoftHyphen
223 ? pFrame->GetText().indexOf(CHAR_SOFTHYPHEN, nSoftHyphen.GetAnyIndex())
224 : -1));
226 else
228 nSoftHyphen.SetModelIndex(bRemoveSoftHyphen
229 ? rNd.GetText().indexOf(CHAR_SOFTHYPHEN, nSoftHyphen.GetAnyIndex())
230 : -1);
234 bNewHint = false;
235 bNewSoftHyphen = false;
236 AmbiguousIndex nStt;
238 // Check if next stop is a hint.
239 if (0 <= nHintStart.GetAnyIndex()
240 && (-1 == nSoftHyphen.GetAnyIndex() || nHintStart < nSoftHyphen)
241 && nHintStart < nEnd )
243 nStt = nHintStart;
244 bNewHint = true;
246 // Check if next stop is a soft hyphen.
247 else if ( -1 != nSoftHyphen.GetAnyIndex()
248 && (-1 == nHintStart.GetAnyIndex() || nSoftHyphen < nHintStart)
249 && nSoftHyphen < nEnd)
251 nStt = nSoftHyphen;
252 bNewSoftHyphen = true;
254 // If nSoftHyphen == nHintStart, the current hint *must* be a hint with an end.
255 else if (-1 != nSoftHyphen.GetAnyIndex() && nSoftHyphen == nHintStart)
257 nStt = nSoftHyphen;
258 bNewHint = true;
259 bNewSoftHyphen = true;
261 else
262 break;
264 AmbiguousIndex nCurrent(nStt);
265 nCurrent.GetAnyIndex() -= rArr.size();
267 if ( bNewHint )
269 if (pNextHint && pNextHint->HasDummyChar() && (nStart <= nStt))
271 switch (pNextHint->Which())
273 case RES_TXTATR_FLYCNT:
274 case RES_TXTATR_FIELD:
275 case RES_TXTATR_REFMARK:
276 case RES_TXTATR_TOXMARK:
277 case RES_TXTATR_META:
278 case RES_TXTATR_METAFIELD:
280 // (1998) they are desired as separators and
281 // belong not any longer to a word.
282 // they should also be ignored at a
283 // beginning/end of a sentence if blank. Those are
284 // simply removed if first. If at the end, we keep the
285 // replacement and remove afterwards all at a string's
286 // end (might be normal 0x7f).
287 const bool bEmpty = pNextHint->Which() != RES_TXTATR_FIELD
288 || (static_txtattr_cast<SwTextField const*>(pNextHint)->GetFormatField().GetField()->ExpandField(true, pLayout).isEmpty());
289 if ( bEmpty && nStart == nCurrent )
291 rArr.push_back( nCurrent );
292 if (rEnd.GetAnyIndex() > nCurrent.GetAnyIndex())
294 --rEnd.GetAnyIndex();
296 buf.remove(nCurrent.GetAnyIndex(), 1);
298 else
300 if ( bEmpty )
301 aReplaced.push_back( nCurrent );
302 buf[nCurrent.GetAnyIndex()] = '\x7f';
305 break;
306 case RES_TXTATR_ANNOTATION:
308 if( bRemoveCommentAnchors )
310 rArr.push_back( nCurrent );
311 if (rEnd.GetAnyIndex() > nCurrent.GetAnyIndex())
313 --rEnd.GetAnyIndex();
315 buf.remove( nCurrent.GetAnyIndex(), 1 );
318 break;
319 default:
320 OSL_FAIL( "unknown case in lcl_CleanStr" );
321 break;
324 pNextHint = iter.NextAttr(pNextHintNode);
327 if ( bNewSoftHyphen )
329 rArr.push_back( nCurrent );
331 // If the soft hyphen to be removed is past the end of the range we're searching in,
332 // don't adjust the end.
333 if (rEnd.GetAnyIndex() > nCurrent.GetAnyIndex())
335 --rEnd.GetAnyIndex();
338 buf.remove(nCurrent.GetAnyIndex(), 1);
339 ++nSoftHyphen.GetAnyIndex();
342 while ( true );
344 for (auto i = aReplaced.size(); i; )
346 const AmbiguousIndex nTmp = aReplaced[ --i ];
347 if (nTmp.GetAnyIndex() == buf.getLength() - 1)
349 buf.truncate(nTmp.GetAnyIndex());
350 rArr.push_back( nTmp );
351 --rEnd.GetAnyIndex();
355 return buf.makeStringAndClear();
358 static bool DoSearch(SwPaM & rSearchPam,
359 const i18nutil::SearchOptions2& rSearchOpt, utl::TextSearch& rSText,
360 SwMoveFnCollection const & fnMove,
361 bool bSrchForward, bool bRegSearch, bool bChkEmptyPara, bool bChkParaEnd,
362 AmbiguousIndex & nStart, AmbiguousIndex & nEnd, AmbiguousIndex nTextLen,
363 SwTextNode const* pNode, SwTextFrame const* pTextFrame,
364 SwRootFrame const* pLayout, SwPaM* pPam);
366 namespace sw {
368 // @param xSearchItem allocate in parent so we can do so outside the calling loop
369 bool FindTextImpl(SwPaM & rSearchPam,
370 const i18nutil::SearchOptions2& rSearchOpt, bool bSearchInNotes,
371 utl::TextSearch& rSText,
372 SwMoveFnCollection const & fnMove, const SwPaM & rRegion,
373 bool bInReadOnly, SwRootFrame const*const pLayout,
374 std::unique_ptr<SvxSearchItem>& xSearchItem)
376 if( rSearchOpt.searchString.isEmpty() )
377 return false;
379 std::optional<SwPaM> oPam;
380 sw::MakeRegion(fnMove, rRegion, oPam);
381 const bool bSrchForward = &fnMove == &fnMoveForward;
382 SwPosition& rPtPos = *oPam->GetPoint();
384 // If bFound is true then the string was found and is between nStart and nEnd
385 bool bFound = false;
386 // start position in text or initial position
387 bool bFirst = true;
388 SwContentNode * pNode;
390 const bool bRegSearch = SearchAlgorithms2::REGEXP == rSearchOpt.AlgorithmType2;
391 const bool bChkEmptyPara = bRegSearch && 2 == rSearchOpt.searchString.getLength() &&
392 ( rSearchOpt.searchString == "^$" ||
393 rSearchOpt.searchString == "$^" );
394 const bool bChkParaEnd = bRegSearch && rSearchOpt.searchString == "$";
396 if (!xSearchItem)
398 xSearchItem.reset(new SvxSearchItem(SID_SEARCH_ITEM)); // this is a very expensive operation (calling configmgr etc.)
399 xSearchItem->SetSearchOptions(rSearchOpt);
400 xSearchItem->SetBackward(!bSrchForward);
403 // LanguageType eLastLang = 0;
404 while (nullptr != (pNode = ::GetNode(*oPam, bFirst, fnMove, bInReadOnly, pLayout)))
406 if( pNode->IsTextNode() )
408 SwTextNode& rTextNode = *pNode->GetTextNode();
409 SwTextFrame const*const pFrame(pLayout
410 ? static_cast<SwTextFrame const*>(rTextNode.getLayoutFrame(pLayout))
411 : nullptr);
412 assert(!pLayout || pFrame);
413 AmbiguousIndex nTextLen;
414 if (pLayout)
416 nTextLen.SetFrameIndex(TextFrameIndex(pFrame->GetText().getLength()));
418 else
420 nTextLen.SetModelIndex(rTextNode.GetText().getLength());
422 AmbiguousIndex nEnd;
423 if (pLayout
424 ? FrameContainsNode(*pFrame, oPam->GetMark()->GetNodeIndex())
425 : rPtPos.GetNode() == oPam->GetMark()->GetNode())
427 if (pLayout)
429 nEnd.SetFrameIndex(pFrame->MapModelToViewPos(*oPam->GetMark()));
431 else
433 nEnd.SetModelIndex(oPam->GetMark()->GetContentIndex());
436 else
438 if (bSrchForward)
440 nEnd = nTextLen;
442 else
444 if (pLayout)
446 nEnd.SetFrameIndex(TextFrameIndex(0));
448 else
450 nEnd.SetModelIndex(0);
454 AmbiguousIndex nStart;
455 if (pLayout)
457 nStart.SetFrameIndex(pFrame->MapModelToViewPos(*oPam->GetPoint()));
459 else
461 nStart.SetModelIndex(rPtPos.GetContentIndex());
464 /* #i80135# */
465 // if there are SwPostItFields inside our current node text, we
466 // split the text into separate pieces and search for text inside
467 // the pieces as well as inside the fields
468 MaybeMergedIter iter(pLayout ? pFrame : nullptr, pLayout ? nullptr : &rTextNode);
470 // count PostItFields by looping over all fields
471 std::vector<std::pair<SwTextAttr const*, AmbiguousIndex>> postits;
472 if (bSearchInNotes)
474 if (!bSrchForward)
476 std::swap(nStart, nEnd);
479 SwTextNode const* pTemp(nullptr);
480 while (SwTextAttr const*const pTextAttr = iter.NextAttr(pTemp))
482 if ( pTextAttr->Which()==RES_TXTATR_ANNOTATION )
484 AmbiguousIndex aPos;
485 aPos.SetModelIndex(pTextAttr->GetStart());
486 if (pLayout)
488 aPos.SetFrameIndex(pFrame->MapModelToView(pTemp, aPos.GetModelIndex()));
490 if ((nStart <= aPos) && (aPos <= nEnd))
492 postits.emplace_back(pTextAttr, aPos);
497 if (!bSrchForward)
499 std::swap(nStart, nEnd);
504 SwDocShell *const pDocShell = pNode->GetDoc().GetDocShell();
505 SwWrtShell *const pWrtShell = pDocShell ? pDocShell->GetWrtShell() : nullptr;
506 SwPostItMgr *const pPostItMgr = pWrtShell ? pWrtShell->GetPostItMgr() : nullptr;
508 // If there is an active text edit, then search there.
509 bool bEndedTextEdit = false;
510 SdrView* pSdrView = pWrtShell ? pWrtShell->GetDrawView() : nullptr;
511 if (pSdrView)
513 // If the edited object is not anchored to this node, then ignore it.
514 SdrObject* pObject = pSdrView->GetTextEditObject();
515 if (pObject)
517 if (SwFrameFormat* pFrameFormat = FindFrameFormat(pObject))
519 const SwNode* pAnchorNode = pFrameFormat->GetAnchor().GetAnchorNode();
520 if (!pAnchorNode || (pLayout
521 ? !FrameContainsNode(*pFrame, pAnchorNode->GetIndex())
522 : pAnchorNode->GetIndex() != pNode->GetIndex()))
523 pObject = nullptr;
527 if (pObject)
529 sal_uInt16 nResult = pSdrView->GetTextEditOutlinerView()->StartSearchAndReplace(*xSearchItem);
530 if (!nResult)
532 // If not found, end the text edit.
533 pSdrView->SdrEndTextEdit();
534 const Point aPoint(pSdrView->GetAllMarkedRect().TopLeft());
535 pSdrView->UnmarkAll();
536 pWrtShell->CallSetCursor(&aPoint, true);
537 pWrtShell->Edit();
538 bEndedTextEdit = true;
540 else
542 bFound = true;
543 break;
548 if (comphelper::LibreOfficeKit::isActive())
550 // Writer and editeng selections are not supported in parallel.
551 SvxSearchItem* pSearchItem = SwView::GetSearchItem();
552 // If we just finished search in shape text, don't attempt to do that again.
553 if (!bEndedTextEdit && !(pSearchItem && pSearchItem->GetCommand() == SvxSearchCmd::FIND_ALL))
555 // If there are any shapes anchored to this node, search there.
556 SwPaM aPaM(pNode->GetDoc().GetNodes().GetEndOfContent());
557 if (pLayout)
559 *aPaM.GetPoint() = pFrame->MapViewToModelPos(nStart.GetFrameIndex());
561 else
563 aPaM.GetPoint()->Assign(rTextNode, nStart.GetModelIndex());
565 aPaM.SetMark();
566 if (pLayout)
568 aPaM.GetMark()->Assign( (pFrame->GetMergedPara()
569 ? *pFrame->GetMergedPara()->pLastNode
570 : rTextNode)
571 .GetIndex() + 1 );
573 else
575 aPaM.GetMark()->Assign( rTextNode.GetIndex() + 1 );
577 if (pNode->GetDoc().getIDocumentDrawModelAccess().Search(aPaM, *xSearchItem) && pSdrView)
579 if (SdrObject* pObject = pSdrView->GetTextEditObject())
581 if (SwFrameFormat* pFrameFormat = FindFrameFormat(pObject))
583 const SwNode* pAnchorNode = pFrameFormat->GetAnchor().GetAnchorNode();
584 if (pAnchorNode)
586 // Set search position to the shape's anchor point.
587 rSearchPam.GetPoint()->Assign(*pAnchorNode);
588 rSearchPam.SetMark();
589 bFound = true;
590 break;
598 // do we need to finish a note?
599 if (pPostItMgr && pPostItMgr->HasActiveSidebarWin())
601 if (bSearchInNotes)
603 if (!postits.empty())
605 if (bSrchForward)
607 postits.erase(postits.begin());
609 else
611 postits.pop_back(); // hope that's the right one?
614 //search inside, finish and put focus back into the doc
615 if (pPostItMgr->FinishSearchReplace(rSearchOpt,bSrchForward))
617 bFound = true ;
618 break;
621 else
623 pPostItMgr->SetActiveSidebarWin(nullptr);
627 if (!postits.empty())
629 // now we have to split
630 AmbiguousIndex nStartInside;
631 AmbiguousIndex nEndInside;
632 sal_Int32 aLoop = bSrchForward ? 0 : postits.size();
634 while ((0 <= aLoop) && (o3tl::make_unsigned(aLoop) <= postits.size()))
636 if (bSrchForward)
638 if (aLoop == 0)
640 nStartInside = nStart;
642 else if (pLayout)
644 nStartInside.SetFrameIndex(postits[aLoop - 1].second.GetFrameIndex() + TextFrameIndex(1));
646 else
648 nStartInside.SetModelIndex(postits[aLoop - 1].second.GetModelIndex() + 1);
650 nEndInside = static_cast<size_t>(aLoop) == postits.size()
651 ? nEnd
652 : postits[aLoop].second;
653 nTextLen = nEndInside - nStartInside;
655 else
657 nStartInside = static_cast<size_t>(aLoop) == postits.size()
658 ? nStart
659 : postits[aLoop].second;
660 if (aLoop == 0)
662 nEndInside = nEnd;
664 else if (pLayout)
666 nEndInside.SetFrameIndex(postits[aLoop - 1].second.GetFrameIndex() + TextFrameIndex(1));
668 else
670 nEndInside.SetModelIndex(postits[aLoop - 1].second.GetModelIndex() + 1);
672 nTextLen = nStartInside - nEndInside;
674 // search inside the text between a note
675 bFound = DoSearch( rSearchPam,
676 rSearchOpt, rSText, fnMove, bSrchForward,
677 bRegSearch, bChkEmptyPara, bChkParaEnd,
678 nStartInside, nEndInside, nTextLen,
679 pNode->GetTextNode(), pFrame, pLayout,
680 oPam ? &*oPam : nullptr );
681 if ( bFound )
682 break;
683 else
685 // we should now be right in front of a note, search inside
686 if (bSrchForward
687 ? (static_cast<size_t>(aLoop) != postits.size())
688 : (aLoop != 0))
690 const SwTextAttr *const pTextAttr = bSrchForward
691 ? postits[aLoop].first
692 : postits[aLoop - 1].first;
693 if (pPostItMgr && pPostItMgr->SearchReplace(
694 static_txtattr_cast<SwTextField const*>(pTextAttr)->GetFormatField(),rSearchOpt,bSrchForward))
696 bFound = true ;
697 break;
701 aLoop = bSrchForward ? aLoop+1 : aLoop-1;
704 else
706 // if there is no SwPostItField inside or searching inside notes
707 // is disabled, we search the whole length just like before
708 bFound = DoSearch( rSearchPam,
709 rSearchOpt, rSText, fnMove, bSrchForward,
710 bRegSearch, bChkEmptyPara, bChkParaEnd,
711 nStart, nEnd, nTextLen,
712 pNode->GetTextNode(), pFrame, pLayout,
713 oPam ? &*oPam : nullptr );
715 if (bFound)
716 break;
719 return bFound;
722 } // namespace sw
724 bool DoSearch(SwPaM & rSearchPam,
725 const i18nutil::SearchOptions2& rSearchOpt, utl::TextSearch& rSText,
726 SwMoveFnCollection const & fnMove, bool bSrchForward, bool bRegSearch,
727 bool bChkEmptyPara, bool bChkParaEnd,
728 AmbiguousIndex & nStart, AmbiguousIndex & nEnd, AmbiguousIndex const nTextLen,
729 SwTextNode const*const pNode, SwTextFrame const*const pFrame,
730 SwRootFrame const*const pLayout, SwPaM* pPam)
732 bool bFound = false;
733 OUString sCleanStr;
734 std::vector<AmbiguousIndex> aFltArr;
735 LanguageType eLastLang = LANGUAGE_SYSTEM;
736 // if the search string contains a soft hyphen,
737 // we don't strip them from the text:
738 bool bRemoveSoftHyphens = true;
739 // if the search string contains a comment, we don't strip them from the text
740 const bool bRemoveCommentAnchors = rSearchOpt.searchString.indexOf( CH_TXTATR_INWORD ) == -1;
742 if ( bRegSearch )
744 if ( -1 != rSearchOpt.searchString.indexOf("\\xAD")
745 || -1 != rSearchOpt.searchString.indexOf("\\x{00AD}")
746 || -1 != rSearchOpt.searchString.indexOf("\\u00AD")
747 || -1 != rSearchOpt.searchString.indexOf("\\u00ad")
748 || -1 != rSearchOpt.searchString.indexOf("\\U000000AD")
749 || -1 != rSearchOpt.searchString.indexOf("\\N{SOFT HYPHEN}"))
751 bRemoveSoftHyphens = false;
754 else
756 if ( 1 == rSearchOpt.searchString.getLength() &&
757 CHAR_SOFTHYPHEN == rSearchOpt.searchString.toChar() )
758 bRemoveSoftHyphens = false;
761 if( bSrchForward )
762 sCleanStr = lcl_CleanStr(*pNode, pFrame, pLayout, nStart, nEnd,
763 aFltArr, bRemoveSoftHyphens, bRemoveCommentAnchors);
764 else
765 sCleanStr = lcl_CleanStr(*pNode, pFrame, pLayout, nEnd, nStart,
766 aFltArr, bRemoveSoftHyphens, bRemoveCommentAnchors);
768 std::unique_ptr<SwScriptIterator> pScriptIter;
769 sal_uInt16 nSearchScript = 0;
770 sal_uInt16 nCurrScript = 0;
772 if (SearchAlgorithms2::APPROXIMATE == rSearchOpt.AlgorithmType2)
774 pScriptIter.reset(new SwScriptIterator(sCleanStr, nStart.GetAnyIndex(), bSrchForward));
775 nSearchScript = g_pBreakIt->GetRealScriptOfText( rSearchOpt.searchString, 0 );
778 const AmbiguousIndex nStringEnd = nEnd;
779 bool bZeroMatch = false; // zero-length match, i.e. only $ anchor as regex
780 while ( ((bSrchForward && nStart < nStringEnd) ||
781 (!bSrchForward && nStringEnd < nStart)) && !bZeroMatch )
783 // SearchAlgorithms_APPROXIMATE works on a per word base so we have to
784 // provide the text searcher with the correct locale, because it uses
785 // the break-iterator
786 if ( pScriptIter )
788 nEnd.GetAnyIndex() = pScriptIter->GetScriptChgPos();
789 nCurrScript = pScriptIter->GetCurrScript();
790 if ( nSearchScript == nCurrScript )
792 const LanguageType eCurrLang = pLayout
793 ? pFrame->GetLangOfChar(bSrchForward
794 ? nStart.GetFrameIndex()
795 : nEnd.GetFrameIndex(),
796 0, true)
797 : pNode->GetLang(bSrchForward
798 ? nStart.GetModelIndex()
799 : nEnd.GetModelIndex());
801 if ( eCurrLang != eLastLang )
803 const lang::Locale aLocale(
804 g_pBreakIt->GetLocale( eCurrLang ) );
805 rSText.SetLocale( utl::TextSearch::UpgradeToSearchOptions2( rSearchOpt), aLocale );
806 eLastLang = eCurrLang;
809 pScriptIter->Next();
811 AmbiguousIndex nProxyStart = nStart;
812 AmbiguousIndex nProxyEnd = nEnd;
813 if( nSearchScript == nCurrScript &&
814 (rSText.*fnMove.fnSearch)( sCleanStr, &nProxyStart.GetAnyIndex(), &nProxyEnd.GetAnyIndex(), nullptr) &&
815 !(bZeroMatch = (nProxyStart == nProxyEnd)))
817 nStart = nProxyStart;
818 nEnd = nProxyEnd;
819 // set section correctly
820 *rSearchPam.GetPoint() = *pPam->GetPoint();
821 rSearchPam.SetMark();
823 // adjust start and end
824 if( !aFltArr.empty() )
826 // if backward search, switch positions temporarily
827 if (!bSrchForward) { std::swap(nStart, nEnd); }
829 AmbiguousIndex nNew = nStart;
830 for (size_t n = 0; n < aFltArr.size() && aFltArr[ n ] <= nStart; ++n )
832 ++nNew.GetAnyIndex();
835 nStart = nNew;
836 nNew = nEnd;
837 for( size_t n = 0; n < aFltArr.size() && aFltArr[ n ] < nEnd; ++n )
839 ++nNew.GetAnyIndex();
842 nEnd = nNew;
843 // if backward search, switch positions temporarily
844 if( !bSrchForward ) { std::swap(nStart, nEnd); }
846 if (pLayout)
848 *rSearchPam.GetMark() = pFrame->MapViewToModelPos(nStart.GetFrameIndex());
849 *rSearchPam.GetPoint() = pFrame->MapViewToModelPos(nEnd.GetFrameIndex());
851 else
853 rSearchPam.GetMark()->SetContent( nStart.GetModelIndex() );
854 rSearchPam.GetPoint()->SetContent( nEnd.GetModelIndex() );
857 // if backward search, switch point and mark
858 if( !bSrchForward )
859 rSearchPam.Exchange();
860 bFound = true;
861 break;
863 else
865 nEnd = nProxyEnd;
867 nStart = nEnd;
870 pScriptIter.reset();
872 if ( bFound )
873 return true;
875 if (!bChkEmptyPara && !bChkParaEnd)
876 return false;
878 if (bChkEmptyPara && bSrchForward && nTextLen.GetAnyIndex())
879 return false; // the length is not zero - there is content here
881 // move to the end (or start) of the paragraph
882 *rSearchPam.GetPoint() = *pPam->GetPoint();
883 if (pLayout)
885 *rSearchPam.GetPoint() = pFrame->MapViewToModelPos(
886 bSrchForward ? nTextLen.GetFrameIndex() : TextFrameIndex(0));
888 else
890 rSearchPam.GetPoint()->SetContent(bSrchForward ? nTextLen.GetModelIndex() : 0);
892 rSearchPam.SetMark();
894 if (!rSearchPam.Move(fnMove, GoInContent))
895 return false; // at start or end of the document
897 // selection must not be outside of the search area
898 if (!pPam->ContainsPosition(*rSearchPam.GetPoint()))
899 return false;
901 if (SwNodeOffset(1) == abs(rSearchPam.GetPoint()->GetNodeIndex() -
902 rSearchPam.GetMark()->GetNodeIndex()))
904 if (bChkEmptyPara && !bSrchForward && rSearchPam.GetPoint()->GetContentIndex())
905 return false; // the length is not zero - there is content here
907 return true;
910 return false;
913 namespace {
915 /// parameters for search and replace in text
916 struct SwFindParaText : public SwFindParas
918 const i18nutil::SearchOptions2& m_rSearchOpt;
919 SwCursor& m_rCursor;
920 SwRootFrame const* m_pLayout;
921 utl::TextSearch m_aSText;
922 bool m_bReplace;
923 bool m_bSearchInNotes;
925 SwFindParaText(const i18nutil::SearchOptions2& rOpt, bool bSearchInNotes,
926 bool bRepl, SwCursor& rCursor, SwRootFrame const*const pLayout)
927 : m_rSearchOpt( rOpt )
928 , m_rCursor( rCursor )
929 , m_pLayout(pLayout)
930 , m_aSText( utl::TextSearch::UpgradeToSearchOptions2(rOpt) )
931 , m_bReplace( bRepl )
932 , m_bSearchInNotes( bSearchInNotes )
934 virtual int DoFind(SwPaM &, SwMoveFnCollection const &, const SwPaM &, bool bInReadOnly, std::unique_ptr<SvxSearchItem>& xSearchItem) override;
935 virtual bool IsReplaceMode() const override;
936 virtual ~SwFindParaText();
941 SwFindParaText::~SwFindParaText()
945 int SwFindParaText::DoFind(SwPaM & rCursor, SwMoveFnCollection const & fnMove,
946 const SwPaM & rRegion, bool bInReadOnly,
947 std::unique_ptr<SvxSearchItem>& xSearchItem)
949 if( bInReadOnly && m_bReplace )
950 bInReadOnly = false;
952 const bool bFnd = sw::FindTextImpl(rCursor, m_rSearchOpt, m_bSearchInNotes,
953 m_aSText, fnMove, rRegion, bInReadOnly, m_pLayout, xSearchItem);
955 if( bFnd && m_bReplace ) // replace string
957 // use replace method in SwDoc
958 const bool bRegExp(SearchAlgorithms2::REGEXP == m_rSearchOpt.AlgorithmType2);
959 const sal_Int32 nSttCnt = rCursor.Start()->GetContentIndex();
960 // add to shell-cursor-ring so that the regions will be moved eventually
961 SwPaM* pPrev(nullptr);
962 if( bRegExp )
964 pPrev = const_cast<SwPaM&>(rRegion).GetPrev();
965 const_cast<SwPaM&>(rRegion).GetRingContainer().merge( m_rCursor.GetRingContainer() );
968 std::optional<OUString> xRepl;
969 if (bRegExp)
970 xRepl = sw::ReplaceBackReferences(m_rSearchOpt, &rCursor, m_pLayout);
971 bool const bReplaced = sw::ReplaceImpl(rCursor,
972 xRepl ? *xRepl : m_rSearchOpt.replaceString,
973 bRegExp, m_rCursor.GetDoc(), m_pLayout);
975 m_rCursor.SaveTableBoxContent( rCursor.GetPoint() );
977 if( bRegExp )
979 // and remove region again
980 SwPaM* p;
981 SwPaM* pNext(const_cast<SwPaM*>(&rRegion));
982 do {
983 p = pNext;
984 pNext = p->GetNext();
985 p->MoveTo(const_cast<SwPaM*>(&rRegion));
986 } while( p != pPrev );
988 if (bRegExp && !bReplaced)
989 { // fdo#80715 avoid infinite loop if join failed
990 bool bRet = ((&fnMoveForward == &fnMove) ? &GoNextPara : &GoPrevPara)
991 (rCursor, fnMove);
992 (void) bRet;
993 assert(bRet); // if join failed, next node must be SwTextNode
995 else
996 rCursor.Start()->SetContent(nSttCnt);
997 return FIND_NO_RING;
999 return bFnd ? FIND_FOUND : FIND_NOT_FOUND;
1002 bool SwFindParaText::IsReplaceMode() const
1004 return m_bReplace;
1007 sal_Int32 SwCursor::Find_Text( const i18nutil::SearchOptions2& rSearchOpt, bool bSearchInNotes,
1008 SwDocPositions nStart, SwDocPositions nEnd,
1009 bool& bCancel, FindRanges eFndRngs, bool bReplace,
1010 SwRootFrame const*const pLayout)
1012 // switch off OLE-notifications
1013 SwDoc& rDoc = GetDoc();
1014 Link<bool,void> aLnk( rDoc.GetOle2Link() );
1015 rDoc.SetOle2Link( Link<bool,void>() );
1017 bool const bStartUndo = rDoc.GetIDocumentUndoRedo().DoesUndo() && bReplace;
1018 if (bStartUndo)
1020 rDoc.GetIDocumentUndoRedo().StartUndo( SwUndoId::REPLACE, nullptr );
1023 bool bSearchSel = 0 != (rSearchOpt.searchFlag & SearchFlags::REG_NOT_BEGINOFLINE);
1024 if( bSearchSel )
1025 eFndRngs = static_cast<FindRanges>(eFndRngs | FindRanges::InSel);
1026 SwFindParaText aSwFindParaText(rSearchOpt, bSearchInNotes, bReplace, *this, pLayout);
1027 sal_Int32 nRet = FindAll( aSwFindParaText, nStart, nEnd, eFndRngs, bCancel );
1028 rDoc.SetOle2Link( aLnk );
1029 if( nRet && bReplace )
1030 rDoc.getIDocumentState().SetModified();
1032 if (bStartUndo)
1034 SwRewriter rewriter(MakeUndoReplaceRewriter(
1035 nRet, rSearchOpt.searchString, rSearchOpt.replaceString));
1036 rDoc.GetIDocumentUndoRedo().EndUndo( SwUndoId::REPLACE, & rewriter );
1038 return nRet;
1041 namespace sw {
1043 bool ReplaceImpl(
1044 SwPaM & rCursor,
1045 OUString const& rReplacement,
1046 bool const bRegExp,
1047 SwDoc & rDoc,
1048 SwRootFrame const*const pLayout)
1050 bool bReplaced(true);
1051 IDocumentContentOperations & rIDCO(rDoc.getIDocumentContentOperations());
1052 #if 0
1053 // FIXME there's some problem with multiple redlines here on Undo
1054 std::vector<std::shared_ptr<SwUnoCursor>> ranges;
1055 if (rDoc.getIDocumentRedlineAccess().IsRedlineOn()
1056 || !pLayout
1057 || !pLayout->IsHideRedlines()
1058 || sw::GetRanges(ranges, rDoc, rCursor))
1060 bReplaced = rIDCO.ReplaceRange(rCursor, rReplacement, bRegExp);
1062 else
1064 assert(!ranges.empty());
1065 assert(ranges.front()->GetPoint()->GetNode() == ranges.front()->GetMark()->GetNode());
1066 bReplaced = rIDCO.ReplaceRange(*ranges.front(), rReplacement, bRegExp);
1067 for (auto it = ranges.begin() + 1; it != ranges.end(); ++it)
1069 bReplaced &= rIDCO.DeleteAndJoin(**it);
1072 #else
1073 IDocumentRedlineAccess const& rIDRA(rDoc.getIDocumentRedlineAccess());
1074 if (pLayout && pLayout->IsHideRedlines()
1075 && !rIDRA.IsRedlineOn() // otherwise: ReplaceRange will handle it
1076 && (rIDRA.GetRedlineFlags() & RedlineFlags::ShowDelete)) // otherwise: ReplaceRange will DeleteRedline()
1078 SwRedlineTable::size_type tmp;
1079 rIDRA.GetRedline(*rCursor.Start(), &tmp);
1080 while (tmp < rIDRA.GetRedlineTable().size())
1082 SwRangeRedline const*const pRedline(rIDRA.GetRedlineTable()[tmp]);
1083 if (*rCursor.End() <= *pRedline->Start())
1085 break;
1087 if (*pRedline->End() <= *rCursor.Start())
1089 ++tmp;
1090 continue;
1092 if (pRedline->GetType() == RedlineType::Delete)
1094 assert(*pRedline->Start() != *pRedline->End());
1095 // search in hidden layout can't overlap redlines
1096 assert(*rCursor.Start() <= *pRedline->Start() && *pRedline->End() <= *rCursor.End());
1097 SwPaM pam(*pRedline, nullptr);
1098 bReplaced &= rIDCO.DeleteAndJoin(pam);
1100 else
1102 ++tmp;
1106 bReplaced &= rIDCO.ReplaceRange(rCursor, rReplacement, bRegExp);
1107 #endif
1108 return bReplaced;
1111 std::optional<OUString> ReplaceBackReferences(const i18nutil::SearchOptions2& rSearchOpt,
1112 SwPaM *const pPam, SwRootFrame const*const pLayout)
1114 std::optional<OUString> xRet;
1115 if( pPam && pPam->HasMark() &&
1116 SearchAlgorithms2::REGEXP == rSearchOpt.AlgorithmType2 )
1118 SwContentNode const*const pTextNode = pPam->GetPointContentNode();
1119 SwContentNode const*const pMarkTextNode = pPam->GetMarkContentNode();
1120 if (!pTextNode || !pTextNode->IsTextNode()
1121 || !pMarkTextNode || !pMarkTextNode->IsTextNode())
1123 return xRet;
1125 SwTextFrame const*const pFrame(pLayout
1126 ? static_cast<SwTextFrame const*>(pTextNode->getLayoutFrame(pLayout))
1127 : nullptr);
1128 const bool bParaEnd = rSearchOpt.searchString == "$" || rSearchOpt.searchString == "^$" || rSearchOpt.searchString == "$^";
1129 if (bParaEnd || (pLayout
1130 ? sw::FrameContainsNode(*pFrame, pPam->GetMark()->GetNodeIndex())
1131 : pTextNode == pMarkTextNode))
1133 utl::TextSearch aSText( utl::TextSearch::UpgradeToSearchOptions2( rSearchOpt) );
1134 SearchResult aResult;
1135 OUString aReplaceStr( rSearchOpt.replaceString );
1136 if (bParaEnd)
1138 OUString const aStr("\\n");
1139 aResult.subRegExpressions = 1;
1140 aResult.startOffset = { 0 };
1141 aResult.endOffset = { aStr.getLength() };
1142 aSText.ReplaceBackReferences( aReplaceStr, aStr, aResult );
1143 xRet = aReplaceStr;
1145 else
1147 AmbiguousIndex nStart;
1148 AmbiguousIndex nEnd;
1149 if (pLayout)
1151 nStart.SetFrameIndex(pFrame->MapModelToViewPos(*pPam->Start()));
1152 nEnd.SetFrameIndex(pFrame->MapModelToViewPos(*pPam->End()));
1154 else
1156 nStart.SetModelIndex(pPam->Start()->GetContentIndex());
1157 nEnd.SetModelIndex(pPam->End()->GetContentIndex());
1159 std::vector<AmbiguousIndex> aFltArr;
1160 OUString const aStr = lcl_CleanStr(*pTextNode->GetTextNode(), pFrame, pLayout,
1161 nStart, nEnd, aFltArr, false, false);
1162 if (aSText.SearchForward(aStr, &nStart.GetAnyIndex(), &nEnd.GetAnyIndex(), &aResult))
1164 aSText.ReplaceBackReferences( aReplaceStr, aStr, aResult );
1165 xRet = aReplaceStr;
1170 return xRet;
1173 } // namespace sw
1175 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */