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