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