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