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"
45 /// A proxy for the macro values
46 class ArgumentProxy : public InsetMath {
49 ArgumentProxy(MathMacro & mathMacro, size_t idx)
50 : mathMacro_(mathMacro), idx_(idx) {}
52 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
53 : mathMacro_(mathMacro), idx_(idx)
58 void metrics(MetricsInfo & mi, Dimension & dim) const {
59 mathMacro_.macro()->unlock();
60 if (!mathMacro_.editMetrics(mi.base.bv)
61 && mathMacro_.cell(idx_).empty())
62 def_.metrics(mi, dim);
64 CoordCache & coords = mi.base.bv->coordCache();
65 dim = coords.arrays().dim(&mathMacro_.cell(idx_));
67 mathMacro_.macro()->lock();
70 void draw(PainterInfo & pi, int x, int y) const {
71 if (mathMacro_.editMetrics(pi.base.bv)) {
72 // The only way a ArgumentProxy can appear is in a cell of the
73 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
74 // mode and then, if the macro is edited the monochrome
75 // mode is entered by the MathMacro before calling the cells' draw
76 // method. Then eventually this code is reached and the proxy leaves
77 // monochrome mode temporarely. Hence, if it is not in monochrome
78 // here (and the assert triggers in pain.leaveMonochromeMode())
80 pi.pain.leaveMonochromeMode();
81 mathMacro_.cell(idx_).draw(pi, x, y);
82 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
83 } else if (mathMacro_.cell(idx_).empty()) {
84 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
87 mathMacro_.cell(idx_).draw(pi, x, y);
90 size_t idx() const { return idx_; }
92 int kerning(BufferView const * bv) const
94 if (mathMacro_.editMetrics(bv)
95 || !mathMacro_.cell(idx_).empty())
96 return mathMacro_.cell(idx_).kerning(bv);
98 return def_.kerning(bv);
103 Inset * clone() const
105 return new ArgumentProxy(*this);
108 MathMacro & mathMacro_;
116 MathMacro::MathMacro(docstring const & name)
117 : InsetMathNest(0), name_(name), displayMode_(DISPLAY_INIT),
118 attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
119 macro_(0), needsUpdate_(false), appetite_(9)
123 Inset * MathMacro::clone() const
125 MathMacro * copy = new MathMacro(*this);
126 copy->needsUpdate_ = true;
127 copy->expanded_.cell(0).clear();
132 docstring MathMacro::name() const
134 if (displayMode_ == DISPLAY_UNFOLDED)
135 return asString(cell(0));
141 void MathMacro::cursorPos(BufferView const & bv,
142 CursorSlice const & sl, bool boundary, int & x, int & y) const
144 // We may have 0 arguments, but InsetMathNest requires at least one.
146 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
150 bool MathMacro::editMode(BufferView const * bv) const {
151 // find this in cursor trace
152 Cursor const & cur = bv->cursor();
153 for (size_t i = 0; i != cur.depth(); ++i)
154 if (&cur[i].inset() == this) {
155 // look if there is no other macro in edit mode above
157 for (; i != cur.depth(); ++i) {
158 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
159 if (macro && macro->displayMode() == DISPLAY_NORMAL)
163 // ok, none found, I am the highest one
171 bool MathMacro::editMetrics(BufferView const * bv) const
177 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
179 // set edit mode for which we will have calculated metrics. But only
180 editing_[mi.base.bv] = editMode(mi.base.bv);
182 // calculate new metrics according to display mode
183 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
184 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
185 } else if (displayMode_ == DISPLAY_UNFOLDED) {
186 cell(0).metrics(mi, dim);
188 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
189 dim.wid += bsdim.width() + 1;
190 dim.asc = max(bsdim.ascent(), dim.ascent());
191 dim.des = max(bsdim.descent(), dim.descent());
193 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
194 && editing_[mi.base.bv]) {
195 // Macro will be edited in a old-style list mode here:
197 BOOST_ASSERT(macro_ != 0);
199 FontInfo labelFont = sane_font;
200 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
202 // get dimension of components of list view
204 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
205 nameDim.asc = fontDim.asc;
206 nameDim.des = fontDim.des;
209 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
210 argDim.asc = fontDim.asc;
211 argDim.des = fontDim.des;
214 definition_.metrics(mi, defDim);
217 dim.wid = nameDim.wid + defDim.wid;
218 dim.asc = max(nameDim.asc, defDim.asc);
219 dim.des = max(nameDim.des, defDim.des);
221 for (idx_type i = 0; i < nargs(); ++i) {
223 cell(i).metrics(mi, cdim);
224 dim.des += max(argDim.height(), cdim.height()) + 1;
225 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
228 // make space for box and markers, 2 pixels
232 metricsMarkers2(dim);
234 BOOST_ASSERT(macro_ != 0);
236 // metrics are computed here for the cells,
237 // in the proxy we will then use the dim from the cache
238 InsetMathNest::metrics(mi);
240 // calculate metrics finally
242 expanded_.cell(0).metrics(mi, dim);
245 // calculate dimension with label while editing
246 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
247 && editing_[mi.base.bv]) {
248 FontInfo font = mi.base.font;
249 augmentFont(font, from_ascii("lyxtex"));
251 mathed_string_dim(font, name(), namedim);
253 dim.wid += 2 + namedim.wid + 2 + 2;
254 dim.asc = max(dim.asc, namedim.asc) + 2;
255 dim.des = max(dim.des, namedim.des) + 2;
257 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
258 dim.asc += 1 + namedim.height() + 1;
266 int MathMacro::kerning(BufferView const * bv) const {
267 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
268 return expanded_.kerning(bv);
274 void MathMacro::updateMacro(MacroContext const & mc)
277 macro_ = mc.get(name());
278 if (macro_ && macroBackup_ != *macro_) {
279 macroBackup_ = *macro_;
288 void MathMacro::updateRepresentation()
295 requires_ = macro_->requires();
297 // non-normal mode? We are done!
298 if (displayMode_ != DISPLAY_NORMAL)
305 needsUpdate_ = false;
307 // get default values of macro
308 vector<docstring> const & defaults = macro_->defaults();
310 // create MathMacroArgumentValue objects pointing to the cells of the macro
311 vector<MathData> values(nargs());
312 for (size_t i = 0; i < nargs(); ++i) {
313 ArgumentProxy * proxy;
314 if (i < defaults.size())
315 proxy = new ArgumentProxy(*this, i, defaults[i]);
317 proxy = new ArgumentProxy(*this, i);
318 values[i].insert(0, MathAtom(proxy));
321 // expanding macro with the values
322 macro_->expand(values, expanded_.cell(0));
323 // get definition for list edit mode
324 docstring const & display = macro_->display();
325 asArray(display.empty() ? macro_->definition() : display, definition_);
329 void MathMacro::draw(PainterInfo & pi, int x, int y) const
331 Dimension const dim = dimension(*pi.base.bv);
333 setPosCache(pi, x, y);
337 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
338 PainterInfo pi2(pi.base.bv, pi.pain);
339 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
340 //pi2.base.style = LM_ST_TEXT;
341 pi2.pain.text(x, y, from_ascii("\\") + name(), pi2.base.font);
342 } else if (displayMode_ == DISPLAY_UNFOLDED) {
343 PainterInfo pi2(pi.base.bv, pi.pain);
344 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
345 //pi2.base.style = LM_ST_TEXT;
346 pi2.pain.text(x, y, from_ascii("\\"), pi2.base.font);
347 x += mathed_string_width(pi2.base.font, from_ascii("\\")) + 1;
348 cell(0).draw(pi2, x, y);
349 drawMarkers(pi2, expx, expy);
350 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
351 && editing_[pi.base.bv]) {
352 // Macro will be edited in a old-style list mode here:
354 CoordCache & coords = pi.base.bv->coordCache();
355 FontInfo const & labelFont = sane_font;
357 // markers and box needs two pixels
360 // get maximal font height
362 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
365 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
366 pi.pain.text(x, y, label, labelFont);
367 x += mathed_string_width(labelFont, label);
370 definition_.draw(pi, x, y);
372 = coords.arrays().dim(&definition_);
373 y += max(fontDim.des, defDim.des);
376 docstring str = from_ascii("#9");
377 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
378 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
380 for (idx_type i = 0; i < nargs(); ++i) {
383 = coords.arrays().dim(&cell(i));
385 y += max(fontDim.asc, cdim.asc) + 1;
389 pi.pain.text(x, y, str, labelFont);
391 pi.pain.text(x, y, from_ascii(":"), labelFont);
395 cell(i).draw(pi, x, y);
398 y += max(fontDim.des, cdim.des);
401 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
402 dim.height() - 2, Color_mathmacroframe);
403 drawMarkers2(pi, expx, expy);
405 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
408 for (size_t i = 0; i < nargs(); ++i)
409 cell(i).setXY(*pi.base.bv, x, y);
411 if (drawBox && editing_[pi.base.bv]) {
412 // draw header and rectangle around
413 FontInfo font = pi.base.font;
414 augmentFont(font, from_ascii("lyxtex"));
415 font.setSize(FONT_SIZE_TINY);
416 font.setColor(Color_mathmacrolabel);
418 mathed_string_dim(font, name(), namedim);
420 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
421 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
422 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
425 if (editing_[pi.base.bv]) {
426 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
427 expanded_.cell(0).draw(pi, expx, expy);
428 pi.pain.leaveMonochromeMode();
431 pi.pain.rectangle(x, y - dim.asc, dim.wid,
432 dim.height(), Color_mathmacroframe);
434 expanded_.cell(0).draw(pi, expx, expy);
437 drawMarkers(pi, x, y);
440 // edit mode changed?
441 if (editing_[pi.base.bv] != editMode(pi.base.bv))
442 pi.base.bv->cursor().updateFlags(Update::SinglePar);
446 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
448 // We may have 0 arguments, but InsetMathNest requires at least one.
449 if (cells_.size() > 0)
450 InsetMathNest::drawSelection(pi, x, y);
454 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
456 if (displayMode_ != mode) {
457 // transfer name if changing from or to DISPLAY_UNFOLDED
458 if (mode == DISPLAY_UNFOLDED) {
460 asArray(name_, cell(0));
461 } else if (displayMode_ == DISPLAY_UNFOLDED) {
462 name_ = asString(cell(0));
470 // the interactive init mode is non-greedy by default
472 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
474 appetite_ = size_t(appetite);
478 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
480 if (nextFoldMode_ == true && macro_ && !macro_->locked())
481 return DISPLAY_NORMAL;
483 return DISPLAY_UNFOLDED;
487 bool MathMacro::validName() const
489 docstring n = name();
495 // converting back and force doesn't swallow anything?
498 if (asString(ma) != n)
502 for (size_t i = 0; i<n.size(); ++i) {
503 if (!(n[i] >= 'a' && n[i] <= 'z')
504 && !(n[i] >= 'A' && n[i] <= 'Z')
513 void MathMacro::validate(LaTeXFeatures & features) const
515 if (!requires_.empty())
516 features.require(requires_);
518 if (name() == "binom" || name() == "mathcircumflex")
519 features.require(to_utf8(name()));
521 // validate the cells and the definition
522 if (displayMode() == DISPLAY_NORMAL) {
523 definition_.validate(features);
524 InsetMathNest::validate(features);
529 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
531 cur.updateFlags(Update::SinglePar);
532 InsetMathNest::edit(cur, front, entry_from);
536 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
538 // We may have 0 arguments, but InsetMathNest requires at least one.
540 cur.updateFlags(Update::SinglePar);
541 return InsetMathNest::editXY(cur, x, y);
547 void MathMacro::removeArgument(Inset::pos_type pos) {
548 if (displayMode_ == DISPLAY_NORMAL) {
549 BOOST_ASSERT(size_t(pos) < cells_.size());
550 cells_.erase(cells_.begin() + pos);
551 if (size_t(pos) < attachedArgsNum_)
553 if (size_t(pos) < optionals_) {
562 void MathMacro::insertArgument(Inset::pos_type pos) {
563 if (displayMode_ == DISPLAY_NORMAL) {
564 BOOST_ASSERT(size_t(pos) <= cells_.size());
565 cells_.insert(cells_.begin() + pos, MathData());
566 if (size_t(pos) < attachedArgsNum_)
568 if (size_t(pos) < optionals_)
576 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
578 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
581 // strip off empty cells, but not more than arity-attachedArgsNum_
584 for (i = cells_.size(); i > attachedArgsNum_; --i)
585 if (!cell(i - 1).empty()) break;
589 attachedArgsNum_ = 0;
590 expanded_.cell(0) = MathData();
597 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
599 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
601 attachedArgsNum_ = args.size();
602 cells_.resize(arity);
603 expanded_.cell(0) = MathData();
604 optionals_ = optionals;
610 bool MathMacro::idxFirst(Cursor & cur) const
612 cur.updateFlags(Update::SinglePar);
613 return InsetMathNest::idxFirst(cur);
617 bool MathMacro::idxLast(Cursor & cur) const
619 cur.updateFlags(Update::SinglePar);
620 return InsetMathNest::idxLast(cur);
624 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
626 cur.updateFlags(Update::Force);
627 return InsetMathNest::notifyCursorLeaves(old, cur);
631 void MathMacro::fold(Cursor & cur)
633 if (!nextFoldMode_) {
634 nextFoldMode_ = true;
635 cur.updateFlags(Update::SinglePar);
640 void MathMacro::unfold(Cursor & cur)
643 nextFoldMode_ = false;
644 cur.updateFlags(Update::SinglePar);
649 bool MathMacro::folded() const
651 return nextFoldMode_;
655 void MathMacro::write(WriteStream & os) const
658 if (displayMode_ != DISPLAY_NORMAL) {
659 os << "\\" << name() << " ";
660 os.pendingSpace(true);
665 BOOST_ASSERT(macro_);
667 // optional arguments make macros fragile
668 if (optionals_ > 0 && os.fragile())
671 os << "\\" << name();
674 // Optional arguments:
675 // First find last non-empty optional argument
676 idx_type emptyOptFrom = 0;
678 for (; i < cells_.size() && i < optionals_; ++i) {
679 if (!cell(i).empty())
680 emptyOptFrom = i + 1;
683 // print out optionals
684 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
686 os << "[" << cell(i) << "]";
689 // skip the tailing empty optionals
692 // Print remaining macros
693 for (; i < cells_.size(); ++i) {
694 if (cell(i).size() == 1
695 && cell(i)[0].nucleus()->asCharInset()) {
700 os << "{" << cell(i) << "}";
704 // add space if there was no argument
706 os.pendingSpace(true);
710 void MathMacro::maple(MapleStream & os) const
712 lyx::maple(expanded_.cell(0), os);
716 void MathMacro::mathmlize(MathStream & os) const
718 lyx::mathmlize(expanded_.cell(0), os);
722 void MathMacro::octave(OctaveStream & os) const
724 lyx::octave(expanded_.cell(0), os);
728 void MathMacro::infoize(odocstream & os) const
730 os << "Macro: " << name();
734 void MathMacro::infoize2(odocstream & os) const
736 os << "Macro: " << name();
741 bool MathMacro::completionSupported(Cursor const & cur) const
743 if (displayMode() != DISPLAY_UNFOLDED)
744 return InsetMathNest::completionSupported(cur);
746 return lyxrc.completion_popup_math
747 && displayMode() == DISPLAY_UNFOLDED
748 && cur.bv().cursor().pos() == int(name().size());
752 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
754 if (displayMode() != DISPLAY_UNFOLDED)
755 return InsetMathNest::inlineCompletionSupported(cur);
757 return lyxrc.completion_inline_math
758 && displayMode() == DISPLAY_UNFOLDED
759 && cur.bv().cursor().pos() == int(name().size());
763 bool MathMacro::automaticInlineCompletion() const
765 if (displayMode() != DISPLAY_UNFOLDED)
766 return InsetMathNest::automaticInlineCompletion();
768 return lyxrc.completion_inline_math;
772 bool MathMacro::automaticPopupCompletion() const
774 if (displayMode() != DISPLAY_UNFOLDED)
775 return InsetMathNest::automaticPopupCompletion();
777 return lyxrc.completion_popup_math;
781 CompletionList const *
782 MathMacro::createCompletionList(Cursor const & cur) const
784 if (displayMode() != DISPLAY_UNFOLDED)
785 return InsetMathNest::createCompletionList(cur);
787 return new MathCompletionList(cur.bv().cursor());
791 docstring MathMacro::completionPrefix(Cursor const & cur) const
793 if (displayMode() != DISPLAY_UNFOLDED)
794 return InsetMathNest::completionPrefix(cur);
796 if (!completionSupported(cur))
799 return "\\" + name();
803 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
806 if (displayMode() != DISPLAY_UNFOLDED)
807 return InsetMathNest::insertCompletion(cur, s, finished);
809 if (!completionSupported(cur))
813 docstring newName = name() + s;
814 asArray(newName, cell(0));
815 cur.bv().cursor().pos() = name().size();
816 cur.updateFlags(Update::SinglePar);
820 cur.bv().cursor().pop();
821 ++cur.bv().cursor().pos();
822 cur.updateFlags(Update::SinglePar);
829 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
830 Dimension & dim) const
832 if (displayMode() != DISPLAY_UNFOLDED)
833 InsetMathNest::completionPosAndDim(cur, x, y, dim);
835 // get inset dimensions
836 dim = cur.bv().coordCache().insets().dim(this);
837 // FIXME: these 3 are no accurate, but should depend on the font.
838 // Now the popup jumps down if you enter a char with descent > 0.
844 = cur.bv().coordCache().insets().xy(this);