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