]> git.lyx.org Git - lyx.git/blob - src/mathed/MathData.cpp
9d218987d3245e2a36513b7ddf84f2113dffc8b6
[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 "MathMacro.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 MathAtom & MathData::operator[](pos_type pos)
56 {
57         LBUFERR(pos < size());
58         return base_type::operator[](pos);
59 }
60
61
62 MathAtom const & MathData::operator[](pos_type pos) const
63 {
64         LBUFERR(pos < size());
65         return base_type::operator[](pos);
66 }
67
68
69 void MathData::insert(size_type pos, MathAtom const & t)
70 {
71         LBUFERR(pos <= size());
72         base_type::insert(begin() + pos, t);
73 }
74
75
76 void MathData::insert(size_type pos, MathData const & ar)
77 {
78         LBUFERR(pos <= size());
79         base_type::insert(begin() + pos, ar.begin(), ar.end());
80 }
81
82
83 void MathData::append(MathData const & ar)
84 {
85         insert(size(), ar);
86 }
87
88
89 void MathData::erase(size_type pos)
90 {
91         if (pos < size())
92                 erase(pos, pos + 1);
93 }
94
95
96 void MathData::erase(iterator pos1, iterator pos2)
97 {
98         base_type::erase(pos1, pos2);
99 }
100
101
102 void MathData::erase(iterator pos)
103 {
104         base_type::erase(pos);
105 }
106
107
108 void MathData::erase(size_type pos1, size_type pos2)
109 {
110         base_type::erase(begin() + pos1, begin() + pos2);
111 }
112
113
114 void MathData::dump2() const
115 {
116         odocstringstream os;
117         NormalStream ns(os);
118         for (const_iterator it = begin(); it != end(); ++it)
119                 ns << *it << ' ';
120         lyxerr << to_utf8(os.str());
121 }
122
123
124 void MathData::dump() const
125 {
126         odocstringstream os;
127         NormalStream ns(os);
128         for (const_iterator it = begin(); it != end(); ++it)
129                 ns << '<' << *it << '>';
130         lyxerr << to_utf8(os.str());
131 }
132
133
134 void MathData::validate(LaTeXFeatures & features) const
135 {
136         for (const_iterator it = begin(); it != end(); ++it)
137                 (*it)->validate(features);
138 }
139
140
141 bool MathData::match(MathData const & ar) const
142 {
143         return size() == ar.size() && matchpart(ar, 0);
144 }
145
146
147 bool MathData::matchpart(MathData const & ar, pos_type pos) const
148 {
149         if (size() < ar.size() + pos)
150                 return false;
151         const_iterator it = begin() + pos;
152         for (const_iterator jt = ar.begin(); jt != ar.end(); ++jt, ++it)
153                 if (asString(*it) != asString(*jt))
154                         return false;
155         return true;
156 }
157
158
159 void MathData::replace(ReplaceData & rep)
160 {
161         for (size_type i = 0; i < size(); ++i) {
162                 if (find1(rep.from, i)) {
163                         // match found
164                         lyxerr << "match found!" << endl;
165                         erase(i, i + rep.from.size());
166                         insert(i, rep.to);
167                 }
168         }
169
170         // FIXME: temporarily disabled
171         // for (const_iterator it = begin(); it != end(); ++it)
172         //      it->nucleus()->replace(rep);
173 }
174
175
176 bool MathData::find1(MathData const & ar, size_type pos) const
177 {
178         lyxerr << "finding '" << ar << "' in '" << *this << "'" << endl;
179         for (size_type i = 0, n = ar.size(); i < n; ++i)
180                 if (asString(operator[](pos + i)) != asString(ar[i]))
181                         return false;
182         return true;
183 }
184
185
186 MathData::size_type MathData::find(MathData const & ar) const
187 {
188         for (int i = 0, last = size() - ar.size(); i < last; ++i)
189                 if (find1(ar, i))
190                         return i;
191         return size();
192 }
193
194
195 MathData::size_type MathData::find_last(MathData const & ar) const
196 {
197         for (int i = size() - ar.size(); i >= 0; --i)
198                 if (find1(ar, i))
199                         return i;
200         return size();
201 }
202
203
204 bool MathData::contains(MathData const & ar) const
205 {
206         if (find(ar) != size())
207                 return true;
208         for (const_iterator it = begin(); it != end(); ++it)
209                 if ((*it)->contains(ar))
210                         return true;
211         return false;
212 }
213
214
215 void MathData::touch() const
216 {
217 }
218
219
220 bool MathData::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
221 {
222         bool has_contents = false;
223         BufferView * bv = mi.base.bv;
224         MathData * ar = const_cast<MathData*>(this);
225         ar->updateMacros(&bv->cursor(), mi.macrocontext,
226                          InternalUpdate, mi.base.macro_nesting);
227
228
229         // FIXME: for completion, try to insert the relevant data in the
230         // mathrow (like is done for text rows). We could add a pair of
231         // InsetMathColor inset, but these come with extra spacing of
232         // their own.
233         DocIterator const & inlineCompletionPos = bv->inlineCompletionPos();
234         bool const has_completion = inlineCompletionPos.inMathed()
235                 && &inlineCompletionPos.cell() == this;
236         size_t const compl_pos = has_completion ? inlineCompletionPos.pos() : 0;
237
238         for (size_t i = 0 ; i < size() ; ++i) {
239                 has_contents |= (*this)[i]->addToMathRow(mrow, mi);
240                 if (i + 1 == compl_pos) {
241                         mrow.back().compl_text = bv->inlineCompletion();
242                         mrow.back().compl_unique_to = bv->inlineCompletionUniqueChars();
243                 }
244         }
245         return has_contents;
246 }
247
248
249 #if 0
250 namespace {
251
252 bool isInside(DocIterator const & it, MathData const & ar,
253         pos_type p1, pos_type p2)
254 {
255         for (size_t i = 0; i != it.depth(); ++i) {
256                 CursorSlice const & sl = it[i];
257                 if (sl.inset().inMathed() && &sl.cell() == &ar)
258                         return p1 <= sl.pos() && sl.pos() < p2;
259         }
260         return false;
261 }
262
263 }
264 #endif
265
266
267 void MathData::metrics(MetricsInfo & mi, Dimension & dim) const
268 {
269         frontend::FontMetrics const & fm = theFontMetrics(mi.base.font);
270         dim = fm.dimension('I');
271         int xascent = fm.dimension('x').ascent();
272         if (xascent >= dim.asc)
273                 xascent = (2 * dim.asc) / 3;
274         minasc_ = xascent;
275         mindes_ = (3 * xascent) / 4;
276         slevel_ = (4 * xascent) / 5;
277         sshift_ = xascent / 4;
278
279         MathRow mrow(mi, this);
280         mrow_cache_[mi.base.bv] = mrow;
281         mrow.metrics(mi, dim);
282         kerning_ = mrow.kerning(mi.base.bv);
283
284         // Cache the dimension.
285         mi.base.bv->coordCache().arrays().add(this, dim);
286 }
287
288
289 void MathData::drawSelection(PainterInfo & pi, int const x, int const y) const
290 {
291         BufferView const * bv = pi.base.bv;
292         Cursor const & cur = bv->cursor();
293         InsetMath const * inset = cur.inset().asInsetMath();
294         if (!cur.selection() || !inset || inset->nargs() == 0)
295                 return;
296
297         CursorSlice const s1 = cur.selBegin();
298         CursorSlice const s2 = cur.selEnd();
299         MathData const & c1 = inset->cell(s1.idx());
300
301         if (s1.idx() == s2.idx() && &c1 == this) {
302                 // selection indide cell
303                 Dimension const dim = bv->coordCache().getArrays().dim(&c1);
304                 int const beg = c1.pos2x(bv, s1.pos());
305                 int const end = c1.pos2x(bv, s2.pos());
306                 pi.pain.fillRectangle(x + beg, y - dim.ascent(),
307                                       end - beg, dim.height(), Color_selection);
308         } else {
309                 for (idx_type i = 0; i < inset->nargs(); ++i) {
310                         MathData const & c = inset->cell(i);
311                         if (&c == this && inset->idxBetween(i, s1.idx(), s2.idx())) {
312                                 // The whole cell is selected
313                                 Dimension const dim = bv->coordCache().getArrays().dim(&c);
314                                 pi.pain.fillRectangle(x, y - dim.ascent(),
315                                                       dim.width(), dim.height(),
316                                                       Color_selection);
317                         }
318                 }
319         }
320 }
321
322
323 void MathData::draw(PainterInfo & pi, int const x, int const y) const
324 {
325         //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
326         BufferView & bv  = *pi.base.bv;
327         setXY(bv, x, y);
328
329         Dimension const & dim = bv.coordCache().getArrays().dim(this);
330
331         // don't draw outside the workarea
332         if (y + dim.descent() <= 0
333                 || y - dim.ascent() >= bv.workHeight()
334                 || x + dim.width() <= 0
335                 || x >= bv. workWidth())
336                 return;
337
338         drawSelection(pi, x, y);
339         MathRow const & mrow = mrow_cache_[pi.base.bv];
340         mrow.draw(pi, x, y);
341 }
342
343
344 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
345 {
346         dim.clear();
347         Dimension d;
348         for (const_iterator it = begin(); it != end(); ++it) {
349                 (*it)->metricsT(mi, d);
350                 dim += d;
351         }
352 }
353
354
355 void MathData::drawT(TextPainter & pain, int x, int y) const
356 {
357         //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
358
359         // FIXME: Abdel 16/10/2006
360         // This drawT() method is never used, this is dead code.
361
362         for (const_iterator it = begin(), et = end(); it != et; ++it) {
363                 (*it)->drawT(pain, x, y);
364                 //x += (*it)->width_;
365                 x += 2;
366         }
367 }
368
369
370 void MathData::updateBuffer(ParIterator const & it, UpdateType utype)
371 {
372         // pass down
373         for (size_t i = 0, n = size(); i != n; ++i) {
374                 MathAtom & at = operator[](i);
375                 at.nucleus()->updateBuffer(it, utype);
376         }
377 }
378
379
380 void MathData::updateMacros(Cursor * cur, MacroContext const & mc,
381                 UpdateType utype, int nesting)
382 {
383         // If we are editing a macro, we cannot update it immediately,
384         // otherwise wrong undo steps will be recorded (bug 6208).
385         InsetMath const * inmath = cur ? cur->inset().asInsetMath() : 0;
386         MathMacro const * inmacro = inmath ? inmath->asMacro() : 0;
387         docstring const edited_name = inmacro ? inmacro->name() : docstring();
388
389         // go over the array and look for macros
390         for (size_t i = 0; i < size(); ++i) {
391                 MathMacro * macroInset = operator[](i).nucleus()->asMacro();
392                 if (!macroInset || macroInset->macroName().empty()
393                                 || macroInset->macroName()[0] == '^'
394                                 || macroInset->macroName()[0] == '_'
395                                 || (macroInset->name() == edited_name
396                                     && macroInset->displayMode() ==
397                                                 MathMacro::DISPLAY_UNFOLDED))
398                         continue;
399
400                 // get macro
401                 macroInset->updateMacro(mc);
402                 size_t macroNumArgs = 0;
403                 size_t macroOptionals = 0;
404                 MacroData const * macro = macroInset->macro();
405                 if (macro) {
406                         macroNumArgs = macro->numargs();
407                         macroOptionals = macro->optionals();
408                 }
409
410                 // store old and compute new display mode
411                 MathMacro::DisplayMode newDisplayMode;
412                 MathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
413                 newDisplayMode = macroInset->computeDisplayMode();
414
415                 // arity changed or other reason to detach?
416                 if (oldDisplayMode == MathMacro::DISPLAY_NORMAL
417                     && (macroInset->arity() != macroNumArgs
418                         || macroInset->optionals() != macroOptionals
419                         || newDisplayMode == MathMacro::DISPLAY_UNFOLDED))
420                         detachMacroParameters(cur, i);
421
422                 // the macro could have been copied while resizing this
423                 macroInset = operator[](i).nucleus()->asMacro();
424
425                 // Cursor in \label?
426                 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED
427                     && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
428                         // put cursor in front of macro
429                         if (cur) {
430                                 int macroSlice = cur->find(macroInset);
431                                 if (macroSlice != -1)
432                                         cur->cutOff(macroSlice - 1);
433                         }
434                 }
435
436                 // update the display mode
437                 size_t appetite = macroInset->appetite();
438                 macroInset->setDisplayMode(newDisplayMode);
439
440                 // arity changed?
441                 if (newDisplayMode == MathMacro::DISPLAY_NORMAL
442                     && (macroInset->arity() != macroNumArgs
443                         || macroInset->optionals() != macroOptionals)) {
444                         // is it a virgin macro which was never attached to parameters?
445                         bool fromInitToNormalMode
446                         = (oldDisplayMode == MathMacro::DISPLAY_INIT
447                            || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
448                           && newDisplayMode == MathMacro::DISPLAY_NORMAL;
449
450                         // if the macro was entered interactively (i.e. not by paste or during
451                         // loading), it should not be greedy, but the cursor should
452                         // automatically jump into the macro when behind
453                         bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
454
455                         // attach parameters
456                         attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
457                                 fromInitToNormalMode, interactive, appetite);
458
459                         if (cur)
460                                 cur->updateInsets(&cur->bottom().inset());
461                 }
462
463                 // Give macro the chance to adapt to new situation.
464                 // The macroInset could be invalid now because it was put into a script
465                 // inset and therefore "deep" copied. So get it again from the MathData.
466                 InsetMath * inset = operator[](i).nucleus();
467                 if (inset->asScriptInset())
468                         inset = inset->asScriptInset()->nuc()[0].nucleus();
469                 LASSERT(inset->asMacro(), continue);
470                 inset->asMacro()->updateRepresentation(cur, mc, utype, nesting + 1);
471         }
472 }
473
474
475 void MathData::detachMacroParameters(DocIterator * cur, const size_type macroPos)
476 {
477         MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
478         // We store this now, because the inset pointer will be invalidated in the scond loop below
479         size_t const optionals = macroInset->optionals();
480
481         // detach all arguments
482         vector<MathData> detachedArgs;
483         if (macroPos + 1 == size())
484                 // strip arguments if we are at the MathData end
485                 macroInset->detachArguments(detachedArgs, true);
486         else
487                 macroInset->detachArguments(detachedArgs, false);
488
489         // find cursor slice
490         int curMacroSlice = -1;
491         if (cur)
492                 curMacroSlice = cur->find(macroInset);
493         idx_type curMacroIdx = -1;
494         pos_type curMacroPos = -1;
495         vector<CursorSlice> argSlices;
496         if (curMacroSlice != -1) {
497                 curMacroPos = (*cur)[curMacroSlice].pos();
498                 curMacroIdx = (*cur)[curMacroSlice].idx();
499                 cur->cutOff(curMacroSlice, argSlices);
500                 cur->pop_back();
501         }
502
503         // only [] after the last non-empty argument can be dropped later
504         size_t lastNonEmptyOptional = 0;
505         for (size_t l = 0; l < detachedArgs.size() && l < optionals; ++l) {
506                 if (!detachedArgs[l].empty())
507                         lastNonEmptyOptional = l;
508         }
509
510         // optional arguments to be put back?
511         pos_type p = macroPos + 1;
512         size_t j = 0;
513         // We do not want to use macroInset below, the insert() call in
514         // the loop will invalidate it.
515         macroInset = 0;
516         for (; j < detachedArgs.size() && j < optionals; ++j) {
517                 // another non-empty parameter follows?
518                 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
519
520                 // then we can drop empty optional parameters
521                 if (detachedArgs[j].empty() && canDropEmptyOptional) {
522                         if (curMacroIdx == j)
523                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 1;
524                         continue;
525                 }
526
527                 // Otherwise we don't drop an empty optional, put it back normally
528                 MathData optarg;
529                 asArray(from_ascii("[]"), optarg);
530                 MathData & arg = detachedArgs[j];
531
532                 // look for "]", i.e. put a brace around?
533                 InsetMathBrace * brace = 0;
534                 for (size_t q = 0; q < arg.size(); ++q) {
535                         if (arg[q]->getChar() == ']') {
536                                 // put brace
537                                 brace = new InsetMathBrace(buffer_);
538                                 break;
539                         }
540                 }
541
542                 // put arg between []
543                 if (brace) {
544                         brace->cell(0) = arg;
545                         optarg.insert(1, MathAtom(brace));
546                 } else
547                         optarg.insert(1, arg);
548
549                 // insert it into the array
550                 insert(p, optarg);
551                 p += optarg.size();
552
553                 // cursor in macro?
554                 if (curMacroSlice == -1)
555                         continue;
556
557                 // cursor in optional argument of macro?
558                 if (curMacroIdx == j) {
559                         if (brace) {
560                                 cur->append(0, curMacroPos);
561                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 2;
562                         } else
563                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
564                         cur->append(argSlices);
565                 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
566                         // cursor right of macro
567                         (*cur)[curMacroSlice - 1].pos() += optarg.size();
568         }
569
570         // put them back into the MathData
571         for (; j < detachedArgs.size(); ++j, ++p) {
572                 MathData const & arg = detachedArgs[j];
573                 if (arg.size() == 1
574                     && !arg[0]->asScriptInset()
575                     && !(arg[0]->asMacro() && arg[0]->asMacro()->arity() > 0))
576                         insert(p, arg[0]);
577                 else
578                         insert(p, MathAtom(new InsetMathBrace(arg)));
579
580                 // cursor in macro?
581                 if (curMacroSlice == -1)
582                         continue;
583
584                 // cursor in j-th argument of macro?
585                 if (curMacroIdx == j) {
586                         if (operator[](p).nucleus()->asBraceInset()) {
587                                 (*cur)[curMacroSlice - 1].pos() = p;
588                                 cur->append(0, curMacroPos);
589                                 cur->append(argSlices);
590                         } else {
591                                 (*cur)[curMacroSlice - 1].pos() = p; // + macroPos;
592                                 cur->append(argSlices);
593                         }
594                 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
595                         ++(*cur)[curMacroSlice - 1].pos();
596         }
597
598         if (cur)
599                 cur->updateInsets(&cur->bottom().inset());
600 }
601
602
603 void MathData::attachMacroParameters(Cursor * cur,
604         const size_type macroPos, const size_type macroNumArgs,
605         const int macroOptionals, const bool fromInitToNormalMode,
606         const bool interactiveInit, const size_t appetite)
607 {
608         MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
609
610         // start at atom behind the macro again, maybe with some new arguments
611         // from the detach phase above, to add them back into the macro inset
612         size_t p = macroPos + 1;
613         vector<MathData> detachedArgs;
614         MathAtom scriptToPutAround;
615
616         // find cursor slice again of this MathData
617         int thisSlice = -1;
618         if (cur)
619                 thisSlice = cur->find(*this);
620         int thisPos = -1;
621         if (thisSlice != -1)
622                 thisPos = (*cur)[thisSlice].pos();
623
624         // find arguments behind the macro
625         if (!interactiveInit) {
626                 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
627                         scriptToPutAround, macroPos, thisPos, thisSlice);
628         }
629         collectParameters(cur, macroNumArgs, detachedArgs, p,
630                 scriptToPutAround, macroPos, thisPos, thisSlice, appetite);
631
632         // attach arguments back to macro inset
633         macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
634
635         // found tail script? E.g. \foo{a}b^x
636         if (scriptToPutAround.nucleus()) {
637                 InsetMathScript * scriptInset =
638                         scriptToPutAround.nucleus()->asScriptInset();
639                 // In the math parser we remove empty braces in the base
640                 // of a script inset, but we have to restore them here.
641                 if (scriptInset->nuc().empty()) {
642                         MathData ar;
643                         scriptInset->nuc().push_back(
644                                         MathAtom(new InsetMathBrace(ar)));
645                 }
646                 // put macro into a script inset
647                 scriptInset->nuc()[0] = operator[](macroPos);
648                 operator[](macroPos) = scriptToPutAround;
649
650                 // go into the script inset nucleus
651                 if (cur && thisPos == int(macroPos))
652                         cur->append(0, 0);
653
654                 // get pointer to "deep" copied macro inset
655                 scriptInset = operator[](macroPos).nucleus()->asScriptInset();
656                 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();
657         }
658
659         // remove them from the MathData
660         erase(macroPos + 1, p);
661
662         // cursor outside this MathData?
663         if (thisSlice == -1)
664                 return;
665
666         // fix cursor if right of p
667         if (thisPos >= int(p))
668                 (*cur)[thisSlice].pos() -= p - (macroPos + 1);
669
670         // was the macro inset just inserted interactively and was now folded
671         // and the cursor is just behind?
672         if ((*cur)[thisSlice].pos() == int(macroPos + 1)
673             && interactiveInit
674             && fromInitToNormalMode
675             && macroInset->arity() > 0
676             && thisSlice + 1 == int(cur->depth())) {
677                 // then enter it if the cursor was just behind
678                 (*cur)[thisSlice].pos() = macroPos;
679                 cur->push_back(CursorSlice(*macroInset));
680                 macroInset->idxFirst(*cur);
681         }
682 }
683
684
685 void MathData::collectOptionalParameters(Cursor * cur,
686         const size_type numOptionalParams, vector<MathData> & params,
687         size_t & pos, MathAtom & scriptToPutAround,
688         const pos_type macroPos, const int thisPos, const int thisSlice)
689 {
690         Buffer * buf = cur ? cur->buffer() : 0;
691         // insert optional arguments?
692         while (params.size() < numOptionalParams
693                && pos < size()
694                && !scriptToPutAround.nucleus()) {
695                 // is a [] block following which could be an optional parameter?
696                 if (operator[](pos)->getChar() != '[')
697                         break;
698
699                 // found possible optional argument, look for pairing "]"
700                 int count = 1;
701                 size_t right = pos + 1;
702                 for (; right < size(); ++right) {
703                         MathAtom & cell = operator[](right);
704
705                         if (cell->getChar() == '[')
706                                 ++count;
707                         else if (cell->getChar() == ']' && --count == 0)
708                                 // found right end
709                                 break;
710
711                         // maybe "]" with a script around?
712                         InsetMathScript * script = cell.nucleus()->asScriptInset();
713                         if (!script)
714                                 continue;
715                         if (script->nuc().size() != 1)
716                                 continue;
717                         if (script->nuc()[0]->getChar() == ']') {
718                                 // script will be put around the macro later
719                                 scriptToPutAround = cell;
720                                 break;
721                         }
722                 }
723
724                 // found?
725                 if (right >= size()) {
726                         // no ] found, so it's not an optional argument
727                         break;
728                 }
729
730                 // add everything between [ and ] as optional argument
731                 MathData optarg(buf, begin() + pos + 1, begin() + right);
732
733                 // a brace?
734                 bool brace = false;
735                 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
736                         brace = true;
737                         params.push_back(optarg[0]->asBraceInset()->cell(0));
738                 } else
739                         params.push_back(optarg);
740
741                 // place cursor in optional argument of macro
742                 // Note: The two expressions on the first line are equivalent
743                 // (see caller), but making this explicit pleases coverity.
744                 if (cur && thisSlice != -1
745                     && thisPos >= int(pos) && thisPos <= int(right)) {
746                         int paramPos = max(0, thisPos - int(pos) - 1);
747                         vector<CursorSlice> x;
748                         cur->cutOff(thisSlice, x);
749                         (*cur)[thisSlice].pos() = macroPos;
750                         if (brace) {
751                                 paramPos = x[0].pos();
752                                 x.erase(x.begin());
753                         }
754                         cur->append(0, paramPos);
755                         cur->append(x);
756                 }
757                 pos = right + 1;
758         }
759
760         // fill up empty optional parameters
761         while (params.size() < numOptionalParams)
762                 params.push_back(MathData());
763 }
764
765
766 void MathData::collectParameters(Cursor * cur,
767         const size_type numParams, vector<MathData> & params,
768         size_t & pos, MathAtom & scriptToPutAround,
769         const pos_type macroPos, const int thisPos, const int thisSlice,
770         const size_t appetite)
771 {
772         size_t startSize = params.size();
773
774         // insert normal arguments
775         while (params.size() < numParams
776                && params.size() - startSize < appetite
777                && pos < size()
778                && !scriptToPutAround.nucleus()) {
779                 MathAtom & cell = operator[](pos);
780
781                 // fix cursor
782                 vector<CursorSlice> argSlices;
783                 int argPos = 0;
784                 // Note: The two expressions on the first line are equivalent
785                 // (see caller), but making this explicit pleases coverity.
786                 if (cur && thisSlice != -1
787                         && thisPos == int(pos))
788                         cur->cutOff(thisSlice, argSlices);
789
790                 // which kind of parameter is it? In {}? With index x^n?
791                 InsetMathBrace const * brace = cell->asBraceInset();
792                 if (brace) {
793                         // found brace, convert into argument
794                         params.push_back(brace->cell(0));
795
796                         // cursor inside of the brace or just in front of?
797                         if (thisPos == int(pos) && !argSlices.empty()) {
798                                 argPos = argSlices[0].pos();
799                                 argSlices.erase(argSlices.begin());
800                         }
801                 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
802                         // last inset with scripts without braces
803                         // -> they belong to the macro, not the argument
804                         InsetMathScript * script = cell.nucleus()->asScriptInset();
805                         if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
806                                 // nucleus in brace? Unpack!
807                                 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
808                         else
809                                 params.push_back(script->nuc());
810
811                         // script will be put around below
812                         scriptToPutAround = cell;
813
814                         // this should only happen after loading, so make cursor handling simple
815                         if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
816                                 argSlices.clear();
817                                 if (cur)
818                                         cur->append(0, 0);
819                         }
820                 } else {
821                         // the simplest case: plain inset
822                         MathData array;
823                         array.insert(0, cell);
824                         params.push_back(array);
825                 }
826
827                 // put cursor in argument again
828                 if (thisSlice != - 1 && thisPos == int(pos)) {
829                         cur->append(params.size() - 1, argPos);
830                         cur->append(argSlices);
831                         (*cur)[thisSlice].pos() = macroPos;
832                 }
833
834                 ++pos;
835         }
836 }
837
838
839 int MathData::pos2x(BufferView const * bv, size_type pos) const
840 {
841         int x = 0;
842         size_type target = min(pos, size());
843         CoordCache::Insets const & coords = bv->coordCache().getInsets();
844         for (size_type i = 0; i < target; ++i) {
845                 const_iterator it = begin() + i;
846                 //lyxerr << "char: " << (*it)->getChar()
847                 //      << "width: " << (*it)->width() << endl;
848                 x += coords.dim((*it).nucleus()).wid;
849         }
850         return x;
851 }
852
853
854 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx) const
855 {
856         const_iterator it = begin();
857         int lastx = 0;
858         int currx = 0;
859         CoordCache::Insets const & coords = bv->coordCache().getInsets();
860         // find first position after targetx
861         for (; currx < targetx && it != end(); ++it) {
862                 lastx = currx;
863                 currx += coords.dim((*it).nucleus()).wid;
864         }
865
866         /**
867          * If we are not at the beginning of the array, go to the left
868          * of the inset if one of the following two condition holds:
869          * - the current inset is editable (so that the cursor tip is
870          *   deeper than us): in this case, we want all intermediate
871          *   cursor slices to be before insets;
872          * - the mouse is closer to the left side of the inset than to
873          *   the right one.
874          * See bug 1918 for details.
875          **/
876         if (it != begin() && currx >= targetx
877             && ((*prev(it, 1))->asNestInset()
878                 || abs(lastx - targetx) < abs(currx - targetx))) {
879                 --it;
880         }
881
882         return it - begin();
883 }
884
885
886 int MathData::dist(BufferView const & bv, int x, int y) const
887 {
888         return bv.coordCache().getArrays().squareDistance(this, x, y);
889 }
890
891
892 void MathData::setXY(BufferView & bv, int x, int y) const
893 {
894         //lyxerr << "setting position cache for MathData " << this << endl;
895         bv.coordCache().arrays().add(this, x, y);
896 }
897
898
899 Dimension const & MathData::dimension(BufferView const & bv) const
900 {
901         return bv.coordCache().getArrays().dim(this);
902 }
903
904
905 int MathData::xm(BufferView const & bv) const
906 {
907         Geometry const & g = bv.coordCache().getArrays().geometry(this);
908
909         return g.pos.x_ + g.dim.wid / 2;
910 }
911
912
913 int MathData::ym(BufferView const & bv) const
914 {
915         Geometry const & g = bv.coordCache().getArrays().geometry(this);
916
917         return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
918 }
919
920
921 int MathData::xo(BufferView const & bv) const
922 {
923         return bv.coordCache().getArrays().x(this);
924 }
925
926
927 int MathData::yo(BufferView const & bv) const
928 {
929         return bv.coordCache().getArrays().y(this);
930 }
931
932
933 MathClass MathData::mathClass() const
934 {
935         MathClass res = MC_UNKNOWN;
936         for (MathAtom const & at : *this) {
937                 MathClass mc = at->mathClass();
938                 if (res == MC_UNKNOWN)
939                         res = mc;
940                 else if (mc != MC_UNKNOWN && res != mc)
941                         return MC_ORD;
942         }
943         return res == MC_UNKNOWN ? MC_ORD : res;
944 }
945
946
947 ostream & operator<<(ostream & os, MathData const & ar)
948 {
949         odocstringstream oss;
950         NormalStream ns(oss);
951         ns << ar;
952         return os << to_utf8(oss.str());
953 }
954
955
956 odocstream & operator<<(odocstream & os, MathData const & ar)
957 {
958         NormalStream ns(os);
959         ns << ar;
960         return os;
961 }
962
963
964 } // namespace lyx