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