3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
8 * \author Stefan Schimanski
10 * Full author contact details are available in file CREDITS.
15 #include "MathMacro.h"
16 #include "MathSupport.h"
17 #include "MathExtern.h"
18 #include "MathStream.h"
21 #include "BufferView.h"
22 #include "CoordCache.h"
24 #include "FuncStatus.h"
25 #include "FuncRequest.h"
26 #include "LaTeXFeatures.h"
31 #include "frontends/Painter.h"
33 #include "support/debug.h"
43 /// A proxy for the macro values
44 class ArgumentProxy : public InsetMath {
47 ArgumentProxy(MathMacro & mathMacro, size_t idx)
48 : mathMacro_(mathMacro), idx_(idx) {}
50 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
51 : mathMacro_(mathMacro), idx_(idx)
56 void metrics(MetricsInfo & mi, Dimension & dim) const {
57 mathMacro_.macro()->unlock();
58 if (!mathMacro_.editMetrics(mi.base.bv)
59 && mathMacro_.cell(idx_).empty())
60 def_.metrics(mi, dim);
62 CoordCache & coords = mi.base.bv->coordCache();
63 dim = coords.arrays().dim(&mathMacro_.cell(idx_));
65 mathMacro_.macro()->lock();
68 void draw(PainterInfo & pi, int x, int y) const {
69 if (mathMacro_.editMetrics(pi.base.bv)) {
70 // The only way a ArgumentProxy can appear is in a cell of the
71 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
72 // mode and then, if the macro is edited the monochrome
73 // mode is entered by the MathMacro before calling the cells' draw
74 // method. Then eventually this code is reached and the proxy leaves
75 // monochrome mode temporarely. Hence, if it is not in monochrome
76 // here (and the assert triggers in pain.leaveMonochromeMode())
78 pi.pain.leaveMonochromeMode();
79 mathMacro_.cell(idx_).draw(pi, x, y);
80 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
81 } else if (mathMacro_.cell(idx_).empty()) {
82 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
85 mathMacro_.cell(idx_).draw(pi, x, y);
88 size_t idx() const { return idx_; }
90 int kerning(BufferView const * bv) const
92 if (mathMacro_.editMetrics(bv)
93 || !mathMacro_.cell(idx_).empty())
94 return mathMacro_.cell(idx_).kerning(bv);
96 return def_.kerning(bv);
101 Inset * clone() const
103 return new ArgumentProxy(*this);
106 MathMacro & mathMacro_;
114 MathMacro::MathMacro(docstring const & name)
115 : InsetMathNest(0), name_(name), displayMode_(DISPLAY_INIT),
116 attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
117 macro_(0), needsUpdate_(false), appetite_(9)
121 Inset * MathMacro::clone() const
123 MathMacro * copy = new MathMacro(*this);
124 copy->needsUpdate_ = true;
125 copy->expanded_.cell(0).clear();
130 docstring MathMacro::name() const
132 if (displayMode_ == DISPLAY_UNFOLDED)
133 return asString(cell(0));
139 void MathMacro::cursorPos(BufferView const & bv,
140 CursorSlice const & sl, bool boundary, int & x, int & y) const
142 // We may have 0 arguments, but InsetMathNest requires at least one.
144 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
148 bool MathMacro::editMode(BufferView const * bv) const {
149 // find this in cursor trace
150 Cursor const & cur = bv->cursor();
151 for (size_t i = 0; i != cur.depth(); ++i)
152 if (&cur[i].inset() == this) {
153 // look if there is no other macro in edit mode above
155 for (; i != cur.depth(); ++i) {
156 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
157 if (macro && macro->displayMode() == DISPLAY_NORMAL)
161 // ok, none found, I am the highest one
169 bool MathMacro::editMetrics(BufferView const * bv) const
175 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
177 // set edit mode for which we will have calculated metrics. But only
178 editing_[mi.base.bv] = editMode(mi.base.bv);
180 // calculate new metrics according to display mode
181 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
182 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
183 } else if (displayMode_ == DISPLAY_UNFOLDED) {
184 cell(0).metrics(mi, dim);
186 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
187 dim.wid += bsdim.width() + 1;
188 dim.asc = max(bsdim.ascent(), dim.ascent());
189 dim.des = max(bsdim.descent(), dim.descent());
191 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
192 && editing_[mi.base.bv]) {
193 // Macro will be edited in a old-style list mode here:
195 BOOST_ASSERT(macro_ != 0);
197 FontInfo labelFont = sane_font;
198 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
200 // get dimension of components of list view
202 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
203 nameDim.asc = fontDim.asc;
204 nameDim.des = fontDim.des;
207 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
208 argDim.asc = fontDim.asc;
209 argDim.des = fontDim.des;
212 definition_.metrics(mi, defDim);
215 dim.wid = nameDim.wid + defDim.wid;
216 dim.asc = max(nameDim.asc, defDim.asc);
217 dim.des = max(nameDim.des, defDim.des);
219 for (idx_type i = 0; i < nargs(); ++i) {
221 cell(i).metrics(mi, cdim);
222 dim.des += max(argDim.height(), cdim.height()) + 1;
223 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
226 // make space for box and markers, 2 pixels
230 metricsMarkers2(dim);
232 BOOST_ASSERT(macro_ != 0);
234 // metrics are computed here for the cells,
235 // in the proxy we will then use the dim from the cache
236 InsetMathNest::metrics(mi);
238 // calculate metrics finally
240 expanded_.cell(0).metrics(mi, dim);
243 // calculate dimension with label while editing
244 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
245 && editing_[mi.base.bv]) {
246 FontInfo font = mi.base.font;
247 augmentFont(font, from_ascii("lyxtex"));
249 mathed_string_dim(font, name(), namedim);
251 dim.wid += 2 + namedim.wid + 2 + 2;
252 dim.asc = max(dim.asc, namedim.asc) + 2;
253 dim.des = max(dim.des, namedim.des) + 2;
255 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
256 dim.asc += 1 + namedim.height() + 1;
264 int MathMacro::kerning(BufferView const * bv) const {
265 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
266 return expanded_.kerning(bv);
272 void MathMacro::updateMacro(MacroContext const & mc)
275 macro_ = mc.get(name());
276 if (macro_ && macroBackup_ != *macro_) {
277 macroBackup_ = *macro_;
286 void MathMacro::updateRepresentation()
293 requires_ = macro_->requires();
295 // non-normal mode? We are done!
296 if (displayMode_ != DISPLAY_NORMAL)
303 needsUpdate_ = false;
305 // get default values of macro
306 vector<docstring> const & defaults = macro_->defaults();
308 // create MathMacroArgumentValue objects pointing to the cells of the macro
309 vector<MathData> values(nargs());
310 for (size_t i = 0; i < nargs(); ++i) {
311 ArgumentProxy * proxy;
312 if (i < defaults.size())
313 proxy = new ArgumentProxy(*this, i, defaults[i]);
315 proxy = new ArgumentProxy(*this, i);
316 values[i].insert(0, MathAtom(proxy));
319 // expanding macro with the values
320 macro_->expand(values, expanded_.cell(0));
321 // get definition for list edit mode
322 docstring const & display = macro_->display();
323 asArray(display.empty() ? macro_->definition() : display, definition_);
327 void MathMacro::draw(PainterInfo & pi, int x, int y) const
329 Dimension const dim = dimension(*pi.base.bv);
331 setPosCache(pi, x, y);
335 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
336 PainterInfo pi2(pi.base.bv, pi.pain);
337 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
338 //pi2.base.style = LM_ST_TEXT;
339 pi2.pain.text(x, y, from_ascii("\\") + name(), pi2.base.font);
340 } else if (displayMode_ == DISPLAY_UNFOLDED) {
341 PainterInfo pi2(pi.base.bv, pi.pain);
342 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
343 //pi2.base.style = LM_ST_TEXT;
344 pi2.pain.text(x, y, from_ascii("\\"), pi2.base.font);
345 x += mathed_string_width(pi2.base.font, from_ascii("\\")) + 1;
346 cell(0).draw(pi2, x, y);
347 drawMarkers(pi2, expx, expy);
348 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
349 && editing_[pi.base.bv]) {
350 // Macro will be edited in a old-style list mode here:
352 CoordCache & coords = pi.base.bv->coordCache();
353 FontInfo const & labelFont = sane_font;
355 // markers and box needs two pixels
358 // get maximal font height
360 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
363 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
364 pi.pain.text(x, y, label, labelFont);
365 x += mathed_string_width(labelFont, label);
368 definition_.draw(pi, x, y);
370 = coords.arrays().dim(&definition_);
371 y += max(fontDim.des, defDim.des);
374 docstring str = from_ascii("#9");
375 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
376 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
378 for (idx_type i = 0; i < nargs(); ++i) {
381 = coords.arrays().dim(&cell(i));
383 y += max(fontDim.asc, cdim.asc) + 1;
387 pi.pain.text(x, y, str, labelFont);
389 pi.pain.text(x, y, from_ascii(":"), labelFont);
393 cell(i).draw(pi, x, y);
396 y += max(fontDim.des, cdim.des);
399 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
400 dim.height() - 2, Color_mathmacroframe);
401 drawMarkers2(pi, expx, expy);
403 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
406 for (size_t i = 0; i < nargs(); ++i)
407 cell(i).setXY(*pi.base.bv, x, y);
409 if (drawBox && editing_[pi.base.bv]) {
410 // draw header and rectangle around
411 FontInfo font = pi.base.font;
412 augmentFont(font, from_ascii("lyxtex"));
413 font.setSize(FONT_SIZE_TINY);
414 font.setColor(Color_mathmacrolabel);
416 mathed_string_dim(font, name(), namedim);
418 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
419 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
420 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
423 if (editing_[pi.base.bv]) {
424 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
425 expanded_.cell(0).draw(pi, expx, expy);
426 pi.pain.leaveMonochromeMode();
429 pi.pain.rectangle(x, y - dim.asc, dim.wid,
430 dim.height(), Color_mathmacroframe);
432 expanded_.cell(0).draw(pi, expx, expy);
435 drawMarkers(pi, x, y);
438 // edit mode changed?
439 if (editing_[pi.base.bv] != editMode(pi.base.bv))
440 pi.base.bv->cursor().updateFlags(Update::SinglePar);
444 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
446 // We may have 0 arguments, but InsetMathNest requires at least one.
447 if (cells_.size() > 0)
448 InsetMathNest::drawSelection(pi, x, y);
452 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
454 if (displayMode_ != mode) {
455 // transfer name if changing from or to DISPLAY_UNFOLDED
456 if (mode == DISPLAY_UNFOLDED) {
458 asArray(name_, cell(0));
459 } else if (displayMode_ == DISPLAY_UNFOLDED) {
460 name_ = asString(cell(0));
468 // the interactive init mode is non-greedy by default
470 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
472 appetite_ = size_t(appetite);
476 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
478 if (nextFoldMode_ == true && macro_ && !macro_->locked())
479 return DISPLAY_NORMAL;
481 return DISPLAY_UNFOLDED;
485 bool MathMacro::validName() const
487 docstring n = name();
493 // converting back and force doesn't swallow anything?
496 if (asString(ma) != n)
500 for (size_t i = 0; i<n.size(); ++i) {
501 if (!(n[i] >= 'a' && n[i] <= 'z')
502 && !(n[i] >= 'A' && n[i] <= 'Z')
511 void MathMacro::validate(LaTeXFeatures & features) const
513 if (!requires_.empty())
514 features.require(requires_);
516 if (name() == "binom" || name() == "mathcircumflex")
517 features.require(to_utf8(name()));
521 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
523 cur.updateFlags(Update::SinglePar);
524 InsetMathNest::edit(cur, front, entry_from);
528 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
530 // We may have 0 arguments, but InsetMathNest requires at least one.
532 cur.updateFlags(Update::SinglePar);
533 return InsetMathNest::editXY(cur, x, y);
539 void MathMacro::removeArgument(Inset::pos_type pos) {
540 if (displayMode_ == DISPLAY_NORMAL) {
541 BOOST_ASSERT(size_t(pos) < cells_.size());
542 cells_.erase(cells_.begin() + pos);
543 if (size_t(pos) < attachedArgsNum_)
545 if (size_t(pos) < optionals_) {
554 void MathMacro::insertArgument(Inset::pos_type pos) {
555 if (displayMode_ == DISPLAY_NORMAL) {
556 BOOST_ASSERT(size_t(pos) <= cells_.size());
557 cells_.insert(cells_.begin() + pos, MathData());
558 if (size_t(pos) < attachedArgsNum_)
560 if (size_t(pos) < optionals_)
568 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
570 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
573 // strip off empty cells, but not more than arity-attachedArgsNum_
576 for (i = cells_.size(); i > attachedArgsNum_; --i)
577 if (!cell(i - 1).empty()) break;
581 attachedArgsNum_ = 0;
582 expanded_.cell(0) = MathData();
589 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
591 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
593 attachedArgsNum_ = args.size();
594 cells_.resize(arity);
595 expanded_.cell(0) = MathData();
596 optionals_ = optionals;
602 bool MathMacro::idxFirst(Cursor & cur) const
604 cur.updateFlags(Update::SinglePar);
605 return InsetMathNest::idxFirst(cur);
609 bool MathMacro::idxLast(Cursor & cur) const
611 cur.updateFlags(Update::SinglePar);
612 return InsetMathNest::idxLast(cur);
616 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
618 cur.updateFlags(Update::Force);
619 return InsetMathNest::notifyCursorLeaves(old, cur);
623 void MathMacro::fold(Cursor & cur)
625 if (!nextFoldMode_) {
626 nextFoldMode_ = true;
627 cur.updateFlags(Update::SinglePar);
632 void MathMacro::unfold(Cursor & cur)
635 nextFoldMode_ = false;
636 cur.updateFlags(Update::SinglePar);
641 bool MathMacro::folded() const
643 return nextFoldMode_;
647 void MathMacro::write(WriteStream & os) const
650 if (displayMode_ != DISPLAY_NORMAL) {
651 os << "\\" << name() << " ";
652 os.pendingSpace(true);
657 BOOST_ASSERT(macro_);
659 // optional arguments make macros fragile
660 if (optionals_ > 0 && os.fragile())
663 os << "\\" << name();
666 // Optional arguments:
667 // First find last non-empty optional argument
668 idx_type emptyOptFrom = 0;
670 for (; i < cells_.size() && i < optionals_; ++i) {
671 if (!cell(i).empty())
672 emptyOptFrom = i + 1;
675 // print out optionals
676 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
678 os << "[" << cell(i) << "]";
681 // skip the tailing empty optionals
684 // Print remaining macros
685 for (; i < cells_.size(); ++i) {
686 if (cell(i).size() == 1
687 && cell(i)[0].nucleus()->asCharInset()) {
692 os << "{" << cell(i) << "}";
696 // add space if there was no argument
698 os.pendingSpace(true);
702 void MathMacro::maple(MapleStream & os) const
704 lyx::maple(expanded_.cell(0), os);
708 void MathMacro::mathmlize(MathStream & os) const
710 lyx::mathmlize(expanded_.cell(0), os);
714 void MathMacro::octave(OctaveStream & os) const
716 lyx::octave(expanded_.cell(0), os);
720 void MathMacro::infoize(odocstream & os) const
722 os << "Macro: " << name();
726 void MathMacro::infoize2(odocstream & os) const
728 os << "Macro: " << name();
733 bool MathMacro::completionSupported(Cursor const & cur) const
735 if (displayMode() != DISPLAY_UNFOLDED)
736 return InsetMathNest::completionSupported(cur);
738 return lyxrc.completion_popup_math
739 && displayMode() == DISPLAY_UNFOLDED
740 && cur.bv().cursor().pos() == int(name().size());
744 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
746 if (displayMode() != DISPLAY_UNFOLDED)
747 return InsetMathNest::inlineCompletionSupported(cur);
749 return lyxrc.completion_inline_math
750 && displayMode() == DISPLAY_UNFOLDED
751 && cur.bv().cursor().pos() == int(name().size());
755 bool MathMacro::automaticInlineCompletion() const
757 if (displayMode() != DISPLAY_UNFOLDED)
758 return InsetMathNest::automaticInlineCompletion();
760 return lyxrc.completion_inline_math;
764 bool MathMacro::automaticPopupCompletion() const
766 if (displayMode() != DISPLAY_UNFOLDED)
767 return InsetMathNest::automaticPopupCompletion();
769 return lyxrc.completion_popup_math;
773 Inset::CompletionList const *
774 MathMacro::createCompletionList(Cursor const & cur) const
776 if (displayMode() != DISPLAY_UNFOLDED)
777 return InsetMathNest::createCompletionList(cur);
779 return new MathCompletionList(cur.bv().cursor());
783 docstring MathMacro::completionPrefix(Cursor const & cur) const
785 if (displayMode() != DISPLAY_UNFOLDED)
786 return InsetMathNest::completionPrefix(cur);
788 if (!completionSupported(cur))
791 return "\\" + name();
795 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
798 if (displayMode() != DISPLAY_UNFOLDED)
799 return InsetMathNest::insertCompletion(cur, s, finished);
801 if (!completionSupported(cur))
805 docstring newName = name() + s;
806 asArray(newName, cell(0));
807 cur.bv().cursor().pos() = name().size();
808 cur.updateFlags(Update::SinglePar);
812 cur.bv().cursor().pop();
813 ++cur.bv().cursor().pos();
814 cur.updateFlags(Update::SinglePar);
821 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
822 Dimension & dim) const
824 if (displayMode() != DISPLAY_UNFOLDED)
825 InsetMathNest::completionPosAndDim(cur, x, y, dim);
827 // get inset dimensions
828 dim = cur.bv().coordCache().insets().dim(this);
829 // FIXME: these 3 are no accurate, but should depend on the font.
830 // Now the popup jumps down if you enter a char with descent > 0.
836 = cur.bv().coordCache().insets().xy(this);