2 * \file MathMacroTemplate.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
14 #include "MathMacroTemplate.h"
16 #include "DocIterator.h"
17 #include "LaTeXFeatures.h"
18 #include "InsetMathBrace.h"
19 #include "InsetMathChar.h"
20 #include "InsetMathSqrt.h"
21 #include "MathMacro.h"
22 #include "MathMacroArgument.h"
23 #include "MathStream.h"
24 #include "MathParser.h"
25 #include "MathSupport.h"
26 #include "MathMacroArgument.h"
29 #include "BufferView.h"
32 #include "DispatchResult.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
38 #include "frontends/Painter.h"
40 #include "support/lassert.h"
41 #include "support/convert.h"
42 #include "support/debug.h"
43 #include "support/gettext.h"
44 #include "support/docstream.h"
45 #include "support/lstrings.h"
53 using support::bformat;
55 //////////////////////////////////////////////////////////////////////
57 class InsetLabelBox : public InsetMathNest {
60 InsetLabelBox(MathAtom const & atom, docstring label,
61 MathMacroTemplate const & parent, bool frame = false);
62 InsetLabelBox(docstring label, MathMacroTemplate const & parent,
65 void metrics(MetricsInfo & mi, Dimension & dim) const;
67 void draw(PainterInfo &, int x, int y) const;
71 MathMacroTemplate const & parent_;
73 Inset * clone() const;
75 docstring const label_;
81 InsetLabelBox::InsetLabelBox(MathAtom const & atom, docstring label,
82 MathMacroTemplate const & parent, bool frame)
83 : InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
85 cell(0).insert(0, atom);
89 InsetLabelBox::InsetLabelBox(docstring label,
90 MathMacroTemplate const & parent, bool frame)
91 : InsetMathNest(1), parent_(parent), label_(label), frame_(frame)
96 Inset * InsetLabelBox::clone() const
98 return new InsetLabelBox(*this);
102 void InsetLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
105 cell(0).metrics(mi, dim);
114 // adjust to common height in main metrics phase
115 if (!parent_.premetrics()) {
116 dim.asc = max(dim.asc, parent_.commonLabelBoxAscent());
117 dim.des = max(dim.des, parent_.commonLabelBoxDescent());
121 if (parent_.editing(mi.base.bv) && label_.length() > 0) {
123 FontInfo font = sane_font;
124 font.setSize(FONT_SIZE_TINY);
125 font.setColor(Color_mathmacrolabel);
127 // make space for label and box
128 int lwid = mathed_string_width(font, label_);
131 math_font_max_dim(font, maxasc, maxdes);
133 dim.wid = max(dim.wid, lwid + 2);
135 // space for the label
136 if (!parent_.premetrics())
137 dim.des += maxasc + maxdes + 1;
142 void InsetLabelBox::draw(PainterInfo & pi, int x, int y) const
144 Dimension const dim = dimension(*pi.base.bv);
145 Dimension const cdim = cell(0).dimension(*pi.base.bv);
148 cell(0).draw(pi, x + (dim.wid - cdim.wid) / 2, y);
151 if (parent_.editing(pi.base.bv) && label_.length() > 0) {
153 FontInfo font = sane_font;
154 font.setSize(FONT_SIZE_TINY);
155 font.setColor(Color_mathmacrolabel);
157 // make space for label and box
158 int lwid = mathed_string_width(font, label_);
161 math_font_max_dim(font, maxasc, maxdes);
164 pi.pain.text(x + (dim.wid - lwid) / 2, y + dim.des - maxdes, label_, font);
166 pi.pain.text(x, y + dim.des - maxdes, label_, font);
170 int boxHeight = parent_.commonLabelBoxAscent() + parent_.commonLabelBoxDescent();
172 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
173 dim.wid - 2, boxHeight - 2,
179 //////////////////////////////////////////////////////////////////////
181 class DisplayLabelBox : public InsetLabelBox {
184 DisplayLabelBox(MathAtom const & atom, docstring label,
185 MathMacroTemplate const & parent);
188 void metrics(MetricsInfo & mi, Dimension & dim) const;
190 void draw(PainterInfo &, int x, int y) const;
194 Inset * clone() const;
198 DisplayLabelBox::DisplayLabelBox(MathAtom const & atom,
200 MathMacroTemplate const & parent)
201 : InsetLabelBox(atom, label, parent, true)
207 Inset * DisplayLabelBox::clone() const
209 return new DisplayLabelBox(*this);
213 void DisplayLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
215 InsetLabelBox::metrics(mi, dim);
216 if (!parent_.editing(mi.base.bv)
217 && parent_.cell(parent_.displayIdx()).empty()) {
225 void DisplayLabelBox::draw(PainterInfo & pi, int x, int y) const
227 if (parent_.editing(pi.base.bv)
228 || !parent_.cell(parent_.displayIdx()).empty()) {
229 InsetLabelBox::draw(pi, x, y);
231 bool enabled = pi.pain.isDrawingEnabled();
232 pi.pain.setDrawingEnabled(false);
233 InsetLabelBox::draw(pi, x, y);
234 pi.pain.setDrawingEnabled(enabled);
239 //////////////////////////////////////////////////////////////////////
241 class InsetMathWrapper : public InsetMath {
244 InsetMathWrapper(MathData const * value) : value_(value) {}
246 void metrics(MetricsInfo & mi, Dimension & dim) const;
248 void draw(PainterInfo &, int x, int y) const;
252 Inset * clone() const;
254 MathData const * value_;
258 Inset * InsetMathWrapper::clone() const
260 return new InsetMathWrapper(*this);
264 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
266 value_->metrics(mi, dim);
267 //metricsMarkers2(dim);
271 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
273 value_->draw(pi, x, y);
274 //drawMarkers(pi, x, y);
278 ///////////////////////////////////////////////////////////////////////
279 class InsetColoredCell : public InsetMathNest {
282 InsetColoredCell(ColorCode min, ColorCode max);
284 InsetColoredCell(ColorCode min, ColorCode max, MathAtom const & atom);
286 void draw(PainterInfo &, int x, int y) const;
288 void metrics(MetricsInfo & mi, Dimension & dim) const;
292 Inset * clone() const;
300 InsetColoredCell::InsetColoredCell(ColorCode min, ColorCode max)
301 : InsetMathNest(1), min_(min), max_(max)
306 InsetColoredCell::InsetColoredCell(ColorCode min, ColorCode max, MathAtom const & atom)
307 : InsetMathNest(1), min_(min), max_(max)
309 cell(0).insert(0, atom);
313 Inset * InsetColoredCell::clone() const
315 return new InsetColoredCell(*this);
319 void InsetColoredCell::metrics(MetricsInfo & mi, Dimension & dim) const
321 cell(0).metrics(mi, dim);
325 void InsetColoredCell::draw(PainterInfo & pi, int x, int y) const
327 pi.pain.enterMonochromeMode(min_, max_);
328 cell(0).draw(pi, x, y);
329 pi.pain.leaveMonochromeMode();
333 ///////////////////////////////////////////////////////////////////////
335 class InsetNameWrapper : public InsetMathWrapper {
338 InsetNameWrapper(MathData const * value, MathMacroTemplate const & parent);
340 void metrics(MetricsInfo & mi, Dimension & dim) const;
342 void draw(PainterInfo &, int x, int y) const;
346 MathMacroTemplate const & parent_;
348 Inset * clone() const;
352 InsetNameWrapper::InsetNameWrapper(MathData const * value,
353 MathMacroTemplate const & parent)
354 : InsetMathWrapper(value), parent_(parent)
359 Inset * InsetNameWrapper::clone() const
361 return new InsetNameWrapper(*this);
365 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
367 InsetMathWrapper::metrics(mi, dim);
368 dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
372 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
375 PainterInfo namepi = pi;
376 if (parent_.validMacro())
377 namepi.base.font.setColor(Color_latex);
379 namepi.base.font.setColor(Color_error);
382 pi.pain.text(x, y, from_ascii("\\"), namepi.base.font);
383 x += mathed_string_width(namepi.base.font, from_ascii("\\"));
386 InsetMathWrapper::draw(namepi, x, y);
390 ///////////////////////////////////////////////////////////////////////
393 MathMacroTemplate::MathMacroTemplate(Buffer * buf)
394 : InsetMathNest(3), numargs_(0), argsInLook_(0), optionals_(0),
395 type_(MacroTypeNewcommand), lookOutdated_(true)
402 MathMacroTemplate::MathMacroTemplate(docstring const & name, int numargs,
403 int optionals, MacroType type, Buffer * buf,
404 vector<MathData> const & optionalValues,
405 MathData const & def, MathData const & display)
406 : InsetMathNest(optionals + 3), numargs_(numargs), argsInLook_(numargs),
407 optionals_(optionals), optionalValues_(optionalValues),
408 type_(type), lookOutdated_(true)
414 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
417 asArray(name, cell(0));
418 optionalValues_.resize(9);
419 for (int i = 0; i < optionals_; ++i)
420 cell(optIdx(i)) = optionalValues_[i];
421 cell(defIdx()) = def;
422 cell(displayIdx()) = display;
428 MathMacroTemplate::MathMacroTemplate(docstring const & str, Buffer * buf)
429 : InsetMathNest(3), numargs_(0), optionals_(0),
430 type_(MacroTypeNewcommand), lookOutdated_(true)
436 mathed_parse_cell(ar, str, Parse::NORMAL, buf);
437 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
438 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
439 asArray(from_ascii("invalidmacro"), cell(0));
440 // FIXME: The macro template does not make sense after this.
441 // The whole parsing should not be in a constructor which
442 // has no chance to report failure.
445 operator=( *(ar[0]->asMacroTemplate()) );
451 Inset * MathMacroTemplate::clone() const
453 MathMacroTemplate * inset = new MathMacroTemplate(*this);
454 // the parent pointers of the proxy insets above will point to
455 // to the old template. Hence, the look must be updated.
461 docstring MathMacroTemplate::name() const
463 return asString(cell(0));
467 void MathMacroTemplate::updateToContext(MacroContext const & mc) const
469 redefinition_ = mc.get(name()) != 0;
473 void MathMacroTemplate::updateLook() const
475 lookOutdated_ = true;
479 void MathMacroTemplate::createLook(int args) const
485 look_.push_back(MathAtom(new InsetLabelBox(_("Name"), *this, false)));
486 MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
487 nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
491 if (optionals_ > 0) {
492 look_.push_back(MathAtom(new InsetLabelBox(_("optional"), *this, false)));
494 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
495 for (; i < optionals_; ++i) {
496 // color it light grey, if it is to be removed when the cursor leaves
497 if (i == argsInLook_) {
498 optData->push_back(MathAtom(
499 new InsetColoredCell(Color_mathbg, Color_mathmacrooldarg)));
500 optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
503 optData->push_back(MathAtom(new InsetMathChar('[')));
504 optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
505 optData->push_back(MathAtom(new InsetMathChar(']')));
510 for (; i < numargs_; ++i) {
512 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
513 if (i >= argsInLook_) {
514 look_.push_back(MathAtom(new InsetColoredCell(
515 Color_mathbg, Color_mathmacrooldarg,
516 MathAtom(new InsetMathBrace(arg)))));
518 look_.push_back(MathAtom(new InsetMathBrace(arg)));
520 for (; i < argsInLook_; ++i) {
522 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
523 look_.push_back(MathAtom(new InsetColoredCell(
524 Color_mathbg, Color_mathmacronewarg,
525 MathAtom(new InsetMathBrace(arg)))));
529 look_.push_back(MathAtom(new InsetMathChar(':')));
530 look_.push_back(MathAtom(new InsetMathChar('=')));
533 look_.push_back(MathAtom(
534 new InsetLabelBox(MathAtom(
535 new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this, true)));
538 look_.push_back(MathAtom(
539 new DisplayLabelBox(MathAtom(
540 new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
544 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
546 FontSetChanger dummy1(mi.base, from_ascii("mathnormal"));
547 StyleChanger dummy2(mi.base, LM_ST_TEXT);
550 MacroData const * macro = 0;
552 macro = mi.macrocontext.get(name());
554 // updateToContext() - avoids another lookup
555 redefinition_ = macro != 0;
559 int argsInDef = maxArgumentInDefinition();
560 if (lookOutdated_ || argsInDef != argsInLook_) {
561 lookOutdated_ = false;
562 createLook(argsInDef);
565 /// metrics for inset contents
569 // first phase, premetric:
571 look_.metrics(mi, dim);
572 labelBoxAscent_ = dim.asc;
573 labelBoxDescent_ = dim.des;
575 // second phase, main metric:
577 look_.metrics(mi, dim);
586 setDimCache(mi, dim);
590 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
592 FontSetChanger dummy1(pi.base, from_ascii("mathnormal"));
593 StyleChanger dummy2(pi.base, LM_ST_TEXT);
595 setPosCache(pi, x, y);
596 Dimension const dim = dimension(*pi.base.bv);
599 int const a = y - dim.asc + 1;
600 int const w = dim.wid - 2;
601 int const h = dim.height() - 2;
602 pi.pain.rectangle(x, a, w, h, Color_mathframe);
604 // just to be sure: set some dummy values for coord cache
605 for (idx_type i = 0; i < nargs(); ++i)
606 cell(i).setXY(*pi.base.bv, x, y);
609 look_.draw(pi, x + 3, y);
613 void MathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
616 cur.updateFlags(Update::SinglePar);
617 InsetMathNest::edit(cur, front, entry_from);
621 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
623 // find this in cursor old
624 Cursor insetCur = old;
625 int scriptSlice = insetCur.find(this);
626 LASSERT(scriptSlice != -1, /**/);
627 insetCur.cutOff(scriptSlice);
629 commitEditChanges(insetCur);
631 cur.updateFlags(Update::Force);
632 return InsetMathNest::notifyCursorLeaves(old, cur);
636 void MathMacroTemplate::removeArguments(Cursor & cur, int from, int to)
638 for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
641 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
643 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
644 int n = arg->number() - 1;
645 if (from <= n && n <= to) {
646 int cellSlice = cur.find(it.cell());
647 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
648 --cur[cellSlice].pos();
650 it.cell().erase(it.pos());
658 void MathMacroTemplate::shiftArguments(size_t from, int by)
660 for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
663 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
665 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
666 if (arg->number() >= int(from) + 1)
667 arg->setNumber(arg->number() + by);
674 int MathMacroTemplate::maxArgumentInDefinition() const
676 // We don't have a buffer when pasting from the clipboard (bug 6014).
677 Buffer const * macro_buffer = this->isBufferValid() ? &buffer() : 0;
679 DocIterator it = doc_iterator_begin(macro_buffer, this);
681 for (; it; it.forwardChar()) {
684 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
686 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
687 maxArg = std::max(int(arg->number()), maxArg);
693 void MathMacroTemplate::insertMissingArguments(int maxArg)
695 bool found[9] = { false, false, false, false, false, false, false, false, false };
696 idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
698 // search for #n macros arguments
699 DocIterator it = doc_iterator_begin(&buffer(), this);
701 for (; it && it[0].idx() == idx; it.forwardChar()) {
704 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
706 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
707 found[arg->number() - 1] = true;
711 for (int i = 0; i < maxArg; ++i) {
715 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
720 void MathMacroTemplate::changeArity(Cursor & cur, int newNumArg)
722 // remove parameter which do not appear anymore in the definition
723 for (int i = numargs_; i > newNumArg; --i)
724 removeParameter(cur, numargs_ - 1, false);
726 // add missing parameter
727 for (int i = numargs_; i < newNumArg; ++i)
728 insertParameter(cur, numargs_, false, false);
732 void MathMacroTemplate::commitEditChanges(Cursor & cur)
734 int argsInDef = maxArgumentInDefinition();
735 if (argsInDef != numargs_) {
736 cur.recordUndoFullDocument();
737 changeArity(cur, argsInDef);
739 insertMissingArguments(argsInDef);
743 // FIXME: factorize those functions here with a functional style, maybe using Boost's function
746 void fixMacroInstancesAddRemove(Cursor const & from, docstring const & name, int n, bool insert) {
749 for (; dit; dit.forwardPos()) {
750 // only until a macro is redefined
751 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
752 MathMacroTemplate const & macroTemplate
753 = static_cast<MathMacroTemplate const &>(dit.inset());
754 if (macroTemplate.name() == name)
758 // in front of macro instance?
759 Inset * inset = dit.nextInset();
762 InsetMath * insetMath = inset->asInsetMath();
766 MathMacro * macro = insetMath->asMacro();
767 if (macro && macro->name() == name && macro->folded()) {
768 // found macro instance
770 macro->insertArgument(n);
772 macro->removeArgument(n);
778 void fixMacroInstancesOptional(Cursor const & from, docstring const & name, int optionals) {
781 for (; dit; dit.forwardPos()) {
782 // only until a macro is redefined
783 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
784 MathMacroTemplate const & macroTemplate
785 = static_cast<MathMacroTemplate const &>(dit.inset());
786 if (macroTemplate.name() == name)
790 // in front of macro instance?
791 Inset * inset = dit.nextInset();
794 InsetMath * insetMath = inset->asInsetMath();
797 MathMacro * macro = insetMath->asMacro();
798 if (macro && macro->name() == name && macro->folded()) {
799 // found macro instance
800 macro->setOptionals(optionals);
807 void fixMacroInstancesFunctional(Cursor const & from,
808 docstring const & name, F & fix) {
811 for (; dit; dit.forwardPos()) {
812 // only until a macro is redefined
813 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
814 MathMacroTemplate const & macroTemplate
815 = static_cast<MathMacroTemplate const &>(dit.inset());
816 if (macroTemplate.name() == name)
820 // in front of macro instance?
821 Inset * inset = dit.nextInset();
824 InsetMath * insetMath = inset->asInsetMath();
827 MathMacro * macro = insetMath->asMacro();
828 if (macro && macro->name() == name && macro->folded())
834 void MathMacroTemplate::insertParameter(Cursor & cur, int pos, bool greedy, bool addarg)
836 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
841 shiftArguments(pos, 1);
843 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
844 if (!cell(displayIdx()).empty())
845 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
850 dit.leaveInset(*this);
851 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
852 dit.top().forwardPos();
854 // fix macro instances
855 fixMacroInstancesAddRemove(dit, name(), pos, true);
863 void MathMacroTemplate::removeParameter(Cursor & cur, int pos, bool greedy)
865 if (pos < numargs_ && pos >= 0) {
867 removeArguments(cur, pos, pos);
868 shiftArguments(pos + 1, -1);
870 // removed optional parameter?
871 if (pos < optionals_) {
873 optionalValues_[pos] = cell(optIdx(pos));
874 cells_.erase(cells_.begin() + optIdx(pos));
877 int macroSlice = cur.find(this);
878 if (macroSlice != -1) {
879 if (cur[macroSlice].idx() == optIdx(pos)) {
880 cur.cutOff(macroSlice);
881 cur[macroSlice].idx() = 1;
882 cur[macroSlice].pos() = 0;
883 } else if (cur[macroSlice].idx() > optIdx(pos))
884 --cur[macroSlice].idx();
889 // fix macro instances
890 //boost::function<void(MathMacro *)> fix = _1->insertArgument(n);
891 //fixMacroInstancesFunctional(dit, name(), fix);
893 dit.leaveInset(*this);
894 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
895 dit.top().forwardPos();
896 fixMacroInstancesAddRemove(dit, name(), pos, false);
904 void MathMacroTemplate::makeOptional(Cursor & cur) {
905 if (numargs_ > 0 && optionals_ < numargs_) {
907 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
909 int macroSlice = cur.find(this);
910 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
911 ++cur[macroSlice].idx();
913 // fix macro instances
915 dit.leaveInset(*this);
916 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
917 dit.top().forwardPos();
918 fixMacroInstancesOptional(dit, name(), optionals_);
925 void MathMacroTemplate::makeNonOptional(Cursor & cur) {
926 if (numargs_ > 0 && optionals_ > 0) {
929 // store default value for later if the user changes his mind
930 optionalValues_[optionals_] = cell(optIdx(optionals_));
931 cells_.erase(cells_.begin() + optIdx(optionals_));
934 int macroSlice = cur.find(this);
935 if (macroSlice != -1) {
936 if (cur[macroSlice].idx() > optIdx(optionals_))
937 --cur[macroSlice].idx();
938 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
939 cur.cutOff(macroSlice);
940 cur[macroSlice].idx() = optIdx(optionals_);
941 cur[macroSlice].pos() = 0;
945 // fix macro instances
947 dit.leaveInset(*this);
948 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
949 dit.top().forwardPos();
950 fixMacroInstancesOptional(dit, name(), optionals_);
957 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
959 string const arg = to_utf8(cmd.argument());
960 switch (cmd.action) {
962 case LFUN_MATH_MACRO_ADD_PARAM:
964 commitEditChanges(cur);
965 cur.recordUndoFullDocument();
966 size_t pos = numargs_;
968 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
969 insertParameter(cur, pos);
974 case LFUN_MATH_MACRO_REMOVE_PARAM:
976 commitEditChanges(cur);
977 cur.recordUndoFullDocument();
978 size_t pos = numargs_ - 1;
980 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
981 removeParameter(cur, pos);
985 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
987 commitEditChanges(cur);
988 cur.recordUndoFullDocument();
989 insertParameter(cur, numargs_, true);
993 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
995 commitEditChanges(cur);
996 cur.recordUndoFullDocument();
997 removeParameter(cur, numargs_ - 1, true);
1001 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1002 commitEditChanges(cur);
1003 cur.recordUndoFullDocument();
1007 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1008 commitEditChanges(cur);
1009 cur.recordUndoFullDocument();
1010 makeNonOptional(cur);
1013 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1015 commitEditChanges(cur);
1016 cur.recordUndoFullDocument();
1017 insertParameter(cur, optionals_);
1022 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1023 if (optionals_ > 0) {
1024 commitEditChanges(cur);
1025 cur.recordUndoFullDocument();
1026 removeParameter(cur, optionals_ - 1);
1029 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1030 if (numargs_ == optionals_) {
1031 commitEditChanges(cur);
1032 cur.recordUndoFullDocument();
1033 insertParameter(cur, 0, true);
1039 InsetMathNest::doDispatch(cur, cmd);
1045 bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
1046 FuncStatus & flag) const
1049 string const arg = to_utf8(cmd.argument());
1050 switch (cmd.action) {
1051 case LFUN_MATH_MACRO_ADD_PARAM: {
1052 int num = numargs_ + 1;
1053 if (arg.size() != 0)
1054 num = convert<int>(arg);
1055 bool on = (num >= optionals_
1056 && numargs_ < 9 && num <= numargs_ + 1);
1057 flag.setEnabled(on);
1061 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1062 flag.setEnabled(numargs_ < 9);
1065 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1067 if (arg.size() != 0)
1068 num = convert<int>(arg);
1069 flag.setEnabled(num >= 1 && num <= numargs_);
1073 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1074 flag.setEnabled(numargs_ > 0
1075 && optionals_ < numargs_
1076 && type_ != MacroTypeDef);
1079 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1080 flag.setEnabled(optionals_ > 0
1081 && type_ != MacroTypeDef);
1084 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1085 flag.setEnabled(numargs_ < 9);
1088 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1089 flag.setEnabled(optionals_ > 0);
1092 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1093 flag.setEnabled(numargs_ == 0
1094 && type_ != MacroTypeDef);
1097 case LFUN_IN_MATHMACROTEMPLATE:
1098 flag.setEnabled(true);
1109 void MathMacroTemplate::read(Lexer & lex)
1112 mathed_parse_cell(ar, lex.getStream(), Parse::NORMAL, &buffer());
1113 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1114 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1115 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1118 operator=( *(ar[0]->asMacroTemplate()) );
1124 void MathMacroTemplate::write(ostream & os) const
1126 odocstringstream oss;
1127 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1128 oss << "FormulaMacro\n";
1130 os << to_utf8(oss.str());
1134 void MathMacroTemplate::write(WriteStream & os) const
1140 void MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1143 if (optionals_ > 0) {
1144 // macros with optionals use the xargs package, e.g.:
1145 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1146 // \long is implicit by xargs
1147 if (redefinition_ && !overwriteRedefinition)
1148 os << "\\renewcommandx";
1150 os << "\\newcommandx";
1152 os << "\\" << name()
1153 << "[" << numargs_ << "]"
1154 << "[usedefault, addprefix=\\global";
1155 for (int i = 0; i < optionals_; ++i) {
1156 docstring optValue = asString(cell(optIdx(i)));
1157 if (optValue.find(']') != docstring::npos
1158 || optValue.find(',') != docstring::npos)
1159 os << ", " << i + 1 << "="
1160 << "{" << cell(optIdx(i)) << "}";
1162 os << ", " << i + 1 << "="
1167 // Macros without optionals use standard _global_ \def macros:
1168 // \global\def\long\foo#1#2{#1,#2}
1169 // We use the \long prefix as this is the equivalent to \newcommand.
1170 // We cannot use \newcommand directly because \global does not work with it.
1171 os << "\\global\\long\\def\\" << name();
1172 docstring param = from_ascii("#0");
1173 for (int i = 1; i <= numargs_; ++i) {
1179 // in LyX output we use some pseudo syntax which is implementation
1180 // independent, e.g.
1181 // \newcommand{\foo}[2][default]{#1,#2}
1182 if (redefinition_ && !overwriteRedefinition)
1183 os << "\\renewcommand";
1185 os << "\\newcommand";
1186 os << "{\\" << name() << '}';
1188 os << '[' << numargs_ << ']';
1190 for (int i = 0; i < optionals_; ++i) {
1191 docstring optValue = asString(cell(optIdx(i)));
1192 if (optValue.find(']') != docstring::npos)
1193 os << "[{" << cell(optIdx(i)) << "}]";
1195 os << "[" << cell(optIdx(i)) << "]";
1199 os << "{" << cell(defIdx()) << "}";
1202 // writing .tex. done.
1205 // writing .lyx, write special .tex export only if necessary
1206 if (!cell(displayIdx()).empty())
1207 os << "\n{" << cell(displayIdx()) << '}';
1212 int MathMacroTemplate::plaintext(odocstream & os,
1213 OutputParams const &) const
1215 static docstring const str = '[' + buffer().B_("math macro") + ']';
1222 bool MathMacroTemplate::validName() const
1224 docstring n = name();
1230 // converting back and force doesn't swallow anything?
1233 if (asString(ma) != n)
1236 // valid characters?
1237 for (size_t i = 0; i < n.size(); ++i) {
1238 if (!(n[i] >= 'a' && n[i] <= 'z')
1239 && !(n[i] >= 'A' && n[i] <= 'Z')
1248 bool MathMacroTemplate::validMacro() const
1254 bool MathMacroTemplate::fixNameAndCheckIfValid()
1256 // check all the characters/insets in the name cell
1258 MathData & data = cell(0);
1259 while (i < data.size()) {
1260 InsetMathChar const * cinset = data[i]->asCharInset();
1262 // valid character in [a-zA-Z]?
1263 char_type c = cinset->getChar();
1264 if ((c >= 'a' && c <= 'z')
1265 || (c >= 'A' && c <= 'Z')) {
1275 // now it should be valid if anything in the name survived
1276 return data.size() > 0;
1280 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1282 // we need global optional macro arguments. They are not available
1283 // with \def, and \newcommand does not support global macros. So we
1284 // are bound to xargs also for the single-optional-parameter case.
1286 features.require("xargs");
1289 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1291 defaults.resize(numargs_);
1292 for (int i = 0; i < optionals_; ++i)
1293 defaults[i] = asString(cell(optIdx(i)));
1297 docstring MathMacroTemplate::definition() const
1299 return asString(cell(defIdx()));
1303 docstring MathMacroTemplate::displayDefinition() const
1305 return asString(cell(displayIdx()));
1309 size_t MathMacroTemplate::numArgs() const
1315 size_t MathMacroTemplate::numOptionals() const
1321 void MathMacroTemplate::infoize(odocstream & os) const
1323 os << "Math Macro: \\" << name();
1327 docstring MathMacroTemplate::contextMenu(BufferView const &, int, int) const
1329 return from_ascii("context-math-macro-definition");