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