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