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