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