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