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