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