]> git.lyx.org Git - features.git/blob - src/insets/insettext.C
The Paste Recent patch
[features.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                 size_t sel_index = 0;
1254                 string const & arg = cmd.argument;
1255                 if (isStrUnsignedInt(arg)) {
1256                         size_t const paste_arg = strToUnsignedInt(arg);
1257 #warning FIXME Check if the arg is in the domain of available selections.
1258                         sel_index = paste_arg;
1259                 }
1260                 lt->pasteSelection(sel_index);
1261                 // bug 393
1262                 lt->clearSelection();
1263                 updwhat = CURSOR_PAR;
1264                 updflag = true;
1265                 break;
1266         }
1267
1268         case LFUN_BREAKPARAGRAPH:
1269                 if (!autoBreakRows) {
1270                         result = DISPATCHED;
1271                         break;
1272                 }
1273                 lt->breakParagraph(paragraphs, 0);
1274                 updwhat = CURSOR | FULL;
1275                 updflag = true;
1276                 break;
1277
1278         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
1279                 if (!autoBreakRows) {
1280                         result = DISPATCHED;
1281                         break;
1282                 }
1283                 lt->breakParagraph(paragraphs, 1);
1284                 updwhat = CURSOR | FULL;
1285                 updflag = true;
1286                 break;
1287
1288         case LFUN_BREAKLINE: {
1289                 if (!autoBreakRows) {
1290                         result = DISPATCHED;
1291                         break;
1292                 }
1293
1294                 lt->insertInset(new InsetNewline);
1295                 updwhat = CURSOR | CURSOR_PAR;
1296                 updflag = true;
1297                 break;
1298         }
1299
1300         case LFUN_LAYOUT:
1301                 // do not set layouts on non breakable textinsets
1302                 if (autoBreakRows) {
1303                         string cur_layout = cpar(bv)->layout()->name();
1304
1305                         // Derive layout number from given argument (string)
1306                         // and current buffer's textclass (number). */
1307                         LyXTextClass const & tclass =
1308                                 bv->buffer()->params.getLyXTextClass();
1309                         string layout = cmd.argument;
1310                         bool hasLayout = tclass.hasLayout(layout);
1311
1312                         // If the entry is obsolete, use the new one instead.
1313                         if (hasLayout) {
1314                                 string const & obs =
1315                                         tclass[layout]->obsoleted_by();
1316                                 if (!obs.empty())
1317                                         layout = obs;
1318                         }
1319
1320                         // see if we found the layout number:
1321                         if (!hasLayout) {
1322                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + cmd.argument + N_(" not known"));
1323                                 bv->owner()->dispatch(lf);
1324                                 break;
1325                         }
1326
1327                         if (cur_layout != layout) {
1328                                 cur_layout = layout;
1329                                 lt->setLayout(layout);
1330                                 bv->owner()->setLayout(cpar(bv)->layout()->name());
1331                                 updwhat = CURSOR_PAR;
1332                                 updflag = true;
1333                         }
1334                 } else {
1335                         // reset the layout box
1336                         bv->owner()->setLayout(cpar(bv)->layout()->name());
1337                 }
1338                 break;
1339         case LFUN_PARAGRAPH_SPACING:
1340                 // This one is absolutely not working. When fiddling with this
1341                 // it also seems to me that the paragraphs inside the insettext
1342                 // inherit bufferparams/paragraphparams in a strange way. (Lgb)
1343                 // FIXME: how old is this comment ? ...
1344         {
1345                 ParagraphList::iterator pit = lt->cursor.par();
1346                 Spacing::Space cur_spacing = pit->params().spacing().getSpace();
1347                 float cur_value = 1.0;
1348                 if (cur_spacing == Spacing::Other) {
1349                         cur_value = pit->params().spacing().getValue();
1350                 }
1351
1352                 istringstream istr(STRCONV(cmd.argument));
1353                 string tmp;
1354                 istr >> tmp;
1355                 Spacing::Space new_spacing = cur_spacing;
1356                 float new_value = cur_value;
1357                 if (tmp.empty()) {
1358                         lyxerr << "Missing argument to `paragraph-spacing'"
1359                                    << endl;
1360                 } else if (tmp == "single") {
1361                         new_spacing = Spacing::Single;
1362                 } else if (tmp == "onehalf") {
1363                         new_spacing = Spacing::Onehalf;
1364                 } else if (tmp == "double") {
1365                         new_spacing = Spacing::Double;
1366                 } else if (tmp == "other") {
1367                         new_spacing = Spacing::Other;
1368                         float tmpval = 0.0;
1369                         istr >> tmpval;
1370                         lyxerr << "new_value = " << tmpval << endl;
1371                         if (tmpval != 0.0)
1372                                 new_value = tmpval;
1373                 } else if (tmp == "default") {
1374                         new_spacing = Spacing::Default;
1375                 } else {
1376                         lyxerr << _("Unknown spacing argument: ")
1377                                    << cmd.argument << endl;
1378                 }
1379                 if (cur_spacing != new_spacing || cur_value != new_value) {
1380                         pit->params().spacing(Spacing(new_spacing, new_value));
1381                         updwhat = CURSOR_PAR;
1382                         updflag = true;
1383                 }
1384         }
1385         break;
1386
1387         // These need to do repaints but don't require
1388         // special handling otherwise. A *lot* of the
1389         // above could probably be done similarly ...
1390
1391         case LFUN_HOME:
1392         case LFUN_END:
1393         case LFUN_WORDLEFT:
1394         case LFUN_WORDRIGHT:
1395         // these two are really unhandled ...
1396         case LFUN_ENDBUF:
1397         case LFUN_BEGINNINGBUF:
1398                 updwhat = cursor_update;
1399                 if (!bv->dispatch(cmd))
1400                         result = UNDISPATCHED;
1401                 break;
1402
1403         case LFUN_RIGHTSEL:
1404         case LFUN_UPSEL:
1405         case LFUN_DOWNSEL:
1406         case LFUN_LEFTSEL:
1407         case LFUN_HOMESEL:
1408         case LFUN_ENDSEL:
1409         case LFUN_WORDLEFTSEL:
1410         case LFUN_WORDRIGHTSEL:
1411                 updwhat = SELECTION;
1412
1413                 // fallthrough
1414
1415         default:
1416                 if (!bv->dispatch(cmd))
1417                         result = UNDISPATCHED;
1418                 break;
1419         }
1420
1421         if (clear)
1422                 lt = 0;
1423         if (updwhat > 0)
1424                 updateLocal(bv, updwhat, updflag);
1425         /// If the action has deleted all text in the inset, we need to change the
1426         // language to the language of the surronding text.
1427         if (!was_empty && paragraphs.begin()->empty() &&
1428             boost::next(paragraphs.begin()) == paragraphs.end()) {
1429                 LyXFont font(LyXFont::ALL_IGNORE);
1430                 font.setLanguage(bv->getParentLanguage(this));
1431                 setFont(bv, font, false);
1432         }
1433
1434         if (result >= FINISHED)
1435                 bv->unlockInset(this);
1436
1437         if (result == DISPATCHED_NOUPDATE && (need_update & FULL))
1438                 result = DISPATCHED;
1439         return result;
1440 }
1441
1442
1443 int InsetText::latex(Buffer const * buf, ostream & os,
1444                      LatexRunParams const & runparams) const
1445 {
1446         TexRow texrow;
1447         latexParagraphs(buf, paragraphs, os, texrow, runparams);
1448         return texrow.rows();
1449 }
1450
1451
1452 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1453 {
1454         unsigned int lines = 0;
1455
1456         ParagraphList::const_iterator beg = paragraphs.begin();
1457         ParagraphList::const_iterator end = paragraphs.end();
1458         ParagraphList::const_iterator it = beg;
1459         for (; it != end; ++it) {
1460                 string const tmp = buf->asciiParagraph(*it, linelen, it == beg);
1461                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1462                 os << tmp;
1463         }
1464         return lines;
1465 }
1466
1467
1468 int InsetText::docbook(Buffer const * buf, ostream & os, bool mixcont) const
1469 {
1470         unsigned int lines = 0;
1471
1472         vector<string> environment_stack(10);
1473         vector<string> environment_inner(10);
1474
1475         int const command_depth = 0;
1476         string item_name;
1477
1478         Paragraph::depth_type depth = 0; // paragraph depth
1479
1480         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1481         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1482
1483         for (; pit != pend; ++pit) {
1484                 string sgmlparam;
1485                 int desc_on = 0; // description mode
1486
1487                 LyXLayout_ptr const & style = pit->layout();
1488
1489                 // environment tag closing
1490                 for (; depth > pit->params().depth(); --depth) {
1491                         if (environment_inner[depth] != "!-- --") {
1492                                 item_name = "listitem";
1493                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1494                                 if (environment_inner[depth] == "varlistentry")
1495                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1496                         }
1497                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1498                         environment_stack[depth].erase();
1499                         environment_inner[depth].erase();
1500                 }
1501
1502                 if (depth == pit->params().depth()
1503                    && environment_stack[depth] != style->latexname()
1504                    && !environment_stack[depth].empty()) {
1505                         if (environment_inner[depth] != "!-- --") {
1506                                 item_name= "listitem";
1507                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1508                                 if (environment_inner[depth] == "varlistentry")
1509                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1510                         }
1511
1512                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1513
1514                         environment_stack[depth].erase();
1515                         environment_inner[depth].erase();
1516                 }
1517
1518                 // Write opening SGML tags.
1519                 switch (style->latextype) {
1520                 case LATEX_PARAGRAPH:
1521                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1522                         break;
1523
1524                 case LATEX_COMMAND:
1525                         buf->sgmlError(pit, 0,  _("Error: LatexType Command not allowed here.\n"));
1526                         return -1;
1527                         break;
1528
1529                 case LATEX_ENVIRONMENT:
1530                 case LATEX_ITEM_ENVIRONMENT:
1531                         if (depth < pit->params().depth()) {
1532                                 depth = pit->params().depth();
1533                                 environment_stack[depth].erase();
1534                         }
1535
1536                         if (environment_stack[depth] != style->latexname()) {
1537                                 if (environment_stack.size() == depth + 1) {
1538                                         environment_stack.push_back("!-- --");
1539                                         environment_inner.push_back("!-- --");
1540                                 }
1541                                 environment_stack[depth] = style->latexname();
1542                                 environment_inner[depth] = "!-- --";
1543                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1544                         } else {
1545                                 if (environment_inner[depth] != "!-- --") {
1546                                         item_name= "listitem";
1547                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1548                                         if (environment_inner[depth] == "varlistentry")
1549                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1550                                 }
1551                         }
1552
1553                         if (style->latextype == LATEX_ENVIRONMENT) {
1554                                 if (!style->latexparam().empty()) {
1555                                         if (style->latexparam() == "CDATA")
1556                                                 os << "<![CDATA[";
1557                                         else
1558                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1559                                 }
1560                                 break;
1561                         }
1562
1563                         desc_on = (style->labeltype == LABEL_MANUAL);
1564
1565                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1566                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1567
1568                         item_name = desc_on ? "term" : "para";
1569                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1570
1571                         break;
1572                 default:
1573                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1574                         break;
1575                 }
1576
1577                 buf->simpleDocBookOnePar(os, pit, desc_on, depth + 1 + command_depth);
1578
1579                 string end_tag;
1580                 // write closing SGML tags
1581                 switch (style->latextype) {
1582                 case LATEX_ENVIRONMENT:
1583                         if (!style->latexparam().empty()) {
1584                                 if (style->latexparam() == "CDATA")
1585                                         os << "]]>";
1586                                 else
1587                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1588                         }
1589                         break;
1590                 case LATEX_ITEM_ENVIRONMENT:
1591                         if (desc_on == 1) break;
1592                         end_tag= "para";
1593                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1594                         break;
1595                 case LATEX_PARAGRAPH:
1596                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1597                         break;
1598                 default:
1599                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1600                         break;
1601                 }
1602         }
1603
1604         // Close open tags
1605         for (int d = depth; d >= 0; --d) {
1606                 if (!environment_stack[depth].empty()) {
1607                         if (environment_inner[depth] != "!-- --") {
1608                                 item_name = "listitem";
1609                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1610                                if (environment_inner[depth] == "varlistentry")
1611                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1612                         }
1613
1614                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1615                 }
1616         }
1617
1618         return lines;
1619 }
1620
1621
1622 void InsetText::validate(LaTeXFeatures & features) const
1623 {
1624         for_each(paragraphs.begin(), paragraphs.end(),
1625                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1626 }
1627
1628
1629 void InsetText::getCursor(BufferView & bv, int & x, int & y) const
1630 {
1631         if (the_locking_inset) {
1632                 the_locking_inset->getCursor(bv, x, y);
1633                 return;
1634         }
1635         x = cx(&bv);
1636         y = cy(&bv) + InsetText::y();
1637 }
1638
1639
1640 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1641 {
1642         if (the_locking_inset) {
1643                 the_locking_inset->getCursorPos(bv, x, y);
1644                 return;
1645         }
1646         x = cx(bv) - top_x - TEXT_TO_INSET_OFFSET;
1647         y = cy(bv) - TEXT_TO_INSET_OFFSET;
1648 }
1649
1650
1651 int InsetText::insetInInsetY() const
1652 {
1653         if (!the_locking_inset)
1654                 return 0;
1655
1656         return (inset_y + the_locking_inset->insetInInsetY());
1657 }
1658
1659
1660 void InsetText::fitInsetCursor(BufferView * bv) const
1661 {
1662         if (the_locking_inset) {
1663                 the_locking_inset->fitInsetCursor(bv);
1664                 return;
1665         }
1666         LyXFont const font =
1667                 getLyXText(bv)->getFont(bv->buffer(), cpar(bv), cpos(bv));
1668
1669         int const asc = font_metrics::maxAscent(font);
1670         int const desc = font_metrics::maxDescent(font);
1671
1672         if (bv->fitLockedInsetCursor(cx(bv), cy(bv), asc, desc))
1673                 need_update |= FULL;
1674 }
1675
1676
1677 Inset::RESULT
1678 InsetText::moveRight(BufferView * bv, bool activate_inset, bool selecting)
1679 {
1680         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1681                 return moveLeftIntern(bv, false, activate_inset, selecting);
1682         else
1683                 return moveRightIntern(bv, true, activate_inset, selecting);
1684 }
1685
1686
1687 Inset::RESULT
1688 InsetText::moveLeft(BufferView * bv, bool activate_inset, bool selecting)
1689 {
1690         if (getLyXText(bv)->cursor.par()->isRightToLeftPar(bv->buffer()->params))
1691                 return moveRightIntern(bv, true, activate_inset, selecting);
1692         else
1693                 return moveLeftIntern(bv, false, activate_inset, selecting);
1694 }
1695
1696
1697 Inset::RESULT
1698 InsetText::moveRightIntern(BufferView * bv, bool front,
1699                            bool activate_inset, bool selecting)
1700 {
1701         LyXText * text = getLyXText(bv);
1702
1703         ParagraphList::iterator c_par = cpar(bv);
1704
1705         if (boost::next(c_par) == paragraphs.end() &&
1706             (cpos(bv) >= c_par->size()))
1707                 return FINISHED_RIGHT;
1708         if (activate_inset && checkAndActivateInset(bv, front))
1709                 return DISPATCHED;
1710         text->cursorRight(bv);
1711         if (!selecting)
1712                 text->clearSelection();
1713         return DISPATCHED_NOUPDATE;
1714 }
1715
1716
1717 Inset::RESULT
1718 InsetText::moveLeftIntern(BufferView * bv, bool front,
1719                           bool activate_inset, bool selecting)
1720 {
1721         LyXText * text = getLyXText(bv);
1722
1723         if (cpar(bv) == paragraphs.begin() && (cpos(bv) <= 0))
1724                 return FINISHED;
1725         text->cursorLeft(bv);
1726         if (!selecting)
1727                 text->clearSelection();
1728         if (activate_inset && checkAndActivateInset(bv, front))
1729                 return DISPATCHED;
1730         return DISPATCHED_NOUPDATE;
1731 }
1732
1733
1734 Inset::RESULT InsetText::moveUp(BufferView * bv)
1735 {
1736         if (crow(bv) == getLyXText(bv)->rows().begin())
1737                 return FINISHED_UP;
1738         getLyXText(bv)->cursorUp(bv);
1739         getLyXText(bv)->clearSelection();
1740         return DISPATCHED_NOUPDATE;
1741 }
1742
1743
1744 Inset::RESULT InsetText::moveDown(BufferView * bv)
1745 {
1746         if (boost::next(crow(bv)) == getLyXText(bv)->rows().end())
1747                 return FINISHED_DOWN;
1748         getLyXText(bv)->cursorDown(bv);
1749         getLyXText(bv)->clearSelection();
1750         return DISPATCHED_NOUPDATE;
1751 }
1752
1753
1754 bool InsetText::insertInset(BufferView * bv, Inset * inset)
1755 {
1756         if (the_locking_inset) {
1757                 if (the_locking_inset->insetAllowed(inset))
1758                         return the_locking_inset->insertInset(bv, inset);
1759                 return false;
1760         }
1761         inset->setOwner(this);
1762         getLyXText(bv)->insertInset(inset);
1763         bv->fitCursor();
1764         updateLocal(bv, CURSOR_PAR|CURSOR, true);
1765         return true;
1766 }
1767
1768
1769 bool InsetText::insetAllowed(Inset::Code code) const
1770 {
1771         // in_insetAllowed is a really gross hack,
1772         // to allow us to call the owner's insetAllowed
1773         // without stack overflow, which can happen
1774         // when the owner uses InsetCollapsable::insetAllowed()
1775         bool ret = true;
1776         if (in_insetAllowed)
1777                 return ret;
1778         in_insetAllowed = true;
1779         if (the_locking_inset)
1780                 ret = the_locking_inset->insetAllowed(code);
1781         else if (owner())
1782                 ret = owner()->insetAllowed(code);
1783         in_insetAllowed = false;
1784         return ret;
1785 }
1786
1787
1788 UpdatableInset * InsetText::getLockingInset() const
1789 {
1790         return the_locking_inset ? the_locking_inset->getLockingInset() :
1791                 const_cast<InsetText *>(this);
1792 }
1793
1794
1795 UpdatableInset * InsetText::getFirstLockingInsetOfType(Inset::Code c)
1796 {
1797         if (c == lyxCode())
1798                 return this;
1799         if (the_locking_inset)
1800                 return the_locking_inset->getFirstLockingInsetOfType(c);
1801         return 0;
1802 }
1803
1804
1805 bool InsetText::showInsetDialog(BufferView * bv) const
1806 {
1807         if (the_locking_inset)
1808                 return the_locking_inset->showInsetDialog(bv);
1809         return false;
1810 }
1811
1812
1813 void InsetText::getLabelList(std::vector<string> & list) const
1814 {
1815         ParagraphList::const_iterator pit = paragraphs.begin();
1816         ParagraphList::const_iterator pend = paragraphs.end();
1817         for (; pit != pend; ++pit) {
1818                 InsetList::const_iterator beg = pit->insetlist.begin();
1819                 InsetList::const_iterator end = pit->insetlist.end();
1820                 for (; beg != end; ++beg)
1821                         beg->inset->getLabelList(list);
1822         }
1823 }
1824
1825
1826 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1827                         bool selectall)
1828 {
1829         if (the_locking_inset) {
1830                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1831                 return;
1832         }
1833         if ((boost::next(paragraphs.begin()) == paragraphs.end() &&
1834              paragraphs.begin()->empty()) || cpar(bv)->empty()) {
1835                 getLyXText(bv)->setFont(font, toggleall);
1836                 return;
1837         }
1838         bool clear = false;
1839         if (!lt) {
1840                 lt = getLyXText(bv);
1841                 clear = true;
1842         }
1843         if (lt->selection.set()) {
1844                 setUndo(bv, Undo::EDIT, lt->cursor.par());
1845         }
1846         if (selectall)
1847                 selectAll(bv);
1848         lt->toggleFree(font, toggleall);
1849         if (selectall)
1850                 lt->clearSelection();
1851         bv->fitCursor();
1852         bool flag = (selectall || lt->selection.set());
1853         if (clear)
1854                 lt = 0;
1855         if (flag)
1856                 updateLocal(bv, FULL, true);
1857         else
1858                 updateLocal(bv, CURSOR_PAR, true);
1859 }
1860
1861
1862 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1863 {
1864         if (cpar(bv)->isInset(cpos(bv))) {
1865                 Inset * inset =
1866                         static_cast<UpdatableInset*>(cpar(bv)->getInset(cpos(bv)));
1867                 if (!isHighlyEditableInset(inset))
1868                         return false;
1869                 FuncRequest cmd(bv, LFUN_INSET_EDIT, front ? "left" : "right");
1870                 inset->localDispatch(cmd);
1871                 if (!the_locking_inset)
1872                         return false;
1873                 updateLocal(bv, CURSOR, false);
1874                 return true;
1875         }
1876         return false;
1877 }
1878
1879
1880 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1881                                       mouse_button::state button)
1882 {
1883         x -= drawTextXOffset;
1884         int dummyx = x;
1885         int dummyy = y + dim_.asc;
1886         Inset * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1887         // we only do the edit() call if the inset was hit by the mouse
1888         // or if it is a highly editable inset. So we should call this
1889         // function from our own edit with button < 0.
1890         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1891         // WRONG
1892         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1893                 return false;
1894
1895         if (inset) {
1896                 if (x < 0)
1897                         x = dim_.wid;
1898                 if (y < 0)
1899                         y = dim_.des;
1900                 inset_x = cix(bv) - top_x + drawTextXOffset;
1901                 inset_y = ciy(bv) + drawTextYOffset;
1902                 FuncRequest cmd(bv, LFUN_INSET_EDIT, x - inset_x, y - inset_y, button);
1903                 inset->localDispatch(cmd);
1904                 if (!the_locking_inset)
1905                         return false;
1906                 updateLocal(bv, CURSOR, false);
1907                 return true;
1908         }
1909         return false;
1910 }
1911
1912
1913 int InsetText::getMaxWidth(BufferView * bv, UpdatableInset const * inset) const
1914 {
1915 #if 0
1916         int w = UpdatableInset::getMaxWidth(bv, inset);
1917         if (w < 0) {
1918                 return -1;
1919         }
1920         if (owner()) {
1921                 w = w - top_x + owner()->x();
1922                 return w;
1923         }
1924         w -= (2 * TEXT_TO_INSET_OFFSET);
1925         return w - top_x;
1926 #else
1927         return UpdatableInset::getMaxWidth(bv, inset);
1928 #endif
1929 }
1930
1931
1932 void InsetText::setParagraphData(ParagraphList const & plist)
1933 {
1934         // we have to unlock any locked inset otherwise we're in troubles
1935         the_locking_inset = 0;
1936
1937         // But it it makes no difference that is a lot better.
1938 #warning FIXME.
1939         // See if this can be simplified when std::list is in effect.
1940         paragraphs.clear();
1941
1942         ParagraphList::const_iterator it = plist.begin();
1943         ParagraphList::const_iterator end = plist.end();
1944         for (; it != end; ++it) {
1945                 paragraphs.push_back(*it);
1946                 Paragraph & tmp = paragraphs.back();
1947                 tmp.setInsetOwner(this);
1948         }
1949
1950         reinitLyXText();
1951         need_update = INIT;
1952 }
1953
1954
1955 void InsetText::markNew(bool track_changes)
1956 {
1957         ParagraphList::iterator pit = paragraphs.begin();
1958         ParagraphList::iterator pend = paragraphs.end();
1959         for (; pit != pend; ++pit) {
1960                 if (track_changes) {
1961                         pit->trackChanges();
1962                 } else {
1963                         // no-op when not tracking
1964                         pit->cleanChanges();
1965                 }
1966         }
1967 }
1968
1969
1970 void InsetText::setText(string const & data, LyXFont const & font)
1971 {
1972         clear(false);
1973         for (unsigned int i = 0; i < data.length(); ++i)
1974                 paragraphs.begin()->insertChar(i, data[i], font);
1975         reinitLyXText();
1976 }
1977
1978
1979 void InsetText::setAutoBreakRows(bool flag)
1980 {
1981         if (flag != autoBreakRows) {
1982                 autoBreakRows = flag;
1983                 if (!flag)
1984                         removeNewlines();
1985                 need_update = INIT;
1986         }
1987 }
1988
1989
1990 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
1991 {
1992         if (how != drawFrame_) {
1993                 drawFrame_ = how;
1994                 if (bv)
1995                         updateLocal(bv, DRAW_FRAME, false);
1996         }
1997 }
1998
1999
2000 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
2001 {
2002         if (frame_color != col) {
2003                 frame_color = col;
2004                 if (bv)
2005                         updateLocal(bv, DRAW_FRAME, false);
2006         }
2007 }
2008
2009
2010 int InsetText::cx(BufferView * bv) const
2011 {
2012         // we do nothing dangerous so we use a local cache
2013         LyXText * llt = getLyXText(bv);
2014         int x = llt->cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
2015         if (the_locking_inset) {
2016                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2017                                             llt->cursor.pos());
2018                 if (font.isVisibleRightToLeft())
2019                         x -= the_locking_inset->width(bv, font);
2020         }
2021         return x;
2022 }
2023
2024
2025 int InsetText::cix(BufferView * bv) const
2026 {
2027         // we do nothing dangerous so we use a local cache
2028         LyXText * llt = getLyXText(bv);
2029         int x = llt->cursor.ix() + top_x + TEXT_TO_INSET_OFFSET;
2030         if (the_locking_inset) {
2031                 LyXFont font = llt->getFont(bv->buffer(), llt->cursor.par(),
2032                                             llt->cursor.pos());
2033                 if (font.isVisibleRightToLeft())
2034                         x -= the_locking_inset->width(bv, font);
2035         }
2036         return x;
2037 }
2038
2039
2040 int InsetText::cy(BufferView * bv) const
2041 {
2042         LyXFont font;
2043         return getLyXText(bv)->cursor.y() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2044 }
2045
2046
2047 int InsetText::ciy(BufferView * bv) const
2048 {
2049         LyXFont font;
2050         return getLyXText(bv)->cursor.iy() - ascent(bv, font) + TEXT_TO_INSET_OFFSET;
2051 }
2052
2053
2054 pos_type InsetText::cpos(BufferView * bv) const
2055 {
2056         return getLyXText(bv)->cursor.pos();
2057 }
2058
2059
2060 ParagraphList::iterator InsetText::cpar(BufferView * bv) const
2061 {
2062         return getLyXText(bv)->cursor.par();
2063 }
2064
2065
2066 bool InsetText::cboundary(BufferView * bv) const
2067 {
2068         return getLyXText(bv)->cursor.boundary();
2069 }
2070
2071
2072 RowList::iterator InsetText::crow(BufferView * bv) const
2073 {
2074         return getLyXText(bv)->cursor.row();
2075 }
2076
2077
2078 LyXText * InsetText::getLyXText(BufferView const * lbv,
2079                                 bool const recursive) const
2080 {
2081         if (cached_bview == lbv) {
2082                 if (recursive && the_locking_inset)
2083                         return the_locking_inset->getLyXText(lbv, true);
2084                 LyXText * lt = cached_text.get();
2085                 lyx::Assert(lt && lt->rows().begin()->par() == const_cast<ParagraphList&>(paragraphs).begin());
2086                 return lt;
2087         }
2088         // Super UGLY! (Lgb)
2089         BufferView * bv = const_cast<BufferView *>(lbv);
2090
2091         cached_bview = bv;
2092         Cache::iterator it = cache.find(bv);
2093
2094         if (it != cache.end()) {
2095                 if (do_reinit) {
2096                         reinitLyXText();
2097                 } else if (do_resize) {
2098                         resizeLyXText(do_resize);
2099                 } else {
2100                         if (lt || !it->second.remove) {
2101                                 lyx::Assert(it->second.text.get());
2102                                 cached_text = it->second.text;
2103                                 if (recursive && the_locking_inset) {
2104                                         return the_locking_inset->getLyXText(bv, true);
2105                                 }
2106                                 return cached_text.get();
2107                         } else if (it->second.remove) {
2108                                 if (locked) {
2109                                         saveLyXTextState(it->second.text.get());
2110                                 } else {
2111                                         sstate.lpar = const_cast<ParagraphList&>(paragraphs).end();
2112                                 }
2113                         }
2114                         //
2115                         // when we have to reinit the existing LyXText!
2116                         //
2117                         it->second.text->init(bv);
2118                         restoreLyXTextState(it->second.text.get());
2119                         it->second.remove = false;
2120                 }
2121                 cached_text = it->second.text;
2122                 if (the_locking_inset && recursive) {
2123                         return the_locking_inset->getLyXText(bv);
2124                 }
2125                 return cached_text.get();
2126         }
2127         ///
2128         // we are here only if we don't have a BufferView * in the cache!!!
2129         ///
2130         cached_text.reset(new LyXText(bv, const_cast<InsetText *>(this)));
2131         cached_text->init(bv);
2132         restoreLyXTextState(cached_text.get());
2133
2134         cache.insert(make_pair(bv, cached_text));
2135
2136         if (the_locking_inset && recursive) {
2137                 return the_locking_inset->getLyXText(bv);
2138         }
2139         return cached_text.get();
2140 }
2141
2142
2143 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
2144 {
2145         cached_bview = 0;
2146
2147         Cache::iterator it = cache.find(bv);
2148
2149         if (it == cache.end()) {
2150                 return;
2151         }
2152
2153         lyx::Assert(it->second.text.get());
2154
2155         it->second.remove = true;
2156         if (recursive) {
2157                 /// then remove all LyXText in text-insets
2158                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
2159                          const_cast<ParagraphList&>(paragraphs).end(),
2160                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
2161         }
2162 }
2163
2164
2165 void InsetText::resizeLyXText(BufferView * bv, bool force) const
2166 {
2167         if (lt) {
2168                 // we cannot resize this because we are in use!
2169                 // so do this on the next possible getLyXText()
2170                 do_resize = bv;
2171                 return;
2172         }
2173         do_resize = 0;
2174         if (boost::next(paragraphs.begin()) == paragraphs.end() &&
2175             paragraphs.begin()->empty()) { // no data, resize not neccessary!
2176                 // we have to do this as a fixed width may have changed!
2177                 LyXText * t = getLyXText(bv);
2178                 saveLyXTextState(t);
2179                 t->init(bv, true);
2180                 restoreLyXTextState(t);
2181                 return;
2182         }
2183         // one endless line, resize normally not necessary
2184         if (!force && getMaxWidth(bv, this) < 0)
2185                 return;
2186
2187         Cache::iterator it = cache.find(bv);
2188         if (it == cache.end()) {
2189                 return;
2190         }
2191         lyx::Assert(it->second.text.get());
2192
2193         LyXText * t = it->second.text.get();
2194         saveLyXTextState(t);
2195
2196         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
2197                  const_cast<ParagraphList&>(paragraphs).end(),
2198                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2199
2200         t->init(bv, true);
2201         restoreLyXTextState(t);
2202         if (the_locking_inset) {
2203                 inset_x = cix(bv) - top_x + drawTextXOffset;
2204                 inset_y = ciy(bv) + drawTextYOffset;
2205         }
2206
2207         t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2208         if (!owner()) {
2209                 const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2210                 // this will scroll the screen such that the cursor becomes visible
2211                 bv->updateScrollbar();
2212         } else {
2213                 need_update |= FULL;
2214         }
2215 }
2216
2217
2218 void InsetText::reinitLyXText() const
2219 {
2220         if (lt) {
2221                 // we cannot resize this because we are in use!
2222                 // so do this on the next possible getLyXText()
2223                 do_reinit = true;
2224                 return;
2225         }
2226         do_reinit = false;
2227         do_resize = 0;
2228         for (Cache::iterator it = cache.begin(); it != cache.end(); ++it) {
2229                 lyx::Assert(it->second.text.get());
2230
2231                 LyXText * t = it->second.text.get();
2232                 BufferView * bv = it->first;
2233
2234                 saveLyXTextState(t);
2235
2236                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
2237                          const_cast<ParagraphList&>(paragraphs).end(),
2238                          boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2239
2240                 t->init(bv, true);
2241                 restoreLyXTextState(t);
2242                 if (the_locking_inset) {
2243                         inset_x = cix(bv) - top_x + drawTextXOffset;
2244                         inset_y = ciy(bv) + drawTextYOffset;
2245                 }
2246                 t->top_y(bv->screen().topCursorVisible(t->cursor, t->top_y()));
2247                 if (!owner()) {
2248                         const_cast<InsetText*>(this)->updateLocal(bv, FULL, false);
2249                         // this will scroll the screen such that the cursor becomes visible
2250                         bv->updateScrollbar();
2251                 } else {
2252                         need_update = FULL;
2253                 }
2254         }
2255 }
2256
2257
2258 void InsetText::removeNewlines()
2259 {
2260         bool changed = false;
2261
2262         ParagraphList::iterator it = paragraphs.begin();
2263         ParagraphList::iterator end = paragraphs.end();
2264         for (; it != end; ++it) {
2265                 for (int i = 0; i < it->size(); ++i) {
2266                         if (it->isNewline(i)) {
2267                                 changed = true;
2268                                 it->erase(i);
2269                         }
2270                 }
2271         }
2272         if (changed)
2273                 reinitLyXText();
2274 }
2275
2276
2277 bool InsetText::nodraw() const
2278 {
2279         if (the_locking_inset)
2280                 return the_locking_inset->nodraw();
2281         return UpdatableInset::nodraw();
2282 }
2283
2284
2285 int InsetText::scroll(bool recursive) const
2286 {
2287         int sx = UpdatableInset::scroll(false);
2288
2289         if (recursive && the_locking_inset)
2290                 sx += the_locking_inset->scroll(recursive);
2291
2292         return sx;
2293 }
2294
2295
2296 void InsetText::selectAll(BufferView * bv)
2297 {
2298         getLyXText(bv)->cursorTop();
2299         getLyXText(bv)->selection.cursor = getLyXText(bv)->cursor;
2300         getLyXText(bv)->cursorBottom();
2301         getLyXText(bv)->setSelection();
2302 }
2303
2304
2305 void InsetText::clearSelection(BufferView * bv)
2306 {
2307         getLyXText(bv)->clearSelection();
2308 }
2309
2310
2311 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
2312 {
2313         Painter & pain = bv->painter();
2314         int w = dim_.wid;
2315         int h = dim_.asc + dim_.des;
2316         int ty = baseline - dim_.asc;
2317
2318         if (ty < 0) {
2319                 h += ty;
2320                 ty = 0;
2321         }
2322         if ((ty + h) > pain.paperHeight())
2323                 h = pain.paperHeight();
2324         if ((top_x + drawTextXOffset + w) > pain.paperWidth())
2325                 w = pain.paperWidth();
2326         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
2327         need_update = FULL;
2328 }
2329
2330
2331 ParagraphList * InsetText::getParagraphs(int i) const
2332 {
2333         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
2334 }
2335
2336
2337 LyXCursor const & InsetText::cursor(BufferView * bv) const
2338 {
2339         if (the_locking_inset)
2340                 return the_locking_inset->cursor(bv);
2341         return getLyXText(bv)->cursor;
2342 }
2343
2344
2345 Inset * InsetText::getInsetFromID(int id_arg) const
2346 {
2347         if (id_arg == id())
2348                 return const_cast<InsetText *>(this);
2349
2350         ParagraphList::const_iterator pit = paragraphs.begin();
2351         ParagraphList::const_iterator pend = paragraphs.end();
2352         for (; pit != pend; ++pit) {
2353                 InsetList::const_iterator it = pit->insetlist.begin();
2354                 InsetList::const_iterator end = pit->insetlist.end();
2355                 for (; it != end; ++it) {
2356                         if (it->inset->id() == id_arg)
2357                                 return it->inset;
2358                         Inset * in = it->inset->getInsetFromID(id_arg);
2359                         if (in)
2360                                 return in;
2361                 }
2362         }
2363         return 0;
2364 }
2365
2366
2367 WordLangTuple const
2368 InsetText::selectNextWordToSpellcheck(BufferView * bv,
2369                                       float & value) const
2370 {
2371         bool clear = false;
2372         WordLangTuple word;
2373
2374         if (!lt) {
2375                 lt = getLyXText(bv);
2376                 clear = true;
2377         }
2378         if (the_locking_inset) {
2379                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
2380                 if (!word.word().empty()) {
2381                         value += cy(bv);
2382                         if (clear)
2383                                 lt = 0;
2384                         return word;
2385                 }
2386                 // we have to go on checking so move cursor to the next char
2387                 lt->cursor.pos(lt->cursor.pos() + 1);
2388         }
2389         word = lt->selectNextWordToSpellcheck(value);
2390         if (word.word().empty())
2391                 bv->unlockInset(const_cast<InsetText *>(this));
2392         else
2393                 value = cy(bv);
2394         if (clear)
2395                 lt = 0;
2396         return word;
2397 }
2398
2399
2400 void InsetText::selectSelectedWord(BufferView * bv)
2401 {
2402         if (the_locking_inset) {
2403                 the_locking_inset->selectSelectedWord(bv);
2404                 return;
2405         }
2406         getLyXText(bv)->selectSelectedWord();
2407         updateLocal(bv, SELECTION, false);
2408 }
2409
2410
2411 void InsetText::toggleSelection(BufferView * bv, bool kill_selection)
2412 {
2413         if (the_locking_inset) {
2414                 the_locking_inset->toggleSelection(bv, kill_selection);
2415         }
2416         bool clear = false;
2417         if (!lt) {
2418                 lt = getLyXText(bv);
2419                 clear = true;
2420         }
2421
2422         int x = top_x + TEXT_TO_INSET_OFFSET;
2423
2424         RowList::iterator rowit = lt->rows().begin();
2425         RowList::iterator end = lt->rows().end();
2426         int y_offset = top_baseline - rowit->ascent_of_text();
2427         int y = y_offset;
2428         while ((rowit != end) && ((y + rowit->height()) <= 0)) {
2429                 y += rowit->height();
2430                 ++rowit;
2431         }
2432         if (y_offset < 0)
2433                 y_offset = y;
2434
2435         if (need_update & SELECTION)
2436                 need_update = NONE;
2437         bv->screen().toggleSelection(lt, bv, kill_selection, y_offset, x);
2438         if (clear)
2439                 lt = 0;
2440 }
2441
2442
2443 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
2444 {
2445         bool clear = false;
2446         if (!lt) {
2447                 lt = getLyXText(bv);
2448                 clear = true;
2449         }
2450         if (the_locking_inset) {
2451                 if (the_locking_inset->nextChange(bv, length))
2452                         return true;
2453                 lt->cursorRight(true);
2454         }
2455         lyxfind::SearchResult result =
2456                 lyxfind::findNextChange(bv, lt, length);
2457
2458         if (result == lyxfind::SR_FOUND) {
2459                 LyXCursor cur = lt->cursor;
2460                 bv->unlockInset(bv->theLockingInset());
2461                 if (bv->lockInset(this))
2462                         locked = true;
2463                 lt->cursor = cur;
2464                 lt->setSelectionRange(length);
2465                 updateLocal(bv, SELECTION, false);
2466         }
2467         if (clear)
2468                 lt = 0;
2469         return result != lyxfind::SR_NOT_FOUND;
2470 }
2471
2472
2473 bool InsetText::searchForward(BufferView * bv, string const & str,
2474                               bool cs, bool mw)
2475 {
2476         bool clear = false;
2477         if (!lt) {
2478                 lt = getLyXText(bv);
2479                 clear = true;
2480         }
2481         if (the_locking_inset) {
2482                 if (the_locking_inset->searchForward(bv, str, cs, mw))
2483                         return true;
2484                 lt->cursorRight(true);
2485         }
2486         lyxfind::SearchResult result =
2487                 lyxfind::LyXFind(bv, lt, str, true, cs, mw);
2488
2489         if (result == lyxfind::SR_FOUND) {
2490                 LyXCursor cur = lt->cursor;
2491                 bv->unlockInset(bv->theLockingInset());
2492                 if (bv->lockInset(this))
2493                         locked = true;
2494                 lt->cursor = cur;
2495                 lt->setSelectionRange(str.length());
2496                 updateLocal(bv, SELECTION, false);
2497         }
2498         if (clear)
2499                 lt = 0;
2500         return (result != lyxfind::SR_NOT_FOUND);
2501 }
2502
2503 bool InsetText::searchBackward(BufferView * bv, string const & str,
2504                                bool cs, bool mw)
2505 {
2506         if (the_locking_inset) {
2507                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2508                         return true;
2509         }
2510         bool clear = false;
2511         if (!lt) {
2512                 lt = getLyXText(bv);
2513                 clear = true;
2514         }
2515         if (!locked) {
2516                 ParagraphList::iterator pit = paragraphs.begin();
2517                 ParagraphList::iterator pend = paragraphs.end();
2518
2519                 while (boost::next(pit) != pend)
2520                         ++pit;
2521
2522                 lt->setCursor(pit, pit->size());
2523         }
2524         lyxfind::SearchResult result =
2525                 lyxfind::LyXFind(bv, lt, str, false, cs, mw);
2526
2527         if (result == lyxfind::SR_FOUND) {
2528                 LyXCursor cur = lt->cursor;
2529                 bv->unlockInset(bv->theLockingInset());
2530                 if (bv->lockInset(this))
2531                         locked = true;
2532                 lt->cursor = cur;
2533                 lt->setSelectionRange(str.length());
2534                 updateLocal(bv, SELECTION, false);
2535         }
2536         if (clear)
2537                 lt = 0;
2538         return (result != lyxfind::SR_NOT_FOUND);
2539 }
2540
2541
2542 bool InsetText::checkInsertChar(LyXFont & font)
2543 {
2544         if (owner())
2545                 return owner()->checkInsertChar(font);
2546         return true;
2547 }
2548
2549
2550 void InsetText::collapseParagraphs(BufferView * bv)
2551 {
2552         LyXText * llt = getLyXText(bv);
2553
2554         while (boost::next(paragraphs.begin()) != paragraphs.end()) {
2555                 if (!paragraphs.begin()->empty() &&
2556                     !boost::next(paragraphs.begin())->empty() &&
2557                         !paragraphs.begin()->isSeparator(paragraphs.begin()->size() - 1))
2558                 {
2559                         paragraphs.begin()->insertChar(paragraphs.begin()->size(), ' ');
2560                 }
2561                 if (llt->selection.set()) {
2562                         if (llt->selection.start.par() == boost::next(paragraphs.begin())) {
2563                                 llt->selection.start.par(paragraphs.begin());
2564                                 llt->selection.start.pos(
2565                                         llt->selection.start.pos() + paragraphs.begin()->size());
2566                         }
2567                         if (llt->selection.end.par() == boost::next(paragraphs.begin())) {
2568                                 llt->selection.end.par(paragraphs.begin());
2569                                 llt->selection.end.pos(
2570                                         llt->selection.end.pos() + paragraphs.begin()->size());
2571                         }
2572                 }
2573                 mergeParagraph(bv->buffer()->params, paragraphs, paragraphs.begin());
2574         }
2575         reinitLyXText();
2576 }
2577
2578
2579 void InsetText::getDrawFont(LyXFont & font) const
2580 {
2581         if (!owner())
2582                 return;
2583         owner()->getDrawFont(font);
2584 }
2585
2586
2587 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
2588 {
2589 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
2590 // And it probably does. You have to take a look at this John. (Lgb)
2591 #warning John, have a look here. (Lgb)
2592         ParagraphList::iterator pit = plist.begin();
2593         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(), *pit);
2594         ++pit;
2595         mergeParagraph(buffer->params, paragraphs, boost::prior(ins));
2596
2597         ParagraphList::iterator pend = plist.end();
2598         for (; pit != pend; ++pit) {
2599                 paragraphs.push_back(*pit);
2600         }
2601
2602         reinitLyXText();
2603 }
2604
2605
2606 void InsetText::addPreview(grfx::PreviewLoader & loader) const
2607 {
2608         ParagraphList::const_iterator pit = paragraphs.begin();
2609         ParagraphList::const_iterator pend = paragraphs.end();
2610
2611         for (; pit != pend; ++pit) {
2612                 InsetList::const_iterator it  = pit->insetlist.begin();
2613                 InsetList::const_iterator end = pit->insetlist.end();
2614                 for (; it != end; ++it) {
2615                         it->inset->addPreview(loader);
2616                 }
2617         }
2618 }