kbrown / rpms / libreoffice

Forked from rpms/libreoffice 2 years ago
Clone

Blame SOURCES/0044-fdo-81309-Adjust-references-during-sort.patch

f085be
From d4aed409279d3b9b8b95d84418fb7f279367cc30 Mon Sep 17 00:00:00 2001
f085be
From: Kohei Yoshida <kohei.yoshida@collabora.com>
f085be
Date: Mon, 2 Jun 2014 18:29:27 -0400
f085be
Subject: [PATCH 044/137] fdo#81309: Adjust references during sort.
f085be
f085be
(cherry picked from commit 5c6ee09126631342939ae8766fe36083d8c011e3)
f085be
Signed-off-by: Andras Timar <andras.timar@collabora.com>
f085be
f085be
Conflicts:
f085be
	sc/inc/sortparam.hxx
f085be
	sc/source/ui/docshell/dbdocfun.cxx
f085be
	sc/source/ui/undo/undodat.cxx
f085be
	sc/inc/formulacell.hxx
f085be
	sc/qa/unit/filters-test.cxx
f085be
	sc/qa/unit/ucalc.cxx
f085be
	sc/source/core/data/documen3.cxx
f085be
	sc/source/ui/docshell/dbdocfun.cxx
f085be
f085be
Change-Id: I2b98610f6b774400ecfaffe2905201c27fcab33f
f085be
(cherry picked from commit e31300e8749ac7de07bbcb91c6ae28559238e60c)
f085be
Signed-off-by: Andras Timar <andras.timar@collabora.com>
f085be
---
f085be
 include/svl/listener.hxx                         |  12 +
f085be
 sc/Library_sc.mk                                 |   2 +
f085be
 sc/inc/document.hxx                              |  35 +-
f085be
 sc/inc/formulacell.hxx                           |   2 +
f085be
 sc/inc/listenerquery.hxx                         |  50 +++
f085be
 sc/inc/listenerqueryids.hxx                      |  17 +
f085be
 sc/inc/refhint.hxx                               |  30 +-
f085be
 sc/inc/sharedformula.hxx                         |   9 +
f085be
 sc/inc/sortparam.hxx                             |  27 ++
f085be
 sc/inc/table.hxx                                 |  16 +-
f085be
 sc/inc/tokenarray.hxx                            |   8 +-
f085be
 sc/inc/types.hxx                                 |   2 +-
f085be
 sc/inc/undosort.hxx                              |  37 ++
f085be
 sc/qa/unit/filters-test.cxx                      |   4 +
f085be
 sc/qa/unit/ucalc.cxx                             |  11 +-
f085be
 sc/source/core/data/documen3.cxx                 |  27 +-
f085be
 sc/source/core/data/document10.cxx               |  18 +
f085be
 sc/source/core/data/formulacell.cxx              |  38 +-
f085be
 sc/source/core/data/sortparam.cxx                |  51 +++
f085be
 sc/source/core/data/table3.cxx                   | 467 +++++++++++++++++------
f085be
 sc/source/core/data/table7.cxx                   |  17 +
f085be
 sc/source/core/tool/listenerquery.cxx            |  72 ++++
f085be
 sc/source/core/tool/refhint.cxx                  |  29 +-
f085be
 sc/source/core/tool/sharedformula.cxx            |  29 ++
f085be
 sc/source/core/tool/token.cxx                    |  71 +++-
f085be
 sc/source/filter/xml/XMLExportDatabaseRanges.cxx |   1 +
f085be
 sc/source/filter/xml/xmldrani.cxx                |   1 +
f085be
 sc/source/ui/docshell/dbdocfun.cxx               | 163 +-------
f085be
 sc/source/ui/undo/undobase.cxx                   |   1 +
f085be
 sc/source/ui/undo/undosort.cxx                   |  55 +++
f085be
 sc/source/ui/unoobj/cellsuno.cxx                 |   1 +
f085be
 sc/source/ui/unoobj/datauno.cxx                  |   1 +
f085be
 svl/source/notify/listener.cxx                   |  24 +-
f085be
 33 files changed, 1018 insertions(+), 310 deletions(-)
f085be
 create mode 100644 sc/inc/listenerquery.hxx
f085be
 create mode 100644 sc/inc/listenerqueryids.hxx
f085be
 create mode 100644 sc/inc/undosort.hxx
f085be
 create mode 100644 sc/source/core/tool/listenerquery.cxx
f085be
 create mode 100644 sc/source/ui/undo/undosort.cxx
f085be
f085be
diff --git a/include/svl/listener.hxx b/include/svl/listener.hxx
f085be
index 1c98458..8b47fda 100644
f085be
--- a/include/svl/listener.hxx
f085be
+++ b/include/svl/listener.hxx
f085be
@@ -34,6 +34,16 @@ class SVL_DLLPUBLIC SvtListener
f085be
     const SvtListener&  operator=(const SvtListener &); // n.i., ist verboten
f085be
 
f085be
 public:
f085be
+    class SVL_DLLPUBLIC QueryBase
f085be
+    {
f085be
+        sal_uInt16 mnId;
f085be
+    public:
f085be
+        QueryBase( sal_uInt16 nId );
f085be
+        virtual ~QueryBase();
f085be
+
f085be
+        sal_uInt16 getId() const;
f085be
+    };
f085be
+
f085be
     SvtListener();
f085be
     SvtListener( const SvtListener &r );
f085be
     virtual ~SvtListener();
f085be
@@ -43,9 +53,11 @@ public:
f085be
     void EndListeningAll();
f085be
     bool IsListening( SvtBroadcaster& rBroadcaster ) const;
f085be
 
f085be
+    void CopyAllBroadcasters( const SvtListener& r );
f085be
     bool HasBroadcaster() const;
f085be
 
f085be
     virtual void Notify( const SfxHint& rHint );
f085be
+    virtual void Query( QueryBase& rQuery ) const;
f085be
 };
f085be
 
f085be
 
f085be
diff --git a/sc/Library_sc.mk b/sc/Library_sc.mk
f085be
index b7041b8..33c6652 100644
f085be
--- a/sc/Library_sc.mk
f085be
+++ b/sc/Library_sc.mk
f085be
@@ -234,6 +234,7 @@ $(eval $(call gb_Library_add_exception_objects,sc,\
f085be
     sc/source/core/tool/interpr6 \
f085be
     sc/source/core/tool/interpr7 \
f085be
     sc/source/core/tool/jumpmatrix \
f085be
+    sc/source/core/tool/listenerquery \
f085be
     sc/source/core/tool/lookupcache \
f085be
     sc/source/core/tool/navicfg \
f085be
     sc/source/core/tool/odffmap \
f085be
@@ -515,6 +516,7 @@ $(eval $(call gb_Library_add_exception_objects,sc,\
f085be
     sc/source/ui/undo/undodraw \
f085be
     sc/source/ui/undo/undoolk \
f085be
     sc/source/ui/undo/undorangename \
f085be
+    sc/source/ui/undo/undosort \
f085be
     sc/source/ui/undo/undostyl \
f085be
     sc/source/ui/undo/undotab \
f085be
     sc/source/ui/undo/undoutil \
f085be
diff --git a/sc/inc/document.hxx b/sc/inc/document.hxx
f085be
index a2aea94..c901af5 100644
f085be
--- a/sc/inc/document.hxx
f085be
+++ b/sc/inc/document.hxx
f085be
@@ -29,7 +29,6 @@
f085be
 #include "rangenam.hxx"
f085be
 #include "brdcst.hxx"
f085be
 #include "tabopparams.hxx"
f085be
-#include "sortparam.hxx"
f085be
 #include "types.hxx"
f085be
 #include "formula/grammar.hxx"
f085be
 #include "formula/types.hxx"
f085be
@@ -76,6 +75,8 @@ class DocumentStreamAccess;
f085be
 class DocumentLinkManager;
f085be
 struct SetFormulaDirtyContext;
f085be
 class RefMovedHint;
f085be
+struct SortUndoParam;
f085be
+struct ReorderParam;
f085be
 
f085be
 }
f085be
 
f085be
@@ -178,6 +179,8 @@ class EditTextObject;
f085be
 struct ScRefCellValue;
f085be
 class ScDocumentImport;
f085be
 class ScPostIt;
f085be
+struct ScSubTotalParam;
f085be
+struct ScQueryParam;
f085be
 
f085be
 namespace com { namespace sun { namespace star {
f085be
     namespace lang {
f085be
@@ -1664,7 +1667,9 @@ public:
f085be
     SC_DLLPUBLIC SvNumberFormatter* GetFormatTable() const;
f085be
     SC_DLLPUBLIC SvNumberFormatter* CreateFormatTable() const;
f085be
 
f085be
-    void            Sort( SCTAB nTab, const ScSortParam& rSortParam, bool bKeepQuery, ScProgress* pProgress );
f085be
+    void Sort( SCTAB nTab, const ScSortParam& rSortParam, bool bKeepQuery, ScProgress* pProgress, sc::ReorderParam* pUndo );
f085be
+    void Reorder( const sc::ReorderParam& rParam, ScProgress* pProgress );
f085be
+
f085be
     SCSIZE          Query( SCTAB nTab, const ScQueryParam& rQueryParam, bool bKeepSub );
f085be
     SC_DLLPUBLIC bool           CreateQueryParam( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2,
f085be
                                         SCTAB nTab, ScQueryParam& rQueryParam );
f085be
@@ -2022,8 +2027,8 @@ public:
f085be
 
f085be
     void            InvalidateStyleSheetUsage()
f085be
                         { bStyleSheetUsageInvalid = true; }
f085be
-    void GetSortParam( ScSortParam& rParam, SCTAB nTab );
f085be
-    void SetSortParam( ScSortParam& rParam, SCTAB nTab );
f085be
+    void SC_DLLPUBLIC GetSortParam( ScSortParam& rParam, SCTAB nTab );
f085be
+    void SC_DLLPUBLIC SetSortParam( ScSortParam& rParam, SCTAB nTab );
f085be
 
f085be
     inline void     SetVbaEventProcessor( const com::sun::star::uno::Reference< com::sun::star::script::vba::XVBAEventProcessor >& rxVbaEvents )
f085be
                         { mxVbaEvents = rxVbaEvents; }
f085be
@@ -2052,6 +2057,19 @@ public:
f085be
 
f085be
     size_t GetFormulaHash( const ScAddress& rPos ) const;
f085be
 
f085be
+    /**
f085be
+     * Make specified formula cells non-grouped.
f085be
+     *
f085be
+     * @param nTab sheet index
f085be
+     * @param nCol column index
f085be
+     * @param rRows list of row indices at which formula cells are to be
f085be
+     *              unshared. This call sorts the passed row indices and
f085be
+     *              removes duplicates, which is why the caller must pass it
f085be
+     *              as reference.
f085be
+     */
f085be
+    void UnshareFormulaCells( SCTAB nTab, SCCOL nCol, std::vector<SCROW>& rRows );
f085be
+    void RegroupFormulaCells( SCTAB nTab, SCCOL nCol );
f085be
+
f085be
     ScFormulaVectorState GetFormulaVectorState( const ScAddress& rPos ) const;
f085be
 
f085be
     formula::FormulaTokenRef ResolveStaticReference( const ScAddress& rPos );
f085be
@@ -2130,15 +2148,6 @@ private: // CLOOK-Impl-methods
f085be
 
f085be
     void SharePooledResources( ScDocument* pSrcDoc );
f085be
 };
f085be
-inline void ScDocument::GetSortParam( ScSortParam& rParam, SCTAB nTab )
f085be
-{
f085be
-    rParam = mSheetSortParams[ nTab ];
f085be
-}
f085be
-
f085be
-inline void ScDocument::SetSortParam( ScSortParam& rParam, SCTAB nTab )
f085be
-{
f085be
-    mSheetSortParams[ nTab ] = rParam;
f085be
-}
f085be
 
f085be
 #endif
f085be
 
f085be
diff --git a/sc/inc/formulacell.hxx b/sc/inc/formulacell.hxx
f085be
index 2d25c9b..9c7cd10 100644
f085be
--- a/sc/inc/formulacell.hxx
f085be
+++ b/sc/inc/formulacell.hxx
f085be
@@ -322,6 +322,8 @@ public:
f085be
     void            SetNextTrack( ScFormulaCell* pF );
f085be
 
f085be
     virtual void Notify( const SfxHint& rHint );
f085be
+    virtual void Query( SvtListener::QueryBase& rQuery ) const;
f085be
+
f085be
     void SetCompile( bool bVal );
f085be
     ScDocument* GetDocument() const;
f085be
     void            SetMatColsRows( SCCOL nCols, SCROW nRows, bool bDirtyFlag=true );
f085be
diff --git a/sc/inc/listenerquery.hxx b/sc/inc/listenerquery.hxx
f085be
new file mode 100644
f085be
index 0000000..2cbc957
f085be
--- /dev/null
f085be
+++ b/sc/inc/listenerquery.hxx
f085be
@@ -0,0 +1,50 @@
f085be
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
f085be
+/*
f085be
+ * This file is part of the LibreOffice project.
f085be
+ *
f085be
+ * This Source Code Form is subject to the terms of the Mozilla Public
f085be
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
f085be
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
f085be
+ */
f085be
+
f085be
+#ifndef SC_LISTENERQUERY_HXX
f085be
+#define SC_LISTENERQUERY_HXX
f085be
+
f085be
+#include <address.hxx>
f085be
+#include <svl/listener.hxx>
f085be
+
f085be
+namespace sc {
f085be
+
f085be
+/**
f085be
+ * Used to collect positions of formula cells that belong to a formula
f085be
+ * group.
f085be
+ */
f085be
+class RefQueryFormulaGroup : public SvtListener::QueryBase
f085be
+{
f085be
+public:
f085be
+    typedef std::vector<SCROW> ColType;
f085be
+    typedef boost::unordered_map<SCCOL,ColType> ColsType;
f085be
+    typedef boost::unordered_map<SCTAB,ColsType> TabsType;
f085be
+
f085be
+    RefQueryFormulaGroup();
f085be
+    virtual ~RefQueryFormulaGroup();
f085be
+
f085be
+    void setSkipRange( const ScRange& rRange );
f085be
+    void add( const ScAddress& rPos );
f085be
+
f085be
+    /**
f085be
+     * Row positions in each column may contain duplicates.  Caller must
f085be
+     * remove duplicates if necessary.
f085be
+     */
f085be
+    const TabsType& getAllPositions() const;
f085be
+
f085be
+private:
f085be
+    ScRange maSkipRange;
f085be
+    TabsType maTabs;
f085be
+};
f085be
+
f085be
+}
f085be
+
f085be
+#endif
f085be
+
f085be
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
f085be
diff --git a/sc/inc/listenerqueryids.hxx b/sc/inc/listenerqueryids.hxx
f085be
new file mode 100644
f085be
index 0000000..48f240b
f085be
--- /dev/null
f085be
+++ b/sc/inc/listenerqueryids.hxx
f085be
@@ -0,0 +1,17 @@
f085be
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
f085be
+/*
f085be
+ * This file is part of the LibreOffice project.
f085be
+ *
f085be
+ * This Source Code Form is subject to the terms of the Mozilla Public
f085be
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
f085be
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
f085be
+ */
f085be
+
f085be
+#ifndef SC_LISTENERQUERYIDS_HXX
f085be
+#define SC_LISTENERQUERYIDS_HXX
f085be
+
f085be
+#define SC_LISTENER_QUERY_FORMULA_GROUP_POS 0
f085be
+
f085be
+#endif
f085be
+
f085be
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
f085be
diff --git a/sc/inc/refhint.hxx b/sc/inc/refhint.hxx
f085be
index 3ffe861..6ccda8b 100644
f085be
--- a/sc/inc/refhint.hxx
f085be
+++ b/sc/inc/refhint.hxx
f085be
@@ -18,7 +18,11 @@ namespace sc {
f085be
 class RefHint : public SfxSimpleHint
f085be
 {
f085be
 public:
f085be
-    enum Type { Moved, ColumnReordered };
f085be
+    enum Type {
f085be
+        Moved,
f085be
+        ColumnReordered,
f085be
+        RowReordered
f085be
+    };
f085be
 
f085be
 private:
f085be
     Type meType;
f085be
@@ -57,22 +61,40 @@ public:
f085be
 
f085be
 class RefColReorderHint : public RefHint
f085be
 {
f085be
-    const sc::ColReorderMapType& mrColMap;
f085be
+    const sc::ColRowReorderMapType& mrColMap;
f085be
     SCTAB mnTab;
f085be
     SCROW mnRow1;
f085be
     SCROW mnRow2;
f085be
 
f085be
 public:
f085be
-    RefColReorderHint( const sc::ColReorderMapType& rColMap, SCTAB nTab, SCROW nRow1, SCROW nRow2 );
f085be
+    RefColReorderHint( const sc::ColRowReorderMapType& rColMap, SCTAB nTab, SCROW nRow1, SCROW nRow2 );
f085be
     virtual ~RefColReorderHint();
f085be
 
f085be
-    const sc::ColReorderMapType& getColMap() const;
f085be
+    const sc::ColRowReorderMapType& getColMap() const;
f085be
 
f085be
     SCTAB getTab() const;
f085be
     SCROW getStartRow() const;
f085be
     SCROW getEndRow() const;
f085be
 };
f085be
 
f085be
+class RefRowReorderHint : public RefHint
f085be
+{
f085be
+    const sc::ColRowReorderMapType& mrRowMap;
f085be
+    SCTAB mnTab;
f085be
+    SCCOL mnCol1;
f085be
+    SCCOL mnCol2;
f085be
+
f085be
+public:
f085be
+    RefRowReorderHint( const sc::ColRowReorderMapType& rRowMap, SCTAB nTab, SCCOL nCol1, SCCOL nCol2 );
f085be
+    virtual ~RefRowReorderHint();
f085be
+
f085be
+    const sc::ColRowReorderMapType& getRowMap() const;
f085be
+
f085be
+    SCTAB getTab() const;
f085be
+    SCCOL getStartColumn() const;
f085be
+    SCCOL getEndColumn() const;
f085be
+};
f085be
+
f085be
 }
f085be
 
f085be
 #endif
f085be
diff --git a/sc/inc/sharedformula.hxx b/sc/inc/sharedformula.hxx
f085be
index 571d73c..453b14f 100644
f085be
--- a/sc/inc/sharedformula.hxx
f085be
+++ b/sc/inc/sharedformula.hxx
f085be
@@ -100,6 +100,15 @@ public:
f085be
      * @param rCell formula cell instance
f085be
      */
f085be
     static void unshareFormulaCell(const CellStoreType::position_type& aPos, ScFormulaCell& rCell);
f085be
+
f085be
+    /**
f085be
+     * Make specified formula cells non-shared ones, and split them off from
f085be
+     * their respective adjacent formula cell groups.
f085be
+     *
f085be
+     * @param rCells cell storage container
f085be
+     * @param rRows row positions at which to unshare formula cells.
f085be
+     */
f085be
+    static void unshareFormulaCells(CellStoreType& rCells, std::vector<SCROW>& rRows);
f085be
 };
f085be
 
f085be
 }
f085be
diff --git a/sc/inc/sortparam.hxx b/sc/inc/sortparam.hxx
f085be
index b6f1427..4c3ef1b 100644
f085be
--- a/sc/inc/sortparam.hxx
f085be
+++ b/sc/inc/sortparam.hxx
f085be
@@ -80,6 +80,33 @@ struct SC_DLLPUBLIC ScSortParam
f085be
     inline sal_uInt16 GetSortKeyCount() const { return maKeyState.size(); }
f085be
 };
f085be
 
f085be
+namespace sc {
f085be
+
f085be
+struct SC_DLLPUBLIC ReorderParam
f085be
+{
f085be
+    /**
f085be
+     * This sort range already takes into account the presence or absence of
f085be
+     * header row / column i.e. if a header row / column is present, it
f085be
+     * excludes that row / column.
f085be
+     */
f085be
+    ScRange maSortRange;
f085be
+
f085be
+    /**
f085be
+     * List of original column / row positions after reordering.
f085be
+     */
f085be
+    std::vector<SCCOLROW> maOrderIndices;
f085be
+    bool mbByRow;
f085be
+    bool mbPattern;
f085be
+    bool mbHiddenFiltered;
f085be
+
f085be
+    /**
f085be
+     * Reorder the position indices such that it can be used to undo the
f085be
+     * original reordering.
f085be
+     */
f085be
+    void reverse();
f085be
+};
f085be
+
f085be
+}
f085be
 
f085be
 #endif // SC_SORTPARAM_HXX
f085be
 
f085be
diff --git a/sc/inc/table.hxx b/sc/inc/table.hxx
f085be
index fe8adb6..97ee720 100644
f085be
--- a/sc/inc/table.hxx
f085be
+++ b/sc/inc/table.hxx
f085be
@@ -71,6 +71,7 @@ class DocumentStreamAccess;
f085be
 class CompileFormulaContext;
f085be
 struct SetFormulaDirtyContext;
f085be
 class RefMovedHint;
f085be
+struct ReorderParam;
f085be
 
f085be
 }
f085be
 
f085be
@@ -828,7 +829,10 @@ public:
f085be
     void        StripHidden( SCCOL& rX1, SCROW& rY1, SCCOL& rX2, SCROW& rY2 );
f085be
     void        ExtendHidden( SCCOL& rX1, SCROW& rY1, SCCOL& rX2, SCROW& rY2 );
f085be
 
f085be
-    void        Sort(const ScSortParam& rSortParam, bool bKeepQuery, ScProgress* pProgress);
f085be
+    void Sort(
f085be
+        const ScSortParam& rSortParam, bool bKeepQuery, ScProgress* pProgress, sc::ReorderParam* pUndo );
f085be
+    void Reorder( const sc::ReorderParam& rParam, ScProgress* pProgress );
f085be
+
f085be
     bool ValidQuery(
f085be
         SCROW nRow, const ScQueryParam& rQueryParam, ScRefCellValue* pCell = NULL,
f085be
         bool* pbTestEqualCondition = NULL);
f085be
@@ -884,6 +888,9 @@ public:
f085be
     formula::FormulaTokenRef ResolveStaticReference( SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2 );
f085be
     formula::VectorRefArray FetchVectorRefArray( SCCOL nCol, SCROW nRow1, SCROW nRow2 );
f085be
 
f085be
+    void UnshareFormulaCells( SCCOL nCol, std::vector<SCROW>& rRows );
f085be
+    void RegroupFormulaCells( SCCOL nCol );
f085be
+
f085be
     ScRefCellValue GetRefCellValue( SCCOL nCol, SCROW nRow );
f085be
 
f085be
     SvtBroadcaster* GetBroadcaster( SCCOL nCol, SCROW nRow );
f085be
@@ -998,10 +1005,11 @@ private:
f085be
         ScRefCellValue& rCell2, SCCOL nCell2Col, SCROW nCell2Row ) const;
f085be
     short       Compare(SCCOLROW nIndex1, SCCOLROW nIndex2) const;
f085be
     short       Compare( ScSortInfoArray*, SCCOLROW nIndex1, SCCOLROW nIndex2) const;
f085be
-    ScSortInfoArray* CreateSortInfoArray( SCCOLROW nInd1, SCCOLROW nInd2, bool bKeepQuery );
f085be
+    ScSortInfoArray* CreateSortInfoArray( const sc::ReorderParam& rParam );
f085be
+    ScSortInfoArray* CreateSortInfoArray( const ScSortParam& rSortParam, SCCOLROW nInd1, SCCOLROW nInd2, bool bKeepQuery );
f085be
     void        QuickSort( ScSortInfoArray*, SCsCOLROW nLo, SCsCOLROW nHi);
f085be
-    void SortReorder( ScSortInfoArray* pArray, ScProgress* pProgress );
f085be
-    void SortReorderByRow( ScSortInfoArray* pArray, ScProgress* pProgress );
f085be
+    void SortReorderByColumn( ScSortInfoArray* pArray, SCROW nRow1, SCROW nRow2, bool bPattern, ScProgress* pProgress );
f085be
+    void SortReorderByRow( ScSortInfoArray* pArray, SCCOL nCol1, SCCOL nCol2, ScProgress* pProgress );
f085be
 
f085be
     bool        CreateExcelQuery(SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2, ScQueryParam& rQueryParam);
f085be
     bool        CreateStarQuery(SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2, ScQueryParam& rQueryParam);
f085be
diff --git a/sc/inc/tokenarray.hxx b/sc/inc/tokenarray.hxx
f085be
index 8715e9c..fbb613c 100644
f085be
--- a/sc/inc/tokenarray.hxx
f085be
+++ b/sc/inc/tokenarray.hxx
f085be
@@ -167,7 +167,13 @@ public:
f085be
      * @param nRow2 bottom row of reordered range.
f085be
      * @param rColMap old-to-new column mapping.
f085be
      */
f085be
-    void MoveReference( const ScAddress& rPos, SCTAB nTab, SCROW nRow1, SCROW nRow2, const sc::ColReorderMapType& rColMap );
f085be
+    void MoveReferenceColReorder(
f085be
+        const ScAddress& rPos, SCTAB nTab, SCROW nRow1, SCROW nRow2,
f085be
+        const sc::ColRowReorderMapType& rColMap );
f085be
+
f085be
+    void MoveReferenceRowReorder(
f085be
+        const ScAddress& rPos, SCTAB nTab, SCCOL nCol1, SCCOL nCol2,
f085be
+        const sc::ColRowReorderMapType& rRowMap );
f085be
 
f085be
     /**
f085be
      * Adjust all references in named expression. In named expression, we only
f085be
diff --git a/sc/inc/types.hxx b/sc/inc/types.hxx
f085be
index e0163aa..732ff19 100644
f085be
--- a/sc/inc/types.hxx
f085be
+++ b/sc/inc/types.hxx
f085be
@@ -98,7 +98,7 @@ struct RangeMatrix
f085be
     bool isRangeValid() const;
f085be
 };
f085be
 
f085be
-typedef boost::unordered_map<SCCOL,SCCOL> ColReorderMapType;
f085be
+typedef boost::unordered_map<SCCOLROW,SCCOLROW> ColRowReorderMapType;
f085be
 
f085be
 }
f085be
 
f085be
diff --git a/sc/inc/undosort.hxx b/sc/inc/undosort.hxx
f085be
new file mode 100644
f085be
index 0000000..388fcfa
f085be
--- /dev/null
f085be
+++ b/sc/inc/undosort.hxx
f085be
@@ -0,0 +1,37 @@
f085be
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
f085be
+/*
f085be
+ * This file is part of the LibreOffice project.
f085be
+ *
f085be
+ * This Source Code Form is subject to the terms of the Mozilla Public
f085be
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
f085be
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
f085be
+ */
f085be
+
f085be
+#ifndef INCLUDED_SC_UNDOSORT_HXX
f085be
+#define INCLUDED_SC_UNDOSORT_HXX
f085be
+
f085be
+#include <undobase.hxx>
f085be
+#include <sortparam.hxx>
f085be
+
f085be
+namespace sc {
f085be
+
f085be
+class UndoSort : public ScSimpleUndo
f085be
+{
f085be
+    ReorderParam maParam;
f085be
+
f085be
+public:
f085be
+    UndoSort( ScDocShell* pDocSh, const ReorderParam& rParam );
f085be
+
f085be
+    virtual OUString GetComment() const;
f085be
+    virtual void Undo();
f085be
+    virtual void Redo();
f085be
+
f085be
+private:
f085be
+    void Execute( bool bUndo );
f085be
+};
f085be
+
f085be
+}
f085be
+
f085be
+#endif
f085be
+
f085be
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
f085be
diff --git a/sc/qa/unit/filters-test.cxx b/sc/qa/unit/filters-test.cxx
f085be
index e7dcae2..dab2b9e 100644
f085be
--- a/sc/qa/unit/filters-test.cxx
f085be
+++ b/sc/qa/unit/filters-test.cxx
f085be
@@ -33,6 +33,10 @@
f085be
 #include "drwlayer.hxx"
f085be
 #include "userdat.hxx"
f085be
 #include "formulacell.hxx"
f085be
+#include <dbdocfun.hxx>
f085be
+#include <globalnames.hxx>
f085be
+#include <dbdata.hxx>
f085be
+#include <sortparam.hxx>
f085be
 
f085be
 #include <svx/svdpage.hxx>
f085be
 
f085be
diff --git a/sc/qa/unit/ucalc.cxx b/sc/qa/unit/ucalc.cxx
f085be
index e993a9b..fbc2919 100644
f085be
--- a/sc/qa/unit/ucalc.cxx
f085be
+++ b/sc/qa/unit/ucalc.cxx
f085be
@@ -51,6 +51,7 @@
f085be
 #include "queryparam.hxx"
f085be
 #include "edittextiterator.hxx"
f085be
 #include "editutil.hxx"
f085be
+#include <sortparam.hxx>
f085be
 
f085be
 #include "formula/IFunctionDescription.hxx"
f085be
 
f085be
@@ -4276,7 +4277,7 @@ void Test::testSortWithFormulaRefs()
f085be
     aSortData.maKeyState[0].bDoSort = true;
f085be
     aSortData.maKeyState[0].nField = 0;
f085be
 
f085be
-    pDoc->Sort(0, aSortData, false, NULL);
f085be
+    pDoc->Sort(0, aSortData, false, NULL, NULL);
f085be
 
f085be
     nEnd = SAL_N_ELEMENTS( aResults );
f085be
     for ( SCROW i = nStart; i < nEnd; ++i )
f085be
@@ -4312,7 +4313,7 @@ void Test::testSortWithStrings()
f085be
     aParam.maKeyState[0].bAscending = true;
f085be
     aParam.maKeyState[0].nField = 1;
f085be
 
f085be
-    m_pDoc->Sort(0, aParam, false, NULL);
f085be
+    m_pDoc->Sort(0, aParam, false, NULL, NULL);
f085be
 
f085be
     CPPUNIT_ASSERT_EQUAL(OUString("Header"), m_pDoc->GetString(ScAddress(1,1,0)));
f085be
     CPPUNIT_ASSERT_EQUAL(OUString("Val1"), m_pDoc->GetString(ScAddress(1,2,0)));
f085be
@@ -4320,7 +4321,7 @@ void Test::testSortWithStrings()
f085be
 
f085be
     aParam.maKeyState[0].bAscending = false;
f085be
 
f085be
-    m_pDoc->Sort(0, aParam, false, NULL);
f085be
+    m_pDoc->Sort(0, aParam, false, NULL, NULL);
f085be
 
f085be
     CPPUNIT_ASSERT_EQUAL(OUString("Header"), m_pDoc->GetString(ScAddress(1,1,0)));
f085be
     CPPUNIT_ASSERT_EQUAL(OUString("Val2"), m_pDoc->GetString(ScAddress(1,2,0)));
f085be
@@ -4366,7 +4367,7 @@ void Test::testSort()
f085be
     aSortData.maKeyState[0].nField = 1;
f085be
     aSortData.maKeyState[0].bAscending = true;
f085be
 
f085be
-    m_pDoc->Sort(0, aSortData, false, NULL);
f085be
+    m_pDoc->Sort(0, aSortData, false, NULL, NULL);
f085be
 
f085be
     double nVal = m_pDoc->GetValue(1,0,0);
f085be
     ASSERT_DOUBLES_EQUAL(nVal, 1.0);
f085be
@@ -4399,7 +4400,7 @@ void Test::testSort()
f085be
     aSortData.nRow2 = aDataRange.aEnd.Row();
f085be
     aSortData.bHasHeader = true;
f085be
     aSortData.maKeyState[0].nField = 0;
f085be
-    m_pDoc->Sort(0, aSortData, false, NULL);
f085be
+    m_pDoc->Sort(0, aSortData, false, NULL, NULL);
f085be
 
f085be
     // Title should stay at the top, numbers should be sorted numerically,
f085be
     // numbers always come before strings, and empty cells always occur at the
f085be
diff --git a/sc/source/core/data/documen3.cxx b/sc/source/core/data/documen3.cxx
f085be
index b2efbdf..75514fd 100644
f085be
--- a/sc/source/core/data/documen3.cxx
f085be
+++ b/sc/source/core/data/documen3.cxx
f085be
@@ -1354,17 +1354,30 @@ bool ScDocument::UpdateOutlineRow( SCROW nStartRow, SCROW nEndRow, SCTAB nTab, b
f085be
     return false;
f085be
 }
f085be
 
f085be
-void ScDocument::Sort(SCTAB nTab, const ScSortParam& rSortParam, bool bKeepQuery, ScProgress* pProgress)
f085be
+void ScDocument::Sort(
f085be
+    SCTAB nTab, const ScSortParam& rSortParam, bool bKeepQuery, ScProgress* pProgress, sc::ReorderParam* pUndo )
f085be
 {
f085be
     if ( ValidTab(nTab) && nTab < static_cast<SCTAB>(maTabs.size()) && maTabs[nTab] )
f085be
     {
f085be
         bool bOldEnableIdle = IsIdleEnabled();
f085be
         EnableIdle(false);
f085be
-        maTabs[nTab]->Sort(rSortParam, bKeepQuery, pProgress);
f085be
+        maTabs[nTab]->Sort(rSortParam, bKeepQuery, pProgress, pUndo);
f085be
         EnableIdle(bOldEnableIdle);
f085be
     }
f085be
 }
f085be
 
f085be
+void ScDocument::Reorder( const sc::ReorderParam& rParam, ScProgress* pProgress )
f085be
+{
f085be
+    ScTable* pTab = FetchTable(rParam.maSortRange.aStart.Tab());
f085be
+    if (!pTab)
f085be
+        return;
f085be
+
f085be
+    bool bOldEnableIdle = IsIdleEnabled();
f085be
+    EnableIdle(false);
f085be
+    pTab->Reorder(rParam, pProgress);
f085be
+    EnableIdle(bOldEnableIdle);
f085be
+}
f085be
+
f085be
 SCSIZE ScDocument::Query(SCTAB nTab, const ScQueryParam& rQueryParam, bool bKeepSub)
f085be
 {
f085be
     if ( ValidTab(nTab) && nTab < static_cast<SCTAB>(maTabs.size()) && maTabs[nTab] )
f085be
@@ -2016,4 +2029,14 @@ void ScDocument::ExtendPrintArea( OutputDevice* pDev, SCTAB nTab,
f085be
         maTabs[nTab]->ExtendPrintArea( pDev, nStartCol, nStartRow, rEndCol, nEndRow );
f085be
 }
f085be
 
f085be
+void ScDocument::GetSortParam( ScSortParam& rParam, SCTAB nTab )
f085be
+{
f085be
+    rParam = mSheetSortParams[ nTab ];
f085be
+}
f085be
+
f085be
+void ScDocument::SetSortParam( ScSortParam& rParam, SCTAB nTab )
f085be
+{
f085be
+    mSheetSortParams[ nTab ] = rParam;
f085be
+}
f085be
+
f085be
 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
f085be
diff --git a/sc/source/core/data/document10.cxx b/sc/source/core/data/document10.cxx
f085be
index a4ede21..cb64221 100644
f085be
--- a/sc/source/core/data/document10.cxx
f085be
+++ b/sc/source/core/data/document10.cxx
f085be
@@ -93,4 +93,22 @@ bool ScDocument::HasUniformRowHeight( SCTAB nTab, SCROW nRow1, SCROW nRow2 ) con
f085be
     return pTab->HasUniformRowHeight(nRow1, nRow2);
f085be
 }
f085be
 
f085be
+void ScDocument::UnshareFormulaCells( SCTAB nTab, SCCOL nCol, std::vector<SCROW>& rRows )
f085be
+{
f085be
+    ScTable* pTab = FetchTable(nTab);
f085be
+    if (!pTab)
f085be
+        return;
f085be
+
f085be
+    pTab->UnshareFormulaCells(nCol, rRows);
f085be
+}
f085be
+
f085be
+void ScDocument::RegroupFormulaCells( SCTAB nTab, SCCOL nCol )
f085be
+{
f085be
+    ScTable* pTab = FetchTable(nTab);
f085be
+    if (!pTab)
f085be
+        return;
f085be
+
f085be
+    pTab->RegroupFormulaCells(nCol);
f085be
+}
f085be
+
f085be
 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
f085be
diff --git a/sc/source/core/data/formulacell.cxx b/sc/source/core/data/formulacell.cxx
f085be
index 1397372..18194e1 100644
f085be
--- a/sc/source/core/data/formulacell.cxx
f085be
+++ b/sc/source/core/data/formulacell.cxx
f085be
@@ -52,6 +52,8 @@
f085be
 #include "refupdatecontext.hxx"
f085be
 #include <tokenstringcontext.hxx>
f085be
 #include <refhint.hxx>
f085be
+#include <listenerquery.hxx>
f085be
+#include <listenerqueryids.hxx>
f085be
 
f085be
 #include <boost/scoped_ptr.hpp>
f085be
 
f085be
@@ -1915,8 +1917,23 @@ void ScFormulaCell::Notify( const SfxHint& rHint )
f085be
                 const sc::RefColReorderHint& rRefColReorder =
f085be
                     static_cast<const sc::RefColReorderHint&>(rRefHint);
f085be
                 if (!IsShared() || IsSharedTop())
f085be
-                    pCode->MoveReference(
f085be
-                        aPos, rRefColReorder.getTab(), rRefColReorder.getStartRow(), rRefColReorder.getEndRow(), rRefColReorder.getColMap());
f085be
+                    pCode->MoveReferenceColReorder(
f085be
+                        aPos, rRefColReorder.getTab(),
f085be
+                        rRefColReorder.getStartRow(),
f085be
+                        rRefColReorder.getEndRow(),
f085be
+                        rRefColReorder.getColMap());
f085be
+            }
f085be
+            break;
f085be
+            case sc::RefHint::RowReordered:
f085be
+            {
f085be
+                const sc::RefRowReorderHint& rRefRowReorder =
f085be
+                    static_cast<const sc::RefRowReorderHint&>(rRefHint);
f085be
+                if (!IsShared() || IsSharedTop())
f085be
+                    pCode->MoveReferenceRowReorder(
f085be
+                        aPos, rRefRowReorder.getTab(),
f085be
+                        rRefRowReorder.getStartColumn(),
f085be
+                        rRefRowReorder.getEndColumn(),
f085be
+                        rRefRowReorder.getRowMap());
f085be
             }
f085be
             break;
f085be
             default:
f085be
@@ -1961,6 +1978,23 @@ void ScFormulaCell::Notify( const SfxHint& rHint )
f085be
     }
f085be
 }
f085be
 
f085be
+void ScFormulaCell::Query( SvtListener::QueryBase& rQuery ) const
f085be
+{
f085be
+    switch (rQuery.getId())
f085be
+    {
f085be
+        case SC_LISTENER_QUERY_FORMULA_GROUP_POS:
f085be
+        {
f085be
+            sc::RefQueryFormulaGroup& rRefQuery =
f085be
+                static_cast<sc::RefQueryFormulaGroup&>(rQuery);
f085be
+            if (IsShared())
f085be
+                rRefQuery.add(aPos);
f085be
+        }
f085be
+        break;
f085be
+        default:
f085be
+            ;
f085be
+    }
f085be
+}
f085be
+
f085be
 void ScFormulaCell::SetDirty( bool bDirtyFlag )
f085be
 {
f085be
     if ( !IsInChangeTrack() )
f085be
diff --git a/sc/source/core/data/sortparam.cxx b/sc/source/core/data/sortparam.cxx
f085be
index d416f32..e4aee16 100644
f085be
--- a/sc/source/core/data/sortparam.cxx
f085be
+++ b/sc/source/core/data/sortparam.cxx
f085be
@@ -252,4 +252,55 @@ void ScSortParam::MoveToDest()
f085be
     }
f085be
 }
f085be
 
f085be
+namespace sc {
f085be
+
f085be
+namespace {
f085be
+
f085be
+struct ReorderIndex
f085be
+{
f085be
+    struct LessByPos2 : std::binary_function<ReorderIndex, ReorderIndex, bool>
f085be
+    {
f085be
+        bool operator() ( const ReorderIndex& r1, const ReorderIndex& r2 ) const
f085be
+        {
f085be
+            return r1.mnPos2 < r2.mnPos2;
f085be
+        }
f085be
+    };
f085be
+
f085be
+    SCCOLROW mnPos1;
f085be
+    SCCOLROW mnPos2;
f085be
+
f085be
+    ReorderIndex( SCCOLROW nPos1, SCCOLROW nPos2 ) : mnPos1(nPos1), mnPos2(nPos2) {}
f085be
+};
f085be
+
f085be
+}
f085be
+
f085be
+void ReorderParam::reverse()
f085be
+{
f085be
+    SCCOLROW nStart;
f085be
+    if (mbByRow)
f085be
+        nStart = maSortRange.aStart.Row();
f085be
+    else
f085be
+        nStart = maSortRange.aStart.Col();
f085be
+
f085be
+    size_t n = maOrderIndices.size();
f085be
+    std::vector<ReorderIndex> aBucket;
f085be
+    aBucket.reserve(n);
f085be
+    for (size_t i = 0; i < n; ++i)
f085be
+    {
f085be
+        SCCOLROW nPos1 = i + nStart;
f085be
+        SCCOLROW nPos2 = maOrderIndices[i];
f085be
+        aBucket.push_back(ReorderIndex(nPos1, nPos2));
f085be
+    }
f085be
+
f085be
+    std::sort(aBucket.begin(), aBucket.end(), ReorderIndex::LessByPos2());
f085be
+    std::vector<SCCOLROW> aNew;
f085be
+    aNew.reserve(n);
f085be
+    for (size_t i = 0; i < n; ++i)
f085be
+        aNew.push_back(aBucket[i].mnPos1);
f085be
+
f085be
+    maOrderIndices.swap(aNew);
f085be
+}
f085be
+
f085be
+}
f085be
+
f085be
 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
f085be
diff --git a/sc/source/core/data/table3.cxx b/sc/source/core/data/table3.cxx
f085be
index 6a169ef..31cfe2e 100644
f085be
--- a/sc/source/core/data/table3.cxx
f085be
+++ b/sc/source/core/data/table3.cxx
f085be
@@ -61,6 +61,7 @@
f085be
 #include <listenercontext.hxx>
f085be
 #include <sharedformula.hxx>
f085be
 #include <refhint.hxx>
f085be
+#include <listenerquery.hxx>
f085be
 
f085be
 #include "svl/sharedstringpool.hxx"
f085be
 
f085be
@@ -257,39 +258,46 @@ private:
f085be
     SCCOLROW        mnLastIndex; /// index of last non-empty cell position.
f085be
     sal_uInt16      nUsedSorts;
f085be
 
f085be
-    std::vector<SCCOLROW> maOldIndices;
f085be
+    std::vector<SCCOLROW> maOrderIndices;
f085be
     bool mbKeepQuery;
f085be
 
f085be
 public:
f085be
     ScSortInfoArray( sal_uInt16 nSorts, SCCOLROW nInd1, SCCOLROW nInd2 ) :
f085be
-        pppInfo( new ScSortInfo**[nSorts]),
f085be
+        pppInfo(NULL),
f085be
         nCount( nInd2 - nInd1 + 1 ), nStart( nInd1 ),
f085be
         mnLastIndex(nInd2),
f085be
         nUsedSorts(nSorts),
f085be
         mbKeepQuery(false)
f085be
     {
f085be
-        for ( sal_uInt16 nSort = 0; nSort < nUsedSorts; nSort++ )
f085be
+        if (nUsedSorts)
f085be
         {
f085be
-            ScSortInfo** ppInfo = new ScSortInfo* [nCount];
f085be
-            for ( SCSIZE j = 0; j < nCount; j++ )
f085be
-                ppInfo[j] = new ScSortInfo;
f085be
-            pppInfo[nSort] = ppInfo;
f085be
+            pppInfo = new ScSortInfo**[nUsedSorts];
f085be
+            for ( sal_uInt16 nSort = 0; nSort < nUsedSorts; nSort++ )
f085be
+            {
f085be
+                ScSortInfo** ppInfo = new ScSortInfo* [nCount];
f085be
+                for ( SCSIZE j = 0; j < nCount; j++ )
f085be
+                    ppInfo[j] = new ScSortInfo;
f085be
+                pppInfo[nSort] = ppInfo;
f085be
+            }
f085be
         }
f085be
 
f085be
         for (size_t i = 0; i < nCount; ++i)
f085be
-            maOldIndices.push_back(i+nStart);
f085be
+            maOrderIndices.push_back(i+nStart);
f085be
     }
f085be
 
f085be
     ~ScSortInfoArray()
f085be
     {
f085be
-        for ( sal_uInt16 nSort = 0; nSort < nUsedSorts; nSort++ )
f085be
+        if (pppInfo)
f085be
         {
f085be
-            ScSortInfo** ppInfo = pppInfo[nSort];
f085be
-            for ( SCSIZE j = 0; j < nCount; j++ )
f085be
-                delete ppInfo[j];
f085be
-            delete [] ppInfo;
f085be
+            for ( sal_uInt16 nSort = 0; nSort < nUsedSorts; nSort++ )
f085be
+            {
f085be
+                ScSortInfo** ppInfo = pppInfo[nSort];
f085be
+                for ( SCSIZE j = 0; j < nCount; j++ )
f085be
+                    delete ppInfo[j];
f085be
+                delete [] ppInfo;
f085be
+            }
f085be
+            delete[] pppInfo;
f085be
         }
f085be
-        delete[] pppInfo;
f085be
 
f085be
         if (mpRows)
f085be
             std::for_each(mpRows->begin(), mpRows->end(), ScDeleteObjectByPtr<Row>());
f085be
@@ -299,11 +307,30 @@ public:
f085be
 
f085be
     bool IsKeepQuery() const { return mbKeepQuery; }
f085be
 
f085be
+    /**
f085be
+     * Call this only during normal sorting, not from reordering.
f085be
+     */
f085be
+    ScSortInfo** GetFirstArray() const
f085be
+    {
f085be
+        OSL_ASSERT(pppInfo);
f085be
+        return pppInfo[0];
f085be
+    }
f085be
+
f085be
+    /**
f085be
+     * Call this only during normal sorting, not from reordering.
f085be
+     */
f085be
     ScSortInfo* Get( sal_uInt16 nSort, SCCOLROW nInd )
f085be
-                    { return (pppInfo[nSort])[ nInd - nStart ]; }
f085be
+    {
f085be
+        OSL_ASSERT(pppInfo);
f085be
+        return (pppInfo[nSort])[ nInd - nStart ];
f085be
+    }
f085be
 
f085be
+    /**
f085be
+     * Call this only during normal sorting, not from reordering.
f085be
+     */
f085be
     void Swap( SCCOLROW nInd1, SCCOLROW nInd2 )
f085be
     {
f085be
+        OSL_ASSERT(pppInfo);
f085be
         SCSIZE n1 = static_cast<SCSIZE>(nInd1 - nStart);
f085be
         SCSIZE n2 = static_cast<SCSIZE>(nInd2 - nStart);
f085be
         for ( sal_uInt16 nSort = 0; nSort < nUsedSorts; nSort++ )
f085be
@@ -314,7 +341,7 @@ public:
f085be
             ppInfo[n2] = pTmp;
f085be
         }
f085be
 
f085be
-        std::swap(maOldIndices[n1], maOldIndices[n2]);
f085be
+        std::swap(maOrderIndices[n1], maOrderIndices[n2]);
f085be
 
f085be
         if (mpRows)
f085be
         {
f085be
@@ -324,13 +351,47 @@ public:
f085be
         }
f085be
     }
f085be
 
f085be
+    void SetOrderIndices( const std::vector<SCCOLROW>& rIndices )
f085be
+    {
f085be
+        maOrderIndices = rIndices;
f085be
+    }
f085be
+
f085be
+    /**
f085be
+     * @param rIndices indices are actual row positions on the sheet, not an
f085be
+     *                 offset from the top row.
f085be
+     */
f085be
+    void ReorderByRow( const std::vector<SCCOLROW>& rIndices )
f085be
+    {
f085be
+        if (!mpRows)
f085be
+            return;
f085be
+
f085be
+        RowsType& rRows = *mpRows;
f085be
+
f085be
+        std::vector<SCCOLROW> aOrderIndices2;
f085be
+        aOrderIndices2.reserve(rIndices.size());
f085be
+
f085be
+        RowsType aRows2;
f085be
+        aRows2.reserve(rRows.size());
f085be
+
f085be
+        std::vector<SCCOLROW>::const_iterator it = rIndices.begin(), itEnd = rIndices.end();
f085be
+        for (; it != itEnd; ++it)
f085be
+        {
f085be
+            size_t nPos = *it - nStart; // switch to an offset to top row.
f085be
+            aRows2.push_back(rRows[nPos]);
f085be
+            aOrderIndices2.push_back(maOrderIndices[nPos]);
f085be
+        }
f085be
+
f085be
+        rRows.swap(aRows2);
f085be
+        maOrderIndices.swap(aOrderIndices2);
f085be
+    }
f085be
+
f085be
     sal_uInt16      GetUsedSorts() const { return nUsedSorts; }
f085be
-    ScSortInfo**    GetFirstArray() const { return pppInfo[0]; }
f085be
+
f085be
     SCCOLROW    GetStart() const { return nStart; }
f085be
     SCCOLROW GetLast() const { return mnLastIndex; }
f085be
     SCSIZE      GetCount() const { return nCount; }
f085be
 
f085be
-    const std::vector<SCCOLROW>& GetOldIndices() const { return maOldIndices; }
f085be
+    const std::vector<SCCOLROW>& GetOrderIndices() const { return maOrderIndices; }
f085be
 
f085be
     RowsType& InitDataRows( size_t nRowSize, size_t nColSize )
f085be
     {
f085be
@@ -348,19 +409,98 @@ public:
f085be
     }
f085be
 };
f085be
 
f085be
-ScSortInfoArray* ScTable::CreateSortInfoArray( SCCOLROW nInd1, SCCOLROW nInd2, bool bKeepQuery )
f085be
+namespace {
f085be
+
f085be
+void initDataRows(
f085be
+    ScSortInfoArray& rArray, ScTable& rTab, ScColumn* pCols,
f085be
+    SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2,
f085be
+    bool bPattern, bool bHiddenFiltered )
f085be
+{
f085be
+    // Fill row-wise data table.
f085be
+    ScSortInfoArray::RowsType& rRows = rArray.InitDataRows(nRow2-nRow1+1, nCol2-nCol1+1);
f085be
+
f085be
+    for (SCCOL nCol = nCol1; nCol <= nCol2; ++nCol)
f085be
+    {
f085be
+        ScColumn& rCol = pCols[nCol];
f085be
+
f085be
+        // Skip reordering of cell formats if the whole span is on the same pattern entry.
f085be
+        bool bUniformPattern = rCol.GetPatternCount(nRow1, nRow2) < 2u;
f085be
+
f085be
+        sc::ColumnBlockConstPosition aBlockPos;
f085be
+        rCol.InitBlockPosition(aBlockPos);
f085be
+        for (SCROW nRow = nRow1; nRow <= nRow2; ++nRow)
f085be
+        {
f085be
+            ScSortInfoArray::Row& rRow = *rRows[nRow-nRow1];
f085be
+            ScSortInfoArray::Cell& rCell = rRow.maCells[nCol-nCol1];
f085be
+
f085be
+            rCell.maCell = rCol.GetCellValue(aBlockPos, nRow);
f085be
+            rCell.mpAttr = rCol.GetCellTextAttr(aBlockPos, nRow);
f085be
+            rCell.mpBroadcaster = rCol.GetBroadcaster(aBlockPos, nRow);
f085be
+            rCell.mpNote = rCol.GetCellNote(aBlockPos, nRow);
f085be
+
f085be
+            if (!bUniformPattern && bPattern)
f085be
+                rCell.mpPattern = rCol.GetPattern(nRow);
f085be
+        }
f085be
+    }
f085be
+
f085be
+    if (bHiddenFiltered)
f085be
+    {
f085be
+        for (SCROW nRow = nRow1; nRow <= nRow2; ++nRow)
f085be
+        {
f085be
+            ScSortInfoArray::Row& rRow = *rRows[nRow-nRow1];
f085be
+            rRow.mbHidden = rTab.RowHidden(nRow);
f085be
+            rRow.mbFiltered = rTab.RowFiltered(nRow);
f085be
+        }
f085be
+    }
f085be
+}
f085be
+
f085be
+}
f085be
+
f085be
+ScSortInfoArray* ScTable::CreateSortInfoArray( const sc::ReorderParam& rParam )
f085be
+{
f085be
+    ScSortInfoArray* pArray = NULL;
f085be
+
f085be
+    if (rParam.mbByRow)
f085be
+    {
f085be
+        // Create a sort info array with just the data table.
f085be
+        SCROW nRow1 = rParam.maSortRange.aStart.Row();
f085be
+        SCROW nRow2 = rParam.maSortRange.aEnd.Row();
f085be
+        SCCOL nCol1 = rParam.maSortRange.aStart.Col();
f085be
+        SCCOL nCol2 = rParam.maSortRange.aEnd.Col();
f085be
+
f085be
+        pArray = new ScSortInfoArray(0, nRow1, nRow2);
f085be
+        pArray->SetKeepQuery(rParam.mbHiddenFiltered);
f085be
+
f085be
+        initDataRows(
f085be
+            *pArray, *this, aCol, nCol1, nRow1, nCol2, nRow2,
f085be
+            rParam.mbPattern, rParam.mbHiddenFiltered);
f085be
+    }
f085be
+    else
f085be
+    {
f085be
+        SCCOLROW nCol1 = rParam.maSortRange.aStart.Col();
f085be
+        SCCOLROW nCol2 = rParam.maSortRange.aEnd.Col();
f085be
+
f085be
+        pArray = new ScSortInfoArray(0, nCol1, nCol2);
f085be
+        pArray->SetKeepQuery(rParam.mbHiddenFiltered);
f085be
+    }
f085be
+
f085be
+    return pArray;
f085be
+}
f085be
+
f085be
+ScSortInfoArray* ScTable::CreateSortInfoArray(
f085be
+    const ScSortParam& rSortParam, SCCOLROW nInd1, SCCOLROW nInd2, bool bKeepQuery )
f085be
 {
f085be
     sal_uInt16 nUsedSorts = 1;
f085be
-    while ( nUsedSorts < aSortParam.GetSortKeyCount() && aSortParam.maKeyState[nUsedSorts].bDoSort )
f085be
+    while ( nUsedSorts < rSortParam.GetSortKeyCount() && rSortParam.maKeyState[nUsedSorts].bDoSort )
f085be
         nUsedSorts++;
f085be
     ScSortInfoArray* pArray = new ScSortInfoArray( nUsedSorts, nInd1, nInd2 );
f085be
     pArray->SetKeepQuery(bKeepQuery);
f085be
 
f085be
-    if ( aSortParam.bByRow )
f085be
+    if ( rSortParam.bByRow )
f085be
     {
f085be
         for ( sal_uInt16 nSort = 0; nSort < nUsedSorts; nSort++ )
f085be
         {
f085be
-            SCCOL nCol = static_cast<SCCOL>(aSortParam.maKeyState[nSort].nField);
f085be
+            SCCOL nCol = static_cast<SCCOL>(rSortParam.maKeyState[nSort].nField);
f085be
             ScColumn* pCol = &aCol[nCol];
f085be
             sc::ColumnBlockConstPosition aBlockPos;
f085be
             pCol->InitBlockPosition(aBlockPos);
f085be
@@ -372,49 +512,15 @@ ScSortInfoArray* ScTable::CreateSortInfoArray( SCCOLROW nInd1, SCCOLROW nInd2, b
f085be
             }
f085be
         }
f085be
 
f085be
-        // Fill row-wise data table.
f085be
-        ScSortInfoArray::RowsType& rRows = pArray->InitDataRows(
f085be
-            nInd2 - nInd1 + 1, aSortParam.nCol2 - aSortParam.nCol1 + 1);
f085be
-
f085be
-        for (SCCOL nCol = aSortParam.nCol1; nCol <= aSortParam.nCol2; ++nCol)
f085be
-        {
f085be
-            ScColumn& rCol = aCol[nCol];
f085be
-
f085be
-            // Skip reordering of cell formats if the whole span is on the same pattern entry.
f085be
-            bool bUniformPattern = rCol.GetPatternCount(nInd1, nInd2) < 2u;
f085be
-
f085be
-            sc::ColumnBlockConstPosition aBlockPos;
f085be
-            rCol.InitBlockPosition(aBlockPos);
f085be
-            for (SCROW nRow = nInd1; nRow <= nInd2; ++nRow)
f085be
-            {
f085be
-                ScSortInfoArray::Row& rRow = *rRows[nRow-nInd1];
f085be
-                ScSortInfoArray::Cell& rCell = rRow.maCells[nCol-aSortParam.nCol1];
f085be
-
f085be
-                rCell.maCell = rCol.GetCellValue(aBlockPos, nRow);
f085be
-                rCell.mpAttr = rCol.GetCellTextAttr(aBlockPos, nRow);
f085be
-                rCell.mpBroadcaster = rCol.GetBroadcaster(aBlockPos, nRow);
f085be
-                rCell.mpNote = rCol.GetCellNote(aBlockPos, nRow);
f085be
-
f085be
-                if (!bUniformPattern && aSortParam.bIncludePattern)
f085be
-                    rCell.mpPattern = rCol.GetPattern(nRow);
f085be
-            }
f085be
-        }
f085be
-
f085be
-        if (bKeepQuery)
f085be
-        {
f085be
-            for (SCROW nRow = nInd1; nRow <= nInd2; ++nRow)
f085be
-            {
f085be
-                ScSortInfoArray::Row& rRow = *rRows[nRow-nInd1];
f085be
-                rRow.mbHidden = RowHidden(nRow);
f085be
-                rRow.mbFiltered = RowFiltered(nRow);
f085be
-            }
f085be
-        }
f085be
+        initDataRows(
f085be
+            *pArray, *this, aCol, rSortParam.nCol1, nInd1, rSortParam.nCol2, nInd2,
f085be
+            rSortParam.bIncludePattern, bKeepQuery);
f085be
     }
f085be
     else
f085be
     {
f085be
         for ( sal_uInt16 nSort = 0; nSort < nUsedSorts; nSort++ )
f085be
         {
f085be
-            SCROW nRow = aSortParam.maKeyState[nSort].nField;
f085be
+            SCROW nRow = rSortParam.maKeyState[nSort].nField;
f085be
             for ( SCCOL nCol = static_cast<SCCOL>(nInd1);
f085be
                     nCol <= static_cast<SCCOL>(nInd2); nCol++ )
f085be
             {
f085be
@@ -530,12 +636,13 @@ void ScTable::DestroySortCollator()
f085be
 
f085be
 namespace {
f085be
 
f085be
-class ColReorderNotifier : std::unary_function<SvtListener*, void>
f085be
+template<typename _Hint, typename _ReorderMap, typename _Index>
f085be
+class ReorderNotifier : std::unary_function<SvtListener*, void>
f085be
 {
f085be
-    sc::RefColReorderHint maHint;
f085be
+    _Hint maHint;
f085be
 public:
f085be
-    ColReorderNotifier( const sc::ColReorderMapType& rColMap, SCTAB nTab, SCROW nRow1, SCROW nRow2 ) :
f085be
-        maHint(rColMap, nTab, nRow1, nRow2) {}
f085be
+    ReorderNotifier( const _ReorderMap& rMap, SCTAB nTab, _Index nPos1, _Index nPos2 ) :
f085be
+        maHint(rMap, nTab, nPos1, nPos2) {}
f085be
 
f085be
     void operator() ( SvtListener* p )
f085be
     {
f085be
@@ -543,77 +650,86 @@ public:
f085be
     }
f085be
 };
f085be
 
f085be
-}
f085be
+typedef ReorderNotifier<sc::RefColReorderHint, sc::ColRowReorderMapType, SCCOL> ColReorderNotifier;
f085be
+typedef ReorderNotifier<sc::RefRowReorderHint, sc::ColRowReorderMapType, SCROW> RowReorderNotifier;
f085be
 
f085be
-void ScTable::SortReorder( ScSortInfoArray* pArray, ScProgress* pProgress )
f085be
+class FormulaGroupPosCollector : std::unary_function<SvtListener*, void>
f085be
 {
f085be
-    if (aSortParam.bByRow)
f085be
+    sc::RefQueryFormulaGroup& mrQuery;
f085be
+
f085be
+public:
f085be
+    FormulaGroupPosCollector( sc::RefQueryFormulaGroup& rQuery ) : mrQuery(rQuery) {}
f085be
+
f085be
+    void operator() ( SvtListener* p )
f085be
     {
f085be
-        SortReorderByRow(pArray, pProgress);
f085be
-        return;
f085be
+        p->Query(mrQuery);
f085be
     }
f085be
+};
f085be
 
f085be
-    size_t nCount = pArray->GetCount();
f085be
+}
f085be
+
f085be
+void ScTable::SortReorderByColumn(
f085be
+    ScSortInfoArray* pArray, SCROW nRow1, SCROW nRow2, bool bPattern, ScProgress* pProgress )
f085be
+{
f085be
     SCCOLROW nStart = pArray->GetStart();
f085be
     SCCOLROW nLast = pArray->GetLast();
f085be
-    ScSortInfo** ppInfo = pArray->GetFirstArray();
f085be
-
f085be
-    std::vector<ScSortInfo*> aTable(nCount);
f085be
 
f085be
-    SCSIZE nPos;
f085be
-    for ( nPos = 0; nPos < nCount; nPos++ )
f085be
-        aTable[ppInfo[nPos]->nOrg - nStart] = ppInfo[nPos];
f085be
+    std::vector<SCCOLROW> aIndices = pArray->GetOrderIndices();
f085be
+    size_t nCount = aIndices.size();
f085be
 
f085be
     // Cut formula grouping at row and reference boundaries before the reordering.
f085be
-    ScRange aSortRange(nStart, aSortParam.nRow1, nTab, nLast, aSortParam.nRow2, nTab);
f085be
+    ScRange aSortRange(nStart, nRow1, nTab, nLast, nRow2, nTab);
f085be
     for (SCCOL nCol = nStart; nCol <= nLast; ++nCol)
f085be
         aCol[nCol].SplitFormulaGroupByRelativeRef(aSortRange);
f085be
 
f085be
+    // table to keep track of column index to position in the index table.
f085be
+    std::vector<SCCOLROW> aPosTable(nCount);
f085be
+    for (size_t i = 0; i < nCount; ++i)
f085be
+        aPosTable[aIndices[i]-nStart] = i;
f085be
+
f085be
     SCCOLROW nDest = nStart;
f085be
-    for ( nPos = 0; nPos < nCount; nPos++, nDest++ )
f085be
+    for (size_t i = 0; i < nCount; ++i, ++nDest)
f085be
     {
f085be
-        SCCOLROW nOrg = ppInfo[nPos]->nOrg;
f085be
-        if ( nDest != nOrg )
f085be
+        SCCOLROW nSrc = aIndices[i];
f085be
+        if (nDest != nSrc)
f085be
         {
f085be
-            aCol[nDest].Swap(aCol[nOrg], aSortParam.nRow1, aSortParam.nRow2, aSortParam.bIncludePattern);
f085be
+            aCol[nDest].Swap(aCol[nSrc], nRow1, nRow2, bPattern);
f085be
 
f085be
-            // neue Position des weggeswapten eintragen
f085be
-            ScSortInfo* p = ppInfo[nPos];
f085be
-            p->nOrg = nDest;
f085be
-            ::std::swap(p, aTable[nDest-nStart]);
f085be
-            p->nOrg = nOrg;
f085be
-            ::std::swap(p, aTable[nOrg-nStart]);
f085be
-            OSL_ENSURE( p == ppInfo[nPos], "SortReorder: nOrg MisMatch" );
f085be
+            // Update the position of the index that was originally equal to nDest.
f085be
+            size_t nPos = aPosTable[nDest-nStart];
f085be
+            aIndices[nPos] = nSrc;
f085be
+            aPosTable[nSrc-nStart] = nPos;
f085be
         }
f085be
-        if(pProgress)
f085be
-            pProgress->SetStateOnPercent( nPos );
f085be
+
f085be
+        if (pProgress)
f085be
+            pProgress->SetStateOnPercent(i);
f085be
     }
f085be
 
f085be
     // Reset formula cell positions which became out-of-sync after column reordering.
f085be
     for (SCCOL nCol = nStart; nCol <= nLast; ++nCol)
f085be
-        aCol[nCol].ResetFormulaCellPositions(aSortParam.nRow1, aSortParam.nRow2);
f085be
+        aCol[nCol].ResetFormulaCellPositions(nRow1, nRow2);
f085be
 
f085be
     // Set up column reorder map (for later broadcasting of reference updates).
f085be
-    sc::ColReorderMapType aColMap;
f085be
-    const std::vector<SCCOLROW>& rOldIndices = pArray->GetOldIndices();
f085be
+    sc::ColRowReorderMapType aColMap;
f085be
+    const std::vector<SCCOLROW>& rOldIndices = pArray->GetOrderIndices();
f085be
     for (size_t i = 0, n = rOldIndices.size(); i < n; ++i)
f085be
     {
f085be
         SCCOL nNew = i + nStart;
f085be
-        SCROW nOld = rOldIndices[i];
f085be
-        aColMap.insert(sc::ColReorderMapType::value_type(nOld, nNew));
f085be
+        SCCOL nOld = rOldIndices[i];
f085be
+        aColMap.insert(sc::ColRowReorderMapType::value_type(nOld, nNew));
f085be
     }
f085be
 
f085be
     // Collect all listeners within sorted range ahead of time.
f085be
     std::vector<SvtListener*> aListeners;
f085be
     for (SCCOL nCol = nStart; nCol <= nLast; ++nCol)
f085be
-        aCol[nCol].CollectListeners(aListeners, aSortParam.nRow1, aSortParam.nRow2);
f085be
+        aCol[nCol].CollectListeners(aListeners, nRow1, nRow2);
f085be
 
f085be
     // Remove any duplicate listener entries and notify all listeners
f085be
     // afterward.  We must ensure that we notify each unique listener only
f085be
     // once.
f085be
     std::sort(aListeners.begin(), aListeners.end());
f085be
     aListeners.erase(std::unique(aListeners.begin(), aListeners.end()), aListeners.end());
f085be
-    ColReorderNotifier aFunc(aColMap, nTab, aSortParam.nRow1, aSortParam.nRow2);
f085be
+    ColReorderNotifier aFunc(aColMap, nTab, nRow1, nRow2);
f085be
     std::for_each(aListeners.begin(), aListeners.end(), aFunc);
f085be
 
f085be
     // Re-join formulas at row boundaries now that all the references have
f085be
@@ -621,28 +737,28 @@ void ScTable::SortReorder( ScSortInfoArray* pArray, ScProgress* pProgress )
f085be
     for (SCCOL nCol = nStart; nCol <= nLast; ++nCol)
f085be
     {
f085be
         sc::CellStoreType& rCells = aCol[nCol].maCells;
f085be
-        sc::CellStoreType::position_type aPos = rCells.position(aSortParam.nRow1);
f085be
+        sc::CellStoreType::position_type aPos = rCells.position(nRow1);
f085be
         sc::SharedFormulaUtil::joinFormulaCellAbove(aPos);
f085be
-        aPos = rCells.position(aPos.first, aSortParam.nRow2+1);
f085be
+        aPos = rCells.position(aPos.first, nRow2+1);
f085be
         sc::SharedFormulaUtil::joinFormulaCellAbove(aPos);
f085be
     }
f085be
 }
f085be
 
f085be
-void ScTable::SortReorderByRow( ScSortInfoArray* pArray, ScProgress* pProgress )
f085be
+void ScTable::SortReorderByRow(
f085be
+    ScSortInfoArray* pArray, SCCOL nCol1, SCCOL nCol2, ScProgress* pProgress )
f085be
 {
f085be
+    if (nCol2 < nCol1)
f085be
+        return;
f085be
+
f085be
     SCROW nRow1 = pArray->GetStart();
f085be
     SCROW nRow2 = pArray->GetLast();
f085be
     ScSortInfoArray::RowsType* pRows = pArray->GetDataRows();
f085be
     assert(pRows); // In sort-by-row mode we must have data rows already populated.
f085be
 
f085be
-    // Detach all formula cells within the sorted range first.
f085be
-    sc::EndListeningContext aCxt(*pDocument);
f085be
-    DetachFormulaCells(aCxt, aSortParam.nCol1, nRow1, aSortParam.nCol2, nRow2);
f085be
-
f085be
     // Cells in the data rows only reference values in the document. Make
f085be
     // a copy before updating the document.
f085be
 
f085be
-    size_t nColCount = aSortParam.nCol2 - aSortParam.nCol1 + 1;
f085be
+    size_t nColCount = nCol2 - nCol1 + 1;
f085be
     boost::ptr_vector<SortedColumn> aSortedCols; // storage for copied cells.
f085be
     SortedRowFlags aRowFlags;
f085be
     aSortedCols.reserve(nColCount);
f085be
@@ -659,7 +775,7 @@ void ScTable::SortReorderByRow( ScSortInfoArray* pArray, ScProgress* pProgress )
f085be
         ScSortInfoArray::Row* pRow = (*pRows)[i];
f085be
         for (size_t j = 0; j < pRow->maCells.size(); ++j)
f085be
         {
f085be
-            ScAddress aCellPos(aSortParam.nCol1 + j, nRow1 + i, nTab);
f085be
+            ScAddress aCellPos(nCol1 + j, nRow1 + i, nTab);
f085be
 
f085be
             ScSortInfoArray::Cell& rCell = pRow->maCells[j];
f085be
 
f085be
@@ -681,14 +797,14 @@ void ScTable::SortReorderByRow( ScSortInfoArray* pArray, ScProgress* pProgress )
f085be
                 case CELLTYPE_FORMULA:
f085be
                 {
f085be
                     assert(rCell.mpAttr);
f085be
-                    size_t n = rCellStore.size();
f085be
-                    sc::CellStoreType::iterator itBlk = rCellStore.push_back( rCell.maCell.mpFormula->Clone(
f085be
-                                aCellPos, SC_CLONECELL_DEFAULT | SC_CLONECELL_ADJUST3DREL));
f085be
-
f085be
-                    // Join the formula cells as we fill the container.
f085be
-                    size_t nOffset = n - itBlk->position;
f085be
-                    sc::CellStoreType::position_type aPos(itBlk, nOffset);
f085be
-                    sc::SharedFormulaUtil::joinFormulaCellAbove(aPos);
f085be
+                    ScAddress aOldPos = rCell.maCell.mpFormula->aPos;
f085be
+
f085be
+                    ScFormulaCell* pNew = rCell.maCell.mpFormula->Clone(
f085be
+                        aCellPos, SC_CLONECELL_DEFAULT | SC_CLONECELL_ADJUST3DREL);
f085be
+                    pNew->CopyAllBroadcasters(*rCell.maCell.mpFormula);
f085be
+                    pNew->GetCode()->AdjustReferenceOnMovedOrigin(aOldPos, aCellPos);
f085be
+
f085be
+                    sc::CellStoreType::iterator itBlk = rCellStore.push_back(pNew);
f085be
                 }
f085be
                 break;
f085be
                 default:
f085be
@@ -737,7 +853,7 @@ void ScTable::SortReorderByRow( ScSortInfoArray* pArray, ScProgress* pProgress )
f085be
 
f085be
     for (size_t i = 0, n = aSortedCols.size(); i < n; ++i)
f085be
     {
f085be
-        SCCOL nThisCol = i + aSortParam.nCol1;
f085be
+        SCCOL nThisCol = i + nCol1;
f085be
 
f085be
         {
f085be
             sc::CellStoreType& rDest = aCol[nThisCol].maCells;
f085be
@@ -812,10 +928,62 @@ void ScTable::SortReorderByRow( ScSortInfoArray* pArray, ScProgress* pProgress )
f085be
             SetRowFiltered(it->mnRow1, it->mnRow2, true);
f085be
     }
f085be
 
f085be
-    // Attach all formula cells within sorted range, to have them start listening again.
f085be
-    sc::StartListeningContext aStartListenCxt(*pDocument);
f085be
-    AttachFormulaCells(
f085be
-        aStartListenCxt, aSortParam.nCol1, nRow1, aSortParam.nCol2, nRow2);
f085be
+    // Set up row reorder map (for later broadcasting of reference updates).
f085be
+    sc::ColRowReorderMapType aRowMap;
f085be
+    const std::vector<SCCOLROW>& rOldIndices = pArray->GetOrderIndices();
f085be
+    for (size_t i = 0, n = rOldIndices.size(); i < n; ++i)
f085be
+    {
f085be
+        SCROW nNew = i + nRow1;
f085be
+        SCROW nOld = rOldIndices[i];
f085be
+        aRowMap.insert(sc::ColRowReorderMapType::value_type(nOld, nNew));
f085be
+    }
f085be
+
f085be
+    // Collect all listeners within sorted range ahead of time.
f085be
+    std::vector<SvtListener*> aListeners;
f085be
+    for (SCCOL nCol = nCol1; nCol <= nCol2; ++nCol)
f085be
+        aCol[nCol].CollectListeners(aListeners, nRow1, nRow2);
f085be
+
f085be
+    // Remove any duplicate listener entries.  We must ensure that we notify
f085be
+    // each unique listener only once.
f085be
+    std::sort(aListeners.begin(), aListeners.end());
f085be
+    aListeners.erase(std::unique(aListeners.begin(), aListeners.end()), aListeners.end());
f085be
+
f085be
+    // Collect positions of all shared formula cells outside the sorted range,
f085be
+    // and make them unshared before notifying them.
f085be
+    sc::RefQueryFormulaGroup aFormulaGroupPos;
f085be
+    aFormulaGroupPos.setSkipRange(ScRange(nCol1, nRow1, nTab, nCol2, nRow2, nTab));
f085be
+
f085be
+    std::for_each(aListeners.begin(), aListeners.end(), FormulaGroupPosCollector(aFormulaGroupPos));
f085be
+    const sc::RefQueryFormulaGroup::TabsType& rGroupTabs = aFormulaGroupPos.getAllPositions();
f085be
+    sc::RefQueryFormulaGroup::TabsType::const_iterator itGroupTab = rGroupTabs.begin(), itGroupTabEnd = rGroupTabs.end();
f085be
+    for (; itGroupTab != itGroupTabEnd; ++itGroupTab)
f085be
+    {
f085be
+        const sc::RefQueryFormulaGroup::ColsType& rCols = itGroupTab->second;
f085be
+        sc::RefQueryFormulaGroup::ColsType::const_iterator itCol = rCols.begin(), itColEnd = rCols.end();
f085be
+        for (; itCol != itColEnd; ++itCol)
f085be
+        {
f085be
+            const sc::RefQueryFormulaGroup::ColType& rCol = itCol->second;
f085be
+            std::vector<SCROW> aBounds(rCol);
f085be
+            pDocument->UnshareFormulaCells(itGroupTab->first, itCol->first, aBounds);
f085be
+        }
f085be
+    }
f085be
+
f085be
+    // Notify the listeners.
f085be
+    RowReorderNotifier aFunc(aRowMap, nTab, nCol1, nCol2);
f085be
+    std::for_each(aListeners.begin(), aListeners.end(), aFunc);
f085be
+
f085be
+    // Re-group formulas in affected columns.
f085be
+    for (itGroupTab = rGroupTabs.begin(); itGroupTab != itGroupTabEnd; ++itGroupTab)
f085be
+    {
f085be
+        const sc::RefQueryFormulaGroup::ColsType& rCols = itGroupTab->second;
f085be
+        sc::RefQueryFormulaGroup::ColsType::const_iterator itCol = rCols.begin(), itColEnd = rCols.end();
f085be
+        for (; itCol != itColEnd; ++itCol)
f085be
+            pDocument->RegroupFormulaCells(itGroupTab->first, itCol->first);
f085be
+    }
f085be
+
f085be
+    // Re-group columns in the sorted range too.
f085be
+    for (SCCOL i = nCol1; i <= nCol2; ++i)
f085be
+        aCol[i].RegroupFormulaCells();
f085be
 }
f085be
 
f085be
 short ScTable::CompareCell(
f085be
@@ -1034,11 +1202,21 @@ void ScTable::DecoladeRow( ScSortInfoArray* pArray, SCROW nRow1, SCROW nRow2 )
f085be
     }
f085be
 }
f085be
 
f085be
-void ScTable::Sort(const ScSortParam& rSortParam, bool bKeepQuery, ScProgress* pProgress)
f085be
+void ScTable::Sort(
f085be
+    const ScSortParam& rSortParam, bool bKeepQuery, ScProgress* pProgress, sc::ReorderParam* pUndo )
f085be
 {
f085be
     aSortParam = rSortParam;
f085be
     InitSortCollator( rSortParam );
f085be
     bGlobalKeepQuery = bKeepQuery;
f085be
+
f085be
+    if (pUndo)
f085be
+    {
f085be
+        // Copy over the basic sort parameters.
f085be
+        pUndo->mbByRow = rSortParam.bByRow;
f085be
+        pUndo->mbPattern = rSortParam.bIncludePattern;
f085be
+        pUndo->mbHiddenFiltered = bKeepQuery;
f085be
+    }
f085be
+
f085be
     if (rSortParam.bByRow)
f085be
     {
f085be
         SCROW nLastRow = 0;
f085be
@@ -1052,15 +1230,19 @@ void ScTable::Sort(const ScSortParam& rSortParam, bool bKeepQuery, ScProgress* p
f085be
             if(pProgress)
f085be
                 pProgress->SetState( 0, nLastRow-nRow1 );
f085be
 
f085be
-            boost::scoped_ptr<ScSortInfoArray> pArray(CreateSortInfoArray(nRow1, nLastRow, bKeepQuery));
f085be
+            boost::scoped_ptr<ScSortInfoArray> pArray(CreateSortInfoArray(aSortParam, nRow1, nLastRow, bKeepQuery));
f085be
 
f085be
             if ( nLastRow - nRow1 > 255 )
f085be
                 DecoladeRow(pArray.get(), nRow1, nLastRow);
f085be
 
f085be
             QuickSort(pArray.get(), nRow1, nLastRow);
f085be
-            SortReorder(pArray.get(), pProgress);
f085be
+            SortReorderByRow(pArray.get(), aSortParam.nCol1, aSortParam.nCol2, pProgress);
f085be
 
f085be
-            // #i59745# update position of caption objects of cell notes --> reported at (SortReorder) ScColumn::SwapCellNotes level
f085be
+            if (pUndo)
f085be
+            {
f085be
+                pUndo->maSortRange = ScRange(rSortParam.nCol1, nRow1, nTab, rSortParam.nCol2, nLastRow, nTab);
f085be
+                pUndo->maOrderIndices = pArray->GetOrderIndices();
f085be
+            }
f085be
         }
f085be
     }
f085be
     else
f085be
@@ -1077,17 +1259,48 @@ void ScTable::Sort(const ScSortParam& rSortParam, bool bKeepQuery, ScProgress* p
f085be
             if(pProgress)
f085be
                 pProgress->SetState( 0, nLastCol-nCol1 );
f085be
 
f085be
-            boost::scoped_ptr<ScSortInfoArray> pArray(CreateSortInfoArray(nCol1, nLastCol, bKeepQuery));
f085be
+            boost::scoped_ptr<ScSortInfoArray> pArray(CreateSortInfoArray(aSortParam, nCol1, nLastCol, bKeepQuery));
f085be
 
f085be
             QuickSort(pArray.get(), nCol1, nLastCol);
f085be
-            SortReorder(pArray.get(), pProgress);
f085be
+            SortReorderByColumn(pArray.get(), aSortParam.nRow1, aSortParam.nRow2, aSortParam.bIncludePattern, pProgress);
f085be
 
f085be
-            // #i59745# update position of caption objects of cell notes --> reported at (SortReorder) ScColumn::SwapCellNotes level
f085be
+            if (pUndo)
f085be
+            {
f085be
+                pUndo->maSortRange = ScRange(nCol1, aSortParam.nRow1, nTab, nLastCol, aSortParam.nRow2, nTab);
f085be
+                pUndo->maOrderIndices = pArray->GetOrderIndices();
f085be
+            }
f085be
         }
f085be
     }
f085be
     DestroySortCollator();
f085be
 }
f085be
 
f085be
+void ScTable::Reorder( const sc::ReorderParam& rParam, ScProgress* pProgress )
f085be
+{
f085be
+    if (rParam.maOrderIndices.empty())
f085be
+        return;
f085be
+
f085be
+    boost::scoped_ptr<ScSortInfoArray> pArray(CreateSortInfoArray(rParam));
f085be
+    if (!pArray)
f085be
+        return;
f085be
+
f085be
+    if (rParam.mbByRow)
f085be
+    {
f085be
+        // Re-play sorting from the known sort indices.
f085be
+        pArray->ReorderByRow(rParam.maOrderIndices);
f085be
+
f085be
+        SortReorderByRow(
f085be
+            pArray.get(), rParam.maSortRange.aStart.Col(), rParam.maSortRange.aEnd.Col(), pProgress);
f085be
+    }
f085be
+    else
f085be
+    {
f085be
+        // Ordering by column is much simpler.  Just set the order indices and we are done.
f085be
+        pArray->SetOrderIndices(rParam.maOrderIndices);
f085be
+        SortReorderByColumn(
f085be
+            pArray.get(), rParam.maSortRange.aStart.Row(), rParam.maSortRange.aEnd.Row(),
f085be
+            rParam.mbPattern, pProgress);
f085be
+    }
f085be
+}
f085be
+
f085be
 namespace {
f085be
 
f085be
 class SubTotalRowFinder
f085be
@@ -2078,7 +2291,7 @@ void ScTable::TopTenQuery( ScQueryParam& rParam )
f085be
                     bSortCollatorInitialized = true;
f085be
                     InitSortCollator( aLocalSortParam );
f085be
                 }
f085be
-                boost::scoped_ptr<ScSortInfoArray> pArray(CreateSortInfoArray(nRow1, rParam.nRow2, bGlobalKeepQuery));
f085be
+                boost::scoped_ptr<ScSortInfoArray> pArray(CreateSortInfoArray(aSortParam, nRow1, rParam.nRow2, bGlobalKeepQuery));
f085be
                 DecoladeRow( pArray.get(), nRow1, rParam.nRow2 );
f085be
                 QuickSort( pArray.get(), nRow1, rParam.nRow2 );
f085be
                 ScSortInfo** ppInfo = pArray->GetFirstArray();
f085be
diff --git a/sc/source/core/data/table7.cxx b/sc/source/core/data/table7.cxx
f085be
index 2e6aad1..f3528dd 100644
f085be
--- a/sc/source/core/data/table7.cxx
f085be
+++ b/sc/source/core/data/table7.cxx
f085be
@@ -13,6 +13,7 @@
f085be
 #include <clipparam.hxx>
f085be
 #include <bcaslot.hxx>
f085be
 #include <segmenttree.hxx>
f085be
+#include <sharedformula.hxx>
f085be
 
f085be
 void ScTable::DeleteBeforeCopyFromClip( sc::CopyFromClipContext& rCxt, const ScTable& rClipTab )
f085be
 {
f085be
@@ -78,4 +79,20 @@ bool ScTable::HasUniformRowHeight( SCROW nRow1, SCROW nRow2 ) const
f085be
     return nRow2 <= aData.mnRow2;
f085be
 }
f085be
 
f085be
+void ScTable::UnshareFormulaCells( SCCOL nCol, std::vector<SCROW>& rRows )
f085be
+{
f085be
+    if (!ValidCol(nCol))
f085be
+        return;
f085be
+
f085be
+    sc::SharedFormulaUtil::unshareFormulaCells(aCol[nCol].maCells, rRows);
f085be
+}
f085be
+
f085be
+void ScTable::RegroupFormulaCells( SCCOL nCol )
f085be
+{
f085be
+    if (!ValidCol(nCol))
f085be
+        return;
f085be
+
f085be
+    aCol[nCol].RegroupFormulaCells();
f085be
+}
f085be
+
f085be
 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
f085be
diff --git a/sc/source/core/tool/listenerquery.cxx b/sc/source/core/tool/listenerquery.cxx
f085be
new file mode 100644
f085be
index 0000000..bf9d38f
f085be
--- /dev/null
f085be
+++ b/sc/source/core/tool/listenerquery.cxx
f085be
@@ -0,0 +1,72 @@
f085be
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
f085be
+/*
f085be
+ * This file is part of the LibreOffice project.
f085be
+ *
f085be
+ * This Source Code Form is subject to the terms of the Mozilla Public
f085be
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
f085be
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
f085be
+ */
f085be
+
f085be
+#include <listenerquery.hxx>
f085be
+#include <listenerqueryids.hxx>
f085be
+#include <address.hxx>
f085be
+
f085be
+namespace sc {
f085be
+
f085be
+RefQueryFormulaGroup::RefQueryFormulaGroup() :
f085be
+    SvtListener::QueryBase(SC_LISTENER_QUERY_FORMULA_GROUP_POS),
f085be
+    maSkipRange(ScAddress::INITIALIZE_INVALID) {}
f085be
+
f085be
+RefQueryFormulaGroup::~RefQueryFormulaGroup() {}
f085be
+
f085be
+void RefQueryFormulaGroup::setSkipRange( const ScRange& rRange )
f085be
+{
f085be
+    maSkipRange = rRange;
f085be
+}
f085be
+
f085be
+void RefQueryFormulaGroup::add( const ScAddress& rPos )
f085be
+{
f085be
+    if (!rPos.IsValid())
f085be
+        return;
f085be
+
f085be
+    if (maSkipRange.IsValid() && maSkipRange.In(rPos))
f085be
+        // This is within the skip range.  Skip it.
f085be
+        return;
f085be
+
f085be
+    TabsType::iterator itTab = maTabs.find(rPos.Tab());
f085be
+    if (itTab == maTabs.end())
f085be
+    {
f085be
+        std::pair<TabsType::iterator,bool> r =
f085be
+            maTabs.insert(TabsType::value_type(rPos.Tab(), ColsType()));
f085be
+        if (!r.second)
f085be
+            // Insertion failed.
f085be
+            return;
f085be
+
f085be
+        itTab = r.first;
f085be
+    }
f085be
+
f085be
+    ColsType& rCols = itTab->second;
f085be
+    ColsType::iterator itCol = rCols.find(rPos.Col());
f085be
+    if (itCol == rCols.end())
f085be
+    {
f085be
+        std::pair<ColsType::iterator,bool> r =
f085be
+            rCols.insert(ColsType::value_type(rPos.Col(), ColType()));
f085be
+        if (!r.second)
f085be
+            // Insertion failed.
f085be
+            return;
f085be
+
f085be
+        itCol = r.first;
f085be
+    }
f085be
+
f085be
+    ColType& rCol = itCol->second;
f085be
+    rCol.push_back(rPos.Row());
f085be
+}
f085be
+
f085be
+const RefQueryFormulaGroup::TabsType& RefQueryFormulaGroup::getAllPositions() const
f085be
+{
f085be
+    return maTabs;
f085be
+}
f085be
+
f085be
+}
f085be
+
f085be
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
f085be
diff --git a/sc/source/core/tool/refhint.cxx b/sc/source/core/tool/refhint.cxx
f085be
index 0e70b4f..29a9166 100644
f085be
--- a/sc/source/core/tool/refhint.cxx
f085be
+++ b/sc/source/core/tool/refhint.cxx
f085be
@@ -31,12 +31,12 @@ const ScAddress& RefMovedHint::getDelta() const
f085be
     return maMoveDelta;
f085be
 }
f085be
 
f085be
-RefColReorderHint::RefColReorderHint( const sc::ColReorderMapType& rColMap, SCTAB nTab, SCROW nRow1, SCROW nRow2 ) :
f085be
+RefColReorderHint::RefColReorderHint( const sc::ColRowReorderMapType& rColMap, SCTAB nTab, SCROW nRow1, SCROW nRow2 ) :
f085be
     RefHint(ColumnReordered), mrColMap(rColMap), mnTab(nTab), mnRow1(nRow1), mnRow2(nRow2) {}
f085be
 
f085be
 RefColReorderHint::~RefColReorderHint() {}
f085be
 
f085be
-const sc::ColReorderMapType& RefColReorderHint::getColMap() const
f085be
+const sc::ColRowReorderMapType& RefColReorderHint::getColMap() const
f085be
 {
f085be
     return mrColMap;
f085be
 }
f085be
@@ -56,6 +56,31 @@ SCROW RefColReorderHint::getEndRow() const
f085be
     return mnRow2;
f085be
 }
f085be
 
f085be
+RefRowReorderHint::RefRowReorderHint( const sc::ColRowReorderMapType& rRowMap, SCTAB nTab, SCCOL nCol1, SCCOL nCol2 ) :
f085be
+    RefHint(RowReordered), mrRowMap(rRowMap), mnTab(nTab), mnCol1(nCol1), mnCol2(nCol2) {}
f085be
+
f085be
+RefRowReorderHint::~RefRowReorderHint() {}
f085be
+
f085be
+const sc::ColRowReorderMapType& RefRowReorderHint::getRowMap() const
f085be
+{
f085be
+    return mrRowMap;
f085be
+}
f085be
+
f085be
+SCTAB RefRowReorderHint::getTab() const
f085be
+{
f085be
+    return mnTab;
f085be
+}
f085be
+
f085be
+SCCOL RefRowReorderHint::getStartColumn() const
f085be
+{
f085be
+    return mnCol1;
f085be
+}
f085be
+
f085be
+SCCOL RefRowReorderHint::getEndColumn() const
f085be
+{
f085be
+    return mnCol2;
f085be
+}
f085be
+
f085be
 }
f085be
 
f085be
 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
f085be
diff --git a/sc/source/core/tool/sharedformula.cxx b/sc/source/core/tool/sharedformula.cxx
f085be
index ed35690..6f66365 100644
f085be
--- a/sc/source/core/tool/sharedformula.cxx
f085be
+++ b/sc/source/core/tool/sharedformula.cxx
f085be
@@ -297,6 +297,35 @@ void SharedFormulaUtil::unshareFormulaCell(const CellStoreType::position_type& a
f085be
     rCell.SetCellGroup(xNone);
f085be
 }
f085be
 
f085be
+void SharedFormulaUtil::unshareFormulaCells(CellStoreType& rCells, std::vector<SCROW>& rRows)
f085be
+{
f085be
+    if (rRows.empty())
f085be
+        return;
f085be
+
f085be
+    // Sort and remove duplicates.
f085be
+    std::sort(rRows.begin(), rRows.end());
f085be
+    rRows.erase(std::unique(rRows.begin(), rRows.end()), rRows.end());
f085be
+
f085be
+    // Add next cell positions to the list (to ensure that each position becomes a single cell).
f085be
+    std::vector<SCROW> aRows2;
f085be
+    std::vector<SCROW>::const_iterator it = rRows.begin(), itEnd = rRows.end();
f085be
+    for (; it != itEnd; ++it)
f085be
+    {
f085be
+        if (*it > MAXROW)
f085be
+            break;
f085be
+
f085be
+        aRows2.push_back(*it);
f085be
+
f085be
+        if (*it < MAXROW)
f085be
+            aRows2.push_back(*it+1);
f085be
+    }
f085be
+
f085be
+    // Remove duplicates again (the vector should still be sorted).
f085be
+    aRows2.erase(std::unique(aRows2.begin(), aRows2.end()), aRows2.end());
f085be
+
f085be
+    splitFormulaCellGroups(rCells, aRows2);
f085be
+}
f085be
+
f085be
 }
f085be
 
f085be
 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
f085be
diff --git a/sc/source/core/tool/token.cxx b/sc/source/core/tool/token.cxx
f085be
index ab47bee..c289960 100644
f085be
--- a/sc/source/core/tool/token.cxx
f085be
+++ b/sc/source/core/tool/token.cxx
f085be
@@ -2914,8 +2914,8 @@ void ScTokenArray::MoveReference(
f085be
     }
f085be
 }
f085be
 
f085be
-void ScTokenArray::MoveReference(
f085be
-    const ScAddress& rPos, SCTAB nTab, SCROW nRow1, SCROW nRow2, const sc::ColReorderMapType& rColMap )
f085be
+void ScTokenArray::MoveReferenceColReorder(
f085be
+    const ScAddress& rPos, SCTAB nTab, SCROW nRow1, SCROW nRow2, const sc::ColRowReorderMapType& rColMap )
f085be
 {
f085be
     FormulaToken** p = pCode;
f085be
     FormulaToken** pEnd = p + static_cast<size_t>(nLen);
f085be
@@ -2932,7 +2932,7 @@ void ScTokenArray::MoveReference(
f085be
                 if (aAbs.Tab() == nTab && nRow1 <= aAbs.Row() && aAbs.Row() <= nRow2)
f085be
                 {
f085be
                     // Inside reordered row range.
f085be
-                    sc::ColReorderMapType::const_iterator it = rColMap.find(aAbs.Col());
f085be
+                    sc::ColRowReorderMapType::const_iterator it = rColMap.find(aAbs.Col());
f085be
                     if (it != rColMap.end())
f085be
                     {
f085be
                         // This column is reordered.
f085be
@@ -2960,7 +2960,7 @@ void ScTokenArray::MoveReference(
f085be
                 if (aAbs.aStart.Tab() == nTab && nRow1 <= aAbs.aStart.Row() && aAbs.aEnd.Row() <= nRow2)
f085be
                 {
f085be
                     // Inside reordered row range.
f085be
-                    sc::ColReorderMapType::const_iterator it = rColMap.find(aAbs.aStart.Col());
f085be
+                    sc::ColRowReorderMapType::const_iterator it = rColMap.find(aAbs.aStart.Col());
f085be
                     if (it != rColMap.end())
f085be
                     {
f085be
                         // This column is reordered.
f085be
@@ -2978,6 +2978,69 @@ void ScTokenArray::MoveReference(
f085be
     }
f085be
 }
f085be
 
f085be
+void ScTokenArray::MoveReferenceRowReorder( const ScAddress& rPos, SCTAB nTab, SCCOL nCol1, SCCOL nCol2, const sc::ColRowReorderMapType& rRowMap )
f085be
+{
f085be
+    FormulaToken** p = pCode;
f085be
+    FormulaToken** pEnd = p + static_cast<size_t>(nLen);
f085be
+    for (; p != pEnd; ++p)
f085be
+    {
f085be
+        switch ((*p)->GetType())
f085be
+        {
f085be
+            case svSingleRef:
f085be
+            {
f085be
+                ScToken* pToken = static_cast<ScToken*>(*p);
f085be
+                ScSingleRefData& rRef = pToken->GetSingleRef();
f085be
+                ScAddress aAbs = rRef.toAbs(rPos);
f085be
+
f085be
+                if (aAbs.Tab() == nTab && nCol1 <= aAbs.Col() && aAbs.Col() <= nCol2)
f085be
+                {
f085be
+                    // Inside reordered column range.
f085be
+                    sc::ColRowReorderMapType::const_iterator it = rRowMap.find(aAbs.Row());
f085be
+                    if (it != rRowMap.end())
f085be
+                    {
f085be
+                        // This column is reordered.
f085be
+                        SCROW nNewRow = it->second;
f085be
+                        aAbs.SetRow(nNewRow);
f085be
+                        rRef.SetAddress(aAbs, rPos);
f085be
+                    }
f085be
+                }
f085be
+            }
f085be
+            break;
f085be
+            case svDoubleRef:
f085be
+            {
f085be
+                ScToken* pToken = static_cast<ScToken*>(*p);
f085be
+                ScComplexRefData& rRef = pToken->GetDoubleRef();
f085be
+                ScRange aAbs = rRef.toAbs(rPos);
f085be
+
f085be
+                if (aAbs.aStart.Tab() != aAbs.aEnd.Tab())
f085be
+                    // Must be a single-sheet reference.
f085be
+                    break;
f085be
+
f085be
+                if (aAbs.aStart.Row() != aAbs.aEnd.Row())
f085be
+                    // Whole range must fit in a single row.
f085be
+                    break;
f085be
+
f085be
+                if (aAbs.aStart.Tab() == nTab && nCol1 <= aAbs.aStart.Col() && aAbs.aEnd.Col() <= nCol2)
f085be
+                {
f085be
+                    // Inside reordered column range.
f085be
+                    sc::ColRowReorderMapType::const_iterator it = rRowMap.find(aAbs.aStart.Row());
f085be
+                    if (it != rRowMap.end())
f085be
+                    {
f085be
+                        // This row is reordered.
f085be
+                        SCCOL nNewRow = it->second;
f085be
+                        aAbs.aStart.SetRow(nNewRow);
f085be
+                        aAbs.aEnd.SetRow(nNewRow);
f085be
+                        rRef.SetRange(aAbs, rPos);
f085be
+                    }
f085be
+                }
f085be
+            }
f085be
+            break;
f085be
+            default:
f085be
+                ;
f085be
+        }
f085be
+    }
f085be
+}
f085be
+
f085be
 namespace {
f085be
 
f085be
 bool adjustSingleRefInName(
f085be
diff --git a/sc/source/filter/xml/XMLExportDatabaseRanges.cxx b/sc/source/filter/xml/XMLExportDatabaseRanges.cxx
f085be
index ea2b31c..8e954ad 100644
f085be
--- a/sc/source/filter/xml/XMLExportDatabaseRanges.cxx
f085be
+++ b/sc/source/filter/xml/XMLExportDatabaseRanges.cxx
f085be
@@ -35,6 +35,7 @@
f085be
 #include "subtotalparam.hxx"
f085be
 #include "queryparam.hxx"
f085be
 #include "queryentry.hxx"
f085be
+#include <sortparam.hxx>
f085be
 
f085be
 #include "svx/dataaccessdescriptor.hxx"
f085be
 
f085be
diff --git a/sc/source/filter/xml/xmldrani.cxx b/sc/source/filter/xml/xmldrani.cxx
f085be
index 9478b0c..c6a8727 100644
f085be
--- a/sc/source/filter/xml/xmldrani.cxx
f085be
+++ b/sc/source/filter/xml/xmldrani.cxx
f085be
@@ -34,6 +34,7 @@
f085be
 #include "rangeutl.hxx"
f085be
 #include "queryentry.hxx"
f085be
 #include "dputil.hxx"
f085be
+#include <sortparam.hxx>
f085be
 
f085be
 #include <xmloff/xmltkmap.hxx>
f085be
 #include <xmloff/nmspmap.hxx>
f085be
diff --git a/sc/source/ui/docshell/dbdocfun.cxx b/sc/source/ui/docshell/dbdocfun.cxx
f085be
index d9d5550..900bf3e 100644
f085be
--- a/sc/source/ui/docshell/dbdocfun.cxx
f085be
+++ b/sc/source/ui/docshell/dbdocfun.cxx
f085be
@@ -47,6 +47,7 @@
f085be
 #include "queryentry.hxx"
f085be
 #include "markdata.hxx"
f085be
 #include "progress.hxx"
f085be
+#include <undosort.hxx>
f085be
 
f085be
 #include <set>
f085be
 #include <memory>
f085be
@@ -433,8 +434,6 @@ sal_Bool ScDBDocFunc::Sort( SCTAB nTab, const ScSortParam& rSortParam,
f085be
     ScDocument* pDoc = rDocShell.GetDocument();
f085be
     if (bRecord && !pDoc->IsUndoEnabled())
f085be
         bRecord = false;
f085be
-    SCTAB nSrcTab = nTab;
f085be
-    ScDrawLayer* pDrawLayer = pDoc->GetDrawLayer();
f085be
 
f085be
     ScDBData* pDBData = pDoc->GetDBAtArea( nTab, rSortParam.nCol1, rSortParam.nRow1,
f085be
                                                     rSortParam.nCol2, rSortParam.nRow2 );
f085be
@@ -444,28 +443,25 @@ sal_Bool ScDBDocFunc::Sort( SCTAB nTab, const ScSortParam& rSortParam,
f085be
         return false;
f085be
     }
f085be
 
f085be
-    ScDBData* pDestData = NULL;
f085be
-    ScRange aOldDest;
f085be
-    sal_Bool bCopy = !rSortParam.bInplace;
f085be
+    bool bCopy = !rSortParam.bInplace;
f085be
     if ( bCopy && rSortParam.nDestCol == rSortParam.nCol1 &&
f085be
                   rSortParam.nDestRow == rSortParam.nRow1 && rSortParam.nDestTab == nTab )
f085be
         bCopy = false;
f085be
+
f085be
     ScSortParam aLocalParam( rSortParam );
f085be
     if ( bCopy )
f085be
     {
f085be
-        aLocalParam.MoveToDest();
f085be
-        if ( !ValidColRow( aLocalParam.nCol2, aLocalParam.nRow2 ) )
f085be
-        {
f085be
-            if (!bApi)
f085be
-                rDocShell.ErrorMessage(STR_PASTE_FULL);
f085be
+        // Copy the data range to the destination then move the sort range to it.
f085be
+        ScRange aSrcRange(rSortParam.nCol1, rSortParam.nRow1, nTab, rSortParam.nCol2, rSortParam.nRow2, nTab);
f085be
+        ScAddress aDestPos(rSortParam.nDestCol,rSortParam.nDestRow,rSortParam.nDestTab);
f085be
+
f085be
+        ScDocFunc& rDocFunc = rDocShell.GetDocFunc();
f085be
+        bool bRet = rDocFunc.MoveBlock(aSrcRange, aDestPos, false, bRecord, bPaint, bApi);
f085be
+
f085be
+        if (!bRet)
f085be
             return false;
f085be
-        }
f085be
 
f085be
-        nTab = rSortParam.nDestTab;
f085be
-        pDestData = pDoc->GetDBAtCursor( rSortParam.nDestCol, rSortParam.nDestRow,
f085be
-                                            rSortParam.nDestTab, sal_True );
f085be
-        if (pDestData)
f085be
-            pDestData->GetArea(aOldDest);
f085be
+        aLocalParam.MoveToDest();
f085be
     }
f085be
 
f085be
     ScEditableTester aTester( pDoc, nTab, aLocalParam.nCol1,aLocalParam.nRow1,
f085be
@@ -515,133 +511,23 @@ sal_Bool ScDBDocFunc::Sort( SCTAB nTab, const ScSortParam& rSortParam,
f085be
     if ( aQueryParam.GetEntry(0).bDoQuery )
f085be
         bRepeatQuery = sal_True;
f085be
 
f085be
-    if (bRepeatQuery && bCopy)
f085be
-    {
f085be
-        if ( aQueryParam.bInplace ||
f085be
-                aQueryParam.nDestCol != rSortParam.nDestCol ||
f085be
-                aQueryParam.nDestRow != rSortParam.nDestRow ||
f085be
-                aQueryParam.nDestTab != rSortParam.nDestTab )       // Query auf selben Zielbereich?
f085be
-            bRepeatQuery = false;
f085be
-    }
f085be
-
f085be
-    ScUndoSort* pUndoAction = 0;
f085be
-    if ( bRecord )
f085be
-    {
f085be
-        //  Referenzen ausserhalb des Bereichs werden nicht veraendert !
f085be
-
f085be
-        ScDocument* pUndoDoc = new ScDocument( SCDOCMODE_UNDO );
f085be
-        //  Zeilenhoehen immer (wegen automatischer Anpassung)
f085be
-        //! auf ScBlockUndo umstellen
f085be
-        pUndoDoc->InitUndo( pDoc, nTab, nTab, false, sal_True );
f085be
-
f085be
-        /*  #i59745# Do not copy note captions to undo document. All existing
f085be
-            caption objects will be repositioned while sorting which is tracked
f085be
-            in drawing undo. When undo is executed, the old positions will be
f085be
-            restored, and the cells with the old notes (which still refer to the
f085be
-            existing captions) will be copied back into the source document. */
f085be
-        pDoc->CopyToDocument( aLocalParam.nCol1, aLocalParam.nRow1, nTab,
f085be
-                                aLocalParam.nCol2, aLocalParam.nRow2, nTab,
f085be
-                                IDF_ALL|IDF_NOCAPTIONS, false, pUndoDoc );
f085be
-
f085be
-        const ScRange* pR = 0;
f085be
-        if (pDestData)
f085be
-        {
f085be
-            /*  #i59745# Do not copy note captions from destination range to
f085be
-                undo document. All existing caption objects will be removed
f085be
-                which is tracked in drawing undo. When undo is executed, the
f085be
-                caption objects are reinserted with drawing undo, and the cells
f085be
-                with the old notes (which still refer to the existing captions)
f085be
-                will be copied back into the source document. */
f085be
-            pDoc->CopyToDocument( aOldDest, IDF_ALL|IDF_NOCAPTIONS, false, pUndoDoc );
f085be
-            pR = &aOldDest;
f085be
-        }
f085be
-
f085be
-        //  Zeilenhoehen immer (wegen automatischer Anpassung)
f085be
-        //! auf ScBlockUndo umstellen
f085be
-//        if (bRepeatQuery)
f085be
-            pDoc->CopyToDocument( 0, aLocalParam.nRow1, nTab, MAXCOL, aLocalParam.nRow2, nTab,
f085be
-                                    IDF_NONE, false, pUndoDoc );
f085be
-
f085be
-        ScDBCollection* pUndoDB = NULL;
f085be
-        ScDBCollection* pDocDB = pDoc->GetDBCollection();
f085be
-        if (!pDocDB->empty())
f085be
-            pUndoDB = new ScDBCollection( *pDocDB );
f085be
-
f085be
-        pUndoAction = new ScUndoSort( &rDocShell, nTab, rSortParam, pUndoDoc, pUndoDB, pR );
f085be
-        rDocShell.GetUndoManager()->AddUndoAction( pUndoAction );
f085be
-
f085be
-        // #i59745# collect all drawing undo actions affecting cell note captions
f085be
-        if( pDrawLayer )
f085be
-            pDrawLayer->BeginCalcUndo(false);
f085be
-    }
f085be
-
f085be
-    if ( bCopy )
f085be
-    {
f085be
-        if (pDestData)
f085be
-            pDoc->DeleteAreaTab(aOldDest, IDF_CONTENTS);            // Zielbereich vorher loeschen
f085be
-
f085be
-        ScRange aSource( rSortParam.nCol1,rSortParam.nRow1,nSrcTab,
f085be
-                            rSortParam.nCol2,rSortParam.nRow2,nSrcTab );
f085be
-        ScAddress aDest( rSortParam.nDestCol, rSortParam.nDestRow, rSortParam.nDestTab );
f085be
-
f085be
-        rDocShell.GetDocFunc().MoveBlock( aSource, aDest, false, false, false, sal_True );
f085be
-    }
f085be
+    sc::ReorderParam aUndoParam;
f085be
 
f085be
     // don't call ScDocument::Sort with an empty SortParam (may be empty here if bCopy is set)
f085be
     if (aLocalParam.GetSortKeyCount() && aLocalParam.maKeyState[0].bDoSort)
f085be
     {
f085be
         ScProgress aProgress(&rDocShell, ScGlobal::GetRscString(STR_PROGRESS_SORTING), 0);
f085be
-        pDoc->Sort( nTab, aLocalParam, bRepeatQuery, &aProgress );
f085be
+        pDoc->Sort(nTab, aLocalParam, bRepeatQuery, &aProgress, &aUndoParam);
f085be
     }
f085be
 
f085be
-    sal_Bool bSave = sal_True;
f085be
-    if (bCopy)
f085be
-    {
f085be
-        ScSortParam aOldSortParam;
f085be
-        pDBData->GetSortParam( aOldSortParam );
f085be
-        if (aOldSortParam.GetSortKeyCount() &&
f085be
-            aOldSortParam.maKeyState[0].bDoSort && aOldSortParam.bInplace)
f085be
-        {
f085be
-            bSave = false;
f085be
-            aOldSortParam.nDestCol = rSortParam.nDestCol;
f085be
-            aOldSortParam.nDestRow = rSortParam.nDestRow;
f085be
-            aOldSortParam.nDestTab = rSortParam.nDestTab;
f085be
-            pDBData->SetSortParam( aOldSortParam );                 // dann nur DestPos merken
f085be
-        }
f085be
-    }
f085be
-    if (bSave)                                              // Parameter merken
f085be
+    if (bRecord)
f085be
     {
f085be
-        pDBData->SetSortParam( rSortParam );
f085be
-        pDBData->SetHeader( rSortParam.bHasHeader );        //! ???
f085be
-        pDBData->SetByRow( rSortParam.bByRow );             //! ???
f085be
+        // Set up an undo object.
f085be
+        sc::UndoSort* pUndoAction = new sc::UndoSort(&rDocShell, aUndoParam);
f085be
+        rDocShell.GetUndoManager()->AddUndoAction(pUndoAction);
f085be
     }
f085be
 
f085be
-    if (bCopy)                                          // neuen DB-Bereich merken
f085be
-    {
f085be
-        //  Tabelle umschalten von aussen (View)
f085be
-        //! SetCursor ??!?!
f085be
-
f085be
-        ScRange aDestPos( aLocalParam.nCol1, aLocalParam.nRow1, nTab,
f085be
-                            aLocalParam.nCol2, aLocalParam.nRow2, nTab );
f085be
-        ScDBData* pNewData;
f085be
-        if (pDestData)
f085be
-            pNewData = pDestData;               // Bereich vorhanden -> anpassen
f085be
-        else                                    // Bereich ab Cursor/Markierung wird angelegt
f085be
-            pNewData = rDocShell.GetDBData(aDestPos, SC_DB_MAKE, SC_DBSEL_FORCE_MARK );
f085be
-        if (pNewData)
f085be
-        {
f085be
-            pNewData->SetArea( nTab,
f085be
-                                aLocalParam.nCol1,aLocalParam.nRow1,
f085be
-                                aLocalParam.nCol2,aLocalParam.nRow2 );
f085be
-            pNewData->SetSortParam( aLocalParam );
f085be
-            pNewData->SetHeader( aLocalParam.bHasHeader );      //! ???
f085be
-            pNewData->SetByRow( aLocalParam.bByRow );
f085be
-        }
f085be
-        else
f085be
-        {
f085be
-            OSL_FAIL("Zielbereich nicht da");
f085be
-        }
f085be
-    }
f085be
+    pDBData->SetSortParam(rSortParam);
f085be
 
f085be
     ScRange aDirtyRange(
f085be
         aLocalParam.nCol1, nStartRow, nTab,
f085be
@@ -661,23 +547,12 @@ sal_Bool ScDBDocFunc::Sort( SCTAB nTab, const ScSortParam& rSortParam,
f085be
             nStartX = 0;
f085be
             nEndX = MAXCOL;
f085be
         }
f085be
-        if (pDestData)
f085be
-        {
f085be
-            if ( nEndX < aOldDest.aEnd.Col() )
f085be
-                nEndX = aOldDest.aEnd.Col();
f085be
-            if ( nEndY < aOldDest.aEnd.Row() )
f085be
-                nEndY = aOldDest.aEnd.Row();
f085be
-        }
f085be
         rDocShell.PostPaint(ScRange(nStartX, nStartY, nTab, nEndX, nEndY, nTab), nPaint);
f085be
     }
f085be
 
f085be
     if (!bUniformRowHeight)
f085be
         rDocShell.AdjustRowHeight(nStartRow, aLocalParam.nRow2, nTab);
f085be
 
f085be
-    // #i59745# set collected drawing undo actions at sorting undo action
f085be
-    if( pUndoAction && pDrawLayer )
f085be
-        pUndoAction->SetDrawUndoAction( pDrawLayer->GetCalcUndo() );
f085be
-
f085be
     aModificator.SetDocumentModified();
f085be
 
f085be
     return sal_True;
f085be
diff --git a/sc/source/ui/undo/undobase.cxx b/sc/source/ui/undo/undobase.cxx
f085be
index 609b6fe..6342910 100644
f085be
--- a/sc/source/ui/undo/undobase.cxx
f085be
+++ b/sc/source/ui/undo/undobase.cxx
f085be
@@ -31,6 +31,7 @@
f085be
 #include "subtotalparam.hxx"
f085be
 #include "globstr.hrc"
f085be
 #include <column.hxx>
f085be
+#include <sortparam.hxx>
f085be
 
f085be
 TYPEINIT1(ScSimpleUndo,     SfxUndoAction);
f085be
 TYPEINIT1(ScBlockUndo,      ScSimpleUndo);
f085be
diff --git a/sc/source/ui/undo/undosort.cxx b/sc/source/ui/undo/undosort.cxx
f085be
new file mode 100644
f085be
index 0000000..4ff0960
f085be
--- /dev/null
f085be
+++ b/sc/source/ui/undo/undosort.cxx
f085be
@@ -0,0 +1,55 @@
f085be
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
f085be
+/*
f085be
+ * This file is part of the LibreOffice project.
f085be
+ *
f085be
+ * This Source Code Form is subject to the terms of the Mozilla Public
f085be
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
f085be
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
f085be
+ */
f085be
+
f085be
+#include <undosort.hxx>
f085be
+#include <globstr.hrc>
f085be
+#include <global.hxx>
f085be
+#include <undoutil.hxx>
f085be
+
f085be
+namespace sc {
f085be
+
f085be
+UndoSort::UndoSort( ScDocShell* pDocSh, const ReorderParam& rParam ) :
f085be
+    ScSimpleUndo(pDocSh), maParam(rParam) {}
f085be
+
f085be
+OUString UndoSort::GetComment() const
f085be
+{
f085be
+    return ScGlobal::GetRscString(STR_UNDO_SORT);
f085be
+}
f085be
+
f085be
+void UndoSort::Undo()
f085be
+{
f085be
+    BeginUndo();
f085be
+    Execute(true);
f085be
+    EndUndo();
f085be
+}
f085be
+
f085be
+void UndoSort::Redo()
f085be
+{
f085be
+    BeginRedo();
f085be
+    Execute(false);
f085be
+    EndRedo();
f085be
+}
f085be
+
f085be
+void UndoSort::Execute( bool bUndo )
f085be
+{
f085be
+    ScDocument& rDoc = *pDocShell->GetDocument();
f085be
+    sc::ReorderParam aParam = maParam;
f085be
+    if (bUndo)
f085be
+        aParam.reverse();
f085be
+    rDoc.Reorder(aParam, NULL);
f085be
+
f085be
+    ScUndoUtil::MarkSimpleBlock(pDocShell, maParam.maSortRange);
f085be
+
f085be
+    pDocShell->PostPaint(maParam.maSortRange, PAINT_GRID);
f085be
+    pDocShell->PostDataChanged();
f085be
+}
f085be
+
f085be
+}
f085be
+
f085be
+/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
f085be
diff --git a/sc/source/ui/unoobj/cellsuno.cxx b/sc/source/ui/unoobj/cellsuno.cxx
f085be
index a9cf2eb..c1963e0 100644
f085be
--- a/sc/source/ui/unoobj/cellsuno.cxx
f085be
+++ b/sc/source/ui/unoobj/cellsuno.cxx
f085be
@@ -124,6 +124,7 @@
f085be
 #include "tokenarray.hxx"
f085be
 #include "stylehelper.hxx"
f085be
 #include "dputil.hxx"
f085be
+#include <sortparam.hxx>
f085be
 
f085be
 #include <list>
f085be
 #include <boost/scoped_ptr.hpp>
f085be
diff --git a/sc/source/ui/unoobj/datauno.cxx b/sc/source/ui/unoobj/datauno.cxx
f085be
index 8886776..26838e1 100644
f085be
--- a/sc/source/ui/unoobj/datauno.cxx
f085be
+++ b/sc/source/ui/unoobj/datauno.cxx
f085be
@@ -51,6 +51,7 @@
f085be
 #include "dpshttab.hxx"
f085be
 #include "queryentry.hxx"
f085be
 #include "dputil.hxx"
f085be
+#include <sortparam.hxx>
f085be
 
f085be
 #include <comphelper/extract.hxx>
f085be
 #include <comphelper/servicehelper.hxx>
f085be
diff --git a/svl/source/notify/listener.cxx b/svl/source/notify/listener.cxx
f085be
index 66207bf..f905090 100644
f085be
--- a/svl/source/notify/listener.cxx
f085be
+++ b/svl/source/notify/listener.cxx
f085be
@@ -21,6 +21,14 @@
f085be
 #include <svl/broadcast.hxx>
f085be
 #include <tools/debug.hxx>
f085be
 
f085be
+SvtListener::QueryBase::QueryBase( sal_uInt16 nId ) : mnId(nId) {}
f085be
+SvtListener::QueryBase::~QueryBase() {}
f085be
+
f085be
+sal_uInt16 SvtListener::QueryBase::getId() const
f085be
+{
f085be
+    return mnId;
f085be
+}
f085be
+
f085be
 SvtListener::SvtListener() {}
f085be
 
f085be
 SvtListener::SvtListener( const SvtListener &r ) :
f085be
@@ -75,12 +83,26 @@ bool SvtListener::IsListening( SvtBroadcaster& rBroadcaster ) const
f085be
     return maBroadcasters.count(&rBroadcaster) > 0;
f085be
 }
f085be
 
f085be
+void SvtListener::CopyAllBroadcasters( const SvtListener& r )
f085be
+{
f085be
+    BroadcastersType aCopy(r.maBroadcasters);
f085be
+    maBroadcasters.swap(aCopy);
f085be
+    BroadcastersType::iterator it = maBroadcasters.begin(), itEnd = maBroadcasters.end();
f085be
+    for (; it != itEnd; ++it)
f085be
+    {
f085be
+        SvtBroadcaster* p = *it;
f085be
+        p->Add(this);
f085be
+    }
f085be
+}
f085be
+
f085be
 bool SvtListener::HasBroadcaster() const
f085be
 {
f085be
     return !maBroadcasters.empty();
f085be
 }
f085be
 
f085be
-void SvtListener::Notify( const SfxHint& ) {}
f085be
+void SvtListener::Notify( const SfxHint& /*rHint*/ ) {}
f085be
+
f085be
+void SvtListener::Query( QueryBase& /*rQuery*/ ) const {}
f085be
 
f085be
 
f085be
 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
f085be
-- 
f085be
1.9.3
f085be