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());
190 BOOST_ASSERT(macro_ != 0);
192 // metrics are computed here for the cells,
193 // in the proxy we will then use the dim from the cache
194 InsetMathNest::metrics(mi);
196 // calculate metrics finally
198 expanded_.cell(0).metrics(mi, dim);
201 // calculate dimension with label while editing
202 if (lyxrc.show_macro_label && editing_[mi.base.bv]) {
203 FontInfo font = mi.base.font;
204 augmentFont(font, from_ascii("lyxtex"));
206 mathed_string_dim(font, name(), namedim);
208 dim.wid += 2 + namedim.wid + 2 + 2;
209 dim.asc = max(dim.asc, namedim.asc) + 2;
210 dim.des = max(dim.des, namedim.des) + 2;
212 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
213 dim.asc += 1 + namedim.height() + 1;
220 int MathMacro::kerning(BufferView const * bv) const {
221 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
222 return expanded_.kerning(bv);
228 void MathMacro::updateMacro(MacroContext const & mc)
231 macro_ = mc.get(name());
232 if (macro_ && macroBackup_ != *macro_) {
233 macroBackup_ = *macro_;
242 void MathMacro::updateRepresentation(Cursor const * bvCur)
249 requires_ = macro_->requires();
251 // non-normal mode? We are done!
252 if (displayMode_ != DISPLAY_NORMAL)
257 needsUpdate_ = false;
259 // get default values of macro
260 vector<docstring> const & defaults = macro_->defaults();
262 // create MathMacroArgumentValue objects pointing to the cells of the macro
263 vector<MathData> values(nargs());
264 for (size_t i = 0; i < nargs(); ++i) {
265 ArgumentProxy * proxy;
266 if (i < defaults.size())
267 proxy = new ArgumentProxy(*this, i, defaults[i]);
269 proxy = new ArgumentProxy(*this, i);
270 values[i].insert(0, MathAtom(proxy));
273 // expanding macro with the values
274 macro_->expand(values, expanded_.cell(0));
279 void MathMacro::draw(PainterInfo & pi, int x, int y) const
281 Dimension const dim = dimension(*pi.base.bv);
283 setPosCache(pi, x, y);
287 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
288 PainterInfo pi2(pi.base.bv, pi.pain);
289 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
290 //pi2.base.style = LM_ST_TEXT;
291 pi2.pain.text(x, y, from_ascii("\\") + name(), pi2.base.font);
292 } else if (displayMode_ == DISPLAY_UNFOLDED) {
293 PainterInfo pi2(pi.base.bv, pi.pain);
294 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
295 //pi2.base.style = LM_ST_TEXT;
296 pi2.pain.text(x, y, from_ascii("\\"), pi2.base.font);
297 x += mathed_string_width(pi2.base.font, from_ascii("\\")) + 1;
298 cell(0).draw(pi2, x, y);
299 drawMarkers(pi2, expx, expy);
302 for (size_t i = 0; i < nargs(); ++i)
303 cell(i).setXY(*pi.base.bv, x, y);
305 if (lyxrc.show_macro_label && editing_[pi.base.bv]) {
306 // draw header and rectangle around
307 FontInfo font = pi.base.font;
308 augmentFont(font, from_ascii("lyxtex"));
309 font.setSize(FONT_SIZE_TINY);
310 font.setColor(Color_mathmacrolabel);
312 mathed_string_dim(font, name(), namedim);
314 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
315 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
316 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
319 if (editing_[pi.base.bv]) {
320 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
321 expanded_.cell(0).draw(pi, expx, expy);
322 pi.pain.leaveMonochromeMode();
324 if (lyxrc.show_macro_label)
325 pi.pain.rectangle(x, y - dim.asc, dim.wid,
326 dim.height(), Color_mathmacroframe);
328 expanded_.cell(0).draw(pi, expx, expy);
330 if (!lyxrc.show_macro_label)
331 drawMarkers(pi, x, y);
334 // edit mode changed?
335 if (editing_[pi.base.bv] != editMode(pi.base.bv))
336 pi.base.bv->cursor().updateFlags(Update::Force);
340 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
342 // We may have 0 arguments, but InsetMathNest requires at least one.
343 if (cells_.size() > 0)
344 InsetMathNest::drawSelection(pi, x, y);
348 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode)
350 if (displayMode_ != mode) {
351 // transfer name if changing from or to DISPLAY_UNFOLDED
352 if (mode == DISPLAY_UNFOLDED) {
354 asArray(name_, cell(0));
355 } else if (displayMode_ == DISPLAY_UNFOLDED) {
356 name_ = asString(cell(0));
366 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
368 if (nextFoldMode_ == true && macro_ && !macro_->locked())
369 return DISPLAY_NORMAL;
371 return DISPLAY_UNFOLDED;
375 bool MathMacro::validName() const
377 docstring n = name();
383 // converting back and force doesn't swallow anything?
386 if (asString(ma) != n)
390 for (size_t i = 0; i<n.size(); ++i) {
391 if (!(n[i] >= 'a' && n[i] <= 'z') &&
392 !(n[i] >= 'A' && n[i] <= 'Z'))
400 void MathMacro::validate(LaTeXFeatures & features) const
402 if (!requires_.empty())
403 features.require(requires_);
405 if (name() == "binom" || name() == "mathcircumflex")
406 features.require(to_utf8(name()));
410 void MathMacro::edit(Cursor & cur, bool left)
412 cur.updateFlags(Update::Force);
413 InsetMathNest::edit(cur, left);
417 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
419 // We may have 0 arguments, but InsetMathNest requires at least one.
421 cur.updateFlags(Update::Force);
422 return InsetMathNest::editXY(cur, x, y);
428 void MathMacro::removeArgument(Inset::pos_type pos) {
429 if (displayMode_ == DISPLAY_NORMAL) {
430 BOOST_ASSERT(size_t(pos) < cells_.size());
431 cells_.erase(cells_.begin() + pos);
432 if (size_t(pos) < attachedArgsNum_)
434 if (size_t(pos) < optionals_) {
443 void MathMacro::insertArgument(Inset::pos_type pos) {
444 if (displayMode_ == DISPLAY_NORMAL) {
445 BOOST_ASSERT(size_t(pos) <= cells_.size());
446 cells_.insert(cells_.begin() + pos, MathData());
447 if (size_t(pos) < attachedArgsNum_)
449 if (size_t(pos) < optionals_)
457 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
459 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
462 // strip off empty cells, but not more than arity-attachedArgsNum_
465 for (i = cells_.size(); i > attachedArgsNum_; --i)
466 if (!cell(i - 1).empty()) break;
470 attachedArgsNum_ = 0;
471 expanded_.cell(0) = MathData();
478 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
480 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
482 attachedArgsNum_ = args.size();
483 cells_.resize(arity);
484 expanded_.cell(0) = MathData();
485 optionals_ = optionals;
491 bool MathMacro::idxFirst(Cursor & cur) const
493 cur.updateFlags(Update::Force);
494 return InsetMathNest::idxFirst(cur);
498 bool MathMacro::idxLast(Cursor & cur) const
500 cur.updateFlags(Update::Force);
501 return InsetMathNest::idxLast(cur);
505 bool MathMacro::notifyCursorLeaves(Cursor & cur)
507 cur.updateFlags(Update::Force);
508 return InsetMathNest::notifyCursorLeaves(cur);
512 void MathMacro::fold(Cursor & cur)
514 if (!nextFoldMode_) {
515 nextFoldMode_ = true;
516 cur.updateFlags(Update::Force);
521 void MathMacro::unfold(Cursor & cur)
524 nextFoldMode_ = false;
525 cur.updateFlags(Update::Force);
530 bool MathMacro::folded() const
532 return nextFoldMode_;
536 void MathMacro::write(WriteStream & os) const
539 if (displayMode_ != DISPLAY_NORMAL) {
540 os << "\\" << name() << " ";
541 os.pendingSpace(true);
546 BOOST_ASSERT(macro_);
548 // optional arguments make macros fragile
549 if (optionals_ > 0 && os.fragile())
552 os << "\\" << name();
555 // Optional arguments:
556 // First find last non-empty optional argument
557 idx_type emptyOptFrom = 0;
559 for (; i < cells_.size() && i < optionals_; ++i) {
560 if (!cell(i).empty())
561 emptyOptFrom = i + 1;
564 // print out optionals
565 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
567 os << "[" << cell(i) << "]";
570 // skip the tailing empty optionals
573 // Print remaining macros
574 for (; i < cells_.size(); ++i) {
575 if (cell(i).size() == 1
576 && cell(i)[0].nucleus()->asCharInset()) {
581 os << "{" << cell(i) << "}";
585 // add space if there was no argument
587 os.pendingSpace(true);
591 void MathMacro::maple(MapleStream & os) const
593 lyx::maple(expanded_.cell(0), os);
597 void MathMacro::mathmlize(MathStream & os) const
599 lyx::mathmlize(expanded_.cell(0), os);
603 void MathMacro::octave(OctaveStream & os) const
605 lyx::octave(expanded_.cell(0), os);
609 void MathMacro::infoize(odocstream & os) const
611 os << "Macro: " << name();
615 void MathMacro::infoize2(odocstream & os) const
617 os << "Macro: " << name();