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/lassert.h"
36 #include "support/debug.h"
46 /// A proxy for the macro values
47 class ArgumentProxy : public InsetMath {
50 ArgumentProxy(MathMacro & mathMacro, size_t idx)
51 : mathMacro_(mathMacro), idx_(idx) {}
53 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
54 : mathMacro_(mathMacro), idx_(idx)
59 void metrics(MetricsInfo & mi, Dimension & dim) const {
60 mathMacro_.macro()->unlock();
61 if (!mathMacro_.editMetrics(mi.base.bv)
62 && mathMacro_.cell(idx_).empty())
63 def_.metrics(mi, dim);
65 CoordCache & coords = mi.base.bv->coordCache();
66 dim = coords.arrays().dim(&mathMacro_.cell(idx_));
68 mathMacro_.macro()->lock();
71 void draw(PainterInfo & pi, int x, int y) const {
72 if (mathMacro_.editMetrics(pi.base.bv)) {
73 // The only way a ArgumentProxy can appear is in a cell of the
74 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
75 // mode and then, if the macro is edited the monochrome
76 // mode is entered by the MathMacro before calling the cells' draw
77 // method. Then eventually this code is reached and the proxy leaves
78 // monochrome mode temporarely. Hence, if it is not in monochrome
79 // here (and the assert triggers in pain.leaveMonochromeMode())
81 pi.pain.leaveMonochromeMode();
82 mathMacro_.cell(idx_).draw(pi, x, y);
83 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
84 } else if (mathMacro_.cell(idx_).empty()) {
85 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
88 mathMacro_.cell(idx_).draw(pi, x, y);
91 size_t idx() const { return idx_; }
93 int kerning(BufferView const * bv) const
95 if (mathMacro_.editMetrics(bv)
96 || !mathMacro_.cell(idx_).empty())
97 return mathMacro_.cell(idx_).kerning(bv);
99 return def_.kerning(bv);
104 Inset * clone() const
106 return new ArgumentProxy(*this);
109 MathMacro & mathMacro_;
117 MathMacro::MathMacro(docstring const & name)
118 : InsetMathNest(0), name_(name), displayMode_(DISPLAY_INIT),
119 attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
120 macro_(0), needsUpdate_(false), appetite_(9)
124 Inset * MathMacro::clone() const
126 MathMacro * copy = new MathMacro(*this);
127 copy->needsUpdate_ = true;
128 copy->expanded_.cell(0).clear();
133 docstring MathMacro::name() const
135 if (displayMode_ == DISPLAY_UNFOLDED)
136 return asString(cell(0));
142 void MathMacro::cursorPos(BufferView const & bv,
143 CursorSlice const & sl, bool boundary, int & x, int & y) const
145 // We may have 0 arguments, but InsetMathNest requires at least one.
147 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
151 bool MathMacro::editMode(BufferView const * bv) const {
152 // find this in cursor trace
153 Cursor const & cur = bv->cursor();
154 for (size_t i = 0; i != cur.depth(); ++i)
155 if (&cur[i].inset() == this) {
156 // look if there is no other macro in edit mode above
158 for (; i != cur.depth(); ++i) {
159 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
160 if (macro && macro->displayMode() == DISPLAY_NORMAL)
164 // ok, none found, I am the highest one
172 bool MathMacro::editMetrics(BufferView const * bv) const
178 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
180 // set edit mode for which we will have calculated metrics. But only
181 editing_[mi.base.bv] = editMode(mi.base.bv);
183 // calculate new metrics according to display mode
184 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
185 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
186 } else if (displayMode_ == DISPLAY_UNFOLDED) {
187 cell(0).metrics(mi, dim);
189 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
190 dim.wid += bsdim.width() + 1;
191 dim.asc = max(bsdim.ascent(), dim.ascent());
192 dim.des = max(bsdim.descent(), dim.descent());
194 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
195 && editing_[mi.base.bv]) {
196 // Macro will be edited in a old-style list mode here:
198 LASSERT(macro_ != 0, /**/);
200 FontInfo labelFont = sane_font;
201 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
203 // get dimension of components of list view
205 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
206 nameDim.asc = fontDim.asc;
207 nameDim.des = fontDim.des;
210 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
211 argDim.asc = fontDim.asc;
212 argDim.des = fontDim.des;
215 definition_.metrics(mi, defDim);
218 dim.wid = nameDim.wid + defDim.wid;
219 dim.asc = max(nameDim.asc, defDim.asc);
220 dim.des = max(nameDim.des, defDim.des);
222 for (idx_type i = 0; i < nargs(); ++i) {
224 cell(i).metrics(mi, cdim);
225 dim.des += max(argDim.height(), cdim.height()) + 1;
226 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
229 // make space for box and markers, 2 pixels
233 metricsMarkers2(dim);
235 LASSERT(macro_ != 0, /**/);
237 // metrics are computed here for the cells,
238 // in the proxy we will then use the dim from the cache
239 InsetMathNest::metrics(mi);
241 // calculate metrics finally
243 expanded_.cell(0).metrics(mi, dim);
246 // calculate dimension with label while editing
247 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
248 && editing_[mi.base.bv]) {
249 FontInfo font = mi.base.font;
250 augmentFont(font, from_ascii("lyxtex"));
252 mathed_string_dim(font, name(), namedim);
254 dim.wid += 2 + namedim.wid + 2 + 2;
255 dim.asc = max(dim.asc, namedim.asc) + 2;
256 dim.des = max(dim.des, namedim.des) + 2;
258 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
259 dim.asc += 1 + namedim.height() + 1;
267 int MathMacro::kerning(BufferView const * bv) const {
268 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
269 return expanded_.kerning(bv);
275 void MathMacro::updateMacro(MacroContext const & mc)
278 macro_ = mc.get(name());
279 if (macro_ && macroBackup_ != *macro_) {
280 macroBackup_ = *macro_;
289 void MathMacro::updateRepresentation()
296 requires_ = macro_->requires();
298 // non-normal mode? We are done!
299 if (displayMode_ != DISPLAY_NORMAL)
306 needsUpdate_ = false;
308 // get default values of macro
309 vector<docstring> const & defaults = macro_->defaults();
311 // create MathMacroArgumentValue objects pointing to the cells of the macro
312 vector<MathData> values(nargs());
313 for (size_t i = 0; i < nargs(); ++i) {
314 ArgumentProxy * proxy;
315 if (i < defaults.size())
316 proxy = new ArgumentProxy(*this, i, defaults[i]);
318 proxy = new ArgumentProxy(*this, i);
319 values[i].insert(0, MathAtom(proxy));
322 // expanding macro with the values
323 macro_->expand(values, expanded_.cell(0));
324 // get definition for list edit mode
325 docstring const & display = macro_->display();
326 asArray(display.empty() ? macro_->definition() : display, definition_);
330 void MathMacro::draw(PainterInfo & pi, int x, int y) const
332 Dimension const dim = dimension(*pi.base.bv);
334 setPosCache(pi, x, y);
338 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
339 PainterInfo pi2(pi.base.bv, pi.pain);
340 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
341 //pi2.base.style = LM_ST_TEXT;
342 pi2.pain.text(x, y, from_ascii("\\") + name(), pi2.base.font);
343 } else if (displayMode_ == DISPLAY_UNFOLDED) {
344 PainterInfo pi2(pi.base.bv, pi.pain);
345 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
346 //pi2.base.style = LM_ST_TEXT;
347 pi2.pain.text(x, y, from_ascii("\\"), pi2.base.font);
348 x += mathed_string_width(pi2.base.font, from_ascii("\\")) + 1;
349 cell(0).draw(pi2, x, y);
350 drawMarkers(pi2, expx, expy);
351 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
352 && editing_[pi.base.bv]) {
353 // Macro will be edited in a old-style list mode here:
355 CoordCache & coords = pi.base.bv->coordCache();
356 FontInfo const & labelFont = sane_font;
358 // markers and box needs two pixels
361 // get maximal font height
363 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
366 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
367 pi.pain.text(x, y, label, labelFont);
368 x += mathed_string_width(labelFont, label);
371 definition_.draw(pi, x, y);
373 = coords.arrays().dim(&definition_);
374 y += max(fontDim.des, defDim.des);
377 docstring str = from_ascii("#9");
378 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
379 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
381 for (idx_type i = 0; i < nargs(); ++i) {
384 = coords.arrays().dim(&cell(i));
386 y += max(fontDim.asc, cdim.asc) + 1;
390 pi.pain.text(x, y, str, labelFont);
392 pi.pain.text(x, y, from_ascii(":"), labelFont);
396 cell(i).draw(pi, x, y);
399 y += max(fontDim.des, cdim.des);
402 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
403 dim.height() - 2, Color_mathmacroframe);
404 drawMarkers2(pi, expx, expy);
406 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
409 for (size_t i = 0; i < nargs(); ++i)
410 cell(i).setXY(*pi.base.bv, x, y);
412 if (drawBox && editing_[pi.base.bv]) {
413 // draw header and rectangle around
414 FontInfo font = pi.base.font;
415 augmentFont(font, from_ascii("lyxtex"));
416 font.setSize(FONT_SIZE_TINY);
417 font.setColor(Color_mathmacrolabel);
419 mathed_string_dim(font, name(), namedim);
421 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
422 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
423 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
426 if (editing_[pi.base.bv]) {
427 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
428 expanded_.cell(0).draw(pi, expx, expy);
429 pi.pain.leaveMonochromeMode();
432 pi.pain.rectangle(x, y - dim.asc, dim.wid,
433 dim.height(), Color_mathmacroframe);
435 expanded_.cell(0).draw(pi, expx, expy);
438 drawMarkers(pi, x, y);
441 // edit mode changed?
442 if (editing_[pi.base.bv] != editMode(pi.base.bv))
443 pi.base.bv->cursor().updateFlags(Update::SinglePar);
447 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
449 // We may have 0 arguments, but InsetMathNest requires at least one.
450 if (cells_.size() > 0)
451 InsetMathNest::drawSelection(pi, x, y);
455 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
457 if (displayMode_ != mode) {
458 // transfer name if changing from or to DISPLAY_UNFOLDED
459 if (mode == DISPLAY_UNFOLDED) {
461 asArray(name_, cell(0));
462 } else if (displayMode_ == DISPLAY_UNFOLDED) {
463 name_ = asString(cell(0));
471 // the interactive init mode is non-greedy by default
473 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
475 appetite_ = size_t(appetite);
479 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
481 if (nextFoldMode_ == true && macro_ && !macro_->locked())
482 return DISPLAY_NORMAL;
484 return DISPLAY_UNFOLDED;
488 bool MathMacro::validName() const
490 docstring n = name();
496 // converting back and force doesn't swallow anything?
499 if (asString(ma) != n)
503 for (size_t i = 0; i<n.size(); ++i) {
504 if (!(n[i] >= 'a' && n[i] <= 'z')
505 && !(n[i] >= 'A' && n[i] <= 'Z')
514 void MathMacro::validate(LaTeXFeatures & features) const
516 if (!requires_.empty())
517 features.require(requires_);
519 if (name() == "binom" || name() == "mathcircumflex")
520 features.require(to_utf8(name()));
522 // validate the cells and the definition
523 if (displayMode() == DISPLAY_NORMAL) {
524 definition_.validate(features);
525 InsetMathNest::validate(features);
530 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
532 cur.updateFlags(Update::SinglePar);
533 InsetMathNest::edit(cur, front, entry_from);
537 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
539 // We may have 0 arguments, but InsetMathNest requires at least one.
541 cur.updateFlags(Update::SinglePar);
542 return InsetMathNest::editXY(cur, x, y);
548 void MathMacro::removeArgument(Inset::pos_type pos) {
549 if (displayMode_ == DISPLAY_NORMAL) {
550 LASSERT(size_t(pos) < cells_.size(), /**/);
551 cells_.erase(cells_.begin() + pos);
552 if (size_t(pos) < attachedArgsNum_)
554 if (size_t(pos) < optionals_) {
563 void MathMacro::insertArgument(Inset::pos_type pos) {
564 if (displayMode_ == DISPLAY_NORMAL) {
565 LASSERT(size_t(pos) <= cells_.size(), /**/);
566 cells_.insert(cells_.begin() + pos, MathData());
567 if (size_t(pos) < attachedArgsNum_)
569 if (size_t(pos) < optionals_)
577 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
579 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
582 // strip off empty cells, but not more than arity-attachedArgsNum_
585 for (i = cells_.size(); i > attachedArgsNum_; --i)
586 if (!cell(i - 1).empty()) break;
590 attachedArgsNum_ = 0;
591 expanded_.cell(0) = MathData();
598 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
600 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
602 attachedArgsNum_ = args.size();
603 cells_.resize(arity);
604 expanded_.cell(0) = MathData();
605 optionals_ = optionals;
611 bool MathMacro::idxFirst(Cursor & cur) const
613 cur.updateFlags(Update::SinglePar);
614 return InsetMathNest::idxFirst(cur);
618 bool MathMacro::idxLast(Cursor & cur) const
620 cur.updateFlags(Update::SinglePar);
621 return InsetMathNest::idxLast(cur);
625 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
627 cur.updateFlags(Update::Force);
628 return InsetMathNest::notifyCursorLeaves(old, cur);
632 void MathMacro::fold(Cursor & cur)
634 if (!nextFoldMode_) {
635 nextFoldMode_ = true;
636 cur.updateFlags(Update::SinglePar);
641 void MathMacro::unfold(Cursor & cur)
644 nextFoldMode_ = false;
645 cur.updateFlags(Update::SinglePar);
650 bool MathMacro::folded() const
652 return nextFoldMode_;
656 void MathMacro::write(WriteStream & os) const
658 bool brace = os.pendingBrace();
659 os.pendingBrace(false);
661 if (os.textMode() && macro_) {
662 // This is for sure a math macro
663 os << "\\ensuremath{";
666 } else if (brace && !macro_) {
667 // Cannot tell, so don't mess with the mode
675 if (displayMode_ != DISPLAY_NORMAL) {
676 os << "\\" << name();
677 os.pendingSpace(true);
678 os.pendingBrace(brace);
683 LASSERT(macro_, /**/);
685 // optional arguments make macros fragile
686 if (optionals_ > 0 && os.fragile())
689 os << "\\" << name();
692 // Optional arguments:
693 // First find last non-empty optional argument
694 idx_type emptyOptFrom = 0;
696 for (; i < cells_.size() && i < optionals_; ++i) {
697 if (!cell(i).empty())
698 emptyOptFrom = i + 1;
701 // print out optionals
702 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
704 os << "[" << cell(i) << "]";
707 // skip the tailing empty optionals
710 // Print remaining macros
711 for (; i < cells_.size(); ++i) {
712 if (cell(i).size() == 1
713 && cell(i)[0].nucleus()->asCharInset()) {
718 os << "{" << cell(i) << "}";
722 // add space if there was no argument
724 os.pendingSpace(true);
726 os.pendingBrace(brace);
730 void MathMacro::maple(MapleStream & os) const
732 lyx::maple(expanded_.cell(0), os);
736 void MathMacro::mathmlize(MathStream & os) const
738 lyx::mathmlize(expanded_.cell(0), os);
742 void MathMacro::octave(OctaveStream & os) const
744 lyx::octave(expanded_.cell(0), os);
748 void MathMacro::infoize(odocstream & os) const
750 os << "Macro: " << name();
754 void MathMacro::infoize2(odocstream & os) const
756 os << "Macro: " << name();
761 bool MathMacro::completionSupported(Cursor const & cur) const
763 if (displayMode() != DISPLAY_UNFOLDED)
764 return InsetMathNest::completionSupported(cur);
766 return lyxrc.completion_popup_math
767 && displayMode() == DISPLAY_UNFOLDED
768 && cur.bv().cursor().pos() == int(name().size());
772 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
774 if (displayMode() != DISPLAY_UNFOLDED)
775 return InsetMathNest::inlineCompletionSupported(cur);
777 return lyxrc.completion_inline_math
778 && displayMode() == DISPLAY_UNFOLDED
779 && cur.bv().cursor().pos() == int(name().size());
783 bool MathMacro::automaticInlineCompletion() const
785 if (displayMode() != DISPLAY_UNFOLDED)
786 return InsetMathNest::automaticInlineCompletion();
788 return lyxrc.completion_inline_math;
792 bool MathMacro::automaticPopupCompletion() const
794 if (displayMode() != DISPLAY_UNFOLDED)
795 return InsetMathNest::automaticPopupCompletion();
797 return lyxrc.completion_popup_math;
801 CompletionList const *
802 MathMacro::createCompletionList(Cursor const & cur) const
804 if (displayMode() != DISPLAY_UNFOLDED)
805 return InsetMathNest::createCompletionList(cur);
807 return new MathCompletionList(cur.bv().cursor());
811 docstring MathMacro::completionPrefix(Cursor const & cur) const
813 if (displayMode() != DISPLAY_UNFOLDED)
814 return InsetMathNest::completionPrefix(cur);
816 if (!completionSupported(cur))
819 return "\\" + name();
823 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
826 if (displayMode() != DISPLAY_UNFOLDED)
827 return InsetMathNest::insertCompletion(cur, s, finished);
829 if (!completionSupported(cur))
833 docstring newName = name() + s;
834 asArray(newName, cell(0));
835 cur.bv().cursor().pos() = name().size();
836 cur.updateFlags(Update::SinglePar);
840 cur.bv().cursor().pop();
841 ++cur.bv().cursor().pos();
842 cur.updateFlags(Update::SinglePar);
849 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
850 Dimension & dim) const
852 if (displayMode() != DISPLAY_UNFOLDED)
853 InsetMathNest::completionPosAndDim(cur, x, y, dim);
855 // get inset dimensions
856 dim = cur.bv().coordCache().insets().dim(this);
857 // FIXME: these 3 are no accurate, but should depend on the font.
858 // Now the popup jumps down if you enter a char with descent > 0.
864 = cur.bv().coordCache().insets().xy(this);