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