]> git.lyx.org Git - lyx.git/blob - src/mathed/MathData.cpp
Fix #10863 compiler warnings.
[lyx.git] / src / mathed / MathData.cpp
1 /**
2  * \file MathData.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 "MathData.h"
15
16 #include "InsetMathBrace.h"
17 #include "InsetMathFont.h"
18 #include "InsetMathScript.h"
19 #include "MacroTable.h"
20 #include "InsetMathMacro.h"
21 #include "MathStream.h"
22 #include "MathSupport.h"
23 #include "MetricsInfo.h"
24 #include "ReplaceData.h"
25
26 #include "Buffer.h"
27 #include "BufferView.h"
28 #include "CoordCache.h"
29 #include "Cursor.h"
30
31 #include "mathed/InsetMathUnknown.h"
32
33 #include "frontends/FontMetrics.h"
34 #include "frontends/Painter.h"
35
36 #include "support/debug.h"
37 #include "support/docstream.h"
38 #include "support/gettext.h"
39 #include "support/lassert.h"
40 #include "support/lyxalgo.h"
41
42 #include <cstdlib>
43
44 using namespace std;
45
46 namespace lyx {
47
48
49 MathData::MathData(Buffer * buf, const_iterator from, const_iterator to)
50         : base_type(from, to), minasc_(0), mindes_(0), slevel_(0),
51           sshift_(0), kerning_(0), buffer_(buf)
52 {}
53
54
55 MathAtom & MathData::operator[](pos_type pos)
56 {
57         LBUFERR(pos < size());
58         return base_type::operator[](pos);
59 }
60
61
62 MathAtom const & MathData::operator[](pos_type pos) const
63 {
64         LBUFERR(pos < size());
65         return base_type::operator[](pos);
66 }
67
68
69 void MathData::insert(size_type pos, MathAtom const & t)
70 {
71         LBUFERR(pos <= size());
72         base_type::insert(begin() + pos, t);
73 }
74
75
76 void MathData::insert(size_type pos, MathData const & ar)
77 {
78         LBUFERR(pos <= size());
79         base_type::insert(begin() + pos, ar.begin(), ar.end());
80 }
81
82
83 void MathData::append(MathData const & ar)
84 {
85         insert(size(), ar);
86 }
87
88
89 void MathData::erase(size_type pos)
90 {
91         if (pos < size())
92                 erase(pos, pos + 1);
93 }
94
95
96 void MathData::erase(iterator pos1, iterator pos2)
97 {
98         base_type::erase(pos1, pos2);
99 }
100
101
102 void MathData::erase(iterator pos)
103 {
104         base_type::erase(pos);
105 }
106
107
108 void MathData::erase(size_type pos1, size_type pos2)
109 {
110         base_type::erase(begin() + pos1, begin() + pos2);
111 }
112
113
114 void MathData::dump2() const
115 {
116         odocstringstream os;
117         NormalStream ns(os);
118         for (const_iterator it = begin(); it != end(); ++it)
119                 ns << *it << ' ';
120         lyxerr << to_utf8(os.str());
121 }
122
123
124 void MathData::dump() const
125 {
126         odocstringstream os;
127         NormalStream ns(os);
128         for (const_iterator it = begin(); it != end(); ++it)
129                 ns << '<' << *it << '>';
130         lyxerr << to_utf8(os.str());
131 }
132
133
134 void MathData::validate(LaTeXFeatures & features) const
135 {
136         for (const_iterator it = begin(); it != end(); ++it)
137                 (*it)->validate(features);
138 }
139
140
141 bool MathData::match(MathData const & ar) const
142 {
143         return size() == ar.size() && matchpart(ar, 0);
144 }
145
146
147 bool MathData::matchpart(MathData const & ar, pos_type pos) const
148 {
149         if (size() < ar.size() + pos)
150                 return false;
151         const_iterator it = begin() + pos;
152         for (const_iterator jt = ar.begin(); jt != ar.end(); ++jt, ++it)
153                 if (asString(*it) != asString(*jt))
154                         return false;
155         return true;
156 }
157
158
159 void MathData::replace(ReplaceData & rep)
160 {
161         for (size_type i = 0; i < size(); ++i) {
162                 if (find1(rep.from, i)) {
163                         // match found
164                         lyxerr << "match found!" << endl;
165                         erase(i, i + rep.from.size());
166                         insert(i, rep.to);
167                 }
168         }
169
170         // FIXME: temporarily disabled
171         // for (const_iterator it = begin(); it != end(); ++it)
172         //      it->nucleus()->replace(rep);
173 }
174
175
176 bool MathData::find1(MathData const & ar, size_type pos) const
177 {
178         lyxerr << "finding '" << ar << "' in '" << *this << "'" << endl;
179         for (size_type i = 0, n = ar.size(); i < n; ++i)
180                 if (asString(operator[](pos + i)) != asString(ar[i]))
181                         return false;
182         return true;
183 }
184
185
186 MathData::size_type MathData::find(MathData const & ar) const
187 {
188         for (int i = 0, last = size() - ar.size(); i < last; ++i)
189                 if (find1(ar, i))
190                         return i;
191         return size();
192 }
193
194
195 MathData::size_type MathData::find_last(MathData const & ar) const
196 {
197         for (int i = size() - ar.size(); i >= 0; --i)
198                 if (find1(ar, i))
199                         return i;
200         return size();
201 }
202
203
204 bool MathData::contains(MathData const & ar) const
205 {
206         if (find(ar) != size())
207                 return true;
208         for (const_iterator it = begin(); it != end(); ++it)
209                 if ((*it)->contains(ar))
210                         return true;
211         return false;
212 }
213
214
215 bool MathData::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
216 {
217         bool has_contents = false;
218         BufferView * bv = mi.base.bv;
219         MathData * ar = const_cast<MathData*>(this);
220         ar->updateMacros(&bv->cursor(), mi.macrocontext,
221                          InternalUpdate, mi.base.macro_nesting);
222
223
224         // FIXME: for completion, try to insert the relevant data in the
225         // mathrow (like is done for text rows). We could add a pair of
226         // InsetMathColor inset, but these come with extra spacing of
227         // their own.
228         DocIterator const & inlineCompletionPos = bv->inlineCompletionPos();
229         bool const has_completion = inlineCompletionPos.inMathed()
230                 && &inlineCompletionPos.cell() == this;
231         size_t const compl_pos = has_completion ? inlineCompletionPos.pos() : 0;
232
233         for (size_t i = 0 ; i < size() ; ++i) {
234                 has_contents |= (*this)[i]->addToMathRow(mrow, mi);
235                 if (i + 1 == compl_pos) {
236                         mrow.back().compl_text = bv->inlineCompletion();
237                         mrow.back().compl_unique_to = bv->inlineCompletionUniqueChars();
238                 }
239         }
240         return has_contents;
241 }
242
243
244 #if 0
245 namespace {
246
247 bool isInside(DocIterator const & it, MathData const & ar,
248         pos_type p1, pos_type p2)
249 {
250         for (size_t i = 0; i != it.depth(); ++i) {
251                 CursorSlice const & sl = it[i];
252                 if (sl.inset().inMathed() && &sl.cell() == &ar)
253                         return p1 <= sl.pos() && sl.pos() < p2;
254         }
255         return false;
256 }
257
258 }
259 #endif
260
261
262 void MathData::metrics(MetricsInfo & mi, Dimension & dim) const
263 {
264         frontend::FontMetrics const & fm = theFontMetrics(mi.base.font);
265         dim = fm.dimension('I');
266         int xascent = fm.dimension('x').ascent();
267         if (xascent >= dim.asc)
268                 xascent = (2 * dim.asc) / 3;
269         minasc_ = xascent;
270         mindes_ = (3 * xascent) / 4;
271         slevel_ = (4 * xascent) / 5;
272         sshift_ = xascent / 4;
273
274         MathRow mrow(mi, this);
275         mrow.metrics(mi, dim);
276         mrow_cache_[mi.base.bv] = mrow;
277         kerning_ = mrow.kerning(mi.base.bv);
278
279         // Cache the dimension.
280         mi.base.bv->coordCache().arrays().add(this, dim);
281 }
282
283
284 void MathData::drawSelection(PainterInfo & pi, int const x, int const y) const
285 {
286         BufferView const * bv = pi.base.bv;
287         Cursor const & cur = bv->cursor();
288         InsetMath const * inset = cur.inset().asInsetMath();
289         if (!cur.selection() || !inset || inset->nargs() == 0)
290                 return;
291
292         CursorSlice const s1 = cur.selBegin();
293         CursorSlice const s2 = cur.selEnd();
294         MathData const & c1 = inset->cell(s1.idx());
295
296         if (s1.idx() == s2.idx() && &c1 == this) {
297                 // selection indide cell
298                 Dimension const dim = bv->coordCache().getArrays().dim(&c1);
299                 int const beg = c1.pos2x(bv, s1.pos());
300                 int const end = c1.pos2x(bv, s2.pos());
301                 pi.pain.fillRectangle(x + beg, y - dim.ascent(),
302                                       end - beg, dim.height(), Color_selection);
303         } else {
304                 for (idx_type i = 0; i < inset->nargs(); ++i) {
305                         MathData const & c = inset->cell(i);
306                         if (&c == this && inset->idxBetween(i, s1.idx(), s2.idx())) {
307                                 // The whole cell is selected
308                                 Dimension const dim = bv->coordCache().getArrays().dim(&c);
309                                 pi.pain.fillRectangle(x, y - dim.ascent(),
310                                                       dim.width(), dim.height(),
311                                                       Color_selection);
312                         }
313                 }
314         }
315 }
316
317
318 void MathData::draw(PainterInfo & pi, int const x, int const y) const
319 {
320         //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
321         setXY(*pi.base.bv, x, y);
322
323         drawSelection(pi, x, y);
324         MathRow const & mrow = mrow_cache_[pi.base.bv];
325         mrow.draw(pi, x, y);
326 }
327
328
329 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
330 {
331         dim.clear();
332         Dimension d;
333         for (const_iterator it = begin(); it != end(); ++it) {
334                 (*it)->metricsT(mi, d);
335                 dim += d;
336         }
337 }
338
339
340 void MathData::drawT(TextPainter & pain, int x, int y) const
341 {
342         //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
343
344         // FIXME: Abdel 16/10/2006
345         // This drawT() method is never used, this is dead code.
346
347         for (const_iterator it = begin(), et = end(); it != et; ++it) {
348                 (*it)->drawT(pain, x, y);
349                 //x += (*it)->width_;
350                 x += 2;
351         }
352 }
353
354
355 void MathData::updateBuffer(ParIterator const & it, UpdateType utype)
356 {
357         // pass down
358         for (size_t i = 0, n = size(); i != n; ++i) {
359                 MathAtom & at = operator[](i);
360                 at.nucleus()->updateBuffer(it, utype);
361         }
362 }
363
364
365 void MathData::updateMacros(Cursor * cur, MacroContext const & mc,
366                 UpdateType utype, int nesting)
367 {
368         // If we are editing a macro, we cannot update it immediately,
369         // otherwise wrong undo steps will be recorded (bug 6208).
370         InsetMath const * inmath = cur ? cur->inset().asInsetMath() : 0;
371         InsetMathMacro const * inmacro = inmath ? inmath->asMacro() : 0;
372         docstring const edited_name = inmacro ? inmacro->name() : docstring();
373
374         // go over the array and look for macros
375         for (size_t i = 0; i < size(); ++i) {
376                 InsetMathMacro * macroInset = operator[](i).nucleus()->asMacro();
377                 if (!macroInset || macroInset->macroName().empty()
378                                 || macroInset->macroName()[0] == '^'
379                                 || macroInset->macroName()[0] == '_'
380                                 || (macroInset->name() == edited_name
381                                     && macroInset->displayMode() ==
382                                                 InsetMathMacro::DISPLAY_UNFOLDED))
383                         continue;
384
385                 // get macro
386                 macroInset->updateMacro(mc);
387                 size_t macroNumArgs = 0;
388                 size_t macroOptionals = 0;
389                 MacroData const * macro = macroInset->macro();
390                 if (macro) {
391                         macroNumArgs = macro->numargs();
392                         macroOptionals = macro->optionals();
393                 }
394
395                 // store old and compute new display mode
396                 InsetMathMacro::DisplayMode newDisplayMode;
397                 InsetMathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
398                 newDisplayMode = macroInset->computeDisplayMode();
399
400                 // arity changed or other reason to detach?
401                 if (oldDisplayMode == InsetMathMacro::DISPLAY_NORMAL
402                     && (macroInset->arity() != macroNumArgs
403                         || macroInset->optionals() != macroOptionals
404                         || newDisplayMode == InsetMathMacro::DISPLAY_UNFOLDED))
405                         detachMacroParameters(cur, i);
406
407                 // the macro could have been copied while resizing this
408                 macroInset = operator[](i).nucleus()->asMacro();
409
410                 // Cursor in \label?
411                 if (newDisplayMode != InsetMathMacro::DISPLAY_UNFOLDED
412                     && oldDisplayMode == InsetMathMacro::DISPLAY_UNFOLDED) {
413                         // put cursor in front of macro
414                         if (cur) {
415                                 int macroSlice = cur->find(macroInset);
416                                 if (macroSlice != -1)
417                                         cur->cutOff(macroSlice - 1);
418                         }
419                 }
420
421                 // update the display mode
422                 size_t appetite = macroInset->appetite();
423                 macroInset->setDisplayMode(newDisplayMode);
424
425                 // arity changed?
426                 if (newDisplayMode == InsetMathMacro::DISPLAY_NORMAL
427                     && (macroInset->arity() != macroNumArgs
428                         || macroInset->optionals() != macroOptionals)) {
429                         // is it a virgin macro which was never attached to parameters?
430                         bool fromInitToNormalMode
431                         = (oldDisplayMode == InsetMathMacro::DISPLAY_INIT
432                            || oldDisplayMode == InsetMathMacro::DISPLAY_INTERACTIVE_INIT)
433                           && newDisplayMode == InsetMathMacro::DISPLAY_NORMAL;
434
435                         // if the macro was entered interactively (i.e. not by paste or during
436                         // loading), it should not be greedy, but the cursor should
437                         // automatically jump into the macro when behind
438                         bool interactive = (oldDisplayMode == InsetMathMacro::DISPLAY_INTERACTIVE_INIT);
439
440                         // attach parameters
441                         attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
442                                 fromInitToNormalMode, interactive, appetite);
443
444                         if (cur)
445                                 cur->updateInsets(&cur->bottom().inset());
446                 }
447
448                 // Give macro the chance to adapt to new situation.
449                 // The macroInset could be invalid now because it was put into a script
450                 // inset and therefore "deep" copied. So get it again from the MathData.
451                 InsetMath * inset = operator[](i).nucleus();
452                 if (inset->asScriptInset())
453                         inset = inset->asScriptInset()->nuc()[0].nucleus();
454                 LASSERT(inset->asMacro(), continue);
455                 inset->asMacro()->updateRepresentation(cur, mc, utype, nesting + 1);
456         }
457 }
458
459
460 void MathData::detachMacroParameters(DocIterator * cur, const size_type macroPos)
461 {
462         InsetMathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
463         // We store this now, because the inset pointer will be invalidated in the scond loop below
464         size_t const optionals = macroInset->optionals();
465
466         // detach all arguments
467         vector<MathData> detachedArgs;
468         if (macroPos + 1 == size())
469                 // strip arguments if we are at the MathData end
470                 macroInset->detachArguments(detachedArgs, true);
471         else
472                 macroInset->detachArguments(detachedArgs, false);
473
474         // find cursor slice
475         int curMacroSlice = -1;
476         if (cur)
477                 curMacroSlice = cur->find(macroInset);
478         idx_type curMacroIdx = -1;
479         pos_type curMacroPos = -1;
480         vector<CursorSlice> argSlices;
481         if (curMacroSlice != -1) {
482                 curMacroPos = (*cur)[curMacroSlice].pos();
483                 curMacroIdx = (*cur)[curMacroSlice].idx();
484                 cur->cutOff(curMacroSlice, argSlices);
485                 cur->pop_back();
486         }
487
488         // only [] after the last non-empty argument can be dropped later
489         size_t lastNonEmptyOptional = 0;
490         for (size_t l = 0; l < detachedArgs.size() && l < optionals; ++l) {
491                 if (!detachedArgs[l].empty())
492                         lastNonEmptyOptional = l;
493         }
494
495         // optional arguments to be put back?
496         pos_type p = macroPos + 1;
497         size_t j = 0;
498         // We do not want to use macroInset below, the insert() call in
499         // the loop will invalidate it.
500         macroInset = 0;
501         for (; j < detachedArgs.size() && j < optionals; ++j) {
502                 // another non-empty parameter follows?
503                 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
504
505                 // then we can drop empty optional parameters
506                 if (detachedArgs[j].empty() && canDropEmptyOptional) {
507                         if (curMacroIdx == j)
508                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 1;
509                         continue;
510                 }
511
512                 // Otherwise we don't drop an empty optional, put it back normally
513                 MathData optarg;
514                 asArray(from_ascii("[]"), optarg);
515                 MathData & arg = detachedArgs[j];
516
517                 // look for "]", i.e. put a brace around?
518                 InsetMathBrace * brace = 0;
519                 for (size_t q = 0; q < arg.size(); ++q) {
520                         if (arg[q]->getChar() == ']') {
521                                 // put brace
522                                 brace = new InsetMathBrace(buffer_);
523                                 break;
524                         }
525                 }
526
527                 // put arg between []
528                 if (brace) {
529                         brace->cell(0) = arg;
530                         optarg.insert(1, MathAtom(brace));
531                 } else
532                         optarg.insert(1, arg);
533
534                 // insert it into the array
535                 insert(p, optarg);
536                 p += optarg.size();
537
538                 // cursor in macro?
539                 if (curMacroSlice == -1)
540                         continue;
541
542                 // cursor in optional argument of macro?
543                 if (curMacroIdx == j) {
544                         if (brace) {
545                                 cur->append(0, curMacroPos);
546                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 2;
547                         } else
548                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
549                         cur->append(argSlices);
550                 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
551                         // cursor right of macro
552                         (*cur)[curMacroSlice - 1].pos() += optarg.size();
553         }
554
555         // put them back into the MathData
556         for (; j < detachedArgs.size(); ++j, ++p) {
557                 MathData const & arg = detachedArgs[j];
558                 if (arg.size() == 1
559                     && !arg[0]->asScriptInset()
560                     && !(arg[0]->asMacro() && arg[0]->asMacro()->arity() > 0))
561                         insert(p, arg[0]);
562                 else
563                         insert(p, MathAtom(new InsetMathBrace(arg)));
564
565                 // cursor in macro?
566                 if (curMacroSlice == -1)
567                         continue;
568
569                 // cursor in j-th argument of macro?
570                 if (curMacroIdx == j) {
571                         if (operator[](p).nucleus()->asBraceInset()) {
572                                 (*cur)[curMacroSlice - 1].pos() = p;
573                                 cur->append(0, curMacroPos);
574                                 cur->append(argSlices);
575                         } else {
576                                 (*cur)[curMacroSlice - 1].pos() = p; // + macroPos;
577                                 cur->append(argSlices);
578                         }
579                 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
580                         ++(*cur)[curMacroSlice - 1].pos();
581         }
582
583         if (cur)
584                 cur->updateInsets(&cur->bottom().inset());
585 }
586
587
588 void MathData::attachMacroParameters(Cursor * cur,
589         const size_type macroPos, const size_type macroNumArgs,
590         const int macroOptionals, const bool fromInitToNormalMode,
591         const bool interactiveInit, const size_t appetite)
592 {
593         InsetMathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
594
595         // start at atom behind the macro again, maybe with some new arguments
596         // from the detach phase above, to add them back into the macro inset
597         size_t p = macroPos + 1;
598         vector<MathData> detachedArgs;
599         MathAtom scriptToPutAround;
600
601         // find cursor slice again of this MathData
602         int thisSlice = -1;
603         if (cur)
604                 thisSlice = cur->find(*this);
605         int thisPos = -1;
606         if (thisSlice != -1)
607                 thisPos = (*cur)[thisSlice].pos();
608
609         // find arguments behind the macro
610         if (!interactiveInit) {
611                 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
612                         scriptToPutAround, macroPos, thisPos, thisSlice);
613         }
614         collectParameters(cur, macroNumArgs, detachedArgs, p,
615                 scriptToPutAround, macroPos, thisPos, thisSlice, appetite);
616
617         // attach arguments back to macro inset
618         macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
619
620         // found tail script? E.g. \foo{a}b^x
621         if (scriptToPutAround.nucleus()) {
622                 InsetMathScript * scriptInset =
623                         scriptToPutAround.nucleus()->asScriptInset();
624                 // In the math parser we remove empty braces in the base
625                 // of a script inset, but we have to restore them here.
626                 if (scriptInset->nuc().empty()) {
627                         MathData ar;
628                         scriptInset->nuc().push_back(
629                                         MathAtom(new InsetMathBrace(ar)));
630                 }
631                 // put macro into a script inset
632                 scriptInset->nuc()[0] = operator[](macroPos);
633                 operator[](macroPos) = scriptToPutAround;
634
635                 // go into the script inset nucleus
636                 if (cur && thisPos == int(macroPos))
637                         cur->append(0, 0);
638
639                 // get pointer to "deep" copied macro inset
640                 scriptInset = operator[](macroPos).nucleus()->asScriptInset();
641                 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();
642         }
643
644         // remove them from the MathData
645         erase(macroPos + 1, p);
646
647         // cursor outside this MathData?
648         if (thisSlice == -1)
649                 return;
650
651         // fix cursor if right of p
652         if (thisPos >= int(p))
653                 (*cur)[thisSlice].pos() -= p - (macroPos + 1);
654
655         // was the macro inset just inserted interactively and was now folded
656         // and the cursor is just behind?
657         if ((*cur)[thisSlice].pos() == int(macroPos + 1)
658             && interactiveInit
659             && fromInitToNormalMode
660             && macroInset->arity() > 0
661             && thisSlice + 1 == int(cur->depth())) {
662                 // then enter it if the cursor was just behind
663                 (*cur)[thisSlice].pos() = macroPos;
664                 cur->push_back(CursorSlice(*macroInset));
665                 macroInset->idxFirst(*cur);
666         }
667 }
668
669
670 void MathData::collectOptionalParameters(Cursor * cur,
671         const size_type numOptionalParams, vector<MathData> & params,
672         size_t & pos, MathAtom & scriptToPutAround,
673         const pos_type macroPos, const int thisPos, const int thisSlice)
674 {
675         Buffer * buf = cur ? cur->buffer() : 0;
676         // insert optional arguments?
677         while (params.size() < numOptionalParams
678                && pos < size()
679                && !scriptToPutAround.nucleus()) {
680                 // is a [] block following which could be an optional parameter?
681                 if (operator[](pos)->getChar() != '[')
682                         break;
683
684                 // found possible optional argument, look for pairing "]"
685                 int count = 1;
686                 size_t right = pos + 1;
687                 for (; right < size(); ++right) {
688                         MathAtom & cell = operator[](right);
689
690                         if (cell->getChar() == '[')
691                                 ++count;
692                         else if (cell->getChar() == ']' && --count == 0)
693                                 // found right end
694                                 break;
695
696                         // maybe "]" with a script around?
697                         InsetMathScript * script = cell.nucleus()->asScriptInset();
698                         if (!script)
699                                 continue;
700                         if (script->nuc().size() != 1)
701                                 continue;
702                         if (script->nuc()[0]->getChar() == ']') {
703                                 // script will be put around the macro later
704                                 scriptToPutAround = cell;
705                                 break;
706                         }
707                 }
708
709                 // found?
710                 if (right >= size()) {
711                         // no ] found, so it's not an optional argument
712                         break;
713                 }
714
715                 // add everything between [ and ] as optional argument
716                 MathData optarg(buf, begin() + pos + 1, begin() + right);
717
718                 // a brace?
719                 bool brace = false;
720                 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
721                         brace = true;
722                         params.push_back(optarg[0]->asBraceInset()->cell(0));
723                 } else
724                         params.push_back(optarg);
725
726                 // place cursor in optional argument of macro
727                 // Note: The two expressions on the first line are equivalent
728                 // (see caller), but making this explicit pleases coverity.
729                 if (cur && thisSlice != -1
730                     && thisPos >= int(pos) && thisPos <= int(right)) {
731                         int paramPos = max(0, thisPos - int(pos) - 1);
732                         vector<CursorSlice> x;
733                         cur->cutOff(thisSlice, x);
734                         (*cur)[thisSlice].pos() = macroPos;
735                         if (brace) {
736                                 paramPos = x[0].pos();
737                                 x.erase(x.begin());
738                         }
739                         cur->append(0, paramPos);
740                         cur->append(x);
741                 }
742                 pos = right + 1;
743         }
744
745         // fill up empty optional parameters
746         while (params.size() < numOptionalParams)
747                 params.push_back(MathData());
748 }
749
750
751 void MathData::collectParameters(Cursor * cur,
752         const size_type numParams, vector<MathData> & params,
753         size_t & pos, MathAtom & scriptToPutAround,
754         const pos_type macroPos, const int thisPos, const int thisSlice,
755         const size_t appetite)
756 {
757         size_t startSize = params.size();
758
759         // insert normal arguments
760         while (params.size() < numParams
761                && params.size() - startSize < appetite
762                && pos < size()
763                && !scriptToPutAround.nucleus()) {
764                 MathAtom & cell = operator[](pos);
765
766                 // fix cursor
767                 vector<CursorSlice> argSlices;
768                 int argPos = 0;
769                 // Note: The two expressions on the first line are equivalent
770                 // (see caller), but making this explicit pleases coverity.
771                 if (cur && thisSlice != -1
772                         && thisPos == int(pos))
773                         cur->cutOff(thisSlice, argSlices);
774
775                 // which kind of parameter is it? In {}? With index x^n?
776                 InsetMathBrace const * brace = cell->asBraceInset();
777                 if (brace) {
778                         // found brace, convert into argument
779                         params.push_back(brace->cell(0));
780
781                         // cursor inside of the brace or just in front of?
782                         if (thisPos == int(pos) && !argSlices.empty()) {
783                                 argPos = argSlices[0].pos();
784                                 argSlices.erase(argSlices.begin());
785                         }
786                 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
787                         // last inset with scripts without braces
788                         // -> they belong to the macro, not the argument
789                         InsetMathScript * script = cell.nucleus()->asScriptInset();
790                         if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
791                                 // nucleus in brace? Unpack!
792                                 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
793                         else
794                                 params.push_back(script->nuc());
795
796                         // script will be put around below
797                         scriptToPutAround = cell;
798
799                         // this should only happen after loading, so make cursor handling simple
800                         if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
801                                 argSlices.clear();
802                                 if (cur)
803                                         cur->append(0, 0);
804                         }
805                 } else {
806                         // the simplest case: plain inset
807                         MathData array;
808                         array.insert(0, cell);
809                         params.push_back(array);
810                 }
811
812                 // put cursor in argument again
813                 // Note: The first two expressions on the first line are
814                 // equivalent (see caller), but making this explicit pleases
815                 // coverity.
816                 if (cur && thisSlice != -1 && thisPos == int(pos)) {
817                         cur->append(params.size() - 1, argPos);
818                         cur->append(argSlices);
819                         (*cur)[thisSlice].pos() = macroPos;
820                 }
821
822                 ++pos;
823         }
824 }
825
826
827 int MathData::pos2x(BufferView const * bv, size_type pos) const
828 {
829         int x = 0;
830         size_type target = min(pos, size());
831         CoordCache::Insets const & coords = bv->coordCache().getInsets();
832         for (size_type i = 0; i < target; ++i) {
833                 const_iterator it = begin() + i;
834                 //lyxerr << "char: " << (*it)->getChar()
835                 //      << "width: " << (*it)->width() << endl;
836                 x += coords.dim((*it).nucleus()).wid;
837         }
838         return x;
839 }
840
841
842 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx) const
843 {
844         const_iterator it = begin();
845         int lastx = 0;
846         int currx = 0;
847         CoordCache::Insets const & coords = bv->coordCache().getInsets();
848         // find first position after targetx
849         for (; currx < targetx && it != end(); ++it) {
850                 lastx = currx;
851                 currx += coords.dim((*it).nucleus()).wid;
852         }
853
854         /**
855          * If we are not at the beginning of the array, go to the left
856          * of the inset if one of the following two condition holds:
857          * - the current inset is editable (so that the cursor tip is
858          *   deeper than us): in this case, we want all intermediate
859          *   cursor slices to be before insets;
860          * - the mouse is closer to the left side of the inset than to
861          *   the right one.
862          * See bug 1918 for details.
863          **/
864         if (it != begin() && currx >= targetx
865             && ((*prev(it, 1))->asNestInset()
866                 || abs(lastx - targetx) < abs(currx - targetx))) {
867                 --it;
868         }
869
870         return it - begin();
871 }
872
873
874 int MathData::dist(BufferView const & bv, int x, int y) const
875 {
876         return bv.coordCache().getArrays().squareDistance(this, x, y);
877 }
878
879
880 void MathData::setXY(BufferView & bv, int x, int y) const
881 {
882         //lyxerr << "setting position cache for MathData " << this << endl;
883         bv.coordCache().arrays().add(this, x, y);
884 }
885
886
887 Dimension const & MathData::dimension(BufferView const & bv) const
888 {
889         return bv.coordCache().getArrays().dim(this);
890 }
891
892
893 int MathData::xm(BufferView const & bv) const
894 {
895         Geometry const & g = bv.coordCache().getArrays().geometry(this);
896
897         return g.pos.x_ + g.dim.wid / 2;
898 }
899
900
901 int MathData::ym(BufferView const & bv) const
902 {
903         Geometry const & g = bv.coordCache().getArrays().geometry(this);
904
905         return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
906 }
907
908
909 int MathData::xo(BufferView const & bv) const
910 {
911         return bv.coordCache().getArrays().x(this);
912 }
913
914
915 int MathData::yo(BufferView const & bv) const
916 {
917         return bv.coordCache().getArrays().y(this);
918 }
919
920
921 MathClass MathData::mathClass() const
922 {
923         MathClass res = MC_UNKNOWN;
924         for (MathAtom const & at : *this) {
925                 MathClass mc = at->mathClass();
926                 if (res == MC_UNKNOWN)
927                         res = mc;
928                 else if (mc != MC_UNKNOWN && res != mc)
929                         return MC_ORD;
930         }
931         return res == MC_UNKNOWN ? MC_ORD : res;
932 }
933
934
935 ostream & operator<<(ostream & os, MathData const & ar)
936 {
937         odocstringstream oss;
938         NormalStream ns(oss);
939         ns << ar;
940         return os << to_utf8(oss.str());
941 }
942
943
944 odocstream & operator<<(odocstream & os, MathData const & ar)
945 {
946         NormalStream ns(os);
947         ns << ar;
948         return os;
949 }
950
951
952 } // namespace lyx