]> git.lyx.org Git - lyx.git/blobdiff - src/mathed/MathMacro.cpp
fix a crash when the inset containing the new word at cursor is deleted
[lyx.git] / src / mathed / MathMacro.cpp
index dd8d2814b8ecc35f69bc3a76d8da6d971545d0c1..d96dc31b449623fbe62f5cd3352523d6b25f860b 100644 (file)
@@ -4,7 +4,7 @@
  * Licence details can be found in the file COPYING.
  *
  * \author Alejandro Aguilar Sierra
- * \author André Pönitz
+ * \author André Pönitz
  * \author Stefan Schimanski
  *
  * Full author contact details are available in file CREDITS.
 #include <config.h>
 
 #include "MathMacro.h"
-#include "MathSupport.h"
+
+#include "InsetMathChar.h"
+#include "MathCompletionList.h"
 #include "MathExtern.h"
+#include "MathFactory.h"
 #include "MathStream.h"
+#include "MathSupport.h"
 
 #include "Buffer.h"
 #include "BufferView.h"
 #include "FuncStatus.h"
 #include "FuncRequest.h"
 #include "LaTeXFeatures.h"
-#include "LyXFunc.h"
+#include "LyX.h"
 #include "LyXRC.h"
-#include "Undo.h"
 
 #include "frontends/Painter.h"
 
 #include "support/debug.h"
+#include "support/lassert.h"
+#include "support/textutils.h"
 
 #include <ostream>
 #include <vector>
@@ -53,17 +58,23 @@ public:
                        asArray(def, def_);
        }
        ///
+       InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
+       ///
        void metrics(MetricsInfo & mi, Dimension & dim) const {
                mathMacro_.macro()->unlock();
-               if (!mathMacro_.editMetrics(mi.base.bv) 
+               mathMacro_.cell(idx_).metrics(mi, dim);
+
+               if (!mathMacro_.editMetrics(mi.base.bv)
                    && mathMacro_.cell(idx_).empty())
                        def_.metrics(mi, dim);
-               else {
-                       CoordCache & coords = mi.base.bv->coordCache();
-                       dim = coords.arrays().dim(&mathMacro_.cell(idx_));
-               }
+
                mathMacro_.macro()->lock();
        }
+       // FIXME Other external things need similar treatment.
+       ///
+       void mathmlize(MathStream & ms) const { ms << mathMacro_.cell(idx_); }
+       ///
+       void htmlize(HtmlStream & ms) const { ms << mathMacro_.cell(idx_); }
        ///
        void draw(PainterInfo & pi, int x, int y) const {
                if (mathMacro_.editMetrics(pi.base.bv)) {
@@ -111,10 +122,10 @@ private:
 };
 
 
-MathMacro::MathMacro(docstring const & name)
-       : InsetMathNest(0), name_(name), displayMode_(DISPLAY_INIT),
-               attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
-               macro_(0), needsUpdate_(false)
+MathMacro::MathMacro(Buffer * buf, docstring const & name)
+       : InsetMathNest(buf, 0), name_(name), displayMode_(DISPLAY_INIT),
+               expanded_(buf), attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
+               macroBackup_(buf), macro_(0), needsUpdate_(false), appetite_(9)
 {}
 
 
@@ -122,7 +133,7 @@ Inset * MathMacro::clone() const
 {
        MathMacro * copy = new MathMacro(*this);
        copy->needsUpdate_ = true;
-       copy->expanded_.cell(0).clear();
+       //copy->expanded_.cell(0).clear();
        return copy;
 }
 
@@ -131,8 +142,8 @@ docstring MathMacro::name() const
 {
        if (displayMode_ == DISPLAY_UNFOLDED)
                return asString(cell(0));
-       else
-               return name_;
+
+       return name_;
 }
 
 
@@ -153,9 +164,12 @@ bool MathMacro::editMode(BufferView const * bv) const {
                        // look if there is no other macro in edit mode above
                        ++i;
                        for (; i != cur.depth(); ++i) {
-                               MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
-                               if (macro && macro->displayMode() == DISPLAY_NORMAL)
-                                       return false;
+                               InsetMath * im = cur[i].asInsetMath();
+                               if (im) {
+                                       MathMacro const * macro = im->asMacro();
+                                       if (macro && macro->displayMode() == DISPLAY_NORMAL)
+                                               return false;
+                               }
                        }
 
                        // ok, none found, I am the highest one
@@ -192,7 +206,7 @@ void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
                   && editing_[mi.base.bv]) {
                // Macro will be edited in a old-style list mode here:
 
-               BOOST_ASSERT(macro_ != 0);
+               LASSERT(macro_ != 0, /**/);
                Dimension fontDim;
                FontInfo labelFont = sane_font;
                math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
@@ -229,15 +243,20 @@ void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
                dim.wid += 2;
                metricsMarkers2(dim);
        } else {
-               BOOST_ASSERT(macro_ != 0);
+               LASSERT(macro_ != 0, /**/);
 
-               // metrics are computed here for the cells,
-               // in the proxy we will then use the dim from the cache
-               InsetMathNest::metrics(mi);
-               
-               // calculate metrics finally
+               // calculate metrics, hoping that all cells are seen
                macro_->lock();
                expanded_.cell(0).metrics(mi, dim);
+
+               // otherwise do a manual metrics call
+               CoordCache & coords = mi.base.bv->coordCache();
+               for (idx_type i = 0; i < nargs(); ++i) {
+                       if (!coords.getArrays().has(&cell(i))) {
+                               Dimension tdim;
+                               cell(i).metrics(mi, tdim);
+                       }
+               }
                macro_->unlock();
 
                // calculate dimension with label while editing
@@ -272,7 +291,7 @@ int MathMacro::kerning(BufferView const * bv) const {
 void MathMacro::updateMacro(MacroContext const & mc) 
 {
        if (validName()) {
-               macro_ = mc.get(name());            
+               macro_ = mc.get(name());    
                if (macro_ && macroBackup_ != *macro_) {
                        macroBackup_ = *macro_;
                        needsUpdate_ = true;
@@ -283,7 +302,7 @@ void MathMacro::updateMacro(MacroContext const & mc)
 }
 
 
-void MathMacro::updateRepresentation(Cursor const * bvCur)
+void MathMacro::updateRepresentation()
 {
        // known macro?
        if (macro_ == 0)
@@ -292,35 +311,31 @@ void MathMacro::updateRepresentation(Cursor const * bvCur)
        // update requires
        requires_ = macro_->requires();
        
-       // non-normal mode? We are done!
-       if (displayMode_ != DISPLAY_NORMAL)
+       if (!needsUpdate_
+               // non-normal mode? We are done!
+               || (displayMode_ != DISPLAY_NORMAL))
                return;
 
-       // macro changed?
-       if (needsUpdate_) {
-               needsUpdate_ = false;
-               
-               // get default values of macro
-               vector<docstring> const & defaults = macro_->defaults();
-               
-               // create MathMacroArgumentValue objects pointing to the cells of the macro
-               vector<MathData> values(nargs());
-               for (size_t i = 0; i < nargs(); ++i) {
-                       ArgumentProxy * proxy;
-                       if (i < defaults.size()) 
-                               proxy = new ArgumentProxy(*this, i, defaults[i]);
-                       else
-                               proxy = new ArgumentProxy(*this, i);
-                       values[i].insert(0, MathAtom(proxy));
-               }
-               
-               // expanding macro with the values
-               macro_->expand(values, expanded_.cell(0));
-
-               // get definition for list edit mode
-               docstring const & display = macro_->display();
-               asArray(display.empty() ? macro_->definition() : display, definition_);
+       needsUpdate_ = false;
+       
+       // get default values of macro
+       vector<docstring> const & defaults = macro_->defaults();
+       
+       // create MathMacroArgumentValue objects pointing to the cells of the macro
+       vector<MathData> values(nargs());
+       for (size_t i = 0; i < nargs(); ++i) {
+               ArgumentProxy * proxy;
+               if (i < defaults.size()) 
+                       proxy = new ArgumentProxy(*this, i, defaults[i]);
+               else
+                       proxy = new ArgumentProxy(*this, i);
+               values[i].insert(0, MathAtom(proxy));
        }
+       // expanding macro with the values
+       macro_->expand(values, expanded_.cell(0));
+       // get definition for list edit mode
+       docstring const & display = macro_->display();
+       asArray(display.empty() ? macro_->definition() : display, definition_);
 }
 
 
@@ -333,23 +348,19 @@ void MathMacro::draw(PainterInfo & pi, int x, int y) const
        int expy = y;
 
        if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {         
-               PainterInfo pi2(pi.base.bv, pi.pain);
-               pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
-               //pi2.base.style = LM_ST_TEXT;
-               pi2.pain.text(x, y, from_ascii("\\") + name(), pi2.base.font);
+               FontSetChanger dummy(pi.base, "lyxtex");
+               pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
        } else if (displayMode_ == DISPLAY_UNFOLDED) {
-               PainterInfo pi2(pi.base.bv, pi.pain);
-               pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
-               //pi2.base.style = LM_ST_TEXT;
-               pi2.pain.text(x, y, from_ascii("\\"), pi2.base.font);
-               x += mathed_string_width(pi2.base.font, from_ascii("\\")) + 1;
-               cell(0).draw(pi2, x, y);
-               drawMarkers(pi2, expx, expy);
+               FontSetChanger dummy(pi.base, "lyxtex");
+               pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
+               x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
+               cell(0).draw(pi, x, y);
+               drawMarkers(pi, expx, expy);
        } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
                   && editing_[pi.base.bv]) {
                // Macro will be edited in a old-style list mode here:
                
-               CoordCache & coords = pi.base.bv->coordCache();
+               CoordCache const & coords = pi.base.bv->coordCache();
                FontInfo const & labelFont = sane_font;
                
                // markers and box needs two pixels
@@ -366,8 +377,7 @@ void MathMacro::draw(PainterInfo & pi, int x, int y) const
 
                // draw definition
                definition_.draw(pi, x, y);
-               Dimension defDim
-               = coords.arrays().dim(&definition_);
+               Dimension const & defDim = coords.getArrays().dim(&definition_);
                y += max(fontDim.des, defDim.des);
                                
                // draw parameters
@@ -377,8 +387,7 @@ void MathMacro::draw(PainterInfo & pi, int x, int y) const
                
                for (idx_type i = 0; i < nargs(); ++i) {
                        // position of label
-                       Dimension cdim
-                       = coords.arrays().dim(&cell(i));
+                       Dimension const & cdim = coords.getArrays().dim(&cell(i));
                        x = expx + 2;
                        y += max(fontDim.asc, cdim.asc) + 1;
                        
@@ -437,7 +446,7 @@ void MathMacro::draw(PainterInfo & pi, int x, int y) const
 
        // edit mode changed?
        if (editing_[pi.base.bv] != editMode(pi.base.bv))
-               pi.base.bv->cursor().updateFlags(Update::Force);
+               pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
 }
 
 
@@ -449,7 +458,7 @@ void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
 }
 
 
-void MathMacro::setDisplayMode(MathMacro::DisplayMode mode)
+void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
 {
        if (displayMode_ != mode) {             
                // transfer name if changing from or to DISPLAY_UNFOLDED
@@ -464,6 +473,12 @@ void MathMacro::setDisplayMode(MathMacro::DisplayMode mode)
                displayMode_ = mode;
                needsUpdate_ = true;
        }
+       
+       // the interactive init mode is non-greedy by default
+       if (appetite == -1)
+               appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
+       else
+               appetite_ = size_t(appetite);
 }
 
 
@@ -492,8 +507,9 @@ bool MathMacro::validName() const
 
        // valid characters?
        for (size_t i = 0; i<n.size(); ++i) {
-               if (!(n[i] >= 'a' && n[i] <= 'z') &&
-                               !(n[i] >= 'A' && n[i] <= 'Z')) 
+               if (!(n[i] >= 'a' && n[i] <= 'z')
+                   && !(n[i] >= 'A' && n[i] <= 'Z')
+                   && n[i] != '*') 
                        return false;
        }
 
@@ -506,14 +522,20 @@ void MathMacro::validate(LaTeXFeatures & features) const
        if (!requires_.empty())
                features.require(requires_);
 
-       if (name() == "binom" || name() == "mathcircumflex")
-               features.require(to_utf8(name()));
+       if (name() == "binom")
+               features.require("binom");
+       
+       // validate the cells and the definition
+       if (displayMode() == DISPLAY_NORMAL) {
+               definition_.validate(features);
+               InsetMathNest::validate(features);
+       }
 }
 
 
 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
 {
-       cur.updateFlags(Update::Force);
+       cur.screenUpdateFlags(Update::SinglePar);
        InsetMathNest::edit(cur, front, entry_from);
 }
 
@@ -522,7 +544,7 @@ Inset * MathMacro::editXY(Cursor & cur, int x, int y)
 {
        // We may have 0 arguments, but InsetMathNest requires at least one.
        if (nargs() > 0) {
-               cur.updateFlags(Update::Force);
+               cur.screenUpdateFlags(Update::SinglePar);
                return InsetMathNest::editXY(cur, x, y);                
        } else
                return this;
@@ -531,7 +553,7 @@ Inset * MathMacro::editXY(Cursor & cur, int x, int y)
 
 void MathMacro::removeArgument(Inset::pos_type pos) {
        if (displayMode_ == DISPLAY_NORMAL) {
-               BOOST_ASSERT(size_t(pos) < cells_.size());
+               LASSERT(size_t(pos) < cells_.size(), /**/);
                cells_.erase(cells_.begin() + pos);
                if (size_t(pos) < attachedArgsNum_)
                        --attachedArgsNum_;
@@ -546,7 +568,7 @@ void MathMacro::removeArgument(Inset::pos_type pos) {
 
 void MathMacro::insertArgument(Inset::pos_type pos) {
        if (displayMode_ == DISPLAY_NORMAL) {
-               BOOST_ASSERT(size_t(pos) <= cells_.size());
+               LASSERT(size_t(pos) <= cells_.size(), /**/);
                cells_.insert(cells_.begin() + pos, MathData());
                if (size_t(pos) < attachedArgsNum_)
                        ++attachedArgsNum_;
@@ -560,7 +582,7 @@ void MathMacro::insertArgument(Inset::pos_type pos) {
 
 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
 {
-       BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);   
+       LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);  
        args = cells_;
 
        // strip off empty cells, but not more than arity-attachedArgsNum_
@@ -581,7 +603,7 @@ void MathMacro::detachArguments(vector<MathData> & args, bool strip)
 
 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
 {
-       BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
+       LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
        cells_ = args;
        attachedArgsNum_ = args.size();
        cells_.resize(arity);
@@ -594,22 +616,40 @@ void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int
 
 bool MathMacro::idxFirst(Cursor & cur) const 
 {
-       cur.updateFlags(Update::Force);
+       cur.screenUpdateFlags(Update::SinglePar);
        return InsetMathNest::idxFirst(cur);
 }
 
 
 bool MathMacro::idxLast(Cursor & cur) const 
 {
-       cur.updateFlags(Update::Force);
+       cur.screenUpdateFlags(Update::SinglePar);
        return InsetMathNest::idxLast(cur);
 }
 
 
-bool MathMacro::notifyCursorLeaves(Cursor & cur)
-{
-       cur.updateFlags(Update::Force);
-       return InsetMathNest::notifyCursorLeaves(cur);
+bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
+{
+       if (displayMode_ == DISPLAY_UNFOLDED) {
+               docstring const & unfolded_name = name();
+               if (unfolded_name != name_) {
+                       // The macro name was changed
+                       Cursor inset_cursor = old;
+                       int macroSlice = inset_cursor.find(this);
+                       LASSERT(macroSlice != -1, /**/);
+                       inset_cursor.cutOff(macroSlice);
+                       inset_cursor.recordUndoInset();
+                       inset_cursor.pop();
+                       inset_cursor.cell().erase(inset_cursor.pos());
+                       inset_cursor.cell().insert(inset_cursor.pos(),
+                               createInsetMath(unfolded_name, cur.buffer()));
+                       cur.resetAnchor();
+                       cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
+                       return true;
+               }
+       }
+       cur.screenUpdateFlags(Update::Force);
+       return InsetMathNest::notifyCursorLeaves(old, cur);
 }
 
 
@@ -617,7 +657,7 @@ void MathMacro::fold(Cursor & cur)
 {
        if (!nextFoldMode_) {
                nextFoldMode_ = true;
-               cur.updateFlags(Update::Force);
+               cur.screenUpdateFlags(Update::SinglePar);
        }
 }
 
@@ -626,7 +666,7 @@ void MathMacro::unfold(Cursor & cur)
 {
        if (nextFoldMode_) {
                nextFoldMode_ = false;
-               cur.updateFlags(Update::Force);
+               cur.screenUpdateFlags(Update::SinglePar);
        }
 }
 
@@ -639,15 +679,18 @@ bool MathMacro::folded() const
 
 void MathMacro::write(WriteStream & os) const
 {
+       MathEnsurer ensurer(os, macro_ != 0, true);
+
        // non-normal mode
        if (displayMode_ != DISPLAY_NORMAL) {
-               os << "\\" << name() << " ";
-               os.pendingSpace(true);
+               os << "\\" << name();
+               if (name().size() != 1 || isAlphaASCII(name()[0]))
+                       os.pendingSpace(true);
                return;
        }
 
        // normal mode
-       BOOST_ASSERT(macro_);
+       LASSERT(macro_, /**/);
 
        // optional arguments make macros fragile
        if (optionals_ > 0 && os.fragile())
@@ -674,10 +717,11 @@ void MathMacro::write(WriteStream & os) const
        // skip the tailing empty optionals
        i = optionals_;
        
-       // Print remaining macros 
+       // Print remaining arguments
        for (; i < cells_.size(); ++i) {
                if (cell(i).size() == 1 
-                        && cell(i)[0].nucleus()->asCharInset()) {
+                       && cell(i)[0].nucleus()->asCharInset()
+                       && cell(i)[0].nucleus()->asCharInset()->getChar() < 0x80) {
                        if (first)
                                os << " ";
                        os << cell(i);
@@ -700,7 +744,13 @@ void MathMacro::maple(MapleStream & os) const
 
 void MathMacro::mathmlize(MathStream & os) const
 {
-       lyx::mathmlize(expanded_.cell(0), os);
+       os << expanded_.cell(0);
+}
+
+
+void MathMacro::htmlize(HtmlStream & os) const
+{
+       os << expanded_.cell(0);
 }
 
 
@@ -725,6 +775,9 @@ void MathMacro::infoize2(odocstream & os) const
 
 bool MathMacro::completionSupported(Cursor const & cur) const
 {
+       if (displayMode() != DISPLAY_UNFOLDED)
+               return InsetMathNest::completionSupported(cur);
+
        return lyxrc.completion_popup_math
                && displayMode() == DISPLAY_UNFOLDED
                && cur.bv().cursor().pos() == int(name().size());
@@ -733,6 +786,9 @@ bool MathMacro::completionSupported(Cursor const & cur) const
 
 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
 {
+       if (displayMode() != DISPLAY_UNFOLDED)
+               return InsetMathNest::inlineCompletionSupported(cur);
+
        return lyxrc.completion_inline_math
                && displayMode() == DISPLAY_UNFOLDED
                && cur.bv().cursor().pos() == int(name().size());
@@ -741,24 +797,37 @@ bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
 
 bool MathMacro::automaticInlineCompletion() const
 {
+       if (displayMode() != DISPLAY_UNFOLDED)
+               return InsetMathNest::automaticInlineCompletion();
+
        return lyxrc.completion_inline_math;
 }
 
 
 bool MathMacro::automaticPopupCompletion() const
 {
+       if (displayMode() != DISPLAY_UNFOLDED)
+               return InsetMathNest::automaticPopupCompletion();
+
        return lyxrc.completion_popup_math;
 }
 
 
-Inset::CompletionListPtr MathMacro::completionList(Cursor const & cur) const
+CompletionList const * 
+MathMacro::createCompletionList(Cursor const & cur) const
 {
-       return CompletionListPtr(new MathCompletionList(cur.bv().cursor()));
+       if (displayMode() != DISPLAY_UNFOLDED)
+               return InsetMathNest::createCompletionList(cur);
+
+       return new MathCompletionList(cur.bv().cursor());
 }
 
 
 docstring MathMacro::completionPrefix(Cursor const & cur) const
 {
+       if (displayMode() != DISPLAY_UNFOLDED)
+               return InsetMathNest::completionPrefix(cur);
+
        if (!completionSupported(cur))
                return docstring();
        
@@ -769,26 +838,23 @@ docstring MathMacro::completionPrefix(Cursor const & cur) const
 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
                                        bool finished)
 {
-       if (completionSupported(cur))
+       if (displayMode() != DISPLAY_UNFOLDED)
+               return InsetMathNest::insertCompletion(cur, s, finished);
+
+       if (!completionSupported(cur))
                return false;
 
        // append completion
        docstring newName = name() + s;
        asArray(newName, cell(0));
        cur.bv().cursor().pos() = name().size();
-       cur.updateFlags(Update::Force);
+       cur.screenUpdateFlags(Update::SinglePar);
        
        // finish macro
        if (finished) {
-#if 0
-               // FIXME: this creates duplicates in the completion popup
-               // which looks ugly. Moreover the changes the list lengths
-               // which seems to confuse the popup as well.
-               MathCompletionList::addToFavorites(inset->name());
-#endif
                cur.bv().cursor().pop();
                ++cur.bv().cursor().pos();
-               cur.updateFlags(Update::Force | Update::SinglePar);
+               cur.screenUpdateFlags(Update::SinglePar);
        }
        
        return true;
@@ -798,6 +864,9 @@ bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
        Dimension & dim) const
 {
+       if (displayMode() != DISPLAY_UNFOLDED)
+               InsetMathNest::completionPosAndDim(cur, x, y, dim);
+       
        // get inset dimensions
        dim = cur.bv().coordCache().insets().dim(this);
        // FIXME: these 3 are no accurate, but should depend on the font.