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