]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
more not-so-useful stuff removed
[lyx.git] / src / insets / insettext.C
1 /**
2  * \file insettext.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  *
8  * Full author contact details are available in file CREDITS
9  */
10
11 #include <config.h>
12
13 #include "insettext.h"
14
15 #include "buffer.h"
16 #include "BufferView.h"
17 #include "bufferview_funcs.h"
18 #include "CutAndPaste.h"
19 #include "debug.h"
20 #include "dimension.h"
21 #include "funcrequest.h"
22 #include "gettext.h"
23 #include "errorlist.h"
24 #include "intl.h"
25 #include "LaTeXFeatures.h"
26 #include "LColor.h"
27 #include "Lsstream.h"
28 #include "lyxfont.h"
29 #include "lyxcursor.h"
30 #include "lyxfind.h"
31 #include "lyxlex.h"
32 #include "lyxrow.h"
33 #include "lyxrc.h"
34 #include "lyxtext.h"
35 #include "paragraph.h"
36 #include "ParagraphParameters.h"
37 #include "trans_mgr.h"
38 #include "undo_funcs.h"
39 #include "WordLangTuple.h"
40 #include "paragraph_funcs.h"
41 #include "sgml.h"
42 #include "rowpainter.h"
43 #include "insetnewline.h"
44 #include "metricsinfo.h"
45
46 #include "frontends/Alert.h"
47 #include "frontends/Dialogs.h"
48 #include "frontends/font_metrics.h"
49 #include "frontends/LyXView.h"
50 #include "frontends/Painter.h"
51 #include "frontends/screen.h"
52
53 #include "support/textutils.h"
54 #include "support/LAssert.h"
55 #include "support/lstrings.h"
56 #include "support/lyxalgo.h" // lyx::count
57
58 #include <boost/bind.hpp>
59
60 #include <fstream>
61 #include <algorithm>
62 #include <cstdlib>
63
64 using std::ostream;
65 using std::ifstream;
66 using std::endl;
67 using std::min;
68 using std::max;
69 using std::make_pair;
70 using std::vector;
71 using std::pair;
72 using std::for_each;
73 using std::auto_ptr;
74
75 using namespace lyx::support;
76 using namespace lyx::graphics;
77 using namespace bv_funcs;
78
79 using lyx::pos_type;
80 using lyx::textclass_type;
81
82
83 // we should get rid of these (Andre')
84
85 void InsetText::saveLyXTextState() const
86 {
87         // check if my paragraphs are still valid
88         ParagraphList::iterator it = const_cast<ParagraphList&>(paragraphs).begin();
89         ParagraphList::iterator end = const_cast<ParagraphList&>(paragraphs).end();
90         for (; it != end; ++it)
91                 if (it == text_.cursor.par())
92                         break;
93
94         if (it != end && text_.cursor.pos() <= it->size())
95                 sstate = text_; // slicing intended
96         else
97                 sstate.cursor.par(end);
98 }
99
100
101 void InsetText::restoreLyXTextState() const
102 {
103         if (sstate.cursor.par() == const_cast<ParagraphList&>(paragraphs).end())
104                 return;
105
106         text_.selection.set(true);
107         // at this point just to avoid the DEPM when setting the cursor
108         text_.selection.mark(sstate.selection.mark());
109         if (sstate.selection.set()) {
110                 text_.setCursor(sstate.selection.start.par(),
111                         sstate.selection.start.pos(),
112                         true, sstate.selection.start.boundary());
113                 text_.selection.cursor = text_.cursor;
114                 text_.setCursor(sstate.selection.end.par(), sstate.selection.end.pos(),
115                         true, sstate.selection.end.boundary());
116                 text_.setSelection();
117                 text_.setCursor(sstate.cursor.par(), sstate.cursor.pos());
118         } else {
119                 text_.setCursor(sstate.cursor.par(), sstate.cursor.pos(),
120                         true, sstate.cursor.boundary());
121                 text_.selection.cursor = text_.cursor;
122                 text_.selection.set(false);
123         }
124 }
125
126
127 InsetText::InsetText(BufferParams const & bp)
128         : UpdatableInset(), text_(0, this)
129 {
130         paragraphs.push_back(Paragraph());
131         paragraphs.begin()->layout(bp.getLyXTextClass().defaultLayout());
132         if (bp.tracking_changes)
133                 paragraphs.begin()->trackChanges();
134         init(0);
135 }
136
137
138 InsetText::InsetText(InsetText const & in)
139         : UpdatableInset(in), text_(0, this)
140 {
141         init(&in);
142 }
143
144
145 InsetText & InsetText::operator=(InsetText const & it)
146 {
147         init(&it);
148         return *this;
149 }
150
151
152 void InsetText::init(InsetText const * ins)
153 {
154         if (ins) {
155                 textwidth_ = ins->textwidth_;
156                 text_.bv_owner = ins->text_.bv_owner;
157
158                 paragraphs = ins->paragraphs;
159
160                 ParagraphList::iterator pit = paragraphs.begin();
161                 ParagraphList::iterator end = paragraphs.end();
162                 for (; pit != end; ++pit)
163                         pit->setInsetOwner(this);
164
165                 reinitLyXText();
166
167                 autoBreakRows = ins->autoBreakRows;
168                 drawFrame_ = ins->drawFrame_;
169                 frame_color = ins->frame_color;
170         } else {
171                 textwidth_ = 0; // broken
172                 drawFrame_ = NEVER;
173                 frame_color = LColor::insetframe;
174                 autoBreakRows = false;
175         }
176         the_locking_inset = 0;
177         for_each(paragraphs.begin(), paragraphs.end(),
178                  boost::bind(&Paragraph::setInsetOwner, _1, this));
179         top_y = 0;
180         no_selection = true;
181         drawTextXOffset = 0;
182         drawTextYOffset = 0;
183         locked = false;
184         old_par = paragraphs.end();
185         sstate.cursor.par(paragraphs.end());
186         in_insetAllowed = false;
187 }
188
189
190 void InsetText::clear(bool just_mark_erased)
191 {
192         if (just_mark_erased) {
193                 ParagraphList::iterator it = paragraphs.begin();
194                 ParagraphList::iterator end = paragraphs.end();
195                 for (; it != end; ++it) {
196                         it->markErased();
197                 }
198                 return;
199         }
200
201         // This is a gross hack...
202         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
203
204         paragraphs.clear();
205         paragraphs.push_back(Paragraph());
206         paragraphs.begin()->setInsetOwner(this);
207         paragraphs.begin()->layout(old_layout);
208
209         reinitLyXText();
210 }
211
212
213 auto_ptr<InsetBase> InsetText::clone() const
214 {
215         return auto_ptr<InsetBase>(new InsetText(*this));
216 }
217
218
219 void InsetText::write(Buffer const * buf, ostream & os) const
220 {
221         os << "Text\n";
222         writeParagraphData(buf, os);
223 }
224
225
226 void InsetText::writeParagraphData(Buffer const * buf, ostream & os) const
227 {
228         ParagraphList::const_iterator it = paragraphs.begin();
229         ParagraphList::const_iterator end = paragraphs.end();
230         Paragraph::depth_type dth = 0;
231         for (; it != end; ++it) {
232                 it->write(buf, os, buf->params, dth);
233         }
234 }
235
236
237 void InsetText::read(Buffer const * buf, LyXLex & lex)
238 {
239         string token;
240         Paragraph::depth_type depth = 0;
241
242         clear(false);
243
244         if (buf->params.tracking_changes)
245                 paragraphs.begin()->trackChanges();
246
247         // delete the initial paragraph
248         paragraphs.clear();
249         ParagraphList::iterator pit = paragraphs.begin();
250
251         while (lex.isOK()) {
252                 lex.nextToken();
253                 token = lex.getString();
254                 if (token.empty())
255                         continue;
256                 if (token == "\\end_inset") {
257                         break;
258                 }
259
260                 if (token == "\\end_document") {
261                         lex.printError("\\end_document read in inset! Error in document!");
262                         return;
263                 }
264
265                 // FIXME: ugly.
266                 const_cast<Buffer*>(buf)->readParagraph(lex, token, paragraphs, pit, depth);
267         }
268
269         pit = paragraphs.begin();
270         ParagraphList::iterator const end = paragraphs.end();
271         for (; pit != end; ++pit)
272                 pit->setInsetOwner(this);
273
274         if (token != "\\end_inset") {
275                 lex.printError("Missing \\end_inset at this point. "
276                                            "Read: `$$Token'");
277         }
278 }
279
280
281 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
282 {
283         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
284
285         textwidth_ = mi.base.textwidth;
286         BufferView * bv = mi.base.bv;
287         setViewCache(bv);
288         text_.metrics(mi, dim);
289         dim.asc += TEXT_TO_INSET_OFFSET;
290         dim.des += TEXT_TO_INSET_OFFSET;
291         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
292         dim.wid = max(dim.wid, 10);
293         dim_ = dim;
294 }
295
296
297 int InsetText::textWidth() const
298 {
299         return textwidth_;
300 }
301
302
303 void InsetText::draw(PainterInfo & pi, int x, int baseline) const
304 {
305         // update our idea of where we are. Clearly, we should
306         // not have to know this information.
307         top_x = x;
308
309         int const start_x = x;
310
311         BufferView * bv = pi.base.bv;
312         Painter & pain = pi.pain;
313
314         // repaint the background if needed
315         if (backgroundColor() != LColor::background)
316                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, baseline);
317
318         // no draw is necessary !!!
319         if (drawFrame_ == LOCKED && !locked && paragraphs.begin()->empty()) {
320                 top_baseline = baseline;
321                 return;
322         }
323
324         bv->hideCursor();
325
326         if (!owner())
327                 x += scroll();
328
329         top_baseline = baseline;
330         top_y = baseline - dim_.asc;
331
332         if (the_locking_inset && cpar() == inset_par && cpos() == inset_pos) {
333                 inset_x = cix() - x + drawTextXOffset;
334                 inset_y = ciy() + drawTextYOffset;
335         }
336
337         x += TEXT_TO_INSET_OFFSET;
338
339         RowList::iterator rit = text_.rows().begin();
340         RowList::iterator end = text_.rows().end();
341
342         int y_offset = baseline - rit->ascent_of_text();
343         int y2 = pain.paperHeight();
344         int first = 0;
345         int y = y_offset;
346         while (rit != end && y + rit->height() <= 0) {
347                 y += rit->height();
348                 first += rit->height();
349                 ++rit;
350         }
351         if (y_offset < 0) {
352                 text_.top_y(-y_offset);
353                 first = y;
354                 y_offset = 0;
355         } else {
356                 text_.top_y(first);
357                 first = 0;
358         }
359
360         int yo = y_offset + first;
361
362         paintRows(*bv, text_, rit, x, 0, yo, y2, yo);
363
364         if (drawFrame_ == ALWAYS || (drawFrame_ == LOCKED && locked))
365                 drawFrame(pain, int(start_x));
366 }
367
368
369 void InsetText::drawFrame(Painter & pain, int x) const
370 {
371         int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
372         int const frame_x = x + ttoD2;
373         int const frame_y = top_baseline - dim_.asc + ttoD2;
374         int const frame_w = dim_.wid - TEXT_TO_INSET_OFFSET;
375         int const frame_h = dim_.asc + dim_.des - TEXT_TO_INSET_OFFSET;
376         pain.rectangle(frame_x, frame_y, frame_w, frame_h, frame_color);
377 }
378
379
380 void InsetText::updateLocal(BufferView * bv, bool /*mark_dirty*/)
381 {
382         if (!bv)
383                 return;
384
385         if (!autoBreakRows && paragraphs.size() > 1)
386                 collapseParagraphs(bv);
387
388         text_.partialRebreak();
389         if (!text_.selection.set())
390                 text_.selection.cursor = text_.cursor;
391
392         bv->fitCursor();
393         bv->updateInset();
394         bv->owner()->view_state_changed();
395         bv->owner()->updateMenubar();
396         bv->owner()->updateToolbar();
397         if (old_par != cpar()) {
398                 bv->owner()->setLayout(cpar()->layout()->name());
399                 old_par = cpar();
400         }
401 }
402
403
404 string const InsetText::editMessage() const
405 {
406         return _("Opened Text Inset");
407 }
408
409
410 void InsetText::insetUnlock(BufferView * bv)
411 {
412         if (the_locking_inset) {
413                 the_locking_inset->insetUnlock(bv);
414                 the_locking_inset = 0;
415                 updateLocal(bv, false);
416         }
417         no_selection = true;
418         locked = false;
419
420         if (text_.selection.set()) {
421                 text_.clearSelection();
422         } else if (owner()) {
423                 bv->owner()->setLayout(owner()->getLyXText(bv)
424                                        ->cursor.par()->layout()->name());
425         } else
426                 bv->owner()->setLayout(bv->text->cursor.par()->layout()->name());
427         // hack for deleteEmptyParMech
428         ParagraphList::iterator first_par = paragraphs.begin();
429         if (!first_par->empty()) {
430                 text_.setCursor(first_par, 0);
431         } else if (paragraphs.size() > 1) {
432                 text_.setCursor(boost::next(first_par), 0);
433         }
434 }
435
436
437 void InsetText::lockInset(BufferView * bv)
438 {
439         locked = true;
440         the_locking_inset = 0;
441         inset_pos = inset_x = inset_y = 0;
442         inset_boundary = false;
443         inset_par = paragraphs.end();
444         old_par = paragraphs.end();
445         text_.setCursorIntern(paragraphs.begin(), 0);
446         text_.clearSelection();
447         finishUndo();
448         // If the inset is empty set the language of the current font to the
449         // language to the surronding text (if different).
450         if (paragraphs.begin()->empty() && paragraphs.size() == 1 &&
451                 bv->getParentLanguage(this) != text_.current_font.language()) {
452                 LyXFont font(LyXFont::ALL_IGNORE);
453                 font.setLanguage(bv->getParentLanguage(this));
454                 setFont(bv, font, false);
455         }
456 }
457
458
459 void InsetText::lockInset(BufferView * /*bv*/, UpdatableInset * inset)
460 {
461         the_locking_inset = inset;
462         inset_x = cix() - top_x + drawTextXOffset;
463         inset_y = ciy() + drawTextYOffset;
464         inset_pos = cpos();
465         inset_par = cpar();
466         inset_boundary = cboundary();
467 }
468
469
470 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
471 {
472         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
473                               << inset << "): " << endl;
474         if (!inset)
475                 return false;
476         if (!the_locking_inset) {
477                 ParagraphList::iterator pit = paragraphs.begin();
478                 ParagraphList::iterator pend = paragraphs.end();
479
480                 int const id = inset->id();
481                 for (; pit != pend; ++pit) {
482                         InsetList::iterator it = pit->insetlist.begin();
483                         InsetList::iterator const end = pit->insetlist.end();
484                         for (; it != end; ++it) {
485                                 if (it->inset == inset) {
486                                         lyxerr << "InsetText::lockInsetInInset: 1 a" << endl;
487                                         text_.setCursorIntern(pit, it->pos);
488                                         lyxerr << "InsetText::lockInsetInInset: 1 b" << endl;
489                                         lyxerr << "bv: " << bv << " inset: " << inset << endl;
490                                         lockInset(bv, inset);
491                                         lyxerr << "InsetText::lockInsetInInset: 1 c" << endl;
492                                         return true;
493                                 }
494                                 if (it->inset->getInsetFromID(id)) {
495                                         lyxerr << "InsetText::lockInsetInInset: 2" << endl;
496                                         text_.setCursorIntern(pit, it->pos);
497                                         it->inset->localDispatch(FuncRequest(bv, LFUN_INSET_EDIT));
498                                         return the_locking_inset->lockInsetInInset(bv, inset);
499                                 }
500                         }
501                 }
502                 lyxerr << "InsetText::lockInsetInInset: 3" << endl;
503                 return false;
504         }
505         if (inset == cpar()->getInset(cpos())) {
506                 lyxerr[Debug::INSETS] << "OK" << endl;
507                 lockInset(bv, inset);
508                 return true;
509         }
510
511         if (the_locking_inset && the_locking_inset == inset) {
512                 if (cpar() == inset_par && cpos() == inset_pos) {
513                         lyxerr[Debug::INSETS] << "OK" << endl;
514                         inset_x = cix() - top_x + drawTextXOffset;
515                         inset_y = ciy() + drawTextYOffset;
516                 } else {
517                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
518                 }
519         } else if (the_locking_inset) {
520                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
521                 return the_locking_inset->lockInsetInInset(bv, inset);
522         }
523         lyxerr[Debug::INSETS] << "NOT OK" << endl;
524         return false;
525 }
526
527
528 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
529                                    bool lr)
530 {
531         if (!the_locking_inset)
532                 return false;
533         if (the_locking_inset == inset) {
534                 the_locking_inset->insetUnlock(bv);
535                 the_locking_inset = 0;
536                 if (lr)
537                         moveRightIntern(bv, true, false);
538                 old_par = paragraphs.end(); // force layout setting
539                 if (scroll())
540                         scroll(bv, 0.0F);
541                 else
542                         updateLocal(bv, false);
543                 return true;
544         }
545         return the_locking_inset->unlockInsetInInset(bv, inset, lr);
546 }
547
548
549 void InsetText::lfunMousePress(FuncRequest const & cmd)
550 {
551         no_selection = true;
552
553         // use this to check mouse motion for selection!
554         mouse_x = cmd.x;
555         mouse_y = cmd.y;
556
557         BufferView * bv = cmd.view();
558         FuncRequest cmd1 = cmd;
559         cmd1.x -= inset_x;
560         cmd1.y -= inset_y;
561         if (!locked)
562                 lockInset(bv);
563
564         int tmp_x = cmd.x - drawTextXOffset;
565         int tmp_y = cmd.y + dim_.asc - getLyXText(bv)->top_y();
566         InsetOld * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
567
568         if (the_locking_inset) {
569                 if (the_locking_inset == inset) {
570                         the_locking_inset->localDispatch(cmd1);
571                         return;
572                 }
573                 // otherwise only unlock the_locking_inset
574                 the_locking_inset->insetUnlock(bv);
575                 the_locking_inset = 0;
576         }
577         if (!inset)
578                 no_selection = false;
579
580         if (bv->theLockingInset()) {
581                 if (isHighlyEditableInset(inset)) {
582                         // We just have to lock the inset before calling a
583                         // PressEvent on it!
584                         UpdatableInset * uinset = static_cast<UpdatableInset*>(inset);
585                         if (!bv->lockInset(uinset)) {
586                                 lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
587                         }
588                         inset->localDispatch(cmd1);
589                         if (the_locking_inset)
590                                 updateLocal(bv, false);
591                         return;
592                 }
593         }
594         if (!inset) {
595                 bool paste_internally = false;
596                 if (cmd.button() == mouse_button::button2 && getLyXText(bv)->selection.set()) {
597                         localDispatch(FuncRequest(bv, LFUN_COPY));
598                         paste_internally = true;
599                 }
600                 int old_top_y = text_.top_y();
601
602                 text_.setCursorFromCoordinates(cmd.x - drawTextXOffset,
603                                              cmd.y + dim_.asc);
604                 // set the selection cursor!
605                 text_.selection.cursor = text_.cursor;
606                 text_.cursor.x_fix(text_.cursor.x());
607
608                 text_.clearSelection();
609                 updateLocal(bv, false);
610
611                 bv->owner()->setLayout(cpar()->layout()->name());
612
613                 // we moved the view we cannot do mouse selection in this case!
614                 if (getLyXText(bv)->top_y() != old_top_y)
615                         no_selection = true;
616                 old_par = cpar();
617                 // Insert primary selection with middle mouse
618                 // if there is a local selection in the current buffer,
619                 // insert this
620                 if (cmd.button() == mouse_button::button2) {
621                         if (paste_internally)
622                                 localDispatch(FuncRequest(bv, LFUN_PASTE));
623                         else
624                                 localDispatch(FuncRequest(bv, LFUN_PASTESELECTION, "paragraph"));
625                 }
626         } else {
627                 getLyXText(bv)->clearSelection();
628         }
629 }
630
631
632 bool InsetText::lfunMouseRelease(FuncRequest const & cmd)
633 {
634         BufferView * bv = cmd.view();
635         FuncRequest cmd1 = cmd;
636         cmd1.x -= inset_x;
637         cmd1.y -= inset_y;
638
639         no_selection = true;
640         if (the_locking_inset)
641                 return the_locking_inset->localDispatch(cmd1);
642
643         int tmp_x = cmd.x - drawTextXOffset;
644         int tmp_y = cmd.y + dim_.asc - getLyXText(bv)->top_y();
645         InsetOld * inset = getLyXText(bv)->checkInsetHit(tmp_x, tmp_y);
646         bool ret = false;
647         if (inset) {
648 // This code should probably be removed now. Simple insets
649 // (!highlyEditable) can actually take the localDispatch,
650 // and turn it into edit() if necessary. But we still
651 // need to deal properly with the whole relative vs.
652 // absolute mouse co-ords thing in a realiable, sensible way
653 #if 0
654                 if (isHighlyEditableInset(inset))
655                         ret = inset->localDispatch(cmd1);
656                 else {
657                         inset_x = cix(bv) - top_x + drawTextXOffset;
658                         inset_y = ciy() + drawTextYOffset;
659                         cmd1.x = cmd.x - inset_x;
660                         cmd1.y = cmd.x - inset_y;
661                         inset->edit(bv, cmd1.x, cmd1.y, cmd.button());
662                         ret = true;
663                 }
664 #endif
665                 ret = inset->localDispatch(cmd1);
666                 updateLocal(bv, false);
667
668         }
669         return ret;
670 }
671
672
673 void InsetText::lfunMouseMotion(FuncRequest const & cmd)
674 {
675         FuncRequest cmd1 = cmd;
676         cmd1.x -= inset_x;
677         cmd1.y -= inset_y;
678
679         if (the_locking_inset) {
680                 the_locking_inset->localDispatch(cmd1);
681                 return;
682         }
683
684         if (no_selection || (mouse_x == cmd.x && mouse_y == cmd.y))
685                 return;
686
687         BufferView * bv = cmd.view();
688         LyXCursor cur = text_.cursor;
689         text_.setCursorFromCoordinates
690                 (cmd.x - drawTextXOffset, cmd.y + dim_.asc);
691         text_.cursor.x_fix(text_.cursor.x());
692         if (cur == text_.cursor)
693                 return;
694         text_.setSelection();
695         updateLocal(bv, false);
696 }
697
698
699 InsetOld::RESULT InsetText::localDispatch(FuncRequest const & cmd)
700 {
701         BufferView * bv = cmd.view();
702         setViewCache(bv);
703
704         switch (cmd.action) {
705         case LFUN_INSET_EDIT: {
706                 UpdatableInset::localDispatch(cmd);
707
708                 if (!bv->lockInset(this)) {
709                         lyxerr[Debug::INSETS] << "Cannot lock inset" << endl;
710                         return DISPATCHED;
711                 }
712
713                 locked = true;
714                 the_locking_inset = 0;
715                 inset_pos = 0;
716                 inset_x = 0;
717                 inset_y = 0;
718                 inset_boundary = false;
719                 inset_par = paragraphs.end();
720                 old_par = paragraphs.end();
721
722
723                 if (cmd.argument.size()) {
724                         if (cmd.argument == "left")
725                                 text_.setCursorIntern(paragraphs.begin(), 0);
726                         else {
727                                 ParagraphList::iterator it = boost::prior(paragraphs.end());
728                                 text_.setCursor(it, it->size());
729                         }
730                 } else {
731                         int tmp_y = (cmd.y < 0) ? 0 : cmd.y;
732                         // we put here -1 and not button as now the button in the
733                         // edit call should not be needed we will fix this in 1.3.x
734                         // cycle hopefully (Jug 20020509)
735                         // FIXME: GUII I've changed this to none: probably WRONG
736                         if (!checkAndActivateInset(bv, cmd.x, tmp_y, mouse_button::none)) {
737                                 text_.setCursorFromCoordinates(cmd.x - drawTextXOffset,
738                                                                         cmd.y + dim_.asc);
739                                 text_.cursor.x_fix(text_.cursor.x());
740                         }
741                 }
742
743                 text_.clearSelection();
744                 finishUndo();
745
746                 // If the inset is empty set the language of the current font to the
747                 // language to the surronding text (if different).
748                 if (paragraphs.begin()->empty() &&
749                     paragraphs.size() == 1 &&
750                     bv->getParentLanguage(this) != text_.current_font.language())
751                 {
752                         LyXFont font(LyXFont::ALL_IGNORE);
753                         font.setLanguage(bv->getParentLanguage(this));
754                         setFont(bv, font, false);
755                 }
756
757                 updateLocal(bv, false);
758                 // Tell the paragraph dialog that we've entered an insettext.
759                 bv->dispatch(FuncRequest(LFUN_PARAGRAPH_UPDATE));
760                 return DISPATCHED;
761         }
762
763         case LFUN_MOUSE_PRESS:
764                 lfunMousePress(cmd);
765                 return DISPATCHED;
766
767         case LFUN_MOUSE_MOTION:
768                 lfunMouseMotion(cmd);
769                 return DISPATCHED;
770
771         case LFUN_MOUSE_RELEASE:
772                 return lfunMouseRelease(cmd) ? DISPATCHED : UNDISPATCHED;
773
774         default:
775                 break;
776         }
777
778         bool was_empty = paragraphs.begin()->empty() && paragraphs.size() == 1;
779         no_selection = false;
780
781         RESULT result = UpdatableInset::localDispatch(cmd);
782         if (result != UNDISPATCHED)
783                 return DISPATCHED;
784
785         result = DISPATCHED;
786         if (cmd.action < 0 && cmd.argument.empty())
787                 return FINISHED;
788
789         if (the_locking_inset) {
790                 result = the_locking_inset->localDispatch(cmd);
791                 if (result == DISPATCHED_NOUPDATE)
792                         return result;
793                 if (result == DISPATCHED) {
794                         updateLocal(bv, false);
795                         return result;
796                 }
797                 if (result >= FINISHED) {
798                         switch (result) {
799                         case FINISHED_RIGHT:
800                                 moveRightIntern(bv, false, false);
801                                 result = DISPATCHED;
802                                 break;
803                         case FINISHED_UP:
804                                 result = moveUp(bv);
805                                 if (result >= FINISHED) {
806                                         updateLocal(bv, false);
807                                         bv->unlockInset(this);
808                                 }
809                                 break;
810                         case FINISHED_DOWN:
811                                 result = moveDown(bv);
812                                 if (result >= FINISHED) {
813                                         updateLocal(bv, false);
814                                         bv->unlockInset(this);
815                                 }
816                                 break;
817                         default:
818                                 result = DISPATCHED;
819                                 break;
820                         }
821                         the_locking_inset = 0;
822                         updateLocal(bv, false);
823                         // make sure status gets reset immediately
824                         bv->owner()->clearMessage();
825                         return result;
826                 }
827         }
828         bool updflag = false;
829
830         switch (cmd.action) {
831
832         // Normal chars
833         case LFUN_SELFINSERT:
834                 if (bv->buffer()->isReadonly()) {
835 //          setErrorMessage(N_("Document is read only"));
836                         break;
837                 }
838                 if (!cmd.argument.empty()) {
839                         /* Automatically delete the currently selected
840                          * text and replace it with what is being
841                          * typed in now. Depends on lyxrc settings
842                          * "auto_region_delete", which defaults to
843                          * true (on). */
844 #if 0
845                         // This should not be needed here and is also WRONG!
846                         recordUndo(bv, Undo::INSERT, text_.cursor.par());
847 #endif
848                         bv->switchKeyMap();
849
850                         if (lyxrc.auto_region_delete && text_.selection.set())
851                                 text_.cutSelection(false, false);
852                         text_.clearSelection();
853
854                         for (string::size_type i = 0; i < cmd.argument.length(); ++i)
855                                 bv->owner()->getIntl().getTransManager().
856                                         TranslateAndInsert(cmd.argument[i], &text_);
857                 }
858                 text_.selection.cursor = text_.cursor;
859                 updflag = true;
860                 result = DISPATCHED_NOUPDATE;
861                 break;
862
863         // cursor movements that need special handling
864
865         case LFUN_RIGHT:
866                 result = moveRight(bv);
867                 finishUndo();
868                 break;
869         case LFUN_LEFT:
870                 finishUndo();
871                 result = moveLeft(bv);
872                 break;
873         case LFUN_DOWN:
874                 finishUndo();
875                 result = moveDown(bv);
876                 break;
877         case LFUN_UP:
878                 finishUndo();
879                 result = moveUp(bv);
880                 break;
881
882         case LFUN_PRIOR:
883                 if (crow() == text_.rows().begin())
884                         result = FINISHED_UP;
885                 else {
886                         text_.cursorPrevious();
887                         text_.clearSelection();
888                         result = DISPATCHED_NOUPDATE;
889                 }
890                 break;
891
892         case LFUN_NEXT:
893                 if (boost::next(crow()) == text_.rows().end())
894                         result = FINISHED_DOWN;
895                 else {
896                         text_.cursorNext();
897                         text_.clearSelection();
898                         result = DISPATCHED_NOUPDATE;
899                 }
900                 break;
901
902         case LFUN_BACKSPACE:
903                 if (text_.selection.set())
904                         text_.cutSelection(true, false);
905                 else
906                         text_.backspace();
907                 updflag = true;
908                 break;
909
910         case LFUN_DELETE:
911                 if (text_.selection.set())
912                         text_.cutSelection(true, false);
913                 else 
914                         text_.Delete();
915                 updflag = true;
916                 break;
917
918         case LFUN_PASTE: {
919                 if (!autoBreakRows) {
920                         if (CutAndPaste::nrOfParagraphs() > 1) {
921 #ifdef WITH_WARNINGS
922 #warning FIXME horrendously bad UI
923 #endif
924                                 Alert::error(_("Paste failed"), _("Cannot include more than one paragraph."));
925                                 break;
926                         }
927                 }
928
929                 replaceSelection(bv->getLyXText());
930                 size_t sel_index = 0;
931                 string const & arg = cmd.argument;
932                 if (isStrUnsignedInt(arg)) {
933                         size_t const paste_arg = strToUnsignedInt(arg);
934 #warning FIXME Check if the arg is in the domain of available selections.
935                         sel_index = paste_arg;
936                 }
937                 text_.pasteSelection(sel_index);
938                 // bug 393
939                 text_.clearSelection();
940                 updflag = true;
941                 break;
942         }
943
944         case LFUN_BREAKPARAGRAPH:
945                 if (!autoBreakRows) {
946                         result = DISPATCHED;
947                         break;
948                 }
949                 replaceSelection(bv->getLyXText());
950                 text_.breakParagraph(paragraphs, 0);
951                 updflag = true;
952                 break;
953
954         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
955                 if (!autoBreakRows) {
956                         result = DISPATCHED;
957                         break;
958                 }
959                 replaceSelection(bv->getLyXText());
960                 text_.breakParagraph(paragraphs, 1);
961                 updflag = true;
962                 break;
963
964         case LFUN_BREAKLINE: {
965                 if (!autoBreakRows) {
966                         result = DISPATCHED;
967                         break;
968                 }
969
970                 replaceSelection(bv->getLyXText());
971                 text_.insertInset(new InsetNewline);
972                 updflag = true;
973                 break;
974         }
975
976         case LFUN_LAYOUT:
977                 // do not set layouts on non breakable textinsets
978                 if (autoBreakRows) {
979                         string cur_layout = cpar()->layout()->name();
980
981                         // Derive layout number from given argument (string)
982                         // and current buffer's textclass (number). 
983                         LyXTextClass const & tclass =
984                                 bv->buffer()->params.getLyXTextClass();
985                         string layout = cmd.argument;
986                         bool hasLayout = tclass.hasLayout(layout);
987
988                         // If the entry is obsolete, use the new one instead.
989                         if (hasLayout) {
990                                 string const & obs = tclass[layout]->obsoleted_by();
991                                 if (!obs.empty())
992                                         layout = obs;
993                         }
994
995                         // see if we found the layout number:
996                         if (!hasLayout) {
997                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + cmd.argument + N_(" not known"));
998                                 bv->owner()->dispatch(lf);
999                                 break;
1000                         }
1001
1002                         if (cur_layout != layout) {
1003                                 cur_layout = layout;
1004                                 text_.setLayout(layout);
1005                                 bv->owner()->setLayout(cpar()->layout()->name());
1006                                 updflag = true;
1007                         }
1008                 } else {
1009                         // reset the layout box
1010                         bv->owner()->setLayout(cpar()->layout()->name());
1011                 }
1012                 break;
1013
1014         default:
1015                 if (!bv->dispatch(cmd))
1016                         result = UNDISPATCHED;
1017                 break;
1018         }
1019
1020         updateLocal(bv, updflag);
1021
1022         /// If the action has deleted all text in the inset, we need to change the
1023         // language to the language of the surronding text.
1024         if (!was_empty && paragraphs.begin()->empty() &&
1025             paragraphs.size() == 1) {
1026                 LyXFont font(LyXFont::ALL_IGNORE);
1027                 font.setLanguage(bv->getParentLanguage(this));
1028                 setFont(bv, font, false);
1029         }
1030
1031         if (result >= FINISHED)
1032                 bv->unlockInset(this);
1033
1034         if (result == DISPATCHED_NOUPDATE)
1035                 result = DISPATCHED;
1036         return result;
1037 }
1038
1039
1040 int InsetText::latex(Buffer const * buf, ostream & os,
1041                      LatexRunParams const & runparams) const
1042 {
1043         TexRow texrow;
1044         latexParagraphs(buf, paragraphs, os, texrow, runparams);
1045         return texrow.rows();
1046 }
1047
1048
1049 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1050 {
1051         unsigned int lines = 0;
1052
1053         ParagraphList::const_iterator beg = paragraphs.begin();
1054         ParagraphList::const_iterator end = paragraphs.end();
1055         ParagraphList::const_iterator it = beg;
1056         for (; it != end; ++it) {
1057                 string const tmp = buf->asciiParagraph(*it, linelen, it == beg);
1058                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1059                 os << tmp;
1060         }
1061         return lines;
1062 }
1063
1064
1065 int InsetText::linuxdoc(Buffer const * buf, ostream & os) const
1066 {
1067         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1068         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1069
1070         // There is a confusion between the empty paragraph and the default paragraph
1071         // The default paragraph is <p></p>, the empty paragraph is *empty*
1072         // Since none of the floats of linuxdoc accepts standard paragraphs
1073         // I disable them. I don't expect problems. (jamatos 2003/07/27)
1074         for (; pit != pend; ++pit) {
1075                 const string name = pit->layout()->latexname();
1076                 if (name != "p")
1077                         sgml::openTag(os, 1, 0, name);
1078                 buf->simpleLinuxDocOnePar(os, pit, 0);
1079                 if (name != "p")
1080                         sgml::closeTag(os, 1, 0, name);
1081         }
1082         return 0;
1083 }
1084
1085
1086 int InsetText::docbook(Buffer const * buf, ostream & os, bool mixcont) const
1087 {
1088         unsigned int lines = 0;
1089
1090         vector<string> environment_stack(10);
1091         vector<string> environment_inner(10);
1092
1093         int const command_depth = 0;
1094         string item_name;
1095
1096         Paragraph::depth_type depth = 0; // paragraph depth
1097
1098         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1099         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1100
1101         for (; pit != pend; ++pit) {
1102                 int desc_on = 0; // description mode
1103
1104                 LyXLayout_ptr const & style = pit->layout();
1105
1106                 // environment tag closing
1107                 for (; depth > pit->params().depth(); --depth) {
1108                         if (environment_inner[depth] != "!-- --") {
1109                                 item_name = "listitem";
1110                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1111                                 if (environment_inner[depth] == "varlistentry")
1112                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1113                         }
1114                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1115                         environment_stack[depth].erase();
1116                         environment_inner[depth].erase();
1117                 }
1118
1119                 if (depth == pit->params().depth()
1120                    && environment_stack[depth] != style->latexname()
1121                    && !environment_stack[depth].empty()) {
1122                         if (environment_inner[depth] != "!-- --") {
1123                                 item_name= "listitem";
1124                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1125                                 if (environment_inner[depth] == "varlistentry")
1126                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1127                         }
1128
1129                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1130
1131                         environment_stack[depth].erase();
1132                         environment_inner[depth].erase();
1133                 }
1134
1135                 // Write opening SGML tags.
1136                 switch (style->latextype) {
1137                 case LATEX_PARAGRAPH:
1138                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1139                         break;
1140
1141                 case LATEX_COMMAND:
1142                         buf->error(ErrorItem(_("Error"), _("LatexType Command not allowed here.\n"), pit->id(), 0, pit->size()));
1143                         return -1;
1144                         break;
1145
1146                 case LATEX_ENVIRONMENT:
1147                 case LATEX_ITEM_ENVIRONMENT:
1148                         if (depth < pit->params().depth()) {
1149                                 depth = pit->params().depth();
1150                                 environment_stack[depth].erase();
1151                         }
1152
1153                         if (environment_stack[depth] != style->latexname()) {
1154                                 if (environment_stack.size() == depth + 1) {
1155                                         environment_stack.push_back("!-- --");
1156                                         environment_inner.push_back("!-- --");
1157                                 }
1158                                 environment_stack[depth] = style->latexname();
1159                                 environment_inner[depth] = "!-- --";
1160                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1161                         } else {
1162                                 if (environment_inner[depth] != "!-- --") {
1163                                         item_name= "listitem";
1164                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1165                                         if (environment_inner[depth] == "varlistentry")
1166                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1167                                 }
1168                         }
1169
1170                         if (style->latextype == LATEX_ENVIRONMENT) {
1171                                 if (!style->latexparam().empty()) {
1172                                         if (style->latexparam() == "CDATA")
1173                                                 os << "<![CDATA[";
1174                                         else
1175                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1176                                 }
1177                                 break;
1178                         }
1179
1180                         desc_on = (style->labeltype == LABEL_MANUAL);
1181
1182                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1183                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1184
1185                         item_name = desc_on ? "term" : "para";
1186                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1187
1188                         break;
1189                 default:
1190                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1191                         break;
1192                 }
1193
1194                 buf->simpleDocBookOnePar(os, pit, desc_on, depth + 1 + command_depth);
1195
1196                 string end_tag;
1197                 // write closing SGML tags
1198                 switch (style->latextype) {
1199                 case LATEX_ENVIRONMENT:
1200                         if (!style->latexparam().empty()) {
1201                                 if (style->latexparam() == "CDATA")
1202                                         os << "]]>";
1203                                 else
1204                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1205                         }
1206                         break;
1207                 case LATEX_ITEM_ENVIRONMENT:
1208                         if (desc_on == 1)
1209                                 break;
1210                         end_tag= "para";
1211                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1212                         break;
1213                 case LATEX_PARAGRAPH:
1214                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1215                         break;
1216                 default:
1217                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1218                         break;
1219                 }
1220         }
1221
1222         // Close open tags
1223         for (int d = depth; d >= 0; --d) {
1224                 if (!environment_stack[depth].empty()) {
1225                         if (environment_inner[depth] != "!-- --") {
1226                                 item_name = "listitem";
1227                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1228                                if (environment_inner[depth] == "varlistentry")
1229                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1230                         }
1231
1232                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1233                 }
1234         }
1235
1236         return lines;
1237 }
1238
1239
1240 void InsetText::validate(LaTeXFeatures & features) const
1241 {
1242         for_each(paragraphs.begin(), paragraphs.end(),
1243                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1244 }
1245
1246
1247 void InsetText::getCursor(BufferView & bv, int & x, int & y) const
1248 {
1249         if (the_locking_inset) {
1250                 the_locking_inset->getCursor(bv, x, y);
1251                 return;
1252         }
1253         x = cx();
1254         y = cy() + InsetText::y();
1255 }
1256
1257
1258 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1259 {
1260         if (the_locking_inset) {
1261                 the_locking_inset->getCursorPos(bv, x, y);
1262                 return;
1263         }
1264         x = cx() - top_x - TEXT_TO_INSET_OFFSET;
1265         y = cy() - TEXT_TO_INSET_OFFSET;
1266 }
1267
1268
1269 int InsetText::insetInInsetY() const
1270 {
1271         if (!the_locking_inset)
1272                 return 0;
1273
1274         return inset_y + the_locking_inset->insetInInsetY();
1275 }
1276
1277
1278 void InsetText::fitInsetCursor(BufferView * bv) const
1279 {
1280         if (the_locking_inset) {
1281                 the_locking_inset->fitInsetCursor(bv);
1282                 return;
1283         }
1284
1285         LyXFont const font = text_.getFont(cpar(), cpos());
1286
1287         int const asc = font_metrics::maxAscent(font);
1288         int const desc = font_metrics::maxDescent(font);
1289
1290         bv->fitLockedInsetCursor(cx(), cy(), asc, desc);
1291 }
1292
1293
1294 InsetOld::RESULT InsetText::moveRight(BufferView * bv)
1295 {
1296         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params))
1297                 return moveLeftIntern(bv, false, true, false);
1298         else
1299                 return moveRightIntern(bv, true, true, false);
1300 }
1301
1302
1303 InsetOld::RESULT InsetText::moveLeft(BufferView * bv)
1304 {
1305         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params))
1306                 return moveRightIntern(bv, true, true, false);
1307         else
1308                 return moveLeftIntern(bv, false, true, false);
1309 }
1310
1311
1312 InsetOld::RESULT
1313 InsetText::moveRightIntern(BufferView * bv, bool front,
1314                            bool activate_inset, bool selecting)
1315 {
1316         ParagraphList::iterator c_par = cpar();
1317
1318         if (boost::next(c_par) == paragraphs.end() && cpos() >= c_par->size())
1319                 return FINISHED_RIGHT;
1320         if (activate_inset && checkAndActivateInset(bv, front))
1321                 return DISPATCHED;
1322         text_.cursorRight(bv);
1323         if (!selecting)
1324                 text_.clearSelection();
1325         return DISPATCHED_NOUPDATE;
1326 }
1327
1328
1329 InsetOld::RESULT
1330 InsetText::moveLeftIntern(BufferView * bv, bool front,
1331                           bool activate_inset, bool selecting)
1332 {
1333         if (cpar() == paragraphs.begin() && cpos() <= 0)
1334                 return FINISHED;
1335         text_.cursorLeft(bv);
1336         if (!selecting)
1337                 text_.clearSelection();
1338         if (activate_inset && checkAndActivateInset(bv, front))
1339                 return DISPATCHED;
1340         return DISPATCHED_NOUPDATE;
1341 }
1342
1343
1344 InsetOld::RESULT InsetText::moveUp(BufferView * bv)
1345 {
1346         if (crow() == text_.rows().begin())
1347                 return FINISHED_UP;
1348         text_.cursorUp(bv);
1349         text_.clearSelection();
1350         return DISPATCHED_NOUPDATE;
1351 }
1352
1353
1354 InsetOld::RESULT InsetText::moveDown(BufferView * bv)
1355 {
1356         if (boost::next(crow()) == text_.rows().end())
1357                 return FINISHED_DOWN;
1358         text_.cursorDown(bv);
1359         text_.clearSelection();
1360         return DISPATCHED_NOUPDATE;
1361 }
1362
1363
1364 bool InsetText::insertInset(BufferView * bv, InsetOld * inset)
1365 {
1366         if (the_locking_inset) {
1367                 if (the_locking_inset->insetAllowed(inset))
1368                         return the_locking_inset->insertInset(bv, inset);
1369                 return false;
1370         }
1371         inset->setOwner(this);
1372         text_.insertInset(inset);
1373         bv->fitCursor();
1374         updateLocal(bv, true);
1375         return true;
1376 }
1377
1378
1379 bool InsetText::insetAllowed(InsetOld::Code code) const
1380 {
1381         // in_insetAllowed is a really gross hack,
1382         // to allow us to call the owner's insetAllowed
1383         // without stack overflow, which can happen
1384         // when the owner uses InsetCollapsable::insetAllowed()
1385         bool ret = true;
1386         if (in_insetAllowed)
1387                 return ret;
1388         in_insetAllowed = true;
1389         if (the_locking_inset)
1390                 ret = the_locking_inset->insetAllowed(code);
1391         else if (owner())
1392                 ret = owner()->insetAllowed(code);
1393         in_insetAllowed = false;
1394         return ret;
1395 }
1396
1397
1398 UpdatableInset * InsetText::getLockingInset() const
1399 {
1400         return the_locking_inset ? the_locking_inset->getLockingInset() :
1401                 const_cast<InsetText *>(this);
1402 }
1403
1404
1405 UpdatableInset * InsetText::getFirstLockingInsetOfType(InsetOld::Code c)
1406 {
1407         if (c == lyxCode())
1408                 return this;
1409         if (the_locking_inset)
1410                 return the_locking_inset->getFirstLockingInsetOfType(c);
1411         return 0;
1412 }
1413
1414
1415 bool InsetText::showInsetDialog(BufferView * bv) const
1416 {
1417         if (the_locking_inset)
1418                 return the_locking_inset->showInsetDialog(bv);
1419         return false;
1420 }
1421
1422
1423 void InsetText::getLabelList(std::vector<string> & list) const
1424 {
1425         ParagraphList::const_iterator pit = paragraphs.begin();
1426         ParagraphList::const_iterator pend = paragraphs.end();
1427         for (; pit != pend; ++pit) {
1428                 InsetList::const_iterator beg = pit->insetlist.begin();
1429                 InsetList::const_iterator end = pit->insetlist.end();
1430                 for (; beg != end; ++beg)
1431                         beg->inset->getLabelList(list);
1432         }
1433 }
1434
1435
1436 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1437                         bool selectall)
1438 {
1439         if (the_locking_inset) {
1440                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1441                 return;
1442         }
1443
1444         if ((paragraphs.size() == 1 && paragraphs.begin()->empty())
1445             || cpar()->empty()) {
1446                 text_.setFont(font, toggleall);
1447                 return;
1448         }
1449
1450
1451         if (text_.selection.set())
1452                 recordUndo(bv, Undo::ATOMIC, text_.cursor.par());
1453
1454         if (selectall) {
1455                 text_.cursorTop();
1456                 text_.selection.cursor = text_.cursor;
1457                 text_.cursorBottom();
1458                 text_.setSelection();
1459         }
1460
1461         text_.toggleFree(font, toggleall);
1462
1463         if (selectall)
1464                 text_.clearSelection();
1465
1466         bv->fitCursor();
1467         updateLocal(bv, true);
1468 }
1469
1470
1471 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1472 {
1473         InsetOld * inset = cpar()->getInset(cpos());
1474         if (!isHighlyEditableInset(inset))
1475                 return false;
1476         FuncRequest cmd(bv, LFUN_INSET_EDIT, front ? "left" : "right");
1477         inset->localDispatch(cmd);
1478         if (!the_locking_inset)
1479                 return false;
1480         updateLocal(bv, false);
1481         return true;
1482 }
1483
1484
1485 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1486                                       mouse_button::state button)
1487 {
1488         x -= drawTextXOffset;
1489         int dummyx = x;
1490         int dummyy = y + dim_.asc;
1491         InsetOld * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1492         // we only do the edit() call if the inset was hit by the mouse
1493         // or if it is a highly editable inset. So we should call this
1494         // function from our own edit with button < 0.
1495         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1496         // WRONG
1497         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1498                 return false;
1499
1500         if (!inset)
1501                 return false;
1502         if (x < 0)
1503                 x = dim_.wid;
1504         if (y < 0)
1505                 y = dim_.des;
1506         inset_x = cix() - top_x + drawTextXOffset;
1507         inset_y = ciy() + drawTextYOffset;
1508         FuncRequest cmd(bv, LFUN_INSET_EDIT, x - inset_x, y - inset_y, button);
1509         inset->localDispatch(cmd);
1510         if (!the_locking_inset)
1511                 return false;
1512         updateLocal(bv, false);
1513         return true;
1514 }
1515
1516
1517 void InsetText::markNew(bool track_changes)
1518 {
1519         ParagraphList::iterator pit = paragraphs.begin();
1520         ParagraphList::iterator end = paragraphs.end();
1521         for (; pit != end; ++pit) {
1522                 if (track_changes) {
1523                         pit->trackChanges();
1524                 } else {
1525                         // no-op when not tracking
1526                         pit->cleanChanges();
1527                 }
1528         }
1529 }
1530
1531
1532 void InsetText::setText(string const & data, LyXFont const & font)
1533 {
1534         clear(false);
1535         for (unsigned int i = 0; i < data.length(); ++i)
1536                 paragraphs.begin()->insertChar(i, data[i], font);
1537         reinitLyXText();
1538 }
1539
1540
1541 void InsetText::setAutoBreakRows(bool flag)
1542 {
1543         if (flag != autoBreakRows) {
1544                 autoBreakRows = flag;
1545                 if (!flag)
1546                         removeNewlines();
1547         }
1548 }
1549
1550
1551 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
1552 {
1553         if (how != drawFrame_) {
1554                 drawFrame_ = how;
1555                 updateLocal(bv, false);
1556         }
1557 }
1558
1559
1560 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
1561 {
1562         if (frame_color != col) {
1563                 frame_color = col;
1564                 updateLocal(bv, false);
1565         }
1566 }
1567
1568
1569 int InsetText::cx() const
1570 {
1571         int x = text_.cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
1572         if (the_locking_inset) {
1573                 LyXFont font = text_.getFont(text_.cursor.par(), text_.cursor.pos());
1574                 if (font.isVisibleRightToLeft())
1575                         x -= the_locking_inset->width();
1576         }
1577         return x;
1578 }
1579
1580
1581 int InsetText::cix() const
1582 {
1583         int x = text_.cursor.ix() + top_x + TEXT_TO_INSET_OFFSET;
1584         if (the_locking_inset) {
1585                 LyXFont font = text_.getFont(text_.cursor.par(), text_.cursor.pos());
1586                 if (font.isVisibleRightToLeft())
1587                         x -= the_locking_inset->width();
1588         }
1589         return x;
1590 }
1591
1592
1593 int InsetText::cy() const
1594 {
1595         return text_.cursor.y() - dim_.asc + TEXT_TO_INSET_OFFSET;
1596 }
1597
1598
1599 int InsetText::ciy() const
1600 {
1601         return text_.cursor.iy() - dim_.asc + TEXT_TO_INSET_OFFSET;
1602 }
1603
1604
1605 pos_type InsetText::cpos() const
1606 {
1607         return text_.cursor.pos();
1608 }
1609
1610
1611 ParagraphList::iterator InsetText::cpar() const
1612 {
1613         return text_.cursor.par();
1614 }
1615
1616
1617 bool InsetText::cboundary() const
1618 {
1619         return text_.cursor.boundary();
1620 }
1621
1622
1623 RowList::iterator InsetText::crow() const
1624 {
1625         return text_.cursorRow();
1626 }
1627
1628
1629 LyXText * InsetText::getLyXText(BufferView const * bv,
1630                                 bool const recursive) const
1631 {
1632         setViewCache(bv);
1633         if (recursive && the_locking_inset)
1634                 return the_locking_inset->getLyXText(bv, true);
1635         return &text_;
1636 }
1637
1638
1639 void InsetText::setViewCache(BufferView const * bv) const
1640 {
1641         if (bv)
1642                 text_.bv_owner = const_cast<BufferView *>(bv);
1643 }
1644
1645
1646 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
1647 {
1648         if (recursive) {
1649                 /// then remove all LyXText in text-insets
1650                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1651                          const_cast<ParagraphList&>(paragraphs).end(),
1652                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
1653         }
1654 }
1655
1656
1657 void InsetText::resizeLyXText(BufferView * bv, bool /*force*/) const
1658 {
1659         if (paragraphs.size() == 1 && paragraphs.begin()->empty())
1660                 return;
1661
1662         if (!bv)
1663                 return;
1664
1665         Assert(bv);
1666         setViewCache(bv);
1667
1668         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1669                  const_cast<ParagraphList&>(paragraphs).end(),
1670                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
1671
1672         saveLyXTextState();
1673         text_.init(bv);
1674         restoreLyXTextState();
1675
1676         // seems to be unneeded
1677 #if 1
1678         if (the_locking_inset) {
1679                 inset_x = cix() - top_x + drawTextXOffset;
1680                 inset_y = ciy() + drawTextYOffset;
1681         }
1682 #endif
1683
1684 #if 0
1685         text_.top_y(bv->screen().topCursorVisible(&text_));
1686         if (!owner()) {
1687                 const_cast<InsetText*>(this)->updateLocal(bv, false);
1688                 // this will scroll the screen such that the cursor becomes visible
1689                 bv->updateScrollbar();
1690         }
1691 #endif
1692 }
1693
1694
1695 void InsetText::reinitLyXText() const
1696 {
1697         BufferView * bv = text_.bv_owner;
1698
1699         if (!bv)
1700                 return;
1701
1702         saveLyXTextState();
1703
1704         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1705                  const_cast<ParagraphList&>(paragraphs).end(),
1706                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
1707
1708         text_.init(bv);
1709         restoreLyXTextState();
1710         if (the_locking_inset) {
1711                 inset_x = cix() - top_x + drawTextXOffset;
1712                 inset_y = ciy() + drawTextYOffset;
1713         }
1714         text_.top_y(bv->screen().topCursorVisible(&text_));
1715         if (!owner()) {
1716                 // this will scroll the screen such that the cursor becomes visible
1717                 bv->updateScrollbar();
1718         }
1719 }
1720
1721
1722 void InsetText::removeNewlines()
1723 {
1724         bool changed = false;
1725
1726         ParagraphList::iterator it = paragraphs.begin();
1727         ParagraphList::iterator end = paragraphs.end();
1728         for (; it != end; ++it) {
1729                 for (int i = 0; i < it->size(); ++i) {
1730                         if (it->isNewline(i)) {
1731                                 changed = true;
1732                                 it->erase(i);
1733                         }
1734                 }
1735         }
1736         if (changed)
1737                 reinitLyXText();
1738 }
1739
1740
1741 int InsetText::scroll(bool recursive) const
1742 {
1743         int sx = UpdatableInset::scroll(false);
1744
1745         if (recursive && the_locking_inset)
1746                 sx += the_locking_inset->scroll(recursive);
1747
1748         return sx;
1749 }
1750
1751
1752 void InsetText::clearSelection(BufferView * bv)
1753 {
1754         getLyXText(bv)->clearSelection();
1755 }
1756
1757
1758 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
1759 {
1760         Painter & pain = bv->painter();
1761         int w = dim_.wid;
1762         int h = dim_.asc + dim_.des;
1763         int ty = baseline - dim_.asc;
1764
1765         if (ty < 0) {
1766                 h += ty;
1767                 ty = 0;
1768         }
1769         if (ty + h > pain.paperHeight())
1770                 h = pain.paperHeight();
1771         if (top_x + drawTextXOffset + w > pain.paperWidth())
1772                 w = pain.paperWidth();
1773         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
1774 }
1775
1776
1777 ParagraphList * InsetText::getParagraphs(int i) const
1778 {
1779         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
1780 }
1781
1782
1783 LyXCursor const & InsetText::cursor(BufferView * bv) const
1784 {
1785         if (the_locking_inset)
1786                 return the_locking_inset->cursor(bv);
1787         return getLyXText(bv)->cursor;
1788 }
1789
1790
1791 InsetOld * InsetText::getInsetFromID(int id_arg) const
1792 {
1793         if (id_arg == id())
1794                 return const_cast<InsetText *>(this);
1795
1796         ParagraphList::const_iterator pit = paragraphs.begin();
1797         ParagraphList::const_iterator pend = paragraphs.end();
1798         for (; pit != pend; ++pit) {
1799                 InsetList::const_iterator it = pit->insetlist.begin();
1800                 InsetList::const_iterator end = pit->insetlist.end();
1801                 for (; it != end; ++it) {
1802                         if (it->inset->id() == id_arg)
1803                                 return it->inset;
1804                         InsetOld * in = it->inset->getInsetFromID(id_arg);
1805                         if (in)
1806                                 return in;
1807                 }
1808         }
1809         return 0;
1810 }
1811
1812
1813 WordLangTuple const
1814 InsetText::selectNextWordToSpellcheck(BufferView * bv, float & value) const
1815 {
1816         WordLangTuple word;
1817         if (the_locking_inset) {
1818                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
1819                 if (!word.word().empty()) {
1820                         value += cy();
1821                         return word;
1822                 }
1823                 // we have to go on checking so move cursor to the next char
1824                 text_.cursor.pos(text_.cursor.pos() + 1);
1825         }
1826         word = text_.selectNextWordToSpellcheck(value);
1827         if (word.word().empty())
1828                 bv->unlockInset(const_cast<InsetText *>(this));
1829         else
1830                 value = cy();
1831         return word;
1832 }
1833
1834
1835 void InsetText::selectSelectedWord(BufferView * bv)
1836 {
1837         if (the_locking_inset) {
1838                 the_locking_inset->selectSelectedWord(bv);
1839                 return;
1840         }
1841         getLyXText(bv)->selectSelectedWord();
1842         updateLocal(bv, false);
1843 }
1844
1845
1846 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
1847 {
1848         if (the_locking_inset) {
1849                 if (the_locking_inset->nextChange(bv, length))
1850                         return true;
1851                 text_.cursorRight(true);
1852         }
1853         lyx::find::SearchResult result =
1854                 lyx::find::findNextChange(bv, &text_, length);
1855
1856         if (result == lyx::find::SR_FOUND) {
1857                 LyXCursor cur = text_.cursor;
1858                 bv->unlockInset(bv->theLockingInset());
1859                 if (bv->lockInset(this))
1860                         locked = true;
1861                 text_.cursor = cur;
1862                 text_.setSelectionRange(length);
1863                 updateLocal(bv, false);
1864         }
1865         return result != lyx::find::SR_NOT_FOUND;
1866 }
1867
1868
1869 bool InsetText::searchForward(BufferView * bv, string const & str,
1870                               bool cs, bool mw)
1871 {
1872         if (the_locking_inset) {
1873                 if (the_locking_inset->searchForward(bv, str, cs, mw))
1874                         return true;
1875                 text_.cursorRight(true);
1876         }
1877         lyx::find::SearchResult result =
1878                 lyx::find::find(bv, &text_, str, true, cs, mw);
1879
1880         if (result == lyx::find::SR_FOUND) {
1881                 LyXCursor cur = text_.cursor;
1882                 bv->unlockInset(bv->theLockingInset());
1883                 if (bv->lockInset(this))
1884                         locked = true;
1885                 text_.cursor = cur;
1886                 text_.setSelectionRange(str.length());
1887                 updateLocal(bv, false);
1888         }
1889         return result != lyx::find::SR_NOT_FOUND;
1890 }
1891
1892
1893 bool InsetText::searchBackward(BufferView * bv, string const & str,
1894                                bool cs, bool mw)
1895 {
1896         if (the_locking_inset) {
1897                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
1898                         return true;
1899         }
1900         if (!locked) {
1901                 ParagraphList::iterator pit = paragraphs.begin();
1902                 ParagraphList::iterator pend = paragraphs.end();
1903
1904                 while (boost::next(pit) != pend)
1905                         ++pit;
1906
1907                 text_.setCursor(pit, pit->size());
1908         }
1909         lyx::find::SearchResult result =
1910                 lyx::find::find(bv, &text_, str, false, cs, mw);
1911
1912         if (result == lyx::find::SR_FOUND) {
1913                 LyXCursor cur = text_.cursor;
1914                 bv->unlockInset(bv->theLockingInset());
1915                 if (bv->lockInset(this))
1916                         locked = true;
1917                 text_.cursor = cur;
1918                 text_.setSelectionRange(str.length());
1919                 updateLocal(bv, false);
1920         }
1921         return result != lyx::find::SR_NOT_FOUND;
1922 }
1923
1924
1925 bool InsetText::checkInsertChar(LyXFont & font)
1926 {
1927         return owner() ? owner()->checkInsertChar(font) : true;
1928 }
1929
1930
1931 void InsetText::collapseParagraphs(BufferView * bv)
1932 {
1933         while (paragraphs.size() > 1) {
1934                 ParagraphList::iterator first_par = paragraphs.begin();
1935                 ParagraphList::iterator next_par = boost::next(first_par);
1936                 size_t const first_par_size = first_par->size();
1937
1938                 if (!first_par->empty() &&
1939                     !next_par->empty() &&
1940                     !first_par->isSeparator(first_par_size - 1)) {
1941                         first_par->insertChar(first_par_size, ' ');
1942                 }
1943
1944                 if (text_.selection.set()) {
1945                         if (text_.selection.start.par() == next_par) {
1946                                 text_.selection.start.par(first_par);
1947                                 text_.selection.start.pos(
1948                                         text_.selection.start.pos() + first_par_size);
1949                         }
1950                         if (text_.selection.end.par() == next_par) {
1951                                 text_.selection.end.par(first_par);
1952                                 text_.selection.end.pos(
1953                                         text_.selection.end.pos() + first_par_size);
1954                         }
1955                 }
1956
1957                 mergeParagraph(bv->buffer()->params, paragraphs, first_par);
1958         }
1959         reinitLyXText();
1960 }
1961
1962
1963 void InsetText::getDrawFont(LyXFont & font) const
1964 {
1965         if (!owner())
1966                 return;
1967         owner()->getDrawFont(font);
1968 }
1969
1970
1971 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
1972 {
1973 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
1974 // And it probably does. You have to take a look at this John. (Lgb)
1975 #warning John, have a look here. (Lgb)
1976         ParagraphList::iterator pit = plist.begin();
1977         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(), *pit);
1978         ++pit;
1979         mergeParagraph(buffer->params, paragraphs, boost::prior(ins));
1980
1981         ParagraphList::iterator pend = plist.end();
1982         for (; pit != pend; ++pit)
1983                 paragraphs.push_back(*pit);
1984
1985         reinitLyXText();
1986 }
1987
1988
1989 void InsetText::addPreview(PreviewLoader & loader) const
1990 {
1991         ParagraphList::const_iterator pit = paragraphs.begin();
1992         ParagraphList::const_iterator pend = paragraphs.end();
1993
1994         for (; pit != pend; ++pit) {
1995                 InsetList::const_iterator it  = pit->insetlist.begin();
1996                 InsetList::const_iterator end = pit->insetlist.end();
1997                 for (; it != end; ++it)
1998                         it->inset->addPreview(loader);
1999         }
2000 }