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