]> git.lyx.org Git - lyx.git/blob - src/mathed/MathData.cpp
Add support for stmaryrd.sty (bug #8434)
[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(Buffer * buf, const_iterator from, const_iterator to)
50         : base_type(from, to), buffer_(buf)
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, InternalUpdate);
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                 FontInfo font = mi.base.font;
284                 augmentFont(font, from_ascii("mathnormal"));
285                 dim.wid += mathed_string_width(font, completion);
286         }
287         // Cache the dimension.
288         mi.base.bv->coordCache().arrays().add(this, dim);
289 }
290
291
292 void MathData::draw(PainterInfo & pi, int x, int y) const
293 {
294         //lyxerr << "MathData::draw: x: " << x << " y: " << y << endl;
295         BufferView & bv  = *pi.base.bv;
296         setXY(bv, x, y);
297
298         Dimension const & dim = bv.coordCache().getArrays().dim(this);
299
300         if (empty()) {
301                 pi.pain.rectangle(x, y - dim.ascent(), dim.width(), dim.height(), Color_mathline);
302                 return;
303         }
304
305         // don't draw outside the workarea
306         if (y + dim.descent() <= 0
307                 || y - dim.ascent() >= bv.workHeight()
308                 || x + dim.width() <= 0
309                 || x >= bv. workWidth())
310                 return;
311
312         DocIterator const & inlineCompletionPos = bv.inlineCompletionPos();
313         MathData const * inlineCompletionData = 0;
314         if (inlineCompletionPos.inMathed())
315                 inlineCompletionData = &inlineCompletionPos.cell();
316
317         CoordCacheBase<Inset> & coords = pi.base.bv->coordCache().insets();
318         for (size_t i = 0, n = size(); i != n; ++i) {
319                 MathAtom const & at = operator[](i);
320                 coords.add(at.nucleus(), x, y);
321                 at->drawSelection(pi, x, y);
322                 at->draw(pi, x, y);
323                 x += coords.dim(at.nucleus()).wid;
324                 
325                 // Is the inline completion here?
326                 if (inlineCompletionData != this
327                     || size_t(inlineCompletionPos.pos()) != i + 1)
328                         continue;
329                 docstring const & completion = bv.inlineCompletion();
330                 if (completion.length() == 0)
331                         continue;
332                 FontInfo f = pi.base.font;
333                 augmentFont(f, from_ascii("mathnormal"));
334                 
335                 // draw the unique and the non-unique completion part
336                 // Note: this is not time-critical as it is
337                 // only done once per screen.
338                 size_t uniqueTo = bv.inlineCompletionUniqueChars();
339                 docstring s1 = completion.substr(0, uniqueTo);
340                 docstring s2 = completion.substr(uniqueTo);
341                 
342                 if (!s1.empty()) {
343                         f.setColor(Color_inlinecompletion);
344                         pi.pain.text(x, y, s1, f);
345                         x += mathed_string_width(f, s1);
346                 }
347                 
348                 if (!s2.empty()) {
349                         f.setColor(Color_nonunique_inlinecompletion);
350                         pi.pain.text(x, y, s2, f);
351                         x += mathed_string_width(f, s2);
352                 }
353         }
354 }
355
356
357 void MathData::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
358 {
359         dim.clear();
360         Dimension d;
361         for (const_iterator it = begin(); it != end(); ++it) {
362                 (*it)->metricsT(mi, d);
363                 dim += d;
364         }
365 }
366
367
368 void MathData::drawT(TextPainter & pain, int x, int y) const
369 {
370         //lyxerr << "x: " << x << " y: " << y << ' ' << pain.workAreaHeight() << endl;
371
372         // FIXME: Abdel 16/10/2006
373         // This drawT() method is never used, this is dead code.
374
375         for (const_iterator it = begin(), et = end(); it != et; ++it) {
376                 (*it)->drawT(pain, x, y);
377                 //x += (*it)->width_;
378                 x += 2;
379         }
380 }
381
382
383 void MathData::updateBuffer(ParIterator const & it, UpdateType utype)
384 {
385         // pass down
386         for (size_t i = 0, n = size(); i != n; ++i) {
387                 MathAtom & at = operator[](i);
388                 at.nucleus()->updateBuffer(it, utype);
389         }
390 }
391
392
393 void MathData::updateMacros(Cursor * cur, MacroContext const & mc,
394                 UpdateType utype)
395 {
396         // If we are editing a macro, we cannot update it immediately,
397         // otherwise wrong undo steps will be recorded (bug 6208).
398         InsetMath const * inmath = cur ? cur->inset().asInsetMath() : 0;
399         MathMacro const * inmacro = inmath ? inmath->asMacro() : 0;
400         docstring const edited_name = inmacro ? inmacro->name() : docstring();
401
402         // go over the array and look for macros
403         for (size_t i = 0; i < size(); ++i) {
404                 MathMacro * macroInset = operator[](i).nucleus()->asMacro();
405                 if (!macroInset || macroInset->name_.empty()
406                                 || macroInset->name_[0] == '^'
407                                 || macroInset->name_[0] == '_'
408                                 || (macroInset->name() == edited_name
409                                     && macroInset->displayMode() ==
410                                                 MathMacro::DISPLAY_UNFOLDED))
411                         continue;
412
413                 // get macro
414                 macroInset->updateMacro(mc);
415                 size_t macroNumArgs = 0;
416                 size_t macroOptionals = 0;
417                 MacroData const * macro = macroInset->macro();
418                 if (macro) {
419                         macroNumArgs = macro->numargs();
420                         macroOptionals = macro->optionals();
421                 }
422
423                 // store old and compute new display mode
424                 MathMacro::DisplayMode newDisplayMode;
425                 MathMacro::DisplayMode oldDisplayMode = macroInset->displayMode();
426                 newDisplayMode = macroInset->computeDisplayMode();
427
428                 // arity changed or other reason to detach?
429                 if (oldDisplayMode == MathMacro::DISPLAY_NORMAL
430                     && (macroInset->arity() != macroNumArgs
431                         || macroInset->optionals() != macroOptionals
432                         || newDisplayMode == MathMacro::DISPLAY_UNFOLDED)) {
433
434                         detachMacroParameters(cur, i);
435                         // FIXME: proper anchor handling, this removes the selection
436                         if (cur)
437                                 cur->clearSelection();
438                 }
439
440                 // the macro could have been copied while resizing this
441                 macroInset = operator[](i).nucleus()->asMacro();
442
443                 // Cursor in \label?
444                 if (newDisplayMode != MathMacro::DISPLAY_UNFOLDED 
445                     && oldDisplayMode == MathMacro::DISPLAY_UNFOLDED) {
446                         // put cursor in front of macro
447                         if (cur) {
448                                 int macroSlice = cur->find(macroInset);
449                                 if (macroSlice != -1)
450                                         cur->cutOff(macroSlice - 1);
451                         }
452                 }
453
454                 // update the display mode
455                 size_t appetite = macroInset->appetite();
456                 macroInset->setDisplayMode(newDisplayMode);
457
458                 // arity changed?
459                 if (newDisplayMode == MathMacro::DISPLAY_NORMAL 
460                     && (macroInset->arity() != macroNumArgs
461                         || macroInset->optionals() != macroOptionals)) {
462                         // is it a virgin macro which was never attached to parameters?
463                         bool fromInitToNormalMode
464                         = (oldDisplayMode == MathMacro::DISPLAY_INIT 
465                            || oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT)
466                           && newDisplayMode == MathMacro::DISPLAY_NORMAL;
467                         
468                         // if the macro was entered interactively (i.e. not by paste or during
469                         // loading), it should not be greedy, but the cursor should
470                         // automatically jump into the macro when behind
471                         bool interactive = (oldDisplayMode == MathMacro::DISPLAY_INTERACTIVE_INIT);
472                         
473                         // attach parameters
474                         attachMacroParameters(cur, i, macroNumArgs, macroOptionals,
475                                 fromInitToNormalMode, interactive, appetite);
476                         
477                         if (cur) {
478                                 // FIXME: proper anchor handling, this removes the selection
479                                 cur->updateInsets(&cur->bottom().inset());
480                                 cur->clearSelection();  
481                         }
482                 }
483
484                 // Give macro the chance to adapt to new situation.
485                 // The macroInset could be invalid now because it was put into a script 
486                 // inset and therefore "deep" copied. So get it again from the MathData.
487                 InsetMath * inset = operator[](i).nucleus();
488                 if (inset->asScriptInset())
489                         inset = inset->asScriptInset()->nuc()[0].nucleus();
490                 LASSERT(inset->asMacro(), /**/);
491                 inset->asMacro()->updateRepresentation(cur, mc, utype);
492         }
493 }
494
495
496 void MathData::detachMacroParameters(DocIterator * cur, const size_type macroPos)
497 {
498         MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
499         
500         // detach all arguments
501         vector<MathData> detachedArgs;
502         if (macroPos + 1 == size())
503                 // strip arguments if we are at the MathData end
504                 macroInset->detachArguments(detachedArgs, true);
505         else
506                 macroInset->detachArguments(detachedArgs, false);
507         
508         // find cursor slice
509         int curMacroSlice = -1;
510         if (cur)
511                 curMacroSlice = cur->find(macroInset);
512         idx_type curMacroIdx = -1;
513         pos_type curMacroPos = -1;
514         vector<CursorSlice> argSlices;
515         if (curMacroSlice != -1) {
516                 curMacroPos = (*cur)[curMacroSlice].pos();
517                 curMacroIdx = (*cur)[curMacroSlice].idx();
518                 cur->cutOff(curMacroSlice, argSlices);
519                 cur->pop_back();
520         }
521         
522         // only [] after the last non-empty argument can be dropped later 
523         size_t lastNonEmptyOptional = 0;
524         for (size_t l = 0; l < detachedArgs.size() && l < macroInset->optionals(); ++l) {
525                 if (!detachedArgs[l].empty())
526                         lastNonEmptyOptional = l;
527         }
528         
529         // optional arguments to be put back?
530         pos_type p = macroPos + 1;
531         size_t j = 0;
532         for (; j < detachedArgs.size() && j < macroInset->optionals(); ++j) {
533                 // another non-empty parameter follows?
534                 bool canDropEmptyOptional = j >= lastNonEmptyOptional;
535                 
536                 // then we can drop empty optional parameters
537                 if (detachedArgs[j].empty() && canDropEmptyOptional) {
538                         if (curMacroIdx == j)
539                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 1;
540                         continue;
541                 }
542                 
543                 // Otherwise we don't drop an empty optional, put it back normally
544                 MathData optarg;
545                 asArray(from_ascii("[]"), optarg);
546                 MathData & arg = detachedArgs[j];
547                 
548                 // look for "]", i.e. put a brace around?
549                 InsetMathBrace * brace = 0;
550                 for (size_t q = 0; q < arg.size(); ++q) {
551                         if (arg[q]->getChar() == ']') {
552                                 // put brace
553                                 brace = new InsetMathBrace(buffer_);
554                                 break;
555                         }
556                 }
557                 
558                 // put arg between []
559                 if (brace) {
560                         brace->cell(0) = arg;
561                         optarg.insert(1, MathAtom(brace));
562                 } else
563                         optarg.insert(1, arg);
564                 
565                 // insert it into the array
566                 insert(p, optarg);
567                 p += optarg.size();
568                 
569                 // cursor in macro?
570                 if (curMacroSlice == -1)
571                         continue;
572                 
573                 // cursor in optional argument of macro?
574                 if (curMacroIdx == j) {
575                         if (brace) {
576                                 cur->append(0, curMacroPos);
577                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 2;
578                         } else
579                                 (*cur)[curMacroSlice - 1].pos() = macroPos + 2 + curMacroPos;
580                         cur->append(argSlices);
581                 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
582                         // cursor right of macro
583                         (*cur)[curMacroSlice - 1].pos() += optarg.size();
584         }
585         
586         // put them back into the MathData
587         for (; j < detachedArgs.size(); ++j, ++p) {
588                 MathData const & arg = detachedArgs[j];
589                 if (arg.size() == 1 
590                     && !arg[0]->asScriptInset()
591                     && !(arg[0]->asMacro() && arg[0]->asMacro()->arity() > 0))
592                         insert(p, arg[0]);
593                 else
594                         insert(p, MathAtom(new InsetMathBrace(arg)));
595                 
596                 // cursor in macro?
597                 if (curMacroSlice == -1)
598                         continue;
599                 
600                 // cursor in j-th argument of macro?
601                 if (curMacroIdx == j) {
602                         if (operator[](p).nucleus()->asBraceInset()) {
603                                 (*cur)[curMacroSlice - 1].pos() = p;
604                                 cur->append(0, curMacroPos);
605                                 cur->append(argSlices);
606                         } else {
607                                 (*cur)[curMacroSlice - 1].pos() = p; // + macroPos;
608                                 cur->append(argSlices);
609                         }
610                 } else if ((*cur)[curMacroSlice - 1].pos() >= int(p))
611                         ++(*cur)[curMacroSlice - 1].pos();
612         }
613         
614         if (cur)
615                 cur->updateInsets(&cur->bottom().inset());
616 }
617
618
619 void MathData::attachMacroParameters(Cursor * cur, 
620         const size_type macroPos, const size_type macroNumArgs,
621         const int macroOptionals, const bool fromInitToNormalMode,
622         const bool interactiveInit, const size_t appetite)
623 {
624         MathMacro * macroInset = operator[](macroPos).nucleus()->asMacro();
625
626         // start at atom behind the macro again, maybe with some new arguments 
627         // from the detach phase above, to add them back into the macro inset
628         size_t p = macroPos + 1;
629         vector<MathData> detachedArgs;
630         MathAtom scriptToPutAround;
631
632         // find cursor slice again of this MathData
633         int thisSlice = -1;
634         if (cur)
635                 thisSlice = cur->find(*this);
636         int thisPos = -1;
637         if (thisSlice != -1)
638                 thisPos = (*cur)[thisSlice].pos();
639
640         // find arguments behind the macro
641         if (!interactiveInit) {
642                 collectOptionalParameters(cur, macroOptionals, detachedArgs, p,
643                         scriptToPutAround, macroPos, thisPos, thisSlice);
644         }
645         collectParameters(cur, macroNumArgs, detachedArgs, p,
646                 scriptToPutAround, macroPos, thisPos, thisSlice, appetite);
647
648         // attach arguments back to macro inset
649         macroInset->attachArguments(detachedArgs, macroNumArgs, macroOptionals);
650
651         // found tail script? E.g. \foo{a}b^x
652         if (scriptToPutAround.nucleus()) {
653                 InsetMathScript * scriptInset =
654                         scriptToPutAround.nucleus()->asScriptInset();
655                 // In the math parser we remove empty braces in the base
656                 // of a script inset, but we have to restore them here.
657                 if (scriptInset->nuc().empty()) {
658                         MathData ar;
659                         scriptInset->nuc().push_back(
660                                         MathAtom(new InsetMathBrace(ar)));
661                 }
662                 // put macro into a script inset
663                 scriptInset->nuc()[0] = operator[](macroPos);
664                 operator[](macroPos) = scriptToPutAround;
665
666                 // go into the script inset nucleus
667                 if (cur && thisPos == int(macroPos))
668                         cur->append(0, 0);
669
670                 // get pointer to "deep" copied macro inset
671                 scriptInset = operator[](macroPos).nucleus()->asScriptInset();
672                 macroInset = scriptInset->nuc()[0].nucleus()->asMacro();        
673         }
674
675         // remove them from the MathData
676         erase(begin() + macroPos + 1, begin() + p);
677
678         // cursor outside this MathData?
679         if (thisSlice == -1)
680                 return;
681
682         // fix cursor if right of p
683         if (thisPos >= int(p))
684                 (*cur)[thisSlice].pos() -= p - (macroPos + 1);
685
686         // was the macro inset just inserted interactively and was now folded
687         // and the cursor is just behind?
688         if ((*cur)[thisSlice].pos() == int(macroPos + 1)
689             && interactiveInit
690             && fromInitToNormalMode
691             && macroInset->arity() > 0
692             && thisSlice + 1 == int(cur->depth())) {
693                 // then enter it if the cursor was just behind
694                 (*cur)[thisSlice].pos() = macroPos;
695                 cur->push_back(CursorSlice(*macroInset));
696                 macroInset->idxFirst(*cur);
697         }
698 }
699
700
701 void MathData::collectOptionalParameters(Cursor * cur, 
702         const size_type numOptionalParams, vector<MathData> & params, 
703         size_t & pos, MathAtom & scriptToPutAround,
704         const pos_type macroPos, const int thisPos, const int thisSlice)
705 {
706         Buffer * buf = cur ? cur->buffer() : 0;
707         // insert optional arguments?
708         while (params.size() < numOptionalParams 
709                && pos < size()
710                && !scriptToPutAround.nucleus()) {
711                 // is a [] block following which could be an optional parameter?
712                 if (operator[](pos)->getChar() != '[')
713                         break;
714                 
715                 // found possible optional argument, look for "]"
716                 size_t right = pos + 1;
717                 for (; right < size(); ++right) {
718                         MathAtom & cell = operator[](right);
719
720                         if (cell->getChar() == ']')
721                                 // found right end
722                                 break;
723                         
724                         // maybe "]" with a script around?
725                         InsetMathScript * script = cell.nucleus()->asScriptInset();
726                         if (!script)
727                                 continue;
728                         if (script->nuc().size() != 1)
729                                 continue;
730                         if (script->nuc()[0]->getChar() == ']') {
731                                 // script will be put around the macro later
732                                 scriptToPutAround = cell;
733                                 break;
734                         }
735                 }
736                 
737                 // found?
738                 if (right >= size()) {
739                         // no ] found, so it's not an optional argument
740                         break;
741                 }
742                 
743                 // add everything between [ and ] as optional argument
744                 MathData optarg(buf, begin() + pos + 1, begin() + right);
745                 
746                 // a brace?
747                 bool brace = false;
748                 if (optarg.size() == 1 && optarg[0]->asBraceInset()) {
749                         brace = true;
750                         params.push_back(optarg[0]->asBraceInset()->cell(0));
751                 } else
752                         params.push_back(optarg);
753                 
754                 // place cursor in optional argument of macro
755                 if (thisSlice != -1
756                     && thisPos >= int(pos) && thisPos <= int(right)) {
757                         int paramPos = max(0, thisPos - int(pos) - 1);
758                         vector<CursorSlice> x;
759                         cur->cutOff(thisSlice, x);
760                         (*cur)[thisSlice].pos() = macroPos;
761                         if (brace) {
762                                 paramPos = x[0].pos();
763                                 x.erase(x.begin());
764                         }
765                         cur->append(0, paramPos);
766                         cur->append(x);
767                 }
768                 pos = right + 1;
769         }
770
771         // fill up empty optional parameters
772         while (params.size() < numOptionalParams)
773                 params.push_back(MathData());   
774 }
775
776
777 void MathData::collectParameters(Cursor * cur, 
778         const size_type numParams, vector<MathData> & params, 
779         size_t & pos, MathAtom & scriptToPutAround,
780         const pos_type macroPos, const int thisPos, const int thisSlice,
781         const size_t appetite) 
782 {
783         size_t startSize = params.size();
784         
785         // insert normal arguments
786         while (params.size() < numParams
787                && params.size() - startSize < appetite
788                && pos < size()
789                && !scriptToPutAround.nucleus()) {
790                 MathAtom & cell = operator[](pos);
791                 
792                 // fix cursor
793                 vector<CursorSlice> argSlices;
794                 int argPos = 0;
795                 if (thisSlice != -1 && thisPos == int(pos))
796                         cur->cutOff(thisSlice, argSlices);              
797                 
798                 // which kind of parameter is it? In {}? With index x^n?
799                 InsetMathBrace const * brace = cell->asBraceInset();
800                 if (brace) {
801                         // found brace, convert into argument
802                         params.push_back(brace->cell(0));
803                         
804                         // cursor inside of the brace or just in front of?
805                         if (thisPos == int(pos) && !argSlices.empty()) {
806                                 argPos = argSlices[0].pos();
807                                 argSlices.erase(argSlices.begin());
808                         }
809                 } else if (cell->asScriptInset() && params.size() + 1 == numParams) {
810                         // last inset with scripts without braces
811                         // -> they belong to the macro, not the argument
812                         InsetMathScript * script = cell.nucleus()->asScriptInset();
813                         if (script->nuc().size() == 1 && script->nuc()[0]->asBraceInset())
814                                 // nucleus in brace? Unpack!
815                                 params.push_back(script->nuc()[0]->asBraceInset()->cell(0));
816                         else
817                                 params.push_back(script->nuc());
818                         
819                         // script will be put around below
820                         scriptToPutAround = cell;
821                         
822                         // this should only happen after loading, so make cursor handling simple
823                         if (thisPos >= int(macroPos) && thisPos <= int(macroPos + numParams)) {
824                                 argSlices.clear();
825                                 if (cur)
826                                         cur->append(0, 0);
827                         }
828                 } else {
829                         // the simplest case: plain inset
830                         MathData array;
831                         array.insert(0, cell);
832                         params.push_back(array);
833                 }
834                 
835                 // put cursor in argument again
836                 if (thisSlice != - 1 && thisPos == int(pos)) {
837                         cur->append(params.size() - 1, argPos);
838                         cur->append(argSlices);
839                         (*cur)[thisSlice].pos() = macroPos;
840                 }
841                 
842                 ++pos;
843         }       
844 }
845
846
847 int MathData::pos2x(BufferView const * bv, size_type pos) const
848 {
849         return pos2x(bv, pos, 0);
850 }
851
852
853 int MathData::pos2x(BufferView const * bv, size_type pos, int glue) const
854 {
855         int x = 0;
856         size_type target = min(pos, size());
857         CoordCacheBase<Inset> const & coords = bv->coordCache().getInsets();
858         for (size_type i = 0; i < target; ++i) {
859                 const_iterator it = begin() + i;
860                 if ((*it)->getChar() == ' ')
861                         x += glue;
862                 //lyxerr << "char: " << (*it)->getChar()
863                 //      << "width: " << (*it)->width() << endl;
864                 x += coords.dim((*it).nucleus()).wid;
865         }
866         return x;
867 }
868
869
870 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx) const
871 {
872         return x2pos(bv, targetx, 0);
873 }
874
875
876 MathData::size_type MathData::x2pos(BufferView const * bv, int targetx, int glue) const
877 {
878         const_iterator it = begin();
879         int lastx = 0;
880         int currx = 0;
881         CoordCacheBase<Inset> const & coords = bv->coordCache().getInsets();
882         // find first position after targetx
883         for (; currx < targetx && it < end(); ++it) {
884                 lastx = currx;
885                 if ((*it)->getChar() == ' ')
886                         currx += glue;
887                 currx += coords.dim((*it).nucleus()).wid;
888         }
889
890         /**
891          * If we are not at the beginning of the array, go to the left
892          * of the inset if one of the following two condition holds:
893          * - the current inset is editable (so that the cursor tip is
894          *   deeper than us): in this case, we want all intermediate
895          *   cursor slices to be before insets;
896          * - the mouse is closer to the left side of the inset than to
897          *   the right one.
898          * See bug 1918 for details.
899          **/
900         if (it != begin() && currx >= targetx
901             && ((*boost::prior(it))->asNestInset()
902                 || abs(lastx - targetx) < abs(currx - targetx))) {
903                 --it;
904         }
905
906         return it - begin();
907 }
908
909
910 int MathData::dist(BufferView const & bv, int x, int y) const
911 {
912         return bv.coordCache().getArrays().squareDistance(this, x, y);
913 }
914
915
916 void MathData::setXY(BufferView & bv, int x, int y) const
917 {
918         //lyxerr << "setting position cache for MathData " << this << endl;
919         bv.coordCache().arrays().add(this, x, y);
920 }
921
922
923 Dimension const & MathData::dimension(BufferView const & bv) const
924 {
925         return bv.coordCache().getArrays().dim(this);
926 }
927
928
929 int MathData::xm(BufferView const & bv) const
930 {
931         Geometry const & g = bv.coordCache().getArrays().geometry(this);
932
933         return g.pos.x_ + g.dim.wid / 2;
934 }
935
936
937 int MathData::ym(BufferView const & bv) const
938 {
939         Geometry const & g = bv.coordCache().getArrays().geometry(this);
940
941         return g.pos.y_ + (g.dim.des - g.dim.asc) / 2;
942 }
943
944
945 int MathData::xo(BufferView const & bv) const
946 {
947         return bv.coordCache().getArrays().x(this);
948 }
949
950
951 int MathData::yo(BufferView const & bv) const
952 {
953         return bv.coordCache().getArrays().y(this);
954 }
955
956
957 ostream & operator<<(ostream & os, MathData const & ar)
958 {
959         odocstringstream oss;
960         NormalStream ns(oss);
961         ns << ar;
962         return os << to_utf8(oss.str());
963 }
964
965
966 odocstream & operator<<(odocstream & os, MathData const & ar)
967 {
968         NormalStream ns(os);
969         ns << ar;
970         return os;
971 }
972
973
974 } // namespace lyx