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