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