]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
Pass struct LatexRunParams around a bit...
[lyx.git] / src / insets / insettext.C
1 /**
2  * \file insettext.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "insettext.h"
14
15 #include "buffer.h"
16 #include "BufferView.h"
17 #include "CutAndPaste.h"
18 #include "debug.h"
19 #include "dimension.h"
20 #include "funcrequest.h"
21 #include "gettext.h"
22 #include "intl.h"
23 #include "LaTeXFeatures.h"
24 #include "LColor.h"
25 #include "Lsstream.h"
26 #include "lyxfont.h"
27 #include "lyxcursor.h"
28 #include "lyxfind.h"
29 #include "lyxlex.h"
30 #include "lyxrow.h"
31 #include "lyxrc.h"
32 #include "lyxtext.h"
33 #include "paragraph.h"
34 #include "ParagraphParameters.h"
35 #include "trans_mgr.h"
36 #include "undo_funcs.h"
37 #include "WordLangTuple.h"
38 #include "paragraph_funcs.h"
39 #include "sgml.h"
40 #include "rowpainter.h"
41 #include "insetnewline.h"
42 #include "Lsstream.h"
43
44 #include "frontends/Alert.h"
45 #include "frontends/Dialogs.h"
46 #include "frontends/font_metrics.h"
47 #include "frontends/LyXView.h"
48 #include "frontends/Painter.h"
49 #include "frontends/screen.h"
50
51 #include "support/textutils.h"
52 #include "support/LAssert.h"
53 #include "support/lstrings.h"
54 #include "support/lyxalgo.h" // lyx::count
55
56 #include <boost/bind.hpp>
57
58 #include <fstream>
59 #include <algorithm>
60 #include <cstdlib>
61 //#include <csignal>
62
63 using std::ostream;
64 using std::ifstream;
65 using std::endl;
66 using std::min;
67 using std::max;
68 using std::make_pair;
69 using std::vector;
70 using std::pair;
71 using std::for_each;
72
73 using lyx::pos_type;
74 using lyx::textclass_type;
75
76
77 // These functions should probably go into bufferview_funcs somehow (Jug)
78
79 void InsetText::saveLyXTextState(LyXText * t) const
80 {
81         // check if my paragraphs are still valid
82         ParagraphList::iterator it = paragraphs.begin();
83         ParagraphList::iterator end = paragraphs.end();
84         for (; it != end; ++it) {
85                 if (&*it == t->cursor.par())
86                         break;
87         }
88
89         if (it != end && t->cursor.pos() <= it->size()) {
90                 sstate.lpar = &*t->cursor.par();
91                 sstate.pos = t->cursor.pos();
92                 sstate.boundary = t->cursor.boundary();
93                 sstate.selstartpar = &*t->selection.start.par();
94                 sstate.selstartpos = t->selection.start.pos();
95                 sstate.selstartboundary = t->selection.start.boundary();
96                 sstate.selendpar = &*t->selection.end.par();
97                 sstate.selendpos = t->selection.end.pos();
98                 sstate.selendboundary = t->selection.end.boundary();
99                 sstate.selection = t->selection.set();
100                 sstate.mark_set = t->selection.mark();
101         } else {
102                 sstate.lpar = 0;
103         }
104 }
105
106
107 void InsetText::restoreLyXTextState(LyXText * t) const
108 {
109         if (!sstate.lpar)
110                 return;
111
112         t->selection.set(true);
113         /* at this point just to avoid the DEPM when setting the cursor */
114         t->selection.mark(sstate.mark_set);
115         if (sstate.selection) {
116                 t->setCursor(sstate.selstartpar, sstate.selstartpos,
117                              true, sstate.selstartboundary);
118                 t->selection.cursor = t->cursor;
119                 t->setCursor(sstate.selendpar, sstate.selendpos,
120                              true, sstate.selendboundary);
121                 t->setSelection();
122                 t->setCursor(sstate.lpar, sstate.pos);
123         } else {
124                 t->setCursor(sstate.lpar, sstate.pos, true, sstate.boundary);
125                 t->selection.cursor = t->cursor;
126                 t->selection.set(false);
127         }
128 }
129
130
131 InsetText::InnerCache::InnerCache(boost::shared_ptr<LyXText> t)
132 {
133         text = t;
134         remove = false;
135 }
136
137
138 InsetText::InsetText(BufferParams const & bp)
139         : UpdatableInset(), lt(0), in_update(false), do_resize(0),
140           do_reinit(false)
141 {
142         paragraphs.push_back(new Paragraph);
143         paragraphs.begin()->layout(bp.getLyXTextClass().defaultLayout());
144         if (bp.tracking_changes)
145                 paragraphs.begin()->trackChanges();
146         init();
147 }
148
149
150 InsetText::InsetText(InsetText const & in, bool same_id)
151         : UpdatableInset(in, same_id), lt(0), in_update(false), do_resize(0),
152           do_reinit(false)
153 {
154         init(&in, same_id);
155 }
156
157
158 InsetText & InsetText::operator=(InsetText const & it)
159 {
160         init(&it);
161         return * this;
162 }
163
164
165 void InsetText::init(InsetText const * ins, bool same_id)
166 {
167         if (ins) {
168                 setParagraphData(ins->paragraphs, same_id);
169                 autoBreakRows = ins->autoBreakRows;
170                 drawFrame_ = ins->drawFrame_;
171                 frame_color = ins->frame_color;
172                 if (same_id)
173                         id_ = ins->id_;
174         } else {
175                 for_each(paragraphs.begin(), paragraphs.end(),
176                          boost::bind(&Paragraph::setInsetOwner, _1, this));
177
178                 the_locking_inset = 0;
179                 drawFrame_ = NEVER;
180                 frame_color = LColor::insetframe;
181                 autoBreakRows = false;
182         }
183         top_y = 0;
184         old_max_width = 0;
185         no_selection = true;
186         need_update = FULL;
187         drawTextXOffset = 0;
188         drawTextYOffset = 0;
189         locked = false;
190         old_par = 0;
191         last_drawn_width = -1;
192         cached_bview = 0;
193         sstate.lpar = 0;
194         in_insetAllowed = false;
195 }
196
197
198 InsetText::~InsetText()
199 {
200         paragraphs.clear();
201 }
202
203
204 void InsetText::clear(bool just_mark_erased)
205 {
206         if (just_mark_erased) {
207                 ParagraphList::iterator it = paragraphs.begin();
208                 ParagraphList::iterator end = paragraphs.end();
209                 for (; it != end; ++it) {
210                         it->markErased();
211                 }
212                 need_update = FULL;
213                 return;
214         }
215
216         // This is a gross hack...
217         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
218
219         paragraphs.clear();
220         paragraphs.push_back(new Paragraph);
221         paragraphs.begin()->setInsetOwner(this);
222         paragraphs.begin()->layout(old_layout);
223
224         reinitLyXText();
225         need_update = INIT;
226 }
227
228
229 Inset * InsetText::clone(Buffer const &, bool same_id) const
230 {
231         return new InsetText(*this, same_id);
232 }
233
234
235 void InsetText::write(Buffer const * buf, ostream & os) const
236 {
237         os << "Text\n";
238         writeParagraphData(buf, os);
239 }
240
241
242 void InsetText::writeParagraphData(Buffer const * buf, ostream & os) const
243 {
244         ParagraphList::iterator it = paragraphs.begin();
245         ParagraphList::iterator end = paragraphs.end();
246         Paragraph::depth_type dth = 0;
247         for (; it != end; ++it) {
248                 it->write(buf, os, buf->params, dth);
249         }
250 }
251
252
253 void InsetText::read(Buffer const * buf, LyXLex & lex)
254 {
255         string token;
256         Paragraph::depth_type depth = 0;
257
258         clear(false);
259
260         if (buf->params.tracking_changes)
261                 paragraphs.begin()->trackChanges();
262
263         // delete the initial paragraph
264         paragraphs.clear();
265         ParagraphList::iterator pit = paragraphs.begin();
266
267         while (lex.isOK()) {
268                 lex.nextToken();
269                 token = lex.getString();
270                 if (token.empty())
271                         continue;
272                 if (token == "\\end_inset") {
273                         break;
274                 }
275
276                 if (token == "\\the_end") {
277                         lex.printError("\\the_end read in inset! Error in document!");
278                         return;
279                 }
280
281                 // FIXME: ugly.
282                 const_cast<Buffer*>(buf)->readParagraph(lex, token, paragraphs, pit, depth);
283         }
284
285         pit = paragraphs.begin();
286         ParagraphList::iterator const end = paragraphs.end();
287         for (; pit != end; ++pit)
288                 pit->setInsetOwner(this);
289
290         if (token != "\\end_inset") {
291                 lex.printError("Missing \\end_inset at this point. "
292                                            "Read: `$$Token'");
293         }
294         need_update = FULL;
295 }
296
297
298 void InsetText::dimension(BufferView * bv, LyXFont const &,
299         Dimension & dim) const
300 {
301         LyXText * text = getLyXText(bv);
302         dim.a = text->rows().begin()->ascent_of_text() + TEXT_TO_INSET_OFFSET;
303         dim.d = text->height - dim.a + TEXT_TO_INSET_OFFSET;
304         dim.w = max(textWidth(bv), int(text->width)) + 2 * TEXT_TO_INSET_OFFSET;
305         dim.w = max(dim.w, 10);
306         // cache it
307         dim_ = dim;
308 }
309
310
311 int InsetText::textWidth(BufferView * bv, bool fordraw) const
312 {
313         int w = autoBreakRows ? getMaxWidth(bv, this) : -1;
314
315         if (fordraw)
316                 return max(w - 2 * TEXT_TO_INSET_OFFSET,
317                            (int)getLyXText(bv)->width);
318
319         if (w < 0)
320     return -1;
321
322         return w - 2 * TEXT_TO_INSET_OFFSET;
323 }
324
325
326 void InsetText::draw(BufferView * bv, LyXFont const & f,
327                      int baseline, float & x) const
328 {
329         if (nodraw())
330                 return;
331
332         // update our idea of where we are. Clearly, we should
333         // not have to know this information.
334         if (top_x != int(x))
335                 top_x = int(x);
336
337         int const start_x = int(x);
338
339         Painter & pain = bv->painter();
340
341         // call this method so that dim_ has the right value
342         dimension(bv, f, dim_);
343
344         // repaint the background if needed
345         if (backgroundColor() != LColor::background)
346                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, baseline);
347
348         // no draw is necessary !!!
349         if ((drawFrame_ == LOCKED) && !locked && paragraphs.begin()->empty()) {
350                 top_baseline = baseline;
351                 x += width(bv, f);
352                 need_update = NONE;
353                 return;
354         }
355
356         if (!owner())
357                 x += static_cast<float>(scroll());
358
359         top_baseline = baseline;
360         top_y = baseline - dim_.a;
361
362         if (last_drawn_width != dim_.w) {
363                 need_update |= FULL;
364                 last_drawn_width = dim_.w;
365         }
366
367         if (the_locking_inset && (cpar(bv) == inset_par)
368                 && (cpos(bv) == inset_pos)) {
369                 inset_x = cix(bv) - int(x) + drawTextXOffset;
370                 inset_y = ciy(bv) + drawTextYOffset;
371         }
372
373         bool clear = false;
374         if (!lt) {
375                 lt = getLyXText(bv);
376                 clear = true;
377         }
378         x += TEXT_TO_INSET_OFFSET;
379
380         RowList::iterator rowit = lt->rows().begin();
381         RowList::iterator end = lt->rows().end();
382
383         int y_offset = baseline - rowit->ascent_of_text();
384         int ph = pain.paperHeight();
385         int first = 0;
386         int y = y_offset;
387         while ((rowit != end) && ((y + rowit->height()) <= 0)) {
388                 y += rowit->height();
389                 first += rowit->height();
390                 ++rowit;
391         }
392         if (y_offset < 0) {
393                 lt->top_y(-y_offset);
394                 first = y;
395                 y_offset = 0;
396         } else {
397                 lt->top_y(first);
398                 first = 0;
399         }
400
401         int yf = y_offset + first;
402         y = 0;
403
404         bv->hideCursor();
405
406         while ((rowit != end) && (yf < ph)) {
407                 RowPainter rp(*bv, *lt, rowit);
408                 rp.paint(y + y_offset + first, int(x), y + lt->top_y());
409                 y += rowit->height();
410                 yf += rowit->height();
411                 ++rowit;
412         }
413
414         lt->clearPaint();
415
416         if ((drawFrame_ == ALWAYS) || (drawFrame_ == LOCKED && locked)) {
417                 drawFrame(pain, int(start_x));
418         }
419
420         x += dim_.w - TEXT_TO_INSET_OFFSET;
421
422         if (need_update != INIT) {
423                 need_update = NONE;
424         }
425         if (clear)
426                 lt = 0;
427 }
428
429
430 void InsetText::drawFrame(Painter & pain, int x) const
431 {
432         static int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
433         frame_x = x + ttoD2;
434         frame_y = top_baseline - dim_.a + ttoD2;
435         frame_w = dim_.w - TEXT_TO_INSET_OFFSET;
436         frame_h = dim_.a + dim_.d - TEXT_TO_INSET_OFFSET;
437         pain.rectangle(frame_x, frame_y, frame_w, frame_h,
438                        frame_color);
439 }
440
441
442 void InsetText::update(BufferView * bv, bool reinit)
443 {
444         if (in_update) {
445                 if (reinit && owner()) {
446                         reinitLyXText();
447                         owner()->update(bv, true);
448                 }
449                 return;
450         }
451         in_update = true;
452
453         if (reinit || need_update == INIT) {
454                 need_update = FULL;
455                 // we should put this call where we set need_update to INIT!
456                 reinitLyXText();
457                 if (owner())
458                         owner()->update(bv, true);
459                 in_update = false;
460
461                 int nw = getMaxWidth(bv, this);
462                 if (nw > 0 && old_max_width != nw) {
463                         need_update |= INIT;
464                         old_max_width = nw;
465                 }
466                 return;
467         }
468
469         if (!autoBreakRows &&
470             boost::next(paragraphs.begin()) != paragraphs.end())
471                 collapseParagraphs(bv);
472
473         if (the_locking_inset) {
474                 inset_x = cix(bv) - top_x + drawTextXOffset;
475                 inset_y = ciy(bv) + drawTextYOffset;
476                 the_locking_inset->update(bv, reinit);
477         }
478
479         bool clear = false;
480         if (!lt) {
481                 lt = getLyXText(bv);
482                 clear = true;
483         }
484         if ((need_update & CURSOR_PAR) && (lt->refreshStatus() == LyXText::REFRESH_NONE) &&
485                 the_locking_inset) {
486                 lt->updateInset(the_locking_inset);
487         }
488
489         if (lt->refreshStatus() == LyXText::REFRESH_AREA)
490                 need_update |= FULL;
491         if (clear)
492                 lt = 0;
493
494         in_update = false;
495
496         int nw = getMaxWidth(bv, this);
497         if (nw > 0 && old_max_width != nw) {
498                 need_update |= INIT;
499                 old_max_width = nw;
500         }
501 }
502
503
504 void InsetText::setUpdateStatus(BufferView * bv, int what) const
505 {
506         // this does nothing dangerous so use only a localized buffer
507         LyXText * llt = getLyXText(bv);
508
509         need_update |= what;
510         // we have to redraw us full if our LyXText REFRESH_AREA or
511         // if we don't break row so that we only have one row to update!
512         if ((llt->refreshStatus() == LyXText::REFRESH_AREA) ||
513             (!autoBreakRows &&
514              (llt->refreshStatus() == LyXText::REFRESH_ROW)))
515         {
516                 need_update |= FULL;
517         } else if (llt->refreshStatus() == LyXText::REFRESH_ROW) {
518                 need_update |= CURSOR_PAR;
519         }
520
521         // this to not draw a selection when we redraw all of it!
522         if (need_update & CURSOR && !(need_update & SELECTION)) {
523                 if (llt->selection.set())
524                         need_update = FULL;
525                 llt->clearSelection();
526         }
527 }
528
529
530 void InsetText::updateLocal(BufferView * bv, int what, bool mark_dirty)
531 {
532 #if 0
533         if (!autoBreakRows &&
534             boost::next(paragraphs.begin()) != paragraphs.end())
535                 collapseParagraphs(bv);
536 #else
537         if (!autoBreakRows && paragraphs.size() > 1)
538                 collapseParagraphs(bv);
539 #endif
540
541         bool clear = false;
542         if (!lt) {
543                 lt = getLyXText(bv);
544                 clear = true;
545         }
546         lt->fullRebreak();
547         setUpdateStatus(bv, what);
548         bool flag = mark_dirty ||
549                 (((need_update != CURSOR) && (need_update != NONE)) ||
550                  (lt->refreshStatus() != LyXText::REFRESH_NONE) || lt->selection.set());
551         if (!lt->selection.set())
552                 lt->selection.cursor = lt->cursor;
553
554         bv->fitCursor();
555
556         if (flag) {
557                 lt->postPaint(0);
558                 bv->updateInset(const_cast<InsetText *>(this));
559         }
560
561         if (clear)
562                 lt = 0;
563
564         if (need_update == CURSOR)
565                 need_update = NONE;
566         bv->owner()->view_state_changed();
567         bv->owner()->updateMenubar();
568         bv->owner()->updateToolbar();
569         if (old_par != cpar(bv)) {
570                 bv->owner()->setLayout(cpar(bv)->layout()->name());
571                 old_par = cpar(bv);
572         }
573 }
574
575
576 string const InsetText::editMessage() const
577 {
578         return _("Opened Text Inset");
579 }
580
581
582 void InsetText::insetUnlock(BufferView * bv)
583 {
584         if (the_locking_inset) {
585                 the_locking_inset->insetUnlock(bv);
586                 the_locking_inset = 0;
587                 updateLocal(bv, CURSOR_PAR, false);
588         }
589         no_selection = true;
590         locked = false;
591         int code = NONE;
592         bool clear = false;
593
594         if (!lt) {
595                 lt = getLyXText(bv);
596                 clear = true;
597         }
598         if (lt->selection.set()) {
599                 lt->clearSelection();
600                 code = FULL;
601         } else if (owner()) {
602                 bv->owner()->setLayout(owner()->getLyXText(bv)
603                                        ->cursor.par()->layout()->name());
604         } else
605                 bv->owner()->setLayout(bv->text->cursor.par()->layout()->name());
606         // hack for deleteEmptyParMech
607         if (!paragraphs.begin()->empty()) {
608                 lt->setCursor(paragraphs.begin(), 0);
609         } else if (boost::next(paragraphs.begin()) != paragraphs.end()) {
610                 lt->setCursor(boost::next(paragraphs.begin()), 0);
611         }
612         if (clear)
613                 lt = 0;
614 #if 0
615         updateLocal(bv, code, false);
616 #else
617         if (code != NONE)
618                 setUpdateStatus(bv, code);
619 #endif
620 }
621
622
623 void InsetText::lockInset(BufferView * bv)
624 {
625         locked = true;
626         the_locking_inset = 0;
627         inset_pos = inset_x = inset_y = 0;
628         inset_boundary = false;
629         inset_par = 0;
630         old_par = 0;
631         bool clear = false;
632         if (!lt) {
633                 lt = getLyXText(bv);
634                 clear = true;
635         }
636         lt->setCursor(paragraphs.begin(), 0);
637         lt->clearSelection();
638         finishUndo();
639         // If the inset is empty set the language of the current font to the
640         // language to the surronding text (if different).
641         if (paragraphs.begin()->empty() &&
642             boost::next(paragraphs.begin()) == paragraphs.end() &&
643                 bv->getParentLanguage(this) != lt->current_font.language()) {
644                 LyXFont font(LyXFont::ALL_IGNORE);
645                 font.setLanguage(bv->getParentLanguage(this));
646                 setFont(bv, font, false);
647         }
648         if (clear)
649                 lt = 0;
650         int code = CURSOR;
651         if (drawFrame_ == LOCKED)
652                 code = CURSOR|DRAW_FRAME;
653         setUpdateStatus(bv, code);
654 }
655
656
657 void InsetText::lockInset(BufferView * bv, UpdatableInset * inset)
658 {
659         the_locking_inset = inset;
660         inset_x = cix(bv) - top_x + drawTextXOffset;
661         inset_y = ciy(bv) + drawTextYOffset;
662         inset_pos = cpos(bv);
663         inset_par = cpar(bv);
664         inset_boundary = cboundary(bv);
665         updateLocal(bv, CURSOR, false);
666 }
667
668
669 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
670 {
671         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
672                               << inset << "): ";
673         if (!inset)
674                 return false;
675         if (!the_locking_inset) {
676                 ParagraphList::iterator pit = paragraphs.begin();
677                 ParagraphList::iterator pend = paragraphs.end();
678
679                 int const id = inset->id();
680                 for (; pit != pend; ++pit) {
681                         InsetList::iterator it =
682                                 pit->insetlist.begin();
683                         InsetList::iterator const end =
684                                 pit->insetlist.end();
685                         for (; it != end; ++it) {
686                                 if (it.getInset() == inset) {
687                                         getLyXText(bv)->setCursorIntern(pit, it.getPos());
688                                         lockInset(bv, inset);
689                                         return true;
690                                 }
691                                 if (it.getInset()->getInsetFromID(id)) {
692                                         getLyXText(bv)->setCursorIntern(pit, it.getPos());
693                                         it.getInset()->localDispatch(FuncRequest(bv, LFUN_INSET_EDIT));
694                                         return the_locking_inset->lockInsetInInset(bv, inset);
695                                 }
696                         }
697                 }
698                 return false;
699         }
700         if (inset == cpar(bv)->getInset(cpos(bv))) {
701                 lyxerr[Debug::INSETS] << "OK" << endl;
702                 lockInset(bv, inset);
703                 return true;
704         } else if (the_locking_inset && (the_locking_inset == inset)) {
705                 if (cpar(bv) == inset_par && cpos(bv) == inset_pos) {
706                         lyxerr[Debug::INSETS] << "OK" << endl;
707                         inset_x = cix(bv) - top_x + drawTextXOffset;
708                         inset_y = ciy(bv) + drawTextYOffset;
709                 } else {
710                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
711                 }
712         } else if (the_locking_inset) {
713                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
714                 return the_locking_inset->lockInsetInInset(bv, inset);
715         }
716         lyxerr[Debug::INSETS] << "NOT OK" << endl;
717         return false;
718 }
719
720
721 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
722                                    bool lr)
723 {
724         if (!the_locking_inset)
725                 return false;
726         if (the_locking_inset == inset) {
727                 the_locking_inset->insetUnlock(bv);
728                 getLyXText(bv)->updateInset(inset);
729                 the_locking_inset = 0;
730                 if (lr)
731                         moveRightIntern(bv, true, false);
732                 old_par = 0; // force layout setting
733                 if (scroll())
734                         scroll(bv, 0.0F);
735                 else
736                         updateLocal(bv, CURSOR, false);
737                 return true;
738         }
739         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
740 }
741
742
743 bool InsetText::updateInsetInInset(BufferView * bv, Inset * inset)
744 {
745         if (!autoBreakRows &&
746             boost::next(paragraphs.begin()) != paragraphs.end())
747                 collapseParagraphs(bv);
748         if (inset == this)
749                 return true;
750         bool clear = false;
751         if (!lt) {
752                 lt = getLyXText(bv);
753                 clear = true;
754         }
755         if (inset->owner() != this) {
756                 int ustat = CURSOR_PAR;
757                 bool found = false;
758                 UpdatableInset * tl_inset = the_locking_inset;
759                 if (tl_inset)
760                         found = tl_inset->updateInsetInInset(bv, inset);
761                 if (!found) {
762                         tl_inset = static_cast<UpdatableInset *>(inset);
763                         while(tl_inset->owner() && tl_inset->owner() != this)
764                                 tl_inset = static_cast<UpdatableInset *>(tl_inset->owner());
765                         if (!tl_inset->owner())
766                                 return false;
767                         found = tl_inset->updateInsetInInset(bv, inset);
768                         ustat = FULL;
769                 }
770                 if (found)
771                         lt->updateInset(tl_inset);
772                 if (clear)
773                         lt = 0;
774                 if (found)
775                         setUpdateStatus(bv, ustat);
776                 return found;
777         }
778         bool found = lt->updateInset(inset);
779         if (clear)
780                 lt = 0;
781         if (found) {
782                 setUpdateStatus(bv, CURSOR_PAR);
783                 if (the_locking_inset &&
784                     cpar(bv) == inset_par && cpos(bv) == inset_pos)
785                 {
786                         inset_x = cix(bv) - top_x + drawTextXOffset;
787                         inset_y = ciy(bv) + drawTextYOffset;
788                 }
789         }
790         return found;
791 }
792
793
794 void InsetText::lfunMousePress(FuncRequest const & cmd)
795 {
796         no_selection = true;
797
798         // use this to check mouse motion for selection!
799         mouse_x = cmd.x;
800         mouse_y = cmd.y;
801
802         BufferView * bv = cmd.view();
803         FuncRequest cmd1 = cmd;
804         cmd1.x -= inset_x;
805         cmd1.y -= inset_y;
806         if (!locked)
807                 lockInset(bv);
808
809         int tmp_x = cmd.x - drawTextXOffset;
810         int tmp_y = cmd.y + dim_.a - getLyXText(bv)->top_y();
811         Inset * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
812
813         if (the_locking_inset) {
814                 if (the_locking_inset == inset) {
815                         the_locking_inset->localDispatch(cmd1);
816                         return;
817                 }
818                 // otherwise only unlock the_locking_inset
819                 the_locking_inset->insetUnlock(bv);
820                 the_locking_inset = 0;
821         }
822         if (!inset)
823                 no_selection = false;
824
825         if (bv->theLockingInset()) {
826                 if (isHighlyEditableInset(inset)) {
827                         // We just have to lock the inset before calling a
828                         // PressEvent on it!
829                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
830                         if (!bv->lockInset(uinset)) {
831                                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
832                         }
833                         inset->localDispatch(cmd1);
834                         if (the_locking_inset)
835                                 updateLocal(bv, CURSOR, false);
836                         return;
837                 }
838         }
839         if (!inset) {
840                 bool paste_internally = false;
841                 if (cmd.button() == mouse_button::button2 && getLyXText(bv)->selection.set()) {
842                         localDispatch(FuncRequest(bv, LFUN_COPY));
843                         paste_internally = true;
844                 }
845                 bool clear = false;
846                 if (!lt) {
847                         lt = getLyXText(bv);
848                         clear = true;
849                 }
850                 int old_top_y = lt->top_y();
851
852                 lt->setCursorFromCoordinates(cmd.x - drawTextXOffset,
853                                              cmd.y + dim_.a);
854                 // set the selection cursor!
855                 lt->selection.cursor = lt->cursor;
856                 lt->cursor.x_fix(lt->cursor.x());
857
858                 if (lt->selection.set()) {
859                         lt->clearSelection();
860                         updateLocal(bv, FULL, false);
861                 } else {
862                         lt->clearSelection();
863                         updateLocal(bv, CURSOR, false);
864                 }
865
866                 if (clear)
867                         lt = 0;
868
869                 bv->owner()->setLayout(cpar(bv)->layout()->name());
870
871                 // we moved the view we cannot do mouse selection in this case!
872                 if (getLyXText(bv)->top_y() != old_top_y)
873                         no_selection = true;
874                 old_par = cpar(bv);
875                 // Insert primary selection with middle mouse
876                 // if there is a local selection in the current buffer,
877                 // insert this
878                 if (cmd.button() == mouse_button::button2) {
879                         if (paste_internally)
880                                 localDispatch(FuncRequest(bv, LFUN_PASTE));
881                         else
882                                 localDispatch(FuncRequest(bv, LFUN_PASTESELECTION, "paragraph"));
883                 }
884         } else {
885                 getLyXText(bv)->clearSelection();
886         }
887 }
888
889
890 bool InsetText::lfunMouseRelease(FuncRequest const & cmd)
891 {
892         BufferView * bv = cmd.view();
893         FuncRequest cmd1 = cmd;
894         cmd1.x -= inset_x;
895         cmd1.y -= inset_y;
896
897         no_selection = true;
898         if (the_locking_inset)
899                 return the_locking_inset->localDispatch(cmd1);
900
901         int tmp_x = cmd.x - drawTextXOffset;
902         int tmp_y = cmd.y + dim_.a - getLyXText(bv)->top_y();
903         Inset * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
904         bool ret = false;
905         if (inset) {
906 // This code should probably be removed now. Simple insets
907 // (!highlyEditable) can actually take the localDispatch,
908 // and turn it into edit() if necessary. But we still
909 // need to deal properly with the whole relative vs.
910 // absolute mouse co-ords thing in a realiable, sensible way
911 #if 0
912                 if (isHighlyEditableInset(inset))
913                         ret = inset->localDispatch(cmd1);
914                 else {
915                         inset_x = cix(bv) - top_x + drawTextXOffset;
916                         inset_y = ciy(bv) + drawTextYOffset;
917                         cmd1.x = cmd.x - inset_x;
918                         cmd1.y = cmd.x - inset_y;
919                         inset->edit(bv, cmd1.x, cmd1.y, cmd.button());
920                         ret = true;
921                 }
922 #endif
923                 ret = inset->localDispatch(cmd1);
924                 updateLocal(bv, CURSOR_PAR, false);
925
926         }
927         return ret;
928 }
929
930
931 void InsetText::lfunMouseMotion(FuncRequest const & cmd)
932 {
933         FuncRequest cmd1 = cmd;
934         cmd1.x -= inset_x;
935         cmd1.y -= inset_y;
936
937         if (the_locking_inset) {
938                 the_locking_inset->localDispatch(cmd1);
939                 return;
940         }
941
942         if (no_selection || (mouse_x == cmd.x && mouse_y == cmd.y))
943                 return;
944
945         BufferView * bv = cmd.view();
946         bool clear = false;
947         if (!lt) {
948                 lt = getLyXText(bv);
949                 clear = true;
950         }
951         LyXCursor cur = lt->cursor;
952         lt->setCursorFromCoordinates
953                 (cmd.x - drawTextXOffset, cmd.y + dim_.a);
954         lt->cursor.x_fix(lt->cursor.x());
955         if (cur == lt->cursor) {
956                 if (clear)
957                         lt = 0;
958                 return;
959         }
960         lt->setSelection();
961         bool flag = (lt->toggle_cursor.par() != lt->toggle_end_cursor.par() ||
962                                  lt->toggle_cursor.pos() != lt->toggle_end_cursor.pos());
963         if (clear)
964                 lt = 0;
965         if (flag) {
966                 updateLocal(bv, SELECTION, false);
967         }
968 }
969
970
971 Inset::RESULT InsetText::localDispatch(FuncRequest const & cmd)
972 {
973         BufferView * bv = cmd.view();
974
975         if (cmd.action == LFUN_INSET_EDIT) {
976                 UpdatableInset::localDispatch(cmd);
977
978                 if (!bv->lockInset(this)) {
979                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
980                         return DISPATCHED;
981                 }
982
983                 locked = true;
984                 the_locking_inset = 0;
985                 inset_pos = inset_x = inset_y = 0;
986                 inset_boundary = false;
987                 inset_par = 0;
988                 old_par = 0;
989
990                 bool clear = false;
991                 if (!lt) {
992                         lt = getLyXText(bv);
993                         clear = true;
994                 }
995
996                 if (cmd.argument.size()) {
997                         if (cmd.argument == "left")
998                                 lt->setCursor(paragraphs.begin(), 0);
999                         else {
1000                                 ParagraphList::iterator it = paragraphs.begin();
1001                                 ParagraphList::iterator end = paragraphs.end();
1002                                 while (boost::next(it) != end)
1003                                         ++it;
1004                 //              int const pos = (p->size() ? p->size()-1 : p->size());
1005                                 lt->setCursor(it, it->size());
1006                         }
1007                 } else {
1008                         int tmp_y = (cmd.y < 0) ? 0 : cmd.y;
1009                         // we put here -1 and not button as now the button in the
1010                         // edit call should not be needed we will fix this in 1.3.x
1011                         // cycle hopefully (Jug 20020509)
1012                         // FIXME: GUII I've changed this to none: probably WRONG
1013                         if (!checkAndActivateInset(bv, cmd.x, tmp_y, mouse_button::none)) {
1014                                 lt->setCursorFromCoordinates(cmd.x - drawTextXOffset,
1015                                                                         cmd.y + dim_.a);
1016                                 lt->cursor.x_fix(lt->cursor.x());
1017                         }
1018                 }
1019
1020                 lt->clearSelection();
1021                 finishUndo();
1022
1023                 // If the inset is empty set the language of the current font to the
1024                 // language to the surronding text (if different).
1025                 if (paragraphs.begin()->empty() &&
1026                                 boost::next(paragraphs.begin()) == paragraphs.end()&&
1027                         bv->getParentLanguage(this) != lt->current_font.language())
1028                 {
1029                         LyXFont font(LyXFont::ALL_IGNORE);
1030                         font.setLanguage(bv->getParentLanguage(this));
1031                         setFont(bv, font, false);
1032                 }
1033
1034                 if (clear)
1035                         lt = 0;
1036                 int code = CURSOR;
1037                 if (drawFrame_ == LOCKED)
1038                         code = CURSOR | DRAW_FRAME;
1039
1040                 updateLocal(bv, code, false);
1041                 // Tell the paragraph dialog that we've entered an insettext.
1042                 bv->dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
1043                 return DISPATCHED;
1044         }
1045
1046
1047         switch (cmd.action) {
1048                 case LFUN_MOUSE_PRESS:
1049                         lfunMousePress(cmd);
1050                         return DISPATCHED;
1051                 case LFUN_MOUSE_MOTION:
1052                         lfunMouseMotion(cmd);
1053                         return DISPATCHED;
1054                 case LFUN_MOUSE_RELEASE:
1055                         return lfunMouseRelease(cmd) ? DISPATCHED : UNDISPATCHED;
1056                 default:
1057                         break;
1058         }
1059
1060         bool was_empty = (paragraphs.begin()->empty() &&
1061                           boost::next(paragraphs.begin()) == paragraphs.end());
1062         no_selection = false;
1063         RESULT result = UpdatableInset::localDispatch(cmd);
1064         if (result != UNDISPATCHED)
1065                 return DISPATCHED;
1066
1067         result = DISPATCHED;
1068         if (cmd.action < 0 && cmd.argument.empty())
1069                 return FINISHED;
1070
1071         if (the_locking_inset) {
1072                 result = the_locking_inset->localDispatch(cmd);
1073                 if (result == DISPATCHED_NOUPDATE)
1074                         return result;
1075                 else if (result == DISPATCHED) {
1076                         updateLocal(bv, CURSOR_PAR, false);
1077                         return result;
1078                 } else if (result >= FINISHED) {
1079                         switch (result) {
1080                         case FINISHED_RIGHT:
1081                                 moveRightIntern(bv, false, false);
1082                                 result = DISPATCHED;
1083                                 break;
1084                         case FINISHED_UP:
1085                                 if ((result = moveUp(bv)) >= FINISHED) {
1086                                         updateLocal(bv, CURSOR, false);
1087                                         bv->unlockInset(this);
1088                                 }
1089                                 break;
1090                         case FINISHED_DOWN:
1091                                 if ((result = moveDown(bv)) >= FINISHED) {
1092                                         updateLocal(bv, CURSOR, false);
1093                                         bv->unlockInset(this);
1094                                 }
1095                                 break;
1096                         default:
1097                                 result = DISPATCHED;
1098                                 break;
1099                         }
1100                         the_locking_inset = 0;
1101                         updateLocal(bv, CURSOR, false);
1102                         // make sure status gets reset immediately
1103                         bv->owner()->clearMessage();
1104                         return result;
1105                 }
1106         }
1107         bool clear = false;
1108         if (!lt) {
1109                 lt = getLyXText(bv);
1110                 clear = true;
1111         }
1112         int updwhat = 0;
1113         int updflag = false;
1114
1115         // what type of update to do on a cursor movement
1116         int cursor_update = CURSOR;
1117
1118         if (lt->selection.set())
1119                 cursor_update = SELECTION;
1120
1121         switch (cmd.action) {
1122
1123         // Normal chars
1124         case LFUN_SELFINSERT:
1125                 if (bv->buffer()->isReadonly()) {
1126 //          setErrorMessage(N_("Document is read only"));
1127                         break;
1128                 }
1129                 if (!cmd.argument.empty()) {
1130                         /* Automatically delete the currently selected
1131                          * text and replace it with what is being
1132                          * typed in now. Depends on lyxrc settings
1133                          * "auto_region_delete", which defaults to
1134                          * true (on). */
1135 #if 0
1136                         // This should not be needed here and is also WRONG!
1137                         setUndo(bv, Undo::INSERT,
1138                                 lt->cursor.par(), boost::next(lt->cursor.par()));
1139 #endif
1140                         bv->switchKeyMap();
1141                         if (lyxrc.auto_region_delete) {
1142                                 if (lt->selection.set()) {
1143                                         lt->cutSelection(false, false);
1144                                 }
1145                         }
1146                         lt->clearSelection();
1147                         for (string::size_type i = 0; i < cmd.argument.length(); ++i) {
1148                                 bv->owner()->getIntl().getTransManager().
1149                                         TranslateAndInsert(cmd.argument[i], lt);
1150                         }
1151                 }
1152                 lt->selection.cursor = lt->cursor;
1153                 updwhat = CURSOR | CURSOR_PAR;
1154                 updflag = true;
1155                 result = DISPATCHED_NOUPDATE;
1156                 break;
1157
1158         // cursor movements that need special handling
1159
1160         case LFUN_RIGHT:
1161                 result = moveRight(bv);
1162                 finishUndo();
1163                 updwhat = cursor_update;
1164                 break;
1165         case LFUN_LEFT:
1166                 finishUndo();
1167                 result = moveLeft(bv);
1168                 updwhat = cursor_update;
1169                 break;
1170         case LFUN_DOWN:
1171                 finishUndo();
1172                 result = moveDown(bv);
1173                 updwhat = cursor_update;
1174                 break;
1175         case LFUN_UP:
1176                 finishUndo();
1177                 result = moveUp(bv);
1178                 updwhat = cursor_update;
1179                 break;
1180
1181         case LFUN_PRIOR:
1182                 if (crow(bv) == lt->rows().begin())
1183                         result = FINISHED_UP;
1184                 else {
1185                         lt->cursorPrevious();
1186                         lt->clearSelection();
1187                         result = DISPATCHED_NOUPDATE;
1188                 }
1189                 updwhat = cursor_update;
1190                 break;
1191
1192         case LFUN_NEXT:
1193                 if (boost::next(crow(bv)) == lt->rows().end())
1194                         result = FINISHED_DOWN;
1195                 else {
1196                         lt->cursorNext();
1197                         lt->clearSelection();
1198                         result = DISPATCHED_NOUPDATE;
1199                 }
1200                 updwhat = cursor_update;
1201                 break;
1202
1203         case LFUN_BACKSPACE: {
1204                 if (lt->selection.set())
1205                         lt->cutSelection(true, false);
1206                 else
1207                         lt->backspace();
1208                 updwhat = CURSOR_PAR;
1209                 updflag = true;
1210                 break;
1211         }
1212
1213         case LFUN_DELETE: {
1214                 if (lt->selection.set()) {
1215                         lt->cutSelection(true, false);
1216                 } else {
1217                         lt->Delete();
1218                 }
1219                 updwhat = CURSOR_PAR;
1220                 updflag = true;
1221                 break;
1222         }
1223
1224         case LFUN_CUT: {
1225                 lt->cutSelection(bv);
1226                 updwhat = CURSOR_PAR;
1227                 updflag = true;
1228                 break;
1229         }
1230
1231         case LFUN_COPY:
1232                 finishUndo();
1233                 lt->copySelection();
1234                 updwhat = CURSOR_PAR;
1235                 break;
1236
1237         case LFUN_PASTESELECTION:
1238         {
1239                 string const clip(bv->getClipboard());
1240
1241                 if (clip.empty())
1242                         break;
1243                 if (cmd.argument == "paragraph") {
1244                         lt->insertStringAsParagraphs(clip);
1245                 } else {
1246                         lt->insertStringAsLines(clip);
1247                 }
1248                 // bug 393
1249                 lt->clearSelection();
1250
1251                 updwhat = CURSOR_PAR;
1252                 updflag = true;
1253                 break;
1254         }
1255
1256         case LFUN_PASTE: {
1257                 if (!autoBreakRows) {
1258                         if (CutAndPaste::nrOfParagraphs() > 1) {
1259 #ifdef WITH_WARNINGS
1260 #warning FIXME horrendously bad UI
1261 #endif
1262                                 Alert::error(_("Paste failed"), _("Cannot include more than one paragraph."));
1263                                 break;
1264                         }
1265                 }
1266
1267                 lt->pasteSelection();
1268                 // bug 393
1269                 lt->clearSelection();
1270                 updwhat = CURSOR_PAR;
1271                 updflag = true;
1272                 break;
1273         }
1274
1275         case LFUN_BREAKPARAGRAPH:
1276                 if (!autoBreakRows) {
1277                         result = DISPATCHED;
1278                         break;
1279                 }
1280                 lt->breakParagraph(paragraphs, 0);
1281                 updwhat = CURSOR | FULL;
1282                 updflag = true;
1283                 break;
1284
1285         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1286                 if (!autoBreakRows) {
1287                         result = DISPATCHED;
1288                         break;
1289                 }
1290                 lt->breakParagraph(paragraphs, 1);
1291                 updwhat = CURSOR | FULL;
1292                 updflag = true;
1293                 break;
1294
1295         case LFUN_BREAKLINE: {
1296                 if (!autoBreakRows) {
1297                         result = DISPATCHED;
1298                         break;
1299                 }
1300
1301                 lt->insertInset(new InsetNewline);
1302                 updwhat = CURSOR | CURSOR_PAR;
1303                 updflag = true;
1304                 break;
1305         }
1306
1307         case LFUN_LAYOUT:
1308                 // do not set layouts on non breakable textinsets
1309                 if (autoBreakRows) {
1310                         string cur_layout = cpar(bv)->layout()->name();
1311
1312                         // Derive layout number from given argument (string)
1313                         // and current buffer's textclass (number). */
1314                         LyXTextClass const & tclass =
1315                                 bv->buffer()->params.getLyXTextClass();
1316                         string layout = cmd.argument;
1317                         bool hasLayout = tclass.hasLayout(layout);
1318
1319                         // If the entry is obsolete, use the new one instead.
1320                         if (hasLayout) {
1321                                 string const & obs =
1322                                         tclass[layout]->obsoleted_by();
1323                                 if (!obs.empty())
1324                                         layout = obs;
1325                         }
1326
1327                         // see if we found the layout number:
1328                         if (!hasLayout) {
1329                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + cmd.argument + N_(" not known"));
1330                                 bv->owner()->dispatch(lf);
1331                                 break;
1332                         }
1333
1334                         if (cur_layout != layout) {
1335                                 cur_layout = layout;
1336                                 lt->setLayout(layout);
1337                                 bv->owner()->setLayout(cpar(bv)->layout()->name());
1338                                 updwhat = CURSOR_PAR;
1339                                 updflag = true;
1340                         }
1341                 } else {
1342                         // reset the layout box
1343                         bv->owner()->setLayout(cpar(bv)->layout()->name());
1344                 }
1345                 break;
1346         case LFUN_PARAGRAPH_SPACING:
1347                 // This one is absolutely not working. When fiddling with this
1348                 // it also seems to me that the paragraphs inside the insettext
1349                 // inherit bufferparams/paragraphparams in a strange way. (Lgb)
1350                 // FIXME: how old is this comment ? ...
1351         {
1352                 ParagraphList::iterator pit = lt->cursor.par();
1353                 Spacing::Space cur_spacing = pit->params().spacing().getSpace();
1354                 float cur_value = 1.0;
1355                 if (cur_spacing == Spacing::Other) {
1356                         cur_value = pit->params().spacing().getValue();
1357                 }
1358
1359                 istringstream istr(STRCONV(cmd.argument));
1360                 string tmp;
1361                 istr >> tmp;
1362                 Spacing::Space new_spacing = cur_spacing;
1363                 float new_value = cur_value;
1364                 if (tmp.empty()) {
1365                         lyxerr << "Missing argument to `paragraph-spacing'"
1366                                    << endl;
1367                 } else if (tmp == "single") {
1368                         new_spacing = Spacing::Single;
1369                 } else if (tmp == "onehalf") {
1370                         new_spacing = Spacing::Onehalf;
1371                 } else if (tmp == "double") {
1372                         new_spacing = Spacing::Double;
1373                 } else if (tmp == "other") {
1374                         new_spacing = Spacing::Other;
1375                         float tmpval = 0.0;
1376                         istr >> tmpval;
1377                         lyxerr << "new_value = " << tmpval << endl;
1378                         if (tmpval != 0.0)
1379                                 new_value = tmpval;
1380                 } else if (tmp == "default") {
1381                         new_spacing = Spacing::Default;
1382                 } else {
1383                         lyxerr << _("Unknown spacing argument: ")
1384                                    << cmd.argument << endl;
1385                 }
1386                 if (cur_spacing != new_spacing || cur_value != new_value) {
1387                         pit->params().spacing(Spacing(new_spacing, new_value));
1388                         updwhat = CURSOR_PAR;
1389                         updflag = true;
1390                 }
1391         }
1392         break;
1393
1394         // These need to do repaints but don't require
1395         // special handling otherwise. A *lot* of the
1396         // above could probably be done similarly ...
1397
1398         case LFUN_HOME:
1399         case LFUN_END:
1400         case LFUN_WORDLEFT:
1401         case LFUN_WORDRIGHT:
1402         // these two are really unhandled ...
1403         case LFUN_ENDBUF:
1404         case LFUN_BEGINNINGBUF:
1405                 updwhat = cursor_update;
1406                 if (!bv->dispatch(cmd))
1407                         result = UNDISPATCHED;
1408                 break;
1409
1410         case LFUN_RIGHTSEL:
1411         case LFUN_UPSEL:
1412         case LFUN_DOWNSEL:
1413         case LFUN_LEFTSEL:
1414         case LFUN_HOMESEL:
1415         case LFUN_ENDSEL:
1416         case LFUN_WORDLEFTSEL:
1417         case LFUN_WORDRIGHTSEL:
1418                 updwhat = SELECTION;
1419
1420                 // fallthrough
1421
1422         default:
1423                 if (!bv->dispatch(cmd))
1424                         result = UNDISPATCHED;
1425                 break;
1426         }
1427
1428         if (clear)
1429                 lt = 0;
1430         if (updwhat > 0)
1431                 updateLocal(bv, updwhat, updflag);
1432         /// If the action has deleted all text in the inset, we need to change the
1433         // language to the language of the surronding text.
1434         if (!was_empty && paragraphs.begin()->empty() &&
1435             boost::next(paragraphs.begin()) == paragraphs.end()) {
1436                 LyXFont font(LyXFont::ALL_IGNORE);
1437                 font.setLanguage(bv->getParentLanguage(this));
1438                 setFont(bv, font, false);
1439         }
1440
1441         if (result >= FINISHED)
1442                 bv->unlockInset(this);
1443
1444         if (result == DISPATCHED_NOUPDATE && (need_update & FULL))
1445                 result = DISPATCHED;
1446         return result;
1447 }
1448
1449
1450 int InsetText::latex(Buffer const * buf, ostream & os, LatexRunParams const & runparams,
1451                      bool fragile, bool) const
1452 {
1453         TexRow texrow;
1454         latexParagraphs(buf, paragraphs, os, texrow, runparams, fragile);
1455         return texrow.rows();
1456 }
1457
1458
1459 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1460 {
1461         unsigned int lines = 0;
1462
1463         ParagraphList::iterator beg = paragraphs.begin();
1464         ParagraphList::iterator end = paragraphs.end();
1465         ParagraphList::iterator it = beg;
1466         for (; it != end; ++it) {
1467                 string const tmp = buf->asciiParagraph(*it, linelen, it == beg);
1468                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1469                 os << tmp;
1470         }
1471         return lines;
1472 }
1473
1474
1475 int InsetText::docbook(Buffer const * buf, ostream & os, bool mixcont) const
1476 {
1477         unsigned int lines = 0;
1478
1479         vector<string> environment_stack(10);
1480         vector<string> environment_inner(10);
1481
1482         int const command_depth = 0;
1483         string item_name;
1484
1485         Paragraph::depth_type depth = 0; // paragraph depth
1486
1487         ParagraphList::iterator pit = paragraphs.begin();
1488         ParagraphList::iterator pend = paragraphs.end();
1489
1490         for (; pit != pend; ++pit) {
1491                 string sgmlparam;
1492                 int desc_on = 0; // description mode
1493
1494                 LyXLayout_ptr const & style = pit->layout();
1495
1496                 // environment tag closing
1497                 for (; depth > pit->params().depth(); --depth) {
1498                         if (environment_inner[depth] != "!-- --") {
1499                                 item_name = "listitem";
1500                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1501                                 if (environment_inner[depth] == "varlistentry")
1502                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1503                         }
1504                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1505                         environment_stack[depth].erase();
1506                         environment_inner[depth].erase();
1507                 }
1508
1509                 if (depth == pit->params().depth()
1510                    && environment_stack[depth] != style->latexname()
1511                    && !environment_stack[depth].empty()) {
1512                         if (environment_inner[depth] != "!-- --") {
1513                                 item_name= "listitem";
1514                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1515                                 if (environment_inner[depth] == "varlistentry")
1516                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1517                         }
1518
1519                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1520
1521                         environment_stack[depth].erase();
1522                         environment_inner[depth].erase();
1523                 }
1524
1525                 // Write opening SGML tags.
1526                 switch (style->latextype) {
1527                 case LATEX_PARAGRAPH:
1528                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1529                         break;
1530
1531                 case LATEX_COMMAND:
1532                         buf->sgmlError(pit, 0,  _("Error: LatexType Command not allowed here.\n"));
1533                         return -1;
1534                         break;
1535
1536                 case LATEX_ENVIRONMENT:
1537                 case LATEX_ITEM_ENVIRONMENT:
1538                         if (depth < pit->params().depth()) {
1539                                 depth = pit->params().depth();
1540                                 environment_stack[depth].erase();
1541                         }
1542
1543                         if (environment_stack[depth] != style->latexname()) {
1544                                 if (environment_stack.size() == depth + 1) {
1545                                         environment_stack.push_back("!-- --");
1546                                         environment_inner.push_back("!-- --");
1547                                 }
1548                                 environment_stack[depth] = style->latexname();
1549                                 environment_inner[depth] = "!-- --";
1550                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1551                         } else {
1552                                 if (environment_inner[depth] != "!-- --") {
1553                                         item_name= "listitem";
1554                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1555                                         if (environment_inner[depth] == "varlistentry")
1556                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1557                                 }
1558                         }
1559
1560                         if (style->latextype == LATEX_ENVIRONMENT) {
1561                                 if (!style->latexparam().empty()) {
1562                                         if (style->latexparam() == "CDATA")
1563                                                 os << "<![CDATA[";
1564                                         else
1565                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1566                                 }
1567                                 break;
1568                         }
1569
1570                         desc_on = (style->labeltype == LABEL_MANUAL);
1571
1572                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1573                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1574
1575                         item_name = desc_on ? "term" : "para";
1576                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1577
1578                         break;
1579                 default:
1580                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1581                         break;
1582                 }
1583
1584                 buf->simpleDocBookOnePar(os, pit, desc_on, depth + 1 + command_depth);
1585
1586                 string end_tag;
1587                 // write closing SGML tags
1588                 switch (style->latextype) {
1589                 case LATEX_ENVIRONMENT:
1590                         if (!style->latexparam().empty()) {
1591                                 if (style->latexparam() == "CDATA")
1592                                         os << "]]>";
1593                                 else
1594                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1595                         }
1596                         break;
1597                 case LATEX_ITEM_ENVIRONMENT:
1598                         if (desc_on == 1) break;
1599                         end_tag= "para";
1600                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1601                         break;
1602                 case LATEX_PARAGRAPH:
1603                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1604                         break;
1605                 default:
1606                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1607                         break;
1608                 }
1609         }
1610
1611         // Close open tags
1612         for (int d = depth; d >= 0; --d) {
1613                 if (!environment_stack[depth].empty()) {
1614                         if (environment_inner[depth] != "!-- --") {
1615                                 item_name = "listitem";
1616                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1617                                if (environment_inner[depth] == "varlistentry")
1618                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1619                         }
1620
1621                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1622                 }
1623         }
1624
1625         return lines;
1626 }
1627
1628
1629 void InsetText::validate(LaTeXFeatures & features) const
1630 {
1631         for_each(paragraphs.begin(), paragraphs.end(),
1632                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1633 }
1634
1635
1636 void InsetText::getCursor(BufferView & bv, int & x, int & y) const
1637 {
1638         if (the_locking_inset) {
1639                 the_locking_inset->getCursor(bv, x, y);
1640                 return;
1641         }
1642         x = cx(&bv);
1643         y = cy(&bv) + InsetText::y();
1644 }
1645
1646
1647 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1648 {
1649         if (the_locking_inset) {
1650                 the_locking_inset->getCursorPos(bv, x, y);
1651                 return;
1652         }
1653         x = cx(bv) - top_x - TEXT_TO_INSET_OFFSET;
1654         y = cy(bv) - TEXT_TO_INSET_OFFSET;
1655 }
1656
1657
1658 int InsetText::insetInInsetY() const
1659 {
1660         if (!the_locking_inset)
1661                 return 0;
1662
1663         return (inset_y + the_locking_inset->insetInInsetY());
1664 }
1665
1666
1667 void InsetText::fitInsetCursor(BufferView * bv) const
1668 {
1669         if (the_locking_inset) {
1670                 the_locking_inset->fitInsetCursor(bv);
1671                 return;
1672         }
1673         LyXFont const font =
1674                 getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1675
1676         int const asc = font_metrics::maxAscent(font);
1677         int const desc = font_metrics::maxDescent(font);
1678
1679         if (bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc))
1680                 need_update |= FULL;
1681 }
1682
1683
1684 Inset::RESULT
1685 InsetText::moveRight(BufferView * bv, bool activate_inset, bool selecting)
1686 {
1687         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1688                 return moveLeftIntern(bv, false, activate_inset, selecting);
1689         else
1690                 return moveRightIntern(bv, true, activate_inset, selecting);
1691 }
1692
1693
1694 Inset::RESULT
1695 InsetText::moveLeft(BufferView * bv, bool activate_inset, bool selecting)
1696 {
1697         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1698                 return moveRightIntern(bv, true, activate_inset, selecting);
1699         else
1700                 return moveLeftIntern(bv, false, activate_inset, selecting);
1701 }
1702
1703
1704 Inset::RESULT
1705 InsetText::moveRightIntern(BufferView * bv, bool front,
1706                            bool activate_inset, bool selecting)
1707 {
1708         LyXText * text = getLyXText(bv);
1709
1710         ParagraphList::iterator c_par = cpar(bv);
1711
1712         if (boost::next(c_par) == paragraphs.end() &&
1713             (cpos(bv) >= c_par->size()))
1714                 return FINISHED_RIGHT;
1715         if (activate_inset && checkAndActivateInset(bv, front))
1716                 return DISPATCHED;
1717         text->cursorRight(bv);
1718         if (!selecting)
1719                 text->clearSelection();
1720         return DISPATCHED_NOUPDATE;
1721 }
1722
1723
1724 Inset::RESULT
1725 InsetText::moveLeftIntern(BufferView * bv, bool front,
1726                           bool activate_inset, bool selecting)
1727 {
1728         LyXText * text = getLyXText(bv);
1729
1730         if (cpar(bv) == paragraphs.begin() && (cpos(bv) <= 0))
1731                 return FINISHED;
1732         text->cursorLeft(bv);
1733         if (!selecting)
1734                 text->clearSelection();
1735         if (activate_inset && checkAndActivateInset(bv, front))
1736                 return DISPATCHED;
1737         return DISPATCHED_NOUPDATE;
1738 }
1739
1740
1741 Inset::RESULT InsetText::moveUp(BufferView * bv)
1742 {
1743         if (crow(bv) == getLyXText(bv)->rows().begin())
1744                 return FINISHED_UP;
1745         getLyXText(bv)->cursorUp(bv);
1746         getLyXText(bv)->clearSelection();
1747         return DISPATCHED_NOUPDATE;
1748 }
1749
1750
1751 Inset::RESULT InsetText::moveDown(BufferView * bv)
1752 {
1753         if (boost::next(crow(bv)) == getLyXText(bv)->rows().end())
1754                 return FINISHED_DOWN;
1755         getLyXText(bv)->cursorDown(bv);
1756         getLyXText(bv)->clearSelection();
1757         return DISPATCHED_NOUPDATE;
1758 }
1759
1760
1761 bool InsetText::insertInset(BufferView * bv, Inset * inset)
1762 {
1763         if (the_locking_inset) {
1764                 if (the_locking_inset->insetAllowed(inset))
1765                         return the_locking_inset->insertInset(bv, inset);
1766                 return false;
1767         }
1768         inset->setOwner(this);
1769         getLyXText(bv)->insertInset(inset);
1770         bv->fitCursor();
1771         updateLocal(bv, CURSOR_PAR|CURSOR, true);
1772         return true;
1773 }
1774
1775
1776 bool InsetText::insetAllowed(Inset::Code code) const
1777 {
1778         // in_insetAllowed is a really gross hack,
1779         // to allow us to call the owner's insetAllowed
1780         // without stack overflow, which can happen
1781         // when the owner uses InsetCollapsable::insetAllowed()
1782         bool ret = true;
1783         if (in_insetAllowed)
1784                 return ret;
1785         in_insetAllowed = true;
1786         if (the_locking_inset)
1787                 ret = the_locking_inset->insetAllowed(code);
1788         else if (owner())
1789                 ret = owner()->insetAllowed(code);
1790         in_insetAllowed = false;
1791         return ret;
1792 }
1793
1794
1795 UpdatableInset * InsetText::getLockingInset() const
1796 {
1797         return the_locking_inset ? the_locking_inset->getLockingInset() :
1798                 const_cast<InsetText *>(this);
1799 }
1800
1801
1802 UpdatableInset * InsetText::getFirstLockingInsetOfType(Inset::Code c)
1803 {
1804         if (c == lyxCode())
1805                 return this;
1806         if (the_locking_inset)
1807                 return the_locking_inset->getFirstLockingInsetOfType(c);
1808         return 0;
1809 }
1810
1811
1812 bool InsetText::showInsetDialog(BufferView * bv) const
1813 {
1814         if (the_locking_inset)
1815                 return the_locking_inset->showInsetDialog(bv);
1816         return false;
1817 }
1818
1819
1820 vector<string> const InsetText::getLabelList() const
1821 {
1822         vector<string> label_list;
1823
1824         ParagraphList::iterator pit = paragraphs.begin();
1825         ParagraphList::iterator pend = paragraphs.end();
1826         for (; pit != pend; ++pit) {
1827                 InsetList::iterator beg = pit->insetlist.begin();
1828                 InsetList::iterator end = pit->insetlist.end();
1829                 for (; beg != end; ++beg) {
1830                         vector<string> const l = beg.getInset()->getLabelList();
1831                         label_list.insert(label_list.end(), l.begin(), l.end());
1832                 }
1833         }
1834         return label_list;
1835 }
1836
1837
1838 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1839                         bool selectall)
1840 {
1841         if (the_locking_inset) {
1842                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1843                 return;
1844         }
1845         if ((boost::next(paragraphs.begin()) == paragraphs.end() &&
1846              paragraphs.begin()->empty()) || cpar(bv)->empty()) {
1847                 getLyXText(bv)->setFont(font, toggleall);
1848                 return;
1849         }
1850         bool clear = false;
1851         if (!lt) {
1852                 lt = getLyXText(bv);
1853                 clear = true;
1854         }
1855         if (lt->selection.set()) {
1856                 setUndo(bv, Undo::EDIT, lt->cursor.par(), boost::next(lt->cursor.par()));
1857         }
1858         if (selectall)
1859                 selectAll(bv);
1860         lt->toggleFree(font, toggleall);
1861         if (selectall)
1862                 lt->clearSelection();
1863         bv->fitCursor();
1864         bool flag = (selectall || lt->selection.set());
1865         if (clear)
1866                 lt = 0;
1867         if (flag)
1868                 updateLocal(bv, FULL, true);
1869         else
1870                 updateLocal(bv, CURSOR_PAR, true);
1871 }
1872
1873
1874 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1875 {
1876         if (cpar(bv)->isInset(cpos(bv))) {
1877                 Inset * inset =
1878                         static_cast<UpdatableInset*>(cpar(bv)->getInset(cpos(bv)));
1879                 if (!isHighlyEditableInset(inset))
1880                         return false;
1881                 FuncRequest cmd(bv, LFUN_INSET_EDIT, front ? "left" : "right");
1882                 inset->localDispatch(cmd);
1883                 if (!the_locking_inset)
1884                         return false;
1885                 updateLocal(bv, CURSOR, false);
1886                 return true;
1887         }
1888         return false;
1889 }
1890
1891
1892 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1893                                       mouse_button::state button)
1894 {
1895         x -= drawTextXOffset;
1896         int dummyx = x;
1897         int dummyy = y + dim_.a;
1898         Inset * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1899         // we only do the edit() call if the inset was hit by the mouse
1900         // or if it is a highly editable inset. So we should call this
1901         // function from our own edit with button < 0.
1902         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1903         // WRONG
1904         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1905                 return false;
1906
1907         if (inset) {
1908                 if (x < 0)
1909                         x = dim_.w;
1910                 if (y < 0)
1911                         y = dim_.d;
1912                 inset_x = cix(bv) - top_x + drawTextXOffset;
1913                 inset_y = ciy(bv) + drawTextYOffset;
1914                 FuncRequest cmd(bv, LFUN_INSET_EDIT, x - inset_x, y - inset_y, button);
1915                 inset->localDispatch(cmd);
1916                 if (!the_locking_inset)
1917                         return false;
1918                 updateLocal(bv, CURSOR, false);
1919                 return true;
1920         }
1921         return false;
1922 }
1923
1924
1925 int InsetText::getMaxWidth(BufferView * bv, UpdatableInset const * inset) const
1926 {
1927 #if 0
1928         int w = UpdatableInset::getMaxWidth(bv, inset);
1929         if (w < 0) {
1930                 return -1;
1931         }
1932         if (owner()) {
1933                 w = w - top_x + owner()->x();
1934                 return w;
1935         }
1936         w -= (2 * TEXT_TO_INSET_OFFSET);
1937         return w - top_x;
1938 #else
1939         return UpdatableInset::getMaxWidth(bv, inset);
1940 #endif
1941 }
1942
1943
1944 void InsetText::setParagraphData(ParagraphList const & plist, bool same_id)
1945 {
1946         // we have to unlock any locked inset otherwise we're in troubles
1947         the_locking_inset = 0;
1948
1949         paragraphs.clear();
1950         ParagraphList::iterator pit = plist.begin();
1951         ParagraphList::iterator pend = plist.end();
1952         for (; pit != pend; ++pit) {
1953                 Paragraph * new_par = new Paragraph(*pit, same_id);
1954                 new_par->setInsetOwner(this);
1955                 paragraphs.push_back(new_par);
1956         }
1957
1958         reinitLyXText();
1959         need_update = INIT;
1960 }
1961
1962
1963 void InsetText::markNew(bool track_changes)
1964 {
1965         ParagraphList::iterator pit = paragraphs.begin();
1966         ParagraphList::iterator pend = paragraphs.end();
1967         for (; pit != pend; ++pit) {
1968                 if (track_changes) {
1969                         pit->trackChanges();
1970                 } else {
1971                         // no-op when not tracking
1972                         pit->cleanChanges();
1973                 }
1974         }
1975 }
1976
1977
1978 void InsetText::setText(string const & data, LyXFont const & font)
1979 {
1980         clear(false);
1981         for (unsigned int i = 0; i < data.length(); ++i)
1982                 paragraphs.begin()->insertChar(i, data[i], font);
1983         reinitLyXText();
1984 }
1985
1986
1987 void InsetText::setAutoBreakRows(bool flag)
1988 {
1989         if (flag != autoBreakRows) {
1990                 autoBreakRows = flag;
1991                 if (!flag)
1992                         removeNewlines();
1993                 need_update = INIT;
1994         }
1995 }
1996
1997
1998 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
1999 {
2000         if (how != drawFrame_) {
2001                 drawFrame_ = how;
2002                 if (bv)
2003                         updateLocal(bv, DRAW_FRAME, false);
2004         }
2005 }
2006
2007
2008 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
2009 {
2010         if (frame_color != col) {
2011                 frame_color = col;
2012                 if (bv)
2013                         updateLocal(bv, DRAW_FRAME, false);
2014         }
2015 }
2016
2017
2018 int InsetText::cx(BufferView * bv) const
2019 {
2020         // we do nothing dangerous so we use a local cache
2021         LyXText * llt = getLyXText(bv);
2022         int x = llt->cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
2023         if (the_locking_inset) {
2024                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2025                                             llt->cursor.pos());
2026                 if (font.isVisibleRightToLeft())
2027                         x -= the_locking_inset->width(bv, font);
2028         }
2029         return x;
2030 }
2031
2032
2033 int InsetText::cix(BufferView * bv) const
2034 {
2035         // we do nothing dangerous so we use a local cache
2036         LyXText * llt = getLyXText(bv);
2037         int x = llt->cursor.ix() + top_x + TEXT_TO_INSET_OFFSET;
2038         if (the_locking_inset) {
2039                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2040                                             llt->cursor.pos());
2041                 if (font.isVisibleRightToLeft())
2042                         x -= the_locking_inset->width(bv, font);
2043         }
2044         return x;
2045 }
2046
2047
2048 int InsetText::cy(BufferView * bv) const
2049 {
2050         LyXFont font;
2051         return getLyXText(bv)->cursor.y() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2052 }
2053
2054
2055 int InsetText::ciy(BufferView * bv) const
2056 {
2057         LyXFont font;
2058         return getLyXText(bv)->cursor.iy() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2059 }
2060
2061
2062 pos_type InsetText::cpos(BufferView * bv) const
2063 {
2064         return getLyXText(bv)->cursor.pos();
2065 }
2066
2067
2068 ParagraphList::iterator InsetText::cpar(BufferView * bv) const
2069 {
2070         return getLyXText(bv)->cursor.par();
2071 }
2072
2073
2074 bool InsetText::cboundary(BufferView * bv) const
2075 {
2076         return getLyXText(bv)->cursor.boundary();
2077 }
2078
2079
2080 RowList::iterator InsetText::crow(BufferView * bv) const
2081 {
2082         return getLyXText(bv)->cursor.row();
2083 }
2084
2085
2086 LyXText * InsetText::getLyXText(BufferView const * lbv,
2087                                 bool const recursive) const
2088 {
2089         if (cached_bview == lbv) {
2090                 if (recursive && the_locking_inset)
2091                         return the_locking_inset->getLyXText(lbv, true);
2092                 LyXText * lt = cached_text.get();
2093                 lyx::Assert(lt && lt->rows().begin()->par() == paragraphs.begin());
2094                 return lt;
2095         }
2096         // Super UGLY! (Lgb)
2097         BufferView * bv = const_cast<BufferView *>(lbv);
2098
2099         cached_bview = bv;
2100         Cache::iterator it = cache.find(bv);
2101
2102         if (it != cache.end()) {
2103                 if (do_reinit) {
2104                         reinitLyXText();
2105                 } else if (do_resize) {
2106                         resizeLyXText(do_resize);
2107                 } else {
2108                         if (lt || !it->second.remove) {
2109                                 lyx::Assert(it->second.text.get());
2110                                 cached_text = it->second.text;
2111                                 if (recursive && the_locking_inset) {
2112                                         return the_locking_inset->getLyXText(bv, true);
2113                                 }
2114                                 return cached_text.get();
2115                         } else if (it->second.remove) {
2116                                 if (locked) {
2117                                         saveLyXTextState(it->second.text.get());
2118                                 } else {
2119                                         sstate.lpar = 0;
2120                                 }
2121                         }
2122                         //
2123                         // when we have to reinit the existing LyXText!
2124                         //
2125                         it->second.text->init(bv);
2126                         restoreLyXTextState(it->second.text.get());
2127                         it->second.remove = false;
2128                 }
2129                 cached_text = it->second.text;
2130                 if (the_locking_inset && recursive) {
2131                         return the_locking_inset->getLyXText(bv);
2132                 }
2133                 return cached_text.get();
2134         }
2135         ///
2136         // we are here only if we don't have a BufferView * in the cache!!!
2137         ///
2138         cached_text.reset(new LyXText(bv, const_cast<InsetText *>(this)));
2139         cached_text->init(bv);
2140         restoreLyXTextState(cached_text.get());
2141
2142         cache.insert(make_pair(bv, cached_text));
2143
2144         if (the_locking_inset && recursive) {
2145                 return the_locking_inset->getLyXText(bv);
2146         }
2147         return cached_text.get();
2148 }
2149
2150
2151 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
2152 {
2153         cached_bview = 0;
2154
2155         Cache::iterator it = cache.find(bv);
2156
2157         if (it == cache.end()) {
2158                 return;
2159         }
2160
2161         lyx::Assert(it->second.text.get());
2162
2163         it->second.remove = true;
2164         if (recursive) {
2165                 /// then remove all LyXText in text-insets
2166                 for_each(paragraphs.begin(), paragraphs.end(),
2167                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
2168         }
2169 }
2170
2171
2172 void InsetText::resizeLyXText(BufferView * bv, bool force) const
2173 {
2174         if (lt) {
2175                 // we cannot resize this because we are in use!
2176                 // so do this on the next possible getLyXText()
2177                 do_resize = bv;
2178                 return;
2179         }
2180         do_resize = 0;
2181         if (boost::next(paragraphs.begin()) == paragraphs.end() &&
2182             paragraphs.begin()->empty()) { // no data, resize not neccessary!
2183                 // we have to do this as a fixed width may have changed!
2184                 LyXText * t = getLyXText(bv);
2185                 saveLyXTextState(t);
2186                 t->init(bv, true);
2187                 restoreLyXTextState(t);
2188                 return;
2189         }
2190         // one endless line, resize normally not necessary
2191         if (!force && getMaxWidth(bv, this) < 0)
2192                 return;
2193
2194         Cache::iterator it = cache.find(bv);
2195         if (it == cache.end()) {
2196                 return;
2197         }
2198         lyx::Assert(it->second.text.get());
2199
2200         LyXText * t = it->second.text.get();
2201         saveLyXTextState(t);
2202
2203         for_each(paragraphs.begin(), paragraphs.end(),
2204                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2205
2206         t->init(bv, true);
2207         restoreLyXTextState(t);
2208         if (the_locking_inset) {
2209                 inset_x = cix(bv) - top_x + drawTextXOffset;
2210                 inset_y = ciy(bv) + drawTextYOffset;
2211         }
2212
2213         t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2214         if (!owner()) {
2215                 const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2216                 // this will scroll the screen such that the cursor becomes visible
2217                 bv->updateScrollbar();
2218         } else {
2219                 need_update |= FULL;
2220         }
2221 }
2222
2223
2224 void InsetText::reinitLyXText() const
2225 {
2226         if (lt) {
2227                 // we cannot resize this because we are in use!
2228                 // so do this on the next possible getLyXText()
2229                 do_reinit = true;
2230                 return;
2231         }
2232         do_reinit = false;
2233         do_resize = 0;
2234         for (Cache::iterator it = cache.begin(); it != cache.end(); ++it) {
2235                 lyx::Assert(it->second.text.get());
2236
2237                 LyXText * t = it->second.text.get();
2238                 BufferView * bv = it->first;
2239
2240                 saveLyXTextState(t);
2241
2242                 for_each(paragraphs.begin(), paragraphs.end(),
2243                          boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2244
2245                 t->init(bv, true);
2246                 restoreLyXTextState(t);
2247                 if (the_locking_inset) {
2248                         inset_x = cix(bv) - top_x + drawTextXOffset;
2249                         inset_y = ciy(bv) + drawTextYOffset;
2250                 }
2251                 t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2252                 if (!owner()) {
2253                         const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2254                         // this will scroll the screen such that the cursor becomes visible
2255                         bv->updateScrollbar();
2256                 } else {
2257                         need_update = FULL;
2258                 }
2259         }
2260 }
2261
2262
2263 void InsetText::removeNewlines()
2264 {
2265         bool changed = false;
2266
2267         ParagraphList::iterator it = paragraphs.begin();
2268         ParagraphList::iterator end = paragraphs.end();
2269         for (; it != end; ++it) {
2270                 for (int i = 0; i < it->size(); ++i) {
2271                         if (it->isNewline(i)) {
2272                                 changed = true;
2273                                 it->erase(i);
2274                         }
2275                 }
2276         }
2277         if (changed)
2278                 reinitLyXText();
2279 }
2280
2281
2282 bool InsetText::nodraw() const
2283 {
2284         if (the_locking_inset)
2285                 return the_locking_inset->nodraw();
2286         return UpdatableInset::nodraw();
2287 }
2288
2289
2290 int InsetText::scroll(bool recursive) const
2291 {
2292         int sx = UpdatableInset::scroll(false);
2293
2294         if (recursive && the_locking_inset)
2295                 sx += the_locking_inset->scroll(recursive);
2296
2297         return sx;
2298 }
2299
2300
2301 void InsetText::selectAll(BufferView * bv)
2302 {
2303         getLyXText(bv)->cursorTop();
2304         getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
2305         getLyXText(bv)->cursorBottom();
2306         getLyXText(bv)->setSelection();
2307 }
2308
2309
2310 void InsetText::clearSelection(BufferView * bv)
2311 {
2312         getLyXText(bv)->clearSelection();
2313 }
2314
2315
2316 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
2317 {
2318         Painter & pain = bv->painter();
2319         int w = dim_.w;
2320         int h = dim_.a + dim_.d;
2321         int ty = baseline - dim_.a;
2322
2323         if (ty < 0) {
2324                 h += ty;
2325                 ty = 0;
2326         }
2327         if ((ty + h) > pain.paperHeight())
2328                 h = pain.paperHeight();
2329         if ((top_x + drawTextXOffset + w) > pain.paperWidth())
2330                 w = pain.paperWidth();
2331         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
2332         need_update = FULL;
2333 }
2334
2335
2336 ParagraphList * InsetText::getParagraphs(int i) const
2337 {
2338         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
2339 }
2340
2341
2342 LyXCursor const & InsetText::cursor(BufferView * bv) const
2343 {
2344         if (the_locking_inset)
2345                 return the_locking_inset->cursor(bv);
2346         return getLyXText(bv)->cursor;
2347 }
2348
2349
2350 Inset * InsetText::getInsetFromID(int id_arg) const
2351 {
2352         if (id_arg == id())
2353                 return const_cast<InsetText *>(this);
2354
2355         ParagraphList::iterator pit = paragraphs.begin();
2356         ParagraphList::iterator pend = paragraphs.end();
2357         for (; pit != pend; ++pit) {
2358                 InsetList::iterator it = pit->insetlist.begin();
2359                 InsetList::iterator end = pit->insetlist.end();
2360                 for (; it != end; ++it) {
2361                         if (it.getInset()->id() == id_arg)
2362                                 return it.getInset();
2363                         Inset * in = it.getInset()->getInsetFromID(id_arg);
2364                         if (in)
2365                                 return in;
2366                 }
2367         }
2368         return 0;
2369 }
2370
2371
2372 WordLangTuple const
2373 InsetText::selectNextWordToSpellcheck(BufferView * bv,
2374                                       float & value) const
2375 {
2376         bool clear = false;
2377         WordLangTuple word;
2378
2379         if (!lt) {
2380                 lt = getLyXText(bv);
2381                 clear = true;
2382         }
2383         if (the_locking_inset) {
2384                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
2385                 if (!word.word().empty()) {
2386                         value += cy(bv);
2387                         if (clear)
2388                                 lt = 0;
2389                         return word;
2390                 }
2391                 // we have to go on checking so move cursor to the next char
2392                 lt->cursor.pos(lt->cursor.pos() + 1);
2393         }
2394         word = lt->selectNextWordToSpellcheck(value);
2395         if (word.word().empty())
2396                 bv->unlockInset(const_cast<InsetText *>(this));
2397         else
2398                 value = cy(bv);
2399         if (clear)
2400                 lt = 0;
2401         return word;
2402 }
2403
2404
2405 void InsetText::selectSelectedWord(BufferView * bv)
2406 {
2407         if (the_locking_inset) {
2408                 the_locking_inset->selectSelectedWord(bv);
2409                 return;
2410         }
2411         getLyXText(bv)->selectSelectedWord();
2412         updateLocal(bv, SELECTION, false);
2413 }
2414
2415
2416 void InsetText::toggleSelection(BufferView * bv, bool kill_selection)
2417 {
2418         if (the_locking_inset) {
2419                 the_locking_inset->toggleSelection(bv, kill_selection);
2420         }
2421         bool clear = false;
2422         if (!lt) {
2423                 lt = getLyXText(bv);
2424                 clear = true;
2425         }
2426
2427         int x = top_x + TEXT_TO_INSET_OFFSET;
2428
2429         RowList::iterator rowit = lt->rows().begin();
2430         RowList::iterator end = lt->rows().end();
2431         int y_offset = top_baseline - rowit->ascent_of_text();
2432         int y = y_offset;
2433         while ((rowit != end) && ((y + rowit->height()) <= 0)) {
2434                 y += rowit->height();
2435                 ++rowit;
2436         }
2437         if (y_offset < 0)
2438                 y_offset = y;
2439
2440         if (need_update & SELECTION)
2441                 need_update = NONE;
2442         bv->screen().toggleSelection(lt, bv, kill_selection, y_offset, x);
2443         if (clear)
2444                 lt = 0;
2445 }
2446
2447
2448 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
2449 {
2450         bool clear = false;
2451         if (!lt) {
2452                 lt = getLyXText(bv);
2453                 clear = true;
2454         }
2455         if (the_locking_inset) {
2456                 if (the_locking_inset->nextChange(bv, length))
2457                         return true;
2458                 lt->cursorRight(true);
2459         }
2460         lyxfind::SearchResult result =
2461                 lyxfind::findNextChange(bv, lt, length);
2462
2463         if (result == lyxfind::SR_FOUND) {
2464                 LyXCursor cur = lt->cursor;
2465                 bv->unlockInset(bv->theLockingInset());
2466                 if (bv->lockInset(this))
2467                         locked = true;
2468                 lt->cursor = cur;
2469                 lt->setSelectionRange(length);
2470                 updateLocal(bv, SELECTION, false);
2471         }
2472         if (clear)
2473                 lt = 0;
2474         return result != lyxfind::SR_NOT_FOUND;
2475 }
2476
2477
2478 bool InsetText::searchForward(BufferView * bv, string const & str,
2479                               bool cs, bool mw)
2480 {
2481         bool clear = false;
2482         if (!lt) {
2483                 lt = getLyXText(bv);
2484                 clear = true;
2485         }
2486         if (the_locking_inset) {
2487                 if (the_locking_inset->searchForward(bv, str, cs, mw))
2488                         return true;
2489                 lt->cursorRight(true);
2490         }
2491         lyxfind::SearchResult result =
2492                 lyxfind::LyXFind(bv, lt, str, true, cs, mw);
2493
2494         if (result == lyxfind::SR_FOUND) {
2495                 LyXCursor cur = lt->cursor;
2496                 bv->unlockInset(bv->theLockingInset());
2497                 if (bv->lockInset(this))
2498                         locked = true;
2499                 lt->cursor = cur;
2500                 lt->setSelectionRange(str.length());
2501                 updateLocal(bv, SELECTION, false);
2502         }
2503         if (clear)
2504                 lt = 0;
2505         return (result != lyxfind::SR_NOT_FOUND);
2506 }
2507
2508 bool InsetText::searchBackward(BufferView * bv, string const & str,
2509                                bool cs, bool mw)
2510 {
2511         if (the_locking_inset) {
2512                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2513                         return true;
2514         }
2515         bool clear = false;
2516         if (!lt) {
2517                 lt = getLyXText(bv);
2518                 clear = true;
2519         }
2520         if (!locked) {
2521                 ParagraphList::iterator pit = paragraphs.begin();
2522                 ParagraphList::iterator pend = paragraphs.end();
2523
2524                 while (boost::next(pit) != pend)
2525                         ++pit;
2526
2527                 lt->setCursor(pit, pit->size());
2528         }
2529         lyxfind::SearchResult result =
2530                 lyxfind::LyXFind(bv, lt, str, false, cs, mw);
2531
2532         if (result == lyxfind::SR_FOUND) {
2533                 LyXCursor cur = lt->cursor;
2534                 bv->unlockInset(bv->theLockingInset());
2535                 if (bv->lockInset(this))
2536                         locked = true;
2537                 lt->cursor = cur;
2538                 lt->setSelectionRange(str.length());
2539                 updateLocal(bv, SELECTION, false);
2540         }
2541         if (clear)
2542                 lt = 0;
2543         return (result != lyxfind::SR_NOT_FOUND);
2544 }
2545
2546
2547 bool InsetText::checkInsertChar(LyXFont & font)
2548 {
2549         if (owner())
2550                 return owner()->checkInsertChar(font);
2551         return true;
2552 }
2553
2554
2555 void InsetText::collapseParagraphs(BufferView * bv)
2556 {
2557         LyXText * llt = getLyXText(bv);
2558
2559         while (boost::next(paragraphs.begin()) != paragraphs.end()) {
2560                 if (!paragraphs.begin()->empty() &&
2561                     !boost::next(paragraphs.begin())->empty() &&
2562                         !paragraphs.begin()->isSeparator(paragraphs.begin()->size() - 1))
2563                 {
2564                         paragraphs.begin()->insertChar(paragraphs.begin()->size(), ' ');
2565                 }
2566                 if (llt->selection.set()) {
2567                         if (llt->selection.start.par() == boost::next(paragraphs.begin())) {
2568                                 llt->selection.start.par(paragraphs.begin());
2569                                 llt->selection.start.pos(
2570                                         llt->selection.start.pos() + paragraphs.begin()->size());
2571                         }
2572                         if (llt->selection.end.par() == boost::next(paragraphs.begin())) {
2573                                 llt->selection.end.par(paragraphs.begin());
2574                                 llt->selection.end.pos(
2575                                         llt->selection.end.pos() + paragraphs.begin()->size());
2576                         }
2577                 }
2578                 mergeParagraph(bv->buffer()->params, paragraphs, paragraphs.begin());
2579         }
2580         reinitLyXText();
2581 }
2582
2583
2584 void InsetText::getDrawFont(LyXFont & font) const
2585 {
2586         if (!owner())
2587                 return;
2588         owner()->getDrawFont(font);
2589 }
2590
2591
2592 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
2593 {
2594 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
2595 // And it probably does. You have to take a look at this John. (Lgb)
2596 #warning John, have a look here. (Lgb)
2597 #if 0
2598         BufferParams const & bparams = buffer->params;
2599         Paragraph * buf;
2600         Paragraph * tmpbuf = newpar;
2601         Paragraph * lastbuffer = buf = new Paragraph(*tmpbuf, false);
2602         if (bparams.tracking_changes)
2603                 buf->cleanChanges();
2604
2605         while (tmpbuf->next()) {
2606                 tmpbuf = tmpbuf->next();
2607                 lastbuffer->next(new Paragraph(*tmpbuf, false));
2608                 lastbuffer->next()->previous(lastbuffer);
2609                 lastbuffer = lastbuffer->next();
2610                 if (bparams.tracking_changes)
2611                         lastbuffer->cleanChanges();
2612         }
2613
2614         lastbuffer = &*(paragraphs.begin());
2615         while (lastbuffer->next())
2616                 lastbuffer = lastbuffer->next();
2617         if (!newpar->empty() && !lastbuffer->empty() &&
2618                 !lastbuffer->isSeparator(lastbuffer->size() - 1))
2619         {
2620                 lastbuffer->insertChar(lastbuffer->size(), ' ');
2621         }
2622
2623         // make the buf exactly the same layout than our last paragraph
2624         buf->makeSameLayout(lastbuffer);
2625
2626         // paste it!
2627         lastbuffer->next(buf);
2628         buf->previous(lastbuffer);
2629         mergeParagraph(buffer->params, paragraphs, lastbuffer);
2630 #else
2631         ParagraphList::iterator pit = plist.begin();
2632         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(),
2633                                                         new Paragraph(*pit, false));
2634         ++pit;
2635         mergeParagraph(buffer->params, paragraphs, boost::prior(ins));
2636
2637         ParagraphList::iterator pend = plist.end();
2638         for (; pit != pend; ++pit) {
2639                 paragraphs.push_back(new Paragraph(*pit, false));
2640         }
2641
2642 #endif
2643
2644         reinitLyXText();
2645 }
2646
2647
2648 void InsetText::addPreview(grfx::PreviewLoader & loader) const
2649 {
2650         ParagraphList::iterator pit = paragraphs.begin();
2651         ParagraphList::iterator pend = paragraphs.end();
2652
2653         for (; pit != pend; ++pit) {
2654                 InsetList::iterator it  = pit->insetlist.begin();
2655                 InsetList::iterator end = pit->insetlist.end();
2656                 for (; it != end; ++it) {
2657                         it.getInset()->addPreview(loader);
2658                 }
2659         }
2660 }