]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacro.cpp
* dynamic macros as described in http://1stein.org/download/dynmacro.pdf
[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 "Cursor.h"
23 #include "debug.h"
24 #include "LaTeXFeatures.h"
25 #include "FuncStatus.h"
26 #include "FuncRequest.h"
27 #include "Undo.h"
28
29 #include "frontends/Painter.h"
30
31 #include <vector>
32
33 namespace lyx {
34
35 using std::string;
36 using std::max;
37
38
39 /// A proxy for the macro values
40 class ArgumentProxy : public InsetMath {
41 public:
42         ///
43         ArgumentProxy(MathMacro & mathMacro, size_t idx) 
44                 : mathMacro_(mathMacro), idx_(idx) {}
45         ///
46         ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def) 
47                 : mathMacro_(mathMacro), idx_(idx) 
48         {
49                         asArray(def, def_);
50         }
51         ///
52         void metrics(MetricsInfo & mi, Dimension & dim) const {
53                 mathMacro_.macro()->unlock();
54                 mathMacro_.cell(idx_).metrics(mi, dim);
55                 if (!mathMacro_.editing() && !def_.empty())
56                         def_.metrics(mi, dim);
57                 mathMacro_.macro()->lock();
58         }
59         ///
60         void draw(PainterInfo & pi, int x, int y) const {
61                 if (mathMacro_.editing()) {
62                         pi.pain.leaveMonochromeMode();
63                         mathMacro_.cell(idx_).draw(pi, x, y);
64                         // FIXME: use real min/max colors here, not necessarely the ones of MathMacro are set
65                         pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
66                 } else {
67                         if (def_.empty())
68                                 mathMacro_.cell(idx_).draw(pi, x, y);
69                         else {
70                                 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
71                                 def_.draw(pi, x, y);
72                         }
73                 }
74         }
75         ///
76         size_t idx() const { return idx_; }
77         ///
78         int kerning() const { return mathMacro_.cell(idx_).kerning(); }
79
80 private:
81         ///
82         Inset * clone() const 
83         {
84                 return new ArgumentProxy(*this);
85         }
86         ///
87         MathMacro & mathMacro_;
88         ///
89         size_t idx_;
90         ///
91         MathData def_;
92 };
93
94
95 MathMacro::MathMacro(docstring const & name)
96         : InsetMathNest(0), name_(name), displayMode_(DISPLAY_INIT),
97                 attachedArgsNum_(0), previousCurIdx_(-1), 
98                 optionals_(0), nextFoldMode_(true),
99                 macro_(0), editing_(false), needsUpdate_(false)
100 {}
101
102
103 Inset * MathMacro::clone() const
104 {
105         MathMacro * copy = new MathMacro(*this);
106         copy->needsUpdate_ = true;
107         copy->expanded_.cell(0).clear();
108         return copy;
109 }
110
111
112 docstring MathMacro::name() const
113 {
114         if (displayMode_ == DISPLAY_UNFOLDED)
115                 return asString(cell(0));
116         else
117                 return name_;
118 }
119
120
121 void MathMacro::cursorPos(BufferView const & bv,
122                 CursorSlice const & sl, bool boundary, int & x, int & y) const
123 {
124         // We may have 0 arguments, but InsetMathNest requires at least one.
125         if (nargs() > 0)
126                 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
127 }
128
129
130 int MathMacro::cursorIdx(Cursor const & cur) const {
131         for (size_t i = 0; i != cur.depth(); ++i)
132                         if (&cur[i].inset() == this)
133                                 return cur[i].idx();
134         return -1;
135 }
136
137
138 bool MathMacro::editMode(Cursor const & cur) const {
139         // find this in cursor trace
140         for (size_t i = 0; i != cur.depth(); ++i)
141                 if (&cur[i].inset() == this) {
142                         // look if there is no other macro in edit mode above
143                         ++i;
144                         for (; i != cur.depth(); ++i) {
145                                 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
146                                 if (macro && macro->displayMode() == DISPLAY_NORMAL)
147                                         return false;
148                         }
149
150                         // ok, none found, I am the highest one
151                         return true;
152                 }
153
154         return false;
155 }
156
157
158 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
159 {
160         // calculate new metrics according to display mode
161         if (displayMode_ == DISPLAY_INIT) {
162                 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
163         } else if (displayMode_ == DISPLAY_UNFOLDED) {
164                 cell(0).metrics(mi, dim);
165                 Dimension bsdim;
166                 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
167                 dim.wid += bsdim.width() + 1;
168                 dim.asc = std::max(bsdim.ascent(), dim.ascent());
169                 dim.des = std::max(bsdim.descent(), dim.descent());
170                 metricsMarkers(dim);
171         } else {
172                 BOOST_ASSERT(macro_ != 0);
173
174                 // calculate metric finally
175                 macro_->lock();
176                 expanded_.cell(0).metrics(mi, dim);
177                 macro_->unlock();
178
179                 // calculate dimension with label while editing
180                 if (editing_) {
181                         FontInfo font = mi.base.font;
182                         augmentFont(font, from_ascii("lyxtex"));
183                         Dimension namedim;
184                         mathed_string_dim(font, name(), namedim);
185 #if 0
186                         dim.wid += 2 + namedim.wid + 2 + 2;
187                         dim.asc = std::max(dim.asc, namedim.asc) + 2;
188                         dim.des = std::max(dim.des, namedim.des) + 2;
189 #endif
190                         dim.wid = std::max(1 + namedim.wid + 1, 2 + dim.wid + 2);
191                         dim.asc += 1 + namedim.height() + 1;
192                         dim.des += 2;
193                 }
194         }
195
196         // Cache the inset dimension. 
197         setDimCache(mi, dim);
198 }
199
200
201 int MathMacro::kerning() const {
202         if (displayMode_ == DISPLAY_NORMAL && !editing_)
203                 return expanded_.kerning();
204         else
205                 return 0;
206 }
207
208
209 void MathMacro::updateMacro(MetricsInfo & mi) 
210 {
211         if (validName() && mi.macrocontext.has(name())) {
212                 macro_ = &mi.macrocontext.get(name());
213                 if (macroBackup_ != *macro_) {
214                         macroBackup_ = *macro_;
215                         needsUpdate_ = true;
216                 }
217         } else {
218                 macro_ = 0;
219         }
220 }
221
222
223 void MathMacro::updateRepresentation(MetricsInfo & mi) 
224 {
225         // index of child where the cursor is (or -1 if none is edited)
226         int curIdx = cursorIdx(mi.base.bv->cursor());
227         previousCurIdx_ = curIdx;
228
229         // known macro?
230         if (macro_) {
231                 requires_ = macro_->requires();
232
233                 if (displayMode_ == DISPLAY_NORMAL) {
234                         // set edit mode to draw box around if needed
235                         bool prevEditing = editing_; 
236                         editing_ = editMode(mi.base.bv->cursor());
237
238                         // editMode changed and we have to switch default value and hole of optional?
239                         if (optionals_ > 0 && nargs() > 0 && 
240                                         prevEditing != editing_)
241                                 needsUpdate_ = true;
242
243                         // macro changed?
244                         if (needsUpdate_) {
245                                 needsUpdate_ = false;
246
247                                 // get default values of macro
248                                 std::vector<docstring> const & defaults = macro_->defaults();
249
250                                 // create MathMacroArgumentValue objects pointing to the cells of the macro
251                                 std::vector<MathData> values(nargs());
252                                 for (size_t i = 0; i < nargs(); ++i) {
253                                         if (!cell(i).empty() || i >= defaults.size() || 
254                                                         defaults[i].empty() || curIdx == (int)i)
255                                                 values[i].insert(0, MathAtom(new ArgumentProxy(*this, i)));
256                                         else
257                                                 values[i].insert(0, MathAtom(new ArgumentProxy(*this, i, defaults[i])));
258                                 }
259
260                                 // expanding macro with the values
261                                 macro_->expand(values, expanded_.cell(0));
262                         }
263                 }
264         }
265 }
266
267
268 void MathMacro::draw(PainterInfo & pi, int x, int y) const
269 {
270         Dimension const dim = dimension(*pi.base.bv);
271
272         setPosCache(pi, x, y);
273         int expx = x;
274         int expy = y;
275
276         if (displayMode_ == DISPLAY_INIT) {             
277                 PainterInfo pi2(pi.base.bv, pi.pain);
278                 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
279                 //pi2.base.style = LM_ST_TEXT;
280                 pi2.pain.text(x, y, from_ascii("\\") + name(), pi2.base.font);
281         } else if (displayMode_ == DISPLAY_UNFOLDED) {
282                 PainterInfo pi2(pi.base.bv, pi.pain);
283                 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
284                 //pi2.base.style = LM_ST_TEXT;
285                 pi2.pain.text(x, y, from_ascii("\\"), pi2.base.font);
286                 x += mathed_string_width(pi2.base.font, from_ascii("\\")) + 1;
287                 cell(0).draw(pi2, x, y);
288                 drawMarkers(pi2, expx, expy);
289         } else {
290                 // warm up cells
291                 for (size_t i = 0; i < nargs(); ++i)
292                         cell(i).setXY(*pi.base.bv, x, y);
293
294                 if (editing_) {
295                         // draw header and rectangle around
296                         FontInfo font = pi.base.font;
297                         augmentFont(font, from_ascii("lyxtex"));
298                         font.setSize(FONT_SIZE_TINY);
299                         font.setColor(Color_mathmacrolabel);
300                         Dimension namedim;
301                         mathed_string_dim(font, name(), namedim);
302 #if 0
303                         pi.pain.fillRectangle(x, y - dim.asc, 2 + namedim.width() + 2, dim.height(), Color_mathmacrobg);
304                         pi.pain.text(x + 2, y, name(), font);
305                         expx += 2 + namew + 2;
306 #endif
307                         pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
308                         pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
309                         expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
310
311                         pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
312                         expanded_.cell(0).draw(pi, expx, expy);
313                         pi.pain.leaveMonochromeMode();
314                 } else
315                         expanded_.cell(0).draw(pi, expx, expy);
316
317                 // draw frame while editing
318                 if (editing_)
319                         pi.pain.rectangle(x, y - dim.asc, dim.wid, dim.height(), Color_mathmacroframe);
320         }
321
322         // another argument selected?
323         int curIdx = cursorIdx(pi.base.bv->cursor());
324         if (previousCurIdx_ != curIdx || editing_ != editMode(pi.base.bv->cursor()))
325                 pi.base.bv->cursor().updateFlags(Update::Force);
326 }
327
328
329 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
330 {
331         // We may have 0 arguments, but InsetMathNest requires at least one.
332         if (cells_.size() > 0)
333                 InsetMathNest::drawSelection(pi, x, y);
334 }
335
336
337 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode)
338 {
339         if (displayMode_ != mode) {             
340                 // transfer name if changing from or to DISPLAY_UNFOLDED
341                 if (mode == DISPLAY_UNFOLDED) {
342                         cells_.resize(1);
343                         asArray(name_, cell(0));
344                 } else if (displayMode_ == DISPLAY_UNFOLDED) {
345                         name_ = asString(cell(0));
346                         cells_.resize(0);
347                 }
348
349                 displayMode_ = mode;
350                 needsUpdate_ = true;
351         }
352 }
353
354
355 MathMacro::DisplayMode MathMacro::computeDisplayMode(MetricsInfo const & mi) const
356 {
357         if (nextFoldMode_ == true && macro_ && !macro_->locked())
358                 return DISPLAY_NORMAL;
359         else
360                 return DISPLAY_UNFOLDED;
361 }
362
363
364 bool MathMacro::validName() const
365 {
366         docstring n = name();
367
368         // empty name?
369         if (n.size() == 0)
370                 return false;
371
372         // converting back and force doesn't swallow anything?
373         /*MathData ma;
374         asArray(n, ma);
375         if (asString(ma) != n)
376                 return false;*/
377
378         // valid characters?
379         for (size_t i = 0; i<n.size(); ++i) {
380                 if (!(n[i] >= 'a' && n[i] <= 'z') &&
381                                 !(n[i] >= 'A' && n[i] <= 'Z')) 
382                         return false;
383         }
384
385         return true;
386 }
387
388
389 void MathMacro::validate(LaTeXFeatures & features) const
390 {
391         if (!requires_.empty())
392                 features.require(requires_);
393
394         if (name() == "binom" || name() == "mathcircumflex")
395                 features.require(to_utf8(name()));
396 }
397
398
399 void MathMacro::edit(Cursor & cur, bool left)
400 {
401         cur.updateFlags(Update::Force);
402         InsetMathNest::edit(cur, left);
403 }
404
405
406 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
407 {
408         // We may have 0 arguments, but InsetMathNest requires at least one.
409         if (nargs() > 0) {
410                 cur.updateFlags(Update::Force);
411                 return InsetMathNest::editXY(cur, x, y);                
412         } else
413                 return this;
414 }
415
416
417 void MathMacro::removeArgument(size_t pos) {
418         if (displayMode_ == DISPLAY_NORMAL) {
419                 BOOST_ASSERT(pos >= 0 && pos < cells_.size());
420                 cells_.erase(cells_.begin() + pos);
421                 if (pos < attachedArgsNum_)
422                         --attachedArgsNum_;
423                 if (pos < optionals_) {
424                         --optionals_;
425                 }
426
427                 needsUpdate_ = true;
428         }
429 }
430
431
432 void MathMacro::insertArgument(size_t pos) {
433         if (displayMode_ == DISPLAY_NORMAL) {
434                 BOOST_ASSERT(pos >= 0 && pos <= cells_.size());
435                 cells_.insert(cells_.begin() + pos, MathData());
436                 if (pos < attachedArgsNum_)
437                         ++attachedArgsNum_;
438                 if (pos < optionals_)
439                         ++optionals_;
440
441                 needsUpdate_ = true;
442         }
443 }
444
445
446 void MathMacro::detachArguments(std::vector<MathData> & args, bool strip)
447 {
448         BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);   
449         args = cells_;
450
451         // strip off empty cells, but not more than arity-attachedArgsNum_
452         if (strip) {
453                 size_t i;
454                 for (i = cells_.size(); i > attachedArgsNum_; --i)
455                         if (!cell(i - 1).empty()) break;
456                 args.resize(i);
457         }
458
459         attachedArgsNum_ = 0;
460         expanded_.cell(0) = MathData();
461         cells_.resize(0);
462
463         needsUpdate_ = true;
464 }
465
466
467 void MathMacro::attachArguments(std::vector<MathData> const & args, size_t arity, int optionals)
468 {
469         BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
470         cells_ = args;
471         attachedArgsNum_ = args.size();
472         cells_.resize(arity);
473         expanded_.cell(0) = MathData();
474         optionals_ = optionals;
475
476         needsUpdate_ = true;
477 }
478
479
480 bool MathMacro::idxFirst(Cursor & cur) const 
481 {
482         cur.updateFlags(Update::Force);
483         return InsetMathNest::idxFirst(cur);
484 }
485
486
487 bool MathMacro::idxLast(Cursor & cur) const 
488 {
489         cur.updateFlags(Update::Force);
490         return InsetMathNest::idxLast(cur);
491 }
492
493
494 bool MathMacro::notifyCursorLeaves(Cursor & cur)
495 {
496         cur.updateFlags(Update::Force);
497         return InsetMathNest::notifyCursorLeaves(cur);
498 }
499
500
501 void MathMacro::fold(Cursor & cur)
502 {
503         if (!nextFoldMode_) {
504                 nextFoldMode_ = true;
505                 cur.updateFlags(Update::Force);
506         }
507 }
508
509
510 void MathMacro::unfold(Cursor & cur)
511 {
512         if (nextFoldMode_) {
513                 nextFoldMode_ = false;
514                 cur.updateFlags(Update::Force);
515         }
516 }
517
518
519 bool MathMacro::folded() const
520 {
521         return nextFoldMode_;
522 }
523
524
525 void MathMacro::write(WriteStream & os) const
526 {
527         if (displayMode_ == DISPLAY_NORMAL) {
528                 BOOST_ASSERT(macro_);
529
530                 os << "\\" << name();
531                 bool first = true;
532                 size_t i = 0;
533
534                 // Use macroBackup_ instead of macro_ here, because
535                 // this is outside the metrics/draw calls, hence the macro_
536                 // variable can point to a MacroData which was freed already.
537                 std::vector<docstring> const & defaults = macroBackup_.defaults();
538
539                 // Optional argument
540                 if (os.latex()) {
541                         if (i < optionals_) {
542                                 // the first real optional, the others are non-optional in latex
543                                 if (!cell(i).empty()) {
544                                         first = false;
545                                         os << "[" << cell(0) << "]";
546                                 }
547
548                                 ++i;
549                         }
550                 } else {
551                         // In lyx mode print all in any case
552                         for (; i < cells_.size() && i < optionals_; ++i) {
553                                 first = false;
554                                 os << "[" << cell(i) << "]";
555                         }
556                 }
557
558                 for (; i < cells_.size(); ++i) {
559                         if (cell(i).empty() && i < optionals_) {
560                                 os << "{" << defaults[i] << "}";
561                         } else if (cell(i).size() == 1 && cell(i)[0].nucleus()->asCharInset()) {
562                                 if (first)
563                                         os << " ";
564                                 os << cell(i);
565                         }       else
566                                 os << "{" << cell(i) << "}";
567                         first = false;
568                 }
569                 if (first)
570                         os.pendingSpace(true);
571         } else {
572                 os << "\\" << name() << " ";
573                 os.pendingSpace(true);
574         }
575 }
576
577
578 void MathMacro::maple(MapleStream & os) const
579 {
580         lyx::maple(expanded_.cell(0), os);
581 }
582
583
584 void MathMacro::mathmlize(MathStream & os) const
585 {
586         lyx::mathmlize(expanded_.cell(0), os);
587 }
588
589
590 void MathMacro::octave(OctaveStream & os) const
591 {
592         lyx::octave(expanded_.cell(0), os);
593 }
594
595
596 void MathMacro::infoize(odocstream & os) const
597 {
598         os << "Macro: " << name();
599 }
600
601
602 void MathMacro::infoize2(odocstream & os) const
603 {
604         os << "Macro: " << name();
605
606 }
607
608
609 } // namespace lyx