2 * \file MathMacroTemplate.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "MathMacroTemplate.h"
15 #include "DocIterator.h"
16 #include "InsetMathBrace.h"
17 #include "InsetMathChar.h"
18 #include "InsetMathSqrt.h"
19 #include "MathMacro.h"
20 #include "MathMacroArgument.h"
21 #include "MathStream.h"
22 #include "MathParser.h"
23 #include "MathSupport.h"
24 #include "MathMacroArgument.h"
29 #include "support/debug.h"
30 #include "DispatchResult.h"
31 #include "FuncRequest.h"
32 #include "FuncStatus.h"
33 #include "support/gettext.h"
37 #include "frontends/FontMetrics.h"
38 #include "frontends/Painter.h"
40 #include "support/convert.h"
41 #include "support/docstream.h"
42 #include "support/lstrings.h"
44 #include "support/debug.h"
52 using support::bformat;
55 class InsetMathWrapper : public InsetMath {
58 InsetMathWrapper(MathData const * value) : value_(value) {}
60 void metrics(MetricsInfo & mi, Dimension & dim) const;
62 void draw(PainterInfo &, int x, int y) const;
66 Inset * clone() const;
68 MathData const * value_;
72 Inset * InsetMathWrapper::clone() const
74 return new InsetMathWrapper(*this);
78 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
80 value_->metrics(mi, dim);
81 //metricsMarkers2(dim);
85 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
87 value_->draw(pi, x, y);
88 //drawMarkers(pi, x, y);
92 MathMacroTemplate::MathMacroTemplate()
93 : InsetMathNest(3), numargs_(0), optionals_(0), type_(from_ascii("newcommand"))
99 MathMacroTemplate::MathMacroTemplate(docstring const & name, int numargs,
100 int optionals, docstring const & type,
101 std::vector<MathData> const & optionalValues,
102 MathData const & def, MathData const & display)
103 : InsetMathNest(optionals + 3), numargs_(numargs),
104 optionals_(optionals), optionalValues_(optionalValues), type_(type)
109 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
110 << numargs_ << std::endl;
112 asArray(name, cell(0));
113 optionalValues_.resize(9);
114 for (int i = 0; i < optionals_; ++i)
115 cell(optIdx(i)) = optionalValues_[i];
116 cell(defIdx()) = def;
117 cell(displayIdx()) = display;
121 MathMacroTemplate::MathMacroTemplate(docstring const & str)
122 : InsetMathNest(3), numargs_(0)
127 mathed_parse_cell(ar, str);
128 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
129 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
132 operator=( *(ar[0]->asMacroTemplate()) );
136 Inset * MathMacroTemplate::clone() const
138 return new MathMacroTemplate(*this);
142 docstring MathMacroTemplate::name() const
144 return asString(cell(0));
148 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
150 FontSetChanger dummy1(mi.base, from_ascii("mathnormal"));
151 StyleChanger dummy2(mi.base, LM_ST_TEXT);
154 MacroData const * macro = 0;
155 if (validName() && mi.macrocontext.has(name())) {
156 macro = &mi.macrocontext.get(name());
157 if (type_ == from_ascii("newcommand") || type_ == from_ascii("renewcommand")) {
158 // use the MacroData::redefinition_ information instead of MacroContext::has
159 // because the macro is known here already anyway to detect recursive definitions
160 type_ = macro->redefinition() ? from_ascii("renewcommand") : from_ascii("newcommand");
164 // create label "{#1}{#2}:="
167 for (; i < optionals_; ++i) {
168 label_.push_back(MathAtom(new InsetMathChar('[')));
169 label_.push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
170 label_.push_back(MathAtom(new InsetMathChar(']')));
172 for (; i < numargs_; ++i) {
174 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
175 label_.push_back(MathAtom(new InsetMathBrace(arg)));
177 label_.push_back(MathAtom(new InsetMathChar(':')));
178 label_.push_back(MathAtom(new InsetMathChar('=')));
189 cell(0).metrics(mi, dim0);
190 label_.metrics(mi, labeldim);
191 cell(defIdx()).metrics(mi, defdim);
192 cell(displayIdx()).metrics(mi, dspdim);
197 // calculate metrics taking all cells and labels into account
198 dim.wid = 2 + mathed_string_width(mi.base.font, from_ascii("\\")) +
201 defdim.width() + 16 + dspdim.width() + 2;
203 dim.asc = dim0.ascent();
204 dim.asc = std::max(dim.asc, labeldim.ascent());
205 dim.asc = std::max(dim.asc, defdim.ascent());
206 dim.asc = std::max(dim.asc, dspdim.ascent());
208 dim.des = dim0.descent();
209 dim.des = std::max(dim.des, labeldim.descent());
210 dim.des = std::max(dim.des, defdim.descent());
211 dim.des = std::max(dim.des, dspdim.descent());
213 // make the name cell vertically centered, and 5 pixel lines margin
214 int real_asc = dim.asc - dim0.ascent() / 2;
215 int real_des = dim.des + dim0.ascent() / 2;
216 dim.asc = std::max(real_asc, real_des) + dim0.ascent() / 2 + 5;
217 dim.des = std::max(real_asc, real_des) - dim0.ascent() / 2 + 5;
219 setDimCache(mi, dim);
223 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
225 FontSetChanger dummy1(pi.base, from_ascii("mathnormal"));
226 StyleChanger dummy2(pi.base, LM_ST_TEXT);
228 setPosCache(pi, x, y);
229 Dimension const dim = dimension(*pi.base.bv);
232 bool valid = validMacro();
233 FontInfo font = pi.base.font;
235 font.setColor(Color_latex);
237 font.setColor(Color_error);
240 int const a = y - dim.asc + 1;
241 int const w = dim.wid - 2;
242 int const h = dim.height() - 2;
243 pi.pain.rectangle(x, a, w, h, Color_mathframe);
247 pi.pain.text(x, y, from_ascii("\\"), font);
248 x += mathed_string_width(font, from_ascii("\\"));
251 PainterInfo namepi = pi;
252 namepi.base.font = font;
253 cell(0).draw(namepi, x, y);
254 x += cell(0).dimension(*pi.base.bv).width();
257 label_.draw(pi, x, y);
258 x += label_.dimension(*pi.base.bv).width();
261 cell(defIdx()).draw(pi, x + 2, y);
262 int const w1 = cell(defIdx()).dimension(*pi.base.bv).width();
263 pi.pain.rectangle(x, y - dim.ascent() + 3, w1 + 4, dim.height() - 6, Color_mathline);
267 cell(displayIdx()).draw(pi, x + 2, y);
268 int const w2 = cell(displayIdx()).dimension(*pi.base.bv).width();
269 pi.pain.rectangle(x, y - dim.ascent() + 3, w2 + 4, dim.height() - 6, Color_mathline);
273 void MathMacroTemplate::removeArguments(Cursor & cur, int from, int to) {
274 for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
277 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
279 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
280 int n = arg->number() - 1;
281 if (from <= n && n <= to) {
282 int cellSlice = cur.find(it.cell());
283 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
284 --cur[cellSlice].pos();
286 it.cell().erase(it.pos());
292 void MathMacroTemplate::shiftArguments(size_t from, int by) {
293 for (DocIterator it = doc_iterator_begin(*this); it; it.forwardChar()) {
296 if (it.nextInset()->lyxCode() != MATHMACROARG_CODE)
298 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
299 if (arg->number() >= from + 1)
300 arg->setNumber(arg->number() + by);
305 // FIXME: factorize those functions here with a functional style, maybe using Boost's function
308 void fixMacroInstancesAddRemove(Cursor const & from, docstring const & name, int n, bool insert) {
311 for (; dit; dit.forwardPos()) {
312 // only until a macro is redefined
313 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
314 MathMacroTemplate const & macroTemplate
315 = static_cast<MathMacroTemplate const &>(dit.inset());
316 if (macroTemplate.name() == name)
320 // in front of macro instance?
321 Inset * inset = dit.nextInset();
323 InsetMath * insetMath = inset->asInsetMath();
325 MathMacro * macro = insetMath->asMacro();
326 if (macro && macro->name() == name && macro->folded()) {
327 // found macro instance
329 macro->insertArgument(n);
331 macro->removeArgument(n);
339 void fixMacroInstancesOptional(Cursor const & from, docstring const & name, int optionals) {
342 for (; dit; dit.forwardPos()) {
343 // only until a macro is redefined
344 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
345 MathMacroTemplate const & macroTemplate
346 = static_cast<MathMacroTemplate const &>(dit.inset());
347 if (macroTemplate.name() == name)
351 // in front of macro instance?
352 Inset * inset = dit.nextInset();
354 InsetMath * insetMath = inset->asInsetMath();
356 MathMacro * macro = insetMath->asMacro();
357 if (macro && macro->name() == name && macro->folded()) {
358 // found macro instance
359 macro->setOptionals(optionals);
368 void fixMacroInstancesFunctional(Cursor const & from,
369 docstring const & name, F & fix) {
372 for (; dit; dit.forwardPos()) {
373 // only until a macro is redefined
374 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
375 MathMacroTemplate const & macroTemplate
376 = static_cast<MathMacroTemplate const &>(dit.inset());
377 if (macroTemplate.name() == name)
381 // in front of macro instance?
382 Inset * inset = dit.nextInset();
384 InsetMath * insetMath = inset->asInsetMath();
386 MathMacro * macro = insetMath->asMacro();
387 if (macro && macro->name() == name && macro->folded())
395 void MathMacroTemplate::insertParameter(Cursor & cur, int pos, bool greedy)
397 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
399 shiftArguments(pos, 1);
402 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
403 if (!cell(displayIdx()).empty())
404 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
408 dit.leaveInset(*this);
409 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
410 dit.top().forwardPos();
412 // fix macro instances
413 fixMacroInstancesAddRemove(dit, name(), pos, true);
419 void MathMacroTemplate::removeParameter(Cursor & cur, int pos, bool greedy)
421 if (pos < numargs_ && pos >= 0) {
423 removeArguments(cur, pos, pos);
424 shiftArguments(pos + 1, -1);
426 // removed optional parameter?
427 if (pos < optionals_) {
429 optionalValues_[pos] = cell(optIdx(pos));
430 cells_.erase(cells_.begin() + optIdx(pos));
433 int macroSlice = cur.find(this);
434 if (macroSlice != -1) {
435 if (cur[macroSlice].idx() == optIdx(pos)) {
436 cur.cutOff(macroSlice);
437 cur[macroSlice].idx() = 1;
438 cur[macroSlice].pos() = 0;
439 } else if (cur[macroSlice].idx() > optIdx(pos))
440 --cur[macroSlice].idx();
445 // fix macro instances
446 //boost::function<void(MathMacro *)> fix = _1->insertArgument(n);
447 //fixMacroInstancesFunctional(dit, name(), fix);
449 dit.leaveInset(*this);
450 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
451 dit.top().forwardPos();
452 fixMacroInstancesAddRemove(dit, name(), pos, false);
458 void MathMacroTemplate::makeOptional(Cursor & cur) {
459 if (numargs_ > 0 && optionals_ < numargs_) {
461 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
463 int macroSlice = cur.find(this);
464 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
465 ++cur[macroSlice].idx();
467 // fix macro instances
469 dit.leaveInset(*this);
470 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
471 dit.top().forwardPos();
472 fixMacroInstancesOptional(dit, name(), optionals_);
477 void MathMacroTemplate::makeNonOptional(Cursor & cur) {
478 if (numargs_ > 0 && optionals_ > 0) {
481 // store default value for later if the use changes his mind
482 optionalValues_[optionals_] = cell(optIdx(optionals_));
483 cells_.erase(cells_.begin() + optIdx(optionals_));
486 int macroSlice = cur.find(this);
487 if (macroSlice != -1) {
488 if (cur[macroSlice].idx() > optIdx(optionals_))
489 --cur[macroSlice].idx();
490 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
491 cur.cutOff(macroSlice);
492 cur[macroSlice].idx() = optIdx(optionals_);
493 cur[macroSlice].pos() = 0;
497 // fix macro instances
499 dit.leaveInset(*this);
500 // TODO: this was dit.forwardPosNoDescend before. Check that this is the same
501 dit.top().forwardPos();
502 fixMacroInstancesOptional(dit, name(), optionals_);
507 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
509 std::string const arg = to_utf8(cmd.argument());
510 switch (cmd.action) {
512 case LFUN_MATH_MACRO_ADD_PARAM:
514 cur.recordUndoFullDocument();
515 size_t pos = numargs_;
517 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
518 insertParameter(cur, pos);
523 case LFUN_MATH_MACRO_REMOVE_PARAM:
525 cur.recordUndoFullDocument();
526 size_t pos = numargs_ - 1;
528 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
529 removeParameter(cur, pos);
533 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
535 cur.recordUndoFullDocument();
536 insertParameter(cur, numargs_, true);
540 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
542 cur.recordUndoFullDocument();
543 removeParameter(cur, numargs_ - 1, true);
547 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
548 cur.recordUndoFullDocument();
552 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
553 cur.recordUndoFullDocument();
554 makeNonOptional(cur);
557 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
559 cur.recordUndoFullDocument();
560 insertParameter(cur, optionals_);
565 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
566 if (optionals_ > 0) {
567 cur.recordUndoFullDocument();
568 removeParameter(cur, optionals_ - 1);
571 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
572 if (numargs_ == optionals_) {
573 cur.recordUndoFullDocument();
574 insertParameter(cur, 0, true);
580 InsetMathNest::doDispatch(cur, cmd);
586 bool MathMacroTemplate::getStatus(Cursor & /*cur*/, FuncRequest const & cmd,
587 FuncStatus & flag) const
590 std::string const arg = to_utf8(cmd.argument());
591 switch (cmd.action) {
592 case LFUN_MATH_MACRO_ADD_PARAM: {
593 int num = numargs_ + 1;
595 num = convert<int>(arg);
596 bool on = (num >= optionals_ && numargs_ < 9 && num <= numargs_ + 1);
601 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
602 flag.enabled(numargs_ < 9);
605 case LFUN_MATH_MACRO_REMOVE_PARAM: {
608 num = convert<int>(arg);
609 flag.enabled(num >= 1 && num <= numargs_);
613 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
614 flag.enabled(numargs_ > 0 && optionals_ < numargs_ && type_ != from_ascii("def"));
617 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
618 flag.enabled(optionals_ > 0 && type_ != from_ascii("def"));
621 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
622 flag.enabled(numargs_ < 9);
625 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
626 flag.enabled(optionals_ > 0);
629 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
630 flag.enabled(numargs_ == 0 && type_ != from_ascii("def"));
641 void MathMacroTemplate::read(Buffer const &, Lexer & lex)
644 mathed_parse_cell(ar, lex.getStream());
645 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
646 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
647 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
650 operator=( *(ar[0]->asMacroTemplate()) );
654 void MathMacroTemplate::write(Buffer const &, std::ostream & os) const
656 odocstringstream oss;
657 WriteStream wi(oss, false, false);
658 oss << "FormulaMacro\n";
660 os << to_utf8(oss.str());
664 void MathMacroTemplate::write(WriteStream & os) const
666 if (type_ == "def") {
667 os << "\\def\\" << name().c_str();
668 for (int i = 1; i <= numargs_; ++i)
671 // newcommand or renewcommand
672 os << "\\" << type_.c_str() << "{\\" << name().c_str() << '}';
674 os << '[' << numargs_ << ']';
678 // in latex only one optional possible, simulate the others
679 if (optionals_ >= 1) {
680 docstring optValue = asString(cell(optIdx(0)));
681 if (optValue.find(']') != docstring::npos)
682 os << "[{" << cell(optIdx(0)) << "}]";
684 os << "[" << cell(optIdx(0)) << "]";
687 // in lyx we handle all optionals as real optionals
688 for (int i = 0; i < optionals_; ++i) {
689 docstring optValue = asString(cell(optIdx(i)));
690 if (optValue.find(']') != docstring::npos)
691 os << "[{" << cell(optIdx(i)) << "}]";
693 os << "[" << cell(optIdx(i)) << "]";
698 os << "{" << cell(defIdx()) << "}";
701 // writing .tex. done.
704 // writing .lyx, write special .tex export only if necessary
705 if (!cell(displayIdx()).empty())
706 os << "\n{" << cell(displayIdx()) << '}';
711 int MathMacroTemplate::plaintext(Buffer const & buf, odocstream & os,
712 OutputParams const &) const
714 static docstring const str = '[' + buf.B_("math macro") + ']';
721 bool MathMacroTemplate::validName() const
723 docstring n = name();
729 // converting back and force doesn't swallow anything?
732 if (asString(ma) != n)
736 for (size_t i = 0; i < n.size(); ++i) {
737 if (!(n[i] >= 'a' && n[i] <= 'z') &&
738 !(n[i] >= 'A' && n[i] <= 'Z'))
746 bool MathMacroTemplate::validMacro() const
752 MacroData MathMacroTemplate::asMacroData() const
754 std::vector<docstring> defaults(numargs_);
755 for (int i = 0; i < optionals_; ++i)
756 defaults[i] = asString(cell(optIdx(i)));
757 return MacroData(asString(cell(defIdx())), defaults,
758 numargs_, optionals_, asString(cell(displayIdx())), std::string());