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