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