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