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