]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathMacroTemplate.cpp
1152936ee2e784f64b0ae7c49d654792bc3b78ba
[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 label,
65                       InsetMathMacroTemplate const & parent, bool frame = false);
66         InsetLabelBox(Buffer * buf, docstring 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 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 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 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 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 InsetMath::marker_type InsetDisplayLabelBox::marker(BufferView const * bv) const
220 {
221         if (parent_.editing(bv)
222             || !parent_.cell(parent_.displayIdx()).empty())
223                 return MARKER;
224         else
225                 return 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), 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), numargs_(numargs), argsInLook_(numargs),
409           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;
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
541
542 void InsetMathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
543 {
544         Changer dummy1 = mi.base.changeFontSet("mathnormal");
545         Changer dummy2 = mi.base.font.changeStyle(TEXT_STYLE);
546
547         // valid macro?
548         MacroData const * macro = 0;
549         if (validName())
550                 macro = mi.macrocontext.get(name());
551
552         // update look?
553         int argsInDef = maxArgumentInDefinition();
554         if (lookOutdated_ || argsInDef != argsInLook_) {
555                 lookOutdated_ = false;
556                 createLook(argsInDef);
557         }
558
559         /// metrics for inset contents
560         if (macro)
561                 macro->lock();
562
563         // first phase, premetric:
564         premetrics_ = true;
565         look_.metrics(mi, dim);
566         labelBoxAscent_ = dim.asc;
567         labelBoxDescent_ = dim.des;
568
569         // second phase, main metric:
570         premetrics_ = false;
571         look_.metrics(mi, dim);
572
573         if (macro)
574                 macro->unlock();
575
576         dim.wid += leftOffset(mi.base.bv) + rightOffset(mi.base.bv);;
577         dim.des += bottomOffset(mi.base.bv);
578         dim.asc += topOffset(mi.base.bv);
579 }
580
581
582 void InsetMathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
583 {
584         // FIXME: Calling Changer on the same object repeatedly is inefficient.
585         Changer dummy0 = pi.base.font.changeColor(Color_math);
586         Changer dummy1 = pi.base.changeFontSet("mathnormal");
587         Changer dummy2 = pi.base.font.changeStyle(TEXT_STYLE);
588
589         Dimension const dim = dimension(*pi.base.bv);
590
591         // draw outer frame
592         int const hoffset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
593         int const voffset = topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
594         int const a = y - dim.asc + topOffset(pi.base.bv) / 2;
595         int const w = dim.wid - (hoffset - hoffset / 2);
596         int const h = dim.height() - (voffset - voffset / 2);
597         pi.pain.rectangle(x + leftOffset(pi.base.bv) / 2, a, w, h, Color_mathframe);
598
599         // just to be sure: set some dummy values for coord cache
600         for (idx_type i = 0; i < nargs(); ++i)
601                 cell(i).setXY(*pi.base.bv, x, y);
602
603         // draw contents
604         look_.draw(pi, x + leftOffset(pi.base.bv), y);
605 }
606
607
608 void InsetMathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
609 {
610         updateLook();
611         cur.screenUpdateFlags(Update::SinglePar);
612         InsetMathNest::edit(cur, front, entry_from);
613 }
614
615
616 bool InsetMathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
617 {
618         unsigned int const nargs_before = nargs();
619         commitEditChanges(cur, old);
620         updateLook();
621         cur.screenUpdateFlags(Update::Force);
622         // If we have removed a cell, we might have invalidated the cursor
623         return InsetMathNest::notifyCursorLeaves(old, cur)
624                 || nargs() < nargs_before;
625 }
626
627
628 void InsetMathMacroTemplate::removeArguments(Cursor & cur,
629         DocIterator const & /*inset_pos*/, int from, int to)
630 {
631         DocIterator it = doc_iterator_begin(&buffer(), this);
632         for (; it; it.forwardChar()) {
633                 if (!it.nextInset())
634                         continue;
635                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
636                         continue;
637                 InsetMathMacroArgument * arg = static_cast<InsetMathMacroArgument*>(it.nextInset());
638                 int n = arg->number() - 1;
639                 if (from <= n && n <= to) {
640                         int cellSlice = cur.find(it.cell());
641                         if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
642                                 --cur[cellSlice].pos();
643
644                         it.cell().erase(it.pos());
645                 }
646         }
647
648         updateLook();
649 }
650
651
652 void InsetMathMacroTemplate::shiftArguments(size_t from, int by)
653 {
654         for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
655                 if (!it.nextInset())
656                         continue;
657                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
658                         continue;
659                 InsetMathMacroArgument * arg = static_cast<InsetMathMacroArgument*>(it.nextInset());
660                 if (arg->number() >= int(from) + 1)
661                         arg->setNumber(arg->number() + by);
662         }
663
664         updateLook();
665 }
666
667
668 int InsetMathMacroTemplate::maxArgumentInDefinition() const
669 {
670         // We don't have a buffer when pasting from the clipboard (bug 6014).
671         Buffer const * macro_buffer = isBufferLoaded() ? &buffer() : 0;
672         int maxArg = 0;
673         DocIterator it = doc_iterator_begin(macro_buffer, this);
674         it.idx() = defIdx();
675         for (; it; it.forwardChar()) {
676                 if (!it.nextInset())
677                         continue;
678                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
679                         continue;
680                 InsetMathMacroArgument * arg = static_cast<InsetMathMacroArgument*>(it.nextInset());
681                 maxArg = std::max(int(arg->number()), maxArg);
682         }
683         return maxArg;
684 }
685
686
687 void InsetMathMacroTemplate::insertMissingArguments(int maxArg)
688 {
689         bool found[9] = { false, false, false, false, false, false, false, false, false };
690         idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
691
692         // search for #n macros arguments
693         DocIterator it = doc_iterator_begin(&buffer(), this);
694         it.idx() = idx;
695         for (; it && it[0].idx() == idx; it.forwardChar()) {
696                 if (!it.nextInset())
697                         continue;
698                 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
699                         continue;
700                 InsetMathMacroArgument * arg = static_cast<InsetMathMacroArgument*>(it.nextInset());
701                 found[arg->number() - 1] = true;
702         }
703
704         // add missing ones
705         for (int i = 0; i < maxArg; ++i) {
706                 if (found[i])
707                         continue;
708
709                 cell(idx).push_back(MathAtom(new InsetMathMacroArgument(i + 1)));
710         }
711 }
712
713
714 void InsetMathMacroTemplate::changeArity(Cursor & cur,
715         DocIterator const & inset_pos, int newNumArg)
716 {
717         // remove parameter which do not appear anymore in the definition
718         for (int i = numargs_; i > newNumArg; --i)
719                 removeParameter(cur, inset_pos, numargs_ - 1, true);
720
721         // add missing parameter
722         for (int i = numargs_; i < newNumArg; ++i)
723                 insertParameter(cur, inset_pos, numargs_, true, false);
724 }
725
726
727 ///
728 class AddRemoveMacroInstanceFix
729 {
730 public:
731         ///
732         AddRemoveMacroInstanceFix(int n, bool insert) : n_(n), insert_(insert) {}
733         ///
734         void operator()(InsetMathMacro * macro)
735         {
736                 if (macro->folded()) {
737                         if (insert_)
738                                 macro->insertArgument(n_);
739                         else
740                                 macro->removeArgument(n_);
741                 }
742         }
743
744 private:
745         ///
746         int n_;
747         ///
748         bool insert_;
749 };
750
751
752 ///
753 class OptionalsMacroInstanceFix
754 {
755 public:
756         ///
757         explicit OptionalsMacroInstanceFix(int optionals) : optionals_(optionals) {}
758         ///
759         void operator()(InsetMathMacro * macro)
760         {
761                 macro->setOptionals(optionals_);
762         }
763
764 private:
765         ///
766         int optionals_;
767 };
768
769
770 ///
771 class NullMacroInstanceFix
772 {
773 public:
774         ///
775         void operator()(InsetMathMacro * ) {}
776 };
777
778
779 template<class F>
780 void fixMacroInstances(Cursor & cur, DocIterator const & inset_pos,
781         docstring const & name, F & fix)
782 {
783         // goto position behind macro template
784         DocIterator dit = inset_pos;
785         dit.pop_back();
786         dit.top().forwardPos();
787
788         // remember hull to trigger preview reload
789         DocIterator hull(dit.buffer());
790         bool preview_reload_needed = false;
791         set<DocIterator> preview_hulls;
792
793         // iterate over all positions until macro is redefined
794         for (; dit; dit.forwardPos()) {
795                 // left the outer hull?
796                 if (!hull.empty() && dit.depth() == hull.depth()) {
797                         // schedule reload of the preview if necessary
798                         if (preview_reload_needed) {
799                                 preview_hulls.insert(hull);
800                                 preview_reload_needed = false;
801                         }
802                         hull.clear();
803                 }
804
805                 // only until a macro is redefined
806                 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
807                         InsetMathMacroTemplate const & macroTemplate
808                         = static_cast<InsetMathMacroTemplate const &>(dit.inset());
809                         if (macroTemplate.name() == name)
810                                 break;
811                 }
812
813                 // in front of macro instance?
814                 Inset * inset = dit.nextInset();
815                 if (!inset)
816                         continue;
817                 InsetMath * insetMath = inset->asInsetMath();
818                 if (!insetMath)
819                         continue;
820
821                 // in front of outer hull?
822                 InsetMathHull * inset_hull = insetMath->asHullInset();
823                 if (inset_hull && hull.empty()) {
824                         // remember this for later preview reload
825                         hull = dit;
826                 }
827
828                 InsetMathMacro * macro = insetMath->asMacro();
829                 if (macro && macro->name() == name && macro->folded()) {
830                         fix(macro);
831                         if (RenderPreview::previewMath())
832                                 preview_reload_needed = true;
833                 }
834         }
835
836         if (!preview_hulls.empty()) {
837                 // reload the scheduled previews
838                 set<DocIterator>::const_iterator sit = preview_hulls.begin();
839                 set<DocIterator>::const_iterator end = preview_hulls.end();
840                 for (; sit != end; ++sit) {
841                         InsetMathHull * inset_hull =
842                                 sit->nextInset()->asInsetMath()->asHullInset();
843                         LBUFERR(inset_hull);
844                         inset_hull->reloadPreview(*sit);
845                 }
846                 cur.screenUpdateFlags(Update::Force);
847         }
848 }
849
850
851 void InsetMathMacroTemplate::commitEditChanges(Cursor & cur,
852         DocIterator const & inset_pos)
853 {
854         int args_in_def = maxArgumentInDefinition();
855         if (args_in_def != numargs_) {
856                 // FIXME: implement precise undo handling (only a few places
857                 //   need undo)
858                 cur.recordUndoFullBuffer();
859                 changeArity(cur, inset_pos, args_in_def);
860         }
861         insertMissingArguments(args_in_def);
862
863         // make sure the preview are up to date
864         NullMacroInstanceFix fix;
865         fixMacroInstances(cur, inset_pos, name(), fix);
866 }
867
868
869 void InsetMathMacroTemplate::insertParameter(Cursor & cur,
870         DocIterator const & inset_pos, int pos, bool greedy, bool addarg)
871 {
872         if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
873                 ++numargs_;
874
875                 // append example #n
876                 if (addarg) {
877                         shiftArguments(pos, 1);
878
879                         cell(defIdx()).push_back(MathAtom(new InsetMathMacroArgument(pos + 1)));
880                         if (!cell(displayIdx()).empty())
881                                 cell(displayIdx()).push_back(MathAtom(new InsetMathMacroArgument(pos + 1)));
882                 }
883
884                 if (!greedy) {
885                         // fix macro instances
886                         AddRemoveMacroInstanceFix fix(pos, true);
887                         fixMacroInstances(cur, inset_pos, name(), fix);
888                 }
889         }
890
891         updateLook();
892 }
893
894
895 void InsetMathMacroTemplate::removeParameter(Cursor & cur,
896         DocIterator const & inset_pos, int pos, bool greedy)
897 {
898         if (pos < numargs_ && pos >= 0) {
899                 --numargs_;
900                 removeArguments(cur, inset_pos, pos, pos);
901                 shiftArguments(pos + 1, -1);
902
903                 // removed optional parameter?
904                 if (pos < optionals_) {
905                         --optionals_;
906                         optionalValues_[pos] = cell(optIdx(pos));
907                         cells_.erase(cells_.begin() + optIdx(pos));
908
909                         // fix cursor
910                         int macroSlice = cur.find(this);
911                         if (macroSlice != -1) {
912                                 if (cur[macroSlice].idx() == optIdx(pos)) {
913                                         cur.cutOff(macroSlice);
914                                         cur[macroSlice].idx() = 1;
915                                         cur[macroSlice].pos() = 0;
916                                 } else if (cur[macroSlice].idx() > optIdx(pos))
917                                         --cur[macroSlice].idx();
918                         }
919                 }
920
921                 if (!greedy) {
922                         // fix macro instances
923                         AddRemoveMacroInstanceFix fix(pos, false);
924                         fixMacroInstances(cur, inset_pos, name(), fix);
925                 }
926         }
927
928         updateLook();
929 }
930
931
932 void InsetMathMacroTemplate::makeOptional(Cursor & cur,
933         DocIterator const & inset_pos)
934 {
935         if (numargs_ > 0 && optionals_ < numargs_) {
936                 ++optionals_;
937                 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
938                 // fix cursor
939                 int macroSlice = cur.find(this);
940                 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
941                         ++cur[macroSlice].idx();
942
943                 // fix macro instances
944                 OptionalsMacroInstanceFix fix(optionals_);
945                 fixMacroInstances(cur, inset_pos, name(), fix);
946         }
947
948         updateLook();
949 }
950
951
952 void InsetMathMacroTemplate::makeNonOptional(Cursor & cur,
953         DocIterator const & inset_pos)
954 {
955         if (numargs_ > 0 && optionals_ > 0) {
956                 --optionals_;
957
958                 // store default value for later if the user changes his mind
959                 optionalValues_[optionals_] = cell(optIdx(optionals_));
960                 cells_.erase(cells_.begin() + optIdx(optionals_));
961
962                 // fix cursor
963                 int macroSlice = cur.find(this);
964                 if (macroSlice != -1) {
965                         if (cur[macroSlice].idx() > optIdx(optionals_))
966                                 --cur[macroSlice].idx();
967                         else if (cur[macroSlice].idx() == optIdx(optionals_)) {
968                                 cur.cutOff(macroSlice);
969                                 cur[macroSlice].idx() = optIdx(optionals_);
970                                 cur[macroSlice].pos() = 0;
971                         }
972                 }
973
974                 // fix macro instances
975                 OptionalsMacroInstanceFix fix(optionals_);
976                 fixMacroInstances(cur, inset_pos, name(), fix);
977         }
978
979         updateLook();
980 }
981
982
983 void InsetMathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
984 {
985         string const arg = to_utf8(cmd.argument());
986         switch (cmd.action()) {
987
988         case LFUN_MATH_MACRO_ADD_PARAM:
989                 if (numargs_ < 9) {
990                         commitEditChanges(cur, cur);
991                         // FIXME: implement precise undo handling (only a few places
992                         //   need undo)
993                         cur.recordUndoFullBuffer();
994                         size_t pos = numargs_;
995                         if (!arg.empty())
996                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
997                         insertParameter(cur, cur, pos);
998                 }
999                 break;
1000
1001
1002         case LFUN_MATH_MACRO_REMOVE_PARAM:
1003                 if (numargs_ > 0) {
1004                         commitEditChanges(cur, cur);
1005                         // FIXME: implement precise undo handling (only a few places
1006                         //   need undo)
1007                         cur.recordUndoFullBuffer();
1008                         size_t pos = numargs_ - 1;
1009                         if (!arg.empty())
1010                                 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1011                         removeParameter(cur, cur, pos);
1012                 }
1013                 break;
1014
1015         case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1016                 if (numargs_ < 9) {
1017                         commitEditChanges(cur, cur);
1018                         // FIXME: implement precise undo handling (only a few places
1019                         //   need undo)
1020                         cur.recordUndoFullBuffer();
1021                         insertParameter(cur, cur, numargs_, true);
1022                 }
1023                 break;
1024
1025         case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1026                 if (numargs_ > 0) {
1027                         commitEditChanges(cur, cur);
1028                         // FIXME: implement precise undo handling (only a few places
1029                         //   need undo)
1030                         cur.recordUndoFullBuffer();
1031                         removeParameter(cur, cur, numargs_ - 1, true);
1032                 }
1033                 break;
1034
1035         case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1036                 commitEditChanges(cur, cur);
1037                 // FIXME: implement precise undo handling (only a few places
1038                 //   need undo)
1039                 cur.recordUndoFullBuffer();
1040                 makeOptional(cur, cur);
1041                 break;
1042
1043         case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1044                 commitEditChanges(cur, cur);
1045                 // FIXME: implement precise undo handling (only a few places
1046                 //   need undo)
1047                 cur.recordUndoFullBuffer();
1048                 makeNonOptional(cur, cur);
1049                 break;
1050
1051         case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1052                 if (numargs_ < 9) {
1053                         commitEditChanges(cur, cur);
1054                         // FIXME: implement precise undo handling (only a few places
1055                         //   need undo)
1056                         cur.recordUndoFullBuffer();
1057                         insertParameter(cur, cur, optionals_);
1058                         makeOptional(cur, cur);
1059                 }
1060                 break;
1061
1062         case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1063                 if (optionals_ > 0) {
1064                         commitEditChanges(cur, cur);
1065                         // FIXME: implement precise undo handling (only a few places
1066                         //   need undo)
1067                         cur.recordUndoFullBuffer();
1068                         removeParameter(cur, cur, optionals_ - 1);
1069                 } break;
1070
1071         case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1072                 if (numargs_ == optionals_) {
1073                         commitEditChanges(cur, cur);
1074                         // FIXME: implement precise undo handling (only a few places
1075                         //   need undo)
1076                         cur.recordUndoFullBuffer();
1077                         insertParameter(cur, cur, 0, true);
1078                         makeOptional(cur, cur);
1079                 }
1080                 break;
1081
1082         default:
1083                 InsetMathNest::doDispatch(cur, cmd);
1084                 break;
1085         }
1086 }
1087
1088
1089 bool InsetMathMacroTemplate::getStatus(Cursor & cur, FuncRequest const & cmd,
1090         FuncStatus & status) const
1091 {
1092         bool ret = true;
1093         string const arg = to_utf8(cmd.argument());
1094         switch (cmd.action()) {
1095                 case LFUN_MATH_MACRO_ADD_PARAM: {
1096                         int num = numargs_ + 1;
1097                         if (!arg.empty())
1098                                 num = convert<int>(arg);
1099                         bool on = (num >= optionals_
1100                                    && numargs_ < 9 && num <= numargs_ + 1);
1101                         status.setEnabled(on);
1102                         break;
1103                 }
1104
1105                 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1106                         status.setEnabled(numargs_ < 9);
1107                         break;
1108
1109                 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1110                 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1111                         int num = numargs_;
1112                         if (!arg.empty())
1113                                 num = convert<int>(arg);
1114                         status.setEnabled(num >= 1 && num <= numargs_);
1115                         break;
1116                 }
1117
1118                 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1119                         status.setEnabled(numargs_ > 0
1120                                      && optionals_ < numargs_
1121                                      && type_ != MacroTypeDef);
1122                         break;
1123
1124                 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1125                         status.setEnabled(optionals_ > 0
1126                                      && type_ != MacroTypeDef);
1127                         break;
1128
1129                 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1130                         status.setEnabled(numargs_ < 9);
1131                         break;
1132
1133                 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1134                         status.setEnabled(optionals_ > 0);
1135                         break;
1136
1137                 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1138                         status.setEnabled(numargs_ == 0
1139                                      && type_ != MacroTypeDef);
1140                         break;
1141
1142                 case LFUN_IN_MATHMACROTEMPLATE:
1143                         status.setEnabled(true);
1144                         break;
1145
1146                 default:
1147                         ret = InsetMathNest::getStatus(cur, cmd, status);
1148                         break;
1149         }
1150         return ret;
1151 }
1152
1153
1154 void InsetMathMacroTemplate::read(Lexer & lex)
1155 {
1156         MathData ar(buffer_);
1157         mathed_parse_cell(ar, lex.getStream(), Parse::TRACKMACRO);
1158         if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1159                 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1160                 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1161                 return;
1162         }
1163         operator=( *(ar[0]->asMacroTemplate()) );
1164
1165         updateLook();
1166 }
1167
1168
1169 void InsetMathMacroTemplate::write(ostream & os) const
1170 {
1171         odocstringstream oss;
1172         otexrowstream ots(oss);
1173         WriteStream wi(ots, false, false, WriteStream::wsDefault);
1174         oss << "FormulaMacro\n";
1175         write(wi);
1176         os << to_utf8(oss.str());
1177 }
1178
1179
1180 void InsetMathMacroTemplate::write(WriteStream & os) const
1181 {
1182         write(os, false);
1183 }
1184
1185
1186 int InsetMathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1187 {
1188         int num_lines = 0;
1189
1190         if (os.latex()) {
1191                 if (optionals_ > 0) {
1192                         // macros with optionals use the xargs package, e.g.:
1193                         // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1194                         // \long is implicit by xargs
1195                         if (redefinition_ && !overwriteRedefinition)
1196                                 os << "\\renewcommandx";
1197                         else
1198                                 os << "\\newcommandx";
1199
1200                         os << "\\" << name()
1201                            << "[" << numargs_ << "]"
1202                            << "[usedefault, addprefix=\\global";
1203                         for (int i = 0; i < optionals_; ++i) {
1204                                 docstring optValue = asString(cell(optIdx(i)));
1205                                 if (optValue.find(']') != docstring::npos
1206                                     || optValue.find(',') != docstring::npos)
1207                                         os << ", " << i + 1 << "="
1208                                         << "{" << cell(optIdx(i)) << "}";
1209                                 else
1210                                         os << ", " << i + 1 << "="
1211                                         << cell(optIdx(i));
1212                         }
1213                         os << "]";
1214                 } else {
1215                         // Macros without optionals use standard _global_ \def macros:
1216                         //   \global\def\long\foo#1#2{#1,#2}
1217                         // We use the \long prefix as this is the equivalent to \newcommand.
1218                         // We cannot use \newcommand directly because \global does not work with it.
1219                         os << "\n\\global\\long\\def\\" << name();
1220                         docstring param = from_ascii("#0");
1221                         for (int i = 1; i <= numargs_; ++i) {
1222                                 param[1] = '0' + i;
1223                                 os << param;
1224                         }
1225                 }
1226         } else {
1227                 // in LyX output we use some pseudo syntax which is implementation
1228                 // independent, e.g.
1229                 // \newcommand{\foo}[2][default]{#1,#2}
1230                 if (redefinition_ && !overwriteRedefinition)
1231                         os << "\\renewcommand";
1232                 else
1233                         os << "\\newcommand";
1234                 os << "{\\" << name() << '}';
1235                 if (numargs_ > 0)
1236                         os << '[' << numargs_ << ']';
1237
1238                 for (int i = 0; i < optionals_; ++i) {
1239                         docstring optValue = asString(cell(optIdx(i)));
1240                         if (optValue.find(']') != docstring::npos)
1241                                 os << "[{" << cell(optIdx(i)) << "}]";
1242                         else
1243                                 os << "[" << cell(optIdx(i)) << "]";
1244                 }
1245         }
1246
1247         os << "{" << cell(defIdx()) << "}";
1248
1249         if (os.latex()) {
1250                 // writing .tex. done.
1251                 os << "%\n";
1252                 ++num_lines;
1253         } else {
1254                 // writing .lyx, write special .tex export only if necessary
1255                 if (!cell(displayIdx()).empty()) {
1256                         os << "\n{" << cell(displayIdx()) << '}';
1257                         ++num_lines;
1258                 }
1259         }
1260
1261         return num_lines;
1262 }
1263
1264
1265 docstring InsetMathMacroTemplate::xhtml(XMLStream &, OutputParams const &) const
1266 {
1267         return docstring();
1268 }
1269
1270 int InsetMathMacroTemplate::plaintext(odocstringstream & os,
1271                                  OutputParams const &, size_t) const
1272 {
1273         docstring const str = '[' + buffer().B_("math macro") + ']';
1274
1275         os << str;
1276         return str.size();
1277 }
1278
1279
1280 bool InsetMathMacroTemplate::validName() const
1281 {
1282         docstring n = name();
1283
1284         if (n.empty())
1285                 return false;
1286
1287         // converting back and force doesn't swallow anything?
1288         /*MathData ma;
1289         asArray(n, ma);
1290         if (asString(ma) != n)
1291                 return false;*/
1292
1293         // valid characters?
1294         if (n.size() > 1) {
1295                 for (char_type c : n) {
1296                         if (!(c >= 'a' && c <= 'z')
1297                             && !(c >= 'A' && c <= 'Z')
1298                             && c != '*')
1299                                 return false;
1300                 }
1301         }
1302
1303         return true;
1304 }
1305
1306
1307 bool InsetMathMacroTemplate::validMacro() const
1308 {
1309         return validName();
1310 }
1311
1312
1313 bool InsetMathMacroTemplate::fixNameAndCheckIfValid()
1314 {
1315         // check all the characters/insets in the name cell
1316         size_t i = 0;
1317         MathData & data = cell(0);
1318         while (i < data.size()) {
1319                 InsetMathChar const * cinset = data[i]->asCharInset();
1320                 if (cinset) {
1321                         // valid character in [a-zA-Z]?
1322                         char_type c = cinset->getChar();
1323                         if ((c >= 'a' && c <= 'z')
1324                             || (c >= 'A' && c <= 'Z')) {
1325                                 ++i;
1326                                 continue;
1327                         }
1328                 }
1329
1330                 // throw cell away
1331                 data.erase(i);
1332         }
1333
1334         // now it should be valid if anything in the name survived
1335         return !data.empty();
1336 }
1337
1338
1339 void InsetMathMacroTemplate::validate(LaTeXFeatures & features) const
1340 {
1341         // we need global optional macro arguments. They are not available
1342         // with \def, and \newcommand does not support global macros. So we
1343         // are bound to xargs also for the single-optional-parameter case.
1344         if (optionals_ > 0)
1345                 features.require("xargs");
1346 }
1347
1348 void InsetMathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1349 {
1350         defaults.resize(numargs_);
1351         for (int i = 0; i < optionals_; ++i)
1352                 defaults[i] = asString(cell(optIdx(i)));
1353 }
1354
1355
1356 docstring InsetMathMacroTemplate::definition() const
1357 {
1358         return asString(cell(defIdx()));
1359 }
1360
1361
1362 docstring InsetMathMacroTemplate::displayDefinition() const
1363 {
1364         return asString(cell(displayIdx()));
1365 }
1366
1367
1368 size_t InsetMathMacroTemplate::numArgs() const
1369 {
1370         return numargs_;
1371 }
1372
1373
1374 size_t InsetMathMacroTemplate::numOptionals() const
1375 {
1376         return optionals_;
1377 }
1378
1379
1380 void InsetMathMacroTemplate::infoize(odocstream & os) const
1381 {
1382         os << bformat(_("Math Macro: \\%1$s"), name());
1383 }
1384
1385
1386 string InsetMathMacroTemplate::contextMenuName() const
1387 {
1388         return "context-math-macro-definition";
1389 }
1390
1391
1392 void InsetMathMacroTemplate::addToToc(DocIterator const & pit, bool output_active,
1393                                                                  UpdateType, TocBackend & backend) const
1394 {
1395         docstring str;
1396         if (!validMacro())
1397                 str = bformat(_("Invalid macro! \\%1$s"), name());
1398         else
1399                 str = "\\" + name();
1400         TocBuilder & b = backend.builder("math-macro");
1401         b.pushItem(pit, str, output_active);
1402         b.pop();
1403 }
1404
1405
1406 } // namespace lyx