]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacro.cpp
c43fcd48984e92ad8404811da2c9efc3b84b7093
[lyx.git] / src / mathed / MathMacro.cpp
1 /**
2  * \file MathMacro.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author André Pönitz
8  * \author Stefan Schimanski
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "MathMacro.h"
16 #include "MathSupport.h"
17 #include "MathExtern.h"
18 #include "MathStream.h"
19
20 #include "Buffer.h"
21 #include "BufferView.h"
22 #include "CoordCache.h"
23 #include "Cursor.h"
24 #include "support/debug.h"
25 #include "LaTeXFeatures.h"
26 #include "LyXRC.h"
27 #include "FuncStatus.h"
28 #include "FuncRequest.h"
29 #include "Undo.h"
30
31 #include "frontends/Painter.h"
32
33 #include <ostream>
34 #include <vector>
35
36 using namespace std;
37
38 namespace lyx {
39
40
41 /// A proxy for the macro values
42 class ArgumentProxy : public InsetMath {
43 public:
44         ///
45         ArgumentProxy(MathMacro & mathMacro, size_t idx) 
46                 : mathMacro_(mathMacro), idx_(idx) {}
47         ///
48         ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def) 
49                 : mathMacro_(mathMacro), idx_(idx) 
50         {
51                         asArray(def, def_);
52         }
53         ///
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);
59                 else {
60                         CoordCache & coords = mi.base.bv->coordCache();
61                         dim = coords.arrays().dim(&mathMacro_.cell(idx_));
62                 }
63                 mathMacro_.macro()->lock();
64         }
65         ///
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()) 
75                         // it's a bug.
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);
81                         def_.draw(pi, x, y);
82                 } else
83                         mathMacro_.cell(idx_).draw(pi, x, y);
84         }
85         ///
86         size_t idx() const { return idx_; }
87         ///
88         int kerning(BufferView const * bv) const
89         { 
90                 if (mathMacro_.editMetrics(bv)
91                     || !mathMacro_.cell(idx_).empty())
92                         return mathMacro_.cell(idx_).kerning(bv); 
93                 else
94                         return def_.kerning(bv);
95         }
96
97 private:
98         ///
99         Inset * clone() const 
100         {
101                 return new ArgumentProxy(*this);
102         }
103         ///
104         MathMacro & mathMacro_;
105         ///
106         size_t idx_;
107         ///
108         MathData def_;
109 };
110
111
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)
116 {}
117
118
119 Inset * MathMacro::clone() const
120 {
121         MathMacro * copy = new MathMacro(*this);
122         copy->needsUpdate_ = true;
123         copy->expanded_.cell(0).clear();
124         return copy;
125 }
126
127
128 docstring MathMacro::name() const
129 {
130         if (displayMode_ == DISPLAY_UNFOLDED)
131                 return asString(cell(0));
132         else
133                 return name_;
134 }
135
136
137 void MathMacro::cursorPos(BufferView const & bv,
138                 CursorSlice const & sl, bool boundary, int & x, int & y) const
139 {
140         // We may have 0 arguments, but InsetMathNest requires at least one.
141         if (nargs() > 0)
142                 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
143 }
144
145
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
152                         ++i;
153                         for (; i != cur.depth(); ++i) {
154                                 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
155                                 if (macro && macro->displayMode() == DISPLAY_NORMAL)
156                                         return false;
157                         }
158
159                         // ok, none found, I am the highest one
160                         return true;
161                 }
162
163         return false;
164 }
165
166
167 bool MathMacro::editMetrics(BufferView const * bv) const
168 {
169         return editing_[bv];
170 }
171
172
173 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
174 {
175         // set edit mode for which we will have calculated metrics. But only
176         editing_[mi.base.bv] = editMode(mi.base.bv);
177
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);
183                 Dimension bsdim;
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());
188                 metricsMarkers(dim);
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:
192
193                 BOOST_ASSERT(macro_ != 0);
194                 Dimension fontDim;
195                 FontInfo labelFont = sane_font;
196                 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
197                 
198                 // get dimension of components of list view
199                 Dimension nameDim;
200                 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
201                 nameDim.asc = fontDim.asc;
202                 nameDim.des = fontDim.des;
203
204                 Dimension argDim;
205                 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
206                 argDim.asc = fontDim.asc;
207                 argDim.des = fontDim.des;
208                 
209                 Dimension defDim;
210                 definition_.metrics(mi, defDim);
211                 
212                 // add them up
213                 dim.wid = nameDim.wid + defDim.wid;
214                 dim.asc = max(nameDim.asc, defDim.asc);
215                 dim.des = max(nameDim.des, defDim.des);
216                 
217                 for (idx_type i = 0; i < nargs(); ++i) {
218                         Dimension cdim;
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);
222                 }
223                 
224                 // make space for box and markers, 2 pixels
225                 dim.asc += 1;
226                 dim.des += 1;
227                 dim.wid += 2;
228                 metricsMarkers2(dim);
229         } else {
230                 BOOST_ASSERT(macro_ != 0);
231
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);
235                 
236                 // calculate metrics finally
237                 macro_->lock();
238                 expanded_.cell(0).metrics(mi, dim);
239                 macro_->unlock();
240
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"));
246                         Dimension namedim;
247                         mathed_string_dim(font, name(), namedim);
248 #if 0
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;
252 #endif
253                         dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
254                         dim.asc += 1 + namedim.height() + 1;
255                         dim.des += 2;
256                 }
257          
258         }
259 }
260
261
262 int MathMacro::kerning(BufferView const * bv) const {
263         if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
264                 return expanded_.kerning(bv);
265         else
266                 return 0;
267 }
268
269
270 void MathMacro::updateMacro(MacroContext const & mc) 
271 {
272         if (validName()) {
273                 macro_ = mc.get(name());            
274                 if (macro_ && macroBackup_ != *macro_) {
275                         macroBackup_ = *macro_;
276                         needsUpdate_ = true;
277                 }
278         } else {
279                 macro_ = 0;
280         }
281 }
282
283
284 void MathMacro::updateRepresentation(Cursor const * bvCur)
285 {
286         // known macro?
287         if (macro_ == 0)
288                 return;
289
290         // update requires
291         requires_ = macro_->requires();
292         
293         // non-normal mode? We are done!
294         if (displayMode_ != DISPLAY_NORMAL)
295                 return;
296
297         // macro changed?
298         if (needsUpdate_) {
299                 needsUpdate_ = false;
300                 
301                 // get default values of macro
302                 vector<docstring> const & defaults = macro_->defaults();
303                 
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]);
310                         else
311                                 proxy = new ArgumentProxy(*this, i);
312                         values[i].insert(0, MathAtom(proxy));
313                 }
314                 
315                 // expanding macro with the values
316                 macro_->expand(values, expanded_.cell(0));
317
318                 // get definition for list edit mode
319                 docstring const & display = macro_->display();
320                 asArray(display.empty() ? macro_->definition() : display, definition_);
321         }
322 }
323
324
325 void MathMacro::draw(PainterInfo & pi, int x, int y) const
326 {
327         Dimension const dim = dimension(*pi.base.bv);
328
329         setPosCache(pi, x, y);
330         int expx = x;
331         int expy = y;
332
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:
349                 
350                 CoordCache & coords = pi.base.bv->coordCache();
351                 FontInfo const & labelFont = sane_font;
352                 
353                 // markers and box needs two pixels
354                 x += 2;
355                 
356                 // get maximal font height
357                 Dimension fontDim;
358                 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
359                 
360                 // draw label
361                 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
362                 pi.pain.text(x, y, label, labelFont);
363                 x += mathed_string_width(labelFont, label);
364
365                 // draw definition
366                 definition_.draw(pi, x, y);
367                 Dimension defDim
368                 = coords.arrays().dim(&definition_);
369                 y += max(fontDim.des, defDim.des);
370                                 
371                 // draw parameters
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(": "));
375                 
376                 for (idx_type i = 0; i < nargs(); ++i) {
377                         // position of label
378                         Dimension cdim
379                         = coords.arrays().dim(&cell(i));
380                         x = expx + 2;
381                         y += max(fontDim.asc, cdim.asc) + 1;
382                         
383                         // draw label
384                         str[1] = '1' + i;
385                         pi.pain.text(x, y, str, labelFont);
386                         x += strw1;
387                         pi.pain.text(x, y, from_ascii(":"), labelFont);
388                         x += strw2;
389                         
390                         // draw paramter
391                         cell(i).draw(pi, x, y);
392                         
393                         // next line
394                         y += max(fontDim.des, cdim.des);
395                 }
396                 
397                 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3, 
398                                   dim.height() - 2, Color_mathmacroframe);
399                 drawMarkers2(pi, expx, expy);
400         } else {
401                 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
402                 
403                 // warm up cells
404                 for (size_t i = 0; i < nargs(); ++i)
405                         cell(i).setXY(*pi.base.bv, x, y);
406
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);
413                         Dimension namedim;
414                         mathed_string_dim(font, name(), namedim);
415
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;
419                 }
420
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();
425
426                         if (drawBox)
427                                 pi.pain.rectangle(x, y - dim.asc, dim.wid, 
428                                                   dim.height(), Color_mathmacroframe);
429                 } else
430                         expanded_.cell(0).draw(pi, expx, expy);
431
432                 if (!drawBox)
433                         drawMarkers(pi, x, y);
434         }
435
436         // edit mode changed?
437         if (editing_[pi.base.bv] != editMode(pi.base.bv))
438                 pi.base.bv->cursor().updateFlags(Update::Force);
439 }
440
441
442 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
443 {
444         // We may have 0 arguments, but InsetMathNest requires at least one.
445         if (cells_.size() > 0)
446                 InsetMathNest::drawSelection(pi, x, y);
447 }
448
449
450 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode)
451 {
452         if (displayMode_ != mode) {             
453                 // transfer name if changing from or to DISPLAY_UNFOLDED
454                 if (mode == DISPLAY_UNFOLDED) {
455                         cells_.resize(1);
456                         asArray(name_, cell(0));
457                 } else if (displayMode_ == DISPLAY_UNFOLDED) {
458                         name_ = asString(cell(0));
459                         cells_.resize(0);
460                 }
461
462                 displayMode_ = mode;
463                 needsUpdate_ = true;
464         }
465 }
466
467
468 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
469 {
470         if (nextFoldMode_ == true && macro_ && !macro_->locked())
471                 return DISPLAY_NORMAL;
472         else
473                 return DISPLAY_UNFOLDED;
474 }
475
476
477 bool MathMacro::validName() const
478 {
479         docstring n = name();
480
481         // empty name?
482         if (n.size() == 0)
483                 return false;
484
485         // converting back and force doesn't swallow anything?
486         /*MathData ma;
487         asArray(n, ma);
488         if (asString(ma) != n)
489                 return false;*/
490
491         // valid characters?
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')) 
495                         return false;
496         }
497
498         return true;
499 }
500
501
502 void MathMacro::validate(LaTeXFeatures & features) const
503 {
504         if (!requires_.empty())
505                 features.require(requires_);
506
507         if (name() == "binom" || name() == "mathcircumflex")
508                 features.require(to_utf8(name()));
509 }
510
511
512 void MathMacro::edit(Cursor & cur, bool left)
513 {
514         cur.updateFlags(Update::Force);
515         InsetMathNest::edit(cur, left);
516 }
517
518
519 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
520 {
521         // We may have 0 arguments, but InsetMathNest requires at least one.
522         if (nargs() > 0) {
523                 cur.updateFlags(Update::Force);
524                 return InsetMathNest::editXY(cur, x, y);                
525         } else
526                 return this;
527 }
528
529
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_)
535                         --attachedArgsNum_;
536                 if (size_t(pos) < optionals_) {
537                         --optionals_;
538                 }
539
540                 needsUpdate_ = true;
541         }
542 }
543
544
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_)
550                         ++attachedArgsNum_;
551                 if (size_t(pos) < optionals_)
552                         ++optionals_;
553
554                 needsUpdate_ = true;
555         }
556 }
557
558
559 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
560 {
561         BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);   
562         args = cells_;
563
564         // strip off empty cells, but not more than arity-attachedArgsNum_
565         if (strip) {
566                 size_t i;
567                 for (i = cells_.size(); i > attachedArgsNum_; --i)
568                         if (!cell(i - 1).empty()) break;
569                 args.resize(i);
570         }
571
572         attachedArgsNum_ = 0;
573         expanded_.cell(0) = MathData();
574         cells_.resize(0);
575
576         needsUpdate_ = true;
577 }
578
579
580 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
581 {
582         BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
583         cells_ = args;
584         attachedArgsNum_ = args.size();
585         cells_.resize(arity);
586         expanded_.cell(0) = MathData();
587         optionals_ = optionals;
588
589         needsUpdate_ = true;
590 }
591
592
593 bool MathMacro::idxFirst(Cursor & cur) const 
594 {
595         cur.updateFlags(Update::Force);
596         return InsetMathNest::idxFirst(cur);
597 }
598
599
600 bool MathMacro::idxLast(Cursor & cur) const 
601 {
602         cur.updateFlags(Update::Force);
603         return InsetMathNest::idxLast(cur);
604 }
605
606
607 bool MathMacro::notifyCursorLeaves(Cursor & cur)
608 {
609         cur.updateFlags(Update::Force);
610         return InsetMathNest::notifyCursorLeaves(cur);
611 }
612
613
614 void MathMacro::fold(Cursor & cur)
615 {
616         if (!nextFoldMode_) {
617                 nextFoldMode_ = true;
618                 cur.updateFlags(Update::Force);
619         }
620 }
621
622
623 void MathMacro::unfold(Cursor & cur)
624 {
625         if (nextFoldMode_) {
626                 nextFoldMode_ = false;
627                 cur.updateFlags(Update::Force);
628         }
629 }
630
631
632 bool MathMacro::folded() const
633 {
634         return nextFoldMode_;
635 }
636
637
638 void MathMacro::write(WriteStream & os) const
639 {
640         // non-normal mode
641         if (displayMode_ != DISPLAY_NORMAL) {
642                 os << "\\" << name() << " ";
643                 os.pendingSpace(true);
644                 return;
645         }
646
647         // normal mode
648         BOOST_ASSERT(macro_);
649
650         // optional arguments make macros fragile
651         if (optionals_ > 0 && os.fragile())
652                 os << "\\protect";
653         
654         os << "\\" << name();
655         bool first = true;
656         
657         // Optional arguments:
658         // First find last non-empty optional argument
659         idx_type emptyOptFrom = 0;
660         idx_type i = 0;
661         for (; i < cells_.size() && i < optionals_; ++i) {
662                 if (!cell(i).empty())
663                         emptyOptFrom = i + 1;
664         }
665         
666         // print out optionals
667         for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
668                 first = false;
669                 os << "[" << cell(i) << "]";
670         }
671         
672         // skip the tailing empty optionals
673         i = optionals_;
674         
675         // Print remaining macros 
676         for (; i < cells_.size(); ++i) {
677                 if (cell(i).size() == 1 
678                          && cell(i)[0].nucleus()->asCharInset()) {
679                         if (first)
680                                 os << " ";
681                         os << cell(i);
682                 } else
683                         os << "{" << cell(i) << "}";
684                 first = false;
685         }
686
687         // add space if there was no argument
688         if (first)
689                 os.pendingSpace(true);
690 }
691
692
693 void MathMacro::maple(MapleStream & os) const
694 {
695         lyx::maple(expanded_.cell(0), os);
696 }
697
698
699 void MathMacro::mathmlize(MathStream & os) const
700 {
701         lyx::mathmlize(expanded_.cell(0), os);
702 }
703
704
705 void MathMacro::octave(OctaveStream & os) const
706 {
707         lyx::octave(expanded_.cell(0), os);
708 }
709
710
711 void MathMacro::infoize(odocstream & os) const
712 {
713         os << "Macro: " << name();
714 }
715
716
717 void MathMacro::infoize2(odocstream & os) const
718 {
719         os << "Macro: " << name();
720
721 }
722
723
724 } // namespace lyx