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