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"
16 #include "MathSupport.h"
17 #include "MathExtern.h"
18 #include "MathStream.h"
21 #include "BufferView.h"
22 #include "CoordCache.h"
24 #include "support/debug.h"
25 #include "LaTeXFeatures.h"
27 #include "FuncStatus.h"
28 #include "FuncRequest.h"
31 #include "frontends/Painter.h"
41 /// A proxy for the macro values
42 class ArgumentProxy : public InsetMath {
45 ArgumentProxy(MathMacro & mathMacro, size_t idx)
46 : mathMacro_(mathMacro), idx_(idx) {}
48 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
49 : mathMacro_(mathMacro), idx_(idx)
54 void metrics(MetricsInfo & mi, Dimension & dim) const {
55 mathMacro_.macro()->unlock();
56 if (!mathMacro_.editMetrics(mi.base.bv)
57 && mathMacro_.cell(idx_).empty())
58 def_.metrics(mi, dim);
60 CoordCache & coords = mi.base.bv->coordCache();
61 dim = coords.arrays().dim(&mathMacro_.cell(idx_));
63 mathMacro_.macro()->lock();
66 void draw(PainterInfo & pi, int x, int y) const {
67 if (mathMacro_.editMetrics(pi.base.bv)) {
68 // The only way a ArgumentProxy can appear is in a cell of the
69 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
70 // mode and then, if the macro is edited the monochrome
71 // mode is entered by the MathMacro before calling the cells' draw
72 // method. Then eventually this code is reached and the proxy leaves
73 // monochrome mode temporarely. Hence, if it is not in monochrome
74 // here (and the assert triggers in pain.leaveMonochromeMode())
76 pi.pain.leaveMonochromeMode();
77 mathMacro_.cell(idx_).draw(pi, x, y);
78 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
79 } else if (mathMacro_.cell(idx_).empty()) {
80 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
83 mathMacro_.cell(idx_).draw(pi, x, y);
86 size_t idx() const { return idx_; }
88 int kerning(BufferView const * bv) const
90 if (mathMacro_.editMetrics(bv)
91 || !mathMacro_.cell(idx_).empty())
92 return mathMacro_.cell(idx_).kerning(bv);
94 return def_.kerning(bv);
101 return new ArgumentProxy(*this);
104 MathMacro & mathMacro_;
112 MathMacro::MathMacro(docstring const & name)
113 : InsetMathNest(0), name_(name), displayMode_(DISPLAY_INIT),
114 attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
115 macro_(0), needsUpdate_(false)
119 Inset * MathMacro::clone() const
121 MathMacro * copy = new MathMacro(*this);
122 copy->needsUpdate_ = true;
123 copy->expanded_.cell(0).clear();
128 docstring MathMacro::name() const
130 if (displayMode_ == DISPLAY_UNFOLDED)
131 return asString(cell(0));
137 void MathMacro::cursorPos(BufferView const & bv,
138 CursorSlice const & sl, bool boundary, int & x, int & y) const
140 // We may have 0 arguments, but InsetMathNest requires at least one.
142 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
146 bool MathMacro::editMode(BufferView const * bv) const {
147 // find this in cursor trace
148 Cursor const & cur = bv->cursor();
149 for (size_t i = 0; i != cur.depth(); ++i)
150 if (&cur[i].inset() == this) {
151 // look if there is no other macro in edit mode above
153 for (; i != cur.depth(); ++i) {
154 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
155 if (macro && macro->displayMode() == DISPLAY_NORMAL)
159 // ok, none found, I am the highest one
167 bool MathMacro::editMetrics(BufferView const * bv) const
173 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
175 // set edit mode for which we will have calculated metrics. But only
176 editing_[mi.base.bv] = editMode(mi.base.bv);
178 // calculate new metrics according to display mode
179 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
180 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
181 } else if (displayMode_ == DISPLAY_UNFOLDED) {
182 cell(0).metrics(mi, dim);
184 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
185 dim.wid += bsdim.width() + 1;
186 dim.asc = max(bsdim.ascent(), dim.ascent());
187 dim.des = max(bsdim.descent(), dim.descent());
189 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
190 && editing_[mi.base.bv]) {
191 // Macro will be edited in a old-style list mode here:
193 BOOST_ASSERT(macro_ != 0);
195 FontInfo labelFont = sane_font;
196 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
198 // get dimension of components of list view
200 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
201 nameDim.asc = fontDim.asc;
202 nameDim.des = fontDim.des;
205 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
206 argDim.asc = fontDim.asc;
207 argDim.des = fontDim.des;
210 definition_.metrics(mi, defDim);
213 dim.wid = nameDim.wid + defDim.wid;
214 dim.asc = max(nameDim.asc, defDim.asc);
215 dim.des = max(nameDim.des, defDim.des);
217 for (idx_type i = 0; i < nargs(); ++i) {
219 cell(i).metrics(mi, cdim);
220 dim.des += max(argDim.height(), cdim.height()) + 1;
221 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
224 // make space for box and markers, 2 pixels
228 metricsMarkers2(dim);
230 BOOST_ASSERT(macro_ != 0);
232 // metrics are computed here for the cells,
233 // in the proxy we will then use the dim from the cache
234 InsetMathNest::metrics(mi);
236 // calculate metrics finally
238 expanded_.cell(0).metrics(mi, dim);
241 // calculate dimension with label while editing
242 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
243 && editing_[mi.base.bv]) {
244 FontInfo font = mi.base.font;
245 augmentFont(font, from_ascii("lyxtex"));
247 mathed_string_dim(font, name(), namedim);
249 dim.wid += 2 + namedim.wid + 2 + 2;
250 dim.asc = max(dim.asc, namedim.asc) + 2;
251 dim.des = max(dim.des, namedim.des) + 2;
253 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
254 dim.asc += 1 + namedim.height() + 1;
262 int MathMacro::kerning(BufferView const * bv) const {
263 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
264 return expanded_.kerning(bv);
270 void MathMacro::updateMacro(MacroContext const & mc)
273 macro_ = mc.get(name());
274 if (macro_ && macroBackup_ != *macro_) {
275 macroBackup_ = *macro_;
284 void MathMacro::updateRepresentation(Cursor const * bvCur)
291 requires_ = macro_->requires();
293 // non-normal mode? We are done!
294 if (displayMode_ != DISPLAY_NORMAL)
299 needsUpdate_ = false;
301 // get default values of macro
302 vector<docstring> const & defaults = macro_->defaults();
304 // create MathMacroArgumentValue objects pointing to the cells of the macro
305 vector<MathData> values(nargs());
306 for (size_t i = 0; i < nargs(); ++i) {
307 ArgumentProxy * proxy;
308 if (i < defaults.size())
309 proxy = new ArgumentProxy(*this, i, defaults[i]);
311 proxy = new ArgumentProxy(*this, i);
312 values[i].insert(0, MathAtom(proxy));
315 // expanding macro with the values
316 macro_->expand(values, expanded_.cell(0));
318 // get definition for list edit mode
319 docstring const & display = macro_->display();
320 asArray(display.empty() ? macro_->definition() : display, definition_);
325 void MathMacro::draw(PainterInfo & pi, int x, int y) const
327 Dimension const dim = dimension(*pi.base.bv);
329 setPosCache(pi, x, y);
333 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
334 PainterInfo pi2(pi.base.bv, pi.pain);
335 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
336 //pi2.base.style = LM_ST_TEXT;
337 pi2.pain.text(x, y, from_ascii("\\") + name(), pi2.base.font);
338 } else if (displayMode_ == DISPLAY_UNFOLDED) {
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("\\"), pi2.base.font);
343 x += mathed_string_width(pi2.base.font, from_ascii("\\")) + 1;
344 cell(0).draw(pi2, x, y);
345 drawMarkers(pi2, expx, expy);
346 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
347 && editing_[pi.base.bv]) {
348 // Macro will be edited in a old-style list mode here:
350 CoordCache & coords = pi.base.bv->coordCache();
351 FontInfo const & labelFont = sane_font;
353 // markers and box needs two pixels
356 // get maximal font height
358 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
361 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
362 pi.pain.text(x, y, label, labelFont);
363 x += mathed_string_width(labelFont, label);
366 definition_.draw(pi, x, y);
368 = coords.arrays().dim(&definition_);
369 y += max(fontDim.des, defDim.des);
372 docstring str = from_ascii("#9");
373 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
374 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
376 for (idx_type i = 0; i < nargs(); ++i) {
379 = coords.arrays().dim(&cell(i));
381 y += max(fontDim.asc, cdim.asc) + 1;
385 pi.pain.text(x, y, str, labelFont);
387 pi.pain.text(x, y, from_ascii(":"), labelFont);
391 cell(i).draw(pi, x, y);
394 y += max(fontDim.des, cdim.des);
397 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
398 dim.height() - 2, Color_mathmacroframe);
399 drawMarkers2(pi, expx, expy);
401 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
404 for (size_t i = 0; i < nargs(); ++i)
405 cell(i).setXY(*pi.base.bv, x, y);
407 if (drawBox && editing_[pi.base.bv]) {
408 // draw header and rectangle around
409 FontInfo font = pi.base.font;
410 augmentFont(font, from_ascii("lyxtex"));
411 font.setSize(FONT_SIZE_TINY);
412 font.setColor(Color_mathmacrolabel);
414 mathed_string_dim(font, name(), namedim);
416 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
417 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
418 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
421 if (editing_[pi.base.bv]) {
422 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
423 expanded_.cell(0).draw(pi, expx, expy);
424 pi.pain.leaveMonochromeMode();
427 pi.pain.rectangle(x, y - dim.asc, dim.wid,
428 dim.height(), Color_mathmacroframe);
430 expanded_.cell(0).draw(pi, expx, expy);
433 drawMarkers(pi, x, y);
436 // edit mode changed?
437 if (editing_[pi.base.bv] != editMode(pi.base.bv))
438 pi.base.bv->cursor().updateFlags(Update::Force);
442 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
444 // We may have 0 arguments, but InsetMathNest requires at least one.
445 if (cells_.size() > 0)
446 InsetMathNest::drawSelection(pi, x, y);
450 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode)
452 if (displayMode_ != mode) {
453 // transfer name if changing from or to DISPLAY_UNFOLDED
454 if (mode == DISPLAY_UNFOLDED) {
456 asArray(name_, cell(0));
457 } else if (displayMode_ == DISPLAY_UNFOLDED) {
458 name_ = asString(cell(0));
468 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
470 if (nextFoldMode_ == true && macro_ && !macro_->locked())
471 return DISPLAY_NORMAL;
473 return DISPLAY_UNFOLDED;
477 bool MathMacro::validName() const
479 docstring n = name();
485 // converting back and force doesn't swallow anything?
488 if (asString(ma) != n)
492 for (size_t i = 0; i<n.size(); ++i) {
493 if (!(n[i] >= 'a' && n[i] <= 'z') &&
494 !(n[i] >= 'A' && n[i] <= 'Z'))
502 void MathMacro::validate(LaTeXFeatures & features) const
504 if (!requires_.empty())
505 features.require(requires_);
507 if (name() == "binom" || name() == "mathcircumflex")
508 features.require(to_utf8(name()));
512 void MathMacro::edit(Cursor & cur, bool left)
514 cur.updateFlags(Update::Force);
515 InsetMathNest::edit(cur, left);
519 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
521 // We may have 0 arguments, but InsetMathNest requires at least one.
523 cur.updateFlags(Update::Force);
524 return InsetMathNest::editXY(cur, x, y);
530 void MathMacro::removeArgument(Inset::pos_type pos) {
531 if (displayMode_ == DISPLAY_NORMAL) {
532 BOOST_ASSERT(size_t(pos) < cells_.size());
533 cells_.erase(cells_.begin() + pos);
534 if (size_t(pos) < attachedArgsNum_)
536 if (size_t(pos) < optionals_) {
545 void MathMacro::insertArgument(Inset::pos_type pos) {
546 if (displayMode_ == DISPLAY_NORMAL) {
547 BOOST_ASSERT(size_t(pos) <= cells_.size());
548 cells_.insert(cells_.begin() + pos, MathData());
549 if (size_t(pos) < attachedArgsNum_)
551 if (size_t(pos) < optionals_)
559 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
561 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
564 // strip off empty cells, but not more than arity-attachedArgsNum_
567 for (i = cells_.size(); i > attachedArgsNum_; --i)
568 if (!cell(i - 1).empty()) break;
572 attachedArgsNum_ = 0;
573 expanded_.cell(0) = MathData();
580 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
582 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
584 attachedArgsNum_ = args.size();
585 cells_.resize(arity);
586 expanded_.cell(0) = MathData();
587 optionals_ = optionals;
593 bool MathMacro::idxFirst(Cursor & cur) const
595 cur.updateFlags(Update::Force);
596 return InsetMathNest::idxFirst(cur);
600 bool MathMacro::idxLast(Cursor & cur) const
602 cur.updateFlags(Update::Force);
603 return InsetMathNest::idxLast(cur);
607 bool MathMacro::notifyCursorLeaves(Cursor & cur)
609 cur.updateFlags(Update::Force);
610 return InsetMathNest::notifyCursorLeaves(cur);
614 void MathMacro::fold(Cursor & cur)
616 if (!nextFoldMode_) {
617 nextFoldMode_ = true;
618 cur.updateFlags(Update::Force);
623 void MathMacro::unfold(Cursor & cur)
626 nextFoldMode_ = false;
627 cur.updateFlags(Update::Force);
632 bool MathMacro::folded() const
634 return nextFoldMode_;
638 void MathMacro::write(WriteStream & os) const
641 if (displayMode_ != DISPLAY_NORMAL) {
642 os << "\\" << name() << " ";
643 os.pendingSpace(true);
648 BOOST_ASSERT(macro_);
650 // optional arguments make macros fragile
651 if (optionals_ > 0 && os.fragile())
654 os << "\\" << name();
657 // Optional arguments:
658 // First find last non-empty optional argument
659 idx_type emptyOptFrom = 0;
661 for (; i < cells_.size() && i < optionals_; ++i) {
662 if (!cell(i).empty())
663 emptyOptFrom = i + 1;
666 // print out optionals
667 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
669 os << "[" << cell(i) << "]";
672 // skip the tailing empty optionals
675 // Print remaining macros
676 for (; i < cells_.size(); ++i) {
677 if (cell(i).size() == 1
678 && cell(i)[0].nucleus()->asCharInset()) {
683 os << "{" << cell(i) << "}";
687 // add space if there was no argument
689 os.pendingSpace(true);
693 void MathMacro::maple(MapleStream & os) const
695 lyx::maple(expanded_.cell(0), os);
699 void MathMacro::mathmlize(MathStream & os) const
701 lyx::mathmlize(expanded_.cell(0), os);
705 void MathMacro::octave(OctaveStream & os) const
707 lyx::octave(expanded_.cell(0), os);
711 void MathMacro::infoize(odocstream & os) const
713 os << "Macro: " << name();
717 void MathMacro::infoize2(odocstream & os) const
719 os << "Macro: " << name();