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(BufferView const * bv) const { return mathMacro_.cell(idx_).kerning(bv); }
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 // set edit mode for which we will have calculated metrics
167 editing_[mi.base.bv] = editMode(mi.base.bv->cursor());
169 // calculate new metrics according to display mode
170 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
171 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
172 } else if (displayMode_ == DISPLAY_UNFOLDED) {
173 cell(0).metrics(mi, dim);
175 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
176 dim.wid += bsdim.width() + 1;
177 dim.asc = max(bsdim.ascent(), dim.ascent());
178 dim.des = max(bsdim.descent(), dim.descent());
181 BOOST_ASSERT(macro_ != 0);
183 // calculate metric finally
185 expanded_.cell(0).metrics(mi, dim);
188 // calculate dimension with label while editing
189 if (editing_[mi.base.bv]) {
190 FontInfo font = mi.base.font;
191 augmentFont(font, from_ascii("lyxtex"));
193 mathed_string_dim(font, name(), namedim);
195 dim.wid += 2 + namedim.wid + 2 + 2;
196 dim.asc = max(dim.asc, namedim.asc) + 2;
197 dim.des = max(dim.des, namedim.des) + 2;
199 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
200 dim.asc += 1 + namedim.height() + 1;
207 int MathMacro::kerning(BufferView const * bv) const {
208 if (displayMode_ == DISPLAY_NORMAL && !editing(bv))
209 return expanded_.kerning(bv);
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)
251 needsUpdate_ = false;
253 // get default values of macro
254 vector<docstring> const & defaults = macro_->defaults();
256 // create MathMacroArgumentValue objects pointing to the cells of the macro
257 vector<MathData> values(nargs());
258 for (size_t i = 0; i < nargs(); ++i) {
259 ArgumentProxy * proxy;
261 || i >= defaults.size()
262 || defaults[i].empty()
264 proxy = new ArgumentProxy(*this, i);
266 proxy = new ArgumentProxy(*this, i, defaults[i]);
267 values[i].insert(0, MathAtom(proxy));
270 // expanding macro with the values
271 macro_->expand(values, expanded_.cell(0));
276 void MathMacro::draw(PainterInfo & pi, int x, int y) const
278 Dimension const dim = dimension(*pi.base.bv);
280 setPosCache(pi, x, y);
284 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
285 PainterInfo pi2(pi.base.bv, pi.pain);
286 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
287 //pi2.base.style = LM_ST_TEXT;
288 pi2.pain.text(x, y, from_ascii("\\") + name(), pi2.base.font);
289 } else if (displayMode_ == DISPLAY_UNFOLDED) {
290 PainterInfo pi2(pi.base.bv, pi.pain);
291 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
292 //pi2.base.style = LM_ST_TEXT;
293 pi2.pain.text(x, y, from_ascii("\\"), pi2.base.font);
294 x += mathed_string_width(pi2.base.font, from_ascii("\\")) + 1;
295 cell(0).draw(pi2, x, y);
296 drawMarkers(pi2, expx, expy);
299 for (size_t i = 0; i < nargs(); ++i)
300 cell(i).setXY(*pi.base.bv, x, y);
302 if (editing_[pi.base.bv]) {
303 // draw header and rectangle around
304 FontInfo font = pi.base.font;
305 augmentFont(font, from_ascii("lyxtex"));
306 font.setSize(FONT_SIZE_TINY);
307 font.setColor(Color_mathmacrolabel);
309 mathed_string_dim(font, name(), namedim);
311 pi.pain.fillRectangle(x, y - dim.asc, 2 + namedim.width() + 2, dim.height(), Color_mathmacrobg);
312 pi.pain.text(x + 2, y, name(), font);
313 expx += 2 + namew + 2;
315 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
316 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
317 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
319 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
320 expanded_.cell(0).draw(pi, expx, expy);
321 pi.pain.leaveMonochromeMode();
323 expanded_.cell(0).draw(pi, expx, expy);
325 // draw frame while editing
326 if (editing_[pi.base.bv])
327 pi.pain.rectangle(x, y - dim.asc, dim.wid, dim.height(), Color_mathmacroframe);
330 // another argument selected or edit mode changed?
331 idx_type curIdx = cursorIdx(pi.base.bv->cursor());
332 if (previousCurIdx_[pi.base.bv] != curIdx
333 || editing_[pi.base.bv] != editMode(pi.base.bv->cursor()))
334 pi.base.bv->cursor().updateFlags(Update::Force);
338 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
340 // We may have 0 arguments, but InsetMathNest requires at least one.
341 if (cells_.size() > 0)
342 InsetMathNest::drawSelection(pi, x, y);
346 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode)
348 if (displayMode_ != mode) {
349 // transfer name if changing from or to DISPLAY_UNFOLDED
350 if (mode == DISPLAY_UNFOLDED) {
352 asArray(name_, cell(0));
353 } else if (displayMode_ == DISPLAY_UNFOLDED) {
354 name_ = asString(cell(0));
364 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
366 if (nextFoldMode_ == true && macro_ && !macro_->locked())
367 return DISPLAY_NORMAL;
369 return DISPLAY_UNFOLDED;
373 bool MathMacro::validName() const
375 docstring n = name();
381 // converting back and force doesn't swallow anything?
384 if (asString(ma) != n)
388 for (size_t i = 0; i<n.size(); ++i) {
389 if (!(n[i] >= 'a' && n[i] <= 'z') &&
390 !(n[i] >= 'A' && n[i] <= 'Z'))
398 void MathMacro::validate(LaTeXFeatures & features) const
400 if (!requires_.empty())
401 features.require(requires_);
403 if (name() == "binom" || name() == "mathcircumflex")
404 features.require(to_utf8(name()));
408 void MathMacro::edit(Cursor & cur, bool left)
410 cur.updateFlags(Update::Force);
411 InsetMathNest::edit(cur, left);
415 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
417 // We may have 0 arguments, but InsetMathNest requires at least one.
419 cur.updateFlags(Update::Force);
420 return InsetMathNest::editXY(cur, x, y);
426 void MathMacro::removeArgument(Inset::pos_type pos) {
427 if (displayMode_ == DISPLAY_NORMAL) {
428 BOOST_ASSERT(size_t(pos) < cells_.size());
429 cells_.erase(cells_.begin() + pos);
430 if (size_t(pos) < attachedArgsNum_)
432 if (size_t(pos) < optionals_) {
441 void MathMacro::insertArgument(Inset::pos_type pos) {
442 if (displayMode_ == DISPLAY_NORMAL) {
443 BOOST_ASSERT(size_t(pos) <= cells_.size());
444 cells_.insert(cells_.begin() + pos, MathData());
445 if (size_t(pos) < attachedArgsNum_)
447 if (size_t(pos) < optionals_)
455 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
457 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
460 // strip off empty cells, but not more than arity-attachedArgsNum_
463 for (i = cells_.size(); i > attachedArgsNum_; --i)
464 if (!cell(i - 1).empty()) break;
468 attachedArgsNum_ = 0;
469 expanded_.cell(0) = MathData();
476 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
478 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
480 attachedArgsNum_ = args.size();
481 cells_.resize(arity);
482 expanded_.cell(0) = MathData();
483 optionals_ = optionals;
489 bool MathMacro::idxFirst(Cursor & cur) const
491 cur.updateFlags(Update::Force);
492 return InsetMathNest::idxFirst(cur);
496 bool MathMacro::idxLast(Cursor & cur) const
498 cur.updateFlags(Update::Force);
499 return InsetMathNest::idxLast(cur);
503 bool MathMacro::notifyCursorLeaves(Cursor & cur)
505 cur.updateFlags(Update::Force);
506 return InsetMathNest::notifyCursorLeaves(cur);
510 void MathMacro::fold(Cursor & cur)
512 if (!nextFoldMode_) {
513 nextFoldMode_ = true;
514 cur.updateFlags(Update::Force);
519 void MathMacro::unfold(Cursor & cur)
522 nextFoldMode_ = false;
523 cur.updateFlags(Update::Force);
528 bool MathMacro::folded() const
530 return nextFoldMode_;
534 void MathMacro::write(WriteStream & os) const
537 if (displayMode_ != DISPLAY_NORMAL) {
538 os << "\\" << name() << " ";
539 os.pendingSpace(true);
544 BOOST_ASSERT(macro_);
546 // optional arguments make macros fragile
547 if (optionals_ > 0 && os.fragile())
550 os << "\\" << name();
553 // Optional arguments:
554 // First find last non-empty optional argument
555 idx_type emptyOptFrom = 0;
557 for (; i < cells_.size() && i < optionals_; ++i) {
558 if (!cell(i).empty())
559 emptyOptFrom = i + 1;
562 // print out optionals
563 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
565 os << "[" << cell(i) << "]";
568 // skip the tailing empty optionals
571 // Print remaining macros
572 for (; i < cells_.size(); ++i) {
573 if (cell(i).size() == 1
574 && cell(i)[0].nucleus()->asCharInset()) {
579 os << "{" << cell(i) << "}";
583 // add space if there was no argument
585 os.pendingSpace(true);
589 void MathMacro::maple(MapleStream & os) const
591 lyx::maple(expanded_.cell(0), os);
595 void MathMacro::mathmlize(MathStream & os) const
597 lyx::mathmlize(expanded_.cell(0), os);
601 void MathMacro::octave(OctaveStream & os) const
603 lyx::octave(expanded_.cell(0), os);
607 void MathMacro::infoize(odocstream & os) const
609 os << "Macro: " << name();
613 void MathMacro::infoize2(odocstream & os) const
615 os << "Macro: " << name();