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"
37 #include "TocBackend.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 bool MathMacroTemplate::fromString(docstring const & str)
431 MathData ar(buffer_);
432 mathed_parse_cell(ar, str, Parse::NORMAL);
433 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
434 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
435 asArray(from_ascii("invalidmacro"), cell(0));
436 // The macro template does not make sense after this.
439 operator=( *(ar[0]->asMacroTemplate()) );
446 Inset * MathMacroTemplate::clone() const
448 MathMacroTemplate * inset = new MathMacroTemplate(*this);
449 // the parent pointers of the proxy insets above will point to
450 // to the old template. Hence, the look must be updated.
456 docstring MathMacroTemplate::name() const
458 return asString(cell(0));
462 void MathMacroTemplate::updateToContext(MacroContext const & mc)
464 redefinition_ = mc.get(name()) != 0;
468 void MathMacroTemplate::updateLook() const
470 lookOutdated_ = true;
474 void MathMacroTemplate::createLook(int args) const
480 look_.push_back(MathAtom(
481 new InsetLabelBox(buffer_, _("Name"), *this, false)));
482 MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
483 nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
487 if (optionals_ > 0) {
488 look_.push_back(MathAtom(
489 new InsetLabelBox(buffer_, _("optional"), *this, false)));
491 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
492 for (; i < optionals_; ++i) {
493 // color it light grey, if it is to be removed when the cursor leaves
494 if (i == argsInLook_) {
495 optData->push_back(MathAtom(
496 new InsetColoredCell(buffer_, Color_mathbg, Color_mathmacrooldarg)));
497 optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
500 optData->push_back(MathAtom(new InsetMathChar('[')));
501 optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
502 optData->push_back(MathAtom(new InsetMathChar(']')));
507 for (; i < numargs_; ++i) {
509 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
510 if (i >= argsInLook_) {
511 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
512 Color_mathbg, Color_mathmacrooldarg,
513 MathAtom(new InsetMathBrace(arg)))));
515 look_.push_back(MathAtom(new InsetMathBrace(arg)));
517 for (; i < argsInLook_; ++i) {
519 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
520 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
521 Color_mathbg, Color_mathmacronewarg,
522 MathAtom(new InsetMathBrace(arg)))));
526 look_.push_back(MathAtom(new InsetMathChar(':')));
527 look_.push_back(MathAtom(new InsetMathChar('=')));
530 look_.push_back(MathAtom(
531 new InsetLabelBox(buffer_, MathAtom(
532 new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this, true)));
535 look_.push_back(MathAtom(
536 new DisplayLabelBox(buffer_, MathAtom(
537 new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
541 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
543 FontSetChanger dummy1(mi.base, from_ascii("mathnormal"));
544 StyleChanger dummy2(mi.base, LM_ST_TEXT);
547 MacroData const * macro = 0;
549 macro = mi.macrocontext.get(name());
552 int argsInDef = maxArgumentInDefinition();
553 if (lookOutdated_ || argsInDef != argsInLook_) {
554 lookOutdated_ = false;
555 createLook(argsInDef);
558 /// metrics for inset contents
562 // first phase, premetric:
564 look_.metrics(mi, dim);
565 labelBoxAscent_ = dim.asc;
566 labelBoxDescent_ = dim.des;
568 // second phase, main metric:
570 look_.metrics(mi, dim);
579 setDimCache(mi, dim);
583 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
585 ColorChanger dummy0(pi.base.font, Color_math);
586 FontSetChanger dummy1(pi.base, from_ascii("mathnormal"));
587 StyleChanger dummy2(pi.base, LM_ST_TEXT);
589 setPosCache(pi, x, y);
590 Dimension const dim = dimension(*pi.base.bv);
593 int const a = y - dim.asc + 1;
594 int const w = dim.wid - 2;
595 int const h = dim.height() - 2;
596 pi.pain.rectangle(x, a, w, h, Color_mathframe);
598 // just to be sure: set some dummy values for coord cache
599 for (idx_type i = 0; i < nargs(); ++i)
600 cell(i).setXY(*pi.base.bv, x, y);
603 look_.draw(pi, x + 3, y);
607 void MathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
610 cur.screenUpdateFlags(Update::SinglePar);
611 InsetMathNest::edit(cur, front, entry_from);
615 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
617 unsigned int const nargs_before = nargs();
618 commitEditChanges(cur, old);
620 cur.screenUpdateFlags(Update::Force);
621 // If we have removed a cell, we might have invalidated the cursor
622 return InsetMathNest::notifyCursorLeaves(old, cur)
623 || nargs() < nargs_before;
627 void MathMacroTemplate::removeArguments(Cursor & cur,
628 DocIterator const & /*inset_pos*/, int from, int to)
630 DocIterator it = doc_iterator_begin(&buffer(), this);
631 for (; it; it.forwardChar()) {
634 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
636 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
637 int n = arg->number() - 1;
638 if (from <= n && n <= to) {
639 int cellSlice = cur.find(it.cell());
640 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
641 --cur[cellSlice].pos();
643 it.cell().erase(it.pos());
651 void MathMacroTemplate::shiftArguments(size_t from, int by)
653 for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
656 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
658 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
659 if (arg->number() >= int(from) + 1)
660 arg->setNumber(arg->number() + by);
667 int MathMacroTemplate::maxArgumentInDefinition() const
669 // We don't have a buffer when pasting from the clipboard (bug 6014).
670 Buffer const * macro_buffer = isBufferLoaded() ? &buffer() : 0;
672 DocIterator it = doc_iterator_begin(macro_buffer, this);
674 for (; it; it.forwardChar()) {
677 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
679 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
680 maxArg = std::max(int(arg->number()), maxArg);
686 void MathMacroTemplate::insertMissingArguments(int maxArg)
688 bool found[9] = { false, false, false, false, false, false, false, false, false };
689 idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
691 // search for #n macros arguments
692 DocIterator it = doc_iterator_begin(&buffer(), this);
694 for (; it && it[0].idx() == idx; it.forwardChar()) {
697 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
699 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
700 found[arg->number() - 1] = true;
704 for (int i = 0; i < maxArg; ++i) {
708 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
713 void MathMacroTemplate::changeArity(Cursor & cur,
714 DocIterator const & inset_pos, int newNumArg)
716 // remove parameter which do not appear anymore in the definition
717 for (int i = numargs_; i > newNumArg; --i)
718 removeParameter(cur, inset_pos, numargs_ - 1, true);
720 // add missing parameter
721 for (int i = numargs_; i < newNumArg; ++i)
722 insertParameter(cur, inset_pos, numargs_, true, false);
727 class AddRemoveMacroInstanceFix
731 AddRemoveMacroInstanceFix(int n, bool insert) : n_(n), insert_(insert) {}
733 void operator()(MathMacro * macro)
735 if (macro->folded()) {
737 macro->insertArgument(n_);
739 macro->removeArgument(n_);
752 class OptionalsMacroInstanceFix
756 OptionalsMacroInstanceFix(int optionals) : optionals_(optionals) {}
758 void operator()(MathMacro * macro)
760 macro->setOptionals(optionals_);
770 class NullMacroInstanceFix
774 void operator()(MathMacro * ) {}
779 void fixMacroInstances(Cursor & cur, DocIterator const & inset_pos,
780 docstring const & name, F & fix)
782 // goto position behind macro template
783 DocIterator dit = inset_pos;
785 dit.top().forwardPos();
787 // remember hull to trigger preview reload
788 DocIterator hull(dit.buffer());
789 bool preview_reload_needed = false;
790 set<DocIterator> preview_hulls;
792 // iterate over all positions until macro is redefined
793 for (; dit; dit.forwardPos()) {
794 // left the outer hull?
795 if (!hull.empty() && dit.depth() == hull.depth()) {
796 // schedule reload of the preview if necessary
797 if (preview_reload_needed) {
798 preview_hulls.insert(hull);
799 preview_reload_needed = false;
804 // only until a macro is redefined
805 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
806 MathMacroTemplate const & macroTemplate
807 = static_cast<MathMacroTemplate const &>(dit.inset());
808 if (macroTemplate.name() == name)
812 // in front of macro instance?
813 Inset * inset = dit.nextInset();
816 InsetMath * insetMath = inset->asInsetMath();
820 // in front of outer hull?
821 InsetMathHull * inset_hull = insetMath->asHullInset();
822 if (inset_hull && hull.empty()) {
823 // remember this for later preview reload
827 MathMacro * macro = insetMath->asMacro();
828 if (macro && macro->name() == name && macro->folded()) {
830 if (RenderPreview::previewMath())
831 preview_reload_needed = true;
835 if (!preview_hulls.empty()) {
836 // reload the scheduled previews
837 set<DocIterator>::const_iterator sit = preview_hulls.begin();
838 set<DocIterator>::const_iterator end = preview_hulls.end();
839 for (; sit != end; ++sit) {
840 InsetMathHull * inset_hull =
841 sit->nextInset()->asInsetMath()->asHullInset();
843 inset_hull->reloadPreview(*sit);
845 cur.screenUpdateFlags(Update::Force);
850 void MathMacroTemplate::commitEditChanges(Cursor & cur,
851 DocIterator const & inset_pos)
853 int args_in_def = maxArgumentInDefinition();
854 if (args_in_def != numargs_) {
855 // FIXME: implement precise undo handling (only a few places
857 cur.recordUndoFullBuffer();
858 changeArity(cur, inset_pos, args_in_def);
860 insertMissingArguments(args_in_def);
862 // make sure the preview are up to date
863 NullMacroInstanceFix fix;
864 fixMacroInstances(cur, inset_pos, name(), fix);
868 void MathMacroTemplate::insertParameter(Cursor & cur,
869 DocIterator const & inset_pos, int pos, bool greedy, bool addarg)
871 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
876 shiftArguments(pos, 1);
878 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
879 if (!cell(displayIdx()).empty())
880 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
884 // fix macro instances
885 AddRemoveMacroInstanceFix fix(pos, true);
886 fixMacroInstances(cur, inset_pos, name(), fix);
894 void MathMacroTemplate::removeParameter(Cursor & cur,
895 DocIterator const & inset_pos, int pos, bool greedy)
897 if (pos < numargs_ && pos >= 0) {
899 removeArguments(cur, inset_pos, pos, pos);
900 shiftArguments(pos + 1, -1);
902 // removed optional parameter?
903 if (pos < optionals_) {
905 optionalValues_[pos] = cell(optIdx(pos));
906 cells_.erase(cells_.begin() + optIdx(pos));
909 int macroSlice = cur.find(this);
910 if (macroSlice != -1) {
911 if (cur[macroSlice].idx() == optIdx(pos)) {
912 cur.cutOff(macroSlice);
913 cur[macroSlice].idx() = 1;
914 cur[macroSlice].pos() = 0;
915 } else if (cur[macroSlice].idx() > optIdx(pos))
916 --cur[macroSlice].idx();
921 // fix macro instances
922 AddRemoveMacroInstanceFix fix(pos, false);
923 fixMacroInstances(cur, inset_pos, name(), fix);
931 void MathMacroTemplate::makeOptional(Cursor & cur,
932 DocIterator const & inset_pos)
934 if (numargs_ > 0 && optionals_ < numargs_) {
936 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
938 int macroSlice = cur.find(this);
939 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
940 ++cur[macroSlice].idx();
942 // fix macro instances
943 OptionalsMacroInstanceFix fix(optionals_);
944 fixMacroInstances(cur, inset_pos, name(), fix);
951 void MathMacroTemplate::makeNonOptional(Cursor & cur,
952 DocIterator const & inset_pos)
954 if (numargs_ > 0 && optionals_ > 0) {
957 // store default value for later if the user changes his mind
958 optionalValues_[optionals_] = cell(optIdx(optionals_));
959 cells_.erase(cells_.begin() + optIdx(optionals_));
962 int macroSlice = cur.find(this);
963 if (macroSlice != -1) {
964 if (cur[macroSlice].idx() > optIdx(optionals_))
965 --cur[macroSlice].idx();
966 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
967 cur.cutOff(macroSlice);
968 cur[macroSlice].idx() = optIdx(optionals_);
969 cur[macroSlice].pos() = 0;
973 // fix macro instances
974 OptionalsMacroInstanceFix fix(optionals_);
975 fixMacroInstances(cur, inset_pos, name(), fix);
982 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
984 string const arg = to_utf8(cmd.argument());
985 switch (cmd.action()) {
987 case LFUN_MATH_MACRO_ADD_PARAM:
989 commitEditChanges(cur, cur);
990 // FIXME: implement precise undo handling (only a few places
992 cur.recordUndoFullBuffer();
993 size_t pos = numargs_;
995 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
996 insertParameter(cur, cur, pos);
1001 case LFUN_MATH_MACRO_REMOVE_PARAM:
1003 commitEditChanges(cur, cur);
1004 // FIXME: implement precise undo handling (only a few places
1006 cur.recordUndoFullBuffer();
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 // FIXME: implement precise undo handling (only a few places
1019 cur.recordUndoFullBuffer();
1020 insertParameter(cur, cur, numargs_, true);
1024 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1026 commitEditChanges(cur, cur);
1027 // FIXME: implement precise undo handling (only a few places
1029 cur.recordUndoFullBuffer();
1030 removeParameter(cur, cur, numargs_ - 1, true);
1034 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1035 commitEditChanges(cur, cur);
1036 // FIXME: implement precise undo handling (only a few places
1038 cur.recordUndoFullBuffer();
1039 makeOptional(cur, cur);
1042 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1043 commitEditChanges(cur, cur);
1044 // FIXME: implement precise undo handling (only a few places
1046 cur.recordUndoFullBuffer();
1047 makeNonOptional(cur, cur);
1050 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1052 commitEditChanges(cur, cur);
1053 // FIXME: implement precise undo handling (only a few places
1055 cur.recordUndoFullBuffer();
1056 insertParameter(cur, cur, optionals_);
1057 makeOptional(cur, cur);
1061 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1062 if (optionals_ > 0) {
1063 commitEditChanges(cur, cur);
1064 // FIXME: implement precise undo handling (only a few places
1066 cur.recordUndoFullBuffer();
1067 removeParameter(cur, cur, optionals_ - 1);
1070 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1071 if (numargs_ == optionals_) {
1072 commitEditChanges(cur, cur);
1073 // FIXME: implement precise undo handling (only a few places
1075 cur.recordUndoFullBuffer();
1076 insertParameter(cur, cur, 0, true);
1077 makeOptional(cur, cur);
1082 InsetMathNest::doDispatch(cur, cmd);
1088 bool MathMacroTemplate::getStatus(Cursor & cur, FuncRequest const & cmd,
1089 FuncStatus & flag) const
1092 string const arg = to_utf8(cmd.argument());
1093 switch (cmd.action()) {
1094 case LFUN_MATH_MACRO_ADD_PARAM: {
1095 int num = numargs_ + 1;
1097 num = convert<int>(arg);
1098 bool on = (num >= optionals_
1099 && numargs_ < 9 && num <= numargs_ + 1);
1100 flag.setEnabled(on);
1104 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1105 flag.setEnabled(numargs_ < 9);
1108 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1109 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1112 num = convert<int>(arg);
1113 flag.setEnabled(num >= 1 && num <= numargs_);
1117 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1118 flag.setEnabled(numargs_ > 0
1119 && optionals_ < numargs_
1120 && type_ != MacroTypeDef);
1123 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1124 flag.setEnabled(optionals_ > 0
1125 && type_ != MacroTypeDef);
1128 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1129 flag.setEnabled(numargs_ < 9);
1132 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1133 flag.setEnabled(optionals_ > 0);
1136 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1137 flag.setEnabled(numargs_ == 0
1138 && type_ != MacroTypeDef);
1141 case LFUN_IN_MATHMACROTEMPLATE:
1142 flag.setEnabled(true);
1146 ret = InsetMathNest::getStatus(cur, cmd, flag);
1153 void MathMacroTemplate::read(Lexer & lex)
1155 MathData ar(buffer_);
1156 mathed_parse_cell(ar, lex.getStream(), Parse::TRACKMACRO);
1157 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1158 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1159 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1162 operator=( *(ar[0]->asMacroTemplate()) );
1168 void MathMacroTemplate::write(ostream & os) const
1170 odocstringstream oss;
1171 TexRow texrow(false);
1172 otexrowstream ots(oss,texrow);
1173 WriteStream wi(ots, false, false, WriteStream::wsDefault);
1174 oss << "FormulaMacro\n";
1176 os << to_utf8(oss.str());
1180 void MathMacroTemplate::write(WriteStream & os) const
1186 int MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1191 if (optionals_ > 0) {
1192 // macros with optionals use the xargs package, e.g.:
1193 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1194 // \long is implicit by xargs
1195 if (redefinition_ && !overwriteRedefinition)
1196 os << "\\renewcommandx";
1198 os << "\\newcommandx";
1200 os << "\\" << name()
1201 << "[" << numargs_ << "]"
1202 << "[usedefault, addprefix=\\global";
1203 for (int i = 0; i < optionals_; ++i) {
1204 docstring optValue = asString(cell(optIdx(i)));
1205 if (optValue.find(']') != docstring::npos
1206 || optValue.find(',') != docstring::npos)
1207 os << ", " << i + 1 << "="
1208 << "{" << cell(optIdx(i)) << "}";
1210 os << ", " << i + 1 << "="
1215 // Macros without optionals use standard _global_ \def macros:
1216 // \global\def\long\foo#1#2{#1,#2}
1217 // We use the \long prefix as this is the equivalent to \newcommand.
1218 // We cannot use \newcommand directly because \global does not work with it.
1219 os << "\\global\\long\\def\\" << name();
1220 docstring param = from_ascii("#0");
1221 for (int i = 1; i <= numargs_; ++i) {
1227 // in LyX output we use some pseudo syntax which is implementation
1228 // independent, e.g.
1229 // \newcommand{\foo}[2][default]{#1,#2}
1230 if (redefinition_ && !overwriteRedefinition)
1231 os << "\\renewcommand";
1233 os << "\\newcommand";
1234 os << "{\\" << name() << '}';
1236 os << '[' << numargs_ << ']';
1238 for (int i = 0; i < optionals_; ++i) {
1239 docstring optValue = asString(cell(optIdx(i)));
1240 if (optValue.find(']') != docstring::npos)
1241 os << "[{" << cell(optIdx(i)) << "}]";
1243 os << "[" << cell(optIdx(i)) << "]";
1247 os << "{" << cell(defIdx()) << "}";
1250 // writing .tex. done.
1254 // writing .lyx, write special .tex export only if necessary
1255 if (!cell(displayIdx()).empty()) {
1256 os << "\n{" << cell(displayIdx()) << '}';
1265 docstring MathMacroTemplate::xhtml(XHTMLStream &, OutputParams const &) const
1270 int MathMacroTemplate::plaintext(odocstringstream & os,
1271 OutputParams const &, size_t) const
1273 docstring const str = '[' + buffer().B_("math macro") + ']';
1280 bool MathMacroTemplate::validName() const
1282 docstring n = name();
1287 // converting back and force doesn't swallow anything?
1290 if (asString(ma) != n)
1293 // valid characters?
1294 for (size_t i = 0; i < n.size(); ++i) {
1295 if (!(n[i] >= 'a' && n[i] <= 'z')
1296 && !(n[i] >= 'A' && n[i] <= 'Z')
1305 bool MathMacroTemplate::validMacro() const
1311 bool MathMacroTemplate::fixNameAndCheckIfValid()
1313 // check all the characters/insets in the name cell
1315 MathData & data = cell(0);
1316 while (i < data.size()) {
1317 InsetMathChar const * cinset = data[i]->asCharInset();
1319 // valid character in [a-zA-Z]?
1320 char_type c = cinset->getChar();
1321 if ((c >= 'a' && c <= 'z')
1322 || (c >= 'A' && c <= 'Z')) {
1332 // now it should be valid if anything in the name survived
1333 return !data.empty();
1337 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1339 // we need global optional macro arguments. They are not available
1340 // with \def, and \newcommand does not support global macros. So we
1341 // are bound to xargs also for the single-optional-parameter case.
1343 features.require("xargs");
1346 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1348 defaults.resize(numargs_);
1349 for (int i = 0; i < optionals_; ++i)
1350 defaults[i] = asString(cell(optIdx(i)));
1354 docstring MathMacroTemplate::definition() const
1356 return asString(cell(defIdx()));
1360 docstring MathMacroTemplate::displayDefinition() const
1362 return asString(cell(displayIdx()));
1366 size_t MathMacroTemplate::numArgs() const
1372 size_t MathMacroTemplate::numOptionals() const
1378 void MathMacroTemplate::infoize(odocstream & os) const
1380 os << bformat(_("Math Macro: \\%1$s"), name());
1384 string MathMacroTemplate::contextMenuName() const
1386 return "context-math-macro-definition";
1389 void MathMacroTemplate::addToToc(DocIterator const & pit, bool output_active,
1392 shared_ptr<Toc> toc = buffer().tocBackend().toc("math-macro");
1395 str = bformat(_("Invalid macro! \\%1$s"), name());
1397 str = "\\" + name();
1398 toc->push_back(TocItem(pit, 0, str, output_active));