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