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 "InsetMathHull.h"
21 #include "InsetMathSqrt.h"
22 #include "MathMacro.h"
23 #include "MathMacroArgument.h"
24 #include "MathStream.h"
25 #include "MathParser.h"
26 #include "MathSupport.h"
27 #include "MathMacroArgument.h"
30 #include "BufferView.h"
33 #include "DispatchResult.h"
34 #include "FuncRequest.h"
35 #include "FuncStatus.h"
39 #include "frontends/Painter.h"
41 #include "insets/RenderPreview.h"
43 #include "support/lassert.h"
44 #include "support/convert.h"
45 #include "support/debug.h"
46 #include "support/gettext.h"
47 #include "support/docstream.h"
48 #include "support/lstrings.h"
57 using support::bformat;
59 //////////////////////////////////////////////////////////////////////
61 class InsetLabelBox : public InsetMathNest {
64 InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
65 MathMacroTemplate const & parent, bool frame = false);
66 InsetLabelBox(Buffer * buf, docstring label, MathMacroTemplate const & parent,
69 void metrics(MetricsInfo & mi, Dimension & dim) const;
71 void draw(PainterInfo &, int x, int y) const;
75 MathMacroTemplate const & parent_;
77 Inset * clone() const;
79 docstring const label_;
85 InsetLabelBox::InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
86 MathMacroTemplate const & parent, bool frame)
87 : InsetMathNest(buf, 1), parent_(parent), label_(label), frame_(frame)
89 cell(0).insert(0, atom);
93 InsetLabelBox::InsetLabelBox(Buffer * buf, docstring label,
94 MathMacroTemplate const & parent, bool frame)
95 : InsetMathNest(buf, 1), parent_(parent), label_(label), frame_(frame)
100 Inset * InsetLabelBox::clone() const
102 return new InsetLabelBox(*this);
106 void InsetLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
109 cell(0).metrics(mi, dim);
118 // adjust to common height in main metrics phase
119 if (!parent_.premetrics()) {
120 dim.asc = max(dim.asc, parent_.commonLabelBoxAscent());
121 dim.des = max(dim.des, parent_.commonLabelBoxDescent());
125 if (parent_.editing(mi.base.bv) && label_.length() > 0) {
127 FontInfo font = sane_font;
128 font.setSize(FONT_SIZE_TINY);
129 font.setColor(Color_mathmacrolabel);
131 // make space for label and box
132 int lwid = mathed_string_width(font, label_);
135 math_font_max_dim(font, maxasc, maxdes);
137 dim.wid = max(dim.wid, lwid + 2);
139 // space for the label
140 if (!parent_.premetrics())
141 dim.des += maxasc + maxdes + 1;
146 void InsetLabelBox::draw(PainterInfo & pi, int x, int y) const
148 Dimension const dim = dimension(*pi.base.bv);
149 Dimension const cdim = cell(0).dimension(*pi.base.bv);
152 cell(0).draw(pi, x + (dim.wid - cdim.wid) / 2, y);
155 if (parent_.editing(pi.base.bv) && label_.length() > 0) {
157 FontInfo font = sane_font;
158 font.setSize(FONT_SIZE_TINY);
159 font.setColor(Color_mathmacrolabel);
161 // make space for label and box
162 int lwid = mathed_string_width(font, label_);
165 math_font_max_dim(font, maxasc, maxdes);
168 pi.pain.text(x + (dim.wid - lwid) / 2, y + dim.des - maxdes, label_, font);
170 pi.pain.text(x, y + dim.des - maxdes, label_, font);
174 int boxHeight = parent_.commonLabelBoxAscent() + parent_.commonLabelBoxDescent();
176 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
177 dim.wid - 2, boxHeight - 2,
183 //////////////////////////////////////////////////////////////////////
185 class DisplayLabelBox : public InsetLabelBox {
188 DisplayLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
189 MathMacroTemplate const & parent);
192 void metrics(MetricsInfo & mi, Dimension & dim) const;
194 void draw(PainterInfo &, int x, int y) const;
198 Inset * clone() const;
202 DisplayLabelBox::DisplayLabelBox(Buffer * buf, MathAtom const & atom,
204 MathMacroTemplate const & parent)
205 : InsetLabelBox(buf, atom, label, parent, true)
211 Inset * DisplayLabelBox::clone() const
213 return new DisplayLabelBox(*this);
217 void DisplayLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
219 InsetLabelBox::metrics(mi, dim);
220 if (!parent_.editing(mi.base.bv)
221 && parent_.cell(parent_.displayIdx()).empty()) {
229 void DisplayLabelBox::draw(PainterInfo & pi, int x, int y) const
231 if (parent_.editing(pi.base.bv)
232 || !parent_.cell(parent_.displayIdx()).empty()) {
233 InsetLabelBox::draw(pi, x, y);
235 bool enabled = pi.pain.isDrawingEnabled();
236 pi.pain.setDrawingEnabled(false);
237 InsetLabelBox::draw(pi, x, y);
238 pi.pain.setDrawingEnabled(enabled);
243 //////////////////////////////////////////////////////////////////////
245 class InsetMathWrapper : public InsetMath {
248 InsetMathWrapper(MathData const * value) : value_(value) {}
250 void metrics(MetricsInfo & mi, Dimension & dim) const;
252 void draw(PainterInfo &, int x, int y) const;
256 Inset * clone() const;
258 MathData const * value_;
262 Inset * InsetMathWrapper::clone() const
264 return new InsetMathWrapper(*this);
268 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
270 value_->metrics(mi, dim);
271 //metricsMarkers2(dim);
275 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
277 value_->draw(pi, x, y);
278 //drawMarkers(pi, x, y);
282 ///////////////////////////////////////////////////////////////////////
283 class InsetColoredCell : public InsetMathNest {
286 InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max);
288 InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max, MathAtom const & atom);
290 void draw(PainterInfo &, int x, int y) const;
292 void metrics(MetricsInfo & mi, Dimension & dim) const;
296 Inset * clone() const;
304 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max)
305 : InsetMathNest(buf, 1), min_(min), max_(max)
310 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max, MathAtom const & atom)
311 : InsetMathNest(buf, 1), min_(min), max_(max)
313 cell(0).insert(0, atom);
317 Inset * InsetColoredCell::clone() const
319 return new InsetColoredCell(*this);
323 void InsetColoredCell::metrics(MetricsInfo & mi, Dimension & dim) const
325 cell(0).metrics(mi, dim);
329 void InsetColoredCell::draw(PainterInfo & pi, int x, int y) const
331 pi.pain.enterMonochromeMode(min_, max_);
332 cell(0).draw(pi, x, y);
333 pi.pain.leaveMonochromeMode();
337 ///////////////////////////////////////////////////////////////////////
339 class InsetNameWrapper : public InsetMathWrapper {
342 InsetNameWrapper(MathData const * value, MathMacroTemplate const & parent);
344 void metrics(MetricsInfo & mi, Dimension & dim) const;
346 void draw(PainterInfo &, int x, int y) const;
350 MathMacroTemplate const & parent_;
352 Inset * clone() const;
356 InsetNameWrapper::InsetNameWrapper(MathData const * value,
357 MathMacroTemplate const & parent)
358 : InsetMathWrapper(value), parent_(parent)
363 Inset * InsetNameWrapper::clone() const
365 return new InsetNameWrapper(*this);
369 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
371 InsetMathWrapper::metrics(mi, dim);
372 dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
376 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
379 PainterInfo namepi = pi;
380 if (parent_.validMacro())
381 namepi.base.font.setColor(Color_latex);
383 namepi.base.font.setColor(Color_error);
386 pi.pain.text(x, y, from_ascii("\\"), namepi.base.font);
387 x += mathed_string_width(namepi.base.font, from_ascii("\\"));
390 InsetMathWrapper::draw(namepi, x, y);
394 ///////////////////////////////////////////////////////////////////////
397 MathMacroTemplate::MathMacroTemplate(Buffer * buf)
398 : InsetMathNest(buf, 3), numargs_(0), argsInLook_(0), optionals_(0),
399 type_(MacroTypeNewcommand), lookOutdated_(true)
405 MathMacroTemplate::MathMacroTemplate(Buffer * buf, docstring const & name, int numargs,
406 int optionals, MacroType type, vector<MathData> const & optionalValues,
407 MathData const & def, MathData const & display)
408 : InsetMathNest(buf, optionals + 3), numargs_(numargs), argsInLook_(numargs),
409 optionals_(optionals), optionalValues_(optionalValues),
410 type_(type), lookOutdated_(true)
415 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
418 asArray(name, cell(0));
419 optionalValues_.resize(9);
420 for (int i = 0; i < optionals_; ++i)
421 cell(optIdx(i)) = optionalValues_[i];
422 cell(defIdx()) = def;
423 cell(displayIdx()) = display;
429 MathMacroTemplate::MathMacroTemplate(Buffer * buf, docstring const & str)
430 : InsetMathNest(buf, 3), numargs_(0), optionals_(0),
431 type_(MacroTypeNewcommand), lookOutdated_(true)
437 mathed_parse_cell(ar, str, Parse::NORMAL);
438 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
439 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
440 asArray(from_ascii("invalidmacro"), cell(0));
441 // FIXME: The macro template does not make sense after this.
442 // The whole parsing should not be in a constructor which
443 // has no chance to report failure.
446 operator=( *(ar[0]->asMacroTemplate()) );
452 Inset * MathMacroTemplate::clone() const
454 MathMacroTemplate * inset = new MathMacroTemplate(*this);
455 // the parent pointers of the proxy insets above will point to
456 // to the old template. Hence, the look must be updated.
462 docstring MathMacroTemplate::name() const
464 return asString(cell(0));
468 void MathMacroTemplate::updateToContext(MacroContext const & mc)
470 redefinition_ = mc.get(name()) != 0;
474 void MathMacroTemplate::updateLook() const
476 lookOutdated_ = true;
480 void MathMacroTemplate::createLook(int args) const
486 look_.push_back(MathAtom(
487 new InsetLabelBox(buffer_, _("Name"), *this, false)));
488 MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
489 nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
493 if (optionals_ > 0) {
494 look_.push_back(MathAtom(
495 new InsetLabelBox(buffer_, _("optional"), *this, false)));
497 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
498 for (; i < optionals_; ++i) {
499 // color it light grey, if it is to be removed when the cursor leaves
500 if (i == argsInLook_) {
501 optData->push_back(MathAtom(
502 new InsetColoredCell(buffer_, Color_mathbg, Color_mathmacrooldarg)));
503 optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
506 optData->push_back(MathAtom(new InsetMathChar('[')));
507 optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
508 optData->push_back(MathAtom(new InsetMathChar(']')));
513 for (; i < numargs_; ++i) {
515 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
516 if (i >= argsInLook_) {
517 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
518 Color_mathbg, Color_mathmacrooldarg,
519 MathAtom(new InsetMathBrace(arg)))));
521 look_.push_back(MathAtom(new InsetMathBrace(arg)));
523 for (; i < argsInLook_; ++i) {
525 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
526 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
527 Color_mathbg, Color_mathmacronewarg,
528 MathAtom(new InsetMathBrace(arg)))));
532 look_.push_back(MathAtom(new InsetMathChar(':')));
533 look_.push_back(MathAtom(new InsetMathChar('=')));
536 look_.push_back(MathAtom(
537 new InsetLabelBox(buffer_, MathAtom(
538 new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this, true)));
541 look_.push_back(MathAtom(
542 new DisplayLabelBox(buffer_, MathAtom(
543 new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
547 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
549 FontSetChanger dummy1(mi.base, from_ascii("mathnormal"));
550 StyleChanger dummy2(mi.base, LM_ST_TEXT);
553 MacroData const * macro = 0;
555 macro = mi.macrocontext.get(name());
558 int argsInDef = maxArgumentInDefinition();
559 if (lookOutdated_ || argsInDef != argsInLook_) {
560 lookOutdated_ = false;
561 createLook(argsInDef);
564 /// metrics for inset contents
568 // first phase, premetric:
570 look_.metrics(mi, dim);
571 labelBoxAscent_ = dim.asc;
572 labelBoxDescent_ = dim.des;
574 // second phase, main metric:
576 look_.metrics(mi, dim);
585 setDimCache(mi, dim);
589 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
591 ColorChanger dummy0(pi.base.font, Color_math);
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.screenUpdateFlags(Update::SinglePar);
617 InsetMathNest::edit(cur, front, entry_from);
621 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
623 unsigned int const nargs_before = nargs();
624 commitEditChanges(cur, old);
626 cur.screenUpdateFlags(Update::Force);
627 // If we have removed a cell, we might have invalidated the cursor
628 return InsetMathNest::notifyCursorLeaves(old, cur)
629 || nargs() < nargs_before;
633 void MathMacroTemplate::removeArguments(Cursor & cur,
634 DocIterator const & /*inset_pos*/, int from, int to)
636 DocIterator it = doc_iterator_begin(&buffer(), this);
637 for (; it; it.forwardChar()) {
640 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
642 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
643 int n = arg->number() - 1;
644 if (from <= n && n <= to) {
645 int cellSlice = cur.find(it.cell());
646 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
647 --cur[cellSlice].pos();
649 it.cell().erase(it.pos());
657 void MathMacroTemplate::shiftArguments(size_t from, int by)
659 for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
662 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
664 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
665 if (arg->number() >= int(from) + 1)
666 arg->setNumber(arg->number() + by);
673 int MathMacroTemplate::maxArgumentInDefinition() const
675 // We don't have a buffer when pasting from the clipboard (bug 6014).
676 Buffer const * macro_buffer = isBufferLoaded() ? &buffer() : 0;
678 DocIterator it = doc_iterator_begin(macro_buffer, this);
680 for (; it; it.forwardChar()) {
683 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
685 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
686 maxArg = std::max(int(arg->number()), maxArg);
692 void MathMacroTemplate::insertMissingArguments(int maxArg)
694 bool found[9] = { false, false, false, false, false, false, false, false, false };
695 idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
697 // search for #n macros arguments
698 DocIterator it = doc_iterator_begin(&buffer(), this);
700 for (; it && it[0].idx() == idx; it.forwardChar()) {
703 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
705 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
706 found[arg->number() - 1] = true;
710 for (int i = 0; i < maxArg; ++i) {
714 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
719 void MathMacroTemplate::changeArity(Cursor & cur,
720 DocIterator const & inset_pos, int newNumArg)
722 // remove parameter which do not appear anymore in the definition
723 for (int i = numargs_; i > newNumArg; --i)
724 removeParameter(cur, inset_pos, numargs_ - 1, true);
726 // add missing parameter
727 for (int i = numargs_; i < newNumArg; ++i)
728 insertParameter(cur, inset_pos, numargs_, true, false);
733 class AddRemoveMacroInstanceFix
737 AddRemoveMacroInstanceFix(int n, bool insert) : n_(n), insert_(insert) {}
739 void operator()(MathMacro * macro)
741 if (macro->folded()) {
743 macro->insertArgument(n_);
745 macro->removeArgument(n_);
758 class OptionalsMacroInstanceFix
762 OptionalsMacroInstanceFix(int optionals) : optionals_(optionals) {}
764 void operator()(MathMacro * macro)
766 macro->setOptionals(optionals_);
776 class NullMacroInstanceFix
780 void operator()(MathMacro * ) {}
785 void fixMacroInstances(Cursor & cur, DocIterator const & inset_pos,
786 docstring const & name, F & fix)
788 // goto position behind macro template
789 DocIterator dit = inset_pos;
791 dit.top().forwardPos();
793 // remember hull to trigger preview reload
794 DocIterator hull(dit.buffer());
795 bool preview_reload_needed = false;
796 set<DocIterator> preview_hulls;
798 // iterate over all positions until macro is redefined
799 for (; dit; dit.forwardPos()) {
800 // left the outer hull?
801 if (!hull.empty() && dit.depth() == hull.depth()) {
802 // schedule reload of the preview if necessary
803 if (preview_reload_needed) {
804 preview_hulls.insert(hull);
805 preview_reload_needed = false;
810 // only until a macro is redefined
811 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
812 MathMacroTemplate const & macroTemplate
813 = static_cast<MathMacroTemplate const &>(dit.inset());
814 if (macroTemplate.name() == name)
818 // in front of macro instance?
819 Inset * inset = dit.nextInset();
822 InsetMath * insetMath = inset->asInsetMath();
826 // in front of outer hull?
827 InsetMathHull * inset_hull = insetMath->asHullInset();
828 if (inset_hull && hull.empty()) {
829 // remember this for later preview reload
833 MathMacro * macro = insetMath->asMacro();
834 if (macro && macro->name() == name && macro->folded()) {
836 if (RenderPreview::status() == LyXRC::PREVIEW_ON)
837 preview_reload_needed = true;
841 if (!preview_hulls.empty()) {
842 // reload the scheduled previews
843 set<DocIterator>::const_iterator sit = preview_hulls.begin();
844 set<DocIterator>::const_iterator end = preview_hulls.end();
845 for (; sit != end; ++sit) {
846 InsetMathHull * inset_hull =
847 sit->nextInset()->asInsetMath()->asHullInset();
849 inset_hull->reloadPreview(*sit);
851 cur.screenUpdateFlags(Update::Force);
856 void MathMacroTemplate::commitEditChanges(Cursor & cur,
857 DocIterator const & inset_pos)
859 int args_in_def = maxArgumentInDefinition();
860 if (args_in_def != numargs_) {
861 cur.recordUndoFullDocument();
862 changeArity(cur, inset_pos, args_in_def);
864 insertMissingArguments(args_in_def);
866 // make sure the preview are up to date
867 NullMacroInstanceFix fix;
868 fixMacroInstances(cur, inset_pos, name(), fix);
872 void MathMacroTemplate::insertParameter(Cursor & cur,
873 DocIterator const & inset_pos, int pos, bool greedy, bool addarg)
875 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
880 shiftArguments(pos, 1);
882 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
883 if (!cell(displayIdx()).empty())
884 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
888 // fix macro instances
889 AddRemoveMacroInstanceFix fix(pos, true);
890 fixMacroInstances(cur, inset_pos, name(), fix);
898 void MathMacroTemplate::removeParameter(Cursor & cur,
899 DocIterator const & inset_pos, int pos, bool greedy)
901 if (pos < numargs_ && pos >= 0) {
903 removeArguments(cur, inset_pos, pos, pos);
904 shiftArguments(pos + 1, -1);
906 // removed optional parameter?
907 if (pos < optionals_) {
909 optionalValues_[pos] = cell(optIdx(pos));
910 cells_.erase(cells_.begin() + optIdx(pos));
913 int macroSlice = cur.find(this);
914 if (macroSlice != -1) {
915 if (cur[macroSlice].idx() == optIdx(pos)) {
916 cur.cutOff(macroSlice);
917 cur[macroSlice].idx() = 1;
918 cur[macroSlice].pos() = 0;
919 } else if (cur[macroSlice].idx() > optIdx(pos))
920 --cur[macroSlice].idx();
925 // fix macro instances
926 AddRemoveMacroInstanceFix fix(pos, false);
927 fixMacroInstances(cur, inset_pos, name(), fix);
935 void MathMacroTemplate::makeOptional(Cursor & cur,
936 DocIterator const & inset_pos)
938 if (numargs_ > 0 && optionals_ < numargs_) {
940 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
942 int macroSlice = cur.find(this);
943 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
944 ++cur[macroSlice].idx();
946 // fix macro instances
947 OptionalsMacroInstanceFix fix(optionals_);
948 fixMacroInstances(cur, inset_pos, name(), fix);
955 void MathMacroTemplate::makeNonOptional(Cursor & cur,
956 DocIterator const & inset_pos)
958 if (numargs_ > 0 && optionals_ > 0) {
961 // store default value for later if the user changes his mind
962 optionalValues_[optionals_] = cell(optIdx(optionals_));
963 cells_.erase(cells_.begin() + optIdx(optionals_));
966 int macroSlice = cur.find(this);
967 if (macroSlice != -1) {
968 if (cur[macroSlice].idx() > optIdx(optionals_))
969 --cur[macroSlice].idx();
970 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
971 cur.cutOff(macroSlice);
972 cur[macroSlice].idx() = optIdx(optionals_);
973 cur[macroSlice].pos() = 0;
977 // fix macro instances
978 OptionalsMacroInstanceFix fix(optionals_);
979 fixMacroInstances(cur, inset_pos, name(), fix);
986 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
988 string const arg = to_utf8(cmd.argument());
989 switch (cmd.action()) {
991 case LFUN_MATH_MACRO_ADD_PARAM:
993 commitEditChanges(cur, cur);
994 cur.recordUndoFullDocument();
995 size_t pos = numargs_;
997 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
998 insertParameter(cur, cur, pos);
1003 case LFUN_MATH_MACRO_REMOVE_PARAM:
1005 commitEditChanges(cur, cur);
1006 cur.recordUndoFullDocument();
1007 size_t pos = numargs_ - 1;
1009 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1010 removeParameter(cur, cur, pos);
1014 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1016 commitEditChanges(cur, cur);
1017 cur.recordUndoFullDocument();
1018 insertParameter(cur, cur, numargs_, true);
1022 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1024 commitEditChanges(cur, cur);
1025 cur.recordUndoFullDocument();
1026 removeParameter(cur, cur, numargs_ - 1, true);
1030 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1031 commitEditChanges(cur, cur);
1032 cur.recordUndoFullDocument();
1033 makeOptional(cur, cur);
1036 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1037 commitEditChanges(cur, cur);
1038 cur.recordUndoFullDocument();
1039 makeNonOptional(cur, cur);
1042 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1044 commitEditChanges(cur, cur);
1045 cur.recordUndoFullDocument();
1046 insertParameter(cur, cur, optionals_);
1047 makeOptional(cur, cur);
1051 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1052 if (optionals_ > 0) {
1053 commitEditChanges(cur, cur);
1054 cur.recordUndoFullDocument();
1055 removeParameter(cur, cur, optionals_ - 1);
1058 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1059 if (numargs_ == optionals_) {
1060 commitEditChanges(cur, cur);
1061 cur.recordUndoFullDocument();
1062 insertParameter(cur, cur, 0, true);
1063 makeOptional(cur, cur);
1068 InsetMathNest::doDispatch(cur, cmd);
1074 bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
1075 FuncStatus & flag) const
1078 string const arg = to_utf8(cmd.argument());
1079 switch (cmd.action()) {
1080 case LFUN_MATH_MACRO_ADD_PARAM: {
1081 int num = numargs_ + 1;
1083 num = convert<int>(arg);
1084 bool on = (num >= optionals_
1085 && numargs_ < 9 && num <= numargs_ + 1);
1086 flag.setEnabled(on);
1090 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1091 flag.setEnabled(numargs_ < 9);
1094 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1095 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1098 num = convert<int>(arg);
1099 flag.setEnabled(num >= 1 && num <= numargs_);
1103 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1104 flag.setEnabled(numargs_ > 0
1105 && optionals_ < numargs_
1106 && type_ != MacroTypeDef);
1109 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1110 flag.setEnabled(optionals_ > 0
1111 && type_ != MacroTypeDef);
1114 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1115 flag.setEnabled(numargs_ < 9);
1118 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1119 flag.setEnabled(optionals_ > 0);
1122 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1123 flag.setEnabled(numargs_ == 0
1124 && type_ != MacroTypeDef);
1127 case LFUN_IN_MATHMACROTEMPLATE:
1128 flag.setEnabled(true);
1139 void MathMacroTemplate::read(Lexer & lex)
1141 MathData ar(buffer_);
1142 mathed_parse_cell(ar, lex.getStream(), Parse::TRACKMACRO);
1143 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1144 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1145 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1148 operator=( *(ar[0]->asMacroTemplate()) );
1154 void MathMacroTemplate::write(ostream & os) const
1156 odocstringstream oss;
1157 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1158 oss << "FormulaMacro\n";
1160 os << to_utf8(oss.str());
1164 void MathMacroTemplate::write(WriteStream & os) const
1170 int MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1175 if (optionals_ > 0) {
1176 // macros with optionals use the xargs package, e.g.:
1177 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1178 // \long is implicit by xargs
1179 if (redefinition_ && !overwriteRedefinition)
1180 os << "\\renewcommandx";
1182 os << "\\newcommandx";
1184 os << "\\" << name()
1185 << "[" << numargs_ << "]"
1186 << "[usedefault, addprefix=\\global";
1187 for (int i = 0; i < optionals_; ++i) {
1188 docstring optValue = asString(cell(optIdx(i)));
1189 if (optValue.find(']') != docstring::npos
1190 || optValue.find(',') != docstring::npos)
1191 os << ", " << i + 1 << "="
1192 << "{" << cell(optIdx(i)) << "}";
1194 os << ", " << i + 1 << "="
1199 // Macros without optionals use standard _global_ \def macros:
1200 // \global\def\long\foo#1#2{#1,#2}
1201 // We use the \long prefix as this is the equivalent to \newcommand.
1202 // We cannot use \newcommand directly because \global does not work with it.
1203 os << "\\global\\long\\def\\" << name();
1204 docstring param = from_ascii("#0");
1205 for (int i = 1; i <= numargs_; ++i) {
1211 // in LyX output we use some pseudo syntax which is implementation
1212 // independent, e.g.
1213 // \newcommand{\foo}[2][default]{#1,#2}
1214 if (redefinition_ && !overwriteRedefinition)
1215 os << "\\renewcommand";
1217 os << "\\newcommand";
1218 os << "{\\" << name() << '}';
1220 os << '[' << numargs_ << ']';
1222 for (int i = 0; i < optionals_; ++i) {
1223 docstring optValue = asString(cell(optIdx(i)));
1224 if (optValue.find(']') != docstring::npos)
1225 os << "[{" << cell(optIdx(i)) << "}]";
1227 os << "[" << cell(optIdx(i)) << "]";
1231 os << "{" << cell(defIdx()) << "}";
1234 // writing .tex. done.
1238 // writing .lyx, write special .tex export only if necessary
1239 if (!cell(displayIdx()).empty()) {
1240 os << "\n{" << cell(displayIdx()) << '}';
1249 docstring MathMacroTemplate::xhtml(XHTMLStream &, OutputParams const &) const
1254 int MathMacroTemplate::plaintext(odocstringstream & os,
1255 OutputParams const &, size_t) const
1257 static docstring const str = '[' + buffer().B_("math macro") + ']';
1264 bool MathMacroTemplate::validName() const
1266 docstring n = name();
1271 // converting back and force doesn't swallow anything?
1274 if (asString(ma) != n)
1277 // valid characters?
1278 for (size_t i = 0; i < n.size(); ++i) {
1279 if (!(n[i] >= 'a' && n[i] <= 'z')
1280 && !(n[i] >= 'A' && n[i] <= 'Z')
1289 bool MathMacroTemplate::validMacro() const
1295 bool MathMacroTemplate::fixNameAndCheckIfValid()
1297 // check all the characters/insets in the name cell
1299 MathData & data = cell(0);
1300 while (i < data.size()) {
1301 InsetMathChar const * cinset = data[i]->asCharInset();
1303 // valid character in [a-zA-Z]?
1304 char_type c = cinset->getChar();
1305 if ((c >= 'a' && c <= 'z')
1306 || (c >= 'A' && c <= 'Z')) {
1316 // now it should be valid if anything in the name survived
1317 return !data.empty();
1321 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1323 // we need global optional macro arguments. They are not available
1324 // with \def, and \newcommand does not support global macros. So we
1325 // are bound to xargs also for the single-optional-parameter case.
1327 features.require("xargs");
1330 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1332 defaults.resize(numargs_);
1333 for (int i = 0; i < optionals_; ++i)
1334 defaults[i] = asString(cell(optIdx(i)));
1338 docstring MathMacroTemplate::definition() const
1340 return asString(cell(defIdx()));
1344 docstring MathMacroTemplate::displayDefinition() const
1346 return asString(cell(displayIdx()));
1350 size_t MathMacroTemplate::numArgs() const
1356 size_t MathMacroTemplate::numOptionals() const
1362 void MathMacroTemplate::infoize(odocstream & os) const
1364 os << "Math Macro: \\" << name();
1368 string MathMacroTemplate::contextMenuName() const
1370 return "context-math-macro-definition";