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