]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
remove "deep update"
[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                 setParagraphData(ins->paragraphs);
158                 autoBreakRows = ins->autoBreakRows;
159                 drawFrame_ = ins->drawFrame_;
160                 frame_color = ins->frame_color;
161         } else {
162                 textwidth_ = 0; // broken
163                 drawFrame_ = NEVER;
164                 frame_color = LColor::insetframe;
165                 autoBreakRows = false;
166         }
167         the_locking_inset = 0;
168         for_each(paragraphs.begin(), paragraphs.end(),
169                  boost::bind(&Paragraph::setInsetOwner, _1, this));
170         top_y = 0;
171         no_selection = true;
172         drawTextXOffset = 0;
173         drawTextYOffset = 0;
174         locked = false;
175         old_par = paragraphs.end();
176         last_drawn_width = -1;
177         sstate.cursor.par(paragraphs.end());
178         in_insetAllowed = false;
179 }
180
181
182 void InsetText::clear(bool just_mark_erased)
183 {
184         if (just_mark_erased) {
185                 ParagraphList::iterator it = paragraphs.begin();
186                 ParagraphList::iterator end = paragraphs.end();
187                 for (; it != end; ++it) {
188                         it->markErased();
189                 }
190                 return;
191         }
192
193         // This is a gross hack...
194         LyXLayout_ptr old_layout = paragraphs.begin()->layout();
195
196         paragraphs.clear();
197         paragraphs.push_back(Paragraph());
198         paragraphs.begin()->setInsetOwner(this);
199         paragraphs.begin()->layout(old_layout);
200
201         reinitLyXText();
202 }
203
204
205 auto_ptr<InsetBase> InsetText::clone() const
206 {
207         return auto_ptr<InsetBase>(new InsetText(*this));
208 }
209
210
211 void InsetText::write(Buffer const * buf, ostream & os) const
212 {
213         os << "Text\n";
214         writeParagraphData(buf, os);
215 }
216
217
218 void InsetText::writeParagraphData(Buffer const * buf, ostream & os) const
219 {
220         ParagraphList::const_iterator it = paragraphs.begin();
221         ParagraphList::const_iterator end = paragraphs.end();
222         Paragraph::depth_type dth = 0;
223         for (; it != end; ++it) {
224                 it->write(buf, os, buf->params, dth);
225         }
226 }
227
228
229 void InsetText::read(Buffer const * buf, LyXLex & lex)
230 {
231         string token;
232         Paragraph::depth_type depth = 0;
233
234         clear(false);
235
236         if (buf->params.tracking_changes)
237                 paragraphs.begin()->trackChanges();
238
239         // delete the initial paragraph
240         paragraphs.clear();
241         ParagraphList::iterator pit = paragraphs.begin();
242
243         while (lex.isOK()) {
244                 lex.nextToken();
245                 token = lex.getString();
246                 if (token.empty())
247                         continue;
248                 if (token == "\\end_inset") {
249                         break;
250                 }
251
252                 if (token == "\\end_document") {
253                         lex.printError("\\end_document read in inset! Error in document!");
254                         return;
255                 }
256
257                 // FIXME: ugly.
258                 const_cast<Buffer*>(buf)->readParagraph(lex, token, paragraphs, pit, depth);
259         }
260
261         pit = paragraphs.begin();
262         ParagraphList::iterator const end = paragraphs.end();
263         for (; pit != end; ++pit)
264                 pit->setInsetOwner(this);
265
266         if (token != "\\end_inset") {
267                 lex.printError("Missing \\end_inset at this point. "
268                                            "Read: `$$Token'");
269         }
270 }
271
272
273 void InsetText::metrics(MetricsInfo & mi, Dimension & dim) const
274 {
275         //lyxerr << "InsetText::metrics: width: " << mi.base.textwidth << endl;
276
277         textwidth_ = mi.base.textwidth;
278         BufferView * bv = mi.base.bv;
279         setViewCache(bv);
280         text_.metrics(mi, dim);
281         dim.asc += TEXT_TO_INSET_OFFSET;
282         dim.des += TEXT_TO_INSET_OFFSET;
283         dim.wid += 2 * TEXT_TO_INSET_OFFSET;
284         dim.wid = max(dim.wid, 10);
285         dim_ = dim;
286 }
287
288
289 int InsetText::textWidth() const
290 {
291         return textwidth_;
292 }
293
294
295 void InsetText::draw(PainterInfo & pi, int x, int baseline) const
296 {
297         // update our idea of where we are. Clearly, we should
298         // not have to know this information.
299         top_x = x;
300
301         int const start_x = x;
302
303         BufferView * bv = pi.base.bv;
304         Painter & pain = pi.pain;
305
306         // repaint the background if needed
307         if (backgroundColor() != LColor::background)
308                 clearInset(bv, start_x + TEXT_TO_INSET_OFFSET, baseline);
309
310         // no draw is necessary !!!
311         if (drawFrame_ == LOCKED && !locked && paragraphs.begin()->empty()) {
312                 top_baseline = baseline;
313                 return;
314         }
315
316         bv->hideCursor();
317
318         if (!owner())
319                 x += scroll();
320
321         top_baseline = baseline;
322         top_y = baseline - dim_.asc;
323
324         if (last_drawn_width != dim_.wid)
325                 last_drawn_width = dim_.wid;
326
327         if (the_locking_inset && cpar() == inset_par && cpos() == inset_pos) {
328                 inset_x = cix() - x + drawTextXOffset;
329                 inset_y = ciy() + drawTextYOffset;
330         }
331
332         x += TEXT_TO_INSET_OFFSET;
333
334         RowList::iterator rit = text_.rows().begin();
335         RowList::iterator end = text_.rows().end();
336
337         int y_offset = baseline - rit->ascent_of_text();
338         int y2 = pain.paperHeight();
339         int first = 0;
340         int y = y_offset;
341         while (rit != end && y + rit->height() <= 0) {
342                 y += rit->height();
343                 first += rit->height();
344                 ++rit;
345         }
346         if (y_offset < 0) {
347                 text_.top_y(-y_offset);
348                 first = y;
349                 y_offset = 0;
350         } else {
351                 text_.top_y(first);
352                 first = 0;
353         }
354
355         int yo = y_offset + first;
356
357         paintRows(*bv, text_, rit, x, 0, yo, y2, yo);
358
359         if (drawFrame_ == ALWAYS || (drawFrame_ == LOCKED && locked))
360                 drawFrame(pain, int(start_x));
361 }
362
363
364 void InsetText::drawFrame(Painter & pain, int x) const
365 {
366         static int const ttoD2 = TEXT_TO_INSET_OFFSET / 2;
367         frame_x = x + ttoD2;
368         frame_y = top_baseline - dim_.asc + ttoD2;
369         frame_w = dim_.wid - TEXT_TO_INSET_OFFSET;
370         frame_h = dim_.asc + dim_.des - TEXT_TO_INSET_OFFSET;
371         pain.rectangle(frame_x, frame_y, frame_w, frame_h, frame_color);
372 }
373
374
375 void InsetText::updateLocal(BufferView * bv, bool mark_dirty)
376 {
377         if (!bv)
378                 return;
379
380         if (!autoBreakRows && paragraphs.size() > 1)
381                 collapseParagraphs(bv);
382
383         text_.partialRebreak();
384         bool flag = mark_dirty || text_.selection.set();
385         if (!text_.selection.set())
386                 text_.selection.cursor = text_.cursor;
387
388         bv->fitCursor();
389
390         if (flag)
391                 bv->updateInset();
392
393         bv->owner()->view_state_changed();
394         bv->owner()->updateMenubar();
395         bv->owner()->updateToolbar();
396         if (old_par != cpar()) {
397                 bv->owner()->setLayout(cpar()->layout()->name());
398                 old_par = cpar();
399         }
400 }
401
402
403 string const InsetText::editMessage() const
404 {
405         return _("Opened Text Inset");
406 }
407
408
409 void InsetText::insetUnlock(BufferView * bv)
410 {
411         if (the_locking_inset) {
412                 the_locking_inset->insetUnlock(bv);
413                 the_locking_inset = 0;
414                 updateLocal(bv, false);
415         }
416         no_selection = true;
417         locked = false;
418
419         if (text_.selection.set()) {
420                 text_.clearSelection();
421         } else if (owner()) {
422                 bv->owner()->setLayout(owner()->getLyXText(bv)
423                                        ->cursor.par()->layout()->name());
424         } else
425                 bv->owner()->setLayout(bv->text->cursor.par()->layout()->name());
426         // hack for deleteEmptyParMech
427         ParagraphList::iterator first_par = paragraphs.begin();
428         if (!first_par->empty()) {
429                 text_.setCursor(first_par, 0);
430         } else if (paragraphs.size() > 1) {
431                 text_.setCursor(boost::next(first_par), 0);
432         }
433 }
434
435
436 void InsetText::lockInset(BufferView * bv)
437 {
438         locked = true;
439         the_locking_inset = 0;
440         inset_pos = inset_x = inset_y = 0;
441         inset_boundary = false;
442         inset_par = paragraphs.end();
443         old_par = paragraphs.end();
444         text_.setCursorIntern(paragraphs.begin(), 0);
445         text_.clearSelection();
446         finishUndo();
447         // If the inset is empty set the language of the current font to the
448         // language to the surronding text (if different).
449         if (paragraphs.begin()->empty() && paragraphs.size() == 1 &&
450                 bv->getParentLanguage(this) != text_.current_font.language()) {
451                 LyXFont font(LyXFont::ALL_IGNORE);
452                 font.setLanguage(bv->getParentLanguage(this));
453                 setFont(bv, font, false);
454         }
455 }
456
457
458 void InsetText::lockInset(BufferView * /*bv*/, UpdatableInset * inset)
459 {
460         the_locking_inset = inset;
461         inset_x = cix() - top_x + drawTextXOffset;
462         inset_y = ciy() + drawTextYOffset;
463         inset_pos = cpos();
464         inset_par = cpar();
465         inset_boundary = cboundary();
466 }
467
468
469 bool InsetText::lockInsetInInset(BufferView * bv, UpdatableInset * inset)
470 {
471         lyxerr[Debug::INSETS] << "InsetText::LockInsetInInset("
472                               << inset << "): " << endl;
473         if (!inset)
474                 return false;
475         if (!the_locking_inset) {
476                 ParagraphList::iterator pit = paragraphs.begin();
477                 ParagraphList::iterator pend = paragraphs.end();
478
479                 int const id = inset->id();
480                 for (; pit != pend; ++pit) {
481                         InsetList::iterator it = pit->insetlist.begin();
482                         InsetList::iterator const end = pit->insetlist.end();
483                         for (; it != end; ++it) {
484                                 if (it->inset == inset) {
485                                         lyxerr << "InsetText::lockInsetInInset: 1 a" << endl;
486                                         text_.setCursorIntern(pit, it->pos);
487                                         lyxerr << "InsetText::lockInsetInInset: 1 b" << endl;
488                                         lyxerr << "bv: " << bv << " inset: " << inset << endl;
489                                         lockInset(bv, inset);
490                                         lyxerr << "InsetText::lockInsetInInset: 1 c" << endl;
491                                         return true;
492                                 }
493                                 if (it->inset->getInsetFromID(id)) {
494                                         lyxerr << "InsetText::lockInsetInInset: 2" << endl;
495                                         text_.setCursorIntern(pit, it->pos);
496                                         it->inset->localDispatch(FuncRequest(bv, LFUN_INSET_EDIT));
497                                         return the_locking_inset->lockInsetInInset(bv, inset);
498                                 }
499                         }
500                 }
501                 lyxerr << "InsetText::lockInsetInInset: 3" << endl;
502                 return false;
503         }
504         if (inset == cpar()->getInset(cpos())) {
505                 lyxerr[Debug::INSETS] << "OK" << endl;
506                 lockInset(bv, inset);
507                 return true;
508         }
509
510         if (the_locking_inset && the_locking_inset == inset) {
511                 if (cpar() == inset_par && cpos() == inset_pos) {
512                         lyxerr[Debug::INSETS] << "OK" << endl;
513                         inset_x = cix() - top_x + drawTextXOffset;
514                         inset_y = ciy() + drawTextYOffset;
515                 } else {
516                         lyxerr[Debug::INSETS] << "cursor.pos != inset_pos" << endl;
517                 }
518         } else if (the_locking_inset) {
519                 lyxerr[Debug::INSETS] << "MAYBE" << endl;
520                 return the_locking_inset->lockInsetInInset(bv, inset);
521         }
522         lyxerr[Debug::INSETS] << "NOT OK" << endl;
523         return false;
524 }
525
526
527 bool InsetText::unlockInsetInInset(BufferView * bv, UpdatableInset * inset,
528                                    bool lr)
529 {
530         if (!the_locking_inset)
531                 return false;
532         if (the_locking_inset == inset) {
533                 the_locking_inset->insetUnlock(bv);
534                 getLyXText(bv)->updateInset(inset);
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() &&
779                           paragraphs.size() == 1);
780
781         no_selection = false;
782         RESULT result = UpdatableInset::localDispatch(cmd);
783         if (result != UNDISPATCHED)
784                 return DISPATCHED;
785
786         result = DISPATCHED;
787         if (cmd.action < 0 && cmd.argument.empty())
788                 return FINISHED;
789
790         if (the_locking_inset) {
791                 result = the_locking_inset->localDispatch(cmd);
792                 if (result == DISPATCHED_NOUPDATE)
793                         return result;
794                 if (result == DISPATCHED) {
795                         updateLocal(bv, false);
796                         return result;
797                 }
798                 if (result >= FINISHED) {
799                         switch (result) {
800                         case FINISHED_RIGHT:
801                                 moveRightIntern(bv, false, false);
802                                 result = DISPATCHED;
803                                 break;
804                         case FINISHED_UP:
805                                 result = moveUp(bv);
806                                 if (result >= FINISHED) {
807                                         updateLocal(bv, false);
808                                         bv->unlockInset(this);
809                                 }
810                                 break;
811                         case FINISHED_DOWN:
812                                 result = moveDown(bv);
813                                 if (result >= FINISHED) {
814                                         updateLocal(bv, false);
815                                         bv->unlockInset(this);
816                                 }
817                                 break;
818                         default:
819                                 result = DISPATCHED;
820                                 break;
821                         }
822                         the_locking_inset = 0;
823                         updateLocal(bv, false);
824                         // make sure status gets reset immediately
825                         bv->owner()->clearMessage();
826                         return result;
827                 }
828         }
829         bool updflag = false;
830
831         switch (cmd.action) {
832
833         // Normal chars
834         case LFUN_SELFINSERT:
835                 if (bv->buffer()->isReadonly()) {
836 //          setErrorMessage(N_("Document is read only"));
837                         break;
838                 }
839                 if (!cmd.argument.empty()) {
840                         /* Automatically delete the currently selected
841                          * text and replace it with what is being
842                          * typed in now. Depends on lyxrc settings
843                          * "auto_region_delete", which defaults to
844                          * true (on). */
845 #if 0
846                         // This should not be needed here and is also WRONG!
847                         recordUndo(bv, Undo::INSERT, text_.cursor.par());
848 #endif
849                         bv->switchKeyMap();
850                         if (lyxrc.auto_region_delete) {
851                                 if (text_.selection.set()) {
852                                         text_.cutSelection(false, false);
853                                 }
854                         }
855                         text_.clearSelection();
856                         for (string::size_type i = 0; i < cmd.argument.length(); ++i) {
857                                 bv->owner()->getIntl().getTransManager().
858                                         TranslateAndInsert(cmd.argument[i], &text_);
859                         }
860                 }
861                 text_.selection.cursor = text_.cursor;
862                 updflag = true;
863                 result = DISPATCHED_NOUPDATE;
864                 break;
865
866         // cursor movements that need special handling
867
868         case LFUN_RIGHT:
869                 result = moveRight(bv);
870                 finishUndo();
871                 break;
872         case LFUN_LEFT:
873                 finishUndo();
874                 result = moveLeft(bv);
875                 break;
876         case LFUN_DOWN:
877                 finishUndo();
878                 result = moveDown(bv);
879                 break;
880         case LFUN_UP:
881                 finishUndo();
882                 result = moveUp(bv);
883                 break;
884
885         case LFUN_PRIOR:
886                 if (crow() == text_.rows().begin())
887                         result = FINISHED_UP;
888                 else {
889                         text_.cursorPrevious();
890                         text_.clearSelection();
891                         result = DISPATCHED_NOUPDATE;
892                 }
893                 break;
894
895         case LFUN_NEXT:
896                 if (boost::next(crow()) == text_.rows().end())
897                         result = FINISHED_DOWN;
898                 else {
899                         text_.cursorNext();
900                         text_.clearSelection();
901                         result = DISPATCHED_NOUPDATE;
902                 }
903                 break;
904
905         case LFUN_BACKSPACE: {
906                 if (text_.selection.set())
907                         text_.cutSelection(true, false);
908                 else
909                         text_.backspace();
910                 updflag = true;
911                 break;
912         }
913
914         case LFUN_DELETE: {
915                 if (text_.selection.set()) {
916                         text_.cutSelection(true, false);
917                 } else {
918                         text_.Delete();
919                 }
920                 updflag = true;
921                 break;
922         }
923
924         case LFUN_CUT: {
925                 text_.cutSelection(true, true);
926                 updflag = true;
927                 break;
928         }
929
930         case LFUN_COPY:
931                 finishUndo();
932                 text_.copySelection();
933                 break;
934
935         case LFUN_PASTESELECTION:
936         {
937                 string const clip(bv->getClipboard());
938
939                 if (clip.empty())
940                         break;
941                 if (cmd.argument == "paragraph") {
942                         text_.insertStringAsParagraphs(clip);
943                 } else {
944                         text_.insertStringAsLines(clip);
945                 }
946                 // bug 393
947                 text_.clearSelection();
948
949                 updflag = true;
950                 break;
951         }
952
953         case LFUN_PASTE: {
954                 if (!autoBreakRows) {
955                         if (CutAndPaste::nrOfParagraphs() > 1) {
956 #ifdef WITH_WARNINGS
957 #warning FIXME horrendously bad UI
958 #endif
959                                 Alert::error(_("Paste failed"), _("Cannot include more than one paragraph."));
960                                 break;
961                         }
962                 }
963
964                 replaceSelection(bv->getLyXText());
965                 size_t sel_index = 0;
966                 string const & arg = cmd.argument;
967                 if (isStrUnsignedInt(arg)) {
968                         size_t const paste_arg = strToUnsignedInt(arg);
969 #warning FIXME Check if the arg is in the domain of available selections.
970                         sel_index = paste_arg;
971                 }
972                 text_.pasteSelection(sel_index);
973                 // bug 393
974                 text_.clearSelection();
975                 updflag = true;
976                 break;
977         }
978
979         case LFUN_BREAKPARAGRAPH:
980                 if (!autoBreakRows) {
981                         result = DISPATCHED;
982                         break;
983                 }
984                 replaceSelection(bv->getLyXText());
985                 text_.breakParagraph(paragraphs, 0);
986                 updflag = true;
987                 break;
988
989         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
990                 if (!autoBreakRows) {
991                         result = DISPATCHED;
992                         break;
993                 }
994                 replaceSelection(bv->getLyXText());
995                 text_.breakParagraph(paragraphs, 1);
996                 updflag = true;
997                 break;
998
999         case LFUN_BREAKLINE: {
1000                 if (!autoBreakRows) {
1001                         result = DISPATCHED;
1002                         break;
1003                 }
1004
1005                 replaceSelection(bv->getLyXText());
1006                 text_.insertInset(new InsetNewline);
1007                 updflag = true;
1008                 break;
1009         }
1010
1011         case LFUN_LAYOUT:
1012                 // do not set layouts on non breakable textinsets
1013                 if (autoBreakRows) {
1014                         string cur_layout = cpar()->layout()->name();
1015
1016                         // Derive layout number from given argument (string)
1017                         // and current buffer's textclass (number). */
1018                         LyXTextClass const & tclass =
1019                                 bv->buffer()->params.getLyXTextClass();
1020                         string layout = cmd.argument;
1021                         bool hasLayout = tclass.hasLayout(layout);
1022
1023                         // If the entry is obsolete, use the new one instead.
1024                         if (hasLayout) {
1025                                 string const & obs =
1026                                         tclass[layout]->obsoleted_by();
1027                                 if (!obs.empty())
1028                                         layout = obs;
1029                         }
1030
1031                         // see if we found the layout number:
1032                         if (!hasLayout) {
1033                                 FuncRequest lf(LFUN_MESSAGE, N_("Layout ") + cmd.argument + N_(" not known"));
1034                                 bv->owner()->dispatch(lf);
1035                                 break;
1036                         }
1037
1038                         if (cur_layout != layout) {
1039                                 cur_layout = layout;
1040                                 text_.setLayout(layout);
1041                                 bv->owner()->setLayout(cpar()->layout()->name());
1042                                 updflag = true;
1043                         }
1044                 } else {
1045                         // reset the layout box
1046                         bv->owner()->setLayout(cpar()->layout()->name());
1047                 }
1048                 break;
1049         case LFUN_PARAGRAPH_SPACING:
1050                 // This one is absolutely not working. When fiddling with this
1051                 // it also seems to me that the paragraphs inside the insettext
1052                 // inherit bufferparams/paragraphparams in a strange way. (Lgb)
1053                 // FIXME: how old is this comment ? ...
1054         {
1055                 ParagraphList::iterator pit = text_.cursor.par();
1056                 Spacing::Space cur_spacing = pit->params().spacing().getSpace();
1057                 float cur_value = 1.0;
1058                 if (cur_spacing == Spacing::Other) {
1059                         cur_value = pit->params().spacing().getValue();
1060                 }
1061
1062                 istringstream istr(STRCONV(cmd.argument));
1063                 string tmp;
1064                 istr >> tmp;
1065                 Spacing::Space new_spacing = cur_spacing;
1066                 float new_value = cur_value;
1067                 if (tmp.empty()) {
1068                         lyxerr << "Missing argument to `paragraph-spacing'"
1069                                    << endl;
1070                 } else if (tmp == "single") {
1071                         new_spacing = Spacing::Single;
1072                 } else if (tmp == "onehalf") {
1073                         new_spacing = Spacing::Onehalf;
1074                 } else if (tmp == "double") {
1075                         new_spacing = Spacing::Double;
1076                 } else if (tmp == "other") {
1077                         new_spacing = Spacing::Other;
1078                         float tmpval = 0.0;
1079                         istr >> tmpval;
1080                         lyxerr << "new_value = " << tmpval << endl;
1081                         if (tmpval != 0.0)
1082                                 new_value = tmpval;
1083                 } else if (tmp == "default") {
1084                         new_spacing = Spacing::Default;
1085                 } else {
1086                         lyxerr << _("Unknown spacing argument: ")
1087                                    << cmd.argument << endl;
1088                 }
1089                 if (cur_spacing != new_spacing || cur_value != new_value) {
1090                         pit->params().spacing(Spacing(new_spacing, new_value));
1091                         updflag = true;
1092                 }
1093         }
1094         break;
1095
1096         // These need to do repaints but don't require
1097         // special handling otherwise. A *lot* of the
1098         // above could probably be done similarly ...
1099
1100         case LFUN_HOME:
1101         case LFUN_END:
1102         case LFUN_WORDLEFT:
1103         case LFUN_WORDRIGHT:
1104         // these two are really unhandled ...
1105         case LFUN_ENDBUF:
1106         case LFUN_BEGINNINGBUF:
1107                 if (!bv->dispatch(cmd))
1108                         result = UNDISPATCHED;
1109                 break;
1110
1111         case LFUN_RIGHTSEL:
1112         case LFUN_UPSEL:
1113         case LFUN_DOWNSEL:
1114         case LFUN_LEFTSEL:
1115         case LFUN_HOMESEL:
1116         case LFUN_ENDSEL:
1117         case LFUN_WORDLEFTSEL:
1118         case LFUN_WORDRIGHTSEL:
1119
1120                 // fallthrough
1121
1122         default:
1123                 if (!bv->dispatch(cmd))
1124                         result = UNDISPATCHED;
1125                 break;
1126         }
1127
1128         updateLocal(bv, updflag);
1129
1130         /// If the action has deleted all text in the inset, we need to change the
1131         // language to the language of the surronding text.
1132         if (!was_empty && paragraphs.begin()->empty() &&
1133             paragraphs.size() == 1) {
1134                 LyXFont font(LyXFont::ALL_IGNORE);
1135                 font.setLanguage(bv->getParentLanguage(this));
1136                 setFont(bv, font, false);
1137         }
1138
1139         if (result >= FINISHED)
1140                 bv->unlockInset(this);
1141
1142         if (result == DISPATCHED_NOUPDATE)
1143                 result = DISPATCHED;
1144         return result;
1145 }
1146
1147
1148 int InsetText::latex(Buffer const * buf, ostream & os,
1149                      LatexRunParams const & runparams) const
1150 {
1151         TexRow texrow;
1152         latexParagraphs(buf, paragraphs, os, texrow, runparams);
1153         return texrow.rows();
1154 }
1155
1156
1157 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1158 {
1159         unsigned int lines = 0;
1160
1161         ParagraphList::const_iterator beg = paragraphs.begin();
1162         ParagraphList::const_iterator end = paragraphs.end();
1163         ParagraphList::const_iterator it = beg;
1164         for (; it != end; ++it) {
1165                 string const tmp = buf->asciiParagraph(*it, linelen, it == beg);
1166                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1167                 os << tmp;
1168         }
1169         return lines;
1170 }
1171
1172
1173 int InsetText::linuxdoc(Buffer const * buf, ostream & os) const
1174 {
1175         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1176         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1177
1178         // There is a confusion between the empty paragraph and the default paragraph
1179         // The default paragraph is <p></p>, the empty paragraph is *empty*
1180         // Since none of the floats of linuxdoc accepts standard paragraphs
1181         // I disable them. I don't expect problems. (jamatos 2003/07/27)
1182         for (; pit != pend; ++pit) {
1183                 const string name = pit->layout()->latexname();
1184                 if (name != "p")
1185                         sgml::openTag(os, 1, 0, name);
1186                 buf->simpleLinuxDocOnePar(os, pit, 0);
1187                 if (name != "p")
1188                         sgml::closeTag(os, 1, 0, name);
1189         }
1190         return 0;
1191 }
1192
1193
1194 int InsetText::docbook(Buffer const * buf, ostream & os, bool mixcont) const
1195 {
1196         unsigned int lines = 0;
1197
1198         vector<string> environment_stack(10);
1199         vector<string> environment_inner(10);
1200
1201         int const command_depth = 0;
1202         string item_name;
1203
1204         Paragraph::depth_type depth = 0; // paragraph depth
1205
1206         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1207         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1208
1209         for (; pit != pend; ++pit) {
1210                 string sgmlparam;
1211                 int desc_on = 0; // description mode
1212
1213                 LyXLayout_ptr const & style = pit->layout();
1214
1215                 // environment tag closing
1216                 for (; depth > pit->params().depth(); --depth) {
1217                         if (environment_inner[depth] != "!-- --") {
1218                                 item_name = "listitem";
1219                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1220                                 if (environment_inner[depth] == "varlistentry")
1221                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1222                         }
1223                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1224                         environment_stack[depth].erase();
1225                         environment_inner[depth].erase();
1226                 }
1227
1228                 if (depth == pit->params().depth()
1229                    && environment_stack[depth] != style->latexname()
1230                    && !environment_stack[depth].empty()) {
1231                         if (environment_inner[depth] != "!-- --") {
1232                                 item_name= "listitem";
1233                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1234                                 if (environment_inner[depth] == "varlistentry")
1235                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1236                         }
1237
1238                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1239
1240                         environment_stack[depth].erase();
1241                         environment_inner[depth].erase();
1242                 }
1243
1244                 // Write opening SGML tags.
1245                 switch (style->latextype) {
1246                 case LATEX_PARAGRAPH:
1247                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1248                         break;
1249
1250                 case LATEX_COMMAND:
1251                         buf->error(ErrorItem(_("Error"), _("LatexType Command not allowed here.\n"), pit->id(), 0, pit->size()));
1252                         return -1;
1253                         break;
1254
1255                 case LATEX_ENVIRONMENT:
1256                 case LATEX_ITEM_ENVIRONMENT:
1257                         if (depth < pit->params().depth()) {
1258                                 depth = pit->params().depth();
1259                                 environment_stack[depth].erase();
1260                         }
1261
1262                         if (environment_stack[depth] != style->latexname()) {
1263                                 if (environment_stack.size() == depth + 1) {
1264                                         environment_stack.push_back("!-- --");
1265                                         environment_inner.push_back("!-- --");
1266                                 }
1267                                 environment_stack[depth] = style->latexname();
1268                                 environment_inner[depth] = "!-- --";
1269                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1270                         } else {
1271                                 if (environment_inner[depth] != "!-- --") {
1272                                         item_name= "listitem";
1273                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1274                                         if (environment_inner[depth] == "varlistentry")
1275                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1276                                 }
1277                         }
1278
1279                         if (style->latextype == LATEX_ENVIRONMENT) {
1280                                 if (!style->latexparam().empty()) {
1281                                         if (style->latexparam() == "CDATA")
1282                                                 os << "<![CDATA[";
1283                                         else
1284                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1285                                 }
1286                                 break;
1287                         }
1288
1289                         desc_on = (style->labeltype == LABEL_MANUAL);
1290
1291                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1292                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1293
1294                         item_name = desc_on ? "term" : "para";
1295                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1296
1297                         break;
1298                 default:
1299                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1300                         break;
1301                 }
1302
1303                 buf->simpleDocBookOnePar(os, pit, desc_on, depth + 1 + command_depth);
1304
1305                 string end_tag;
1306                 // write closing SGML tags
1307                 switch (style->latextype) {
1308                 case LATEX_ENVIRONMENT:
1309                         if (!style->latexparam().empty()) {
1310                                 if (style->latexparam() == "CDATA")
1311                                         os << "]]>";
1312                                 else
1313                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1314                         }
1315                         break;
1316                 case LATEX_ITEM_ENVIRONMENT:
1317                         if (desc_on == 1) break;
1318                         end_tag= "para";
1319                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1320                         break;
1321                 case LATEX_PARAGRAPH:
1322                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1323                         break;
1324                 default:
1325                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1326                         break;
1327                 }
1328         }
1329
1330         // Close open tags
1331         for (int d = depth; d >= 0; --d) {
1332                 if (!environment_stack[depth].empty()) {
1333                         if (environment_inner[depth] != "!-- --") {
1334                                 item_name = "listitem";
1335                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1336                                if (environment_inner[depth] == "varlistentry")
1337                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1338                         }
1339
1340                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1341                 }
1342         }
1343
1344         return lines;
1345 }
1346
1347
1348 void InsetText::validate(LaTeXFeatures & features) const
1349 {
1350         for_each(paragraphs.begin(), paragraphs.end(),
1351                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1352 }
1353
1354
1355 void InsetText::getCursor(BufferView & bv, int & x, int & y) const
1356 {
1357         if (the_locking_inset) {
1358                 the_locking_inset->getCursor(bv, x, y);
1359                 return;
1360         }
1361         x = cx();
1362         y = cy() + InsetText::y();
1363 }
1364
1365
1366 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1367 {
1368         if (the_locking_inset) {
1369                 the_locking_inset->getCursorPos(bv, x, y);
1370                 return;
1371         }
1372         x = cx() - top_x - TEXT_TO_INSET_OFFSET;
1373         y = cy() - TEXT_TO_INSET_OFFSET;
1374 }
1375
1376
1377 int InsetText::insetInInsetY() const
1378 {
1379         if (!the_locking_inset)
1380                 return 0;
1381
1382         return inset_y + the_locking_inset->insetInInsetY();
1383 }
1384
1385
1386 void InsetText::fitInsetCursor(BufferView * bv) const
1387 {
1388         if (the_locking_inset) {
1389                 the_locking_inset->fitInsetCursor(bv);
1390                 return;
1391         }
1392
1393         LyXFont const font = text_.getFont(cpar(), cpos());
1394
1395         int const asc = font_metrics::maxAscent(font);
1396         int const desc = font_metrics::maxDescent(font);
1397
1398         bv->fitLockedInsetCursor(cx(), cy(), asc, desc);
1399 }
1400
1401
1402 InsetOld::RESULT
1403 InsetText::moveRight(BufferView * bv, bool activate_inset, bool selecting)
1404 {
1405         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params))
1406                 return moveLeftIntern(bv, false, activate_inset, selecting);
1407         else
1408                 return moveRightIntern(bv, true, activate_inset, selecting);
1409 }
1410
1411
1412 InsetOld::RESULT
1413 InsetText::moveLeft(BufferView * bv, bool activate_inset, bool selecting)
1414 {
1415         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params))
1416                 return moveRightIntern(bv, true, activate_inset, selecting);
1417         else
1418                 return moveLeftIntern(bv, false, activate_inset, selecting);
1419 }
1420
1421
1422 InsetOld::RESULT
1423 InsetText::moveRightIntern(BufferView * bv, bool front,
1424                            bool activate_inset, bool selecting)
1425 {
1426         ParagraphList::iterator c_par = cpar();
1427
1428         if (boost::next(c_par) == paragraphs.end() && cpos() >= c_par->size())
1429                 return FINISHED_RIGHT;
1430         if (activate_inset && checkAndActivateInset(bv, front))
1431                 return DISPATCHED;
1432         text_.cursorRight(bv);
1433         if (!selecting)
1434                 text_.clearSelection();
1435         return DISPATCHED_NOUPDATE;
1436 }
1437
1438
1439 InsetOld::RESULT
1440 InsetText::moveLeftIntern(BufferView * bv, bool front,
1441                           bool activate_inset, bool selecting)
1442 {
1443         if (cpar() == paragraphs.begin() && cpos() <= 0)
1444                 return FINISHED;
1445         text_.cursorLeft(bv);
1446         if (!selecting)
1447                 text_.clearSelection();
1448         if (activate_inset && checkAndActivateInset(bv, front))
1449                 return DISPATCHED;
1450         return DISPATCHED_NOUPDATE;
1451 }
1452
1453
1454 InsetOld::RESULT InsetText::moveUp(BufferView * bv)
1455 {
1456         if (crow() == text_.rows().begin())
1457                 return FINISHED_UP;
1458         text_.cursorUp(bv);
1459         text_.clearSelection();
1460         return DISPATCHED_NOUPDATE;
1461 }
1462
1463
1464 InsetOld::RESULT InsetText::moveDown(BufferView * bv)
1465 {
1466         if (boost::next(crow()) == text_.rows().end())
1467                 return FINISHED_DOWN;
1468         text_.cursorDown(bv);
1469         text_.clearSelection();
1470         return DISPATCHED_NOUPDATE;
1471 }
1472
1473
1474 bool InsetText::insertInset(BufferView * bv, InsetOld * inset)
1475 {
1476         if (the_locking_inset) {
1477                 if (the_locking_inset->insetAllowed(inset))
1478                         return the_locking_inset->insertInset(bv, inset);
1479                 return false;
1480         }
1481         inset->setOwner(this);
1482         text_.insertInset(inset);
1483         bv->fitCursor();
1484         updateLocal(bv, true);
1485         return true;
1486 }
1487
1488
1489 bool InsetText::insetAllowed(InsetOld::Code code) const
1490 {
1491         // in_insetAllowed is a really gross hack,
1492         // to allow us to call the owner's insetAllowed
1493         // without stack overflow, which can happen
1494         // when the owner uses InsetCollapsable::insetAllowed()
1495         bool ret = true;
1496         if (in_insetAllowed)
1497                 return ret;
1498         in_insetAllowed = true;
1499         if (the_locking_inset)
1500                 ret = the_locking_inset->insetAllowed(code);
1501         else if (owner())
1502                 ret = owner()->insetAllowed(code);
1503         in_insetAllowed = false;
1504         return ret;
1505 }
1506
1507
1508 UpdatableInset * InsetText::getLockingInset() const
1509 {
1510         return the_locking_inset ? the_locking_inset->getLockingInset() :
1511                 const_cast<InsetText *>(this);
1512 }
1513
1514
1515 UpdatableInset * InsetText::getFirstLockingInsetOfType(InsetOld::Code c)
1516 {
1517         if (c == lyxCode())
1518                 return this;
1519         if (the_locking_inset)
1520                 return the_locking_inset->getFirstLockingInsetOfType(c);
1521         return 0;
1522 }
1523
1524
1525 bool InsetText::showInsetDialog(BufferView * bv) const
1526 {
1527         if (the_locking_inset)
1528                 return the_locking_inset->showInsetDialog(bv);
1529         return false;
1530 }
1531
1532
1533 void InsetText::getLabelList(std::vector<string> & list) const
1534 {
1535         ParagraphList::const_iterator pit = paragraphs.begin();
1536         ParagraphList::const_iterator pend = paragraphs.end();
1537         for (; pit != pend; ++pit) {
1538                 InsetList::const_iterator beg = pit->insetlist.begin();
1539                 InsetList::const_iterator end = pit->insetlist.end();
1540                 for (; beg != end; ++beg)
1541                         beg->inset->getLabelList(list);
1542         }
1543 }
1544
1545
1546 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1547                         bool selectall)
1548 {
1549         if (the_locking_inset) {
1550                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1551                 return;
1552         }
1553
1554         if ((paragraphs.size() == 1 && paragraphs.begin()->empty())
1555             || cpar()->empty()) {
1556                 text_.setFont(font, toggleall);
1557                 return;
1558         }
1559
1560
1561         if (text_.selection.set())
1562                 recordUndo(bv, Undo::ATOMIC, text_.cursor.par());
1563
1564         if (selectall) {
1565                 text_.cursorTop();
1566                 text_.selection.cursor = text_.cursor;
1567                 text_.cursorBottom();
1568                 text_.setSelection();
1569         }
1570
1571         text_.toggleFree(font, toggleall);
1572
1573         if (selectall)
1574                 text_.clearSelection();
1575
1576         bv->fitCursor();
1577         updateLocal(bv, true);
1578 }
1579
1580
1581 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1582 {
1583         InsetOld * inset = cpar()->getInset(cpos());
1584         if (!isHighlyEditableInset(inset))
1585                 return false;
1586         FuncRequest cmd(bv, LFUN_INSET_EDIT, front ? "left" : "right");
1587         inset->localDispatch(cmd);
1588         if (!the_locking_inset)
1589                 return false;
1590         updateLocal(bv, false);
1591         return true;
1592 }
1593
1594
1595 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1596                                       mouse_button::state button)
1597 {
1598         x -= drawTextXOffset;
1599         int dummyx = x;
1600         int dummyy = y + dim_.asc;
1601         InsetOld * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1602         // we only do the edit() call if the inset was hit by the mouse
1603         // or if it is a highly editable inset. So we should call this
1604         // function from our own edit with button < 0.
1605         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1606         // WRONG
1607         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1608                 return false;
1609
1610         if (!inset)
1611                 return false;
1612         if (x < 0)
1613                 x = dim_.wid;
1614         if (y < 0)
1615                 y = dim_.des;
1616         inset_x = cix() - top_x + drawTextXOffset;
1617         inset_y = ciy() + drawTextYOffset;
1618         FuncRequest cmd(bv, LFUN_INSET_EDIT, x - inset_x, y - inset_y, button);
1619         inset->localDispatch(cmd);
1620         if (!the_locking_inset)
1621                 return false;
1622         updateLocal(bv, false);
1623         return true;
1624 }
1625
1626
1627 void InsetText::setParagraphData(ParagraphList const & plist)
1628 {
1629         // we have to unlock any locked inset otherwise we're in troubles
1630         the_locking_inset = 0;
1631
1632         // But it it makes no difference that is a lot better.
1633 #warning FIXME.
1634         // See if this can be simplified when std::list is in effect.
1635         paragraphs.clear();
1636
1637         ParagraphList::const_iterator it = plist.begin();
1638         ParagraphList::const_iterator end = plist.end();
1639         for (; it != end; ++it) {
1640                 paragraphs.push_back(*it);
1641                 paragraphs.back().setInsetOwner(this);
1642         }
1643
1644         reinitLyXText();
1645 }
1646
1647
1648 void InsetText::markNew(bool track_changes)
1649 {
1650         ParagraphList::iterator pit = paragraphs.begin();
1651         ParagraphList::iterator pend = paragraphs.end();
1652         for (; pit != pend; ++pit) {
1653                 if (track_changes) {
1654                         pit->trackChanges();
1655                 } else {
1656                         // no-op when not tracking
1657                         pit->cleanChanges();
1658                 }
1659         }
1660 }
1661
1662
1663 void InsetText::setText(string const & data, LyXFont const & font)
1664 {
1665         clear(false);
1666         for (unsigned int i = 0; i < data.length(); ++i)
1667                 paragraphs.begin()->insertChar(i, data[i], font);
1668         reinitLyXText();
1669 }
1670
1671
1672 void InsetText::setAutoBreakRows(bool flag)
1673 {
1674         if (flag != autoBreakRows) {
1675                 autoBreakRows = flag;
1676                 if (!flag)
1677                         removeNewlines();
1678         }
1679 }
1680
1681
1682 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
1683 {
1684         if (how != drawFrame_) {
1685                 drawFrame_ = how;
1686                 updateLocal(bv, false);
1687         }
1688 }
1689
1690
1691 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
1692 {
1693         if (frame_color != col) {
1694                 frame_color = col;
1695                 updateLocal(bv, false);
1696         }
1697 }
1698
1699
1700 int InsetText::cx() const
1701 {
1702         int x = text_.cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
1703         if (the_locking_inset) {
1704                 LyXFont font = text_.getFont(text_.cursor.par(), text_.cursor.pos());
1705                 if (font.isVisibleRightToLeft())
1706                         x -= the_locking_inset->width();
1707         }
1708         return x;
1709 }
1710
1711
1712 int InsetText::cix() const
1713 {
1714         int x = text_.cursor.ix() + top_x + TEXT_TO_INSET_OFFSET;
1715         if (the_locking_inset) {
1716                 LyXFont font = text_.getFont(text_.cursor.par(), text_.cursor.pos());
1717                 if (font.isVisibleRightToLeft())
1718                         x -= the_locking_inset->width();
1719         }
1720         return x;
1721 }
1722
1723
1724 int InsetText::cy() const
1725 {
1726         return text_.cursor.y() - dim_.asc + TEXT_TO_INSET_OFFSET;
1727 }
1728
1729
1730 int InsetText::ciy() const
1731 {
1732         return text_.cursor.iy() - dim_.asc + TEXT_TO_INSET_OFFSET;
1733 }
1734
1735
1736 pos_type InsetText::cpos() const
1737 {
1738         return text_.cursor.pos();
1739 }
1740
1741
1742 ParagraphList::iterator InsetText::cpar() const
1743 {
1744         return text_.cursor.par();
1745 }
1746
1747
1748 bool InsetText::cboundary() const
1749 {
1750         return text_.cursor.boundary();
1751 }
1752
1753
1754 RowList::iterator InsetText::crow() const
1755 {
1756         return text_.cursorRow();
1757 }
1758
1759
1760 LyXText * InsetText::getLyXText(BufferView const * bv,
1761                                 bool const recursive) const
1762 {
1763         setViewCache(bv);
1764         if (recursive && the_locking_inset)
1765                 return the_locking_inset->getLyXText(bv, true);
1766         return &text_;
1767 }
1768
1769
1770 void InsetText::setViewCache(BufferView const * bv) const
1771 {
1772         if (bv)
1773                 text_.bv_owner = const_cast<BufferView *>(bv);
1774 }
1775
1776
1777 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
1778 {
1779         if (recursive) {
1780                 /// then remove all LyXText in text-insets
1781                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1782                          const_cast<ParagraphList&>(paragraphs).end(),
1783                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
1784         }
1785 }
1786
1787
1788 void InsetText::resizeLyXText(BufferView * bv, bool /*force*/) const
1789 {
1790         if (paragraphs.size() == 1 && paragraphs.begin()->empty())
1791                 return;
1792
1793         if (!bv)
1794                 return;
1795
1796         Assert(bv);
1797         setViewCache(bv);
1798
1799         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1800                  const_cast<ParagraphList&>(paragraphs).end(),
1801                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
1802
1803         saveLyXTextState();
1804         text_.init(bv);
1805         restoreLyXTextState();
1806
1807         // seems to be unneeded
1808 #if 1
1809         if (the_locking_inset) {
1810                 inset_x = cix() - top_x + drawTextXOffset;
1811                 inset_y = ciy() + drawTextYOffset;
1812         }
1813
1814         text_.top_y(bv->screen().topCursorVisible(&text_));
1815         if (!owner()) {
1816                 const_cast<InsetText*>(this)->updateLocal(bv, false);
1817                 // this will scroll the screen such that the cursor becomes visible
1818                 bv->updateScrollbar();
1819         }
1820 #endif
1821 }
1822
1823
1824 void InsetText::reinitLyXText() const
1825 {
1826         BufferView * bv = text_.bv_owner;
1827
1828         if (!bv)
1829                 return;
1830
1831         saveLyXTextState();
1832
1833         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1834                  const_cast<ParagraphList&>(paragraphs).end(),
1835                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
1836
1837         text_.init(bv);
1838         restoreLyXTextState();
1839         if (the_locking_inset) {
1840                 inset_x = cix() - top_x + drawTextXOffset;
1841                 inset_y = ciy() + drawTextYOffset;
1842         }
1843         text_.top_y(bv->screen().topCursorVisible(&text_));
1844         if (!owner()) {
1845                 // this will scroll the screen such that the cursor becomes visible
1846                 bv->updateScrollbar();
1847         }
1848 }
1849
1850
1851 void InsetText::removeNewlines()
1852 {
1853         bool changed = false;
1854
1855         ParagraphList::iterator it = paragraphs.begin();
1856         ParagraphList::iterator end = paragraphs.end();
1857         for (; it != end; ++it) {
1858                 for (int i = 0; i < it->size(); ++i) {
1859                         if (it->isNewline(i)) {
1860                                 changed = true;
1861                                 it->erase(i);
1862                         }
1863                 }
1864         }
1865         if (changed)
1866                 reinitLyXText();
1867 }
1868
1869
1870 int InsetText::scroll(bool recursive) const
1871 {
1872         int sx = UpdatableInset::scroll(false);
1873
1874         if (recursive && the_locking_inset)
1875                 sx += the_locking_inset->scroll(recursive);
1876
1877         return sx;
1878 }
1879
1880
1881 void InsetText::clearSelection(BufferView * bv)
1882 {
1883         getLyXText(bv)->clearSelection();
1884 }
1885
1886
1887 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
1888 {
1889         Painter & pain = bv->painter();
1890         int w = dim_.wid;
1891         int h = dim_.asc + dim_.des;
1892         int ty = baseline - dim_.asc;
1893
1894         if (ty < 0) {
1895                 h += ty;
1896                 ty = 0;
1897         }
1898         if (ty + h > pain.paperHeight())
1899                 h = pain.paperHeight();
1900         if (top_x + drawTextXOffset + w > pain.paperWidth())
1901                 w = pain.paperWidth();
1902         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
1903 }
1904
1905
1906 ParagraphList * InsetText::getParagraphs(int i) const
1907 {
1908         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
1909 }
1910
1911
1912 LyXCursor const & InsetText::cursor(BufferView * bv) const
1913 {
1914         if (the_locking_inset)
1915                 return the_locking_inset->cursor(bv);
1916         return getLyXText(bv)->cursor;
1917 }
1918
1919
1920 InsetOld * InsetText::getInsetFromID(int id_arg) const
1921 {
1922         if (id_arg == id())
1923                 return const_cast<InsetText *>(this);
1924
1925         ParagraphList::const_iterator pit = paragraphs.begin();
1926         ParagraphList::const_iterator pend = paragraphs.end();
1927         for (; pit != pend; ++pit) {
1928                 InsetList::const_iterator it = pit->insetlist.begin();
1929                 InsetList::const_iterator end = pit->insetlist.end();
1930                 for (; it != end; ++it) {
1931                         if (it->inset->id() == id_arg)
1932                                 return it->inset;
1933                         InsetOld * in = it->inset->getInsetFromID(id_arg);
1934                         if (in)
1935                                 return in;
1936                 }
1937         }
1938         return 0;
1939 }
1940
1941
1942 WordLangTuple const
1943 InsetText::selectNextWordToSpellcheck(BufferView * bv, float & value) const
1944 {
1945         WordLangTuple word;
1946         if (the_locking_inset) {
1947                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
1948                 if (!word.word().empty()) {
1949                         value += cy();
1950                         return word;
1951                 }
1952                 // we have to go on checking so move cursor to the next char
1953                 text_.cursor.pos(text_.cursor.pos() + 1);
1954         }
1955         word = text_.selectNextWordToSpellcheck(value);
1956         if (word.word().empty())
1957                 bv->unlockInset(const_cast<InsetText *>(this));
1958         else
1959                 value = cy();
1960         return word;
1961 }
1962
1963
1964 void InsetText::selectSelectedWord(BufferView * bv)
1965 {
1966         if (the_locking_inset) {
1967                 the_locking_inset->selectSelectedWord(bv);
1968                 return;
1969         }
1970         getLyXText(bv)->selectSelectedWord();
1971         updateLocal(bv, false);
1972 }
1973
1974
1975 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
1976 {
1977         if (the_locking_inset) {
1978                 if (the_locking_inset->nextChange(bv, length))
1979                         return true;
1980                 text_.cursorRight(true);
1981         }
1982         lyx::find::SearchResult result =
1983                 lyx::find::findNextChange(bv, &text_, length);
1984
1985         if (result == lyx::find::SR_FOUND) {
1986                 LyXCursor cur = text_.cursor;
1987                 bv->unlockInset(bv->theLockingInset());
1988                 if (bv->lockInset(this))
1989                         locked = true;
1990                 text_.cursor = cur;
1991                 text_.setSelectionRange(length);
1992                 updateLocal(bv, false);
1993         }
1994         return result != lyx::find::SR_NOT_FOUND;
1995 }
1996
1997
1998 bool InsetText::searchForward(BufferView * bv, string const & str,
1999                               bool cs, bool mw)
2000 {
2001         if (the_locking_inset) {
2002                 if (the_locking_inset->searchForward(bv, str, cs, mw))
2003                         return true;
2004                 text_.cursorRight(true);
2005         }
2006         lyx::find::SearchResult result =
2007                 lyx::find::find(bv, &text_, str, true, cs, mw);
2008
2009         if (result == lyx::find::SR_FOUND) {
2010                 LyXCursor cur = text_.cursor;
2011                 bv->unlockInset(bv->theLockingInset());
2012                 if (bv->lockInset(this))
2013                         locked = true;
2014                 text_.cursor = cur;
2015                 text_.setSelectionRange(str.length());
2016                 updateLocal(bv, false);
2017         }
2018         return result != lyx::find::SR_NOT_FOUND;
2019 }
2020
2021
2022 bool InsetText::searchBackward(BufferView * bv, string const & str,
2023                                bool cs, bool mw)
2024 {
2025         if (the_locking_inset) {
2026                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2027                         return true;
2028         }
2029         if (!locked) {
2030                 ParagraphList::iterator pit = paragraphs.begin();
2031                 ParagraphList::iterator pend = paragraphs.end();
2032
2033                 while (boost::next(pit) != pend)
2034                         ++pit;
2035
2036                 text_.setCursor(pit, pit->size());
2037         }
2038         lyx::find::SearchResult result =
2039                 lyx::find::find(bv, &text_, str, false, cs, mw);
2040
2041         if (result == lyx::find::SR_FOUND) {
2042                 LyXCursor cur = text_.cursor;
2043                 bv->unlockInset(bv->theLockingInset());
2044                 if (bv->lockInset(this))
2045                         locked = true;
2046                 text_.cursor = cur;
2047                 text_.setSelectionRange(str.length());
2048                 updateLocal(bv, false);
2049         }
2050         return result != lyx::find::SR_NOT_FOUND;
2051 }
2052
2053
2054 bool InsetText::checkInsertChar(LyXFont & font)
2055 {
2056         return owner() ? owner()->checkInsertChar(font) : true;
2057 }
2058
2059
2060 void InsetText::collapseParagraphs(BufferView * bv)
2061 {
2062         while (paragraphs.size() > 1) {
2063                 ParagraphList::iterator first_par = paragraphs.begin();
2064                 ParagraphList::iterator next_par = boost::next(first_par);
2065                 size_t const first_par_size = first_par->size();
2066
2067                 if (!first_par->empty() &&
2068                     !next_par->empty() &&
2069                     !first_par->isSeparator(first_par_size - 1)) {
2070                         first_par->insertChar(first_par_size, ' ');
2071                 }
2072
2073                 if (text_.selection.set()) {
2074                         if (text_.selection.start.par() == next_par) {
2075                                 text_.selection.start.par(first_par);
2076                                 text_.selection.start.pos(
2077                                         text_.selection.start.pos() + first_par_size);
2078                         }
2079                         if (text_.selection.end.par() == next_par) {
2080                                 text_.selection.end.par(first_par);
2081                                 text_.selection.end.pos(
2082                                         text_.selection.end.pos() + first_par_size);
2083                         }
2084                 }
2085
2086                 mergeParagraph(bv->buffer()->params, paragraphs, first_par);
2087         }
2088         reinitLyXText();
2089 }
2090
2091
2092 void InsetText::getDrawFont(LyXFont & font) const
2093 {
2094         if (!owner())
2095                 return;
2096         owner()->getDrawFont(font);
2097 }
2098
2099
2100 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
2101 {
2102 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
2103 // And it probably does. You have to take a look at this John. (Lgb)
2104 #warning John, have a look here. (Lgb)
2105         ParagraphList::iterator pit = plist.begin();
2106         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(), *pit);
2107         ++pit;
2108         mergeParagraph(buffer->params, paragraphs, boost::prior(ins));
2109
2110         ParagraphList::iterator pend = plist.end();
2111         for (; pit != pend; ++pit)
2112                 paragraphs.push_back(*pit);
2113
2114         reinitLyXText();
2115 }
2116
2117
2118 void InsetText::addPreview(PreviewLoader & loader) const
2119 {
2120         ParagraphList::const_iterator pit = paragraphs.begin();
2121         ParagraphList::const_iterator pend = paragraphs.end();
2122
2123         for (; pit != pend; ++pit) {
2124                 InsetList::const_iterator it  = pit->insetlist.begin();
2125                 InsetList::const_iterator end = pit->insetlist.end();
2126                 for (; it != end; ++it)
2127                         it->inset->addPreview(loader);
2128         }
2129 }