summaryrefslogtreecommitdiffstats
path: root/sc/source/core/data/table6.cxx
blob: 966b4491c348ebdb29621e416ecdf2ded42e2cae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <unotools/textsearch.hxx>
#include <com/sun/star/util/SearchResult.hpp>
#include <svl/srchitem.hxx>
#include <editeng/editobj.hxx>
#include <osl/diagnose.h>
#include <sal/log.hxx>

#include <table.hxx>
#include <formulacell.hxx>
#include <document.hxx>
#include <stlpool.hxx>
#include <stlsheet.hxx>
#include <markdata.hxx>
#include <editutil.hxx>
#include <postit.hxx>

namespace {

bool lcl_GetTextWithBreaks( const EditTextObject& rData, ScDocument* pDoc, OUString& rVal )
{
    //  true = more than 1 paragraph

    EditEngine& rEngine = pDoc->GetEditEngine();
    rEngine.SetText(rData);
    rVal = rEngine.GetText();
    return ( rEngine.GetParagraphCount() > 1 );
}

}

bool ScTable::SearchCell(const SvxSearchItem& rSearchItem, SCCOL nCol, sc::ColumnBlockConstPosition& rBlockPos, SCROW nRow,
                         const ScMarkData& rMark, OUString& rUndoStr, ScDocument* pUndoDoc)
{
    if ( !IsColRowValid( nCol, nRow ) )
        return false;

    bool    bFound = false;
    bool    bDoSearch = true;
    bool    bDoBack = rSearchItem.GetBackward();
    bool    bSearchFormatted = rSearchItem.IsSearchFormatted();

    OUString  aString;
    ScRefCellValue aCell;
    if (rSearchItem.GetSelection())
        bDoSearch = rMark.IsCellMarked(nCol, nRow);

    if (!bDoSearch)
        return false;

    ScPostIt* pNote;
    if (rSearchItem.GetCellType() == SvxSearchCellType::NOTE)
    {
        pNote = aCol[nCol].GetCellNote(rBlockPos, nRow);
        if (!pNote)
            return false;
    }
    else
    {
        aCell = aCol[nCol].GetCellValue(rBlockPos, nRow);
        if (aCell.isEmpty())
            return false;
        pNote = nullptr;
    }

    bool bMultiLine = false;
    CellType eCellType = aCell.meType;
    switch (rSearchItem.GetCellType())
    {
        case SvxSearchCellType::FORMULA:
        {
            if ( eCellType == CELLTYPE_FORMULA )
                aString = aCell.mpFormula->GetFormula(rDocument.GetGrammar());
            else if ( eCellType == CELLTYPE_EDIT )
                bMultiLine = lcl_GetTextWithBreaks(*aCell.mpEditText, &rDocument, aString);
            else
            {
                if( !bSearchFormatted )
                    aString = aCol[nCol].GetInputString( rBlockPos, nRow );
                else
                    aString = aCol[nCol].GetString( rBlockPos, nRow );
            }
            break;
        }
        case SvxSearchCellType::VALUE:
            if ( eCellType == CELLTYPE_EDIT )
                bMultiLine = lcl_GetTextWithBreaks(*aCell.mpEditText, &rDocument, aString);
            else
            {
                if( !bSearchFormatted )
                    aString = aCol[nCol].GetInputString( rBlockPos, nRow );
                else
                    aString = aCol[nCol].GetString( rBlockPos, nRow );
            }
            break;
        case SvxSearchCellType::NOTE:
        {
            if (pNote)
            {
                aString = pNote->GetText();
                bMultiLine = pNote->HasMultiLineText();
            }
            break;
        }
        default:
            break;
    }
    sal_Int32 nStart = 0;
    sal_Int32 nEnd = aString.getLength();
    css::util::SearchResult aSearchResult;
    if (pSearchText)
    {
        if ( bDoBack )
        {
            sal_Int32 nTemp=nStart; nStart=nEnd; nEnd=nTemp;
            bFound = pSearchText->SearchBackward(aString, &nStart, &nEnd, &aSearchResult);
            // change results to definition before 614:
            --nEnd;
        }
        else
        {
            bFound = pSearchText->SearchForward(aString, &nStart, &nEnd, &aSearchResult);
            // change results to definition before 614:
            --nEnd;
        }

        if (bFound && rSearchItem.GetWordOnly())
            bFound = (nStart == 0 && nEnd == aString.getLength() - 1);
    }
    else
    {
        OSL_FAIL("pSearchText == NULL");
        return bFound;
    }

    if (!bFound)
        return false;
    if ( rSearchItem.GetCommand() != SvxSearchCmd::REPLACE
         && rSearchItem.GetCommand() != SvxSearchCmd::REPLACE_ALL )
        return bFound;

    if (!IsBlockEditable(nCol, nRow, nCol, nRow))
        return bFound;

    ScMatrixMode cMatrixFlag = ScMatrixMode::NONE;

    // Don't split the matrix, only replace Matrix formulas
    if (eCellType == CELLTYPE_FORMULA)
    {
        cMatrixFlag = aCell.mpFormula->GetMatrixFlag();
        if(cMatrixFlag == ScMatrixMode::Reference)
            return bFound;
    }
    // No UndoDoc => Matrix not restorable => don't replace
    if (cMatrixFlag != ScMatrixMode::NONE && !pUndoDoc)
        return bFound;

    if ( cMatrixFlag == ScMatrixMode::NONE && rSearchItem.GetCommand() == SvxSearchCmd::REPLACE )
        rUndoStr = aString;
    else if (pUndoDoc)
    {
        ScAddress aAdr( nCol, nRow, nTab );
        aCell.commit(*pUndoDoc, aAdr);
    }

    bool bRepeat = !rSearchItem.GetWordOnly();
    do
    {
        //  don't continue search if the found text is empty,
        //  otherwise it would never stop (#35410#)
        if ( nEnd < nStart )
            bRepeat = false;

        OUString sReplStr = rSearchItem.GetReplaceString();
        if (rSearchItem.GetRegExp())
        {
            pSearchText->ReplaceBackReferences( sReplStr, aString, aSearchResult );
            OUStringBuffer aStrBuffer(aString);
            aStrBuffer.remove(nStart, nEnd-nStart+1);
            aStrBuffer.insert(nStart, sReplStr);
            aString = aStrBuffer.makeStringAndClear();
        }
        else
        {
            OUStringBuffer aStrBuffer(aString);
            aStrBuffer.remove(nStart, nEnd-nStart+1);
            aStrBuffer.insert(nStart, rSearchItem.GetReplaceString());
            aString = aStrBuffer.makeStringAndClear();
        }

        //  Adjust index
        if (bDoBack)
        {
            nEnd = nStart;
            nStart = 0;
        }
        else
        {
            nStart = nStart + sReplStr.getLength();
            nEnd = aString.getLength();
        }

        //  continue search ?
        if (bRepeat)
        {
            if ( rSearchItem.GetCommand() != SvxSearchCmd::REPLACE_ALL || nStart >= nEnd )
                bRepeat = false;
            else if (bDoBack)
            {
                sal_Int32 nTemp=nStart; nStart=nEnd; nEnd=nTemp;
                bRepeat = pSearchText->SearchBackward(aString, &nStart, &nEnd, &aSearchResult);
                // change results to definition before 614:
                --nEnd;
            }
            else
            {
                bRepeat = pSearchText->SearchForward(aString, &nStart, &nEnd, &aSearchResult);
                // change results to definition before 614:
                --nEnd;
            }
        }
    }
    while (bRepeat);
    if (rSearchItem.GetCellType() == SvxSearchCellType::NOTE)
    {
        // NB: rich text format is lost.
        // This is also true of Cells.
        if (pNote)
            pNote->SetText( ScAddress( nCol, nRow, nTab ), aString );
    }
    else if ( cMatrixFlag != ScMatrixMode::NONE )
    {   // don't split Matrix
        if ( aString.getLength() > 2 )
        {   // remove {} here so that "{=" can be replaced by "{=..."
            if ( aString[ aString.getLength()-1 ] == '}' )
                aString = aString.copy( 0, aString.getLength()-1 );
            if ( aString[0] == '{' )
                aString = aString.copy( 1 );
        }
        ScAddress aAdr( nCol, nRow, nTab );
        ScFormulaCell* pFCell = new ScFormulaCell( rDocument, aAdr,
            aString, rDocument.GetGrammar(), cMatrixFlag );
        SCCOL nMatCols;
        SCROW nMatRows;
        aCell.mpFormula->GetMatColsRows(nMatCols, nMatRows);
        pFCell->SetMatColsRows( nMatCols, nMatRows );
        aCol[nCol].SetFormulaCell(nRow, pFCell);
    }
    else if ( bMultiLine && aString.indexOf('\n') != -1 )
    {
        ScFieldEditEngine& rEngine = rDocument.GetEditEngine();
        rEngine.SetTextCurrentDefaults(aString);
        SetEditText(nCol, nRow, rEngine.CreateTextObject());
    }
    else
        aCol[nCol].SetString(nRow, nTab, aString, rDocument.GetAddressConvention());
    // pCell is invalid now (deleted)
    aCol[nCol].InitBlockPosition( rBlockPos ); // invalidate also the cached position

    return bFound;
}

void ScTable::SkipFilteredRows(SCROW& rRow, SCROW& rLastNonFilteredRow, bool bForward)
{
    if (bForward)
    {
        // forward search

        if (rRow <= rLastNonFilteredRow)
            return;

        SCROW nLastRow = rRow;
        if (RowFiltered(rRow, nullptr, &nLastRow))
            // move to the first non-filtered row.
            rRow = nLastRow + 1;
        else
            // record the last non-filtered row to avoid checking
            // the filtered state for each and every row.
            rLastNonFilteredRow = nLastRow;
    }
    else
    {
        // backward search

        if (rRow >= rLastNonFilteredRow)
            return;

        SCROW nFirstRow = rRow;
        if (RowFiltered(rRow, &nFirstRow))
            // move to the first non-filtered row.
            rRow = nFirstRow - 1;
        else
            // record the last non-filtered row to avoid checking
            // the filtered state for each and every row.
            rLastNonFilteredRow = nFirstRow;
    }
}

bool ScTable::Search(const SvxSearchItem& rSearchItem, SCCOL& rCol, SCROW& rRow,
                     const ScMarkData& rMark, OUString& rUndoStr, ScDocument* pUndoDoc)
{
    SCCOL nLastCol;
    SCROW nLastRow;
    if (rSearchItem.GetCellType() == SvxSearchCellType::NOTE)
        GetCellArea( nLastCol, nLastRow);
    else
        GetLastDataPos(nLastCol, nLastRow);
    std::vector< sc::ColumnBlockConstPosition > blockPos;
    return Search(rSearchItem, rCol, rRow, nLastCol, nLastRow, rMark, rUndoStr, pUndoDoc, blockPos);
}

bool ScTable::Search(const SvxSearchItem& rSearchItem, SCCOL& rCol, SCROW& rRow,
                     SCCOL nLastCol, SCROW nLastRow,
                     const ScMarkData& rMark, OUString& rUndoStr, ScDocument* pUndoDoc,
                     std::vector< sc::ColumnBlockConstPosition >& blockPos)
{
    bool bFound = false;
    bool bAll =  (rSearchItem.GetCommand() == SvxSearchCmd::FIND_ALL)
               ||(rSearchItem.GetCommand() == SvxSearchCmd::REPLACE_ALL);
    SCCOL nCol = rCol;
    SCROW nRow = rRow;

    bool bSkipFiltered = !rSearchItem.IsSearchFiltered();
    bool bSearchNotes = (rSearchItem.GetCellType() == SvxSearchCellType::NOTE);
    // We need to cache sc::ColumnBlockConstPosition per each column.
    if (static_cast<SCCOL>(blockPos.size()) != nLastCol + 1)
    {
        blockPos.resize( nLastCol + 1 );
        for( SCCOL i = 0; i <= nLastCol; ++i )
            aCol[ i ].InitBlockPosition( blockPos[ i ] );
    }
    if (!bAll && rSearchItem.GetBackward())
    {
        SCROW nLastNonFilteredRow = rDocument.MaxRow() + 1;
        if (rSearchItem.GetRowDirection())
        {
            nCol--;
            nCol = std::min(nCol, nLastCol);
            nRow = std::min(nRow, nLastRow);
            while (!bFound && (nRow >= 0))
            {
                if (bSkipFiltered)
                    SkipFilteredRows(nRow, nLastNonFilteredRow, false);

                while (!bFound && (nCol >= 0))
                {
                    bFound = SearchCell(rSearchItem, nCol, blockPos[ nCol ], nRow,
                                        rMark, rUndoStr, pUndoDoc);
                    if (!bFound)
                    {
                        bool bIsEmpty;
                        do
                        {
                            nCol--;
                            if (nCol >= 0)
                            {
                                if (bSearchNotes)
                                    bIsEmpty = !aCol[nCol].HasCellNotes();
                                else
                                    bIsEmpty = aCol[nCol].IsEmptyData();
                            }
                            else
                                bIsEmpty = true;
                        }
                        while ((nCol >= 0) && bIsEmpty);
                    }
                }
                if (!bFound)
                {
                    nCol = nLastCol;
                    nRow--;
                }
            }
        }
        else
        {
            nRow--;
            nCol = std::min(nCol, nLastCol);
            nRow = std::min(nRow, nLastRow);
            while (!bFound && (nCol >= 0))
            {
                while (!bFound && (nRow >= 0))
                {
                    if (bSkipFiltered)
                        SkipFilteredRows(nRow, nLastNonFilteredRow, false);

                    bFound = SearchCell(rSearchItem, nCol, blockPos[ nCol ],
                                        nRow, rMark, rUndoStr, pUndoDoc);
                    if (!bFound)
                    {
                        if (bSearchNotes)
                        {
                            /* TODO: can we look for the previous cell note instead? */
                            --nRow;
                        }
                        else
                        {
                            if (!aCol[nCol].GetPrevDataPos(nRow))
                                nRow = -1;
                        }
                    }
                }
                if (!bFound)
                {
                    // Not found in this column.  Move to the next column.
                    bool bIsEmpty;
                    nRow = nLastRow;
                    nLastNonFilteredRow = rDocument.MaxRow() + 1;
                    do
                    {
                        nCol--;
                        if (nCol >= 0)
                        {
                            if (bSearchNotes)
                                bIsEmpty = !aCol[nCol].HasCellNotes();
                            else
                                bIsEmpty = aCol[nCol].IsEmptyData();
                        }
                        else
                            bIsEmpty = true;
                    }
                    while ((nCol >= 0) && bIsEmpty);
                }
            }
        }
    }
    else
    {
        SCROW nLastNonFilteredRow = -1;
        if (rSearchItem.GetRowDirection())
        {
            nCol++;
            while (!bFound && (nRow <= nLastRow))
            {
                if (bSkipFiltered)
                    SkipFilteredRows(nRow, nLastNonFilteredRow, true);

                while (!bFound && (nCol <= nLastCol))
                {
                    bFound = SearchCell(rSearchItem, nCol, blockPos[ nCol ],
                                        nRow, rMark, rUndoStr, pUndoDoc);
                    if (!bFound)
                    {
                        nCol++;
                        while ((nCol <= nLastCol) &&
                                (bSearchNotes ? !aCol[nCol].HasCellNotes() : aCol[nCol].IsEmptyData()))
                            nCol++;
                    }
                }
                if (!bFound)
                {
                    nCol = 0;
                    nRow++;
                }
            }
        }
        else
        {
            nRow++;
            while (!bFound && (nCol <= nLastCol))
            {
                while (!bFound && (nRow <= nLastRow))
                {
                    if (bSkipFiltered)
                        SkipFilteredRows(nRow, nLastNonFilteredRow, true);

                    bFound = SearchCell(rSearchItem, nCol, blockPos[ nCol ],
                                        nRow, rMark, rUndoStr, pUndoDoc);
                    if (!bFound)
                    {
                        if (bSearchNotes)
                        {
                            /* TODO: can we look for the next cell note instead? */
                            ++nRow;
                        }
                        else
                        {
                            if (!aCol[nCol].GetNextDataPos(nRow))
                                nRow = rDocument.MaxRow() + 1;
                        }
                    }
                }
                if (!bFound)
                {
                    // Not found in this column.  Move to the next column.
                    nRow = 0;
                    nLastNonFilteredRow = -1;
                    nCol++;
                    while ((nCol <= nLastCol) &&
                            (bSearchNotes ? !aCol[nCol].HasCellNotes() : aCol[nCol].IsEmptyData()))
                        nCol++;
                }
            }
        }
    }
    if (bFound)
    {
        rCol = nCol;
        rRow = nRow;
    }
    return bFound;
}

bool ScTable::SearchAll(const SvxSearchItem& rSearchItem, const ScMarkData& rMark,
                        ScRangeList& rMatchedRanges, OUString& rUndoStr, ScDocument* pUndoDoc)
{
    bool bFound = true;
    SCCOL nCol = 0;
    SCROW nRow = -1;
    bool bEverFound = false;

    SCCOL nLastCol;
    SCROW nLastRow;
    if (rSearchItem.GetCellType() == SvxSearchCellType::NOTE)
        GetCellArea( nLastCol, nLastRow);
    else
        GetLastDataPos(nLastCol, nLastRow);

    std::vector< sc::ColumnBlockConstPosition > blockPos;
    do
    {
        bFound = Search(rSearchItem, nCol, nRow, nLastCol, nLastRow, rMark, rUndoStr, pUndoDoc, blockPos);
        if (bFound)
        {
            bEverFound = true;
            rMatchedRanges.Join(ScRange(nCol, nRow, nTab));
        }
    }
    while (bFound);

    return bEverFound;
}

void ScTable::UpdateSearchItemAddressForReplace( const SvxSearchItem& rSearchItem, SCCOL& rCol, SCROW& rRow )
{
    if (rSearchItem.GetBackward())
    {
        if (rSearchItem.GetRowDirection())
            rCol += 1;
        else
            rRow += 1;
    }
    else
    {
        if (rSearchItem.GetRowDirection())
            rCol -= 1;
        else
            rRow -= 1;
    }
}

bool ScTable::Replace(const SvxSearchItem& rSearchItem, SCCOL& rCol, SCROW& rRow,
                      const ScMarkData& rMark, OUString& rUndoStr, ScDocument* pUndoDoc)
{
    SCCOL nCol = rCol;
    SCROW nRow = rRow;

    UpdateSearchItemAddressForReplace( rSearchItem, nCol, nRow );
    bool bFound = Search(rSearchItem, nCol, nRow, rMark, rUndoStr, pUndoDoc);
    if (bFound)
    {
        rCol = nCol;
        rRow = nRow;
    }
    return bFound;
}

bool ScTable::ReplaceAll(
    const SvxSearchItem& rSearchItem, const ScMarkData& rMark, ScRangeList& rMatchedRanges,
    OUString& rUndoStr, ScDocument* pUndoDoc)
{
    SCCOL nCol = 0;
    SCROW nRow = -1;

    SCCOL nLastCol;
    SCROW nLastRow;
    if (rSearchItem.GetCellType() == SvxSearchCellType::NOTE)
        GetCellArea( nLastCol, nLastRow);
    else
        GetLastDataPos(nLastCol, nLastRow);

    // tdf#92160 - columnar replace is faster, and more memory efficient.
    SvxSearchItem aCopyItem(rSearchItem);
    aCopyItem.SetRowDirection(false);

    std::vector< sc::ColumnBlockConstPosition > blockPos;
    bool bEverFound = false;
    while (true)
    {
        bool bFound = Search(aCopyItem, nCol, nRow, nLastCol, nLastRow, rMark, rUndoStr, pUndoDoc, blockPos);

        if (bFound)
        {
            bEverFound = true;
            rMatchedRanges.Join(ScRange(nCol, nRow, nTab));
        }
        else
            break;
    }
    return bEverFound;
}

bool ScTable::SearchStyle(const SvxSearchItem& rSearchItem, SCCOL& rCol, SCROW& rRow,
                          const ScMarkData& rMark)
{
    const ScStyleSheet* pSearchStyle = static_cast<const ScStyleSheet*>(
                                        rDocument.GetStyleSheetPool()->Find(
                                        rSearchItem.GetSearchString(), SfxStyleFamily::Para ));

    SCCOL nCol = rCol;
    SCROW nRow = rRow;
    bool bFound = false;

    bool bSelect = rSearchItem.GetSelection();
    bool bRows = rSearchItem.GetRowDirection();
    bool bBack = rSearchItem.GetBackward();
    short nAdd = bBack ? -1 : 1;

    if (bRows)                                      // by row
    {
        if ( !IsColValid( nCol ) )
        {
            SAL_WARN( "sc.core", "SearchStyle: bad column " << nCol);
            return false;
        }
        nRow += nAdd;
        do
        {
            SCROW nNextRow = aCol[nCol].SearchStyle( nRow, pSearchStyle, bBack, bSelect, rMark );
            if (!ValidRow(nNextRow))
            {
                nRow = bBack ? rDocument.MaxRow() : 0;
                nCol = sal::static_int_cast<SCCOL>( nCol + nAdd );
            }
            else
            {
                nRow = nNextRow;
                bFound = true;
            }
        }
        while ( !bFound && IsColValid( nCol ) );
    }
    else                                    // by column
    {
        SCCOL aColSize = aCol.size();
        std::vector< SCROW > nNextRows ( aColSize );
        SCCOL i;
        for (i=0; i < aColSize; ++i)
        {
            SCROW nSRow = nRow;
            if (bBack)
            {
                if (i>=nCol) --nSRow;
            }
            else
            {
                if (i<=nCol) ++nSRow;
            }
            nNextRows[i] = aCol[i].SearchStyle( nSRow, pSearchStyle, bBack, bSelect, rMark );
        }
        if (bBack)                          // backwards
        {
            nRow = -1;
            for (i = aColSize - 1; i>=0; --i)
                if (nNextRows[i]>nRow)
                {
                    nCol = i;
                    nRow = nNextRows[i];
                    bFound = true;
                }
        }
        else                                // forwards
        {
            nRow = rDocument.MaxRow()+1;
            for (i=0; i < aColSize; ++i)
                if (nNextRows[i]<nRow)
                {
                    nCol = i;
                    nRow = nNextRows[i];
                    bFound = true;
                }
        }
    }

    if (bFound)
    {
        rCol = nCol;
        rRow = nRow;
    }
    return bFound;
}

//TODO: return single Pattern for Undo

bool ScTable::ReplaceStyle(const SvxSearchItem& rSearchItem, SCCOL& rCol, SCROW& rRow,
                           const ScMarkData& rMark, bool bIsUndo)
{
    bool bRet;
    if (bIsUndo)
        bRet = true;
    else
        bRet = SearchStyle(rSearchItem, rCol, rRow, rMark);
    if (bRet)
    {
        const ScStyleSheet* pReplaceStyle = static_cast<const ScStyleSheet*>(
                                        rDocument.GetStyleSheetPool()->Find(
                                        rSearchItem.GetReplaceString(), SfxStyleFamily::Para ));

        if (pReplaceStyle)
            ApplyStyle( rCol, rRow, pReplaceStyle );
        else
        {
            OSL_FAIL("pReplaceStyle==0");
        }
    }

    return bRet;
}

bool ScTable::SearchAllStyle(
    const SvxSearchItem& rSearchItem, const ScMarkData& rMark, ScRangeList& rMatchedRanges)
{
    const ScStyleSheet* pSearchStyle = static_cast<const ScStyleSheet*>(
                                        rDocument.GetStyleSheetPool()->Find(
                                        rSearchItem.GetSearchString(), SfxStyleFamily::Para ));
    bool bSelect = rSearchItem.GetSelection();
    bool bBack = rSearchItem.GetBackward();
    bool bEverFound = false;

    for (SCCOL i=0; i < aCol.size(); ++i)
    {
        bool bFound = true;
        SCROW nRow = 0;
        SCROW nEndRow;
        while (bFound && nRow <= rDocument.MaxRow())
        {
            bFound = aCol[i].SearchStyleRange( nRow, nEndRow, pSearchStyle, bBack, bSelect, rMark );
            if (bFound)
            {
                if (nEndRow<nRow)
                {
                    SCROW nTemp = nRow;
                    nRow = nEndRow;
                    nEndRow = nTemp;
                }
                rMatchedRanges.Join(ScRange(i, nRow, nTab, i, nEndRow, nTab));
                nRow = nEndRow + 1;
                bEverFound = true;
            }
        }
    }

    return bEverFound;
}

bool ScTable::ReplaceAllStyle(
    const SvxSearchItem& rSearchItem, const ScMarkData& rMark, ScRangeList& rMatchedRanges,
    ScDocument* pUndoDoc)
{
    bool bRet = SearchAllStyle(rSearchItem, rMark, rMatchedRanges);
    if (bRet)
    {
        const ScStyleSheet* pReplaceStyle = static_cast<const ScStyleSheet*>(
                                        rDocument.GetStyleSheetPool()->Find(
                                        rSearchItem.GetReplaceString(), SfxStyleFamily::Para ));

        if (pReplaceStyle)
        {
            if (pUndoDoc)
                rDocument.CopyToDocument(0, 0 ,nTab, rDocument.MaxCol(),rDocument.MaxRow(),nTab,
                                          InsertDeleteFlags::ATTRIB, true, *pUndoDoc, &rMark);
            ApplySelectionStyle( *pReplaceStyle, rMark );
        }
        else
        {
            OSL_FAIL("pReplaceStyle==0");
        }
    }

    return bRet;
}

bool ScTable::SearchAndReplace(
    const SvxSearchItem& rSearchItem, SCCOL& rCol, SCROW& rRow, const ScMarkData& rMark,
    ScRangeList& rMatchedRanges, OUString& rUndoStr, ScDocument* pUndoDoc)
{
    SvxSearchCmd nCommand = rSearchItem.GetCommand();
    bool bFound = false;
    if ( ValidColRow(rCol, rRow) ||
         ((nCommand == SvxSearchCmd::FIND || nCommand == SvxSearchCmd::REPLACE) &&
           (((rCol == GetDoc().GetMaxColCount() || rCol == -1) && ValidRow(rRow)) ||
            ((rRow == GetDoc().GetMaxRowCount() || rRow == -1) && ValidCol(rCol))
           )
         )
       )
    {
        bool bStyles = rSearchItem.GetPattern();
        if (bStyles)
        {
            if (nCommand == SvxSearchCmd::FIND)
                bFound = SearchStyle(rSearchItem, rCol, rRow, rMark);
            else if (nCommand == SvxSearchCmd::REPLACE)
                bFound = ReplaceStyle(rSearchItem, rCol, rRow, rMark, false);
            else if (nCommand == SvxSearchCmd::FIND_ALL)
                bFound = SearchAllStyle(rSearchItem, rMark, rMatchedRanges);
            else if (nCommand == SvxSearchCmd::REPLACE_ALL)
                bFound = ReplaceAllStyle(rSearchItem, rMark, rMatchedRanges, pUndoDoc);
        }
        else if (ScDocument::IsEmptyCellSearch( rSearchItem))
        {
            // Search for empty cells.
            bFound = SearchAndReplaceEmptyCells(rSearchItem, rCol, rRow, rMark, rMatchedRanges, rUndoStr, pUndoDoc);
        }
        else
        {
            //  SearchParam no longer needed - SearchOptions contains all settings
            i18nutil::SearchOptions2 aSearchOptions = rSearchItem.GetSearchOptions();
            aSearchOptions.Locale = ScGlobal::GetLocale();

            //  reflect UseAsianOptions flag in SearchOptions
            //  (use only ignore case and width if asian options are disabled).
            //  This is also done in SvxSearchDialog CommandHdl, but not in API object.
            if ( !rSearchItem.IsUseAsianOptions() )
                aSearchOptions.transliterateFlags &=
                    TransliterationFlags::IGNORE_CASE |
                      TransliterationFlags::IGNORE_WIDTH;

            pSearchText.reset( new utl::TextSearch( aSearchOptions ) );

            if (nCommand == SvxSearchCmd::FIND)
                bFound = Search(rSearchItem, rCol, rRow, rMark, rUndoStr, pUndoDoc);
            else if (nCommand == SvxSearchCmd::FIND_ALL)
                bFound = SearchAll(rSearchItem, rMark, rMatchedRanges, rUndoStr, pUndoDoc);
            else if (nCommand == SvxSearchCmd::REPLACE)
                bFound = Replace(rSearchItem, rCol, rRow, rMark, rUndoStr, pUndoDoc);
            else if (nCommand == SvxSearchCmd::REPLACE_ALL)
                bFound = ReplaceAll(rSearchItem, rMark, rMatchedRanges, rUndoStr, pUndoDoc);

            pSearchText.reset();
        }
    }
    return bFound;
}

bool ScTable::SearchAndReplaceEmptyCells(
    const SvxSearchItem& rSearchItem, SCCOL& rCol, SCROW& rRow, const ScMarkData& rMark,
    ScRangeList& rMatchedRanges, OUString& rUndoStr, ScDocument* pUndoDoc)
{
    SCCOL nColStart, nColEnd;
    SCROW nRowStart, nRowEnd;
    GetFirstDataPos(nColStart, nRowStart);
    GetLastDataPos(nColEnd, nRowEnd);

    ScRangeList aRanges(ScRange(nColStart, nRowStart, nTab, nColEnd, nRowEnd, nTab));

    if (rSearchItem.GetSelection())
    {
        // current selection only.
        if (!rMark.IsMarked() && !rMark.IsMultiMarked())
            // There is no selection.  Bail out.
            return false;

        ScRangeList aMarkedRanges, aNewRanges;
        rMark.FillRangeListWithMarks(&aMarkedRanges, true);
        for ( size_t i = 0, n = aMarkedRanges.size(); i < n; ++i )
        {
            ScRange & rRange = aMarkedRanges[ i ];
            if (rRange.aStart.Col() > nColEnd || rRange.aStart.Row() > nRowEnd || rRange.aEnd.Col() < nColStart || rRange.aEnd.Row() < nRowStart)
                // This range is outside the data area.  Skip it.
                continue;

            // Shrink the range into data area only.
            if (rRange.aStart.Col() < nColStart)
                rRange.aStart.SetCol(nColStart);
            if (rRange.aStart.Row() < nRowStart)
                rRange.aStart.SetRow(nRowStart);

            if (rRange.aEnd.Col() > nColEnd)
                rRange.aEnd.SetCol(nColEnd);
            if (rRange.aEnd.Row() > nRowEnd)
                rRange.aEnd.SetRow(nRowEnd);

            aNewRanges.push_back(rRange);
        }
        aRanges = aNewRanges;
    }

    SvxSearchCmd nCommand = rSearchItem.GetCommand();
    if (nCommand == SvxSearchCmd::FIND || nCommand == SvxSearchCmd::REPLACE)
    {
        if (rSearchItem.GetBackward())
        {
            for ( size_t i = aRanges.size(); i > 0; --i )
            {
                const ScRange & rRange = aRanges[ i - 1 ];
                if (SearchRangeForEmptyCell(rRange, rSearchItem, rCol, rRow, rUndoStr))
                    return true;
            }
        }
        else
        {
            for ( size_t i = 0, nListSize = aRanges.size(); i < nListSize; ++i )
            {
                const ScRange & rRange = aRanges[ i ];
                if (SearchRangeForEmptyCell(rRange, rSearchItem, rCol, rRow, rUndoStr))
                    return true;
            }
        }
    }
    else if (nCommand == SvxSearchCmd::FIND_ALL || nCommand == SvxSearchCmd::REPLACE_ALL)
    {
        bool bFound = false;
        for ( size_t i = 0, nListSize = aRanges.size(); i < nListSize; ++i )
        {
            ScRange const & rRange = aRanges[ i ];
            bFound |= SearchRangeForAllEmptyCells(rRange, rSearchItem, rMatchedRanges, rUndoStr, pUndoDoc);
        }
        return bFound;
    }
    return false;
}

namespace {

bool lcl_maybeReplaceCellString(
    ScColumn& rColObj, SCCOL& rCol, SCROW& rRow, OUString& rUndoStr, SCCOL nCol, SCROW nRow, const SvxSearchItem& rSearchItem)
{
    ScRefCellValue aCell = rColObj.GetCellValue(nRow);
    if (aCell.isEmpty())
    {
        // empty cell found.
        rCol = nCol;
        rRow = nRow;
        if (rSearchItem.GetCommand() == SvxSearchCmd::REPLACE &&
            !rSearchItem.GetReplaceString().isEmpty())
        {
            rColObj.SetRawString(nRow, rSearchItem.GetReplaceString());
            rUndoStr.clear();
        }
        return true;
    }
    return false;
}

}

bool ScTable::SearchRangeForEmptyCell(
    const ScRange& rRange, const SvxSearchItem& rSearchItem,
    SCCOL& rCol, SCROW& rRow, OUString& rUndoStr)
{
    SvxSearchCmd nCmd = rSearchItem.GetCommand();
    bool bSkipFiltered = rSearchItem.IsSearchFiltered();
    if (rSearchItem.GetBackward())
    {
        // backward search
        if (rSearchItem.GetRowDirection())
        {
            // row direction.
            SCROW nLastNonFilteredRow = rDocument.MaxRow() + 1;
            SCROW nBeginRow = std::min(rRange.aEnd.Row(), rRow);
            for (SCROW nRow = nBeginRow; nRow >= rRange.aStart.Row(); --nRow)
            {
                if (bSkipFiltered)
                    SkipFilteredRows(nRow, nLastNonFilteredRow, false);
                if (nRow < rRange.aStart.Row())
                    break;

                SCCOL nBeginCol = rRange.aEnd.Col();
                if (nRow == rRow && nBeginCol >= rCol)
                    // always start from one cell before the cursor.
                    nBeginCol = rCol - (nCmd == SvxSearchCmd::FIND ? 1 : 0);

                for (SCCOL nCol = nBeginCol; nCol >= rRange.aStart.Col(); --nCol)
                {
                    if (lcl_maybeReplaceCellString(aCol[nCol], rCol, rRow, rUndoStr, nCol, nRow, rSearchItem))
                        return true;
                }
            }
        }
        else
        {
            // column direction.
            SCCOL nBeginCol = std::min(rRange.aEnd.Col(), rCol);
            for (SCCOL nCol = nBeginCol; nCol >= rRange.aStart.Col(); --nCol)
            {
                SCROW nLastNonFilteredRow = rDocument.MaxRow() + 1;
                SCROW nBeginRow = rRange.aEnd.Row();
                if (nCol == rCol && nBeginRow >= rRow)
                    // always start from one cell before the cursor.
                    nBeginRow = rRow - (nCmd == SvxSearchCmd::FIND ? 1 : 0);
                for (SCROW nRow = nBeginRow; nRow >= rRange.aStart.Row(); --nRow)
                {
                    if (bSkipFiltered)
                        SkipFilteredRows(nRow, nLastNonFilteredRow, false);
                    if (nRow < rRange.aStart.Row())
                        break;

                    if (lcl_maybeReplaceCellString(aCol[nCol], rCol, rRow, rUndoStr, nCol, nRow, rSearchItem))
                        return true;
                }
            }
        }
    }
    else
    {
        // forward search
        if (rSearchItem.GetRowDirection())
        {
            // row direction.
            SCROW nLastNonFilteredRow = -1;
            SCROW nBeginRow = rRange.aStart.Row() < rRow ? rRow : rRange.aStart.Row();
            for (SCROW nRow = nBeginRow; nRow <= rRange.aEnd.Row(); ++nRow)
            {
                if (bSkipFiltered)
                    SkipFilteredRows(nRow, nLastNonFilteredRow, true);
                if (nRow > rRange.aEnd.Row())
                    break;

                SCCOL nBeginCol = rRange.aStart.Col();
                if (nRow == rRow && nBeginCol <= rCol)
                    // always start from one cell past the cursor.
                    nBeginCol = rCol + (nCmd == SvxSearchCmd::FIND ? 1 : 0);
                for (SCCOL nCol = nBeginCol; nCol <= rRange.aEnd.Col(); ++nCol)
                {
                    if (lcl_maybeReplaceCellString(aCol[nCol], rCol, rRow, rUndoStr, nCol, nRow, rSearchItem))
                        return true;
                }
            }
        }
        else
        {
            // column direction.
            SCCOL nBeginCol = rRange.aStart.Col() < rCol ? rCol : rRange.aStart.Col();
            for (SCCOL nCol = nBeginCol; nCol <= rRange.aEnd.Col(); ++nCol)
            {
                SCROW nLastNonFilteredRow = -1;
                SCROW nBeginRow = rRange.aStart.Row();
                if (nCol == rCol && nBeginRow <= rRow)
                    // always start from one cell past the cursor.
                    nBeginRow = rRow + (nCmd == SvxSearchCmd::FIND ? 1 : 0);
                for (SCROW nRow = nBeginRow; nRow <= rRange.aEnd.Row(); ++nRow)
                {
                    if (bSkipFiltered)
                        SkipFilteredRows(nRow, nLastNonFilteredRow, true);
                    if (nRow > rRange.aEnd.Row())
                        break;

                    if (lcl_maybeReplaceCellString(aCol[nCol], rCol, rRow, rUndoStr, nCol, nRow, rSearchItem))
                        return true;
                }
            }
        }
    }
    return false;
}

bool ScTable::SearchRangeForAllEmptyCells(
    const ScRange& rRange, const SvxSearchItem& rSearchItem,
    ScRangeList& rMatchedRanges, OUString& rUndoStr, ScDocument* pUndoDoc)
{
    bool bFound = false;
    bool bReplace = (rSearchItem.GetCommand() == SvxSearchCmd::REPLACE_ALL) &&
                    !rSearchItem.GetReplaceString().isEmpty();
    bool bSkipFiltered = rSearchItem.IsSearchFiltered();

    for (SCCOL nCol = rRange.aStart.Col(); nCol <= rRange.aEnd.Col(); ++nCol)
    {
        SCROW nLastNonFilteredRow = -1;
        if (aCol[nCol].IsEmptyData())
        {
            // The entire column is empty.
            const SCROW nEndRow = rRange.aEnd.Row();
            for (SCROW nRow = rRange.aStart.Row(); nRow <= nEndRow; ++nRow)
            {
                SCROW nLastRow;
                const bool bFiltered = RowFiltered(nRow, nullptr, &nLastRow);
                if (nLastRow > nEndRow)
                    nLastRow = nEndRow;
                if (!bFiltered)
                {
                    rMatchedRanges.Join(ScRange(nCol, nRow, nTab, nCol, nLastRow, nTab));
                    if (bReplace)
                    {
                        const OUString& rNewStr = rSearchItem.GetReplaceString();
                        for (SCROW i = nRow; i <= nLastRow; ++i)
                        {
                            aCol[nCol].SetRawString(i, rNewStr);
                            if (pUndoDoc)
                            {
                                // TODO: I'm using a string cell with empty content to
                                // trigger deletion of cell instance on undo.  Maybe I
                                // should create a new cell type for this?
                                pUndoDoc->SetString(ScAddress(nCol, i, nTab), OUString());
                            }
                        }
                        rUndoStr.clear();
                    }
                }

                nRow = nLastRow; // move to the last filtered row.
            }
            bFound = true;
            continue;
        }

        for (SCROW nRow = rRange.aStart.Row(); nRow <= rRange.aEnd.Row(); ++nRow)
        {
            if (bSkipFiltered)
                SkipFilteredRows(nRow, nLastNonFilteredRow, true);
            if (nRow > rRange.aEnd.Row())
                break;

            ScRefCellValue aCell = aCol[nCol].GetCellValue(nRow);
            if (aCell.isEmpty())
            {
                // empty cell found
                rMatchedRanges.Join(ScRange(nCol, nRow, nTab));
                bFound = true;

                if (bReplace)
                {
                    aCol[nCol].SetRawString(nRow, rSearchItem.GetReplaceString());
                    if (pUndoDoc)
                    {
                        // TODO: I'm using a string cell with empty content to
                        // trigger deletion of cell instance on undo.  Maybe I
                        // should create a new cell type for this?
                        pUndoDoc->SetString(ScAddress(nCol, nRow, nTab), OUString());
                    }
                }
            }
        }
    }
    return bFound;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */