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