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