]> git.lyx.org Git - lyx.git/blob - src/insets/insettext.C
insettext.C (localDispatch): merge cases with default branch
[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         default:
1097                 if (!bv->dispatch(cmd))
1098                         result = UNDISPATCHED;
1099                 break;
1100         }
1101
1102         updateLocal(bv, updflag);
1103
1104         /// If the action has deleted all text in the inset, we need to change the
1105         // language to the language of the surronding text.
1106         if (!was_empty && paragraphs.begin()->empty() &&
1107             paragraphs.size() == 1) {
1108                 LyXFont font(LyXFont::ALL_IGNORE);
1109                 font.setLanguage(bv->getParentLanguage(this));
1110                 setFont(bv, font, false);
1111         }
1112
1113         if (result >= FINISHED)
1114                 bv->unlockInset(this);
1115
1116         if (result == DISPATCHED_NOUPDATE)
1117                 result = DISPATCHED;
1118         return result;
1119 }
1120
1121
1122 int InsetText::latex(Buffer const * buf, ostream & os,
1123                      LatexRunParams const & runparams) const
1124 {
1125         TexRow texrow;
1126         latexParagraphs(buf, paragraphs, os, texrow, runparams);
1127         return texrow.rows();
1128 }
1129
1130
1131 int InsetText::ascii(Buffer const * buf, ostream & os, int linelen) const
1132 {
1133         unsigned int lines = 0;
1134
1135         ParagraphList::const_iterator beg = paragraphs.begin();
1136         ParagraphList::const_iterator end = paragraphs.end();
1137         ParagraphList::const_iterator it = beg;
1138         for (; it != end; ++it) {
1139                 string const tmp = buf->asciiParagraph(*it, linelen, it == beg);
1140                 lines += lyx::count(tmp.begin(), tmp.end(), '\n');
1141                 os << tmp;
1142         }
1143         return lines;
1144 }
1145
1146
1147 int InsetText::linuxdoc(Buffer const * buf, ostream & os) const
1148 {
1149         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1150         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1151
1152         // There is a confusion between the empty paragraph and the default paragraph
1153         // The default paragraph is <p></p>, the empty paragraph is *empty*
1154         // Since none of the floats of linuxdoc accepts standard paragraphs
1155         // I disable them. I don't expect problems. (jamatos 2003/07/27)
1156         for (; pit != pend; ++pit) {
1157                 const string name = pit->layout()->latexname();
1158                 if (name != "p")
1159                         sgml::openTag(os, 1, 0, name);
1160                 buf->simpleLinuxDocOnePar(os, pit, 0);
1161                 if (name != "p")
1162                         sgml::closeTag(os, 1, 0, name);
1163         }
1164         return 0;
1165 }
1166
1167
1168 int InsetText::docbook(Buffer const * buf, ostream & os, bool mixcont) const
1169 {
1170         unsigned int lines = 0;
1171
1172         vector<string> environment_stack(10);
1173         vector<string> environment_inner(10);
1174
1175         int const command_depth = 0;
1176         string item_name;
1177
1178         Paragraph::depth_type depth = 0; // paragraph depth
1179
1180         ParagraphList::iterator pit = const_cast<ParagraphList&>(paragraphs).begin();
1181         ParagraphList::iterator pend = const_cast<ParagraphList&>(paragraphs).end();
1182
1183         for (; pit != pend; ++pit) {
1184                 string sgmlparam;
1185                 int desc_on = 0; // description mode
1186
1187                 LyXLayout_ptr const & style = pit->layout();
1188
1189                 // environment tag closing
1190                 for (; depth > pit->params().depth(); --depth) {
1191                         if (environment_inner[depth] != "!-- --") {
1192                                 item_name = "listitem";
1193                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1194                                 if (environment_inner[depth] == "varlistentry")
1195                                         lines += sgml::closeTag(os, depth+command_depth, mixcont, environment_inner[depth]);
1196                         }
1197                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1198                         environment_stack[depth].erase();
1199                         environment_inner[depth].erase();
1200                 }
1201
1202                 if (depth == pit->params().depth()
1203                    && environment_stack[depth] != style->latexname()
1204                    && !environment_stack[depth].empty()) {
1205                         if (environment_inner[depth] != "!-- --") {
1206                                 item_name= "listitem";
1207                                 lines += sgml::closeTag(os, command_depth+depth, mixcont, item_name);
1208                                 if (environment_inner[depth] == "varlistentry")
1209                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1210                         }
1211
1212                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1213
1214                         environment_stack[depth].erase();
1215                         environment_inner[depth].erase();
1216                 }
1217
1218                 // Write opening SGML tags.
1219                 switch (style->latextype) {
1220                 case LATEX_PARAGRAPH:
1221                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1222                         break;
1223
1224                 case LATEX_COMMAND:
1225                         buf->error(ErrorItem(_("Error"), _("LatexType Command not allowed here.\n"), pit->id(), 0, pit->size()));
1226                         return -1;
1227                         break;
1228
1229                 case LATEX_ENVIRONMENT:
1230                 case LATEX_ITEM_ENVIRONMENT:
1231                         if (depth < pit->params().depth()) {
1232                                 depth = pit->params().depth();
1233                                 environment_stack[depth].erase();
1234                         }
1235
1236                         if (environment_stack[depth] != style->latexname()) {
1237                                 if (environment_stack.size() == depth + 1) {
1238                                         environment_stack.push_back("!-- --");
1239                                         environment_inner.push_back("!-- --");
1240                                 }
1241                                 environment_stack[depth] = style->latexname();
1242                                 environment_inner[depth] = "!-- --";
1243                                 lines += sgml::openTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1244                         } else {
1245                                 if (environment_inner[depth] != "!-- --") {
1246                                         item_name= "listitem";
1247                                         lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1248                                         if (environment_inner[depth] == "varlistentry")
1249                                                 lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1250                                 }
1251                         }
1252
1253                         if (style->latextype == LATEX_ENVIRONMENT) {
1254                                 if (!style->latexparam().empty()) {
1255                                         if (style->latexparam() == "CDATA")
1256                                                 os << "<![CDATA[";
1257                                         else
1258                                           lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexparam());
1259                                 }
1260                                 break;
1261                         }
1262
1263                         desc_on = (style->labeltype == LABEL_MANUAL);
1264
1265                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
1266                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, environment_inner[depth]);
1267
1268                         item_name = desc_on ? "term" : "para";
1269                         lines += sgml::openTag(os, depth + 1 + command_depth, mixcont, item_name);
1270
1271                         break;
1272                 default:
1273                         lines += sgml::openTag(os, depth + command_depth, mixcont, style->latexname());
1274                         break;
1275                 }
1276
1277                 buf->simpleDocBookOnePar(os, pit, desc_on, depth + 1 + command_depth);
1278
1279                 string end_tag;
1280                 // write closing SGML tags
1281                 switch (style->latextype) {
1282                 case LATEX_ENVIRONMENT:
1283                         if (!style->latexparam().empty()) {
1284                                 if (style->latexparam() == "CDATA")
1285                                         os << "]]>";
1286                                 else
1287                                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexparam());
1288                         }
1289                         break;
1290                 case LATEX_ITEM_ENVIRONMENT:
1291                         if (desc_on == 1) break;
1292                         end_tag= "para";
1293                         lines += sgml::closeTag(os, depth + 1 + command_depth, mixcont, end_tag);
1294                         break;
1295                 case LATEX_PARAGRAPH:
1296                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1297                         break;
1298                 default:
1299                         lines += sgml::closeTag(os, depth + command_depth, mixcont, style->latexname());
1300                         break;
1301                 }
1302         }
1303
1304         // Close open tags
1305         for (int d = depth; d >= 0; --d) {
1306                 if (!environment_stack[depth].empty()) {
1307                         if (environment_inner[depth] != "!-- --") {
1308                                 item_name = "listitem";
1309                                 lines += sgml::closeTag(os, command_depth + depth, mixcont, item_name);
1310                                if (environment_inner[depth] == "varlistentry")
1311                                        lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_inner[depth]);
1312                         }
1313
1314                         lines += sgml::closeTag(os, depth + command_depth, mixcont, environment_stack[depth]);
1315                 }
1316         }
1317
1318         return lines;
1319 }
1320
1321
1322 void InsetText::validate(LaTeXFeatures & features) const
1323 {
1324         for_each(paragraphs.begin(), paragraphs.end(),
1325                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1326 }
1327
1328
1329 void InsetText::getCursor(BufferView & bv, int & x, int & y) const
1330 {
1331         if (the_locking_inset) {
1332                 the_locking_inset->getCursor(bv, x, y);
1333                 return;
1334         }
1335         x = cx();
1336         y = cy() + InsetText::y();
1337 }
1338
1339
1340 void InsetText::getCursorPos(BufferView * bv, int & x, int & y) const
1341 {
1342         if (the_locking_inset) {
1343                 the_locking_inset->getCursorPos(bv, x, y);
1344                 return;
1345         }
1346         x = cx() - top_x - TEXT_TO_INSET_OFFSET;
1347         y = cy() - TEXT_TO_INSET_OFFSET;
1348 }
1349
1350
1351 int InsetText::insetInInsetY() const
1352 {
1353         if (!the_locking_inset)
1354                 return 0;
1355
1356         return inset_y + the_locking_inset->insetInInsetY();
1357 }
1358
1359
1360 void InsetText::fitInsetCursor(BufferView * bv) const
1361 {
1362         if (the_locking_inset) {
1363                 the_locking_inset->fitInsetCursor(bv);
1364                 return;
1365         }
1366
1367         LyXFont const font = text_.getFont(cpar(), cpos());
1368
1369         int const asc = font_metrics::maxAscent(font);
1370         int const desc = font_metrics::maxDescent(font);
1371
1372         bv->fitLockedInsetCursor(cx(), cy(), asc, desc);
1373 }
1374
1375
1376 InsetOld::RESULT
1377 InsetText::moveRight(BufferView * bv, bool activate_inset, bool selecting)
1378 {
1379         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params))
1380                 return moveLeftIntern(bv, false, activate_inset, selecting);
1381         else
1382                 return moveRightIntern(bv, true, activate_inset, selecting);
1383 }
1384
1385
1386 InsetOld::RESULT
1387 InsetText::moveLeft(BufferView * bv, bool activate_inset, bool selecting)
1388 {
1389         if (text_.cursor.par()->isRightToLeftPar(bv->buffer()->params))
1390                 return moveRightIntern(bv, true, activate_inset, selecting);
1391         else
1392                 return moveLeftIntern(bv, false, activate_inset, selecting);
1393 }
1394
1395
1396 InsetOld::RESULT
1397 InsetText::moveRightIntern(BufferView * bv, bool front,
1398                            bool activate_inset, bool selecting)
1399 {
1400         ParagraphList::iterator c_par = cpar();
1401
1402         if (boost::next(c_par) == paragraphs.end() && cpos() >= c_par->size())
1403                 return FINISHED_RIGHT;
1404         if (activate_inset && checkAndActivateInset(bv, front))
1405                 return DISPATCHED;
1406         text_.cursorRight(bv);
1407         if (!selecting)
1408                 text_.clearSelection();
1409         return DISPATCHED_NOUPDATE;
1410 }
1411
1412
1413 InsetOld::RESULT
1414 InsetText::moveLeftIntern(BufferView * bv, bool front,
1415                           bool activate_inset, bool selecting)
1416 {
1417         if (cpar() == paragraphs.begin() && cpos() <= 0)
1418                 return FINISHED;
1419         text_.cursorLeft(bv);
1420         if (!selecting)
1421                 text_.clearSelection();
1422         if (activate_inset && checkAndActivateInset(bv, front))
1423                 return DISPATCHED;
1424         return DISPATCHED_NOUPDATE;
1425 }
1426
1427
1428 InsetOld::RESULT InsetText::moveUp(BufferView * bv)
1429 {
1430         if (crow() == text_.rows().begin())
1431                 return FINISHED_UP;
1432         text_.cursorUp(bv);
1433         text_.clearSelection();
1434         return DISPATCHED_NOUPDATE;
1435 }
1436
1437
1438 InsetOld::RESULT InsetText::moveDown(BufferView * bv)
1439 {
1440         if (boost::next(crow()) == text_.rows().end())
1441                 return FINISHED_DOWN;
1442         text_.cursorDown(bv);
1443         text_.clearSelection();
1444         return DISPATCHED_NOUPDATE;
1445 }
1446
1447
1448 bool InsetText::insertInset(BufferView * bv, InsetOld * inset)
1449 {
1450         if (the_locking_inset) {
1451                 if (the_locking_inset->insetAllowed(inset))
1452                         return the_locking_inset->insertInset(bv, inset);
1453                 return false;
1454         }
1455         inset->setOwner(this);
1456         text_.insertInset(inset);
1457         bv->fitCursor();
1458         updateLocal(bv, true);
1459         return true;
1460 }
1461
1462
1463 bool InsetText::insetAllowed(InsetOld::Code code) const
1464 {
1465         // in_insetAllowed is a really gross hack,
1466         // to allow us to call the owner's insetAllowed
1467         // without stack overflow, which can happen
1468         // when the owner uses InsetCollapsable::insetAllowed()
1469         bool ret = true;
1470         if (in_insetAllowed)
1471                 return ret;
1472         in_insetAllowed = true;
1473         if (the_locking_inset)
1474                 ret = the_locking_inset->insetAllowed(code);
1475         else if (owner())
1476                 ret = owner()->insetAllowed(code);
1477         in_insetAllowed = false;
1478         return ret;
1479 }
1480
1481
1482 UpdatableInset * InsetText::getLockingInset() const
1483 {
1484         return the_locking_inset ? the_locking_inset->getLockingInset() :
1485                 const_cast<InsetText *>(this);
1486 }
1487
1488
1489 UpdatableInset * InsetText::getFirstLockingInsetOfType(InsetOld::Code c)
1490 {
1491         if (c == lyxCode())
1492                 return this;
1493         if (the_locking_inset)
1494                 return the_locking_inset->getFirstLockingInsetOfType(c);
1495         return 0;
1496 }
1497
1498
1499 bool InsetText::showInsetDialog(BufferView * bv) const
1500 {
1501         if (the_locking_inset)
1502                 return the_locking_inset->showInsetDialog(bv);
1503         return false;
1504 }
1505
1506
1507 void InsetText::getLabelList(std::vector<string> & list) const
1508 {
1509         ParagraphList::const_iterator pit = paragraphs.begin();
1510         ParagraphList::const_iterator pend = paragraphs.end();
1511         for (; pit != pend; ++pit) {
1512                 InsetList::const_iterator beg = pit->insetlist.begin();
1513                 InsetList::const_iterator end = pit->insetlist.end();
1514                 for (; beg != end; ++beg)
1515                         beg->inset->getLabelList(list);
1516         }
1517 }
1518
1519
1520 void InsetText::setFont(BufferView * bv, LyXFont const & font, bool toggleall,
1521                         bool selectall)
1522 {
1523         if (the_locking_inset) {
1524                 the_locking_inset->setFont(bv, font, toggleall, selectall);
1525                 return;
1526         }
1527
1528         if ((paragraphs.size() == 1 && paragraphs.begin()->empty())
1529             || cpar()->empty()) {
1530                 text_.setFont(font, toggleall);
1531                 return;
1532         }
1533
1534
1535         if (text_.selection.set())
1536                 recordUndo(bv, Undo::ATOMIC, text_.cursor.par());
1537
1538         if (selectall) {
1539                 text_.cursorTop();
1540                 text_.selection.cursor = text_.cursor;
1541                 text_.cursorBottom();
1542                 text_.setSelection();
1543         }
1544
1545         text_.toggleFree(font, toggleall);
1546
1547         if (selectall)
1548                 text_.clearSelection();
1549
1550         bv->fitCursor();
1551         updateLocal(bv, true);
1552 }
1553
1554
1555 bool InsetText::checkAndActivateInset(BufferView * bv, bool front)
1556 {
1557         InsetOld * inset = cpar()->getInset(cpos());
1558         if (!isHighlyEditableInset(inset))
1559                 return false;
1560         FuncRequest cmd(bv, LFUN_INSET_EDIT, front ? "left" : "right");
1561         inset->localDispatch(cmd);
1562         if (!the_locking_inset)
1563                 return false;
1564         updateLocal(bv, false);
1565         return true;
1566 }
1567
1568
1569 bool InsetText::checkAndActivateInset(BufferView * bv, int x, int y,
1570                                       mouse_button::state button)
1571 {
1572         x -= drawTextXOffset;
1573         int dummyx = x;
1574         int dummyy = y + dim_.asc;
1575         InsetOld * inset = getLyXText(bv)->checkInsetHit(dummyx, dummyy);
1576         // we only do the edit() call if the inset was hit by the mouse
1577         // or if it is a highly editable inset. So we should call this
1578         // function from our own edit with button < 0.
1579         // FIXME: GUII jbl. I've changed this to ::none for now which is probably
1580         // WRONG
1581         if (button == mouse_button::none && !isHighlyEditableInset(inset))
1582                 return false;
1583
1584         if (!inset)
1585                 return false;
1586         if (x < 0)
1587                 x = dim_.wid;
1588         if (y < 0)
1589                 y = dim_.des;
1590         inset_x = cix() - top_x + drawTextXOffset;
1591         inset_y = ciy() + drawTextYOffset;
1592         FuncRequest cmd(bv, LFUN_INSET_EDIT, x - inset_x, y - inset_y, button);
1593         inset->localDispatch(cmd);
1594         if (!the_locking_inset)
1595                 return false;
1596         updateLocal(bv, false);
1597         return true;
1598 }
1599
1600
1601 void InsetText::setParagraphData(ParagraphList const & plist)
1602 {
1603         // we have to unlock any locked inset otherwise we're in troubles
1604         the_locking_inset = 0;
1605
1606         // But it it makes no difference that is a lot better.
1607 #warning FIXME.
1608         // See if this can be simplified when std::list is in effect.
1609         paragraphs.clear();
1610
1611         ParagraphList::const_iterator it = plist.begin();
1612         ParagraphList::const_iterator end = plist.end();
1613         for (; it != end; ++it) {
1614                 paragraphs.push_back(*it);
1615                 paragraphs.back().setInsetOwner(this);
1616         }
1617
1618         reinitLyXText();
1619 }
1620
1621
1622 void InsetText::markNew(bool track_changes)
1623 {
1624         ParagraphList::iterator pit = paragraphs.begin();
1625         ParagraphList::iterator pend = paragraphs.end();
1626         for (; pit != pend; ++pit) {
1627                 if (track_changes) {
1628                         pit->trackChanges();
1629                 } else {
1630                         // no-op when not tracking
1631                         pit->cleanChanges();
1632                 }
1633         }
1634 }
1635
1636
1637 void InsetText::setText(string const & data, LyXFont const & font)
1638 {
1639         clear(false);
1640         for (unsigned int i = 0; i < data.length(); ++i)
1641                 paragraphs.begin()->insertChar(i, data[i], font);
1642         reinitLyXText();
1643 }
1644
1645
1646 void InsetText::setAutoBreakRows(bool flag)
1647 {
1648         if (flag != autoBreakRows) {
1649                 autoBreakRows = flag;
1650                 if (!flag)
1651                         removeNewlines();
1652         }
1653 }
1654
1655
1656 void InsetText::setDrawFrame(BufferView * bv, DrawFrame how)
1657 {
1658         if (how != drawFrame_) {
1659                 drawFrame_ = how;
1660                 updateLocal(bv, false);
1661         }
1662 }
1663
1664
1665 void InsetText::setFrameColor(BufferView * bv, LColor::color col)
1666 {
1667         if (frame_color != col) {
1668                 frame_color = col;
1669                 updateLocal(bv, false);
1670         }
1671 }
1672
1673
1674 int InsetText::cx() const
1675 {
1676         int x = text_.cursor.x() + top_x + TEXT_TO_INSET_OFFSET;
1677         if (the_locking_inset) {
1678                 LyXFont font = text_.getFont(text_.cursor.par(), text_.cursor.pos());
1679                 if (font.isVisibleRightToLeft())
1680                         x -= the_locking_inset->width();
1681         }
1682         return x;
1683 }
1684
1685
1686 int InsetText::cix() const
1687 {
1688         int x = text_.cursor.ix() + top_x + TEXT_TO_INSET_OFFSET;
1689         if (the_locking_inset) {
1690                 LyXFont font = text_.getFont(text_.cursor.par(), text_.cursor.pos());
1691                 if (font.isVisibleRightToLeft())
1692                         x -= the_locking_inset->width();
1693         }
1694         return x;
1695 }
1696
1697
1698 int InsetText::cy() const
1699 {
1700         return text_.cursor.y() - dim_.asc + TEXT_TO_INSET_OFFSET;
1701 }
1702
1703
1704 int InsetText::ciy() const
1705 {
1706         return text_.cursor.iy() - dim_.asc + TEXT_TO_INSET_OFFSET;
1707 }
1708
1709
1710 pos_type InsetText::cpos() const
1711 {
1712         return text_.cursor.pos();
1713 }
1714
1715
1716 ParagraphList::iterator InsetText::cpar() const
1717 {
1718         return text_.cursor.par();
1719 }
1720
1721
1722 bool InsetText::cboundary() const
1723 {
1724         return text_.cursor.boundary();
1725 }
1726
1727
1728 RowList::iterator InsetText::crow() const
1729 {
1730         return text_.cursorRow();
1731 }
1732
1733
1734 LyXText * InsetText::getLyXText(BufferView const * bv,
1735                                 bool const recursive) const
1736 {
1737         setViewCache(bv);
1738         if (recursive && the_locking_inset)
1739                 return the_locking_inset->getLyXText(bv, true);
1740         return &text_;
1741 }
1742
1743
1744 void InsetText::setViewCache(BufferView const * bv) const
1745 {
1746         if (bv)
1747                 text_.bv_owner = const_cast<BufferView *>(bv);
1748 }
1749
1750
1751 void InsetText::deleteLyXText(BufferView * bv, bool recursive) const
1752 {
1753         if (recursive) {
1754                 /// then remove all LyXText in text-insets
1755                 for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1756                          const_cast<ParagraphList&>(paragraphs).end(),
1757                          boost::bind(&Paragraph::deleteInsetsLyXText, _1, bv));
1758         }
1759 }
1760
1761
1762 void InsetText::resizeLyXText(BufferView * bv, bool /*force*/) const
1763 {
1764         if (paragraphs.size() == 1 && paragraphs.begin()->empty())
1765                 return;
1766
1767         if (!bv)
1768                 return;
1769
1770         Assert(bv);
1771         setViewCache(bv);
1772
1773         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1774                  const_cast<ParagraphList&>(paragraphs).end(),
1775                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
1776
1777         saveLyXTextState();
1778         text_.init(bv);
1779         restoreLyXTextState();
1780
1781         // seems to be unneeded
1782 #if 1
1783         if (the_locking_inset) {
1784                 inset_x = cix() - top_x + drawTextXOffset;
1785                 inset_y = ciy() + drawTextYOffset;
1786         }
1787
1788         text_.top_y(bv->screen().topCursorVisible(&text_));
1789         if (!owner()) {
1790                 const_cast<InsetText*>(this)->updateLocal(bv, false);
1791                 // this will scroll the screen such that the cursor becomes visible
1792                 bv->updateScrollbar();
1793         }
1794 #endif
1795 }
1796
1797
1798 void InsetText::reinitLyXText() const
1799 {
1800         BufferView * bv = text_.bv_owner;
1801
1802         if (!bv)
1803                 return;
1804
1805         saveLyXTextState();
1806
1807         for_each(const_cast<ParagraphList&>(paragraphs).begin(),
1808                  const_cast<ParagraphList&>(paragraphs).end(),
1809                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
1810
1811         text_.init(bv);
1812         restoreLyXTextState();
1813         if (the_locking_inset) {
1814                 inset_x = cix() - top_x + drawTextXOffset;
1815                 inset_y = ciy() + drawTextYOffset;
1816         }
1817         text_.top_y(bv->screen().topCursorVisible(&text_));
1818         if (!owner()) {
1819                 // this will scroll the screen such that the cursor becomes visible
1820                 bv->updateScrollbar();
1821         }
1822 }
1823
1824
1825 void InsetText::removeNewlines()
1826 {
1827         bool changed = false;
1828
1829         ParagraphList::iterator it = paragraphs.begin();
1830         ParagraphList::iterator end = paragraphs.end();
1831         for (; it != end; ++it) {
1832                 for (int i = 0; i < it->size(); ++i) {
1833                         if (it->isNewline(i)) {
1834                                 changed = true;
1835                                 it->erase(i);
1836                         }
1837                 }
1838         }
1839         if (changed)
1840                 reinitLyXText();
1841 }
1842
1843
1844 int InsetText::scroll(bool recursive) const
1845 {
1846         int sx = UpdatableInset::scroll(false);
1847
1848         if (recursive && the_locking_inset)
1849                 sx += the_locking_inset->scroll(recursive);
1850
1851         return sx;
1852 }
1853
1854
1855 void InsetText::clearSelection(BufferView * bv)
1856 {
1857         getLyXText(bv)->clearSelection();
1858 }
1859
1860
1861 void InsetText::clearInset(BufferView * bv, int start_x, int baseline) const
1862 {
1863         Painter & pain = bv->painter();
1864         int w = dim_.wid;
1865         int h = dim_.asc + dim_.des;
1866         int ty = baseline - dim_.asc;
1867
1868         if (ty < 0) {
1869                 h += ty;
1870                 ty = 0;
1871         }
1872         if (ty + h > pain.paperHeight())
1873                 h = pain.paperHeight();
1874         if (top_x + drawTextXOffset + w > pain.paperWidth())
1875                 w = pain.paperWidth();
1876         pain.fillRectangle(start_x + 1, ty + 1, w - 3, h - 1, backgroundColor());
1877 }
1878
1879
1880 ParagraphList * InsetText::getParagraphs(int i) const
1881 {
1882         return (i == 0) ? const_cast<ParagraphList*>(&paragraphs) : 0;
1883 }
1884
1885
1886 LyXCursor const & InsetText::cursor(BufferView * bv) const
1887 {
1888         if (the_locking_inset)
1889                 return the_locking_inset->cursor(bv);
1890         return getLyXText(bv)->cursor;
1891 }
1892
1893
1894 InsetOld * InsetText::getInsetFromID(int id_arg) const
1895 {
1896         if (id_arg == id())
1897                 return const_cast<InsetText *>(this);
1898
1899         ParagraphList::const_iterator pit = paragraphs.begin();
1900         ParagraphList::const_iterator pend = paragraphs.end();
1901         for (; pit != pend; ++pit) {
1902                 InsetList::const_iterator it = pit->insetlist.begin();
1903                 InsetList::const_iterator end = pit->insetlist.end();
1904                 for (; it != end; ++it) {
1905                         if (it->inset->id() == id_arg)
1906                                 return it->inset;
1907                         InsetOld * in = it->inset->getInsetFromID(id_arg);
1908                         if (in)
1909                                 return in;
1910                 }
1911         }
1912         return 0;
1913 }
1914
1915
1916 WordLangTuple const
1917 InsetText::selectNextWordToSpellcheck(BufferView * bv, float & value) const
1918 {
1919         WordLangTuple word;
1920         if (the_locking_inset) {
1921                 word = the_locking_inset->selectNextWordToSpellcheck(bv, value);
1922                 if (!word.word().empty()) {
1923                         value += cy();
1924                         return word;
1925                 }
1926                 // we have to go on checking so move cursor to the next char
1927                 text_.cursor.pos(text_.cursor.pos() + 1);
1928         }
1929         word = text_.selectNextWordToSpellcheck(value);
1930         if (word.word().empty())
1931                 bv->unlockInset(const_cast<InsetText *>(this));
1932         else
1933                 value = cy();
1934         return word;
1935 }
1936
1937
1938 void InsetText::selectSelectedWord(BufferView * bv)
1939 {
1940         if (the_locking_inset) {
1941                 the_locking_inset->selectSelectedWord(bv);
1942                 return;
1943         }
1944         getLyXText(bv)->selectSelectedWord();
1945         updateLocal(bv, false);
1946 }
1947
1948
1949 bool InsetText::nextChange(BufferView * bv, lyx::pos_type & length)
1950 {
1951         if (the_locking_inset) {
1952                 if (the_locking_inset->nextChange(bv, length))
1953                         return true;
1954                 text_.cursorRight(true);
1955         }
1956         lyx::find::SearchResult result =
1957                 lyx::find::findNextChange(bv, &text_, length);
1958
1959         if (result == lyx::find::SR_FOUND) {
1960                 LyXCursor cur = text_.cursor;
1961                 bv->unlockInset(bv->theLockingInset());
1962                 if (bv->lockInset(this))
1963                         locked = true;
1964                 text_.cursor = cur;
1965                 text_.setSelectionRange(length);
1966                 updateLocal(bv, false);
1967         }
1968         return result != lyx::find::SR_NOT_FOUND;
1969 }
1970
1971
1972 bool InsetText::searchForward(BufferView * bv, string const & str,
1973                               bool cs, bool mw)
1974 {
1975         if (the_locking_inset) {
1976                 if (the_locking_inset->searchForward(bv, str, cs, mw))
1977                         return true;
1978                 text_.cursorRight(true);
1979         }
1980         lyx::find::SearchResult result =
1981                 lyx::find::find(bv, &text_, str, true, cs, mw);
1982
1983         if (result == lyx::find::SR_FOUND) {
1984                 LyXCursor cur = text_.cursor;
1985                 bv->unlockInset(bv->theLockingInset());
1986                 if (bv->lockInset(this))
1987                         locked = true;
1988                 text_.cursor = cur;
1989                 text_.setSelectionRange(str.length());
1990                 updateLocal(bv, false);
1991         }
1992         return result != lyx::find::SR_NOT_FOUND;
1993 }
1994
1995
1996 bool InsetText::searchBackward(BufferView * bv, string const & str,
1997                                bool cs, bool mw)
1998 {
1999         if (the_locking_inset) {
2000                 if (the_locking_inset->searchBackward(bv, str, cs, mw))
2001                         return true;
2002         }
2003         if (!locked) {
2004                 ParagraphList::iterator pit = paragraphs.begin();
2005                 ParagraphList::iterator pend = paragraphs.end();
2006
2007                 while (boost::next(pit) != pend)
2008                         ++pit;
2009
2010                 text_.setCursor(pit, pit->size());
2011         }
2012         lyx::find::SearchResult result =
2013                 lyx::find::find(bv, &text_, str, false, cs, mw);
2014
2015         if (result == lyx::find::SR_FOUND) {
2016                 LyXCursor cur = text_.cursor;
2017                 bv->unlockInset(bv->theLockingInset());
2018                 if (bv->lockInset(this))
2019                         locked = true;
2020                 text_.cursor = cur;
2021                 text_.setSelectionRange(str.length());
2022                 updateLocal(bv, false);
2023         }
2024         return result != lyx::find::SR_NOT_FOUND;
2025 }
2026
2027
2028 bool InsetText::checkInsertChar(LyXFont & font)
2029 {
2030         return owner() ? owner()->checkInsertChar(font) : true;
2031 }
2032
2033
2034 void InsetText::collapseParagraphs(BufferView * bv)
2035 {
2036         while (paragraphs.size() > 1) {
2037                 ParagraphList::iterator first_par = paragraphs.begin();
2038                 ParagraphList::iterator next_par = boost::next(first_par);
2039                 size_t const first_par_size = first_par->size();
2040
2041                 if (!first_par->empty() &&
2042                     !next_par->empty() &&
2043                     !first_par->isSeparator(first_par_size - 1)) {
2044                         first_par->insertChar(first_par_size, ' ');
2045                 }
2046
2047                 if (text_.selection.set()) {
2048                         if (text_.selection.start.par() == next_par) {
2049                                 text_.selection.start.par(first_par);
2050                                 text_.selection.start.pos(
2051                                         text_.selection.start.pos() + first_par_size);
2052                         }
2053                         if (text_.selection.end.par() == next_par) {
2054                                 text_.selection.end.par(first_par);
2055                                 text_.selection.end.pos(
2056                                         text_.selection.end.pos() + first_par_size);
2057                         }
2058                 }
2059
2060                 mergeParagraph(bv->buffer()->params, paragraphs, first_par);
2061         }
2062         reinitLyXText();
2063 }
2064
2065
2066 void InsetText::getDrawFont(LyXFont & font) const
2067 {
2068         if (!owner())
2069                 return;
2070         owner()->getDrawFont(font);
2071 }
2072
2073
2074 void InsetText::appendParagraphs(Buffer * buffer, ParagraphList & plist)
2075 {
2076 #warning FIXME Check if Changes stuff needs changing here. (Lgb)
2077 // And it probably does. You have to take a look at this John. (Lgb)
2078 #warning John, have a look here. (Lgb)
2079         ParagraphList::iterator pit = plist.begin();
2080         ParagraphList::iterator ins = paragraphs.insert(paragraphs.end(), *pit);
2081         ++pit;
2082         mergeParagraph(buffer->params, paragraphs, boost::prior(ins));
2083
2084         ParagraphList::iterator pend = plist.end();
2085         for (; pit != pend; ++pit)
2086                 paragraphs.push_back(*pit);
2087
2088         reinitLyXText();
2089 }
2090
2091
2092 void InsetText::addPreview(PreviewLoader & loader) const
2093 {
2094         ParagraphList::const_iterator pit = paragraphs.begin();
2095         ParagraphList::const_iterator pend = paragraphs.end();
2096
2097         for (; pit != pend; ++pit) {
2098                 InsetList::const_iterator it  = pit->insetlist.begin();
2099                 InsetList::const_iterator end = pit->insetlist.end();
2100                 for (; it != end; ++it)
2101                         it->inset->addPreview(loader);
2102         }
2103 }