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"
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 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
63 void metrics(MetricsInfo & mi, Dimension & dim) const {
64 mathMacro_.macro()->unlock();
65 mathMacro_.cell(idx_).metrics(mi, dim);
67 if (!mathMacro_.editMetrics(mi.base.bv)
68 && mathMacro_.cell(idx_).empty())
69 def_.metrics(mi, dim);
71 mathMacro_.macro()->lock();
73 // FIXME Other external things need similar treatment.
75 void mathmlize(MathStream & ms) const { ms << mathMacro_.cell(idx_); }
77 void htmlize(HtmlStream & ms) const { ms << mathMacro_.cell(idx_); }
79 void draw(PainterInfo & pi, int x, int y) const {
80 if (mathMacro_.editMetrics(pi.base.bv)) {
81 // The only way a ArgumentProxy can appear is in a cell of the
82 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
83 // mode and then, if the macro is edited the monochrome
84 // mode is entered by the MathMacro before calling the cells' draw
85 // method. Then eventually this code is reached and the proxy leaves
86 // monochrome mode temporarely. Hence, if it is not in monochrome
87 // here (and the assert triggers in pain.leaveMonochromeMode())
89 pi.pain.leaveMonochromeMode();
90 mathMacro_.cell(idx_).draw(pi, x, y);
91 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
92 } else if (mathMacro_.cell(idx_).empty()) {
93 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
96 mathMacro_.cell(idx_).draw(pi, x, y);
99 size_t idx() const { return idx_; }
101 int kerning(BufferView const * bv) const
103 if (mathMacro_.editMetrics(bv)
104 || !mathMacro_.cell(idx_).empty())
105 return mathMacro_.cell(idx_).kerning(bv);
107 return def_.kerning(bv);
112 Inset * clone() const
114 return new ArgumentProxy(*this);
117 MathMacro & mathMacro_;
125 MathMacro::MathMacro(Buffer * buf, docstring const & name)
126 : InsetMathNest(buf, 0), name_(name), displayMode_(DISPLAY_INIT),
127 expanded_(buf), attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
128 macroBackup_(buf), macro_(0), needsUpdate_(false), appetite_(9)
132 Inset * MathMacro::clone() const
134 MathMacro * copy = new MathMacro(*this);
135 copy->needsUpdate_ = true;
136 //copy->expanded_.cell(0).clear();
141 docstring MathMacro::name() const
143 if (displayMode_ == DISPLAY_UNFOLDED)
144 return asString(cell(0));
150 void MathMacro::cursorPos(BufferView const & bv,
151 CursorSlice const & sl, bool boundary, int & x, int & y) const
153 // We may have 0 arguments, but InsetMathNest requires at least one.
155 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
159 bool MathMacro::editMode(BufferView const * bv) const {
160 // find this in cursor trace
161 Cursor const & cur = bv->cursor();
162 for (size_t i = 0; i != cur.depth(); ++i)
163 if (&cur[i].inset() == this) {
164 // look if there is no other macro in edit mode above
166 for (; i != cur.depth(); ++i) {
167 InsetMath * im = cur[i].asInsetMath();
169 MathMacro const * macro = im->asMacro();
170 if (macro && macro->displayMode() == DISPLAY_NORMAL)
175 // ok, none found, I am the highest one
183 bool MathMacro::editMetrics(BufferView const * bv) const
189 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
191 // set edit mode for which we will have calculated metrics. But only
192 editing_[mi.base.bv] = editMode(mi.base.bv);
194 // calculate new metrics according to display mode
195 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
196 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
197 } else if (displayMode_ == DISPLAY_UNFOLDED) {
198 cell(0).metrics(mi, dim);
200 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
201 dim.wid += bsdim.width() + 1;
202 dim.asc = max(bsdim.ascent(), dim.ascent());
203 dim.des = max(bsdim.descent(), dim.descent());
205 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
206 && editing_[mi.base.bv]) {
207 // Macro will be edited in a old-style list mode here:
209 LASSERT(macro_ != 0, /**/);
211 FontInfo labelFont = sane_font;
212 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
214 // get dimension of components of list view
216 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
217 nameDim.asc = fontDim.asc;
218 nameDim.des = fontDim.des;
221 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
222 argDim.asc = fontDim.asc;
223 argDim.des = fontDim.des;
226 definition_.metrics(mi, defDim);
229 dim.wid = nameDim.wid + defDim.wid;
230 dim.asc = max(nameDim.asc, defDim.asc);
231 dim.des = max(nameDim.des, defDim.des);
233 for (idx_type i = 0; i < nargs(); ++i) {
235 cell(i).metrics(mi, cdim);
236 dim.des += max(argDim.height(), cdim.height()) + 1;
237 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
240 // make space for box and markers, 2 pixels
244 metricsMarkers2(dim);
246 LASSERT(macro_ != 0, /**/);
248 // calculate metrics, hoping that all cells are seen
250 expanded_.cell(0).metrics(mi, dim);
252 // otherwise do a manual metrics call
253 CoordCache & coords = mi.base.bv->coordCache();
254 for (idx_type i = 0; i < nargs(); ++i) {
255 if (!coords.getArrays().has(&cell(i))) {
257 cell(i).metrics(mi, tdim);
262 // calculate dimension with label while editing
263 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
264 && editing_[mi.base.bv]) {
265 FontInfo font = mi.base.font;
266 augmentFont(font, from_ascii("lyxtex"));
268 mathed_string_dim(font, name(), namedim);
270 dim.wid += 2 + namedim.wid + 2 + 2;
271 dim.asc = max(dim.asc, namedim.asc) + 2;
272 dim.des = max(dim.des, namedim.des) + 2;
274 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
275 dim.asc += 1 + namedim.height() + 1;
283 int MathMacro::kerning(BufferView const * bv) const {
284 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
285 return expanded_.kerning(bv);
291 void MathMacro::updateMacro(MacroContext const & mc)
294 macro_ = mc.get(name());
295 if (macro_ && macroBackup_ != *macro_) {
296 macroBackup_ = *macro_;
305 void MathMacro::updateRepresentation()
312 requires_ = macro_->requires();
315 // non-normal mode? We are done!
316 || (displayMode_ != DISPLAY_NORMAL))
319 needsUpdate_ = false;
321 // get default values of macro
322 vector<docstring> const & defaults = macro_->defaults();
324 // create MathMacroArgumentValue objects pointing to the cells of the macro
325 vector<MathData> values(nargs());
326 for (size_t i = 0; i < nargs(); ++i) {
327 ArgumentProxy * proxy;
328 if (i < defaults.size())
329 proxy = new ArgumentProxy(*this, i, defaults[i]);
331 proxy = new ArgumentProxy(*this, i);
332 values[i].insert(0, MathAtom(proxy));
334 // expanding macro with the values
335 macro_->expand(values, expanded_.cell(0));
336 // get definition for list edit mode
337 docstring const & display = macro_->display();
338 asArray(display.empty() ? macro_->definition() : display, definition_);
342 void MathMacro::draw(PainterInfo & pi, int x, int y) const
344 Dimension const dim = dimension(*pi.base.bv);
346 setPosCache(pi, x, y);
350 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
351 FontSetChanger dummy(pi.base, "lyxtex");
352 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
353 } else if (displayMode_ == DISPLAY_UNFOLDED) {
354 FontSetChanger dummy(pi.base, "lyxtex");
355 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
356 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
357 cell(0).draw(pi, x, y);
358 drawMarkers(pi, expx, expy);
359 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
360 && editing_[pi.base.bv]) {
361 // Macro will be edited in a old-style list mode here:
363 CoordCache const & coords = pi.base.bv->coordCache();
364 FontInfo const & labelFont = sane_font;
366 // markers and box needs two pixels
369 // get maximal font height
371 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
374 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
375 pi.pain.text(x, y, label, labelFont);
376 x += mathed_string_width(labelFont, label);
379 definition_.draw(pi, x, y);
380 Dimension const & defDim = coords.getArrays().dim(&definition_);
381 y += max(fontDim.des, defDim.des);
384 docstring str = from_ascii("#9");
385 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
386 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
388 for (idx_type i = 0; i < nargs(); ++i) {
390 Dimension const & cdim = coords.getArrays().dim(&cell(i));
392 y += max(fontDim.asc, cdim.asc) + 1;
396 pi.pain.text(x, y, str, labelFont);
398 pi.pain.text(x, y, from_ascii(":"), labelFont);
402 cell(i).draw(pi, x, y);
405 y += max(fontDim.des, cdim.des);
408 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
409 dim.height() - 2, Color_mathmacroframe);
410 drawMarkers2(pi, expx, expy);
412 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
415 for (size_t i = 0; i < nargs(); ++i)
416 cell(i).setXY(*pi.base.bv, x, y);
418 if (drawBox && editing_[pi.base.bv]) {
419 // draw header and rectangle around
420 FontInfo font = pi.base.font;
421 augmentFont(font, from_ascii("lyxtex"));
422 font.setSize(FONT_SIZE_TINY);
423 font.setColor(Color_mathmacrolabel);
425 mathed_string_dim(font, name(), namedim);
427 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
428 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
429 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
432 if (editing_[pi.base.bv]) {
433 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
434 expanded_.cell(0).draw(pi, expx, expy);
435 pi.pain.leaveMonochromeMode();
438 pi.pain.rectangle(x, y - dim.asc, dim.wid,
439 dim.height(), Color_mathmacroframe);
441 expanded_.cell(0).draw(pi, expx, expy);
444 drawMarkers(pi, x, y);
447 // edit mode changed?
448 if (editing_[pi.base.bv] != editMode(pi.base.bv))
449 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
453 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
455 // We may have 0 arguments, but InsetMathNest requires at least one.
456 if (cells_.size() > 0)
457 InsetMathNest::drawSelection(pi, x, y);
461 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
463 if (displayMode_ != mode) {
464 // transfer name if changing from or to DISPLAY_UNFOLDED
465 if (mode == DISPLAY_UNFOLDED) {
467 asArray(name_, cell(0));
468 } else if (displayMode_ == DISPLAY_UNFOLDED) {
469 name_ = asString(cell(0));
477 // the interactive init mode is non-greedy by default
479 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
481 appetite_ = size_t(appetite);
485 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
487 if (nextFoldMode_ == true && macro_ && !macro_->locked())
488 return DISPLAY_NORMAL;
490 return DISPLAY_UNFOLDED;
494 bool MathMacro::validName() const
496 docstring n = name();
502 // converting back and force doesn't swallow anything?
505 if (asString(ma) != n)
509 for (size_t i = 0; i<n.size(); ++i) {
510 if (!(n[i] >= 'a' && n[i] <= 'z')
511 && !(n[i] >= 'A' && n[i] <= 'Z')
520 void MathMacro::validate(LaTeXFeatures & features) const
522 if (!requires_.empty())
523 features.require(requires_);
525 if (name() == "binom")
526 features.require("binom");
528 // validate the cells and the definition
529 if (displayMode() == DISPLAY_NORMAL) {
530 definition_.validate(features);
531 InsetMathNest::validate(features);
536 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
538 cur.screenUpdateFlags(Update::SinglePar);
539 InsetMathNest::edit(cur, front, entry_from);
543 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
545 // We may have 0 arguments, but InsetMathNest requires at least one.
547 cur.screenUpdateFlags(Update::SinglePar);
548 return InsetMathNest::editXY(cur, x, y);
554 void MathMacro::removeArgument(Inset::pos_type pos) {
555 if (displayMode_ == DISPLAY_NORMAL) {
556 LASSERT(size_t(pos) < cells_.size(), /**/);
557 cells_.erase(cells_.begin() + pos);
558 if (size_t(pos) < attachedArgsNum_)
560 if (size_t(pos) < optionals_) {
569 void MathMacro::insertArgument(Inset::pos_type pos) {
570 if (displayMode_ == DISPLAY_NORMAL) {
571 LASSERT(size_t(pos) <= cells_.size(), /**/);
572 cells_.insert(cells_.begin() + pos, MathData());
573 if (size_t(pos) < attachedArgsNum_)
575 if (size_t(pos) < optionals_)
583 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
585 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
588 // strip off empty cells, but not more than arity-attachedArgsNum_
591 for (i = cells_.size(); i > attachedArgsNum_; --i)
592 if (!cell(i - 1).empty()) break;
596 attachedArgsNum_ = 0;
597 expanded_.cell(0) = MathData();
604 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
606 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
608 attachedArgsNum_ = args.size();
609 cells_.resize(arity);
610 expanded_.cell(0) = MathData();
611 optionals_ = optionals;
617 bool MathMacro::idxFirst(Cursor & cur) const
619 cur.screenUpdateFlags(Update::SinglePar);
620 return InsetMathNest::idxFirst(cur);
624 bool MathMacro::idxLast(Cursor & cur) const
626 cur.screenUpdateFlags(Update::SinglePar);
627 return InsetMathNest::idxLast(cur);
631 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
633 if (displayMode_ == DISPLAY_UNFOLDED) {
634 docstring const & unfolded_name = name();
635 if (unfolded_name != name_) {
636 // The macro name was changed
637 Cursor inset_cursor = old;
638 int macroSlice = inset_cursor.find(this);
639 LASSERT(macroSlice != -1, /**/);
640 inset_cursor.cutOff(macroSlice);
641 inset_cursor.recordUndoInset();
643 inset_cursor.cell().erase(inset_cursor.pos());
644 inset_cursor.cell().insert(inset_cursor.pos(),
645 createInsetMath(unfolded_name, cur.buffer()));
647 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
651 cur.screenUpdateFlags(Update::Force);
652 return InsetMathNest::notifyCursorLeaves(old, cur);
656 void MathMacro::fold(Cursor & cur)
658 if (!nextFoldMode_) {
659 nextFoldMode_ = true;
660 cur.screenUpdateFlags(Update::SinglePar);
665 void MathMacro::unfold(Cursor & cur)
668 nextFoldMode_ = false;
669 cur.screenUpdateFlags(Update::SinglePar);
674 bool MathMacro::folded() const
676 return nextFoldMode_;
680 void MathMacro::write(WriteStream & os) const
682 MathEnsurer ensurer(os, macro_ != 0, true);
685 if (displayMode_ != DISPLAY_NORMAL) {
686 os << "\\" << name();
687 if (name().size() != 1 || isAlphaASCII(name()[0]))
688 os.pendingSpace(true);
693 LASSERT(macro_, /**/);
695 // optional arguments make macros fragile
696 if (optionals_ > 0 && os.fragile())
699 os << "\\" << name();
702 // Optional arguments:
703 // First find last non-empty optional argument
704 idx_type emptyOptFrom = 0;
706 for (; i < cells_.size() && i < optionals_; ++i) {
707 if (!cell(i).empty())
708 emptyOptFrom = i + 1;
711 // print out optionals
712 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
714 os << "[" << cell(i) << "]";
717 // skip the tailing empty optionals
720 // Print remaining arguments
721 for (; i < cells_.size(); ++i) {
722 if (cell(i).size() == 1
723 && cell(i)[0].nucleus()->asCharInset()
724 && cell(i)[0].nucleus()->asCharInset()->getChar() < 0x80) {
729 os << "{" << cell(i) << "}";
733 // add space if there was no argument
735 os.pendingSpace(true);
739 void MathMacro::maple(MapleStream & os) const
741 lyx::maple(expanded_.cell(0), os);
745 void MathMacro::mathmlize(MathStream & os) const
747 os << expanded_.cell(0);
751 void MathMacro::htmlize(HtmlStream & os) const
753 os << expanded_.cell(0);
757 void MathMacro::octave(OctaveStream & os) const
759 lyx::octave(expanded_.cell(0), os);
763 void MathMacro::infoize(odocstream & os) const
765 os << "Macro: " << name();
769 void MathMacro::infoize2(odocstream & os) const
771 os << "Macro: " << name();
776 bool MathMacro::completionSupported(Cursor const & cur) const
778 if (displayMode() != DISPLAY_UNFOLDED)
779 return InsetMathNest::completionSupported(cur);
781 return lyxrc.completion_popup_math
782 && displayMode() == DISPLAY_UNFOLDED
783 && cur.bv().cursor().pos() == int(name().size());
787 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
789 if (displayMode() != DISPLAY_UNFOLDED)
790 return InsetMathNest::inlineCompletionSupported(cur);
792 return lyxrc.completion_inline_math
793 && displayMode() == DISPLAY_UNFOLDED
794 && cur.bv().cursor().pos() == int(name().size());
798 bool MathMacro::automaticInlineCompletion() const
800 if (displayMode() != DISPLAY_UNFOLDED)
801 return InsetMathNest::automaticInlineCompletion();
803 return lyxrc.completion_inline_math;
807 bool MathMacro::automaticPopupCompletion() const
809 if (displayMode() != DISPLAY_UNFOLDED)
810 return InsetMathNest::automaticPopupCompletion();
812 return lyxrc.completion_popup_math;
816 CompletionList const *
817 MathMacro::createCompletionList(Cursor const & cur) const
819 if (displayMode() != DISPLAY_UNFOLDED)
820 return InsetMathNest::createCompletionList(cur);
822 return new MathCompletionList(cur.bv().cursor());
826 docstring MathMacro::completionPrefix(Cursor const & cur) const
828 if (displayMode() != DISPLAY_UNFOLDED)
829 return InsetMathNest::completionPrefix(cur);
831 if (!completionSupported(cur))
834 return "\\" + name();
838 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
841 if (displayMode() != DISPLAY_UNFOLDED)
842 return InsetMathNest::insertCompletion(cur, s, finished);
844 if (!completionSupported(cur))
848 docstring newName = name() + s;
849 asArray(newName, cell(0));
850 cur.bv().cursor().pos() = name().size();
851 cur.screenUpdateFlags(Update::SinglePar);
855 cur.bv().cursor().pop();
856 ++cur.bv().cursor().pos();
857 cur.screenUpdateFlags(Update::SinglePar);
864 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
865 Dimension & dim) const
867 if (displayMode() != DISPLAY_UNFOLDED)
868 InsetMathNest::completionPosAndDim(cur, x, y, dim);
870 // get inset dimensions
871 dim = cur.bv().coordCache().insets().dim(this);
872 // FIXME: these 3 are no accurate, but should depend on the font.
873 // Now the popup jumps down if you enter a char with descent > 0.
879 = cur.bv().coordCache().insets().xy(this);