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