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