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"
23 #include "support/debug.h"
24 #include "LaTeXFeatures.h"
25 #include "FuncStatus.h"
26 #include "FuncRequest.h"
29 #include "frontends/Painter.h"
39 /// A proxy for the macro values
40 class ArgumentProxy : public InsetMath {
43 ArgumentProxy(MathMacro & mathMacro, size_t idx)
44 : mathMacro_(mathMacro), idx_(idx) {}
46 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
47 : mathMacro_(mathMacro), idx_(idx)
52 void metrics(MetricsInfo & mi, Dimension & dim) const {
53 mathMacro_.macro()->unlock();
54 mathMacro_.cell(idx_).metrics(mi, dim);
55 if (!mathMacro_.editing(mi.base.bv) && !def_.empty())
56 def_.metrics(mi, dim);
57 mathMacro_.macro()->lock();
60 void draw(PainterInfo & pi, int x, int y) const {
61 if (mathMacro_.editing(pi.base.bv)) {
62 // The only way a ArgumentProxy can appear is in a cell of the
63 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
64 // mode and then, in the case of "editing_ == true" the monochrome
65 // mode is entered by the MathMacro before calling the cells' draw
66 // method. Then eventually this code is reached and the proxy leaves
67 // monochrome mode temporarely. Hence, if it is not in monochrome
68 // here (and the assert triggers in pain.leaveMonochromeMode())
70 pi.pain.leaveMonochromeMode();
71 mathMacro_.cell(idx_).draw(pi, x, y);
72 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
75 mathMacro_.cell(idx_).draw(pi, x, y);
77 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
83 size_t idx() const { return idx_; }
85 int kerning() const { return mathMacro_.cell(idx_).kerning(); }
91 return new ArgumentProxy(*this);
94 MathMacro & mathMacro_;
102 MathMacro::MathMacro(docstring const & name)
103 : InsetMathNest(0), name_(name), displayMode_(DISPLAY_INIT),
104 attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
105 macro_(0), needsUpdate_(false)
109 Inset * MathMacro::clone() const
111 MathMacro * copy = new MathMacro(*this);
112 copy->needsUpdate_ = true;
113 copy->expanded_.cell(0).clear();
118 docstring MathMacro::name() const
120 if (displayMode_ == DISPLAY_UNFOLDED)
121 return asString(cell(0));
127 void MathMacro::cursorPos(BufferView const & bv,
128 CursorSlice const & sl, bool boundary, int & x, int & y) const
130 // We may have 0 arguments, but InsetMathNest requires at least one.
132 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
136 int MathMacro::cursorIdx(Cursor const & cur) const {
137 for (size_t i = 0; i != cur.depth(); ++i)
138 if (&cur[i].inset() == this)
144 bool MathMacro::editMode(Cursor const & cur) const {
145 // find this in cursor trace
146 for (size_t i = 0; i != cur.depth(); ++i)
147 if (&cur[i].inset() == this) {
148 // look if there is no other macro in edit mode above
150 for (; i != cur.depth(); ++i) {
151 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
152 if (macro && macro->displayMode() == DISPLAY_NORMAL)
156 // ok, none found, I am the highest one
164 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
166 // calculate new metrics according to display mode
167 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
168 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
169 } else if (displayMode_ == DISPLAY_UNFOLDED) {
170 cell(0).metrics(mi, dim);
172 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
173 dim.wid += bsdim.width() + 1;
174 dim.asc = max(bsdim.ascent(), dim.ascent());
175 dim.des = max(bsdim.descent(), dim.descent());
178 BOOST_ASSERT(macro_ != 0);
180 // calculate metric finally
182 expanded_.cell(0).metrics(mi, dim);
185 // calculate dimension with label while editing
186 if (editing_[mi.base.bv]) {
187 FontInfo font = mi.base.font;
188 augmentFont(font, from_ascii("lyxtex"));
190 mathed_string_dim(font, name(), namedim);
192 dim.wid += 2 + namedim.wid + 2 + 2;
193 dim.asc = max(dim.asc, namedim.asc) + 2;
194 dim.des = max(dim.des, namedim.des) + 2;
196 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
197 dim.asc += 1 + namedim.height() + 1;
202 // Cache the inset dimension.
203 setDimCache(mi, dim);
207 int MathMacro::kerning() const {
208 if (displayMode_ == DISPLAY_NORMAL)
209 return expanded_.kerning();
215 void MathMacro::updateMacro(MacroContext const & mc)
218 macro_ = mc.get(name());
219 if (macro_ && macroBackup_ != *macro_) {
220 macroBackup_ = *macro_;
229 void MathMacro::updateRepresentation(Cursor const * bvCur)
231 // index of child where the cursor is (or -1 if none is edited)
234 curIdx = cursorIdx(*bvCur);
235 previousCurIdx_[&bvCur->bv()] = curIdx;
243 requires_ = macro_->requires();
245 // non-normal mode? We are done!
246 if (displayMode_ != DISPLAY_NORMAL)
249 // set edit mode to draw box around if needed
250 bool prevEditing = false;
251 bool editing = false;
253 prevEditing = editing_[&bvCur->bv()];
254 editing = editMode(*bvCur);
255 editing_[&bvCur->bv()] = editing;
258 // editMode changed and we have to switch default value and hole of optional?
259 if (optionals_ > 0 && nargs() > 0 &&
260 prevEditing != editing)
265 needsUpdate_ = false;
267 // get default values of macro
268 vector<docstring> const & defaults = macro_->defaults();
270 // create MathMacroArgumentValue objects pointing to the cells of the macro
271 vector<MathData> values(nargs());
272 for (size_t i = 0; i < nargs(); ++i) {
273 ArgumentProxy * proxy;
275 || i >= defaults.size()
276 || defaults[i].empty()
278 proxy = new ArgumentProxy(*this, i);
280 proxy = new ArgumentProxy(*this, i, defaults[i]);
281 values[i].insert(0, MathAtom(proxy));
284 // expanding macro with the values
285 macro_->expand(values, expanded_.cell(0));
290 void MathMacro::draw(PainterInfo & pi, int x, int y) const
292 Dimension const dim = dimension(*pi.base.bv);
294 setPosCache(pi, x, y);
298 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
299 PainterInfo pi2(pi.base.bv, pi.pain);
300 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
301 //pi2.base.style = LM_ST_TEXT;
302 pi2.pain.text(x, y, from_ascii("\\") + name(), pi2.base.font);
303 } else if (displayMode_ == DISPLAY_UNFOLDED) {
304 PainterInfo pi2(pi.base.bv, pi.pain);
305 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
306 //pi2.base.style = LM_ST_TEXT;
307 pi2.pain.text(x, y, from_ascii("\\"), pi2.base.font);
308 x += mathed_string_width(pi2.base.font, from_ascii("\\")) + 1;
309 cell(0).draw(pi2, x, y);
310 drawMarkers(pi2, expx, expy);
313 for (size_t i = 0; i < nargs(); ++i)
314 cell(i).setXY(*pi.base.bv, x, y);
316 if (editing_[pi.base.bv]) {
317 // draw header and rectangle around
318 FontInfo font = pi.base.font;
319 augmentFont(font, from_ascii("lyxtex"));
320 font.setSize(FONT_SIZE_TINY);
321 font.setColor(Color_mathmacrolabel);
323 mathed_string_dim(font, name(), namedim);
325 pi.pain.fillRectangle(x, y - dim.asc, 2 + namedim.width() + 2, dim.height(), Color_mathmacrobg);
326 pi.pain.text(x + 2, y, name(), font);
327 expx += 2 + namew + 2;
329 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
330 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
331 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
333 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
334 expanded_.cell(0).draw(pi, expx, expy);
335 pi.pain.leaveMonochromeMode();
337 expanded_.cell(0).draw(pi, expx, expy);
339 // draw frame while editing
340 if (editing_[pi.base.bv])
341 pi.pain.rectangle(x, y - dim.asc, dim.wid, dim.height(), Color_mathmacroframe);
344 // another argument selected?
345 idx_type curIdx = cursorIdx(pi.base.bv->cursor());
346 if (previousCurIdx_[pi.base.bv] != curIdx
347 || editing_[pi.base.bv] != editMode(pi.base.bv->cursor()))
348 pi.base.bv->cursor().updateFlags(Update::Force);
352 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
354 // We may have 0 arguments, but InsetMathNest requires at least one.
355 if (cells_.size() > 0)
356 InsetMathNest::drawSelection(pi, x, y);
360 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode)
362 if (displayMode_ != mode) {
363 // transfer name if changing from or to DISPLAY_UNFOLDED
364 if (mode == DISPLAY_UNFOLDED) {
366 asArray(name_, cell(0));
367 } else if (displayMode_ == DISPLAY_UNFOLDED) {
368 name_ = asString(cell(0));
378 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
380 if (nextFoldMode_ == true && macro_ && !macro_->locked())
381 return DISPLAY_NORMAL;
383 return DISPLAY_UNFOLDED;
387 bool MathMacro::validName() const
389 docstring n = name();
395 // converting back and force doesn't swallow anything?
398 if (asString(ma) != n)
402 for (size_t i = 0; i<n.size(); ++i) {
403 if (!(n[i] >= 'a' && n[i] <= 'z') &&
404 !(n[i] >= 'A' && n[i] <= 'Z'))
412 void MathMacro::validate(LaTeXFeatures & features) const
414 if (!requires_.empty())
415 features.require(requires_);
417 if (name() == "binom" || name() == "mathcircumflex")
418 features.require(to_utf8(name()));
422 void MathMacro::edit(Cursor & cur, bool left)
424 cur.updateFlags(Update::Force);
425 InsetMathNest::edit(cur, left);
429 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
431 // We may have 0 arguments, but InsetMathNest requires at least one.
433 cur.updateFlags(Update::Force);
434 return InsetMathNest::editXY(cur, x, y);
440 void MathMacro::removeArgument(Inset::pos_type pos) {
441 if (displayMode_ == DISPLAY_NORMAL) {
442 BOOST_ASSERT(size_t(pos) < cells_.size());
443 cells_.erase(cells_.begin() + pos);
444 if (size_t(pos) < attachedArgsNum_)
446 if (size_t(pos) < optionals_) {
455 void MathMacro::insertArgument(Inset::pos_type pos) {
456 if (displayMode_ == DISPLAY_NORMAL) {
457 BOOST_ASSERT(size_t(pos) <= cells_.size());
458 cells_.insert(cells_.begin() + pos, MathData());
459 if (size_t(pos) < attachedArgsNum_)
461 if (size_t(pos) < optionals_)
469 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
471 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
474 // strip off empty cells, but not more than arity-attachedArgsNum_
477 for (i = cells_.size(); i > attachedArgsNum_; --i)
478 if (!cell(i - 1).empty()) break;
482 attachedArgsNum_ = 0;
483 expanded_.cell(0) = MathData();
490 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
492 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
494 attachedArgsNum_ = args.size();
495 cells_.resize(arity);
496 expanded_.cell(0) = MathData();
497 optionals_ = optionals;
503 bool MathMacro::idxFirst(Cursor & cur) const
505 cur.updateFlags(Update::Force);
506 return InsetMathNest::idxFirst(cur);
510 bool MathMacro::idxLast(Cursor & cur) const
512 cur.updateFlags(Update::Force);
513 return InsetMathNest::idxLast(cur);
517 bool MathMacro::notifyCursorLeaves(Cursor & cur)
519 cur.updateFlags(Update::Force);
520 return InsetMathNest::notifyCursorLeaves(cur);
524 void MathMacro::fold(Cursor & cur)
526 if (!nextFoldMode_) {
527 nextFoldMode_ = true;
528 cur.updateFlags(Update::Force);
533 void MathMacro::unfold(Cursor & cur)
536 nextFoldMode_ = false;
537 cur.updateFlags(Update::Force);
542 bool MathMacro::folded() const
544 return nextFoldMode_;
548 void MathMacro::write(WriteStream & os) const
551 if (displayMode_ != DISPLAY_NORMAL) {
552 os << "\\" << name() << " ";
553 os.pendingSpace(true);
558 BOOST_ASSERT(macro_);
560 // optional arguments make macros fragile
561 if (optionals_ > 0 && os.fragile())
564 os << "\\" << name();
568 // Use macroBackup_ instead of macro_ here, because
569 // this is outside the metrics/draw calls, hence the macro_
570 // variable can point to a MacroData which was freed already.
571 vector<docstring> const & defaults = macroBackup_.defaults();
575 // Print first optional in LaTeX semantics
576 if (i < optionals_) {
577 // the first real optional, the others are non-optional in latex
578 if (!cell(i).empty()) {
580 os << "[" << cell(0) << "]";
586 // In lyx mode print all in any case
587 for (; i < cells_.size() && i < optionals_; ++i) {
589 os << "[" << cell(i) << "]";
593 // Print remaining macros
594 // (also the further optional parameters in LaTeX mode!)
595 for (; i < cells_.size(); ++i) {
596 if (cell(i).empty() && i < optionals_)
597 os << "{" << defaults[i] << "}";
598 else if (cell(i).size() == 1
599 && cell(i)[0].nucleus()->asCharInset()) {
604 os << "{" << cell(i) << "}";
608 // add space if there was no argument
610 os.pendingSpace(true);
614 void MathMacro::maple(MapleStream & os) const
616 lyx::maple(expanded_.cell(0), os);
620 void MathMacro::mathmlize(MathStream & os) const
622 lyx::mathmlize(expanded_.cell(0), os);
626 void MathMacro::octave(OctaveStream & os) const
628 lyx::octave(expanded_.cell(0), os);
632 void MathMacro::infoize(odocstream & os) const
634 os << "Macro: " << name();
638 void MathMacro::infoize2(odocstream & os) const
640 os << "Macro: " << name();