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