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