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