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 "MathFactory.h"
21 #include "MathStream.h"
22 #include "MathSupport.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
28 #include "FuncStatus.h"
29 #include "FuncRequest.h"
30 #include "LaTeXFeatures.h"
35 #include "frontends/Painter.h"
37 #include "support/debug.h"
38 #include "support/lassert.h"
39 #include "support/textutils.h"
49 /// A proxy for the macro values
50 class ArgumentProxy : public InsetMath {
53 ArgumentProxy(MathMacro & mathMacro, size_t idx)
54 : mathMacro_(mathMacro), idx_(idx) {}
56 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
57 : mathMacro_(mathMacro), idx_(idx)
62 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
64 void metrics(MetricsInfo & mi, Dimension & dim) const {
65 mathMacro_.macro()->unlock();
66 mathMacro_.cell(idx_).metrics(mi, dim);
68 if (!mathMacro_.editMetrics(mi.base.bv)
69 && mathMacro_.cell(idx_).empty())
70 def_.metrics(mi, dim);
72 mathMacro_.macro()->lock();
74 // FIXME Other external things need similar treatment.
76 docstring mathmlize(MathStream & ms) const {
77 ms << mathMacro_.cell(idx_);
81 void draw(PainterInfo & pi, int x, int y) const {
82 if (mathMacro_.editMetrics(pi.base.bv)) {
83 // The only way a ArgumentProxy can appear is in a cell of the
84 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
85 // mode and then, if the macro is edited the monochrome
86 // mode is entered by the MathMacro before calling the cells' draw
87 // method. Then eventually this code is reached and the proxy leaves
88 // monochrome mode temporarely. Hence, if it is not in monochrome
89 // here (and the assert triggers in pain.leaveMonochromeMode())
91 pi.pain.leaveMonochromeMode();
92 mathMacro_.cell(idx_).draw(pi, x, y);
93 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
94 } else if (mathMacro_.cell(idx_).empty()) {
95 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
98 mathMacro_.cell(idx_).draw(pi, x, y);
101 size_t idx() const { return idx_; }
103 int kerning(BufferView const * bv) const
105 if (mathMacro_.editMetrics(bv)
106 || !mathMacro_.cell(idx_).empty())
107 return mathMacro_.cell(idx_).kerning(bv);
109 return def_.kerning(bv);
114 Inset * clone() const
116 return new ArgumentProxy(*this);
119 MathMacro & mathMacro_;
127 MathMacro::MathMacro(Buffer * buf, docstring const & name)
128 : InsetMathNest(buf, 0), name_(name), displayMode_(DISPLAY_INIT),
129 expanded_(buf), attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
130 macroBackup_(buf), macro_(0), needsUpdate_(false), appetite_(9)
134 Inset * MathMacro::clone() const
136 MathMacro * copy = new MathMacro(*this);
137 copy->needsUpdate_ = true;
138 //copy->expanded_.cell(0).clear();
143 docstring MathMacro::name() const
145 if (displayMode_ == DISPLAY_UNFOLDED)
146 return asString(cell(0));
152 void MathMacro::cursorPos(BufferView const & bv,
153 CursorSlice const & sl, bool boundary, int & x, int & y) const
155 // We may have 0 arguments, but InsetMathNest requires at least one.
157 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
161 bool MathMacro::editMode(BufferView const * bv) const {
162 // find this in cursor trace
163 Cursor const & cur = bv->cursor();
164 for (size_t i = 0; i != cur.depth(); ++i)
165 if (&cur[i].inset() == this) {
166 // look if there is no other macro in edit mode above
168 for (; i != cur.depth(); ++i) {
169 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
170 if (macro && macro->displayMode() == DISPLAY_NORMAL)
174 // ok, none found, I am the highest one
182 bool MathMacro::editMetrics(BufferView const * bv) const
188 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
190 // set edit mode for which we will have calculated metrics. But only
191 editing_[mi.base.bv] = editMode(mi.base.bv);
193 // calculate new metrics according to display mode
194 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
195 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
196 } else if (displayMode_ == DISPLAY_UNFOLDED) {
197 cell(0).metrics(mi, dim);
199 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
200 dim.wid += bsdim.width() + 1;
201 dim.asc = max(bsdim.ascent(), dim.ascent());
202 dim.des = max(bsdim.descent(), dim.descent());
204 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
205 && editing_[mi.base.bv]) {
206 // Macro will be edited in a old-style list mode here:
208 LASSERT(macro_ != 0, /**/);
210 FontInfo labelFont = sane_font;
211 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
213 // get dimension of components of list view
215 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
216 nameDim.asc = fontDim.asc;
217 nameDim.des = fontDim.des;
220 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
221 argDim.asc = fontDim.asc;
222 argDim.des = fontDim.des;
225 definition_.metrics(mi, defDim);
228 dim.wid = nameDim.wid + defDim.wid;
229 dim.asc = max(nameDim.asc, defDim.asc);
230 dim.des = max(nameDim.des, defDim.des);
232 for (idx_type i = 0; i < nargs(); ++i) {
234 cell(i).metrics(mi, cdim);
235 dim.des += max(argDim.height(), cdim.height()) + 1;
236 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
239 // make space for box and markers, 2 pixels
243 metricsMarkers2(dim);
245 LASSERT(macro_ != 0, /**/);
247 // calculate metrics, hoping that all cells are seen
249 expanded_.cell(0).metrics(mi, dim);
251 // otherwise do a manual metrics call
252 CoordCache & coords = mi.base.bv->coordCache();
253 for (idx_type i = 0; i < nargs(); ++i) {
254 if (!coords.getArrays().has(&cell(i))) {
256 cell(i).metrics(mi, tdim);
261 // calculate dimension with label while editing
262 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
263 && editing_[mi.base.bv]) {
264 FontInfo font = mi.base.font;
265 augmentFont(font, from_ascii("lyxtex"));
267 mathed_string_dim(font, name(), namedim);
269 dim.wid += 2 + namedim.wid + 2 + 2;
270 dim.asc = max(dim.asc, namedim.asc) + 2;
271 dim.des = max(dim.des, namedim.des) + 2;
273 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
274 dim.asc += 1 + namedim.height() + 1;
282 int MathMacro::kerning(BufferView const * bv) const {
283 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
284 return expanded_.kerning(bv);
290 void MathMacro::updateMacro(MacroContext const & mc)
293 macro_ = mc.get(name());
294 if (macro_ && macroBackup_ != *macro_) {
295 macroBackup_ = *macro_;
304 void MathMacro::updateRepresentation()
311 requires_ = macro_->requires();
313 // non-normal mode? We are done!
314 if (displayMode_ != DISPLAY_NORMAL)
321 needsUpdate_ = false;
323 // get default values of macro
324 vector<docstring> const & defaults = macro_->defaults();
326 // create MathMacroArgumentValue objects pointing to the cells of the macro
327 vector<MathData> values(nargs());
328 for (size_t i = 0; i < nargs(); ++i) {
329 ArgumentProxy * proxy;
330 if (i < defaults.size())
331 proxy = new ArgumentProxy(*this, i, defaults[i]);
333 proxy = new ArgumentProxy(*this, i);
334 values[i].insert(0, MathAtom(proxy));
336 // expanding macro with the values
337 macro_->expand(values, expanded_.cell(0));
338 // get definition for list edit mode
339 docstring const & display = macro_->display();
340 asArray(display.empty() ? macro_->definition() : display, definition_);
344 void MathMacro::draw(PainterInfo & pi, int x, int y) const
346 Dimension const dim = dimension(*pi.base.bv);
348 setPosCache(pi, x, y);
352 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
353 FontSetChanger dummy(pi.base, "lyxtex");
354 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
355 } else if (displayMode_ == DISPLAY_UNFOLDED) {
356 FontSetChanger dummy(pi.base, "lyxtex");
357 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
358 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
359 cell(0).draw(pi, x, y);
360 drawMarkers(pi, expx, expy);
361 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
362 && editing_[pi.base.bv]) {
363 // Macro will be edited in a old-style list mode here:
365 CoordCache const & coords = pi.base.bv->coordCache();
366 FontInfo const & labelFont = sane_font;
368 // markers and box needs two pixels
371 // get maximal font height
373 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
376 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
377 pi.pain.text(x, y, label, labelFont);
378 x += mathed_string_width(labelFont, label);
381 definition_.draw(pi, x, y);
382 Dimension const & defDim = coords.getArrays().dim(&definition_);
383 y += max(fontDim.des, defDim.des);
386 docstring str = from_ascii("#9");
387 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
388 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
390 for (idx_type i = 0; i < nargs(); ++i) {
392 Dimension const & cdim = coords.getArrays().dim(&cell(i));
394 y += max(fontDim.asc, cdim.asc) + 1;
398 pi.pain.text(x, y, str, labelFont);
400 pi.pain.text(x, y, from_ascii(":"), labelFont);
404 cell(i).draw(pi, x, y);
407 y += max(fontDim.des, cdim.des);
410 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
411 dim.height() - 2, Color_mathmacroframe);
412 drawMarkers2(pi, expx, expy);
414 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
417 for (size_t i = 0; i < nargs(); ++i)
418 cell(i).setXY(*pi.base.bv, x, y);
420 if (drawBox && editing_[pi.base.bv]) {
421 // draw header and rectangle around
422 FontInfo font = pi.base.font;
423 augmentFont(font, from_ascii("lyxtex"));
424 font.setSize(FONT_SIZE_TINY);
425 font.setColor(Color_mathmacrolabel);
427 mathed_string_dim(font, name(), namedim);
429 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
430 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
431 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
434 if (editing_[pi.base.bv]) {
435 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
436 expanded_.cell(0).draw(pi, expx, expy);
437 pi.pain.leaveMonochromeMode();
440 pi.pain.rectangle(x, y - dim.asc, dim.wid,
441 dim.height(), Color_mathmacroframe);
443 expanded_.cell(0).draw(pi, expx, expy);
446 drawMarkers(pi, x, y);
449 // edit mode changed?
450 if (editing_[pi.base.bv] != editMode(pi.base.bv))
451 pi.base.bv->cursor().updateFlags(Update::SinglePar);
455 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
457 // We may have 0 arguments, but InsetMathNest requires at least one.
458 if (cells_.size() > 0)
459 InsetMathNest::drawSelection(pi, x, y);
463 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
465 if (displayMode_ != mode) {
466 // transfer name if changing from or to DISPLAY_UNFOLDED
467 if (mode == DISPLAY_UNFOLDED) {
469 asArray(name_, cell(0));
470 } else if (displayMode_ == DISPLAY_UNFOLDED) {
471 name_ = asString(cell(0));
479 // the interactive init mode is non-greedy by default
481 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
483 appetite_ = size_t(appetite);
487 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
489 if (nextFoldMode_ == true && macro_ && !macro_->locked())
490 return DISPLAY_NORMAL;
492 return DISPLAY_UNFOLDED;
496 bool MathMacro::validName() const
498 docstring n = name();
504 // converting back and force doesn't swallow anything?
507 if (asString(ma) != n)
511 for (size_t i = 0; i<n.size(); ++i) {
512 if (!(n[i] >= 'a' && n[i] <= 'z')
513 && !(n[i] >= 'A' && n[i] <= 'Z')
522 void MathMacro::validate(LaTeXFeatures & features) const
524 if (!requires_.empty())
525 features.require(requires_);
527 if (name() == "binom")
528 features.require("binom");
530 // validate the cells and the definition
531 if (displayMode() == DISPLAY_NORMAL) {
532 definition_.validate(features);
533 InsetMathNest::validate(features);
538 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
540 cur.updateFlags(Update::SinglePar);
541 InsetMathNest::edit(cur, front, entry_from);
545 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
547 // We may have 0 arguments, but InsetMathNest requires at least one.
549 cur.updateFlags(Update::SinglePar);
550 return InsetMathNest::editXY(cur, x, y);
556 void MathMacro::removeArgument(Inset::pos_type pos) {
557 if (displayMode_ == DISPLAY_NORMAL) {
558 LASSERT(size_t(pos) < cells_.size(), /**/);
559 cells_.erase(cells_.begin() + pos);
560 if (size_t(pos) < attachedArgsNum_)
562 if (size_t(pos) < optionals_) {
571 void MathMacro::insertArgument(Inset::pos_type pos) {
572 if (displayMode_ == DISPLAY_NORMAL) {
573 LASSERT(size_t(pos) <= cells_.size(), /**/);
574 cells_.insert(cells_.begin() + pos, MathData());
575 if (size_t(pos) < attachedArgsNum_)
577 if (size_t(pos) < optionals_)
585 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
587 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
590 // strip off empty cells, but not more than arity-attachedArgsNum_
593 for (i = cells_.size(); i > attachedArgsNum_; --i)
594 if (!cell(i - 1).empty()) break;
598 attachedArgsNum_ = 0;
599 expanded_.cell(0) = MathData();
606 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
608 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
610 attachedArgsNum_ = args.size();
611 cells_.resize(arity);
612 expanded_.cell(0) = MathData();
613 optionals_ = optionals;
619 bool MathMacro::idxFirst(Cursor & cur) const
621 cur.updateFlags(Update::SinglePar);
622 return InsetMathNest::idxFirst(cur);
626 bool MathMacro::idxLast(Cursor & cur) const
628 cur.updateFlags(Update::SinglePar);
629 return InsetMathNest::idxLast(cur);
633 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
635 if (displayMode_ == DISPLAY_UNFOLDED) {
636 docstring const & unfolded_name = name();
637 if (unfolded_name != name_) {
638 // The macro name was changed
639 Cursor inset_cursor = old;
640 int macroSlice = inset_cursor.find(this);
641 LASSERT(macroSlice != -1, /**/);
642 inset_cursor.cutOff(macroSlice);
643 inset_cursor.recordUndoInset();
645 inset_cursor.cell().erase(inset_cursor.pos());
646 inset_cursor.cell().insert(inset_cursor.pos(),
647 createInsetMath(unfolded_name, cur.buffer()));
648 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
652 cur.updateFlags(Update::Force);
653 return InsetMathNest::notifyCursorLeaves(old, cur);
657 void MathMacro::fold(Cursor & cur)
659 if (!nextFoldMode_) {
660 nextFoldMode_ = true;
661 cur.updateFlags(Update::SinglePar);
666 void MathMacro::unfold(Cursor & cur)
669 nextFoldMode_ = false;
670 cur.updateFlags(Update::SinglePar);
675 bool MathMacro::folded() const
677 return nextFoldMode_;
681 void MathMacro::write(WriteStream & os) const
683 MathEnsurer ensurer(os, macro_ != 0, true);
686 if (displayMode_ != DISPLAY_NORMAL) {
687 os << "\\" << name();
688 if (name().size() != 1 || isAlphaASCII(name()[0]))
689 os.pendingSpace(true);
694 LASSERT(macro_, /**/);
696 // optional arguments make macros fragile
697 if (optionals_ > 0 && os.fragile())
700 os << "\\" << name();
703 // Optional arguments:
704 // First find last non-empty optional argument
705 idx_type emptyOptFrom = 0;
707 for (; i < cells_.size() && i < optionals_; ++i) {
708 if (!cell(i).empty())
709 emptyOptFrom = i + 1;
712 // print out optionals
713 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
715 os << "[" << cell(i) << "]";
718 // skip the tailing empty optionals
721 // Print remaining arguments
722 for (; i < cells_.size(); ++i) {
723 if (cell(i).size() == 1
724 && cell(i)[0].nucleus()->asCharInset()
725 && cell(i)[0].nucleus()->asCharInset()->getChar() < 0x80) {
730 os << "{" << cell(i) << "}";
734 // add space if there was no argument
736 os.pendingSpace(true);
740 void MathMacro::maple(MapleStream & os) const
742 lyx::maple(expanded_.cell(0), os);
746 docstring MathMacro::mathmlize(MathStream & os) const
748 os << expanded_.cell(0);
753 void MathMacro::octave(OctaveStream & os) const
755 lyx::octave(expanded_.cell(0), os);
759 void MathMacro::infoize(odocstream & os) const
761 os << "Macro: " << name();
765 void MathMacro::infoize2(odocstream & os) const
767 os << "Macro: " << name();
772 bool MathMacro::completionSupported(Cursor const & cur) const
774 if (displayMode() != DISPLAY_UNFOLDED)
775 return InsetMathNest::completionSupported(cur);
777 return lyxrc.completion_popup_math
778 && displayMode() == DISPLAY_UNFOLDED
779 && cur.bv().cursor().pos() == int(name().size());
783 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
785 if (displayMode() != DISPLAY_UNFOLDED)
786 return InsetMathNest::inlineCompletionSupported(cur);
788 return lyxrc.completion_inline_math
789 && displayMode() == DISPLAY_UNFOLDED
790 && cur.bv().cursor().pos() == int(name().size());
794 bool MathMacro::automaticInlineCompletion() const
796 if (displayMode() != DISPLAY_UNFOLDED)
797 return InsetMathNest::automaticInlineCompletion();
799 return lyxrc.completion_inline_math;
803 bool MathMacro::automaticPopupCompletion() const
805 if (displayMode() != DISPLAY_UNFOLDED)
806 return InsetMathNest::automaticPopupCompletion();
808 return lyxrc.completion_popup_math;
812 CompletionList const *
813 MathMacro::createCompletionList(Cursor const & cur) const
815 if (displayMode() != DISPLAY_UNFOLDED)
816 return InsetMathNest::createCompletionList(cur);
818 return new MathCompletionList(cur.bv().cursor());
822 docstring MathMacro::completionPrefix(Cursor const & cur) const
824 if (displayMode() != DISPLAY_UNFOLDED)
825 return InsetMathNest::completionPrefix(cur);
827 if (!completionSupported(cur))
830 return "\\" + name();
834 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
837 if (displayMode() != DISPLAY_UNFOLDED)
838 return InsetMathNest::insertCompletion(cur, s, finished);
840 if (!completionSupported(cur))
844 docstring newName = name() + s;
845 asArray(newName, cell(0));
846 cur.bv().cursor().pos() = name().size();
847 cur.updateFlags(Update::SinglePar);
851 cur.bv().cursor().pop();
852 ++cur.bv().cursor().pos();
853 cur.updateFlags(Update::SinglePar);
860 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
861 Dimension & dim) const
863 if (displayMode() != DISPLAY_UNFOLDED)
864 InsetMathNest::completionPosAndDim(cur, x, y, dim);
866 // get inset dimensions
867 dim = cur.bv().coordCache().insets().dim(this);
868 // FIXME: these 3 are no accurate, but should depend on the font.
869 // Now the popup jumps down if you enter a char with descent > 0.
875 = cur.bv().coordCache().insets().xy(this);