summaryrefslogtreecommitdiff
path: root/sc/source/core/data/column3.cxx
blob: abbcd99701e387f1feef962ffbbe4a64280365b4 (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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
/* -*- 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 <boost/scoped_ptr.hpp>

#include <mdds/flat_segment_tree.hpp>

#include <sfx2/objsh.hxx>
#include <svl/zforlist.hxx>
#include <svl/zformat.hxx>
#include <svl/broadcast.hxx>

#include "scitems.hxx"
#include "column.hxx"
#include "cell.hxx"
#include "formulacell.hxx"
#include "document.hxx"
#include "attarray.hxx"
#include "patattr.hxx"
#include "cellform.hxx"
#include "typedstrdata.hxx"
#include "formula/errorcodes.hxx"
#include "formula/token.hxx"
#include "brdcst.hxx"
#include "docoptio.hxx"         // GetStdPrecision for GetMaxNumberStringLen
#include "subtotal.hxx"
#include "markdata.hxx"
#include "detfunc.hxx"          // For Notes for DeleteRange
#include "postit.hxx"
#include "stringutil.hxx"
#include "docpool.hxx"
#include "globalnames.hxx"
#include "cellvalue.hxx"
#include "tokenarray.hxx"

#include <com/sun/star/i18n/LocaleDataItem.hpp>

#include <cstdio>

using ::com::sun::star::i18n::LocaleDataItem;

// Err527 Workaroand
extern const ScFormulaCell* pLastFormulaTreeTop; // in cellform.cxx
using namespace formula;
// STATIC DATA -----------------------------------------------------------

void ScColumn::Insert( SCROW nRow, ScBaseCell* pNewCell )
{
    SetCell(nRow, pNewCell);

    // When we insert from the Clipboard we still have wrong (old) References!
    // First they are rewired in CopyBlockFromClip via UpdateReference and the
    // we call StartListeningFromClip and BroadcastFromClip.
    // If we insert into the Clipboard/andoDoc, we do not use a Broadcast.
    // After Import we call CalcAfterLoad and in there Listening.
    if ( !(pDocument->IsClipOrUndo() || pDocument->IsInsertingFromOtherDoc()) )
    {
        CellType eCellType = pNewCell->GetCellType();
        if (eCellType == CELLTYPE_FORMULA)
            static_cast<ScFormulaCell*>(pNewCell)->StartListeningTo(pDocument);

        // A note cell is only created by StartListeningCell when loading,
        // triggering Formula cells must be dirty anyway.
        if ( !(pDocument->IsCalcingAfterLoad() && eCellType == CELLTYPE_NOTE) )
        {
            if ( eCellType == CELLTYPE_FORMULA )
                ((ScFormulaCell*)pNewCell)->SetDirty();
            else
                pDocument->Broadcast( ScHint( SC_HINT_DATACHANGED,
                    ScAddress( nCol, nRow, nTab ), pNewCell->GetBroadcaster()) );
        }
    }
    bDirtyGroups = true;
}


void ScColumn::Insert( SCROW nRow, sal_uInt32 nNumberFormat, ScBaseCell* pCell )
{
    Insert(nRow, pCell);
    SetNumberFormat(nRow, nNumberFormat);
    bDirtyGroups = true;
}


void ScColumn::Append( SCROW nRow, ScBaseCell* pCell )
{
    maItems.push_back(ColEntry());
    maItems.back().pCell = pCell;
    maItems.back().nRow  = nRow;

    bDirtyGroups = true;
    maTextWidths.set<unsigned short>(nRow, TEXTWIDTH_DIRTY);
    maScriptTypes.set<unsigned short>(nRow, SC_SCRIPTTYPE_UNKNOWN);
    CellStorageModified();
}


void ScColumn::Delete( SCROW nRow )
{
    SCSIZE  nIndex;

    if (Search(nRow, nIndex))
    {
        ScBaseCell* pCell = maItems[nIndex].pCell;
        ScNoteCell* pNoteCell = new ScNoteCell;
        maItems[nIndex].pCell = pNoteCell; // Dummy for Interpret
        pDocument->Broadcast( ScHint( SC_HINT_DYING,
            ScAddress( nCol, nRow, nTab ), pCell->GetBroadcaster()));
        if ( SvtBroadcaster* pBC = pCell->ReleaseBroadcaster() )
        {
            pNoteCell->TakeBroadcaster( pBC );
        }
        else
        {
            pNoteCell->Delete();
            maItems.erase( maItems.begin() + nIndex);
            maTextWidths.set_empty(nRow, nRow);
            maScriptTypes.set_empty(nRow, nRow);
            // Should we free memory here (delta)? It'll be slower!
        }
        if (pCell->GetCellType() == CELLTYPE_FORMULA)
            static_cast<ScFormulaCell*>(pCell)->EndListeningTo(pDocument);
        pCell->Delete();
        bDirtyGroups = true;

        CellStorageModified();
    }
}


void ScColumn::DeleteAtIndex( SCSIZE nIndex )
{
    ScBaseCell* pCell = maItems[nIndex].pCell;
    SCROW nRow = maItems[nIndex].nRow;
    ScNoteCell* pNoteCell = new ScNoteCell;
    maItems[nIndex].pCell = pNoteCell; // Dummy for Interpret
    pDocument->Broadcast(
        ScHint(SC_HINT_DYING, ScAddress(nCol, nRow, nTab), pCell->GetBroadcaster()));
    pNoteCell->Delete();
    maItems.erase(maItems.begin() + nIndex);
    if (pCell->GetCellType() == CELLTYPE_FORMULA)
        static_cast<ScFormulaCell*>(pCell)->EndListeningTo(pDocument);
    pCell->Delete();

    bDirtyGroups = true;
    maTextWidths.set_empty(nRow, nRow);
    maScriptTypes.set_empty(nRow, nRow);
    CellStorageModified();
}


void ScColumn::FreeAll()
{
    for (SCSIZE i = 0; i < maItems.size(); i++)
        maItems[i].pCell->Delete();
    maItems.clear();

    // Text width should keep a logical empty range of 0-MAXROW when the cell array is empty.
    maTextWidths.clear();
    maTextWidths.resize(MAXROWCOUNT);
    maScriptTypes.clear();
    maScriptTypes.resize(MAXROWCOUNT);
    CellStorageModified();
}


void ScColumn::DeleteRow( SCROW nStartRow, SCSIZE nSize )
{
    pAttrArray->DeleteRow( nStartRow, nSize );

    if ( maItems.empty() )
        return ;

    SCSIZE nFirstIndex;
    Search( nStartRow, nFirstIndex );
    if ( nFirstIndex >= maItems.size() )
        return ;

    sal_Bool bOldAutoCalc = pDocument->GetAutoCalc();
    pDocument->SetAutoCalc( false ); // Avoid calculating it multiple times

    bDirtyGroups = true;

    sal_Bool bFound=false;
    SCROW nEndRow = nStartRow + nSize - 1;
    SCSIZE nStartIndex = 0;
    SCSIZE nEndIndex = 0;
    SCSIZE i;

    for ( i = nFirstIndex; i < maItems.size() && maItems[i].nRow <= nEndRow; i++ )
    {
        if (!bFound)
        {
            nStartIndex = i;
            bFound = sal_True;
        }
        nEndIndex = i;

        ScBaseCell* pCell = maItems[i].pCell;
        SvtBroadcaster* pBC = pCell->GetBroadcaster();
        if (pBC)
        {
            // Now returns invalid reference; direct References are not moved
            pCell->DeleteBroadcaster();
            // We delete empty Broadcaster in DeleteRange
        }
    }
    if (bFound)
    {
        DeleteRange( nStartIndex, nEndIndex, IDF_CONTENTS );
        Search( nStartRow, i );
        if ( i >= maItems.size() )
        {
            pDocument->SetAutoCalc( bOldAutoCalc );
            return ;
        }
    }
    else
        i = nFirstIndex;

    // There are cells below the deletion point.  Shift their row positions.

    // Shift the text width array too (before the broadcast).
    maTextWidths.erase(nStartRow, nEndRow);
    maTextWidths.resize(MAXROWCOUNT);
    maScriptTypes.erase(nStartRow, nEndRow);
    maScriptTypes.resize(MAXROWCOUNT);

    ScAddress aAdr( nCol, 0, nTab );
    ScHint aHint( SC_HINT_DATACHANGED, aAdr, NULL ); // only areas (ScBaseCell* == NULL)
    ScAddress& rAddress = aHint.GetAddress();
    // for sparse occupation use single broadcasts, not ranges
    bool bSingleBroadcasts = (((maItems.back().nRow - maItems[i].nRow) /
                (maItems.size() - i)) > 1);
    if ( bSingleBroadcasts )
    {
        SCROW nLastBroadcast = MAXROW+1;
        for ( ; i < maItems.size(); i++ )
        {
            SCROW nOldRow = maItems[i].nRow;
            // Broadcast change in source
            rAddress.SetRow( nOldRow );
            pDocument->AreaBroadcast( aHint );
            SCROW nNewRow = (maItems[i].nRow -= nSize);
            // Broadcast change in target
            if ( nLastBroadcast != nNewRow )
            {   // Do not broadcast successive ones
                rAddress.SetRow( nNewRow );
                pDocument->AreaBroadcast( aHint );
            }
            nLastBroadcast = nOldRow;
            ScBaseCell* pCell = maItems[i].pCell;
            if ( pCell->GetCellType() == CELLTYPE_FORMULA )
                ((ScFormulaCell*)pCell)->aPos.SetRow( nNewRow );
        }
    }
    else
    {
        rAddress.SetRow( maItems[i].nRow );
        ScRange aRange( rAddress );
        aRange.aEnd.SetRow( maItems.back().nRow );
        for ( ; i < maItems.size(); i++ )
        {
            SCROW nNewRow = (maItems[i].nRow -= nSize);
            ScBaseCell* pCell = maItems[i].pCell;
            if ( pCell->GetCellType() == CELLTYPE_FORMULA )
                ((ScFormulaCell*)pCell)->aPos.SetRow( nNewRow );
        }
        pDocument->AreaBroadcastInRange( aRange, aHint );
    }

    CellStorageModified();
    pDocument->SetAutoCalc( bOldAutoCalc );
}

namespace {

bool isDate(const ScDocument& rDoc, const ScColumn& rCol, SCROW nRow)
{
    sal_uLong nIndex = (sal_uLong)((SfxUInt32Item*)rCol.GetAttr(nRow, ATTR_VALUE_FORMAT))->GetValue();
    short nType = rDoc.GetFormatTable()->GetType(nIndex);
    return (nType == NUMBERFORMAT_DATE) || (nType == NUMBERFORMAT_TIME) || (nType == NUMBERFORMAT_DATETIME);
}

bool checkDeleteCellByFlag(
    CellType eCellType, sal_uInt16 nDelFlag, const ScDocument& rDoc, const ScColumn& rCol, const ColEntry& rEntry)
{
    bool bDelete = false;

    switch (eCellType)
    {
        case CELLTYPE_VALUE:
        {
            sal_uInt16 nValFlags = nDelFlag & (IDF_DATETIME|IDF_VALUE);
            // delete values and dates?
            bDelete = nValFlags == (IDF_DATETIME|IDF_VALUE);
            // if not, decide according to cell number format
            if (!bDelete && (nValFlags != 0))
            {
                bool bIsDate = isDate(rDoc, rCol, rEntry.nRow);
                bDelete = nValFlags == (bIsDate ? IDF_DATETIME : IDF_VALUE);
            }
        }
        break;
        case CELLTYPE_STRING:
        case CELLTYPE_EDIT:
            bDelete = (nDelFlag & IDF_STRING) != 0;
        break;
        case CELLTYPE_FORMULA:
            bDelete = (nDelFlag & IDF_FORMULA) != 0;
        break;
        case CELLTYPE_NOTE:
            // do note delete note cell with broadcaster
            bDelete = !rEntry.pCell->GetBroadcaster();
        break;
        default:; // added to avoid warnings
    }

    return bDelete;
}

}

void ScColumn::DeleteRange( SCSIZE nStartIndex, SCSIZE nEndIndex, sal_uInt16 nDelFlag )
{
    /*  If caller specifies to not remove the note caption objects, all cells
        have to forget the pointers to them. This is used e.g. while undoing a
        "paste cells" operation, which removes the caption objects later in
        drawing undo. */

    ScHint aHint( SC_HINT_DYING, ScAddress( nCol, 0, nTab ), 0 );

    // cache all formula cells, they will be deleted at end of this function
    typedef ::std::vector< ScFormulaCell* > FormulaCellVector;
    FormulaCellVector aDelCells;
    aDelCells.reserve( nEndIndex - nStartIndex + 1 );

    typedef mdds::flat_segment_tree<SCSIZE, bool> RemovedSegments_t;
    RemovedSegments_t aRemovedSegments(nStartIndex, maItems.size(), false);
    SCSIZE nFirst = nStartIndex;

    // dummy replacement for old cells, to prevent that interpreter uses old cell
    boost::scoped_ptr<ScNoteCell> pDummyCell(new ScNoteCell);

    for ( SCSIZE nIdx = nStartIndex; nIdx <= nEndIndex; ++nIdx )
    {
        if (((nDelFlag & IDF_CONTENTS) == IDF_CONTENTS) && !maItems[ nIdx ].pCell->GetBroadcaster())
        {
            // all content is deleted and cell does not contain broadcaster

            ScBaseCell* pOldCell = maItems[ nIdx ].pCell;
            if (pOldCell->GetCellType() == CELLTYPE_FORMULA)
            {
                // cache formula cell, will be deleted below
                aDelCells.push_back( static_cast< ScFormulaCell* >( pOldCell ) );
            }
            else
            {
                // interpret in broadcast must not use the old cell
                maItems[ nIdx ].pCell = pDummyCell.get();
                aHint.GetAddress().SetRow( maItems[ nIdx ].nRow );
                aHint.SetBroadcaster(pOldCell->GetBroadcaster());
                pDocument->Broadcast( aHint );
                pOldCell->Delete();
            }
            continue;
        }

        // delete some contents of the cells, or cells with broadcaster
        bool bDelete = false;
        ScBaseCell* pOldCell = maItems[nIdx].pCell;
        CellType eCellType = pOldCell->GetCellType();
        if ((nDelFlag & IDF_CONTENTS) == IDF_CONTENTS)
            // All cell types to be deleted.
            bDelete = true;
        else
        {
            // Decide whether to delete the cell object according to passed
            // flags.
            bDelete = checkDeleteCellByFlag(eCellType, nDelFlag, *pDocument, *this, maItems[nIdx]);
        }

        if (bDelete)
        {
            // Try to create a replacement "note" cell if broadcaster exists.
            ScNoteCell* pNoteCell = NULL;
            SvtBroadcaster* pBC = pOldCell->GetBroadcaster();
            if (pBC && pBC->HasListeners())
            {
                // NOTE: the broadcaster here is transferred and released only
                // if it has listeners! If it does not, it will simply be
                // deleted when the cell is deleted and no replacement cell is
                // created.
                pNoteCell = new ScNoteCell(pBC);
                pOldCell->ReleaseBroadcaster();
            }

            // remove cell entry in cell item list
            SCROW nOldRow = maItems[nIdx].nRow;
            if (pNoteCell)
            {
                // replace old cell with the replacement note cell
                maItems[nIdx].pCell = pNoteCell;
                // ... so it's not really deleted
                bDelete = false;
            }
            else
                maItems[nIdx].pCell = pDummyCell.get();

            if (eCellType == CELLTYPE_FORMULA)
            {
                // Cache formula cells (will be deleted later), delete cell of other type.
                aDelCells.push_back(static_cast<ScFormulaCell*>(pOldCell));
            }
            else
            {
                aHint.GetAddress().SetRow(nOldRow);
                SvtBroadcaster* pHintBC = NULL;
                if (pNoteCell)
                    pHintBC = pNoteCell->GetBroadcaster();
                else if (pOldCell)
                    pHintBC = pOldCell->GetBroadcaster();
                aHint.SetBroadcaster(pHintBC);
                pDocument->Broadcast(aHint);
                if (pNoteCell != pOldCell)
                {
                    pOldCell->Delete();
                }
            }
        }

        if (!bDelete)
        {
            // We just came to a non-deleted cell after a segment of
            // deleted ones. So we need to remember the segment
            // before moving on.
            if (nFirst < nIdx)
                aRemovedSegments.insert_back(nFirst, nIdx, true);
            nFirst = nIdx + 1;
        }
    }
    // there is a segment of deleted cells at the end
    if (nFirst <= nEndIndex)
        aRemovedSegments.insert_back(nFirst, nEndIndex + 1, true);

    {
        // Remove segments from the column array, containing pDummyCell and
        // formula cell pointers to be deleted.

        RemovedSegments_t::const_reverse_iterator it = aRemovedSegments.rbegin();
        RemovedSegments_t::const_reverse_iterator itEnd = aRemovedSegments.rend();

        std::vector<ColEntry>::iterator itErase, itEraseEnd;
        SCSIZE nEndSegment = it->first; // should equal maItems.size(). Non-inclusive.
        // Skip the first node.
        for (++it; it != itEnd; ++it)
        {
            if (!it->second)
            {
                // Don't remove this segment.
                nEndSegment = it->first;
                continue;
            }

            // Remove this segment.
            SCSIZE nStartSegment = it->first;
            SCROW nStartRow = maItems[nStartSegment].nRow;
            SCROW nEndRow = maItems[nEndSegment-1].nRow;

            itErase = maItems.begin();
            std::advance(itErase, nStartSegment);
            itEraseEnd = maItems.begin();
            std::advance(itEraseEnd, nEndSegment);
            maItems.erase(itErase, itEraseEnd);

            maTextWidths.set_empty(nStartRow, nEndRow);
            maScriptTypes.set_empty(nStartRow, nEndRow);

            nEndSegment = nStartSegment;
        }
    }

    // *** delete all formula cells ***
    if (!aDelCells.empty())
    {
        // First, all cells stop listening, may save unneeded broadcasts and
        // recalcualtions.
        // NOTE: this actually may remove ScNoteCell entries from maItems if
        // the last listener is removed from a broadcaster.
        for ( FormulaCellVector::iterator aIt = aDelCells.begin(), aEnd = aDelCells.end(); aIt != aEnd; ++aIt )
            (*aIt)->EndListeningTo( pDocument );

        // NOTE: the vector does not contain cells with broadcasters that have
        // listeners. If it would, broadcasters that were deleted during
        // EndListeningTo() would have to be released from these cells.

        // broadcast SC_HINT_DYING for all cells and delete them
        for ( FormulaCellVector::iterator aIt = aDelCells.begin(), aEnd = aDelCells.end(); aIt != aEnd; ++aIt )
        {
            // A formula cell's broadcaster now is at the replacement cell, use
            // that. If there is no cell anymore it means all listeners are
            // gone for this formula cell and the replacement cell was removed
            // from maItems.
            SCSIZE nIndex;
            ScBaseCell* pCell = (Search( (*aIt)->aPos.Row(), nIndex) ? maItems[nIndex].pCell : NULL);
            aHint.SetBroadcaster(pCell ? pCell->GetBroadcaster() : NULL);
            aHint.SetAddress( (*aIt)->aPos );
            pDocument->Broadcast( aHint );
            (*aIt)->Delete();
        }
    }

    bDirtyGroups = true;
}


void ScColumn::DeleteArea(SCROW nStartRow, SCROW nEndRow, sal_uInt16 nDelFlag)
{
    //  FreeAll must not be called here due to Broadcasters
    //  Delete attribute at the end so that we can distinguish between numbers and dates

    sal_uInt16 nContMask = IDF_CONTENTS;
    // IDF_NOCAPTIONS needs to be passed too, if IDF_NOTE is set
    if( nDelFlag & IDF_NOTE )
        nContMask |= IDF_NOCAPTIONS;
    sal_uInt16 nContFlag = nDelFlag & nContMask;

    if ( !maItems.empty() && nContFlag)
    {
        if (nStartRow==0 && nEndRow==MAXROW)
            DeleteRange( 0, maItems.size()-1, nContFlag );
        else
        {
            sal_Bool bFound=false;
            SCSIZE nStartIndex = 0;
            SCSIZE nEndIndex = 0;
            for (SCSIZE i = 0; i < maItems.size(); i++)
                if ((maItems[i].nRow >= nStartRow) && (maItems[i].nRow <= nEndRow))
                {
                    if (!bFound)
                    {
                        nStartIndex = i;
                        bFound = sal_True;
                    }
                    nEndIndex = i;
                }
            if (bFound)
                DeleteRange( nStartIndex, nEndIndex, nContFlag );
        }
    }

    if ( nDelFlag & IDF_EDITATTR )
    {
        OSL_ENSURE( nContFlag == 0, "DeleteArea: Wrong Flags" );
        RemoveEditAttribs( nStartRow, nEndRow );
    }

    // Delete attributes just now
    if ((nDelFlag & IDF_ATTRIB) == IDF_ATTRIB) pAttrArray->DeleteArea( nStartRow, nEndRow );
    else if ((nDelFlag & IDF_ATTRIB) != 0) pAttrArray->DeleteHardAttr( nStartRow, nEndRow );

    bDirtyGroups = true;
}


ScFormulaCell* ScColumn::CreateRefCell( ScDocument* pDestDoc, const ScAddress& rDestPos,
                                            SCSIZE nIndex, sal_uInt16 nFlags ) const
{
    sal_uInt16 nContFlags = nFlags & IDF_CONTENTS;
    if (!nContFlags)
        return NULL;

    // Test whether the Cell should be copied
    // Also do this for IDF_CONTENTS, due to Notes/Broadcasters
    sal_Bool bMatch = false;
    ScBaseCell* pCell = maItems[nIndex].pCell;
    CellType eCellType = pCell->GetCellType();
    switch ( eCellType )
    {
        case CELLTYPE_VALUE:
            {
                sal_uInt16 nValFlags = nFlags & (IDF_DATETIME|IDF_VALUE);

                if ( nValFlags == (IDF_DATETIME|IDF_VALUE) )
                    bMatch = sal_True;
                else if ( nValFlags )
                {
                    sal_uLong nNumIndex = (sal_uLong)((SfxUInt32Item*)GetAttr(
                                    maItems[nIndex].nRow, ATTR_VALUE_FORMAT ))->GetValue();
                    short nTyp = pDocument->GetFormatTable()->GetType(nNumIndex);
                    if ((nTyp == NUMBERFORMAT_DATE) || (nTyp == NUMBERFORMAT_TIME) || (nTyp == NUMBERFORMAT_DATETIME))
                        bMatch = ((nFlags & IDF_DATETIME) != 0);
                    else
                        bMatch = ((nFlags & IDF_VALUE) != 0);
                }
            }
            break;
        case CELLTYPE_STRING:
        case CELLTYPE_EDIT:     bMatch = ((nFlags & IDF_STRING) != 0); break;
        case CELLTYPE_FORMULA:  bMatch = ((nFlags & IDF_FORMULA) != 0); break;
        default:
        {
            // added to avoid warnings
        }
    }
    if (!bMatch)
        return NULL;


    // Insert Reference
    ScSingleRefData aRef;
    aRef.nCol = nCol;
    aRef.nRow = maItems[nIndex].nRow;
    aRef.nTab = nTab;
    aRef.InitFlags(); // -> Everything absolute
    aRef.SetFlag3D(true);

    // 3D (false) and TabRel (true), if the final Position is at the same Table?
    // The target position is not yet known for TransposeClip!

    aRef.CalcRelFromAbs( rDestPos );

    ScTokenArray aArr;
    aArr.AddSingleReference( aRef );

    return new ScFormulaCell( pDestDoc, rDestPos, &aArr );
}


//  rColumn = source
//  nRow1, nRow2 = target position

void ScColumn::CopyFromClip(SCROW nRow1, SCROW nRow2, long nDy,
                                sal_uInt16 nInsFlag, bool bAsLink, bool bSkipAttrForEmpty,
                                ScColumn& rColumn)
{
    if ((nInsFlag & IDF_ATTRIB) != 0)
    {
        if ( bSkipAttrForEmpty )
        {
            //  copy only attributes for non-empty cells
            //  (notes are not counted as non-empty here, to match the content behavior)

            SCSIZE nStartIndex;
            rColumn.Search( nRow1-nDy, nStartIndex );
            while ( nStartIndex < rColumn.maItems.size() && rColumn.maItems[nStartIndex].nRow <= nRow2-nDy )
            {
                SCSIZE nEndIndex = nStartIndex;
                if ( rColumn.maItems[nStartIndex].pCell->GetCellType() != CELLTYPE_NOTE )
                {
                    SCROW nStartRow = rColumn.maItems[nStartIndex].nRow;
                    SCROW nEndRow = nStartRow;

                    //  find consecutive non-empty cells
                    while ( nEndRow < nRow2-nDy &&
                            nEndIndex+1 < rColumn.maItems.size() &&
                            rColumn.maItems[nEndIndex+1].nRow == nEndRow+1 &&
                            rColumn.maItems[nEndIndex+1].pCell->GetCellType() != CELLTYPE_NOTE )
                    {
                        ++nEndIndex;
                        ++nEndRow;
                    }

                    rColumn.pAttrArray->CopyAreaSafe( nStartRow+nDy, nEndRow+nDy, nDy, *pAttrArray );
                }
                nStartIndex = nEndIndex + 1;
            }
        }
        else
            rColumn.pAttrArray->CopyAreaSafe( nRow1, nRow2, nDy, *pAttrArray );
    }
    if ((nInsFlag & IDF_CONTENTS) == 0)
        return;

    if ( bAsLink && nInsFlag == IDF_ALL )
    {
        // We also reference empty cells for "ALL"
        // IDF_ALL must always contain more flags when compared to "Insert contents" as
        // contents can be selected one by one!

        ReserveSize(maItems.size() + static_cast<SCSIZE>(nRow2-nRow1+1));

        ScAddress aDestPos( nCol, 0, nTab ); // Adapt Row

        //  Create reference (Source Position)
        ScSingleRefData aRef;
        aRef.nCol = rColumn.nCol;
        //  Adapt nRow
        aRef.nTab = rColumn.nTab;
        aRef.InitFlags(); // -> All absolute
        aRef.SetFlag3D(true);

        for (SCROW nDestRow = nRow1; nDestRow <= nRow2; nDestRow++)
        {
            aRef.nRow = nDestRow - nDy; // Source row
            aDestPos.SetRow( nDestRow );

            aRef.CalcRelFromAbs( aDestPos );
            ScTokenArray aArr;
            aArr.AddSingleReference( aRef );
            Insert( nDestRow, new ScFormulaCell( pDocument, aDestPos, &aArr ) );
        }

        return;
    }

    SCSIZE nColCount = rColumn.maItems.size();

    // ignore IDF_FORMULA - "all contents but no formulas" results in the same number of cells
    if ((nInsFlag & ( IDF_CONTENTS & ~IDF_FORMULA )) == ( IDF_CONTENTS & ~IDF_FORMULA ) && nRow2-nRow1 >= 64)
    {
        //! Always do the Resize from the outside, where the number of repetitions is known
        //! (then it can be removed here)

        ReserveSize(maItems.size() + nColCount);
    }

    sal_Bool bAtEnd = false;
    for (SCSIZE i = 0; i < nColCount && !bAtEnd; i++)
    {
        SCsROW nDestRow = rColumn.maItems[i].nRow + nDy;
        if ( nDestRow > (SCsROW) nRow2 )
            bAtEnd = sal_True;
        else if ( nDestRow >= (SCsROW) nRow1 )
        {
            // rows at the beginning may be skipped if filtered rows are left out,
            // nDestRow may be negative then

            ScAddress aDestPos( nCol, (SCROW)nDestRow, nTab );

            ScBaseCell* pNewCell = bAsLink ?
                rColumn.CreateRefCell( pDocument, aDestPos, i, nInsFlag ) :
                rColumn.CloneCell( i, nInsFlag, *pDocument, aDestPos );
            if (pNewCell)
                Insert( aDestPos.Row(), pNewCell );
        }
    }
}


namespace {

/**
 * Helper for ScColumn::CloneCell
 * Decide whether to clone a value cell depending on clone flags and number format.
 */
bool lclCanCloneValue( ScDocument& rDoc, const ScColumn& rCol, SCROW nRow, bool bCloneValue, bool bCloneDateTime )
{
    // values and dates, or nothing to be cloned -> not needed to check number format
    if( bCloneValue == bCloneDateTime )
        return bCloneValue;

    // check number format of value cell
    sal_uLong nNumIndex = (sal_uLong)((SfxUInt32Item*)rCol.GetAttr( nRow, ATTR_VALUE_FORMAT ))->GetValue();
    short nTyp = rDoc.GetFormatTable()->GetType( nNumIndex );
    bool bIsDateTime = (nTyp == NUMBERFORMAT_DATE) || (nTyp == NUMBERFORMAT_TIME) || (nTyp == NUMBERFORMAT_DATETIME);
    return bIsDateTime ? bCloneDateTime : bCloneValue;
}

} // namespace


ScBaseCell* ScColumn::CloneCell(
    SCSIZE nIndex, sal_uInt16 nFlags, ScDocument& rDestDoc, const ScAddress& rDestPos) const
{
    bool bCloneValue    = (nFlags & IDF_VALUE) != 0;
    bool bCloneDateTime = (nFlags & IDF_DATETIME) != 0;
    bool bCloneString   = (nFlags & IDF_STRING) != 0;
    bool bCloneSpecialBoolean  = (nFlags & IDF_SPECIAL_BOOLEAN) != 0;
    bool bCloneFormula  = (nFlags & IDF_FORMULA) != 0;
    bool bForceFormula  = false;

    ScBaseCell* pNew = 0;
    ScBaseCell& rSource = *maItems[nIndex].pCell;
    switch (rSource.GetCellType())
    {
        case CELLTYPE_NOTE:
            // note will be cloned below
        break;

        case CELLTYPE_STRING:
        case CELLTYPE_EDIT:
            // note will be cloned below
            if (bCloneString)
                pNew = rSource.Clone( rDestDoc, rDestPos );
        break;

        case CELLTYPE_VALUE:
            // note will be cloned below
            if (lclCanCloneValue( *pDocument, *this, maItems[nIndex].nRow, bCloneValue, bCloneDateTime ))
                pNew = rSource.Clone( rDestDoc, rDestPos );
        break;

        case CELLTYPE_FORMULA:
            if ( bCloneSpecialBoolean )
            {
                ScFormulaCell& rForm = (ScFormulaCell&)rSource;
                OUStringBuffer aBuf;
                // FIXME: do we have a localisation issue here?
                rForm.GetFormula( aBuf );
                OUString aVal( aBuf.makeStringAndClear() );
                if ( aVal == "=TRUE()" || aVal == "=FALSE()" )
                    bForceFormula = true;
            }
            if (bForceFormula || bCloneFormula)
            {
                // note will be cloned below
                pNew = rSource.Clone( rDestDoc, rDestPos );
            }
            else if ( (bCloneValue || bCloneDateTime || bCloneString) && !rDestDoc.IsUndo() )
            {
                // Always just copy the original row to the Undo Documen;
                // do not create Value/string cells from formulas
                ScFormulaCell& rForm = (ScFormulaCell&)rSource;
                sal_uInt16 nErr = rForm.GetErrCode();
                if ( nErr )
                {
                    // error codes are cloned with values
                    if (bCloneValue)
                    {
                        ScFormulaCell* pErrCell = new ScFormulaCell( &rDestDoc, rDestPos );
                        pErrCell->SetErrCode( nErr );
                        pNew = pErrCell;
                    }
                }
                else if (rForm.IsValue())
                {
                    if (lclCanCloneValue( *pDocument, *this, maItems[nIndex].nRow, bCloneValue, bCloneDateTime ))
                    {
                        double nVal = rForm.GetValue();
                        pNew = new ScValueCell(nVal);
                    }
                }
                else if (bCloneString)
                {
                    String aString = rForm.GetString();
                    // do not clone empty string
                    if (aString.Len() > 0)
                    {
                        if ( rForm.IsMultilineResult() )
                        {
                            pNew = new ScEditCell( aString, &rDestDoc );
                        }
                        else
                        {
                            pNew = new ScStringCell( aString );
                        }
                    }
                }
            }
        break;

        default: OSL_FAIL( "ScColumn::CloneCell - unknown cell type" );
    }

    return pNew;
}


void ScColumn::MixMarked( const ScMarkData& rMark, sal_uInt16 nFunction,
                            bool bSkipEmpty, ScColumn& rSrcCol )
{
    SCROW nRow1, nRow2;

    if (rMark.IsMultiMarked())
    {
        ScMarkArrayIter aIter( rMark.GetArray()+nCol );
        while (aIter.Next( nRow1, nRow2 ))
            MixData( nRow1, nRow2, nFunction, bSkipEmpty, rSrcCol );
    }
}


// Result in rVal1
static sal_Bool lcl_DoFunction( double& rVal1, double nVal2, sal_uInt16 nFunction )
{
    sal_Bool bOk = false;
    switch (nFunction)
    {
        case PASTE_ADD:
            bOk = SubTotal::SafePlus( rVal1, nVal2 );
            break;
        case PASTE_SUB:
            nVal2 = -nVal2;     // FIXME: Can we do this alwyas without error?
            bOk = SubTotal::SafePlus( rVal1, nVal2 );
            break;
        case PASTE_MUL:
            bOk = SubTotal::SafeMult( rVal1, nVal2 );
            break;
        case PASTE_DIV:
            bOk = SubTotal::SafeDiv( rVal1, nVal2 );
            break;
    }
    return bOk;
}


static void lcl_AddCode( ScTokenArray& rArr, ScFormulaCell* pCell )
{
    rArr.AddOpCode(ocOpen);

    ScTokenArray* pCode = pCell->GetCode();
    if (pCode)
    {
        const formula::FormulaToken* pToken = pCode->First();
        while (pToken)
        {
            rArr.AddToken( *pToken );
            pToken = pCode->Next();
        }
    }

    rArr.AddOpCode(ocClose);
}


void ScColumn::MixData( SCROW nRow1, SCROW nRow2,
                            sal_uInt16 nFunction, bool bSkipEmpty,
                            ScColumn& rSrcCol )
{
    SCSIZE nSrcCount = rSrcCol.maItems.size();

    SCSIZE nIndex;
    Search( nRow1, nIndex );

//  SCSIZE nSrcIndex = 0;
    SCSIZE nSrcIndex;
    rSrcCol.Search( nRow1, nSrcIndex ); // See if data is at the beginning

    SCROW nNextThis = MAXROW+1;
    if ( nIndex < maItems.size() )
        nNextThis = maItems[nIndex].nRow;
    SCROW nNextSrc = MAXROW+1;
    if ( nSrcIndex < nSrcCount )
        nNextSrc = rSrcCol.maItems[nSrcIndex].nRow;

    while ( nNextThis <= nRow2 || nNextSrc <= nRow2 )
    {
        SCROW nRow = Min( nNextThis, nNextSrc );

        ScBaseCell* pSrc = NULL;
        ScBaseCell* pDest = NULL;
        ScBaseCell* pNew = NULL;
        sal_Bool bDelete = false;

        if ( nSrcIndex < nSrcCount && nNextSrc == nRow )
            pSrc = rSrcCol.maItems[nSrcIndex].pCell;

        if ( nIndex < maItems.size() && nNextThis == nRow )
            pDest = maItems[nIndex].pCell;

        OSL_ENSURE( pSrc || pDest, "What happened?" );

        CellType eSrcType  = pSrc  ? pSrc->GetCellType()  : CELLTYPE_NONE;
        CellType eDestType = pDest ? pDest->GetCellType() : CELLTYPE_NONE;

        sal_Bool bSrcEmpty = ( eSrcType == CELLTYPE_NONE || eSrcType == CELLTYPE_NOTE );
        sal_Bool bDestEmpty = ( eDestType == CELLTYPE_NONE || eDestType == CELLTYPE_NOTE );

        if ( bSkipEmpty && bDestEmpty ) // Restore original row
        {
            if ( pSrc ) // Did we have a row here?
            {
                pNew = pSrc->Clone( *pDocument );
            }
        }
        else if ( nFunction ) // Really provide calculation function
        {
            double nVal1;
            double nVal2;
            if ( eSrcType == CELLTYPE_VALUE )
                nVal1 = ((ScValueCell*)pSrc)->GetValue();
            else
                nVal1 = 0.0;
            if ( eDestType == CELLTYPE_VALUE )
                nVal2 = ((ScValueCell*)pDest)->GetValue();
            else
                nVal2 = 0.0;

            // Empty row is treated as a value
            sal_Bool bSrcVal  = ( bSrcEmpty || eSrcType == CELLTYPE_VALUE );
            sal_Bool bDestVal  = ( bDestEmpty || eDestType == CELLTYPE_VALUE );

            sal_Bool bSrcText = ( eSrcType == CELLTYPE_STRING ||
                                eSrcType == CELLTYPE_EDIT );
            sal_Bool bDestText = ( eDestType == CELLTYPE_STRING ||
                                eDestType == CELLTYPE_EDIT );

            // Else we only have formulas ...
            if ( bSrcEmpty && bDestEmpty )
            {
                // Both empty -> do nothing
            }
            else if ( bSrcVal && bDestVal )
            {
                // Insterted new value or both have overflown
                sal_Bool bOk = lcl_DoFunction( nVal1, nVal2, nFunction );

                if (bOk)
                    pNew = new ScValueCell( nVal1 );
                else
                {
                    ScFormulaCell* pFC = new ScFormulaCell( pDocument,
                                                ScAddress( nCol, nRow, nTab ) );
                    pFC->SetErrCode( errNoValue );
                    //! oder NOVALUE, dann auch in consoli,
                    //! sonst in Interpreter::GetCellValue die Abfrage auf errNoValue raus
                    //! (dann geht Stringzelle+Wertzelle nicht mehr)
                    pNew = pFC;
                }
            }
            else if ( bSrcText || bDestText )
            {
                // We do no not calculate with texts - alwyas "old" cell, thus pSrc
                if (pSrc)
                    pNew = pSrc->Clone( *pDocument );
                else if (pDest)
                    bDelete = sal_True;
            }
            else
            {
                // Combination of value and at least one formula -> Create formula
                ScTokenArray aArr;

                // First row
                if ( eSrcType == CELLTYPE_FORMULA )
                    lcl_AddCode( aArr, (ScFormulaCell*)pSrc );
                else
                    aArr.AddDouble( nVal1 );

                // Operator
                OpCode eOp = ocAdd;
                switch ( nFunction )
                {
                    case PASTE_ADD: eOp = ocAdd; break;
                    case PASTE_SUB: eOp = ocSub; break;
                    case PASTE_MUL: eOp = ocMul; break;
                    case PASTE_DIV: eOp = ocDiv; break;
                }
                aArr.AddOpCode(eOp); // Function

                // Second row
                if ( eDestType == CELLTYPE_FORMULA )
                    lcl_AddCode( aArr, (ScFormulaCell*)pDest );
                else
                    aArr.AddDouble( nVal2 );

                pNew = new ScFormulaCell( pDocument, ScAddress( nCol, nRow, nTab ), &aArr );
            }
        }


        if ( pNew || bDelete ) // New result?
        {
            if (pDest && !pNew) // Old cell present?
            {
                if ( pDest->GetBroadcaster() )
                    pNew = new ScNoteCell; // Take over Broadcaster
                else
                    Delete(nRow); // -> Delete
            }
            if (pNew)
                Insert(nRow, pNew); // Insert new one

            Search( nRow, nIndex ); // Everything could have moved
            if (pNew)
                nNextThis = nRow; // nIndex points right at nRow now
            else
                nNextThis = ( nIndex < maItems.size() ) ? maItems[nIndex].nRow : MAXROW+1;
        }

        if ( nNextThis == nRow )
        {
            ++nIndex;
            nNextThis = ( nIndex < maItems.size() ) ? maItems[nIndex].nRow : MAXROW+1;
        }
        if ( nNextSrc == nRow )
        {
            ++nSrcIndex;
            nNextSrc = ( nSrcIndex < nSrcCount ) ?
                            rSrcCol.maItems[nSrcIndex].nRow :
                            MAXROW+1;
        }
    }
}


ScAttrIterator* ScColumn::CreateAttrIterator( SCROW nStartRow, SCROW nEndRow ) const
{
    return new ScAttrIterator( pAttrArray, nStartRow, nEndRow );
}


void ScColumn::StartAllListeners()
{
    if ( !maItems.empty() )
        for (SCSIZE i = 0; i < maItems.size(); i++)
        {
            ScBaseCell* pCell = maItems[i].pCell;
            if ( pCell->GetCellType() == CELLTYPE_FORMULA )
            {
                SCROW nRow = maItems[i].nRow;
                ((ScFormulaCell*)pCell)->StartListeningTo( pDocument );
                if ( nRow != maItems[i].nRow )
                    Search( nRow, i ); // Insert Listener?
            }
        }
}


void ScColumn::StartNeededListeners()
{
    if ( !maItems.empty() )
    {
        for (SCSIZE i = 0; i < maItems.size(); i++)
        {
            ScBaseCell* pCell = maItems[i].pCell;
            if ( pCell->GetCellType() == CELLTYPE_FORMULA )
            {
                ScFormulaCell* pFCell = static_cast<ScFormulaCell*>(pCell);
                if (pFCell->NeedsListening())
                {
                    SCROW nRow = maItems[i].nRow;
                    pFCell->StartListeningTo( pDocument );
                    if ( nRow != maItems[i].nRow )
                        Search( nRow, i ); // Insert Listener?
                }
            }
        }
    }
}


void ScColumn::BroadcastInArea( SCROW nRow1, SCROW nRow2 )
{
    if ( !maItems.empty() )
    {
        SCROW nRow;
        SCSIZE nIndex;
        Search( nRow1, nIndex );
        while ( nIndex < maItems.size() && (nRow = maItems[nIndex].nRow) <= nRow2 )
        {
            ScBaseCell* pCell = maItems[nIndex].pCell;
            if ( pCell->GetCellType() == CELLTYPE_FORMULA )
                ((ScFormulaCell*)pCell)->SetDirty();
            else
                pDocument->Broadcast( ScHint( SC_HINT_DATACHANGED,
                    ScAddress(nCol, nRow, nTab), pCell->GetBroadcaster()));
            nIndex++;
        }
    }
}


void ScColumn::StartListeningInArea( SCROW nRow1, SCROW nRow2 )
{
    if ( !maItems.empty() )
    {
        SCROW nRow;
        SCSIZE nIndex;
        Search( nRow1, nIndex );
        while ( nIndex < maItems.size() && (nRow = maItems[nIndex].nRow) <= nRow2 )
        {
            ScBaseCell* pCell = maItems[nIndex].pCell;
            if ( pCell->GetCellType() == CELLTYPE_FORMULA )
                ((ScFormulaCell*)pCell)->StartListeningTo( pDocument );
            if ( nRow != maItems[nIndex].nRow )
                Search( nRow, nIndex ); // Inserted via Listening
            nIndex++;
        }
    }
}


/**
 * Returns true if the cell format was set as well
 */
bool ScColumn::SetString( SCROW nRow, SCTAB nTabP, const String& rString,
                          formula::FormulaGrammar::AddressConvention eConv,
                          ScSetStringParam* pParam )
{
    bool bNumFmtSet = false;
    if (!ValidRow(nRow))
        return false;

    ScBaseCell* pNewCell = NULL;
    sal_Bool bIsLoading = false;
    if (rString.Len() > 0)
    {
        ScSetStringParam aParam;
        if (pParam)
            aParam = *pParam;

        sal_uInt32 nIndex = 0;
        sal_uInt32 nOldIndex = 0;
        sal_Unicode cFirstChar;
        if (!aParam.mpNumFormatter)
            aParam.mpNumFormatter = pDocument->GetFormatTable();
        SfxObjectShell* pDocSh = pDocument->GetDocumentShell();
        if ( pDocSh )
            bIsLoading = pDocSh->IsLoading();
        // IsLoading for ConvertFrom import
        if ( !bIsLoading )
        {
            nIndex = nOldIndex = GetNumberFormat( nRow );
            if ( rString.Len() > 1
                    && aParam.mpNumFormatter->GetType(nIndex) != NUMBERFORMAT_TEXT )
                cFirstChar = rString.GetChar(0);
            else
                cFirstChar = 0; // Text
        }
        else
        {   // There are not applied formats when importing during ConvertFrom
            cFirstChar = rString.GetChar(0);
        }

        if ( cFirstChar == '=' )
        {
            if ( rString.Len() == 1 ) // = Text
                pNewCell = new ScStringCell( rString );
            else // = Formula
                pNewCell = new ScFormulaCell( pDocument,
                    ScAddress( nCol, nRow, nTabP ), rString,
                    formula::FormulaGrammar::mergeToGrammar( formula::FormulaGrammar::GRAM_DEFAULT,
                        eConv), MM_NONE );
        }
        else if ( cFirstChar == '\'') // 'Text
        {
            bool bNumeric = false;
            if (aParam.mbHandleApostrophe)
            {
                // Cell format is not 'Text', and the first char
                // is an apostrophe. Check if the input is considered a number.
                String aTest = rString.Copy(1);
                double fTest;
                bNumeric = aParam.mpNumFormatter->IsNumberFormat(aTest, nIndex, fTest);
                if (bNumeric)
                    // This is a number. Strip out the first char.
                    pNewCell = new ScStringCell(aTest);
            }
            if (!bNumeric)
                // This is normal text. Take it as-is.
                pNewCell = new ScStringCell(rString);
        }
        else
        {
            double nVal;
            sal_Bool bIsText = false;
            if ( bIsLoading )
            {
                if ( !maItems.empty() )
                {
                    String aStr;
                    SCSIZE i = maItems.size();
                    SCSIZE nStop = (i >= 3 ? i - 3 : 0);
                    // Compare the last lines and see whether same String
                    // and IsNumberFormat can be made obsolete
                    do
                    {
                        i--;
                        ScBaseCell* pCell = maItems[i].pCell;
                        switch ( pCell->GetCellType() )
                        {
                            case CELLTYPE_STRING :
                                aStr = ((ScStringCell*)pCell)->GetString();
                                if ( rString == aStr )
                                    bIsText = true;
                            break;
                            case CELLTYPE_NOTE : // Referenced via = Formula
                            break;
                            default:
                                if ( i == maItems.size() - 1 )
                                    i = 0;
                                    // Probably whole column and no String
                        }
                    } while ( i && i > nStop && !bIsText );
                }
                // Prefill nIndex for IsNumberFormat
                if ( !bIsText )
                    nIndex = nOldIndex = aParam.mpNumFormatter->GetStandardIndex();
            }

            do
            {
                if (bIsText)
                    break;

                if (aParam.mbDetectNumberFormat)
                {
                    if (!aParam.mpNumFormatter->IsNumberFormat(rString, nIndex, nVal))
                        break;

                    if ( aParam.mpNumFormatter )
                    {
                        // convert back to the original language if a built-in format was detected
                        const SvNumberformat* pOldFormat = aParam.mpNumFormatter->GetEntry( nOldIndex );
                        if ( pOldFormat )
                            nIndex = aParam.mpNumFormatter->GetFormatForLanguageIfBuiltIn( nIndex, pOldFormat->GetLanguage() );
                    }

                    pNewCell = new ScValueCell( nVal );
                    if ( nIndex != nOldIndex)
                    {
                        // #i22345# New behavior: Apply the detected number format only if
                        // the old one was the default number, date, time or boolean format.
                        // Exception: If the new format is boolean, always apply it.

                        sal_Bool bOverwrite = false;
                        const SvNumberformat* pOldFormat = aParam.mpNumFormatter->GetEntry( nOldIndex );
                        if ( pOldFormat )
                        {
                            short nOldType = pOldFormat->GetType() & ~NUMBERFORMAT_DEFINED;
                            if ( nOldType == NUMBERFORMAT_NUMBER || nOldType == NUMBERFORMAT_DATE ||
                                 nOldType == NUMBERFORMAT_TIME || nOldType == NUMBERFORMAT_LOGICAL )
                            {
                                if ( nOldIndex == aParam.mpNumFormatter->GetStandardFormat(
                                                    nOldType, pOldFormat->GetLanguage() ) )
                                {
                                    bOverwrite = true; // default of these types can be overwritten
                                }
                            }
                        }
                        if ( !bOverwrite && aParam.mpNumFormatter->GetType( nIndex ) == NUMBERFORMAT_LOGICAL )
                        {
                            bOverwrite = true; // overwrite anything if boolean was detected
                        }

                        if ( bOverwrite )
                        {
                            ApplyAttr( nRow, SfxUInt32Item( ATTR_VALUE_FORMAT,
                                (sal_uInt32) nIndex) );
                            bNumFmtSet = true;
                        }
                    }
                }
                else if (aParam.meSetTextNumFormat != ScSetStringParam::Always)
                {
                    // Only check if the string is a regular number.
                    const LocaleDataWrapper* pLocale = aParam.mpNumFormatter->GetLocaleData();
                    if (!pLocale)
                        break;

                    LocaleDataItem aLocaleItem = pLocale->getLocaleItem();
                    const OUString& rDecSep = aLocaleItem.decimalSeparator;
                    const OUString& rGroupSep = aLocaleItem.thousandSeparator;
                    if (rDecSep.getLength() != 1 || rGroupSep.getLength() != 1)
                        break;

                    sal_Unicode dsep = rDecSep.getStr()[0];
                    sal_Unicode gsep = rGroupSep.getStr()[0];

                    if (!ScStringUtil::parseSimpleNumber(rString, dsep, gsep, nVal))
                        break;

                    pNewCell = new ScValueCell(nVal);
                }
            }
            while (false);

            if (!pNewCell)
            {
                if (aParam.meSetTextNumFormat != ScSetStringParam::Never && aParam.mpNumFormatter->IsNumberFormat(rString, nIndex, nVal))
                {
                    // Set the cell format type to Text.
                    sal_uInt32 nFormat = aParam.mpNumFormatter->GetStandardFormat(NUMBERFORMAT_TEXT);
                    ScPatternAttr aNewAttrs(pDocument->GetPool());
                    SfxItemSet& rSet = aNewAttrs.GetItemSet();
                    rSet.Put( SfxUInt32Item(ATTR_VALUE_FORMAT, nFormat) );
                    ApplyPattern(nRow, aNewAttrs);
                }

                pNewCell = new ScStringCell(rString);
            }
        }
    }

    if ( bIsLoading && (maItems.empty() || nRow > maItems.back().nRow) )
    {   // Save search and build up Listener without a detour via Insert
        // Broadcast comes after Loading
        if ( pNewCell )
            Append( nRow, pNewCell );
    }
    else
    {
        SCSIZE i;
        if (Search(nRow, i))
        {
            ScBaseCell* pOldCell = maItems[i].pCell;
            SvtBroadcaster* pBC = pOldCell->ReleaseBroadcaster();
            if (pNewCell || pBC)
            {
                if(!pNewCell)
                    pNewCell = new ScNoteCell();

                if (pBC)
                {
                    pNewCell->TakeBroadcaster(pBC);
                    pLastFormulaTreeTop = 0; // Err527 Workaround
                }

                if ( pOldCell->GetCellType() == CELLTYPE_FORMULA )
                {
                    static_cast<ScFormulaCell*>(pOldCell)->EndListeningTo(pDocument);
                    // If in EndListening NoteCell destroyed in same in gleicher Col
                    if ( i >= maItems.size() || maItems[i].nRow != nRow )
                        Search(nRow, i);
                }

                pOldCell->Delete();
                maItems[i].pCell = pNewCell; // Replace
                maTextWidths.set<unsigned short>(nRow, TEXTWIDTH_DIRTY);
                maScriptTypes.set<unsigned short>(nRow, SC_SCRIPTTYPE_UNKNOWN);
                CellStorageModified();

                if ( pNewCell->GetCellType() == CELLTYPE_FORMULA )
                {
                    static_cast<ScFormulaCell*>(pNewCell)->StartListeningTo(pDocument);
                    ((ScFormulaCell*)pNewCell)->SetDirty();
                }
                else
                    pDocument->Broadcast( ScHint( SC_HINT_DATACHANGED,
                        ScAddress(nCol, nRow, nTabP), pNewCell->GetBroadcaster()));
            }
            else
            {
                DeleteAtIndex(i); // Delete and Broadcast
            }
        }
        else if (pNewCell)
        {
            Insert(nRow, pNewCell); // Re-insert and Broadcast
        }
    }

    // Do not set Formats and Formulas here anymore!
    // These are queried during output

    return bNumFmtSet;
}

void ScColumn::SetEditText( SCROW nRow, EditTextObject* pEditText )
{
    Insert(nRow, new ScEditCell(pEditText, pDocument));
}

void ScColumn::SetEditText( SCROW nRow, const EditTextObject& rEditText, const SfxItemPool* pEditPool )
{
    Insert(nRow, new ScEditCell(rEditText, pDocument, pEditPool));
}

void ScColumn::SetFormula( SCROW nRow, const ScTokenArray& rArray, formula::FormulaGrammar::Grammar eGram )
{
    ScAddress aPos(nCol, nRow, nTab);
    Insert(nRow, new ScFormulaCell(pDocument, aPos, &rArray, eGram));
}

void ScColumn::SetFormula( SCROW nRow, const OUString& rFormula, formula::FormulaGrammar::Grammar eGram )
{
    ScAddress aPos(nCol, nRow, nTab);
    Insert(nRow, new ScFormulaCell(pDocument, aPos, rFormula, eGram));
}

void ScColumn::SetFormulaCell( SCROW nRow, ScFormulaCell* pCell )
{
    Insert(nRow, pCell);
}

void ScColumn::GetFilterEntries(SCROW nStartRow, SCROW nEndRow, std::vector<ScTypedStrData>& rStrings, bool& rHasDates)
{
    bool bHasDates = false;
    SvNumberFormatter* pFormatter = pDocument->GetFormatTable();
    OUString aString;
    SCSIZE nIndex;

    Search( nStartRow, nIndex );

    for (; nIndex < maItems.size(); ++nIndex)
    {
        SCROW nRow = maItems[nIndex].nRow;
        if (nRow > nEndRow)
            break;

        ScBaseCell* pCell = maItems[nIndex].pCell;
        ScRefCellValue aCell;
        aCell.assign(*maItems[nIndex].pCell);
        sal_uLong nFormat = GetNumberFormat( nRow );

        ScCellFormat::GetInputString(aCell, nFormat, aString, *pFormatter);

        if ( pDocument->HasStringData( nCol, nRow, nTab ) )
        {
            rStrings.push_back(ScTypedStrData(aString));
            continue;
        }

        double nValue = 0.0;

        switch ( pCell->GetCellType() )
        {
            case CELLTYPE_VALUE:
                nValue = ((ScValueCell*)pCell)->GetValue();
                break;

            case CELLTYPE_FORMULA:
            {
                ScFormulaCell* pFC = static_cast<ScFormulaCell*>(pCell);
                sal_uInt16 nErr = pFC->GetErrCode();
                if (nErr)
                {
                    // Error cell is evaluated as string (for now).
                    String aErr = ScGlobal::GetErrorString(nErr);
                    if (aErr.Len())
                    {
                        rStrings.push_back(ScTypedStrData(aErr));
                        continue;
                    }
                }
                else
                    nValue = pFC->GetValue();
            }
            break;

            // skip broadcaster cells
            case CELLTYPE_NOTE:
                continue;

            default:
                ;
        }

        if (pFormatter)
        {
            short nType = pFormatter->GetType(nFormat);
            if ((nType & NUMBERFORMAT_DATE) && !(nType & NUMBERFORMAT_TIME))
            {
                // special case for date values.  Disregard the time
                // element if the number format is of date type.
                nValue = ::rtl::math::approxFloor(nValue);
                bHasDates = true;
            }
        }

        rStrings.push_back(ScTypedStrData(aString, nValue, ScTypedStrData::Value));
    }

    rHasDates = bHasDates;
}

//
// GetDataEntries - Strings from continuous Section around nRow
//

// DATENT_MAX      - max. number of entries in list for auto entry
// DATENT_SEARCH   - max. number of cells that get transparent - new: only count Strings
#define DATENT_MAX      200
#define DATENT_SEARCH   2000


bool ScColumn::GetDataEntries(SCROW nStartRow, std::set<ScTypedStrData>& rStrings, bool bLimit)
{
    sal_Bool bFound = false;
    SCSIZE nThisIndex;
    sal_Bool bThisUsed = Search( nStartRow, nThisIndex );
    String aString;
    sal_uInt16 nCells = 0;

    // The limitation to neighbouring cells (without gaps) is not wanted anymore
    // (Featurecommission for 5.1), search upwards/downwards instead so that
    // nearby cell are cought at least first.
    // TODO: Compare distances of cell numbers? Performance??

    SCSIZE nUpIndex = nThisIndex;   // Points after the row
    SCSIZE nDownIndex = nThisIndex; // Points to the row
    if (bThisUsed)
        ++nDownIndex;               // Skip starting row

    while ( nUpIndex || nDownIndex < maItems.size() )
    {
        if ( nUpIndex ) // Up
        {
            ScBaseCell* pCell = maItems[nUpIndex-1].pCell;
            CellType eType = pCell->GetCellType();
            if (eType == CELLTYPE_STRING || eType == CELLTYPE_EDIT) // Only Strings are of interest
            {
                if (eType == CELLTYPE_STRING)
                    aString = ((ScStringCell*)pCell)->GetString();
                else
                    aString = ((ScEditCell*)pCell)->GetString();

                bool bInserted = rStrings.insert(ScTypedStrData(aString)).second;
                if (bInserted && bLimit && rStrings.size() >= DATENT_MAX)
                    break; // Maximum reached
                bFound = true;

                if ( bLimit )
                    if (++nCells >= DATENT_SEARCH)
                        break; // Searched enough
            }
            --nUpIndex;
        }

        if ( nDownIndex < maItems.size() ) // Down
        {
            ScBaseCell* pCell = maItems[nDownIndex].pCell;
            CellType eType = pCell->GetCellType();
            if (eType == CELLTYPE_STRING || eType == CELLTYPE_EDIT) // Only Strings are of interest
            {
                if (eType == CELLTYPE_STRING)
                    aString = ((ScStringCell*)pCell)->GetString();
                else
                    aString = ((ScEditCell*)pCell)->GetString();

                bool bInserted = rStrings.insert(ScTypedStrData(aString)).second;
                if (bInserted && bLimit && rStrings.size() >= DATENT_MAX)
                    break; // Maximum reached
                bFound = true;

                if ( bLimit )
                    if (++nCells >= DATENT_SEARCH)
                        break; // Searched enough
            }
            ++nDownIndex;
        }
    }

    return bFound;
}

#undef DATENT_MAX
#undef DATENT_SEARCH


void ScColumn::RemoveProtected( SCROW nStartRow, SCROW nEndRow )
{
    ScAttrIterator aAttrIter( pAttrArray, nStartRow, nEndRow );
    SCROW nTop = -1;
    SCROW nBottom = -1;
    SCSIZE nIndex;
    const ScPatternAttr* pPattern = aAttrIter.Next( nTop, nBottom );
    while (pPattern)
    {
        const ScProtectionAttr* pAttr = (const ScProtectionAttr*)&pPattern->GetItem(ATTR_PROTECTION);
        if ( pAttr->GetHideCell() )
            DeleteArea( nTop, nBottom, IDF_CONTENTS );
        else if ( pAttr->GetHideFormula() )
        {
            Search( nTop, nIndex );
            while ( nIndex<maItems.size() && maItems[nIndex].nRow<=nBottom )
            {
                if ( maItems[nIndex].pCell->GetCellType() == CELLTYPE_FORMULA )
                {
                    ScFormulaCell* pFormula = (ScFormulaCell*)maItems[nIndex].pCell;
                    if (pFormula->IsValue())
                    {
                        double nVal = pFormula->GetValue();
                        maItems[nIndex].pCell = new ScValueCell( nVal );
                    }
                    else
                    {
                        String aString = pFormula->GetString();
                        maItems[nIndex].pCell = new ScStringCell( aString );
                    }
                    delete pFormula;

                    SetTextWidth(maItems[nIndex].nRow, TEXTWIDTH_DIRTY);
                    CellStorageModified();
                }
                ++nIndex;
            }
        }

        pPattern = aAttrIter.Next( nTop, nBottom );
    }
}


void ScColumn::SetError( SCROW nRow, const sal_uInt16 nError)
{
    if (ValidRow(nRow))
    {
        ScFormulaCell* pCell = new ScFormulaCell
            ( pDocument, ScAddress( nCol, nRow, nTab ) );
        pCell->SetErrCode( nError );
        Insert( nRow, pCell );
    }
}


void ScColumn::SetValue( SCROW nRow, const double& rVal)
{
    if (ValidRow(nRow))
    {
        ScBaseCell* pCell = new ScValueCell(rVal);
        Insert( nRow, pCell );
    }
}


void ScColumn::GetString( SCROW nRow, OUString& rString ) const
{
    SCSIZE  nIndex;
    Color* pColor;
    if (Search(nRow, nIndex))
    {
        ScRefCellValue aCell;
        aCell.assign(*maItems[nIndex].pCell);
        if (aCell.meType != CELLTYPE_NOTE)
        {
            sal_uLong nFormat = GetNumberFormat( nRow );
            ScCellFormat::GetString(aCell, nFormat, rString, &pColor, *(pDocument->GetFormatTable()));
        }
        else
            rString = EMPTY_OUSTRING;
    }
    else
        rString = EMPTY_OUSTRING;
}

const OUString* ScColumn::GetStringCell( SCROW nRow ) const
{
    SCSIZE  nIndex;
    if (!Search(nRow, nIndex))
        return NULL;

    const ScBaseCell* pCell = maItems[nIndex].pCell;
    if (pCell->GetCellType() != CELLTYPE_STRING)
        return NULL;

    return static_cast<const ScStringCell*>(pCell)->GetStringPtr();
}

double* ScColumn::GetValueCell( SCROW nRow )
{
    SCSIZE  nIndex;
    if (!Search(nRow, nIndex))
        return NULL;

    ScBaseCell* pCell = maItems[nIndex].pCell;
    if (pCell->GetCellType() != CELLTYPE_VALUE)
        return NULL;

    return static_cast<ScValueCell*>(pCell)->GetValuePtr();
}

void ScColumn::GetInputString( SCROW nRow, OUString& rString ) const
{
    SCSIZE  nIndex;
    if (Search(nRow, nIndex))
    {
        ScRefCellValue aCell;
        aCell.assign(*maItems[nIndex].pCell);
        if (aCell.meType != CELLTYPE_NOTE)
        {
            sal_uLong nFormat = GetNumberFormat( nRow );
            ScCellFormat::GetInputString(aCell, nFormat, rString, *(pDocument->GetFormatTable()));
        }
        else
            rString = OUString();
    }
    else
        rString = OUString();
}


double ScColumn::GetValue( SCROW nRow ) const
{
    SCSIZE  nIndex;
    if (Search(nRow, nIndex))
    {
        ScBaseCell* pCell = maItems[nIndex].pCell;
        switch (pCell->GetCellType())
        {
            case CELLTYPE_VALUE:
                return ((ScValueCell*)pCell)->GetValue();

            case CELLTYPE_FORMULA:
                {
                    if (((ScFormulaCell*)pCell)->IsValue())
                        return ((ScFormulaCell*)pCell)->GetValue();
                    else
                        return 0.0;
                }

            default:
                return 0.0;
        }
    }
    return 0.0;
}

const EditTextObject* ScColumn::GetEditText( SCROW nRow ) const
{
    SCSIZE nIndex;
    if (!Search(nRow, nIndex))
        return NULL;

    const ScBaseCell* pCell = maItems[nIndex].pCell;
    if (pCell->GetCellType() != CELLTYPE_EDIT)
        return NULL;

    const ScEditCell* pEditCell = static_cast<const ScEditCell*>(pCell);
    return pEditCell->GetData();
}

void ScColumn::RemoveEditTextCharAttribs( SCROW nRow, const ScPatternAttr& rAttr )
{
    SCSIZE nIndex;
    if (!Search(nRow, nIndex))
        return;

    ScBaseCell* pCell = maItems[nIndex].pCell;
    if (pCell->GetCellType() != CELLTYPE_EDIT)
        return;

    ScEditCell* pEditCell = static_cast<ScEditCell*>(pCell);
    pEditCell->RemoveCharAttribs(rAttr);
}

void ScColumn::GetFormula( SCROW nRow, OUString& rFormula ) const
{
    SCSIZE  nIndex;
    if (Search(nRow, nIndex))
    {
        ScBaseCell* pCell = maItems[nIndex].pCell;
        if (pCell->GetCellType() == CELLTYPE_FORMULA)
            ((ScFormulaCell*)pCell)->GetFormula( rFormula );
        else
            rFormula = OUString();
    }
    else
        rFormula = OUString();
}

const ScTokenArray* ScColumn::GetFormulaTokens( SCROW nRow ) const
{
    const ScFormulaCell* pCell = FetchFormulaCell(nRow);
    if (!pCell)
        return NULL;

    return pCell->GetCode();
}

const ScFormulaCell* ScColumn::GetFormulaCell( SCROW nRow ) const
{
    return FetchFormulaCell(nRow);
}

ScFormulaCell* ScColumn::GetFormulaCell( SCROW nRow )
{
    return const_cast<ScFormulaCell*>(FetchFormulaCell(nRow));
}

CellType ScColumn::GetCellType( SCROW nRow ) const
{
    SCSIZE  nIndex;
    if (Search(nRow, nIndex))
        return maItems[nIndex].pCell->GetCellType();
    return CELLTYPE_NONE;
}

SCSIZE ScColumn::GetCellCount() const
{
    return maItems.size();
}

sal_uInt16 ScColumn::GetErrCode( SCROW nRow ) const
{
    SCSIZE  nIndex;
    if (Search(nRow, nIndex))
    {
        ScBaseCell* pCell = maItems[nIndex].pCell;
        if (pCell->GetCellType() == CELLTYPE_FORMULA)
            return ((ScFormulaCell*)pCell)->GetErrCode();
    }
    return 0;
}


bool ScColumn::HasStringData( SCROW nRow ) const
{
    SCSIZE  nIndex;
    if (Search(nRow, nIndex))
        return (maItems[nIndex].pCell)->HasStringData();
    return false;
}


bool ScColumn::HasValueData( SCROW nRow ) const
{
    SCSIZE  nIndex;
    if (Search(nRow, nIndex))
        return (maItems[nIndex].pCell)->HasValueData();
    return false;
}

/**
 * Return true if there is a string or editcell in the range
 */
bool ScColumn::HasStringCells( SCROW nStartRow, SCROW nEndRow ) const
{
    if ( !maItems.empty() )
    {
        SCSIZE nIndex;
        Search( nStartRow, nIndex );
        while ( nIndex < maItems.size() && maItems[nIndex].nRow <= nEndRow )
        {
            CellType eType = maItems[nIndex].pCell->GetCellType();
            if ( eType == CELLTYPE_STRING || eType == CELLTYPE_EDIT )
                return sal_True;
            ++nIndex;
        }
    }
    return false;
}


sal_Int32 ScColumn::GetMaxStringLen( SCROW nRowStart, SCROW nRowEnd, CharSet eCharSet ) const
{
    sal_Int32 nStringLen = 0;
    if ( !maItems.empty() )
    {
        OUString aString;
        OString aOString;
        bool bIsOctetTextEncoding = rtl_isOctetTextEncoding( eCharSet);
        SvNumberFormatter* pNumFmt = pDocument->GetFormatTable();
        SCSIZE nIndex;
        SCROW nRow;
        Search( nRowStart, nIndex );
        while ( nIndex < maItems.size() && (nRow = maItems[nIndex].nRow) <= nRowEnd )
        {
            ScRefCellValue aCell;
            aCell.assign(*maItems[nIndex].pCell);
            if (aCell.meType != CELLTYPE_NOTE)
            {
                Color* pColor;
                sal_uLong nFormat = (sal_uLong) ((SfxUInt32Item*) GetAttr(
                    nRow, ATTR_VALUE_FORMAT ))->GetValue();
                ScCellFormat::GetString(aCell, nFormat, aString, &pColor, *pNumFmt);
                sal_Int32 nLen;
                if (bIsOctetTextEncoding)
                {
                    if (!aString.convertToString( &aOString, eCharSet,
                                RTL_UNICODETOTEXT_FLAGS_UNDEFINED_ERROR |
                                RTL_UNICODETOTEXT_FLAGS_INVALID_ERROR))
                    {
                        // TODO: anything? this is used by the dBase export filter
                        // that throws an error anyway, but in case of another
                        // context we might want to indicate a conversion error
                        // early.
                    }
                    nLen = aOString.getLength();
                }
                else
                    nLen = aString.getLength() * sizeof(sal_Unicode);
                if ( nStringLen < nLen)
                    nStringLen = nLen;
            }
            nIndex++;
        }
    }
    return nStringLen;
}


xub_StrLen ScColumn::GetMaxNumberStringLen(
    sal_uInt16& nPrecision, SCROW nRowStart, SCROW nRowEnd ) const
{
    xub_StrLen nStringLen = 0;
    nPrecision = pDocument->GetDocOptions().GetStdPrecision();
    if ( nPrecision == SvNumberFormatter::UNLIMITED_PRECISION )
        // In case of unlimited precision, use 2 instead.
        nPrecision = 2;

    if ( !maItems.empty() )
    {
        OUString aString;
        SvNumberFormatter* pNumFmt = pDocument->GetFormatTable();
        SCSIZE nIndex;
        SCROW nRow;
        Search( nRowStart, nIndex );
        while ( nIndex < maItems.size() && (nRow = maItems[nIndex].nRow) <= nRowEnd )
        {
            ScRefCellValue aCell;
            aCell.assign(*maItems[nIndex].pCell);
            CellType eType = aCell.meType;
            if ( eType == CELLTYPE_VALUE || (eType == CELLTYPE_FORMULA
                    && aCell.mpFormula->IsValue()) )
            {
                sal_uLong nFormat = (sal_uLong) ((SfxUInt32Item*) GetAttr(
                    nRow, ATTR_VALUE_FORMAT ))->GetValue();
                ScCellFormat::GetInputString(aCell, nFormat, aString, *pNumFmt);
                xub_StrLen nLen = aString.getLength();
                if ( nLen )
                {
                    if ( nFormat )
                    {
                        const SvNumberformat* pEntry = pNumFmt->GetEntry( nFormat );
                        sal_uInt16 nPrec;
                        if (pEntry)
                        {
                            bool bThousand, bNegRed;
                            sal_uInt16 nLeading;
                            pEntry->GetFormatSpecialInfo(bThousand, bNegRed, nPrec, nLeading);
                        }
                        else
                            nPrec = pNumFmt->GetFormatPrecision( nFormat );

                        if ( nPrec != SvNumberFormatter::UNLIMITED_PRECISION && nPrec > nPrecision )
                            nPrecision = nPrec;
                    }
                    if ( nPrecision )
                    {   // less than nPrecision in string => widen it
                        // more => shorten it
                        String aSep = pNumFmt->GetFormatDecimalSep( nFormat );
                        sal_Int32 nTmp = aString.indexOf( aSep );
                        if ( nTmp == -1 )
                            nLen += nPrecision + aSep.Len();
                        else
                        {
                            nTmp = aString.getLength() - (nTmp + aSep.Len());
                            if ( nTmp != nPrecision )
                                nLen += nPrecision - nTmp;
                                // nPrecision > nTmp : nLen + Diff
                                // nPrecision < nTmp : nLen - Diff
                        }
                    }
                    if ( nStringLen < nLen )
                        nStringLen = nLen;
                }
            }
            nIndex++;
        }
    }
    return nStringLen;
}

// Very[!] slow way to look for and merge contiguous runs
// of similar formulae into a formulagroup
void ScColumn::RebuildFormulaGroups()
{
    if ( maItems.empty() || !bDirtyGroups )
        return;

    // clear double groups
    for (std::vector< ColDoubleEntry *>::iterator it = maDoubles.begin();
         it != maDoubles.end(); ++it )
        delete *it;
    maDoubles.clear();

    // clear previous groups
    ScFormulaCellGroupRef xNone;
    for (size_t i = 0; i < maItems.size(); i++)
    {
        ColEntry &rCur = maItems[ i ];
        if ( rCur.pCell && rCur.pCell->GetCellType() == CELLTYPE_FORMULA )
            static_cast<ScFormulaCell *>( rCur.pCell )->SetCellGroup( xNone );
    }
    maFnGroups.clear();

    // re-build groups
    ColDoubleEntry *pLastDouble = NULL;
    for (size_t i = 1; i < maItems.size(); i++)
    {
        ColEntry &rCur = maItems[ i ];
        ColEntry &rPrev = maItems[ i - 1 ];
        if ( ( rPrev.nRow != rCur.nRow - 1 ) ||                        // not contiguous
             !rCur.pCell || !rPrev.pCell ||                            // paranoia
             rCur.pCell->GetCellType() != rPrev.pCell->GetCellType() ) // same type
        {
            pLastDouble = NULL;
            continue;
        }

        // collate doubles
        if ( rCur.pCell->GetCellType() == CELLTYPE_VALUE )
        {
            if ( !pLastDouble )
            {
                pLastDouble = new ColDoubleEntry();
                pLastDouble->mnStart = rPrev.nRow;
                pLastDouble->maData.push_back(
                        static_cast< ScValueCell * >( rPrev.pCell )->GetValue() );
                maDoubles.push_back( pLastDouble );
            }
            pLastDouble->maData.push_back(
                        static_cast< ScValueCell * >( rCur.pCell )->GetValue() );
            continue;
        }

        if ( rCur.pCell->GetCellType() != CELLTYPE_FORMULA )
            continue;

        // see if these formulae are similar
        ScFormulaCell *pCur = static_cast< ScFormulaCell *>( rCur.pCell );
        ScFormulaCell *pPrev = static_cast< ScFormulaCell *>( rPrev.pCell );

        ScSimilarFormulaDelta *pDelta = pPrev->BuildDeltaTo( pCur );

        if ( !pDelta )
        {
            // not similar
            pCur->SetCellGroup( xNone );
            continue;
        }

        ScFormulaCellGroupRef xGroup = pPrev->GetCellGroup();
        if ( !xGroup.get() )
        {
            // create a new group ...
            ScFormulaCellGroup *pGroup = new ScFormulaCellGroup();
            pGroup->mpDelta = pDelta;
            pGroup->mnStart = rPrev.nRow;
            pGroup->mnLength = 2;

            xGroup.reset( pGroup );
            maFnGroups.push_back( xGroup );

            pCur->SetCellGroup( xGroup );
            pPrev->SetCellGroup( xGroup );
        }
        else if ( xGroup->IsCompatible( pDelta ) )
        {
            // we are a compatible extension - extend the group
            pCur->SetCellGroup( xGroup );
            xGroup->mnLength++;
            pCur->ReleaseDelta( pDelta );
        }
        else
        {
#if OSL_DEBUG_LEVEL > 1
            OUString aFormula;
            pCur->GetFormula( aFormula );
            ScAddress aAddr( nCol, rCur.nRow, nTab );
            OUString aCellAddr;
            aAddr.Format( aCellAddr, 0, pDocument );

            fprintf( stderr, "unusual incompatible extension in cell '%s' of formulae '%s'\n" ,
                     OUStringToOString( aCellAddr, RTL_TEXTENCODING_UTF8 ).getStr(),
                     OUStringToOString( aFormula, RTL_TEXTENCODING_UTF8 ).getStr() );
#endif
            pCur->ReleaseDelta( pDelta );
        }
    }

#if OSL_DEBUG_LEVEL > 0
    if ( maDoubles.size() + maFnGroups.size() > 0 )
    {
        OUString aStr;
        fprintf( stderr, "column %2d has %2d double span(s): ", (int)nCol, (int)maDoubles.size() );
        for (std::vector< ColDoubleEntry *>::iterator it = maDoubles.begin();
             it != maDoubles.end(); ++it )
        {
            ScRange aDoubleRange( nCol, (*it)->mnStart, nTab,
                                  nCol, (*it)->mnStart + (*it)->maData.size() - 1, nTab );
            aDoubleRange.Format( aStr, SCA_VALID | SCA_VALID_COL | SCA_VALID_ROW, pDocument );
            fprintf( stderr, "%s, ", OUStringToOString( aStr, RTL_TEXTENCODING_UTF8 ).getStr() );
        }
        fprintf( stderr, "\n" );

        fprintf( stderr, "column %2d has %2d formula span(s): ", (int)nCol, (int)maFnGroups.size() );
        for (std::vector< ScFormulaCellGroupRef>::iterator it = maFnGroups.begin();
             it != maFnGroups.end(); ++it )
        {
            ScRange aDoubleRange( nCol, (*it)->mnStart, nTab,
                                  nCol, (*it)->mnStart + (*it)->mnLength - 1, nTab );
            aDoubleRange.Format( aStr, SCA_VALID | SCA_VALID_COL | SCA_VALID_ROW, pDocument );
            fprintf( stderr, "%s, ", OUStringToOString( aStr, RTL_TEXTENCODING_UTF8 ).getStr() );
        }
        fprintf( stderr, "\n" );
    }
#endif


    bDirtyGroups = false;
}

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