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 "InsetMathChar.h"
18 #include "MathCompletionList.h"
19 #include "MathExtern.h"
20 #include "MathStream.h"
21 #include "MathSupport.h"
24 #include "BufferView.h"
25 #include "CoordCache.h"
27 #include "FuncStatus.h"
28 #include "FuncRequest.h"
29 #include "LaTeXFeatures.h"
34 #include "frontends/Painter.h"
36 #include "support/debug.h"
37 #include "support/lassert.h"
38 #include "support/textutils.h"
48 /// A proxy for the macro values
49 class ArgumentProxy : public InsetMath {
52 ArgumentProxy(MathMacro & mathMacro, size_t idx)
53 : mathMacro_(mathMacro), idx_(idx) {}
55 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
56 : mathMacro_(mathMacro), idx_(idx)
61 void metrics(MetricsInfo & mi, Dimension & dim) const {
62 mathMacro_.macro()->unlock();
63 mathMacro_.cell(idx_).metrics(mi, dim);
65 if (!mathMacro_.editMetrics(mi.base.bv)
66 && mathMacro_.cell(idx_).empty())
67 def_.metrics(mi, dim);
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 // calculate metrics, hoping that all cells are seen
240 expanded_.cell(0).metrics(mi, dim);
242 // otherwise do a manual metrics call
243 CoordCache & coords = mi.base.bv->coordCache();
244 for (idx_type i = 0; i < nargs(); ++i) {
245 if (!coords.arrays().has(&cell(i))) {
247 cell(i).metrics(mi, tdim);
252 // calculate dimension with label while editing
253 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
254 && editing_[mi.base.bv]) {
255 FontInfo font = mi.base.font;
256 augmentFont(font, from_ascii("lyxtex"));
258 mathed_string_dim(font, name(), namedim);
260 dim.wid += 2 + namedim.wid + 2 + 2;
261 dim.asc = max(dim.asc, namedim.asc) + 2;
262 dim.des = max(dim.des, namedim.des) + 2;
264 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
265 dim.asc += 1 + namedim.height() + 1;
273 int MathMacro::kerning(BufferView const * bv) const {
274 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
275 return expanded_.kerning(bv);
281 void MathMacro::updateMacro(MacroContext const & mc)
284 macro_ = mc.get(name());
285 if (macro_ && macroBackup_ != *macro_) {
286 macroBackup_ = *macro_;
295 void MathMacro::updateRepresentation()
302 requires_ = macro_->requires();
304 // non-normal mode? We are done!
305 if (displayMode_ != DISPLAY_NORMAL)
312 needsUpdate_ = false;
314 // get default values of macro
315 vector<docstring> const & defaults = macro_->defaults();
317 // create MathMacroArgumentValue objects pointing to the cells of the macro
318 vector<MathData> values(nargs());
319 for (size_t i = 0; i < nargs(); ++i) {
320 ArgumentProxy * proxy;
321 if (i < defaults.size())
322 proxy = new ArgumentProxy(*this, i, defaults[i]);
324 proxy = new ArgumentProxy(*this, i);
325 values[i].insert(0, MathAtom(proxy));
328 // expanding macro with the values
329 macro_->expand(values, expanded_.cell(0));
330 // get definition for list edit mode
331 docstring const & display = macro_->display();
332 asArray(display.empty() ? macro_->definition() : display, definition_);
336 void MathMacro::draw(PainterInfo & pi, int x, int y) const
338 Dimension const dim = dimension(*pi.base.bv);
340 setPosCache(pi, x, y);
344 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
345 FontSetChanger dummy(pi.base, "lyxtex");
346 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
347 } else if (displayMode_ == DISPLAY_UNFOLDED) {
348 FontSetChanger dummy(pi.base, "lyxtex");
349 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
350 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
351 cell(0).draw(pi, x, y);
352 drawMarkers(pi, expx, expy);
353 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
354 && editing_[pi.base.bv]) {
355 // Macro will be edited in a old-style list mode here:
357 CoordCache & coords = pi.base.bv->coordCache();
358 FontInfo const & labelFont = sane_font;
360 // markers and box needs two pixels
363 // get maximal font height
365 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
368 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
369 pi.pain.text(x, y, label, labelFont);
370 x += mathed_string_width(labelFont, label);
373 definition_.draw(pi, x, y);
375 = coords.arrays().dim(&definition_);
376 y += max(fontDim.des, defDim.des);
379 docstring str = from_ascii("#9");
380 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
381 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
383 for (idx_type i = 0; i < nargs(); ++i) {
386 = coords.arrays().dim(&cell(i));
388 y += max(fontDim.asc, cdim.asc) + 1;
392 pi.pain.text(x, y, str, labelFont);
394 pi.pain.text(x, y, from_ascii(":"), labelFont);
398 cell(i).draw(pi, x, y);
401 y += max(fontDim.des, cdim.des);
404 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
405 dim.height() - 2, Color_mathmacroframe);
406 drawMarkers2(pi, expx, expy);
408 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
411 for (size_t i = 0; i < nargs(); ++i)
412 cell(i).setXY(*pi.base.bv, x, y);
414 if (drawBox && editing_[pi.base.bv]) {
415 // draw header and rectangle around
416 FontInfo font = pi.base.font;
417 augmentFont(font, from_ascii("lyxtex"));
418 font.setSize(FONT_SIZE_TINY);
419 font.setColor(Color_mathmacrolabel);
421 mathed_string_dim(font, name(), namedim);
423 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
424 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
425 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
428 if (editing_[pi.base.bv]) {
429 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
430 expanded_.cell(0).draw(pi, expx, expy);
431 pi.pain.leaveMonochromeMode();
434 pi.pain.rectangle(x, y - dim.asc, dim.wid,
435 dim.height(), Color_mathmacroframe);
437 expanded_.cell(0).draw(pi, expx, expy);
440 drawMarkers(pi, x, y);
443 // edit mode changed?
444 if (editing_[pi.base.bv] != editMode(pi.base.bv))
445 pi.base.bv->cursor().updateFlags(Update::SinglePar);
449 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
451 // We may have 0 arguments, but InsetMathNest requires at least one.
452 if (cells_.size() > 0)
453 InsetMathNest::drawSelection(pi, x, y);
457 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
459 if (displayMode_ != mode) {
460 // transfer name if changing from or to DISPLAY_UNFOLDED
461 if (mode == DISPLAY_UNFOLDED) {
463 asArray(name_, cell(0));
464 } else if (displayMode_ == DISPLAY_UNFOLDED) {
465 name_ = asString(cell(0));
473 // the interactive init mode is non-greedy by default
475 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
477 appetite_ = size_t(appetite);
481 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
483 if (nextFoldMode_ == true && macro_ && !macro_->locked())
484 return DISPLAY_NORMAL;
486 return DISPLAY_UNFOLDED;
490 bool MathMacro::validName() const
492 docstring n = name();
498 // converting back and force doesn't swallow anything?
501 if (asString(ma) != n)
505 for (size_t i = 0; i<n.size(); ++i) {
506 if (!(n[i] >= 'a' && n[i] <= 'z')
507 && !(n[i] >= 'A' && n[i] <= 'Z')
516 void MathMacro::validate(LaTeXFeatures & features) const
518 if (!requires_.empty())
519 features.require(requires_);
521 if (name() == "binom")
522 features.require("binom");
524 // validate the cells and the definition
525 if (displayMode() == DISPLAY_NORMAL) {
526 definition_.validate(features);
527 InsetMathNest::validate(features);
532 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
534 cur.updateFlags(Update::SinglePar);
535 InsetMathNest::edit(cur, front, entry_from);
539 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
541 // We may have 0 arguments, but InsetMathNest requires at least one.
543 cur.updateFlags(Update::SinglePar);
544 return InsetMathNest::editXY(cur, x, y);
550 void MathMacro::removeArgument(Inset::pos_type pos) {
551 if (displayMode_ == DISPLAY_NORMAL) {
552 LASSERT(size_t(pos) < cells_.size(), /**/);
553 cells_.erase(cells_.begin() + pos);
554 if (size_t(pos) < attachedArgsNum_)
556 if (size_t(pos) < optionals_) {
565 void MathMacro::insertArgument(Inset::pos_type pos) {
566 if (displayMode_ == DISPLAY_NORMAL) {
567 LASSERT(size_t(pos) <= cells_.size(), /**/);
568 cells_.insert(cells_.begin() + pos, MathData());
569 if (size_t(pos) < attachedArgsNum_)
571 if (size_t(pos) < optionals_)
579 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
581 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
584 // strip off empty cells, but not more than arity-attachedArgsNum_
587 for (i = cells_.size(); i > attachedArgsNum_; --i)
588 if (!cell(i - 1).empty()) break;
592 attachedArgsNum_ = 0;
593 expanded_.cell(0) = MathData();
600 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
602 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
604 attachedArgsNum_ = args.size();
605 cells_.resize(arity);
606 expanded_.cell(0) = MathData();
607 optionals_ = optionals;
613 bool MathMacro::idxFirst(Cursor & cur) const
615 cur.updateFlags(Update::SinglePar);
616 return InsetMathNest::idxFirst(cur);
620 bool MathMacro::idxLast(Cursor & cur) const
622 cur.updateFlags(Update::SinglePar);
623 return InsetMathNest::idxLast(cur);
627 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
629 cur.updateFlags(Update::Force);
630 return InsetMathNest::notifyCursorLeaves(old, cur);
634 void MathMacro::fold(Cursor & cur)
636 if (!nextFoldMode_) {
637 nextFoldMode_ = true;
638 cur.updateFlags(Update::SinglePar);
643 void MathMacro::unfold(Cursor & cur)
646 nextFoldMode_ = false;
647 cur.updateFlags(Update::SinglePar);
652 bool MathMacro::folded() const
654 return nextFoldMode_;
658 void MathMacro::write(WriteStream & os) const
660 MathEnsurer ensurer(os, macro_ != 0, true);
663 if (displayMode_ != DISPLAY_NORMAL) {
664 os << "\\" << name();
665 if (name().size() != 1 || isAlphaASCII(name()[0]))
666 os.pendingSpace(true);
671 LASSERT(macro_, /**/);
673 // optional arguments make macros fragile
674 if (optionals_ > 0 && os.fragile())
677 os << "\\" << name();
680 // Optional arguments:
681 // First find last non-empty optional argument
682 idx_type emptyOptFrom = 0;
684 for (; i < cells_.size() && i < optionals_; ++i) {
685 if (!cell(i).empty())
686 emptyOptFrom = i + 1;
689 // print out optionals
690 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
692 os << "[" << cell(i) << "]";
695 // skip the tailing empty optionals
698 // Print remaining macros
699 for (; i < cells_.size(); ++i) {
700 if (cell(i).size() == 1
701 && cell(i)[0].nucleus()->asCharInset()
702 && cell(i)[0].nucleus()->asCharInset()->getChar() < 0x80) {
707 os << "{" << cell(i) << "}";
711 // add space if there was no argument
713 os.pendingSpace(true);
717 void MathMacro::maple(MapleStream & os) const
719 lyx::maple(expanded_.cell(0), os);
723 void MathMacro::mathmlize(MathStream & os) const
725 lyx::mathmlize(expanded_.cell(0), os);
729 void MathMacro::octave(OctaveStream & os) const
731 lyx::octave(expanded_.cell(0), os);
735 void MathMacro::infoize(odocstream & os) const
737 os << "Macro: " << name();
741 void MathMacro::infoize2(odocstream & os) const
743 os << "Macro: " << name();
748 bool MathMacro::completionSupported(Cursor const & cur) const
750 if (displayMode() != DISPLAY_UNFOLDED)
751 return InsetMathNest::completionSupported(cur);
753 return lyxrc.completion_popup_math
754 && displayMode() == DISPLAY_UNFOLDED
755 && cur.bv().cursor().pos() == int(name().size());
759 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
761 if (displayMode() != DISPLAY_UNFOLDED)
762 return InsetMathNest::inlineCompletionSupported(cur);
764 return lyxrc.completion_inline_math
765 && displayMode() == DISPLAY_UNFOLDED
766 && cur.bv().cursor().pos() == int(name().size());
770 bool MathMacro::automaticInlineCompletion() const
772 if (displayMode() != DISPLAY_UNFOLDED)
773 return InsetMathNest::automaticInlineCompletion();
775 return lyxrc.completion_inline_math;
779 bool MathMacro::automaticPopupCompletion() const
781 if (displayMode() != DISPLAY_UNFOLDED)
782 return InsetMathNest::automaticPopupCompletion();
784 return lyxrc.completion_popup_math;
788 CompletionList const *
789 MathMacro::createCompletionList(Cursor const & cur) const
791 if (displayMode() != DISPLAY_UNFOLDED)
792 return InsetMathNest::createCompletionList(cur);
794 return new MathCompletionList(cur.bv().cursor());
798 docstring MathMacro::completionPrefix(Cursor const & cur) const
800 if (displayMode() != DISPLAY_UNFOLDED)
801 return InsetMathNest::completionPrefix(cur);
803 if (!completionSupported(cur))
806 return "\\" + name();
810 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
813 if (displayMode() != DISPLAY_UNFOLDED)
814 return InsetMathNest::insertCompletion(cur, s, finished);
816 if (!completionSupported(cur))
820 docstring newName = name() + s;
821 asArray(newName, cell(0));
822 cur.bv().cursor().pos() = name().size();
823 cur.updateFlags(Update::SinglePar);
827 cur.bv().cursor().pop();
828 ++cur.bv().cursor().pos();
829 cur.updateFlags(Update::SinglePar);
836 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
837 Dimension & dim) const
839 if (displayMode() != DISPLAY_UNFOLDED)
840 InsetMathNest::completionPosAndDim(cur, x, y, dim);
842 // get inset dimensions
843 dim = cur.bv().coordCache().insets().dim(this);
844 // FIXME: these 3 are no accurate, but should depend on the font.
845 // Now the popup jumps down if you enter a char with descent > 0.
851 = cur.bv().coordCache().insets().xy(this);