]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacroTemplate.cpp
When selecting math with the mouse, selection happens in the middle (#9748)
[lyx.git] / src / mathed / MathMacroTemplate.cpp
1 /**
2  * \file MathMacroTemplate.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "MathMacroTemplate.h"
15
16 #include "InsetMathBrace.h"
17 #include "InsetMathChar.h"
18 #include "InsetMathHull.h"
19 #include "InsetMathSqrt.h"
20 #include "MathMacro.h"
21 #include "MathMacroArgument.h"
22 #include "MathStream.h"
23 #include "MathParser.h"
24 #include "MathSupport.h"
25 #include "MathMacroArgument.h"
26
27 #include "Buffer.h"
28 #include "BufferView.h"
29 #include "Color.h"
30 #include "Cursor.h"
31 #include "DispatchResult.h"
32 #include "DocIterator.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "LaTeXFeatures.h"
36 #include "Lexer.h"
37 #include "MetricsInfo.h"
38 #include "TocBackend.h"
39
40 #include "frontends/Painter.h"
41
42 #include "insets/RenderPreview.h"
43
44 #include "support/lassert.h"
45 #include "support/convert.h"
46 #include "support/debug.h"
47 #include "support/gettext.h"
48 #include "support/docstream.h"
49 #include "support/lstrings.h"
50
51 #include <set>
52 #include <sstream>
53
54 using namespace std;
55
56 namespace lyx {
57
58 using support::bformat;
59
60 //////////////////////////////////////////////////////////////////////
61
62 class InsetLabelBox : public InsetMathNest {
63 public:
64         ///
65         InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
66                       MathMacroTemplate const & parent, bool frame = false);
67         InsetLabelBox(Buffer * buf, docstring label, MathMacroTemplate const & parent,
68                       bool frame = false);
69         ///
70         void metrics(MetricsInfo & mi, Dimension & dim) const;
71         ///
72         void draw(PainterInfo &, int x, int y) const;
73
74 protected:
75         ///
76         MathMacroTemplate const & parent_;
77         ///
78         Inset * clone() const;
79         ///
80         docstring const label_;
81         ///
82         bool frame_;
83 };
84
85
86 InsetLabelBox::InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
87         MathMacroTemplate const & parent, bool frame)
88         : InsetMathNest(buf, 1), parent_(parent), label_(label), frame_(frame)
89 {
90         cell(0).insert(0, atom);
91 }
92
93
94 InsetLabelBox::InsetLabelBox(Buffer * buf, docstring label,
95                              MathMacroTemplate const & parent, bool frame)
96         : InsetMathNest(buf, 1), parent_(parent), label_(label), frame_(frame)
97 {
98 }
99
100
101 Inset * InsetLabelBox::clone() const
102 {
103         return new InsetLabelBox(*this);
104 }
105
106
107 void InsetLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
108 {
109         // kernel
110         cell(0).metrics(mi, dim);
111
112         // frame
113         if (frame_) {
114                 dim.wid += 6;
115                 dim.asc += 5;
116                 dim.des += 5;
117         }
118
119         // adjust to common height in main metrics phase
120         if (!parent_.premetrics()) {
121                 dim.asc = max(dim.asc, parent_.commonLabelBoxAscent());
122                 dim.des = max(dim.des, parent_.commonLabelBoxDescent());
123         }
124
125         // label
126         if (parent_.editing(mi.base.bv) && label_.length() > 0) {
127                 // grey
128                 FontInfo font = sane_font;
129                 font.setSize(FONT_SIZE_TINY);
130                 font.setColor(Color_mathmacrolabel);
131
132                 // make space for label and box
133                 int lwid = mathed_string_width(font, label_);
134                 int maxasc;
135                 int maxdes;
136                 math_font_max_dim(font, maxasc, maxdes);
137
138                 dim.wid = max(dim.wid, lwid + 2);
139
140                 // space for the label
141                 if (!parent_.premetrics())
142                         dim.des += maxasc + maxdes + 1;
143         }
144 }
145
146
147 void InsetLabelBox::draw(PainterInfo & pi, int x, int y) const
148 {
149         Dimension const dim = dimension(*pi.base.bv);
150         Dimension const cdim = cell(0).dimension(*pi.base.bv);
151
152         // kernel
153         cell(0).draw(pi, x + (dim.wid - cdim.wid) / 2, y);
154
155         // label
156         if (parent_.editing(pi.base.bv) && label_.length() > 0) {
157                 // grey
158                 FontInfo font = sane_font;
159                 font.setSize(FONT_SIZE_TINY);
160                 font.setColor(Color_mathmacrolabel);
161
162                 // make space for label and box
163                 int lwid = mathed_string_width(font, label_);
164                 int maxasc;
165                 int maxdes;
166                 math_font_max_dim(font, maxasc, maxdes);
167
168                 if (lwid < dim.wid)
169                         pi.pain.text(x + (dim.wid - lwid) / 2, y + dim.des - maxdes, label_, font);
170                 else
171                         pi.pain.text(x, y + dim.des - maxdes, label_, font);
172         }
173
174         // draw frame
175         int boxHeight = parent_.commonLabelBoxAscent() + parent_.commonLabelBoxDescent();
176         if (frame_) {
177                 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
178                                   dim.wid - 2, boxHeight - 2,
179                                   Color_mathline);
180         }
181 }
182
183
184 //////////////////////////////////////////////////////////////////////
185
186 class DisplayLabelBox : public InsetLabelBox {
187 public:
188         ///
189         DisplayLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
190                         MathMacroTemplate const & parent);
191
192         ///
193         void metrics(MetricsInfo & mi, Dimension & dim) const;
194         ///
195         void draw(PainterInfo &, int x, int y) const;
196
197 protected:
198         ///
199         Inset * clone() const;
200 };
201
202
203 DisplayLabelBox::DisplayLabelBox(Buffer * buf, MathAtom const & atom,
204                                  docstring label,
205                                  MathMacroTemplate const & parent)
206         : InsetLabelBox(buf, atom, label, parent, true)
207 {
208 }
209
210
211
212 Inset * DisplayLabelBox::clone() const
213 {
214         return new DisplayLabelBox(*this);
215 }
216
217
218 void DisplayLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
219 {
220         InsetLabelBox::metrics(mi, dim);
221         if (!parent_.editing(mi.base.bv)
222             && parent_.cell(parent_.displayIdx()).empty()) {
223                 dim.wid = 0;
224                 dim.asc = 0;
225                 dim.des = 0;
226         }
227 }
228
229
230 void DisplayLabelBox::draw(PainterInfo & pi, int x, int y) const
231 {
232         if (parent_.editing(pi.base.bv)
233             || !parent_.cell(parent_.displayIdx()).empty()) {
234                 InsetLabelBox::draw(pi, x, y);
235         } else {
236                 bool enabled = pi.pain.isDrawingEnabled();
237                 pi.pain.setDrawingEnabled(false);
238                 InsetLabelBox::draw(pi, x, y);
239                 pi.pain.setDrawingEnabled(enabled);
240         }
241 }
242
243
244 //////////////////////////////////////////////////////////////////////
245
246 class InsetMathWrapper : public InsetMath {
247 public:
248         ///
249         InsetMathWrapper(MathData const * value) : value_(value) {}
250         ///
251         void metrics(MetricsInfo & mi, Dimension & dim) const;
252         ///
253         void draw(PainterInfo &, int x, int y) const;
254
255 private:
256         ///
257         Inset * clone() const;
258         ///
259         MathData const * value_;
260 };
261
262
263 Inset * InsetMathWrapper::clone() const
264 {
265         return new InsetMathWrapper(*this);
266 }
267
268
269 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
270 {
271         value_->metrics(mi, dim);
272 }
273
274
275 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
276 {
277         value_->draw(pi, x, y);
278 }
279
280
281 ///////////////////////////////////////////////////////////////////////
282 class InsetColoredCell : public InsetMathNest {
283 public:
284         ///
285         InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max);
286         ///
287         InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max, MathAtom const & atom);
288         ///
289         void draw(PainterInfo &, int x, int y) const;
290         ///
291         void metrics(MetricsInfo & mi, Dimension & dim) const;
292
293 protected:
294         ///
295         Inset * clone() const;
296         ///
297         ColorCode min_;
298         ///
299         ColorCode max_;
300 };
301
302
303 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max)
304         : InsetMathNest(buf, 1), min_(min), max_(max)
305 {
306 }
307
308
309 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max, MathAtom const & atom)
310         : InsetMathNest(buf, 1), min_(min), max_(max)
311 {
312         cell(0).insert(0, atom);
313 }
314
315
316 Inset * InsetColoredCell::clone() const
317 {
318         return new InsetColoredCell(*this);
319 }
320
321
322 void InsetColoredCell::metrics(MetricsInfo & mi, Dimension & dim) const
323 {
324         cell(0).metrics(mi, dim);
325 }
326
327
328 void InsetColoredCell::draw(PainterInfo & pi, int x, int y) const
329 {
330         pi.pain.enterMonochromeMode(min_, max_);
331         cell(0).draw(pi, x, y);
332         pi.pain.leaveMonochromeMode();
333 }
334
335
336 ///////////////////////////////////////////////////////////////////////
337
338 class InsetNameWrapper : public InsetMathWrapper {
339 public:
340         ///
341         InsetNameWrapper(MathData const * value, MathMacroTemplate const & parent);
342         ///
343         void metrics(MetricsInfo & mi, Dimension & dim) const;
344         ///
345         void draw(PainterInfo &, int x, int y) const;
346
347 private:
348         ///
349         MathMacroTemplate const & parent_;
350         ///
351         Inset * clone() const;
352 };
353
354
355 InsetNameWrapper::InsetNameWrapper(MathData const * value,
356                                    MathMacroTemplate const & parent)
357         : InsetMathWrapper(value), parent_(parent)
358 {
359 }
360
361
362 Inset * InsetNameWrapper::clone() const
363 {
364         return new InsetNameWrapper(*this);
365 }
366
367
368 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
369 {
370         Changer dummy = mi.base.changeFontSet("textit");
371         InsetMathWrapper::metrics(mi, dim);
372         dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
373 }
374
375
376 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
377 {
378         ColorCode const color = parent_.validMacro() ? Color_latex : Color_error;
379
380         Changer dummy = pi.base.changeFontSet("textit");
381         Changer dummy2 = pi.base.font.changeColor(color);
382
383         // draw backslash
384         pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
385         x += mathed_string_width(pi.base.font, from_ascii("\\"));
386
387         // draw name
388         InsetMathWrapper::draw(pi, x, y);
389 }
390
391
392 ///////////////////////////////////////////////////////////////////////
393
394
395 MathMacroTemplate::MathMacroTemplate(Buffer * buf)
396         : InsetMathNest(buf, 3), numargs_(0), argsInLook_(0), optionals_(0),
397           type_(MacroTypeNewcommand), redefinition_(false), lookOutdated_(true),
398           premetrics_(false), labelBoxAscent_(0), labelBoxDescent_(0)
399 {
400         initMath();
401 }
402
403
404 MathMacroTemplate::MathMacroTemplate(Buffer * buf, docstring const & name, int numargs,
405         int optionals, MacroType type, vector<MathData> const & optionalValues,
406         MathData const & def, MathData const & display)
407         : InsetMathNest(buf, optionals + 3), numargs_(numargs), argsInLook_(numargs),
408           optionals_(optionals), optionalValues_(optionalValues),
409           type_(type), redefinition_(false), lookOutdated_(true),
410           premetrics_(false), labelBoxAscent_(0), labelBoxDescent_(0)
411 {
412         initMath();
413
414         if (numargs_ > 9)
415                 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
416                         << numargs_ << endl;
417
418         asArray(name, cell(0));
419         optionalValues_.resize(9);
420         for (int i = 0; i < optionals_; ++i)
421                 cell(optIdx(i)) = optionalValues_[i];
422         cell(defIdx()) = def;
423         cell(displayIdx()) = display;
424
425         updateLook();
426 }
427
428
429 bool MathMacroTemplate::fromString(docstring const & str)
430 {
431         MathData ar(buffer_);
432         mathed_parse_cell(ar, str, Parse::NORMAL);
433         if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
434                 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
435                 asArray(from_ascii("invalidmacro"), cell(0));
436                 // The macro template does not make sense after this.
437                 return false;
438         }
439         operator=( *(ar[0]->asMacroTemplate()) );
440
441         updateLook();
442         return true;
443 }
444
445
446 Inset * MathMacroTemplate::clone() const
447 {
448         MathMacroTemplate * inset = new MathMacroTemplate(*this);
449         // the parent pointers of the proxy insets above will point to
450         // to the old template. Hence, the look must be updated.
451         inset->updateLook();
452         return inset;
453 }
454
455
456 docstring MathMacroTemplate::name() const
457 {
458         return asString(cell(0));
459 }
460
461
462 void MathMacroTemplate::updateToContext(MacroContext const & mc)
463 {
464         redefinition_ = mc.get(name()) != 0;
465 }
466
467
468 void MathMacroTemplate::updateLook() const
469 {
470         lookOutdated_ = true;
471 }
472
473
474 void MathMacroTemplate::createLook(int args) const
475 {
476         look_.clear();
477         argsInLook_ = args;
478
479         // \foo
480         look_.push_back(MathAtom(
481                 new InsetLabelBox(buffer_, _("Name"), *this, false)));
482         MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
483         nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
484
485         // [#1][#2]
486         int i = 0;
487         if (optionals_ > 0) {
488                 look_.push_back(MathAtom(
489                         new InsetLabelBox(buffer_, _("optional"), *this, false)));
490                 
491                 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
492                 for (; i < optionals_; ++i) {
493                         // color it light grey, if it is to be removed when the cursor leaves
494                         if (i == argsInLook_) {
495                                 optData->push_back(MathAtom(
496                                         new InsetColoredCell(buffer_, Color_mathbg, Color_mathmacrooldarg)));
497                                 optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
498                         }
499
500                         optData->push_back(MathAtom(new InsetMathChar('[')));
501                         optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
502                         optData->push_back(MathAtom(new InsetMathChar(']')));
503                 }
504         }
505
506         // {#3}{#4}
507         for (; i < numargs_; ++i) {
508                 MathData arg;
509                 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
510                 if (i >= argsInLook_) {
511                         look_.push_back(MathAtom(new InsetColoredCell(buffer_,
512                                 Color_mathbg, Color_mathmacrooldarg,
513                                 MathAtom(new InsetMathBrace(arg)))));
514                 } else
515                         look_.push_back(MathAtom(new InsetMathBrace(arg)));
516         }
517         for (; i < argsInLook_; ++i) {
518                 MathData arg;
519                 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
520                 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
521                         Color_mathbg, Color_mathmacronewarg,
522                         MathAtom(new InsetMathBrace(arg)))));
523         }
524         
525         // :=
526         look_.push_back(MathAtom(new InsetMathChar(':')));
527         look_.push_back(MathAtom(new InsetMathChar('=')));
528
529         // definition
530         look_.push_back(MathAtom(
531                 new InsetLabelBox(buffer_, MathAtom(
532                         new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this,        true)));
533
534         // display
535         look_.push_back(MathAtom(
536                 new DisplayLabelBox(buffer_, MathAtom(
537                         new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
538 }
539
540
541 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
542 {
543         Changer dummy1 = mi.base.changeFontSet("mathnormal");
544         Changer dummy2 = mi.base.font.changeStyle(LM_ST_TEXT);
545
546         // valid macro?
547         MacroData const * macro = 0;
548         if (validName())
549                 macro = mi.macrocontext.get(name());
550
551         // update look?
552         int argsInDef = maxArgumentInDefinition();
553         if (lookOutdated_ || argsInDef != argsInLook_) {
554                 lookOutdated_ = false;
555                 createLook(argsInDef);
556         }
557
558         /// metrics for inset contents
559         if (macro)
560                 macro->lock();
561
562         // first phase, premetric:
563         premetrics_ = true;
564         look_.metrics(mi, dim);
565         labelBoxAscent_ = dim.asc;
566         labelBoxDescent_ = dim.des;
567
568         // second phase, main metric:
569         premetrics_ = false;
570         look_.metrics(mi, dim);
571
572         if (macro)
573                 macro->unlock();
574
575         dim.wid += 6;
576         dim.des += 2;
577         dim.asc += 2;
578 }
579
580
581 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
582 {
583         // FIXME: Calling Changer on the same object repeatedly is inefficient.
584         Changer dummy0 = pi.base.font.changeColor(Color_math);
585         Changer dummy1 = pi.base.changeFontSet("mathnormal");
586         Changer dummy2 = pi.base.font.changeStyle(LM_ST_TEXT);
587
588         Dimension const dim = dimension(*pi.base.bv);
589
590         // draw outer frame
591         int const a = y - dim.asc + 1;
592         int const w = dim.wid - 2;
593         int const h = dim.height() - 2;
594         pi.pain.rectangle(x + 1, a, w, h, Color_mathframe);
595
596         // just to be sure: set some dummy values for coord cache
597         for (idx_type i = 0; i < nargs(); ++i)
598                 cell(i).setXY(*pi.base.bv, x, y);
599
600         // draw contents
601         look_.draw(pi, x + 3, y);
602 }
603
604
605 void MathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
606 {
607         updateLook();
608         cur.screenUpdateFlags(Update::SinglePar);
609         InsetMathNest::edit(cur, front, entry_from);
610 }
611
612
613 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
614 {
615         unsigned int const nargs_before = nargs();
616         commitEditChanges(cur, old);
617         updateLook();
618         cur.screenUpdateFlags(Update::Force);
619         // If we have removed a cell, we might have invalidated the cursor
620         return InsetMathNest::notifyCursorLeaves(old, cur)
621                 || nargs() < nargs_before;
622 }
623
624
625 void MathMacroTemplate::removeArguments(Cursor & cur,
626         DocIterator const & /*inset_pos*/, int from, int to)
627 {
628         DocIterator it = doc_iterator_begin(&buffer(), this);
629         for (; it; it.forwardChar()) {
630                 if (!it.nextInset())
631                         continue;
632                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
633                         continue;
634                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
635                 int n = arg->number() - 1;
636                 if (from <= n && n <= to) {
637                         int cellSlice = cur.find(it.cell());
638                         if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
639                                 --cur[cellSlice].pos();
640
641                         it.cell().erase(it.pos());
642                 }
643         }
644
645         updateLook();
646 }
647
648
649 void MathMacroTemplate::shiftArguments(size_t from, int by)
650 {
651         for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
652                 if (!it.nextInset())
653                         continue;
654                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
655                         continue;
656                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
657                 if (arg->number() >= int(from) + 1)
658                         arg->setNumber(arg->number() + by);
659         }
660
661         updateLook();
662 }
663
664
665 int MathMacroTemplate::maxArgumentInDefinition() const
666 {
667         // We don't have a buffer when pasting from the clipboard (bug 6014).
668         Buffer const * macro_buffer = isBufferLoaded() ? &buffer() : 0;
669         int maxArg = 0;
670         DocIterator it = doc_iterator_begin(macro_buffer, this);
671         it.idx() = defIdx();
672         for (; it; it.forwardChar()) {
673                 if (!it.nextInset())
674                         continue;
675                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
676                         continue;
677                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
678                 maxArg = std::max(int(arg->number()), maxArg);
679         }
680         return maxArg;
681 }
682
683
684 void MathMacroTemplate::insertMissingArguments(int maxArg)
685 {
686         bool found[9] = { false, false, false, false, false, false, false, false, false };
687         idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
688
689         // search for #n macros arguments
690         DocIterator it = doc_iterator_begin(&buffer(), this);
691         it.idx() = idx;
692         for (; it && it[0].idx() == idx; it.forwardChar()) {
693                 if (!it.nextInset())
694                         continue;
695                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
696                         continue;
697                 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
698                 found[arg->number() - 1] = true;
699         }
700
701         // add missing ones
702         for (int i = 0; i < maxArg; ++i) {
703                 if (found[i])
704                         continue;
705
706                 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
707         }
708 }
709
710
711 void MathMacroTemplate::changeArity(Cursor & cur,
712         DocIterator const & inset_pos, int newNumArg)
713 {
714         // remove parameter which do not appear anymore in the definition
715         for (int i = numargs_; i > newNumArg; --i)
716                 removeParameter(cur, inset_pos, numargs_ - 1, true);
717         
718         // add missing parameter
719         for (int i = numargs_; i < newNumArg; ++i)
720                 insertParameter(cur, inset_pos, numargs_, true, false);
721 }
722
723
724 ///
725 class AddRemoveMacroInstanceFix
726 {
727 public:
728         ///
729         AddRemoveMacroInstanceFix(int n, bool insert) : n_(n), insert_(insert) {}
730         ///
731         void operator()(MathMacro * macro)
732         {
733                 if (macro->folded()) {
734                         if (insert_)
735                                 macro->insertArgument(n_);
736                         else
737                                 macro->removeArgument(n_);
738                 }
739         }
740
741 private:
742         ///
743         int n_;
744         ///
745         bool insert_;
746 };
747
748
749 ///
750 class OptionalsMacroInstanceFix
751 {
752 public:
753         ///
754         OptionalsMacroInstanceFix(int optionals) : optionals_(optionals) {}
755         ///
756         void operator()(MathMacro * macro)
757         {
758                 macro->setOptionals(optionals_);
759         }
760
761 private:
762         ///
763         int optionals_;
764 };
765
766
767 ///
768 class NullMacroInstanceFix
769 {
770 public:
771         ///
772         void operator()(MathMacro * ) {}
773 };
774
775
776 template<class F>
777 void fixMacroInstances(Cursor & cur, DocIterator const & inset_pos,
778         docstring const & name, F & fix)
779 {
780         // goto position behind macro template
781         DocIterator dit = inset_pos;
782         dit.pop_back();
783         dit.top().forwardPos();
784
785         // remember hull to trigger preview reload
786         DocIterator hull(dit.buffer());
787         bool preview_reload_needed = false;
788         set<DocIterator> preview_hulls;
789
790         // iterate over all positions until macro is redefined
791         for (; dit; dit.forwardPos()) {
792                 // left the outer hull?
793                 if (!hull.empty() && dit.depth() == hull.depth()) {
794                         // schedule reload of the preview if necessary 
795                         if (preview_reload_needed) {
796                                 preview_hulls.insert(hull);
797                                 preview_reload_needed = false;
798                         }
799                         hull.clear();
800                 }
801
802                 // only until a macro is redefined
803                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
804                         MathMacroTemplate const & macroTemplate
805                         = static_cast<MathMacroTemplate const &>(dit.inset());
806                         if (macroTemplate.name() == name)
807                                 break;
808                 }
809
810                 // in front of macro instance?
811                 Inset * inset = dit.nextInset();
812                 if (!inset)
813                         continue;
814                 InsetMath * insetMath = inset->asInsetMath();
815                 if (!insetMath)
816                         continue;
817
818                 // in front of outer hull?
819                 InsetMathHull * inset_hull = insetMath->asHullInset();
820                 if (inset_hull && hull.empty()) {
821                         // remember this for later preview reload
822                         hull = dit;
823                 }
824
825                 MathMacro * macro = insetMath->asMacro();
826                 if (macro && macro->name() == name && macro->folded()) {
827                         fix(macro);
828                         if (RenderPreview::previewMath())
829                                 preview_reload_needed = true;
830                 }
831         }
832
833         if (!preview_hulls.empty()) {
834                 // reload the scheduled previews
835                 set<DocIterator>::const_iterator sit = preview_hulls.begin();
836                 set<DocIterator>::const_iterator end = preview_hulls.end();
837                 for (; sit != end; ++sit) {
838                         InsetMathHull * inset_hull =
839                                 sit->nextInset()->asInsetMath()->asHullInset();
840                         LBUFERR(inset_hull);
841                         inset_hull->reloadPreview(*sit);
842                 }
843                 cur.screenUpdateFlags(Update::Force);
844         }
845 }
846
847
848 void MathMacroTemplate::commitEditChanges(Cursor & cur,
849         DocIterator const & inset_pos)
850 {
851         int args_in_def = maxArgumentInDefinition();
852         if (args_in_def != numargs_) {
853                 // FIXME: implement precise undo handling (only a few places
854                 //   need undo)
855                 cur.recordUndoFullBuffer();
856                 changeArity(cur, inset_pos, args_in_def);
857         }
858         insertMissingArguments(args_in_def);
859
860         // make sure the preview are up to date
861         NullMacroInstanceFix fix;
862         fixMacroInstances(cur, inset_pos, name(), fix);
863 }
864
865
866 void MathMacroTemplate::insertParameter(Cursor & cur,
867         DocIterator const & inset_pos, int pos, bool greedy, bool addarg)
868 {
869         if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
870                 ++numargs_;
871
872                 // append example #n
873                 if (addarg) {
874                         shiftArguments(pos, 1);
875
876                         cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
877                         if (!cell(displayIdx()).empty())
878                                 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
879                 }
880
881                 if (!greedy) {
882                         // fix macro instances
883                         AddRemoveMacroInstanceFix fix(pos, true);
884                         fixMacroInstances(cur, inset_pos, name(), fix);
885                 }
886         }
887
888         updateLook();
889 }
890
891
892 void MathMacroTemplate::removeParameter(Cursor & cur,
893         DocIterator const & inset_pos, int pos, bool greedy)
894 {
895         if (pos < numargs_ && pos >= 0) {
896                 --numargs_;
897                 removeArguments(cur, inset_pos, pos, pos);
898                 shiftArguments(pos + 1, -1);
899
900                 // removed optional parameter?
901                 if (pos < optionals_) {
902                         --optionals_;
903                         optionalValues_[pos] = cell(optIdx(pos));
904                         cells_.erase(cells_.begin() + optIdx(pos));
905
906                         // fix cursor
907                         int macroSlice = cur.find(this);
908                         if (macroSlice != -1) {
909                                 if (cur[macroSlice].idx() == optIdx(pos)) {
910                                         cur.cutOff(macroSlice);
911                                         cur[macroSlice].idx() = 1;
912                                         cur[macroSlice].pos() = 0;
913                                 } else if (cur[macroSlice].idx() > optIdx(pos))
914                                         --cur[macroSlice].idx();
915                         }
916                 }
917
918                 if (!greedy) {
919                         // fix macro instances
920                         AddRemoveMacroInstanceFix fix(pos, false);
921                         fixMacroInstances(cur, inset_pos, name(), fix);
922                 }
923         }
924
925         updateLook();
926 }
927
928
929 void MathMacroTemplate::makeOptional(Cursor & cur,
930         DocIterator const & inset_pos)
931 {
932         if (numargs_ > 0 && optionals_ < numargs_) {
933                 ++optionals_;
934                 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
935                 // fix cursor
936                 int macroSlice = cur.find(this);
937                 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
938                         ++cur[macroSlice].idx();
939
940                 // fix macro instances
941                 OptionalsMacroInstanceFix fix(optionals_);
942                 fixMacroInstances(cur, inset_pos, name(), fix);
943         }
944
945         updateLook();
946 }
947
948
949 void MathMacroTemplate::makeNonOptional(Cursor & cur,
950         DocIterator const & inset_pos)
951 {
952         if (numargs_ > 0 && optionals_ > 0) {
953                 --optionals_;
954
955                 // store default value for later if the user changes his mind
956                 optionalValues_[optionals_] = cell(optIdx(optionals_));
957                 cells_.erase(cells_.begin() + optIdx(optionals_));
958
959                 // fix cursor
960                 int macroSlice = cur.find(this);
961                 if (macroSlice != -1) {
962                         if (cur[macroSlice].idx() > optIdx(optionals_))
963                                 --cur[macroSlice].idx();
964                         else if (cur[macroSlice].idx() == optIdx(optionals_)) {
965                                 cur.cutOff(macroSlice);
966                                 cur[macroSlice].idx() = optIdx(optionals_);
967                                 cur[macroSlice].pos() = 0;
968                         }
969                 }
970
971                 // fix macro instances
972                 OptionalsMacroInstanceFix fix(optionals_);
973                 fixMacroInstances(cur, inset_pos, name(), fix);
974         }
975
976         updateLook();
977 }
978
979
980 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
981 {
982         string const arg = to_utf8(cmd.argument());
983         switch (cmd.action()) {
984
985         case LFUN_MATH_MACRO_ADD_PARAM:
986                 if (numargs_ < 9) {
987                         commitEditChanges(cur, cur);
988                         // FIXME: implement precise undo handling (only a few places
989                         //   need undo)
990                         cur.recordUndoFullBuffer();
991                         size_t pos = numargs_;
992                         if (!arg.empty())
993                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
994                         insertParameter(cur, cur, pos);
995                 }
996                 break;
997
998
999         case LFUN_MATH_MACRO_REMOVE_PARAM:
1000                 if (numargs_ > 0) {
1001                         commitEditChanges(cur, cur);
1002                         // FIXME: implement precise undo handling (only a few places
1003                         //   need undo)
1004                         cur.recordUndoFullBuffer();
1005                         size_t pos = numargs_ - 1;
1006                         if (!arg.empty())
1007                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1008                         removeParameter(cur, cur, pos);
1009                 }
1010                 break;
1011
1012         case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1013                 if (numargs_ < 9) {
1014                         commitEditChanges(cur, cur);
1015                         // FIXME: implement precise undo handling (only a few places
1016                         //   need undo)
1017                         cur.recordUndoFullBuffer();
1018                         insertParameter(cur, cur, numargs_, true);
1019                 }
1020                 break;
1021
1022         case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1023                 if (numargs_ > 0) {
1024                         commitEditChanges(cur, cur);
1025                         // FIXME: implement precise undo handling (only a few places
1026                         //   need undo)
1027                         cur.recordUndoFullBuffer();
1028                         removeParameter(cur, cur, numargs_ - 1, true);
1029                 }
1030                 break;
1031
1032         case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1033                 commitEditChanges(cur, cur);
1034                 // FIXME: implement precise undo handling (only a few places
1035                 //   need undo)
1036                 cur.recordUndoFullBuffer();
1037                 makeOptional(cur, cur);
1038                 break;
1039
1040         case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1041                 commitEditChanges(cur, cur);
1042                 // FIXME: implement precise undo handling (only a few places
1043                 //   need undo)
1044                 cur.recordUndoFullBuffer();
1045                 makeNonOptional(cur, cur);
1046                 break;
1047
1048         case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1049                 if (numargs_ < 9) {
1050                         commitEditChanges(cur, cur);
1051                         // FIXME: implement precise undo handling (only a few places
1052                         //   need undo)
1053                         cur.recordUndoFullBuffer();
1054                         insertParameter(cur, cur, optionals_);
1055                         makeOptional(cur, cur);
1056                 }
1057                 break;
1058
1059         case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1060                 if (optionals_ > 0) {
1061                         commitEditChanges(cur, cur);
1062                         // FIXME: implement precise undo handling (only a few places
1063                         //   need undo)
1064                         cur.recordUndoFullBuffer();
1065                         removeParameter(cur, cur, optionals_ - 1);
1066                 } break;
1067
1068         case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1069                 if (numargs_ == optionals_) {
1070                         commitEditChanges(cur, cur);
1071                         // FIXME: implement precise undo handling (only a few places
1072                         //   need undo)
1073                         cur.recordUndoFullBuffer();
1074                         insertParameter(cur, cur, 0, true);
1075                         makeOptional(cur, cur);
1076                 }
1077                 break;
1078
1079         default:
1080                 InsetMathNest::doDispatch(cur, cmd);
1081                 break;
1082         }
1083 }
1084
1085
1086 bool MathMacroTemplate::getStatus(Cursor & cur, FuncRequest const & cmd,
1087         FuncStatus & flag) const
1088 {
1089         bool ret = true;
1090         string const arg = to_utf8(cmd.argument());
1091         switch (cmd.action()) {
1092                 case LFUN_MATH_MACRO_ADD_PARAM: {
1093                         int num = numargs_ + 1;
1094                         if (!arg.empty())
1095                                 num = convert<int>(arg);
1096                         bool on = (num >= optionals_
1097                                    && numargs_ < 9 && num <= numargs_ + 1);
1098                         flag.setEnabled(on);
1099                         break;
1100                 }
1101
1102                 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1103                         flag.setEnabled(numargs_ < 9);
1104                         break;
1105
1106                 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1107                 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1108                         int num = numargs_;
1109                         if (!arg.empty())
1110                                 num = convert<int>(arg);
1111                         flag.setEnabled(num >= 1 && num <= numargs_);
1112                         break;
1113                 }
1114
1115                 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1116                         flag.setEnabled(numargs_ > 0
1117                                      && optionals_ < numargs_
1118                                      && type_ != MacroTypeDef);
1119                         break;
1120
1121                 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1122                         flag.setEnabled(optionals_ > 0
1123                                      && type_ != MacroTypeDef);
1124                         break;
1125
1126                 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1127                         flag.setEnabled(numargs_ < 9);
1128                         break;
1129
1130                 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1131                         flag.setEnabled(optionals_ > 0);
1132                         break;
1133
1134                 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1135                         flag.setEnabled(numargs_ == 0
1136                                      && type_ != MacroTypeDef);
1137                         break;
1138
1139                 case LFUN_IN_MATHMACROTEMPLATE:
1140                         flag.setEnabled(true);
1141                         break;
1142
1143                 default:
1144                         ret = InsetMathNest::getStatus(cur, cmd, flag);
1145                         break;
1146         }
1147         return ret;
1148 }
1149
1150
1151 void MathMacroTemplate::read(Lexer & lex)
1152 {
1153         MathData ar(buffer_);
1154         mathed_parse_cell(ar, lex.getStream(), Parse::TRACKMACRO);
1155         if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1156                 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1157                 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1158                 return;
1159         }
1160         operator=( *(ar[0]->asMacroTemplate()) );
1161
1162         updateLook();
1163 }
1164
1165
1166 void MathMacroTemplate::write(ostream & os) const
1167 {
1168         odocstringstream oss;
1169         otexrowstream ots(oss);
1170         WriteStream wi(ots, false, false, WriteStream::wsDefault);
1171         oss << "FormulaMacro\n";
1172         write(wi);
1173         os << to_utf8(oss.str());
1174 }
1175
1176
1177 void MathMacroTemplate::write(WriteStream & os) const
1178 {
1179         write(os, false);
1180 }
1181
1182
1183 int MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1184 {
1185         int num_lines = 0;
1186
1187         if (os.latex()) {
1188                 if (optionals_ > 0) {
1189                         // macros with optionals use the xargs package, e.g.:
1190                         // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1191                         // \long is implicit by xargs
1192                         if (redefinition_ && !overwriteRedefinition)
1193                                 os << "\\renewcommandx";
1194                         else
1195                                 os << "\\newcommandx";
1196
1197                         os << "\\" << name()
1198                            << "[" << numargs_ << "]"
1199                            << "[usedefault, addprefix=\\global";
1200                         for (int i = 0; i < optionals_; ++i) {
1201                                 docstring optValue = asString(cell(optIdx(i)));
1202                                 if (optValue.find(']') != docstring::npos
1203                                     || optValue.find(',') != docstring::npos)
1204                                         os << ", " << i + 1 << "="
1205                                         << "{" << cell(optIdx(i)) << "}";
1206                                 else
1207                                         os << ", " << i + 1 << "="
1208                                         << cell(optIdx(i));
1209                         }
1210                         os << "]";
1211                 } else {
1212                         // Macros without optionals use standard _global_ \def macros:
1213                         //   \global\def\long\foo#1#2{#1,#2}
1214                         // We use the \long prefix as this is the equivalent to \newcommand.
1215                         // We cannot use \newcommand directly because \global does not work with it.
1216                         os << "\\global\\long\\def\\" << name();
1217                         docstring param = from_ascii("#0");
1218                         for (int i = 1; i <= numargs_; ++i) { 
1219                                 param[1] = '0' + i;
1220                                 os << param;
1221                         }
1222                 }
1223         } else {
1224                 // in LyX output we use some pseudo syntax which is implementation
1225                 // independent, e.g.
1226                 // \newcommand{\foo}[2][default]{#1,#2}
1227                 if (redefinition_ && !overwriteRedefinition)
1228                         os << "\\renewcommand";
1229                 else
1230                         os << "\\newcommand";
1231                 os << "{\\" << name() << '}';
1232                 if (numargs_ > 0)
1233                         os << '[' << numargs_ << ']';
1234
1235                 for (int i = 0; i < optionals_; ++i) {
1236                         docstring optValue = asString(cell(optIdx(i)));
1237                         if (optValue.find(']') != docstring::npos)
1238                                 os << "[{" << cell(optIdx(i)) << "}]";
1239                         else
1240                                 os << "[" << cell(optIdx(i)) << "]";
1241                 }
1242         }
1243
1244         os << "{" << cell(defIdx()) << "}";
1245
1246         if (os.latex()) {
1247                 // writing .tex. done.
1248                 os << "\n";
1249                 ++num_lines;
1250         } else {
1251                 // writing .lyx, write special .tex export only if necessary
1252                 if (!cell(displayIdx()).empty()) {
1253                         os << "\n{" << cell(displayIdx()) << '}';
1254                         ++num_lines;
1255                 }
1256         }
1257
1258         return num_lines;
1259 }
1260
1261
1262 docstring MathMacroTemplate::xhtml(XHTMLStream &, OutputParams const &) const
1263 {
1264         return docstring();
1265 }
1266
1267 int MathMacroTemplate::plaintext(odocstringstream & os,
1268                                  OutputParams const &, size_t) const
1269 {
1270         docstring const str = '[' + buffer().B_("math macro") + ']';
1271
1272         os << str;
1273         return str.size();
1274 }
1275
1276
1277 bool MathMacroTemplate::validName() const
1278 {
1279         docstring n = name();
1280
1281         if (n.empty())
1282                 return false;
1283
1284         // converting back and force doesn't swallow anything?
1285         /*MathData ma;
1286         asArray(n, ma);
1287         if (asString(ma) != n)
1288                 return false;*/
1289
1290         // valid characters?
1291         for (size_t i = 0; i < n.size(); ++i) {
1292                 if (!(n[i] >= 'a' && n[i] <= 'z')
1293                     && !(n[i] >= 'A' && n[i] <= 'Z')
1294                     && n[i] != '*')
1295                         return false;
1296         }
1297
1298         return true;
1299 }
1300
1301
1302 bool MathMacroTemplate::validMacro() const
1303 {
1304         return validName();
1305 }
1306
1307
1308 bool MathMacroTemplate::fixNameAndCheckIfValid()
1309 {
1310         // check all the characters/insets in the name cell
1311         size_t i = 0;
1312         MathData & data = cell(0);
1313         while (i < data.size()) {
1314                 InsetMathChar const * cinset = data[i]->asCharInset();
1315                 if (cinset) {
1316                         // valid character in [a-zA-Z]?
1317                         char_type c = cinset->getChar();
1318                         if ((c >= 'a' && c <= 'z')
1319                             || (c >= 'A' && c <= 'Z')) {
1320                                 ++i;
1321                                 continue;
1322                         }
1323                 }
1324
1325                 // throw cell away
1326                 data.erase(i);
1327         }
1328
1329         // now it should be valid if anything in the name survived
1330         return !data.empty();
1331 }
1332
1333         
1334 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1335 {
1336         // we need global optional macro arguments. They are not available 
1337         // with \def, and \newcommand does not support global macros. So we
1338         // are bound to xargs also for the single-optional-parameter case.
1339         if (optionals_ > 0)
1340                 features.require("xargs");
1341 }
1342
1343 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1344 {
1345         defaults.resize(numargs_);
1346         for (int i = 0; i < optionals_; ++i)
1347                 defaults[i] = asString(cell(optIdx(i)));
1348 }
1349
1350
1351 docstring MathMacroTemplate::definition() const
1352 {
1353         return asString(cell(defIdx()));
1354 }
1355
1356
1357 docstring MathMacroTemplate::displayDefinition() const
1358 {
1359         return asString(cell(displayIdx()));
1360 }
1361
1362
1363 size_t MathMacroTemplate::numArgs() const
1364 {
1365         return numargs_;
1366 }
1367
1368
1369 size_t MathMacroTemplate::numOptionals() const
1370 {
1371         return optionals_;
1372 }
1373
1374
1375 void MathMacroTemplate::infoize(odocstream & os) const
1376 {
1377         os << bformat(_("Math Macro: \\%1$s"), name());
1378 }
1379
1380
1381 string MathMacroTemplate::contextMenuName() const
1382 {
1383         return "context-math-macro-definition";
1384 }
1385
1386
1387 void MathMacroTemplate::addToToc(DocIterator const & pit, bool output_active,
1388                                                                  UpdateType, TocBackend & backend) const
1389 {
1390         docstring str;
1391         if (!validMacro())
1392                 str = bformat(_("Invalid macro! \\%1$s"), name());
1393         else
1394                 str = "\\" + name();
1395         TocBuilder & b = backend.builder("math-macro");
1396         b.pushItem(pit, str, output_active);
1397         b.pop();
1398 }
1399
1400
1401 } // namespace lyx