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