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