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