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