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