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