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