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