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), redefinition_(false), lookOutdated_(true),
400 premetrics_(false), labelBoxAscent_(0), labelBoxDescent_(0)
406 MathMacroTemplate::MathMacroTemplate(Buffer * buf, docstring const & name, int numargs,
407 int optionals, MacroType type, vector<MathData> const & optionalValues,
408 MathData const & def, MathData const & display)
409 : InsetMathNest(buf, optionals + 3), numargs_(numargs), argsInLook_(numargs),
410 optionals_(optionals), optionalValues_(optionalValues),
411 type_(type), redefinition_(false), lookOutdated_(true),
412 premetrics_(false), labelBoxAscent_(0), labelBoxDescent_(0)
417 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
420 asArray(name, cell(0));
421 optionalValues_.resize(9);
422 for (int i = 0; i < optionals_; ++i)
423 cell(optIdx(i)) = optionalValues_[i];
424 cell(defIdx()) = def;
425 cell(displayIdx()) = display;
431 bool MathMacroTemplate::fromString(docstring const & str)
433 MathData ar(buffer_);
434 mathed_parse_cell(ar, str, Parse::NORMAL);
435 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
436 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
437 asArray(from_ascii("invalidmacro"), cell(0));
438 // The macro template does not make sense after this.
441 operator=( *(ar[0]->asMacroTemplate()) );
448 Inset * MathMacroTemplate::clone() const
450 MathMacroTemplate * inset = new MathMacroTemplate(*this);
451 // the parent pointers of the proxy insets above will point to
452 // to the old template. Hence, the look must be updated.
458 docstring MathMacroTemplate::name() const
460 return asString(cell(0));
464 void MathMacroTemplate::updateToContext(MacroContext const & mc)
466 redefinition_ = mc.get(name()) != 0;
470 void MathMacroTemplate::updateLook() const
472 lookOutdated_ = true;
476 void MathMacroTemplate::createLook(int args) const
482 look_.push_back(MathAtom(
483 new InsetLabelBox(buffer_, _("Name"), *this, false)));
484 MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
485 nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
489 if (optionals_ > 0) {
490 look_.push_back(MathAtom(
491 new InsetLabelBox(buffer_, _("optional"), *this, false)));
493 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
494 for (; i < optionals_; ++i) {
495 // color it light grey, if it is to be removed when the cursor leaves
496 if (i == argsInLook_) {
497 optData->push_back(MathAtom(
498 new InsetColoredCell(buffer_, Color_mathbg, Color_mathmacrooldarg)));
499 optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
502 optData->push_back(MathAtom(new InsetMathChar('[')));
503 optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
504 optData->push_back(MathAtom(new InsetMathChar(']')));
509 for (; i < numargs_; ++i) {
511 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
512 if (i >= argsInLook_) {
513 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
514 Color_mathbg, Color_mathmacrooldarg,
515 MathAtom(new InsetMathBrace(arg)))));
517 look_.push_back(MathAtom(new InsetMathBrace(arg)));
519 for (; i < argsInLook_; ++i) {
521 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
522 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
523 Color_mathbg, Color_mathmacronewarg,
524 MathAtom(new InsetMathBrace(arg)))));
528 look_.push_back(MathAtom(new InsetMathChar(':')));
529 look_.push_back(MathAtom(new InsetMathChar('=')));
532 look_.push_back(MathAtom(
533 new InsetLabelBox(buffer_, MathAtom(
534 new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this, true)));
537 look_.push_back(MathAtom(
538 new DisplayLabelBox(buffer_, MathAtom(
539 new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
543 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
545 FontSetChanger dummy1(mi.base, from_ascii("mathnormal"));
546 StyleChanger dummy2(mi.base, LM_ST_TEXT);
549 MacroData const * macro = 0;
551 macro = mi.macrocontext.get(name());
554 int argsInDef = maxArgumentInDefinition();
555 if (lookOutdated_ || argsInDef != argsInLook_) {
556 lookOutdated_ = false;
557 createLook(argsInDef);
560 /// metrics for inset contents
564 // first phase, premetric:
566 look_.metrics(mi, dim);
567 labelBoxAscent_ = dim.asc;
568 labelBoxDescent_ = dim.des;
570 // second phase, main metric:
572 look_.metrics(mi, dim);
581 setDimCache(mi, dim);
585 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
587 ColorChanger dummy0(pi.base.font, Color_math);
588 FontSetChanger dummy1(pi.base, from_ascii("mathnormal"));
589 StyleChanger dummy2(pi.base, LM_ST_TEXT);
591 setPosCache(pi, x, y);
592 Dimension const dim = dimension(*pi.base.bv);
595 int const a = y - dim.asc + 1;
596 int const w = dim.wid - 2;
597 int const h = dim.height() - 2;
598 pi.pain.rectangle(x, a, w, h, Color_mathframe);
600 // just to be sure: set some dummy values for coord cache
601 for (idx_type i = 0; i < nargs(); ++i)
602 cell(i).setXY(*pi.base.bv, x, y);
605 look_.draw(pi, x + 3, y);
609 void MathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
612 cur.screenUpdateFlags(Update::SinglePar);
613 InsetMathNest::edit(cur, front, entry_from);
617 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
619 unsigned int const nargs_before = nargs();
620 commitEditChanges(cur, old);
622 cur.screenUpdateFlags(Update::Force);
623 // If we have removed a cell, we might have invalidated the cursor
624 return InsetMathNest::notifyCursorLeaves(old, cur)
625 || nargs() < nargs_before;
629 void MathMacroTemplate::removeArguments(Cursor & cur,
630 DocIterator const & /*inset_pos*/, int from, int to)
632 DocIterator it = doc_iterator_begin(&buffer(), this);
633 for (; it; it.forwardChar()) {
636 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
638 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
639 int n = arg->number() - 1;
640 if (from <= n && n <= to) {
641 int cellSlice = cur.find(it.cell());
642 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
643 --cur[cellSlice].pos();
645 it.cell().erase(it.pos());
653 void MathMacroTemplate::shiftArguments(size_t from, int by)
655 for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
658 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
660 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
661 if (arg->number() >= int(from) + 1)
662 arg->setNumber(arg->number() + by);
669 int MathMacroTemplate::maxArgumentInDefinition() const
671 // We don't have a buffer when pasting from the clipboard (bug 6014).
672 Buffer const * macro_buffer = isBufferLoaded() ? &buffer() : 0;
674 DocIterator it = doc_iterator_begin(macro_buffer, this);
676 for (; it; it.forwardChar()) {
679 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
681 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
682 maxArg = std::max(int(arg->number()), maxArg);
688 void MathMacroTemplate::insertMissingArguments(int maxArg)
690 bool found[9] = { false, false, false, false, false, false, false, false, false };
691 idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
693 // search for #n macros arguments
694 DocIterator it = doc_iterator_begin(&buffer(), this);
696 for (; it && it[0].idx() == idx; it.forwardChar()) {
699 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
701 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
702 found[arg->number() - 1] = true;
706 for (int i = 0; i < maxArg; ++i) {
710 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
715 void MathMacroTemplate::changeArity(Cursor & cur,
716 DocIterator const & inset_pos, int newNumArg)
718 // remove parameter which do not appear anymore in the definition
719 for (int i = numargs_; i > newNumArg; --i)
720 removeParameter(cur, inset_pos, numargs_ - 1, true);
722 // add missing parameter
723 for (int i = numargs_; i < newNumArg; ++i)
724 insertParameter(cur, inset_pos, numargs_, true, false);
729 class AddRemoveMacroInstanceFix
733 AddRemoveMacroInstanceFix(int n, bool insert) : n_(n), insert_(insert) {}
735 void operator()(MathMacro * macro)
737 if (macro->folded()) {
739 macro->insertArgument(n_);
741 macro->removeArgument(n_);
754 class OptionalsMacroInstanceFix
758 OptionalsMacroInstanceFix(int optionals) : optionals_(optionals) {}
760 void operator()(MathMacro * macro)
762 macro->setOptionals(optionals_);
772 class NullMacroInstanceFix
776 void operator()(MathMacro * ) {}
781 void fixMacroInstances(Cursor & cur, DocIterator const & inset_pos,
782 docstring const & name, F & fix)
784 // goto position behind macro template
785 DocIterator dit = inset_pos;
787 dit.top().forwardPos();
789 // remember hull to trigger preview reload
790 DocIterator hull(dit.buffer());
791 bool preview_reload_needed = false;
792 set<DocIterator> preview_hulls;
794 // iterate over all positions until macro is redefined
795 for (; dit; dit.forwardPos()) {
796 // left the outer hull?
797 if (!hull.empty() && dit.depth() == hull.depth()) {
798 // schedule reload of the preview if necessary
799 if (preview_reload_needed) {
800 preview_hulls.insert(hull);
801 preview_reload_needed = false;
806 // only until a macro is redefined
807 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
808 MathMacroTemplate const & macroTemplate
809 = static_cast<MathMacroTemplate const &>(dit.inset());
810 if (macroTemplate.name() == name)
814 // in front of macro instance?
815 Inset * inset = dit.nextInset();
818 InsetMath * insetMath = inset->asInsetMath();
822 // in front of outer hull?
823 InsetMathHull * inset_hull = insetMath->asHullInset();
824 if (inset_hull && hull.empty()) {
825 // remember this for later preview reload
829 MathMacro * macro = insetMath->asMacro();
830 if (macro && macro->name() == name && macro->folded()) {
832 if (RenderPreview::previewMath())
833 preview_reload_needed = true;
837 if (!preview_hulls.empty()) {
838 // reload the scheduled previews
839 set<DocIterator>::const_iterator sit = preview_hulls.begin();
840 set<DocIterator>::const_iterator end = preview_hulls.end();
841 for (; sit != end; ++sit) {
842 InsetMathHull * inset_hull =
843 sit->nextInset()->asInsetMath()->asHullInset();
845 inset_hull->reloadPreview(*sit);
847 cur.screenUpdateFlags(Update::Force);
852 void MathMacroTemplate::commitEditChanges(Cursor & cur,
853 DocIterator const & inset_pos)
855 int args_in_def = maxArgumentInDefinition();
856 if (args_in_def != numargs_) {
857 // FIXME: implement precise undo handling (only a few places
859 cur.recordUndoFullBuffer();
860 changeArity(cur, inset_pos, args_in_def);
862 insertMissingArguments(args_in_def);
864 // make sure the preview are up to date
865 NullMacroInstanceFix fix;
866 fixMacroInstances(cur, inset_pos, name(), fix);
870 void MathMacroTemplate::insertParameter(Cursor & cur,
871 DocIterator const & inset_pos, int pos, bool greedy, bool addarg)
873 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
878 shiftArguments(pos, 1);
880 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
881 if (!cell(displayIdx()).empty())
882 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
886 // fix macro instances
887 AddRemoveMacroInstanceFix fix(pos, true);
888 fixMacroInstances(cur, inset_pos, name(), fix);
896 void MathMacroTemplate::removeParameter(Cursor & cur,
897 DocIterator const & inset_pos, int pos, bool greedy)
899 if (pos < numargs_ && pos >= 0) {
901 removeArguments(cur, inset_pos, pos, pos);
902 shiftArguments(pos + 1, -1);
904 // removed optional parameter?
905 if (pos < optionals_) {
907 optionalValues_[pos] = cell(optIdx(pos));
908 cells_.erase(cells_.begin() + optIdx(pos));
911 int macroSlice = cur.find(this);
912 if (macroSlice != -1) {
913 if (cur[macroSlice].idx() == optIdx(pos)) {
914 cur.cutOff(macroSlice);
915 cur[macroSlice].idx() = 1;
916 cur[macroSlice].pos() = 0;
917 } else if (cur[macroSlice].idx() > optIdx(pos))
918 --cur[macroSlice].idx();
923 // fix macro instances
924 AddRemoveMacroInstanceFix fix(pos, false);
925 fixMacroInstances(cur, inset_pos, name(), fix);
933 void MathMacroTemplate::makeOptional(Cursor & cur,
934 DocIterator const & inset_pos)
936 if (numargs_ > 0 && optionals_ < numargs_) {
938 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
940 int macroSlice = cur.find(this);
941 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
942 ++cur[macroSlice].idx();
944 // fix macro instances
945 OptionalsMacroInstanceFix fix(optionals_);
946 fixMacroInstances(cur, inset_pos, name(), fix);
953 void MathMacroTemplate::makeNonOptional(Cursor & cur,
954 DocIterator const & inset_pos)
956 if (numargs_ > 0 && optionals_ > 0) {
959 // store default value for later if the user changes his mind
960 optionalValues_[optionals_] = cell(optIdx(optionals_));
961 cells_.erase(cells_.begin() + optIdx(optionals_));
964 int macroSlice = cur.find(this);
965 if (macroSlice != -1) {
966 if (cur[macroSlice].idx() > optIdx(optionals_))
967 --cur[macroSlice].idx();
968 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
969 cur.cutOff(macroSlice);
970 cur[macroSlice].idx() = optIdx(optionals_);
971 cur[macroSlice].pos() = 0;
975 // fix macro instances
976 OptionalsMacroInstanceFix fix(optionals_);
977 fixMacroInstances(cur, inset_pos, name(), fix);
984 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
986 string const arg = to_utf8(cmd.argument());
987 switch (cmd.action()) {
989 case LFUN_MATH_MACRO_ADD_PARAM:
991 commitEditChanges(cur, cur);
992 // FIXME: implement precise undo handling (only a few places
994 cur.recordUndoFullBuffer();
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 // FIXME: implement precise undo handling (only a few places
1008 cur.recordUndoFullBuffer();
1009 size_t pos = numargs_ - 1;
1011 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1012 removeParameter(cur, cur, pos);
1016 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1018 commitEditChanges(cur, cur);
1019 // FIXME: implement precise undo handling (only a few places
1021 cur.recordUndoFullBuffer();
1022 insertParameter(cur, cur, numargs_, true);
1026 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1028 commitEditChanges(cur, cur);
1029 // FIXME: implement precise undo handling (only a few places
1031 cur.recordUndoFullBuffer();
1032 removeParameter(cur, cur, numargs_ - 1, true);
1036 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1037 commitEditChanges(cur, cur);
1038 // FIXME: implement precise undo handling (only a few places
1040 cur.recordUndoFullBuffer();
1041 makeOptional(cur, cur);
1044 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1045 commitEditChanges(cur, cur);
1046 // FIXME: implement precise undo handling (only a few places
1048 cur.recordUndoFullBuffer();
1049 makeNonOptional(cur, cur);
1052 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1054 commitEditChanges(cur, cur);
1055 // FIXME: implement precise undo handling (only a few places
1057 cur.recordUndoFullBuffer();
1058 insertParameter(cur, cur, optionals_);
1059 makeOptional(cur, cur);
1063 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1064 if (optionals_ > 0) {
1065 commitEditChanges(cur, cur);
1066 // FIXME: implement precise undo handling (only a few places
1068 cur.recordUndoFullBuffer();
1069 removeParameter(cur, cur, optionals_ - 1);
1072 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1073 if (numargs_ == optionals_) {
1074 commitEditChanges(cur, cur);
1075 // FIXME: implement precise undo handling (only a few places
1077 cur.recordUndoFullBuffer();
1078 insertParameter(cur, cur, 0, true);
1079 makeOptional(cur, cur);
1084 InsetMathNest::doDispatch(cur, cmd);
1090 bool MathMacroTemplate::getStatus(Cursor & cur, FuncRequest const & cmd,
1091 FuncStatus & flag) const
1094 string const arg = to_utf8(cmd.argument());
1095 switch (cmd.action()) {
1096 case LFUN_MATH_MACRO_ADD_PARAM: {
1097 int num = numargs_ + 1;
1099 num = convert<int>(arg);
1100 bool on = (num >= optionals_
1101 && numargs_ < 9 && num <= numargs_ + 1);
1102 flag.setEnabled(on);
1106 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1107 flag.setEnabled(numargs_ < 9);
1110 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1111 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1114 num = convert<int>(arg);
1115 flag.setEnabled(num >= 1 && num <= numargs_);
1119 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1120 flag.setEnabled(numargs_ > 0
1121 && optionals_ < numargs_
1122 && type_ != MacroTypeDef);
1125 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1126 flag.setEnabled(optionals_ > 0
1127 && type_ != MacroTypeDef);
1130 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1131 flag.setEnabled(numargs_ < 9);
1134 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1135 flag.setEnabled(optionals_ > 0);
1138 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1139 flag.setEnabled(numargs_ == 0
1140 && type_ != MacroTypeDef);
1143 case LFUN_IN_MATHMACROTEMPLATE:
1144 flag.setEnabled(true);
1148 ret = InsetMathNest::getStatus(cur, cmd, flag);
1155 void MathMacroTemplate::read(Lexer & lex)
1157 MathData ar(buffer_);
1158 mathed_parse_cell(ar, lex.getStream(), Parse::TRACKMACRO);
1159 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1160 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1161 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1164 operator=( *(ar[0]->asMacroTemplate()) );
1170 void MathMacroTemplate::write(ostream & os) const
1172 odocstringstream oss;
1173 TexRow texrow(false);
1174 otexrowstream ots(oss,texrow);
1175 WriteStream wi(ots, false, false, WriteStream::wsDefault);
1176 oss << "FormulaMacro\n";
1178 os << to_utf8(oss.str());
1182 void MathMacroTemplate::write(WriteStream & os) const
1188 int MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1193 if (optionals_ > 0) {
1194 // macros with optionals use the xargs package, e.g.:
1195 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1196 // \long is implicit by xargs
1197 if (redefinition_ && !overwriteRedefinition)
1198 os << "\\renewcommandx";
1200 os << "\\newcommandx";
1202 os << "\\" << name()
1203 << "[" << numargs_ << "]"
1204 << "[usedefault, addprefix=\\global";
1205 for (int i = 0; i < optionals_; ++i) {
1206 docstring optValue = asString(cell(optIdx(i)));
1207 if (optValue.find(']') != docstring::npos
1208 || optValue.find(',') != docstring::npos)
1209 os << ", " << i + 1 << "="
1210 << "{" << cell(optIdx(i)) << "}";
1212 os << ", " << i + 1 << "="
1217 // Macros without optionals use standard _global_ \def macros:
1218 // \global\def\long\foo#1#2{#1,#2}
1219 // We use the \long prefix as this is the equivalent to \newcommand.
1220 // We cannot use \newcommand directly because \global does not work with it.
1221 os << "\\global\\long\\def\\" << name();
1222 docstring param = from_ascii("#0");
1223 for (int i = 1; i <= numargs_; ++i) {
1229 // in LyX output we use some pseudo syntax which is implementation
1230 // independent, e.g.
1231 // \newcommand{\foo}[2][default]{#1,#2}
1232 if (redefinition_ && !overwriteRedefinition)
1233 os << "\\renewcommand";
1235 os << "\\newcommand";
1236 os << "{\\" << name() << '}';
1238 os << '[' << numargs_ << ']';
1240 for (int i = 0; i < optionals_; ++i) {
1241 docstring optValue = asString(cell(optIdx(i)));
1242 if (optValue.find(']') != docstring::npos)
1243 os << "[{" << cell(optIdx(i)) << "}]";
1245 os << "[" << cell(optIdx(i)) << "]";
1249 os << "{" << cell(defIdx()) << "}";
1252 // writing .tex. done.
1256 // writing .lyx, write special .tex export only if necessary
1257 if (!cell(displayIdx()).empty()) {
1258 os << "\n{" << cell(displayIdx()) << '}';
1267 docstring MathMacroTemplate::xhtml(XHTMLStream &, OutputParams const &) const
1272 int MathMacroTemplate::plaintext(odocstringstream & os,
1273 OutputParams const &, size_t) const
1275 docstring const str = '[' + buffer().B_("math macro") + ']';
1282 bool MathMacroTemplate::validName() const
1284 docstring n = name();
1289 // converting back and force doesn't swallow anything?
1292 if (asString(ma) != n)
1295 // valid characters?
1296 for (size_t i = 0; i < n.size(); ++i) {
1297 if (!(n[i] >= 'a' && n[i] <= 'z')
1298 && !(n[i] >= 'A' && n[i] <= 'Z')
1307 bool MathMacroTemplate::validMacro() const
1313 bool MathMacroTemplate::fixNameAndCheckIfValid()
1315 // check all the characters/insets in the name cell
1317 MathData & data = cell(0);
1318 while (i < data.size()) {
1319 InsetMathChar const * cinset = data[i]->asCharInset();
1321 // valid character in [a-zA-Z]?
1322 char_type c = cinset->getChar();
1323 if ((c >= 'a' && c <= 'z')
1324 || (c >= 'A' && c <= 'Z')) {
1334 // now it should be valid if anything in the name survived
1335 return !data.empty();
1339 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1341 // we need global optional macro arguments. They are not available
1342 // with \def, and \newcommand does not support global macros. So we
1343 // are bound to xargs also for the single-optional-parameter case.
1345 features.require("xargs");
1348 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1350 defaults.resize(numargs_);
1351 for (int i = 0; i < optionals_; ++i)
1352 defaults[i] = asString(cell(optIdx(i)));
1356 docstring MathMacroTemplate::definition() const
1358 return asString(cell(defIdx()));
1362 docstring MathMacroTemplate::displayDefinition() const
1364 return asString(cell(displayIdx()));
1368 size_t MathMacroTemplate::numArgs() const
1374 size_t MathMacroTemplate::numOptionals() const
1380 void MathMacroTemplate::infoize(odocstream & os) const
1382 os << bformat(_("Math Macro: \\%1$s"), name());
1386 string MathMacroTemplate::contextMenuName() const
1388 return "context-math-macro-definition";
1391 void MathMacroTemplate::addToToc(DocIterator const & pit, bool output_active,
1394 shared_ptr<Toc> toc = buffer().tocBackend().toc("math-macro");
1397 str = bformat(_("Invalid macro! \\%1$s"), name());
1399 str = "\\" + name();
1400 toc->push_back(TocItem(pit, 0, str, output_active));