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"
17 #include "MathCompletionList.h"
18 #include "MathExtern.h"
19 #include "MathStream.h"
20 #include "MathSupport.h"
23 #include "BufferView.h"
24 #include "CoordCache.h"
26 #include "FuncStatus.h"
27 #include "FuncRequest.h"
28 #include "LaTeXFeatures.h"
33 #include "frontends/Painter.h"
35 #include "support/debug.h"
36 #include "support/lassert.h"
37 #include "support/textutils.h"
47 /// A proxy for the macro values
48 class ArgumentProxy : public InsetMath {
51 ArgumentProxy(MathMacro & mathMacro, size_t idx)
52 : mathMacro_(mathMacro), idx_(idx) {}
54 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
55 : mathMacro_(mathMacro), idx_(idx)
60 void metrics(MetricsInfo & mi, Dimension & dim) const {
61 mathMacro_.macro()->unlock();
62 if (!mathMacro_.editMetrics(mi.base.bv)
63 && mathMacro_.cell(idx_).empty())
64 def_.metrics(mi, dim);
66 CoordCache & coords = mi.base.bv->coordCache();
67 dim = coords.arrays().dim(&mathMacro_.cell(idx_));
69 mathMacro_.macro()->lock();
72 void draw(PainterInfo & pi, int x, int y) const {
73 if (mathMacro_.editMetrics(pi.base.bv)) {
74 // The only way a ArgumentProxy can appear is in a cell of the
75 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
76 // mode and then, if the macro is edited the monochrome
77 // mode is entered by the MathMacro before calling the cells' draw
78 // method. Then eventually this code is reached and the proxy leaves
79 // monochrome mode temporarely. Hence, if it is not in monochrome
80 // here (and the assert triggers in pain.leaveMonochromeMode())
82 pi.pain.leaveMonochromeMode();
83 mathMacro_.cell(idx_).draw(pi, x, y);
84 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
85 } else if (mathMacro_.cell(idx_).empty()) {
86 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
89 mathMacro_.cell(idx_).draw(pi, x, y);
92 size_t idx() const { return idx_; }
94 int kerning(BufferView const * bv) const
96 if (mathMacro_.editMetrics(bv)
97 || !mathMacro_.cell(idx_).empty())
98 return mathMacro_.cell(idx_).kerning(bv);
100 return def_.kerning(bv);
105 Inset * clone() const
107 return new ArgumentProxy(*this);
110 MathMacro & mathMacro_;
118 MathMacro::MathMacro(docstring const & name)
119 : InsetMathNest(0), name_(name), displayMode_(DISPLAY_INIT),
120 attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
121 macro_(0), needsUpdate_(false), appetite_(9)
125 Inset * MathMacro::clone() const
127 MathMacro * copy = new MathMacro(*this);
128 copy->needsUpdate_ = true;
129 copy->expanded_.cell(0).clear();
134 docstring MathMacro::name() const
136 if (displayMode_ == DISPLAY_UNFOLDED && name_.size() != 1)
137 return asString(cell(0));
143 void MathMacro::cursorPos(BufferView const & bv,
144 CursorSlice const & sl, bool boundary, int & x, int & y) const
146 // We may have 0 arguments, but InsetMathNest requires at least one.
148 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
152 bool MathMacro::editMode(BufferView const * bv) const {
153 // find this in cursor trace
154 Cursor const & cur = bv->cursor();
155 for (size_t i = 0; i != cur.depth(); ++i)
156 if (&cur[i].inset() == this) {
157 // look if there is no other macro in edit mode above
159 for (; i != cur.depth(); ++i) {
160 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
161 if (macro && macro->displayMode() == DISPLAY_NORMAL)
165 // ok, none found, I am the highest one
173 bool MathMacro::editMetrics(BufferView const * bv) const
179 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
181 // set edit mode for which we will have calculated metrics. But only
182 editing_[mi.base.bv] = editMode(mi.base.bv);
184 // calculate new metrics according to display mode
185 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
186 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
187 } else if (displayMode_ == DISPLAY_UNFOLDED) {
188 cell(0).metrics(mi, dim);
190 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
191 dim.wid += bsdim.width() + 1;
192 dim.asc = max(bsdim.ascent(), dim.ascent());
193 dim.des = max(bsdim.descent(), dim.descent());
195 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
196 && editing_[mi.base.bv]) {
197 // Macro will be edited in a old-style list mode here:
199 LASSERT(macro_ != 0, /**/);
201 FontInfo labelFont = sane_font;
202 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
204 // get dimension of components of list view
206 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
207 nameDim.asc = fontDim.asc;
208 nameDim.des = fontDim.des;
211 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
212 argDim.asc = fontDim.asc;
213 argDim.des = fontDim.des;
216 definition_.metrics(mi, defDim);
219 dim.wid = nameDim.wid + defDim.wid;
220 dim.asc = max(nameDim.asc, defDim.asc);
221 dim.des = max(nameDim.des, defDim.des);
223 for (idx_type i = 0; i < nargs(); ++i) {
225 cell(i).metrics(mi, cdim);
226 dim.des += max(argDim.height(), cdim.height()) + 1;
227 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
230 // make space for box and markers, 2 pixels
234 metricsMarkers2(dim);
236 LASSERT(macro_ != 0, /**/);
238 // metrics are computed here for the cells,
239 // in the proxy we will then use the dim from the cache
240 InsetMathNest::metrics(mi);
242 // calculate metrics finally
244 expanded_.cell(0).metrics(mi, dim);
247 // calculate dimension with label while editing
248 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
249 && editing_[mi.base.bv]) {
250 FontInfo font = mi.base.font;
251 augmentFont(font, from_ascii("lyxtex"));
253 mathed_string_dim(font, name(), namedim);
255 dim.wid += 2 + namedim.wid + 2 + 2;
256 dim.asc = max(dim.asc, namedim.asc) + 2;
257 dim.des = max(dim.des, namedim.des) + 2;
259 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
260 dim.asc += 1 + namedim.height() + 1;
268 int MathMacro::kerning(BufferView const * bv) const {
269 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
270 return expanded_.kerning(bv);
276 void MathMacro::updateMacro(MacroContext const & mc)
279 macro_ = mc.get(name());
280 if (macro_ && macroBackup_ != *macro_) {
281 macroBackup_ = *macro_;
290 void MathMacro::updateRepresentation()
297 requires_ = macro_->requires();
299 // non-normal mode? We are done!
300 if (displayMode_ != DISPLAY_NORMAL)
307 needsUpdate_ = false;
309 // get default values of macro
310 vector<docstring> const & defaults = macro_->defaults();
312 // create MathMacroArgumentValue objects pointing to the cells of the macro
313 vector<MathData> values(nargs());
314 for (size_t i = 0; i < nargs(); ++i) {
315 ArgumentProxy * proxy;
316 if (i < defaults.size())
317 proxy = new ArgumentProxy(*this, i, defaults[i]);
319 proxy = new ArgumentProxy(*this, i);
320 values[i].insert(0, MathAtom(proxy));
323 // expanding macro with the values
324 macro_->expand(values, expanded_.cell(0));
325 // get definition for list edit mode
326 docstring const & display = macro_->display();
327 asArray(display.empty() ? macro_->definition() : display, definition_);
331 void MathMacro::draw(PainterInfo & pi, int x, int y) const
333 Dimension const dim = dimension(*pi.base.bv);
335 setPosCache(pi, x, y);
339 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
340 FontSetChanger dummy(pi.base, "lyxtex");
341 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
342 } else if (displayMode_ == DISPLAY_UNFOLDED) {
343 FontSetChanger dummy(pi.base, "lyxtex");
344 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
345 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
346 cell(0).draw(pi, x, y);
347 drawMarkers(pi, 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()));
519 // validate the cells and the definition
520 if (displayMode() == DISPLAY_NORMAL) {
521 definition_.validate(features);
522 InsetMathNest::validate(features);
527 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
529 cur.updateFlags(Update::SinglePar);
530 InsetMathNest::edit(cur, front, entry_from);
534 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
536 // We may have 0 arguments, but InsetMathNest requires at least one.
538 cur.updateFlags(Update::SinglePar);
539 return InsetMathNest::editXY(cur, x, y);
545 void MathMacro::removeArgument(Inset::pos_type pos) {
546 if (displayMode_ == DISPLAY_NORMAL) {
547 LASSERT(size_t(pos) < cells_.size(), /**/);
548 cells_.erase(cells_.begin() + pos);
549 if (size_t(pos) < attachedArgsNum_)
551 if (size_t(pos) < optionals_) {
560 void MathMacro::insertArgument(Inset::pos_type pos) {
561 if (displayMode_ == DISPLAY_NORMAL) {
562 LASSERT(size_t(pos) <= cells_.size(), /**/);
563 cells_.insert(cells_.begin() + pos, MathData());
564 if (size_t(pos) < attachedArgsNum_)
566 if (size_t(pos) < optionals_)
574 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
576 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
579 // strip off empty cells, but not more than arity-attachedArgsNum_
582 for (i = cells_.size(); i > attachedArgsNum_; --i)
583 if (!cell(i - 1).empty()) break;
587 attachedArgsNum_ = 0;
588 expanded_.cell(0) = MathData();
595 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
597 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
599 attachedArgsNum_ = args.size();
600 cells_.resize(arity);
601 expanded_.cell(0) = MathData();
602 optionals_ = optionals;
608 bool MathMacro::idxFirst(Cursor & cur) const
610 cur.updateFlags(Update::SinglePar);
611 return InsetMathNest::idxFirst(cur);
615 bool MathMacro::idxLast(Cursor & cur) const
617 cur.updateFlags(Update::SinglePar);
618 return InsetMathNest::idxLast(cur);
622 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
624 cur.updateFlags(Update::Force);
625 return InsetMathNest::notifyCursorLeaves(old, cur);
629 void MathMacro::fold(Cursor & cur)
631 if (!nextFoldMode_) {
632 nextFoldMode_ = true;
633 cur.updateFlags(Update::SinglePar);
638 void MathMacro::unfold(Cursor & cur)
641 nextFoldMode_ = false;
642 cur.updateFlags(Update::SinglePar);
647 bool MathMacro::folded() const
649 return nextFoldMode_;
653 void MathMacro::write(WriteStream & os) const
655 MathEnsurer ensurer(os, macro_ != 0, true);
658 if (displayMode_ != DISPLAY_NORMAL) {
659 os << "\\" << name();
660 if (name().size() != 1 || isAlphaASCII(name()[0]))
661 os.pendingSpace(true);
666 LASSERT(macro_, /**/);
668 // optional arguments make macros fragile
669 if (optionals_ > 0 && os.fragile())
672 os << "\\" << name();
675 // Optional arguments:
676 // First find last non-empty optional argument
677 idx_type emptyOptFrom = 0;
679 for (; i < cells_.size() && i < optionals_; ++i) {
680 if (!cell(i).empty())
681 emptyOptFrom = i + 1;
684 // print out optionals
685 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
687 os << "[" << cell(i) << "]";
690 // skip the tailing empty optionals
693 // Print remaining macros
694 for (; i < cells_.size(); ++i) {
695 if (cell(i).size() == 1
696 && cell(i)[0].nucleus()->asCharInset()) {
701 os << "{" << cell(i) << "}";
705 // add space if there was no argument
707 os.pendingSpace(true);
711 void MathMacro::maple(MapleStream & os) const
713 lyx::maple(expanded_.cell(0), os);
717 void MathMacro::mathmlize(MathStream & os) const
719 lyx::mathmlize(expanded_.cell(0), os);
723 void MathMacro::octave(OctaveStream & os) const
725 lyx::octave(expanded_.cell(0), os);
729 void MathMacro::infoize(odocstream & os) const
731 os << "Macro: " << name();
735 void MathMacro::infoize2(odocstream & os) const
737 os << "Macro: " << name();
742 bool MathMacro::completionSupported(Cursor const & cur) const
744 if (displayMode() != DISPLAY_UNFOLDED)
745 return InsetMathNest::completionSupported(cur);
747 return lyxrc.completion_popup_math
748 && displayMode() == DISPLAY_UNFOLDED
749 && cur.bv().cursor().pos() == int(name().size());
753 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
755 if (displayMode() != DISPLAY_UNFOLDED)
756 return InsetMathNest::inlineCompletionSupported(cur);
758 return lyxrc.completion_inline_math
759 && displayMode() == DISPLAY_UNFOLDED
760 && cur.bv().cursor().pos() == int(name().size());
764 bool MathMacro::automaticInlineCompletion() const
766 if (displayMode() != DISPLAY_UNFOLDED)
767 return InsetMathNest::automaticInlineCompletion();
769 return lyxrc.completion_inline_math;
773 bool MathMacro::automaticPopupCompletion() const
775 if (displayMode() != DISPLAY_UNFOLDED)
776 return InsetMathNest::automaticPopupCompletion();
778 return lyxrc.completion_popup_math;
782 CompletionList const *
783 MathMacro::createCompletionList(Cursor const & cur) const
785 if (displayMode() != DISPLAY_UNFOLDED)
786 return InsetMathNest::createCompletionList(cur);
788 return new MathCompletionList(cur.bv().cursor());
792 docstring MathMacro::completionPrefix(Cursor const & cur) const
794 if (displayMode() != DISPLAY_UNFOLDED)
795 return InsetMathNest::completionPrefix(cur);
797 if (!completionSupported(cur))
800 return "\\" + name();
804 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
807 if (displayMode() != DISPLAY_UNFOLDED)
808 return InsetMathNest::insertCompletion(cur, s, finished);
810 if (!completionSupported(cur))
814 docstring newName = name() + s;
815 asArray(newName, cell(0));
816 cur.bv().cursor().pos() = name().size();
817 cur.updateFlags(Update::SinglePar);
821 cur.bv().cursor().pop();
822 ++cur.bv().cursor().pos();
823 cur.updateFlags(Update::SinglePar);
830 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
831 Dimension & dim) const
833 if (displayMode() != DISPLAY_UNFOLDED)
834 InsetMathNest::completionPosAndDim(cur, x, y, dim);
836 // get inset dimensions
837 dim = cur.bv().coordCache().insets().dim(this);
838 // FIXME: these 3 are no accurate, but should depend on the font.
839 // Now the popup jumps down if you enter a char with descent > 0.
845 = cur.bv().coordCache().insets().xy(this);