]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
Fix second part of bug #6400: After selecting a word by double-clicking it, extending...
[lyx.git] / src / Text3.cpp
1 /**
2  * \file Text3.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "Text.h"
19
20 #include "Bidi.h"
21 #include "BranchList.h"
22 #include "FloatList.h"
23 #include "FuncStatus.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "Cursor.h"
30 #include "CutAndPaste.h"
31 #include "DispatchResult.h"
32 #include "ErrorList.h"
33 #include "factory.h"
34 #include "FuncRequest.h"
35 #include "InsetList.h"
36 #include "Intl.h"
37 #include "Language.h"
38 #include "Layout.h"
39 #include "LyXAction.h"
40 #include "LyXFunc.h"
41 #include "Lexer.h"
42 #include "LyXRC.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48
49 #include "frontends/Application.h"
50 #include "frontends/Clipboard.h"
51 #include "frontends/Selection.h"
52
53 #include "insets/InsetCollapsable.h"
54 #include "insets/InsetCommand.h"
55 #include "insets/InsetExternal.h"
56 #include "insets/InsetFloat.h"
57 #include "insets/InsetFloatList.h"
58 #include "insets/InsetGraphics.h"
59 #include "insets/InsetGraphicsParams.h"
60 #include "insets/InsetNewline.h"
61 #include "insets/InsetQuotes.h"
62 #include "insets/InsetSpecialChar.h"
63 #include "insets/InsetText.h"
64 #include "insets/InsetWrap.h"
65
66 #include "support/convert.h"
67 #include "support/debug.h"
68 #include "support/gettext.h"
69 #include "support/lstrings.h"
70 #include "support/lyxtime.h"
71 #include "support/os.h"
72
73 #include "mathed/InsetMathHull.h"
74 #include "mathed/MathMacroTemplate.h"
75
76 #include <boost/next_prior.hpp>
77
78 #include <clocale>
79 #include <sstream>
80
81 using namespace std;
82 using namespace lyx::support;
83
84 namespace lyx {
85
86 using cap::copySelection;
87 using cap::cutSelection;
88 using cap::pasteFromStack;
89 using cap::pasteClipboardText;
90 using cap::pasteClipboardGraphics;
91 using cap::replaceSelection;
92 using cap::grabAndEraseSelection;
93 using cap::selClearOrDel;
94
95 // globals...
96 static Font freefont(ignore_font, ignore_language);
97 static bool toggleall = false;
98
99 static void toggleAndShow(Cursor & cur, Text * text,
100         Font const & font, bool toggleall = true)
101 {
102         text->toggleFree(cur, font, toggleall);
103
104         if (font.language() != ignore_language ||
105             font.fontInfo().number() != FONT_IGNORE) {
106                 TextMetrics const & tm = cur.bv().textMetrics(text);
107                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
108                                                        cur.real_current_font))
109                         text->setCursor(cur, cur.pit(), cur.pos(),
110                                         false, !cur.boundary());
111         }
112 }
113
114
115 static void moveCursor(Cursor & cur, bool selecting)
116 {
117         if (selecting || cur.mark())
118                 cur.setSelection();
119 }
120
121
122 static void finishChange(Cursor & cur, bool selecting)
123 {
124         cur.finishUndo();
125         moveCursor(cur, selecting);
126 }
127
128
129 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
130 {
131         cur.recordUndo();
132         docstring sel = cur.selectionAsString(false);
133
134         // It may happen that sel is empty but there is a selection
135         replaceSelection(cur);
136
137         // Is this a valid formula?
138         bool valid = true;
139
140         if (sel.empty()) {
141 #ifdef ENABLE_ASSERTIONS
142                 const int old_pos = cur.pos();
143 #endif
144                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
145 #ifdef ENABLE_ASSERTIONS
146                 LASSERT(old_pos == cur.pos(), /**/);
147 #endif
148                 cur.nextInset()->edit(cur, true);
149                 // don't do that also for LFUN_MATH_MODE
150                 // unless you want end up with always changing
151                 // to mathrm when opening an inlined inset --
152                 // I really hate "LyXfunc overloading"...
153                 if (display)
154                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
155                 // Avoid an unnecessary undo step if cmd.argument
156                 // is empty
157                 if (!cmd.argument().empty())
158                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
159                                                  cmd.argument()));
160         } else {
161                 // create a macro if we see "\\newcommand"
162                 // somewhere, and an ordinary formula
163                 // otherwise
164                 if (sel.find(from_ascii("\\newcommand")) == string::npos
165                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
166                                 && sel.find(from_ascii("\\def")) == string::npos)
167                 {
168                         InsetMathHull * formula = new InsetMathHull(cur.buffer());
169                         string const selstr = to_utf8(sel);
170                         istringstream is(selstr);
171                         Lexer lex;
172                         lex.setStream(is);
173                         if (!formula->readQuiet(lex)) {
174                                 // No valid formula, let's try with delims
175                                 is.str("$" + selstr + "$");
176                                 lex.setStream(is);
177                                 if (!formula->readQuiet(lex)) {
178                                         // Still not valid, leave it as is
179                                         valid = false;
180                                         delete formula;
181                                         cur.insert(sel);
182                                 } else
183                                         cur.insert(formula);
184                         } else
185                                 cur.insert(formula);
186                 } else {
187                         cur.insert(new MathMacroTemplate(cur.buffer(), sel));
188                 }
189         }
190         if (valid)
191                 cur.message(from_utf8(N_("Math editor mode")));
192         else
193                 cur.message(from_utf8(N_("No valid math formula")));
194 }
195
196
197 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
198 {
199         BOOST_ASSERT(cmd.action == LFUN_REGEXP_MODE);
200         if (cur.inRegexped()) {
201                 cur.message(_("Already in regexp mode"));
202                 return;
203         }
204         cur.recordUndo();
205         docstring sel = cur.selectionAsString(false);
206
207         // It may happen that sel is empty but there is a selection
208         replaceSelection(cur);
209
210         cur.insert(new InsetMathHull(cur.buffer(), hullRegexp));
211         cur.nextInset()->edit(cur, true);
212         cur.niceInsert(sel);
213
214         cur.message(_("Regexp editor mode"));
215 }
216
217
218 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
219 {
220         cur.recordUndo();
221         cap::replaceSelection(cur);
222         cur.insert(new InsetSpecialChar(kind));
223         cur.posForward();
224 }
225
226
227 static bool doInsertInset(Cursor & cur, Text * text,
228         FuncRequest const & cmd, bool edit, bool pastesel)
229 {
230         Buffer & buffer = cur.bv().buffer();
231         BufferParams const & bparams = buffer.params();
232         Inset * inset = createInset(&buffer, cmd);
233         if (!inset)
234                 return false;
235
236         if (InsetCollapsable * ci = inset->asInsetCollapsable())
237                 ci->setButtonLabel();
238
239         cur.recordUndo();
240         if (cmd.action == LFUN_INDEX_INSERT) {
241                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
242                 text->insertInset(cur, inset);
243                 if (edit)
244                         inset->edit(cur, true);
245                 // Now put this into inset
246                 cur.text()->insertStringAsLines(cur, ds, cur.current_font);
247                 cur.leaveInset(*inset);
248                 return true;
249         }
250
251         bool gotsel = false;
252         if (cur.selection()) {
253                 cutSelection(cur, false, pastesel);
254                 cur.clearSelection();
255                 gotsel = true;
256         }
257         text->insertInset(cur, inset);
258
259         if (edit)
260                 inset->edit(cur, true);
261
262         if (!gotsel || !pastesel)
263                 return true;
264
265         pasteFromStack(cur, cur.buffer()->errorList("Paste"), 0);
266         cur.buffer()->errors("Paste");
267         cur.clearSelection(); // bug 393
268         cur.finishUndo();
269         InsetText * insetText = dynamic_cast<InsetText *>(inset);
270         if (insetText && (!insetText->allowMultiPar() || cur.lastpit() == 0)) {
271                 // reset first par to default
272                 cur.text()->paragraphs().begin()
273                         ->setPlainOrDefaultLayout(bparams.documentClass());
274                 cur.pos() = 0;
275                 cur.pit() = 0;
276                 // Merge multiple paragraphs -- hack
277                 while (cur.lastpit() > 0)
278                         mergeParagraph(bparams, cur.text()->paragraphs(), 0);
279                 cur.leaveInset(*inset);
280         } else {
281                 cur.leaveInset(*inset);
282                 // reset surrounding par to default
283                 DocumentClass const & dc = bparams.documentClass();
284                 docstring const layoutname = inset->usePlainLayout()
285                         ? dc.plainLayoutName()
286                         : dc.defaultLayoutName();
287                 text->setLayout(cur, layoutname);
288         }
289
290         return true;
291 }
292
293
294 string const freefont2string()
295 {
296         return freefont.toString(toggleall);
297 }
298
299
300 static void dragMove(Cursor & cur, int moveid, int movetoid)
301 {
302         // Create pointers to buffers
303         Buffer & buf_move = *cur.buffer();
304         DocIterator dit_move = buf_move.getParFromID(moveid);
305         DocIterator dit_dest = buf_move.getParFromID(movetoid);
306
307         pit_type & pit_move = dit_move.pit();
308         pit_type & pit_dest = dit_dest.pit();
309         ParagraphList & pars = dit_move.text()->paragraphs();
310
311         // Create references to the paragraphs to be moved
312         ParagraphList::iterator const bgn = pars.begin();
313         ParagraphList::iterator dest_start = boost::next(bgn, pit_dest);
314
315         // The first paragraph of the area to be copied:
316         ParagraphList::iterator start = boost::next(bgn, pit_move);
317         // The final paragraph of area to be copied:
318         ParagraphList::iterator finish = start;
319         ParagraphList::iterator const end = pars.end();
320
321         // Move out (down) from this section header
322         if (finish != end)
323                 ++finish;
324
325         // Seek the one (on same level) below
326         int const thistoclevel = start->layout().toclevel;
327         for (; finish != end; ++finish) {
328                 int const toclevel = finish->layout().toclevel;
329                 if (toclevel != Layout::NOT_IN_TOC
330                     && toclevel <= thistoclevel)
331                         break;
332         }
333
334         if (start == pars.begin() || start == dest_start)
335                 // Nothing to move
336                 return;
337
338         pars.insert(dest_start, start, finish);
339         pars.erase(start, finish);
340
341         // FIXME: This only really needs doing for the newly
342         // introduced paragraphs. Something like:
343         //      pit_type const numpars = distance(start, finish);
344         //      start = boost::next(bgn, pit);
345         //      finish = boost::next(start, numpars);
346         //      for (; start != finish; ++start)
347         //              start->setBuffer(buf);
348         // But while this seems to work, it is kind of fragile.
349         buf_move.inset().setBuffer(buf_move);
350 }
351
352
353 /// the type of outline operation
354 enum OutlineOp {
355         OutlineUp, // Move this header with text down
356         OutlineDown,   // Move this header with text up
357         OutlineIn, // Make this header deeper
358         OutlineOut // Make this header shallower
359 };
360
361
362 static void outline(OutlineOp mode, Cursor & cur)
363 {
364         Buffer & buf = *cur.buffer();
365         pit_type & pit = cur.pit();
366         ParagraphList & pars = buf.text().paragraphs();
367         ParagraphList::iterator const bgn = pars.begin();
368         // The first paragraph of the area to be copied:
369         ParagraphList::iterator start = boost::next(bgn, pit);
370         // The final paragraph of area to be copied:
371         ParagraphList::iterator finish = start;
372         ParagraphList::iterator const end = pars.end();
373
374         DocumentClass const & tc = buf.params().documentClass();
375
376         int const thistoclevel = start->layout().toclevel;
377         int toclevel;
378
379         // Move out (down) from this section header
380         if (finish != end)
381                 ++finish;
382
383         // Seek the one (on same level) below
384         for (; finish != end; ++finish) {
385                 toclevel = finish->layout().toclevel;
386                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
387                         break;
388         }
389
390         switch (mode) {
391                 case OutlineUp: {
392                         if (start == pars.begin())
393                                 // Nothing to move.
394                                 return;
395                         ParagraphList::iterator dest = start;
396                         // Move out (up) from this header
397                         if (dest == bgn)
398                                 return;
399                         // Search previous same-level header above
400                         do {
401                                 --dest;
402                                 toclevel = dest->layout().toclevel;
403                         } while(dest != bgn
404                                 && (toclevel == Layout::NOT_IN_TOC
405                                     || toclevel > thistoclevel));
406                         // Not found; do nothing
407                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
408                                 return;
409                         pit_type const newpit = distance(bgn, dest);
410                         pit_type const len = distance(start, finish);
411                         pit_type const deletepit = pit + len;
412                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
413                         pars.splice(dest, start, finish);
414                         cur.pit() = newpit;
415                         break;
416                 }
417                 case OutlineDown: {
418                         if (finish == end)
419                                 // Nothing to move.
420                                 return;
421                         // Go one down from *this* header:
422                         ParagraphList::iterator dest = boost::next(finish, 1);
423                         // Go further down to find header to insert in front of:
424                         for (; dest != end; ++dest) {
425                                 toclevel = dest->layout().toclevel;
426                                 if (toclevel != Layout::NOT_IN_TOC
427                                       && toclevel <= thistoclevel)
428                                         break;
429                         }
430                         // One such was found:
431                         pit_type newpit = distance(bgn, dest);
432                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
433                         pit_type const len = distance(start, finish);
434                         pars.splice(dest, start, finish);
435                         cur.pit() = newpit - len;
436                         break;
437                 }
438                 case OutlineIn: {
439                         pit_type const len = distance(start, finish);
440                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
441                         for (; start != finish; ++start) {
442                                 toclevel = start->layout().toclevel;
443                                 if (toclevel == Layout::NOT_IN_TOC)
444                                         continue;
445                                 DocumentClass::const_iterator lit = tc.begin();
446                                 DocumentClass::const_iterator len = tc.end();
447                                 for (; lit != len; ++lit) {
448                                         if (lit->toclevel == toclevel + 1 &&
449                                             start->layout().labeltype == lit->labeltype) {
450                                                 start->setLayout(*lit);
451                                                 break;
452                                         }
453                                 }
454                         }
455                         break;
456                 }
457                 case OutlineOut: {
458                         pit_type const len = distance(start, finish);
459                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
460                         for (; start != finish; ++start) {
461                                 toclevel = start->layout().toclevel;
462                                 if (toclevel == Layout::NOT_IN_TOC)
463                                         continue;
464                                 DocumentClass::const_iterator lit = tc.begin();
465                                 DocumentClass::const_iterator len = tc.end();
466                                 for (; lit != len; ++lit) {
467                                         if (lit->toclevel == toclevel - 1 &&
468                                                 start->layout().labeltype == lit->labeltype) {
469                                                         start->setLayout(*lit);
470                                                         break;
471                                         }
472                                 }
473                         }
474                         break;
475                 }
476         }
477 }
478
479
480 void Text::number(Cursor & cur)
481 {
482         FontInfo font = ignore_font;
483         font.setNumber(FONT_TOGGLE);
484         toggleAndShow(cur, this, Font(font, ignore_language));
485 }
486
487
488 bool Text::isRTL(Paragraph const & par) const
489 {
490         Buffer const & buffer = owner_->buffer();
491         return par.isRTL(buffer.params());
492 }
493
494
495 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
496 {
497         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
498
499         // Dispatch if the cursor is inside the text. It is not the
500         // case for context menus (bug 5797).
501         if (cur.text() != this) {
502                 cur.undispatched();
503                 return;
504         }
505
506         BufferView * bv = &cur.bv();
507         TextMetrics * tm = &bv->textMetrics(this);
508         if (!tm->contains(cur.pit())) {
509                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
510                 tm = &bv->textMetrics(this);
511         }
512
513         // FIXME: We use the update flag to indicates wether a singlePar or a
514         // full screen update is needed. We reset it here but shall we restore it
515         // at the end?
516         cur.noUpdate();
517
518         LASSERT(cur.text() == this, /**/);
519         CursorSlice oldTopSlice = cur.top();
520         bool oldBoundary = cur.boundary();
521         bool sel = cur.selection();
522         // Signals that, even if needsUpdate == false, an update of the
523         // cursor paragraph is required
524         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action,
525                 LyXAction::SingleParUpdate);
526         // Signals that a full-screen update is required
527         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action,
528                 LyXAction::NoUpdate) || singleParUpdate);
529
530         switch (cmd.action) {
531
532         case LFUN_PARAGRAPH_MOVE_DOWN: {
533                 pit_type const pit = cur.pit();
534                 recUndo(cur, pit, pit + 1);
535                 cur.finishUndo();
536                 pars_.swap(pit, pit + 1);
537                 cur.buffer()->updateLabels();
538                 needsUpdate = true;
539                 ++cur.pit();
540                 break;
541         }
542
543         case LFUN_PARAGRAPH_MOVE_UP: {
544                 pit_type const pit = cur.pit();
545                 recUndo(cur, pit - 1, pit);
546                 cur.finishUndo();
547                 pars_.swap(pit, pit - 1);
548                 cur.buffer()->updateLabels();
549                 --cur.pit();
550                 needsUpdate = true;
551                 break;
552         }
553
554         case LFUN_APPENDIX: {
555                 Paragraph & par = cur.paragraph();
556                 bool start = !par.params().startOfAppendix();
557
558 // FIXME: The code below only makes sense at top level.
559 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
560                 // ensure that we have only one start_of_appendix in this document
561                 // FIXME: this don't work for multipart document!
562                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
563                         if (pars_[tmp].params().startOfAppendix()) {
564                                 recUndo(cur, tmp);
565                                 pars_[tmp].params().startOfAppendix(false);
566                                 break;
567                         }
568                 }
569
570                 cur.recordUndo();
571                 par.params().startOfAppendix(start);
572
573                 // we can set the refreshing parameters now
574                 cur.buffer()->updateLabels();
575                 break;
576         }
577
578         case LFUN_WORD_DELETE_FORWARD:
579                 if (cur.selection())
580                         cutSelection(cur, true, false);
581                 else
582                         deleteWordForward(cur);
583                 finishChange(cur, false);
584                 break;
585
586         case LFUN_WORD_DELETE_BACKWARD:
587                 if (cur.selection())
588                         cutSelection(cur, true, false);
589                 else
590                         deleteWordBackward(cur);
591                 finishChange(cur, false);
592                 break;
593
594         case LFUN_LINE_DELETE:
595                 if (cur.selection())
596                         cutSelection(cur, true, false);
597                 else
598                         tm->deleteLineForward(cur);
599                 finishChange(cur, false);
600                 break;
601
602         case LFUN_BUFFER_BEGIN:
603         case LFUN_BUFFER_BEGIN_SELECT:
604                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_BEGIN_SELECT);
605                 if (cur.depth() == 1)
606                         needsUpdate |= cursorTop(cur);
607                 else
608                         cur.undispatched();
609                 cur.updateFlags(Update::FitCursor);
610                 break;
611
612         case LFUN_BUFFER_END:
613         case LFUN_BUFFER_END_SELECT:
614                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_END_SELECT);
615                 if (cur.depth() == 1)
616                         needsUpdate |= cursorBottom(cur);
617                 else
618                         cur.undispatched();
619                 cur.updateFlags(Update::FitCursor);
620                 break;
621
622         case LFUN_INSET_BEGIN:
623         case LFUN_INSET_BEGIN_SELECT:
624                 needsUpdate |= cur.selHandle(cmd.action == LFUN_INSET_BEGIN_SELECT);
625                 if (cur.depth() == 1 || !cur.top().at_begin())
626                         needsUpdate |= cursorTop(cur);
627                 else
628                         cur.undispatched();
629                 cur.updateFlags(Update::FitCursor);
630                 break;
631
632         case LFUN_INSET_END:
633         case LFUN_INSET_END_SELECT:
634                 needsUpdate |= cur.selHandle(cmd.action == LFUN_INSET_END_SELECT);
635                 if (cur.depth() == 1 || !cur.top().at_end())
636                         needsUpdate |= cursorBottom(cur);
637                 else
638                         cur.undispatched();
639                 cur.updateFlags(Update::FitCursor);
640                 break;
641
642         case LFUN_INSET_SELECT_ALL:
643                 if (cur.depth() == 1 || !cur.selection() || !cur.selBegin().at_begin()
644                           || !cur.selEnd().at_end()) {
645                         needsUpdate |= cur.selHandle(false);
646                         needsUpdate |= cursorTop(cur);
647                         needsUpdate |= cur.selHandle(true);
648                         needsUpdate |= cursorBottom(cur);
649                 } else 
650                         cur.undispatched();
651                 cur.updateFlags(Update::FitCursor);
652                 break;
653
654         case LFUN_CHAR_FORWARD:
655         case LFUN_CHAR_FORWARD_SELECT:
656                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
657                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
658                 needsUpdate |= cursorForward(cur);
659
660                 if (!needsUpdate && oldTopSlice == cur.top()
661                                 && cur.boundary() == oldBoundary) {
662                         cur.undispatched();
663                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
664                 
665                         // we will probably be moving out the inset, so we should execute
666                         // the depm-mechanism, but only when the cursor has a place to 
667                         // go outside this inset, i.e. in a slice above.
668                         if (cur.depth() > 1 && cur.pos() == cur.lastpos() 
669                                   && cur.pit() == cur.lastpit()) {
670                                 // The cursor hasn't changed yet. To give the 
671                                 // DEPM the possibility of doing something we must
672                                 // provide it with two different cursors.
673                                 Cursor dummy = cur;
674                                 dummy.pos() = dummy.pit() = 0;
675                                 cur.bv().checkDepm(dummy, cur);
676                         }
677                 }
678                 break;
679
680         case LFUN_CHAR_BACKWARD:
681         case LFUN_CHAR_BACKWARD_SELECT:
682                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
683                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
684                 needsUpdate |= cursorBackward(cur);
685
686                 if (!needsUpdate && oldTopSlice == cur.top()
687                         && cur.boundary() == oldBoundary) {
688                         cur.undispatched();
689                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
690
691                         // we will probably be moving out the inset, so we should execute
692                         // the depm-mechanism, but only when the cursor has a place to 
693                         // go outside this inset, i.e. in a slice above.
694                         if (cur.depth() > 1 && cur.pos() == 0 && cur.pit() == 0) {
695                                 // The cursor hasn't changed yet. To give the 
696                                 // DEPM the possibility of doing something we must
697                                 // provide it with two different cursors.
698                                 Cursor dummy = cur;
699                                 dummy.pos() = cur.lastpos();
700                                 dummy.pit() = cur.lastpit();
701                                 cur.bv().checkDepm(dummy, cur);
702                         }
703                 }
704                 break;
705
706         case LFUN_CHAR_LEFT:
707         case LFUN_CHAR_LEFT_SELECT:
708                 if (lyxrc.visual_cursor) {
709                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_LEFT_SELECT);
710                         needsUpdate |= cursorVisLeft(cur);
711                         if (!needsUpdate && oldTopSlice == cur.top()
712                                         && cur.boundary() == oldBoundary) {
713                                 cur.undispatched();
714                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
715                         }
716                 } else {
717                         if (reverseDirectionNeeded(cur)) {
718                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
719                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
720                         } else {
721                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
722                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
723                         }
724                         dispatch(cur, cmd);
725                         return;
726                 }
727                 break;
728
729         case LFUN_CHAR_RIGHT:
730         case LFUN_CHAR_RIGHT_SELECT:
731                 if (lyxrc.visual_cursor) {
732                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_RIGHT_SELECT);
733                         needsUpdate |= cursorVisRight(cur);
734                         if (!needsUpdate && oldTopSlice == cur.top()
735                                         && cur.boundary() == oldBoundary) {
736                                 cur.undispatched();
737                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
738                         }
739                 } else {
740                         if (reverseDirectionNeeded(cur)) {
741                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
742                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
743                         } else {
744                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
745                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
746                         }
747                         dispatch(cur, cmd);
748                         return;
749                 }
750                 break;
751
752
753         case LFUN_UP_SELECT:
754         case LFUN_DOWN_SELECT:
755         case LFUN_UP:
756         case LFUN_DOWN: {
757                 // stop/start the selection
758                 bool select = cmd.action == LFUN_DOWN_SELECT ||
759                         cmd.action == LFUN_UP_SELECT;
760
761                 // move cursor up/down
762                 bool up = cmd.action == LFUN_UP_SELECT || cmd.action == LFUN_UP;
763                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
764
765                 if (!atFirstOrLastRow) {
766                         needsUpdate |= cur.selHandle(select);   
767                         cur.selHandle(select);
768                         cur.upDownInText(up, needsUpdate);
769                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
770                 } else {
771                         // if the cursor cannot be moved up or down do not remove
772                         // the selection right now, but wait for the next dispatch.
773                         if (select)
774                                 needsUpdate |= cur.selHandle(select);   
775                         cur.upDownInText(up, needsUpdate);
776                         cur.undispatched();
777                 }
778
779                 break;
780         }
781
782         case LFUN_PARAGRAPH_UP:
783         case LFUN_PARAGRAPH_UP_SELECT:
784                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_UP_SELECT);
785                 needsUpdate |= cursorUpParagraph(cur);
786                 break;
787
788         case LFUN_PARAGRAPH_DOWN:
789         case LFUN_PARAGRAPH_DOWN_SELECT:
790                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_DOWN_SELECT);
791                 needsUpdate |= cursorDownParagraph(cur);
792                 break;
793
794         case LFUN_LINE_BEGIN:
795         case LFUN_LINE_BEGIN_SELECT:
796                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_BEGIN_SELECT);
797                 needsUpdate |= tm->cursorHome(cur);
798                 break;
799
800         case LFUN_LINE_END:
801         case LFUN_LINE_END_SELECT:
802                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_END_SELECT);
803                 needsUpdate |= tm->cursorEnd(cur);
804                 break;
805
806         case LFUN_SECTION_SELECT: {
807                 Buffer const & buf = *cur.buffer();
808                 pit_type const pit = cur.pit();
809                 ParagraphList & pars = buf.text().paragraphs();
810                 ParagraphList::iterator bgn = pars.begin();
811                 // The first paragraph of the area to be selected:
812                 ParagraphList::iterator start = boost::next(bgn, pit);
813                 // The final paragraph of area to be selected:
814                 ParagraphList::iterator finish = start;
815                 ParagraphList::iterator end = pars.end();
816
817                 int const thistoclevel = start->layout().toclevel;
818                 if (thistoclevel == Layout::NOT_IN_TOC)
819                         break;
820
821                 cur.pos() = 0;
822                 Cursor const old_cur = cur;
823                 needsUpdate |= cur.selHandle(true);
824
825                 // Move out (down) from this section header
826                 if (finish != end)
827                         ++finish;
828
829                 // Seek the one (on same level) below
830                 for (; finish != end; ++finish, ++cur.pit()) {
831                         int const toclevel = finish->layout().toclevel;
832                         if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
833                                 break;
834                 }
835                 cur.pos() = cur.lastpos();
836                 
837                 needsUpdate |= cur != old_cur;
838                 break;
839         }
840
841         case LFUN_WORD_RIGHT:
842         case LFUN_WORD_RIGHT_SELECT:
843                 if (lyxrc.visual_cursor) {
844                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_RIGHT_SELECT);
845                         needsUpdate |= cursorVisRightOneWord(cur);
846                         if (!needsUpdate && oldTopSlice == cur.top()
847                                         && cur.boundary() == oldBoundary) {
848                                 cur.undispatched();
849                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
850                         }
851                 } else {
852                         if (reverseDirectionNeeded(cur)) {
853                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
854                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
855                         } else {
856                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
857                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
858                         }
859                         dispatch(cur, cmd);
860                         return;
861                 }
862                 break;
863
864         case LFUN_WORD_FORWARD:
865         case LFUN_WORD_FORWARD_SELECT:
866                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT);
867                 needsUpdate |= cursorForwardOneWord(cur);
868                 break;
869
870         case LFUN_WORD_LEFT:
871         case LFUN_WORD_LEFT_SELECT:
872                 if (lyxrc.visual_cursor) {
873                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_LEFT_SELECT);
874                         needsUpdate |= cursorVisLeftOneWord(cur);
875                         if (!needsUpdate && oldTopSlice == cur.top()
876                                         && cur.boundary() == oldBoundary) {
877                                 cur.undispatched();
878                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
879                         }
880                 } else {
881                         if (reverseDirectionNeeded(cur)) {
882                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
883                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
884                         } else {
885                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
886                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
887                         }
888                         dispatch(cur, cmd);
889                         return;
890                 }
891                 break;
892
893         case LFUN_WORD_BACKWARD:
894         case LFUN_WORD_BACKWARD_SELECT:
895                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT);
896                 needsUpdate |= cursorBackwardOneWord(cur);
897                 break;
898
899         case LFUN_WORD_SELECT: {
900                 selectWord(cur, WHOLE_WORD);
901                 finishChange(cur, true);
902                 break;
903         }
904
905         case LFUN_NEWLINE_INSERT: {
906                 InsetNewlineParams inp;
907                 docstring arg = cmd.argument();
908                 // this avoids a double undo
909                 // FIXME: should not be needed, ideally
910                 if (!cur.selection())
911                         cur.recordUndo();
912                 cap::replaceSelection(cur);
913                 if (arg == "linebreak")
914                         inp.kind = InsetNewlineParams::LINEBREAK;
915                 else
916                         inp.kind = InsetNewlineParams::NEWLINE;
917                 cur.insert(new InsetNewline(inp));
918                 cur.posForward();
919                 moveCursor(cur, false);
920                 break;
921         }
922
923         case LFUN_TAB_INSERT: {
924                 bool const multi_par_selection = cur.selection() &&
925                         cur.selBegin().pit() != cur.selEnd().pit();
926                 if (multi_par_selection) {
927                         // If there is a multi-paragraph selection, a tab is inserted
928                         // at the beginning of each paragraph.
929                         cur.recordUndoSelection();
930                         pit_type const pit_end = cur.selEnd().pit();
931                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
932                                 pars_[pit].insertChar(0, '\t', 
933                                                       bv->buffer().params().trackChanges);
934                                 // Update the selection pos to make sure the selection does not
935                                 // change as the inserted tab will increase the logical pos.
936                                 if (cur.anchor_.pit() == pit)
937                                         cur.anchor_.forwardPos();
938                                 if (cur.pit() == pit)
939                                         cur.forwardPos();
940                         }
941                         cur.finishUndo();
942                 } else {
943                         // Maybe we shouldn't allow tabs within a line, because they
944                         // are not (yet) aligned as one might do expect.
945                         FuncRequest cmd(LFUN_SELF_INSERT, from_ascii("\t"));
946                         dispatch(cur, cmd);     
947                 }
948                 break;
949         }
950
951         case LFUN_TAB_DELETE: {
952                 bool const tc = bv->buffer().params().trackChanges;
953                 if (cur.selection()) {
954                         // If there is a selection, a tab (if present) is removed from
955                         // the beginning of each paragraph.
956                         cur.recordUndoSelection();
957                         pit_type const pit_end = cur.selEnd().pit();
958                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
959                                 Paragraph & par = paragraphs()[pit];
960                                 if (par.getChar(0) == '\t') {
961                                         if (cur.pit() == pit)
962                                                 cur.posBackward();
963                                         if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
964                                                 cur.anchor_.backwardPos();
965                                         
966                                         par.eraseChar(0, tc);
967                                 } else 
968                                         // If no tab was present, try to remove up to four spaces.
969                                         for (int n_spaces = 0;
970                                              par.getChar(0) == ' ' && n_spaces < 4; ++n_spaces) {
971                                                 if (cur.pit() == pit)
972                                                         cur.posBackward();
973                                                 if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
974                                                         cur.anchor_.backwardPos();
975                                                 
976                                                 par.eraseChar(0, tc);
977                                         }
978                         }
979                         cur.finishUndo();
980                 } else {
981                         // If there is no selection, try to remove a tab or some spaces 
982                         // before the position of the cursor.
983                         Paragraph & par = paragraphs()[cur.pit()];
984                         pos_type const pos = cur.pos();
985                         
986                         if (pos == 0)
987                                 break;
988                         
989                         char_type const c = par.getChar(pos - 1);
990                         cur.recordUndo();
991                         if (c == '\t') {
992                                 cur.posBackward();
993                                 par.eraseChar(cur.pos(), tc);
994                         } else
995                                 for (int n_spaces = 0; 
996                                      cur.pos() > 0
997                                              && par.getChar(cur.pos() - 1) == ' ' 
998                                              && n_spaces < 4;
999                                      ++n_spaces) {
1000                                         cur.posBackward();
1001                                         par.eraseChar(cur.pos(), tc);
1002                                 }
1003                         cur.finishUndo();
1004                 }
1005                 break;
1006         }
1007
1008         case LFUN_CHAR_DELETE_FORWARD:
1009                 if (!cur.selection()) {
1010                         if (cur.pos() == cur.paragraph().size())
1011                                 // Par boundary, force full-screen update
1012                                 singleParUpdate = false;
1013                         needsUpdate |= erase(cur);
1014                         cur.resetAnchor();
1015                         // It is possible to make it a lot faster still
1016                         // just comment out the line below...
1017                 } else {
1018                         cutSelection(cur, true, false);
1019                         singleParUpdate = false;
1020                 }
1021                 moveCursor(cur, false);
1022                 break;
1023
1024         case LFUN_CHAR_DELETE_BACKWARD:
1025                 if (!cur.selection()) {
1026                         if (bv->getIntl().getTransManager().backspace()) {
1027                                 // Par boundary, full-screen update
1028                                 if (cur.pos() == 0)
1029                                         singleParUpdate = false;
1030                                 needsUpdate |= backspace(cur);
1031                                 cur.resetAnchor();
1032                                 // It is possible to make it a lot faster still
1033                                 // just comment out the line below...
1034                         }
1035                 } else {
1036                         cutSelection(cur, true, false);
1037                         singleParUpdate = false;
1038                 }
1039                 break;
1040
1041         case LFUN_BREAK_PARAGRAPH:
1042                 cap::replaceSelection(cur);
1043                 breakParagraph(cur, cmd.argument() == "inverse");
1044                 cur.resetAnchor();
1045                 break;
1046
1047         case LFUN_INSET_INSERT: {
1048                 cur.recordUndo();
1049
1050                 // We have to avoid triggering InstantPreview loading
1051                 // before inserting into the document. See bug #5626.
1052                 bool loaded = bv->buffer().isFullyLoaded();
1053                 bv->buffer().setFullyLoaded(false);
1054                 Inset * inset = createInset(&bv->buffer(), cmd);
1055                 bv->buffer().setFullyLoaded(loaded);
1056
1057                 if (inset) {
1058                         // FIXME (Abdel 01/02/2006):
1059                         // What follows would be a partial fix for bug 2154:
1060                         //   http://www.lyx.org/trac/ticket/2154
1061                         // This automatically put the label inset _after_ a
1062                         // numbered section. It should be possible to extend the mechanism
1063                         // to any kind of LateX environement.
1064                         // The correct way to fix that bug would be at LateX generation.
1065                         // I'll let the code here for reference as it could be used for some
1066                         // other feature like "automatic labelling".
1067                         /*
1068                         Paragraph & par = pars_[cur.pit()];
1069                         if (inset->lyxCode() == LABEL_CODE
1070                                 && par.layout().labeltype == LABEL_COUNTER) {
1071                                 // Go to the end of the paragraph
1072                                 // Warning: Because of Change-Tracking, the last
1073                                 // position is 'size()' and not 'size()-1':
1074                                 cur.pos() = par.size();
1075                                 // Insert a new paragraph
1076                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
1077                                 dispatch(cur, fr);
1078                         }
1079                         */
1080                         if (cur.selection())
1081                                 cutSelection(cur, true, false);
1082                         cur.insert(inset);
1083                         cur.posForward();
1084
1085                         // trigger InstantPreview now
1086                         if (inset->lyxCode() == EXTERNAL_CODE) {
1087                                 InsetExternal & ins =
1088                                         static_cast<InsetExternal &>(*inset);
1089                                 ins.updatePreview();
1090                         }
1091                 }
1092
1093                 break;
1094         }
1095
1096         case LFUN_INSET_DISSOLVE: {
1097                 if (dissolveInset(cur))
1098                         needsUpdate = true;
1099                 break;
1100         }
1101
1102         case LFUN_SET_GRAPHICS_GROUP: {
1103                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1104                 if (!ins)
1105                         break;
1106
1107                 cur.recordUndo();
1108
1109                 string id = to_utf8(cmd.argument());
1110                 string grp = graphics::getGroupParams(bv->buffer(), id);
1111                 InsetGraphicsParams tmp, inspar = ins->getParams();
1112
1113                 if (id.empty())
1114                         inspar.groupId = to_utf8(cmd.argument());
1115                 else {
1116                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1117                         tmp.filename = inspar.filename;
1118                         inspar = tmp;
1119                 }
1120
1121                 ins->setParams(inspar);
1122         }
1123
1124         case LFUN_SPACE_INSERT:
1125                 if (cur.paragraph().layout().free_spacing)
1126                         insertChar(cur, ' ');
1127                 else {
1128                         doInsertInset(cur, this, cmd, false, false);
1129                         cur.posForward();
1130                 }
1131                 moveCursor(cur, false);
1132                 break;
1133
1134         case LFUN_SPECIALCHAR_INSERT: {
1135                 string const name = to_utf8(cmd.argument());
1136                 if (name == "hyphenation")
1137                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1138                 else if (name == "ligature-break")
1139                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1140                 else if (name == "slash")
1141                         specialChar(cur, InsetSpecialChar::SLASH);
1142                 else if (name == "nobreakdash")
1143                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1144                 else if (name == "dots")
1145                         specialChar(cur, InsetSpecialChar::LDOTS);
1146                 else if (name == "end-of-sentence")
1147                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1148                 else if (name == "menu-separator")
1149                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1150                 else if (name.empty())
1151                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1152                 else
1153                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1154                 break;
1155         }
1156
1157         case LFUN_WORD_UPCASE:
1158                 changeCase(cur, text_uppercase);
1159                 break;
1160
1161         case LFUN_WORD_LOWCASE:
1162                 changeCase(cur, text_lowercase);
1163                 break;
1164
1165         case LFUN_WORD_CAPITALIZE:
1166                 changeCase(cur, text_capitalization);
1167                 break;
1168
1169         case LFUN_CHARS_TRANSPOSE:
1170                 charsTranspose(cur);
1171                 break;
1172
1173         case LFUN_PASTE: {
1174                 cur.message(_("Paste"));
1175                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), /**/);
1176                 cap::replaceSelection(cur);
1177
1178                 // without argument?
1179                 string const arg = to_utf8(cmd.argument());
1180                 if (arg.empty()) {
1181                         if (theClipboard().isInternal())
1182                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1183                         else if (theClipboard().hasGraphicsContents() 
1184                                      && !theClipboard().hasTextContents())
1185                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1186                         else
1187                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
1188                 } else if (isStrUnsignedInt(arg)) {
1189                         // we have a numerical argument
1190                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1191                                        convert<unsigned int>(arg));
1192                 } else {
1193                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1194                         if (arg == "pdf")
1195                                 type = Clipboard::PdfGraphicsType;
1196                         else if (arg == "png")
1197                                 type = Clipboard::PngGraphicsType;
1198                         else if (arg == "jpeg")
1199                                 type = Clipboard::JpegGraphicsType;
1200                         else if (arg == "linkback")
1201                                 type = Clipboard::LinkBackGraphicsType;
1202                         else if (arg == "emf")
1203                                 type = Clipboard::EmfGraphicsType;
1204                         else if (arg == "wmf")
1205                                 type = Clipboard::WmfGraphicsType;
1206
1207                         else
1208                                 LASSERT(false, /**/);
1209
1210                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1211                 }
1212
1213                 bv->buffer().errors("Paste");
1214                 cur.clearSelection(); // bug 393
1215                 cur.finishUndo();
1216                 break;
1217         }
1218
1219         case LFUN_CUT:
1220                 cutSelection(cur, true, true);
1221                 cur.message(_("Cut"));
1222                 break;
1223
1224         case LFUN_COPY:
1225                 copySelection(cur);
1226                 cur.message(_("Copy"));
1227                 break;
1228
1229         case LFUN_SERVER_GET_XY:
1230                 cur.message(from_utf8(
1231                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1232                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1233                 break;
1234
1235         case LFUN_SERVER_SET_XY: {
1236                 int x = 0;
1237                 int y = 0;
1238                 istringstream is(to_utf8(cmd.argument()));
1239                 is >> x >> y;
1240                 if (!is)
1241                         lyxerr << "SETXY: Could not parse coordinates in '"
1242                                << to_utf8(cmd.argument()) << endl;
1243                 else
1244                         tm->setCursorFromCoordinates(cur, x, y);
1245                 break;
1246         }
1247
1248         case LFUN_SERVER_GET_LAYOUT:
1249                 cur.message(cur.paragraph().layout().name());
1250                 break;
1251
1252         case LFUN_LAYOUT: {
1253                 docstring layout = cmd.argument();
1254                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1255
1256                 Paragraph const & para = cur.paragraph();
1257                 docstring const old_layout = para.layout().name();
1258                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1259
1260                 if (layout.empty())
1261                         layout = tclass.defaultLayoutName();
1262
1263                 if (owner_->forcePlainLayout())
1264                         // in this case only the empty layout is allowed
1265                         layout = tclass.plainLayoutName();
1266                 else if (para.usePlainLayout()) {
1267                         // in this case, default layout maps to empty layout
1268                         if (layout == tclass.defaultLayoutName())
1269                                 layout = tclass.plainLayoutName();
1270                 } else {
1271                         // otherwise, the empty layout maps to the default
1272                         if (layout == tclass.plainLayoutName())
1273                                 layout = tclass.defaultLayoutName();
1274                 }
1275
1276                 bool hasLayout = tclass.hasLayout(layout);
1277
1278                 // If the entry is obsolete, use the new one instead.
1279                 if (hasLayout) {
1280                         docstring const & obs = tclass[layout].obsoleted_by();
1281                         if (!obs.empty())
1282                                 layout = obs;
1283                 }
1284
1285                 if (!hasLayout) {
1286                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1287                                 from_utf8(N_(" not known")));
1288                         break;
1289                 }
1290
1291                 bool change_layout = (old_layout != layout);
1292
1293                 if (!change_layout && cur.selection() &&
1294                         cur.selBegin().pit() != cur.selEnd().pit())
1295                 {
1296                         pit_type spit = cur.selBegin().pit();
1297                         pit_type epit = cur.selEnd().pit() + 1;
1298                         while (spit != epit) {
1299                                 if (pars_[spit].layout().name() != old_layout) {
1300                                         change_layout = true;
1301                                         break;
1302                                 }
1303                                 ++spit;
1304                         }
1305                 }
1306
1307                 if (change_layout)
1308                         setLayout(cur, layout);
1309
1310                 break;
1311         }
1312
1313         case LFUN_CLIPBOARD_PASTE:
1314                 cur.clearSelection();
1315                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1316                                cmd.argument() == "paragraph");
1317                 bv->buffer().errors("Paste");
1318                 break;
1319
1320         case LFUN_PRIMARY_SELECTION_PASTE:
1321                 pasteString(cur, theSelection().get(),
1322                             cmd.argument() == "paragraph");
1323                 break;
1324
1325         case LFUN_SELECTION_PASTE:
1326                 // Copy the selection buffer to the clipboard stack,
1327                 // because we want it to appear in the "Edit->Paste
1328                 // recent" menu.
1329                 cap::copySelectionToStack();
1330                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1331                 bv->buffer().errors("Paste");
1332                 break;
1333
1334         case LFUN_UNICODE_INSERT: {
1335                 if (cmd.argument().empty())
1336                         break;
1337                 docstring hexstring = cmd.argument();
1338                 if (isHex(hexstring)) {
1339                         char_type c = hexToInt(hexstring);
1340                         if (c >= 32 && c < 0x10ffff) {
1341                                 lyxerr << "Inserting c: " << c << endl;
1342                                 docstring s = docstring(1, c);
1343                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1344                         }
1345                 }
1346                 break;
1347         }
1348
1349         case LFUN_QUOTE_INSERT: {
1350                 Paragraph & par = cur.paragraph();
1351                 pos_type pos = cur.pos();
1352                 BufferParams const & bufparams = bv->buffer().params();
1353                 Layout const & style = par.layout();
1354                 InsetLayout const & ilayout = cur.inset().getLayout();
1355                 if (!style.pass_thru && !ilayout.isPassThru()
1356                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1357                         // this avoids a double undo
1358                         // FIXME: should not be needed, ideally
1359                         if (!cur.selection())
1360                                 cur.recordUndo();
1361                         cap::replaceSelection(cur);
1362                         pos = cur.pos();
1363                         char_type c;
1364                         if (pos == 0)
1365                                 c = ' ';
1366                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1367                                 c = ' ';
1368                         else
1369                                 c = par.getChar(pos - 1);
1370                         string arg = to_utf8(cmd.argument());
1371                         cur.insert(new InsetQuotes(cur.buffer(), c, (arg == "single")
1372                                 ? InsetQuotes::SingleQuotes : InsetQuotes::DoubleQuotes));
1373                         cur.posForward();
1374                 }
1375                 else
1376                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1377                 break;
1378         }
1379
1380         case LFUN_DATE_INSERT: {
1381                 string const format = cmd.argument().empty()
1382                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1383                 string const time = formatted_time(current_time(), format);
1384                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1385                 break;
1386         }
1387
1388         case LFUN_MOUSE_TRIPLE:
1389                 if (cmd.button() == mouse_button::button1) {
1390                         tm->cursorHome(cur);
1391                         cur.resetAnchor();
1392                         tm->cursorEnd(cur);
1393                         cur.setSelection();
1394                         bv->cursor() = cur;
1395                 }
1396                 break;
1397
1398         case LFUN_MOUSE_DOUBLE:
1399                 if (cmd.button() == mouse_button::button1) {
1400                         selectWord(cur, WHOLE_WORD_STRICT);
1401                         bv->cursor() = cur;
1402                 }
1403                 break;
1404
1405         // Single-click on work area
1406         case LFUN_MOUSE_PRESS: {
1407                 // We are not marking a selection with the keyboard in any case.
1408                 Cursor & bvcur = cur.bv().cursor();
1409                 bvcur.setMark(false);
1410                 switch (cmd.button()) {
1411                 case mouse_button::button1:
1412                         // Set the cursor
1413                         if (!bv->mouseSetCursor(cur, cmd.argument() == "region-select"))
1414                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1415                         if (bvcur.wordSelection())
1416                                 selectWord(bvcur, WHOLE_WORD);
1417                         break;
1418
1419                 case mouse_button::button2:
1420                         // Middle mouse pasting.
1421                         bv->mouseSetCursor(cur);
1422                         lyx::dispatch(
1423                                 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1424                                             "selection-paste ; primary-selection-paste paragraph"));
1425                         cur.noUpdate();
1426                         break;
1427
1428                 case mouse_button::button3: {
1429                         // Don't do anything if we right-click a
1430                         // selection, a context menu will popup.
1431                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1432                             && cur < bvcur.selectionEnd()) {
1433                                 cur.noUpdate();
1434                                 return;
1435                         }
1436                         if (!bv->mouseSetCursor(cur, false))
1437                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1438                         break;
1439                 }
1440
1441                 default:
1442                         break;
1443                 } // switch (cmd.button())
1444                 break;
1445         }
1446         case LFUN_MOUSE_MOTION: {
1447                 // Mouse motion with right or middle mouse do nothing for now.
1448                 if (cmd.button() != mouse_button::button1) {
1449                         cur.noUpdate();
1450                         return;
1451                 }
1452                 // ignore motions deeper nested than the real anchor
1453                 Cursor & bvcur = cur.bv().cursor();
1454                 if (!bvcur.anchor_.hasPart(cur)) {
1455                         cur.undispatched();
1456                         break;
1457                 }
1458                 CursorSlice old = bvcur.top();
1459
1460                 int const wh = bv->workHeight();
1461                 int const y = max(0, min(wh - 1, cmd.y));
1462
1463                 tm->setCursorFromCoordinates(cur, cmd.x, y);
1464                 cur.setTargetX(cmd.x);
1465                 if (cmd.y >= wh)
1466                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1467                 else if (cmd.y < 0)
1468                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1469                 // This is to allow jumping over large insets
1470                 if (cur.top() == old) {
1471                         if (cmd.y >= wh)
1472                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1473                         else if (cmd.y < 0)
1474                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1475                 }
1476                 // We continue with our existing selection or start a new one, so don't
1477                 // reset the anchor.
1478                 bvcur.setCursor(cur);
1479                 bvcur.setSelection(true);
1480                 if (cur.top() == old) {
1481                         // We didn't move one iota, so no need to update the screen.
1482                         cur.updateFlags(Update::SinglePar | Update::FitCursor);
1483                         //cur.noUpdate();
1484                         return;
1485                 }
1486                 break;
1487         }
1488
1489         case LFUN_MOUSE_RELEASE:
1490                 switch (cmd.button()) {
1491                 case mouse_button::button1:
1492                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1493                         // If there is a new selection, update persistent selection;
1494                         // otherwise, single click does not clear persistent selection
1495                         // buffer.
1496                         if (cur.selection()) {
1497                                 // Finish selection. If double click,
1498                                 // cur is moved to the end of word by
1499                                 // selectWord but bvcur is current
1500                                 // mouse position.
1501                                 cur.bv().cursor().setSelection();
1502                                 // We might have removed an empty but drawn selection
1503                                 // (probably a margin)
1504                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1505                         } else
1506                                 cur.noUpdate();
1507                         // FIXME: We could try to handle drag and drop of selection here.
1508                         return;
1509
1510                 case mouse_button::button2:
1511                         // Middle mouse pasting is handled at mouse press time,
1512                         // see LFUN_MOUSE_PRESS.
1513                         cur.noUpdate();
1514                         return;
1515
1516                 case mouse_button::button3:
1517                         // Cursor was set at LFUN_MOUSE_PRESS time.
1518                         // FIXME: If there is a selection we could try to handle a special
1519                         // drag & drop context menu.
1520                         cur.noUpdate();
1521                         return;
1522
1523                 case mouse_button::none:
1524                 case mouse_button::button4:
1525                 case mouse_button::button5:
1526                         break;
1527                 } // switch (cmd.button())
1528
1529                 break;
1530
1531         case LFUN_SELF_INSERT: {
1532                 if (cmd.argument().empty())
1533                         break;
1534
1535                 // Automatically delete the currently selected
1536                 // text and replace it with what is being
1537                 // typed in now. Depends on lyxrc settings
1538                 // "auto_region_delete", which defaults to
1539                 // true (on).
1540
1541                 if (lyxrc.auto_region_delete && cur.selection())
1542                         cutSelection(cur, false, false);
1543
1544                 cur.clearSelection();
1545
1546                 docstring::const_iterator cit = cmd.argument().begin();
1547                 docstring::const_iterator const end = cmd.argument().end();
1548                 for (; cit != end; ++cit)
1549                         bv->translateAndInsert(*cit, this, cur);
1550
1551                 cur.resetAnchor();
1552                 moveCursor(cur, false);
1553                 bv->bookmarkEditPosition();
1554                 break;
1555         }
1556
1557         case LFUN_HYPERLINK_INSERT: {
1558                 InsetCommandParams p(HYPERLINK_CODE);
1559                 docstring content;
1560                 if (cur.selection()) {
1561                         content = cur.selectionAsString(false);
1562                         cutSelection(cur, true, false);
1563                 }
1564                 p["target"] = (cmd.argument().empty()) ?
1565                         content : cmd.argument();
1566                 string const data = InsetCommand::params2string("href", p);
1567                 if (p["target"].empty()) {
1568                         bv->showDialog("href", data);
1569                 } else {
1570                         FuncRequest fr(LFUN_INSET_INSERT, data);
1571                         dispatch(cur, fr);
1572                 }
1573                 break;
1574         }
1575
1576         case LFUN_LABEL_INSERT: {
1577                 InsetCommandParams p(LABEL_CODE);
1578                 // Try to generate a valid label
1579                 p["name"] = (cmd.argument().empty()) ?
1580                         cur.getPossibleLabel() :
1581                         cmd.argument();
1582                 string const data = InsetCommand::params2string("label", p);
1583
1584                 if (cmd.argument().empty()) {
1585                         bv->showDialog("label", data);
1586                 } else {
1587                         FuncRequest fr(LFUN_INSET_INSERT, data);
1588                         dispatch(cur, fr);
1589                 }
1590                 break;
1591         }
1592
1593         case LFUN_INFO_INSERT: {
1594                 Inset * inset;
1595                 if (cmd.argument().empty() && cur.selection()) {
1596                         // if command argument is empty use current selection as parameter.
1597                         docstring ds = cur.selectionAsString(false);
1598                         cutSelection(cur, true, false);
1599                         FuncRequest cmd0(cmd, ds);
1600                         inset = createInset(cur.buffer(), cmd0);
1601                 } else {
1602                         inset = createInset(cur.buffer(), cmd);
1603                 }
1604                 if (!inset)
1605                         break;
1606                 cur.recordUndo();
1607                 insertInset(cur, inset);
1608                 cur.posForward();
1609                 break;
1610         }
1611         case LFUN_CAPTION_INSERT:
1612         case LFUN_FOOTNOTE_INSERT:
1613         case LFUN_NOTE_INSERT:
1614         case LFUN_FLEX_INSERT:
1615         case LFUN_BOX_INSERT:
1616         case LFUN_BRANCH_INSERT:
1617         case LFUN_PHANTOM_INSERT:
1618         case LFUN_ERT_INSERT:
1619         case LFUN_LISTING_INSERT:
1620         case LFUN_MARGINALNOTE_INSERT:
1621         case LFUN_OPTIONAL_INSERT:
1622         case LFUN_INDEX_INSERT:
1623                 // Open the inset, and move the current selection
1624                 // inside it.
1625                 doInsertInset(cur, this, cmd, true, true);
1626                 cur.posForward();
1627                 // Some insets are numbered, others are shown in the outline pane so
1628                 // let's update the labels and the toc backend.
1629                 bv->buffer().updateLabels();
1630                 break;
1631
1632         case LFUN_TABULAR_INSERT:
1633                 // if there were no arguments, just open the dialog
1634                 if (doInsertInset(cur, this, cmd, false, true))
1635                         cur.posForward();
1636                 else
1637                         bv->showDialog("tabularcreate");
1638
1639                 break;
1640
1641         case LFUN_FLOAT_INSERT:
1642         case LFUN_FLOAT_WIDE_INSERT:
1643         case LFUN_WRAP_INSERT: {
1644                 // will some text be moved into the inset?
1645                 bool content = cur.selection();
1646
1647                 doInsertInset(cur, this, cmd, true, true);
1648                 cur.posForward();
1649
1650                 // If some text is moved into the inset, doInsertInset 
1651                 // puts the cursor outside the inset. To insert the
1652                 // caption we put it back into the inset.
1653                 if (content)
1654                         cur.backwardPos();
1655
1656                 ParagraphList & pars = cur.text()->paragraphs();
1657
1658                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1659
1660                 // add a separate paragraph for the caption inset
1661                 pars.push_back(Paragraph());
1662                 pars.back().setInsetOwner(&cur.text()->inset());
1663                 pars.back().setPlainOrDefaultLayout(tclass);
1664                 int cap_pit = pars.size() - 1;
1665
1666                 // if an empty inset was created, we create an additional empty
1667                 // paragraph at the bottom so that the user can choose where to put
1668                 // the graphics (or table).
1669                 if (!content) {
1670                         pars.push_back(Paragraph());
1671                         pars.back().setInsetOwner(&cur.text()->inset());
1672                         pars.back().setPlainOrDefaultLayout(tclass);
1673                 }
1674
1675                 // reposition the cursor to the caption
1676                 cur.pit() = cap_pit;
1677                 cur.pos() = 0;
1678                 // FIXME: This Text/Cursor dispatch handling is a mess!
1679                 // We cannot use Cursor::dispatch here it needs access to up to
1680                 // date metrics.
1681                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1682                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
1683                 bv->buffer().updateLabels();
1684                 cur.updateFlags(Update::Force);
1685                 // FIXME: When leaving the Float (or Wrap) inset we should
1686                 // delete any empty paragraph left above or below the
1687                 // caption.
1688                 break;
1689         }
1690
1691         case LFUN_NOMENCL_INSERT: {
1692                 InsetCommandParams p(NOMENCL_CODE);
1693                 if (cmd.argument().empty())
1694                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1695                 else
1696                         p["symbol"] = cmd.argument();
1697                 string const data = InsetCommand::params2string("nomenclature", p);
1698                 bv->showDialog("nomenclature", data);
1699                 break;
1700         }
1701
1702         case LFUN_INDEX_PRINT: {
1703                 InsetCommandParams p(INDEX_PRINT_CODE);
1704                 if (cmd.argument().empty())
1705                         p["type"] = from_ascii("idx");
1706                 else
1707                         p["type"] = cmd.argument();
1708                 string const data = InsetCommand::params2string("index_print", p);
1709                 FuncRequest fr(LFUN_INSET_INSERT, data);
1710                 dispatch(cur, fr);
1711                 break;
1712         }
1713         
1714         case LFUN_NOMENCL_PRINT:
1715         case LFUN_TOC_INSERT:
1716         case LFUN_LINE_INSERT:
1717         case LFUN_NEWPAGE_INSERT:
1718                 // do nothing fancy
1719                 doInsertInset(cur, this, cmd, false, false);
1720                 cur.posForward();
1721                 break;
1722
1723         case LFUN_DEPTH_DECREMENT:
1724                 changeDepth(cur, DEC_DEPTH);
1725                 break;
1726
1727         case LFUN_DEPTH_INCREMENT:
1728                 changeDepth(cur, INC_DEPTH);
1729                 break;
1730
1731         case LFUN_MATH_DISPLAY:
1732                 mathDispatch(cur, cmd, true);
1733                 break;
1734
1735         case LFUN_REGEXP_MODE:
1736                 regexpDispatch(cur, cmd);
1737                 break;
1738
1739         case LFUN_MATH_MODE:
1740                 if (cmd.argument() == "on")
1741                         // don't pass "on" as argument
1742                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1743                 else
1744                         mathDispatch(cur, cmd, false);
1745                 break;
1746
1747         case LFUN_MATH_MACRO:
1748                 if (cmd.argument().empty())
1749                         cur.errorMessage(from_utf8(N_("Missing argument")));
1750                 else {
1751                         string s = to_utf8(cmd.argument());
1752                         string const s1 = token(s, ' ', 1);
1753                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1754                         string const s2 = token(s, ' ', 2);
1755                         MacroType type = MacroTypeNewcommand;
1756                         if (s2 == "def")
1757                                 type = MacroTypeDef;
1758                         MathMacroTemplate * inset = new MathMacroTemplate(cur.buffer(),
1759                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
1760                         inset->setBuffer(bv->buffer());
1761                         insertInset(cur, inset);
1762
1763                         // enter macro inset and select the name
1764                         cur.push(*inset);
1765                         cur.top().pos() = cur.top().lastpos();
1766                         cur.resetAnchor();
1767                         cur.setSelection(true);
1768                         cur.top().pos() = 0;
1769                 }
1770                 break;
1771
1772         // passthrough hat and underscore outside mathed:
1773         case LFUN_MATH_SUBSCRIPT:
1774                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1775                 break;
1776         case LFUN_MATH_SUPERSCRIPT:
1777                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1778                 break;
1779
1780         case LFUN_MATH_INSERT:
1781         case LFUN_MATH_AMS_MATRIX:
1782         case LFUN_MATH_MATRIX:
1783         case LFUN_MATH_DELIM:
1784         case LFUN_MATH_BIGDELIM: {
1785                 cur.recordUndo();
1786                 cap::replaceSelection(cur);
1787                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
1788                 checkAndActivateInset(cur, true);
1789                 LASSERT(cur.inMathed(), /**/);
1790                 cur.dispatch(cmd);
1791                 break;
1792         }
1793
1794         case LFUN_FONT_EMPH: {
1795                 Font font(ignore_font, ignore_language);
1796                 font.fontInfo().setEmph(FONT_TOGGLE);
1797                 toggleAndShow(cur, this, font);
1798                 break;
1799         }
1800
1801         case LFUN_FONT_ITAL: {
1802                 Font font(ignore_font, ignore_language);
1803                 font.fontInfo().setShape(ITALIC_SHAPE);
1804                 toggleAndShow(cur, this, font);
1805                 break;
1806         }
1807
1808         case LFUN_FONT_BOLD:
1809         case LFUN_FONT_BOLDSYMBOL: {
1810                 Font font(ignore_font, ignore_language);
1811                 font.fontInfo().setSeries(BOLD_SERIES);
1812                 toggleAndShow(cur, this, font);
1813                 break;
1814         }
1815
1816         case LFUN_FONT_NOUN: {
1817                 Font font(ignore_font, ignore_language);
1818                 font.fontInfo().setNoun(FONT_TOGGLE);
1819                 toggleAndShow(cur, this, font);
1820                 break;
1821         }
1822
1823         case LFUN_FONT_TYPEWRITER: {
1824                 Font font(ignore_font, ignore_language);
1825                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1826                 toggleAndShow(cur, this, font);
1827                 break;
1828         }
1829
1830         case LFUN_FONT_SANS: {
1831                 Font font(ignore_font, ignore_language);
1832                 font.fontInfo().setFamily(SANS_FAMILY);
1833                 toggleAndShow(cur, this, font);
1834                 break;
1835         }
1836
1837         case LFUN_FONT_ROMAN: {
1838                 Font font(ignore_font, ignore_language);
1839                 font.fontInfo().setFamily(ROMAN_FAMILY);
1840                 toggleAndShow(cur, this, font);
1841                 break;
1842         }
1843
1844         case LFUN_FONT_DEFAULT: {
1845                 Font font(inherit_font, ignore_language);
1846                 toggleAndShow(cur, this, font);
1847                 break;
1848         }
1849
1850         case LFUN_FONT_STRIKEOUT: {
1851                 Font font(ignore_font, ignore_language);
1852                 font.fontInfo().setStrikeout(FONT_TOGGLE);
1853                 toggleAndShow(cur, this, font);
1854                 break;
1855         }
1856
1857         case LFUN_FONT_UULINE: {
1858                 Font font(ignore_font, ignore_language);
1859                 font.fontInfo().setUuline(FONT_TOGGLE);
1860                 toggleAndShow(cur, this, font);
1861                 break;
1862         }
1863
1864         case LFUN_FONT_UWAVE: {
1865                 Font font(ignore_font, ignore_language);
1866                 font.fontInfo().setUwave(FONT_TOGGLE);
1867                 toggleAndShow(cur, this, font);
1868                 break;
1869         }
1870
1871         case LFUN_FONT_UNDERLINE: {
1872                 Font font(ignore_font, ignore_language);
1873                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1874                 toggleAndShow(cur, this, font);
1875                 break;
1876         }
1877
1878         case LFUN_FONT_SIZE: {
1879                 Font font(ignore_font, ignore_language);
1880                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1881                 toggleAndShow(cur, this, font);
1882                 break;
1883         }
1884
1885         case LFUN_LANGUAGE: {
1886                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1887                 if (!lang)
1888                         break;
1889                 Font font(ignore_font, lang);
1890                 toggleAndShow(cur, this, font);
1891                 break;
1892         }
1893
1894         case LFUN_TEXTSTYLE_APPLY:
1895                 toggleAndShow(cur, this, freefont, toggleall);
1896                 cur.message(_("Character set"));
1897                 break;
1898
1899         // Set the freefont using the contents of \param data dispatched from
1900         // the frontends and apply it at the current cursor location.
1901         case LFUN_TEXTSTYLE_UPDATE: {
1902                 Font font;
1903                 bool toggle;
1904                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1905                         freefont = font;
1906                         toggleall = toggle;
1907                         toggleAndShow(cur, this, freefont, toggleall);
1908                         cur.message(_("Character set"));
1909                 } else {
1910                         lyxerr << "Argument not ok";
1911                 }
1912                 break;
1913         }
1914
1915         case LFUN_FINISHED_LEFT:
1916                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1917                 // We're leaving an inset, going left. If the inset is LTR, we're
1918                 // leaving from the front, so we should not move (remain at --- but
1919                 // not in --- the inset). If the inset is RTL, move left, without
1920                 // entering the inset itself; i.e., move to after the inset.
1921                 if (cur.paragraph().getFontSettings(
1922                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1923                         cursorVisLeft(cur, true);
1924                 break;
1925
1926         case LFUN_FINISHED_RIGHT:
1927                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1928                 // We're leaving an inset, going right. If the inset is RTL, we're
1929                 // leaving from the front, so we should not move (remain at --- but
1930                 // not in --- the inset). If the inset is LTR, move right, without
1931                 // entering the inset itself; i.e., move to after the inset.
1932                 if (!cur.paragraph().getFontSettings(
1933                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1934                         cursorVisRight(cur, true);
1935                 break;
1936
1937         case LFUN_FINISHED_BACKWARD:
1938                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1939                 break;
1940
1941         case LFUN_FINISHED_FORWARD:
1942                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1943                 ++cur.pos();
1944                 cur.setCurrentFont();
1945                 break;
1946
1947         case LFUN_LAYOUT_PARAGRAPH: {
1948                 string data;
1949                 params2string(cur.paragraph(), data);
1950                 data = "show\n" + data;
1951                 bv->showDialog("paragraph", data);
1952                 break;
1953         }
1954
1955         case LFUN_PARAGRAPH_UPDATE: {
1956                 string data;
1957                 params2string(cur.paragraph(), data);
1958
1959                 // Will the paragraph accept changes from the dialog?
1960                 bool const accept =
1961                         cur.inset().allowParagraphCustomization(cur.idx());
1962
1963                 data = "update " + convert<string>(accept) + '\n' + data;
1964                 bv->updateDialog("paragraph", data);
1965                 break;
1966         }
1967
1968         case LFUN_ACCENT_UMLAUT:
1969         case LFUN_ACCENT_CIRCUMFLEX:
1970         case LFUN_ACCENT_GRAVE:
1971         case LFUN_ACCENT_ACUTE:
1972         case LFUN_ACCENT_TILDE:
1973         case LFUN_ACCENT_CEDILLA:
1974         case LFUN_ACCENT_MACRON:
1975         case LFUN_ACCENT_DOT:
1976         case LFUN_ACCENT_UNDERDOT:
1977         case LFUN_ACCENT_UNDERBAR:
1978         case LFUN_ACCENT_CARON:
1979         case LFUN_ACCENT_BREVE:
1980         case LFUN_ACCENT_TIE:
1981         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1982         case LFUN_ACCENT_CIRCLE:
1983         case LFUN_ACCENT_OGONEK:
1984                 theApp()->handleKeyFunc(cmd.action);
1985                 if (!cmd.argument().empty())
1986                         // FIXME: Are all these characters encoded in one byte in utf8?
1987                         bv->translateAndInsert(cmd.argument()[0], this, cur);
1988                 break;
1989
1990         case LFUN_FLOAT_LIST_INSERT: {
1991                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1992                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
1993                         cur.recordUndo();
1994                         if (cur.selection())
1995                                 cutSelection(cur, true, false);
1996                         breakParagraph(cur);
1997
1998                         if (cur.lastpos() != 0) {
1999                                 cursorBackward(cur);
2000                                 breakParagraph(cur);
2001                         }
2002
2003                         docstring const laystr = cur.inset().usePlainLayout() ?
2004                                 tclass.plainLayoutName() :
2005                                 tclass.defaultLayoutName();
2006                         setLayout(cur, laystr);
2007                         ParagraphParameters p;
2008                         // FIXME If this call were replaced with one to clearParagraphParams(),
2009                         // then we could get rid of this method altogether.
2010                         setParagraphs(cur, p);
2011                         // FIXME This should be simplified when InsetFloatList takes a
2012                         // Buffer in its constructor.
2013                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2014                         ifl->setBuffer(bv->buffer());
2015                         insertInset(cur, ifl);
2016                         cur.posForward();
2017                 } else {
2018                         lyxerr << "Non-existent float type: "
2019                                << to_utf8(cmd.argument()) << endl;
2020                 }
2021                 break;
2022         }
2023
2024         case LFUN_CHANGE_ACCEPT: {
2025                 acceptOrRejectChanges(cur, ACCEPT);
2026                 break;
2027         }
2028
2029         case LFUN_CHANGE_REJECT: {
2030                 acceptOrRejectChanges(cur, REJECT);
2031                 break;
2032         }
2033
2034         case LFUN_THESAURUS_ENTRY: {
2035                 docstring arg = cmd.argument();
2036                 if (arg.empty()) {
2037                         arg = cur.selectionAsString(false);
2038                         // FIXME
2039                         if (arg.size() > 100 || arg.empty()) {
2040                                 // Get word or selection
2041                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2042                                 arg = cur.selectionAsString(false);
2043                                 arg += " lang=" + from_ascii(cur.getFont().language()->lang());
2044                         }
2045                 }
2046                 bv->showDialog("thesaurus", to_utf8(arg));
2047                 break;
2048         }
2049
2050         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2051                 // Given data, an encoding of the ParagraphParameters
2052                 // generated in the Paragraph dialog, this function sets
2053                 // the current paragraph, or currently selected paragraphs,
2054                 // appropriately.
2055                 // NOTE: This function overrides all existing settings.
2056                 setParagraphs(cur, cmd.argument());
2057                 cur.message(_("Paragraph layout set"));
2058                 break;
2059         }
2060
2061         case LFUN_PARAGRAPH_PARAMS: {
2062                 // Given data, an encoding of the ParagraphParameters as we'd
2063                 // find them in a LyX file, this function modifies the current paragraph,
2064                 // or currently selected paragraphs.
2065                 // NOTE: This function only modifies, and does not override, existing
2066                 // settings.
2067                 setParagraphs(cur, cmd.argument(), true);
2068                 cur.message(_("Paragraph layout set"));
2069                 break;
2070         }
2071
2072         case LFUN_ESCAPE:
2073                 if (cur.selection()) {
2074                         cur.setSelection(false);
2075                 } else {
2076                         cur.undispatched();
2077                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2078                         // correct, but I'm not 100% sure -- dov, 071019
2079                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2080                 }
2081                 break;
2082
2083         case LFUN_OUTLINE_UP:
2084                 outline(OutlineUp, cur);
2085                 setCursor(cur, cur.pit(), 0);
2086                 cur.buffer()->updateLabels();
2087                 needsUpdate = true;
2088                 break;
2089
2090         case LFUN_OUTLINE_DOWN:
2091                 outline(OutlineDown, cur);
2092                 setCursor(cur, cur.pit(), 0);
2093                 cur.buffer()->updateLabels();
2094                 needsUpdate = true;
2095                 break;
2096
2097         case LFUN_OUTLINE_IN:
2098                 outline(OutlineIn, cur);
2099                 cur.buffer()->updateLabels();
2100                 needsUpdate = true;
2101                 break;
2102
2103         case LFUN_OUTLINE_OUT:
2104                 outline(OutlineOut, cur);
2105                 cur.buffer()->updateLabels();
2106                 needsUpdate = true;
2107                 break;
2108         
2109         case LFUN_OUTLINE_DRAGMOVE: {
2110                 int const move_id = convert<int>(cmd.getArg(0));
2111                 int const move_to_id = convert<int>(cmd.getArg(1));
2112                 dragMove(cur, move_id, move_to_id);
2113                 setCursor(cur, cur.pit(), 0);
2114                 cur.buffer()->updateLabels();
2115                 needsUpdate = true;
2116                 break;
2117         }
2118
2119         default:
2120                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2121                 cur.undispatched();
2122                 break;
2123         }
2124
2125         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2126
2127         // FIXME: The cursor flag is reset two lines below
2128         // so we need to check here if some of the LFUN did touch that.
2129         // for now only Text::erase() and Text::backspace() do that.
2130         // The plan is to verify all the LFUNs and then to remove this
2131         // singleParUpdate boolean altogether.
2132         if (cur.result().update() & Update::Force) {
2133                 singleParUpdate = false;
2134                 needsUpdate = true;
2135         }
2136
2137         // FIXME: the following code should go in favor of fine grained
2138         // update flag treatment.
2139         if (singleParUpdate) {
2140                 // Inserting characters does not change par height in general. So, try
2141                 // to update _only_ this paragraph. BufferView will detect if a full
2142                 // metrics update is needed anyway.
2143                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
2144                 return;
2145         }
2146
2147         if (!needsUpdate
2148             && &oldTopSlice.inset() == &cur.inset()
2149             && oldTopSlice.idx() == cur.idx()
2150             && !sel // sel is a backup of cur.selection() at the beginning of the function.
2151             && !cur.selection())
2152                 // FIXME: it would be better if we could just do this
2153                 //
2154                 //if (cur.result().update() != Update::FitCursor)
2155                 //      cur.noUpdate();
2156                 //
2157                 // But some LFUNs do not set Update::FitCursor when needed, so we
2158                 // do it for all. This is not very harmfull as FitCursor will provoke
2159                 // a full redraw only if needed but still, a proper review of all LFUN
2160                 // should be done and this needsUpdate boolean can then be removed.
2161                 cur.updateFlags(Update::FitCursor);
2162         else
2163                 cur.updateFlags(Update::Force | Update::FitCursor);
2164 }
2165
2166
2167 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2168                         FuncStatus & flag) const
2169 {
2170         LASSERT(cur.text() == this, /**/);
2171
2172         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2173         bool enable = true;
2174         InsetCode code = NO_CODE;
2175
2176         switch (cmd.action) {
2177
2178         case LFUN_DEPTH_DECREMENT:
2179                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2180                 break;
2181
2182         case LFUN_DEPTH_INCREMENT:
2183                 enable = changeDepthAllowed(cur, INC_DEPTH);
2184                 break;
2185
2186         case LFUN_APPENDIX:
2187                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2188                 break;
2189
2190         case LFUN_DIALOG_SHOW_NEW_INSET:
2191                 if (cmd.argument() == "bibitem")
2192                         code = BIBITEM_CODE;
2193                 else if (cmd.argument() == "bibtex") {
2194                         code = BIBTEX_CODE;
2195                         // not allowed in description items
2196                         enable = !inDescriptionItem(cur);
2197                 }
2198                 else if (cmd.argument() == "box")
2199                         code = BOX_CODE;
2200                 else if (cmd.argument() == "branch")
2201                         code = BRANCH_CODE;
2202                 else if (cmd.argument() == "citation")
2203                         code = CITE_CODE;
2204                 else if (cmd.argument() == "ert")
2205                         code = ERT_CODE;
2206                 else if (cmd.argument() == "external")
2207                         code = EXTERNAL_CODE;
2208                 else if (cmd.argument() == "float")
2209                         code = FLOAT_CODE;
2210                 else if (cmd.argument() == "graphics")
2211                         code = GRAPHICS_CODE;
2212                 else if (cmd.argument() == "href")
2213                         code = HYPERLINK_CODE;
2214                 else if (cmd.argument() == "include")
2215                         code = INCLUDE_CODE;
2216                 else if (cmd.argument() == "index")
2217                         code = INDEX_CODE;
2218                 else if (cmd.argument() == "index_print")
2219                         code = INDEX_PRINT_CODE;
2220                 else if (cmd.argument() == "nomenclature")
2221                         code = NOMENCL_CODE;
2222                 else if (cmd.argument() == "nomencl_print")
2223                         code = NOMENCL_PRINT_CODE;
2224                 else if (cmd.argument() == "label")
2225                         code = LABEL_CODE;
2226                 else if (cmd.argument() == "note")
2227                         code = NOTE_CODE;
2228                 else if (cmd.argument() == "phantom")
2229                         code = PHANTOM_CODE;
2230                 else if (cmd.argument() == "ref")
2231                         code = REF_CODE;
2232                 else if (cmd.argument() == "space")
2233                         code = SPACE_CODE;
2234                 else if (cmd.argument() == "toc")
2235                         code = TOC_CODE;
2236                 else if (cmd.argument() == "vspace")
2237                         code = VSPACE_CODE;
2238                 else if (cmd.argument() == "wrap")
2239                         code = WRAP_CODE;
2240                 else if (cmd.argument() == "listings")
2241                         code = LISTINGS_CODE;
2242                 break;
2243
2244         case LFUN_ERT_INSERT:
2245                 code = ERT_CODE;
2246                 break;
2247         case LFUN_LISTING_INSERT:
2248                 code = LISTINGS_CODE;
2249                 // not allowed in description items
2250                 enable = !inDescriptionItem(cur);
2251                 break;
2252         case LFUN_FOOTNOTE_INSERT:
2253                 code = FOOT_CODE;
2254                 break;
2255         case LFUN_TABULAR_INSERT:
2256                 code = TABULAR_CODE;
2257                 break;
2258         case LFUN_MARGINALNOTE_INSERT:
2259                 code = MARGIN_CODE;
2260                 break;
2261         case LFUN_FLOAT_INSERT:
2262         case LFUN_FLOAT_WIDE_INSERT:
2263                 // FIXME: If there is a selection, we should check whether there
2264                 // are floats in the selection, but this has performance issues, see
2265                 // LFUN_CHANGE_ACCEPT/REJECT.
2266                 code = FLOAT_CODE;
2267                 if (inDescriptionItem(cur))
2268                         // not allowed in description items
2269                         enable = false;
2270                 else {
2271                         InsetCode const inset_code = cur.inset().lyxCode();
2272
2273                         // algorithm floats cannot be put in another float
2274                         if (to_utf8(cmd.argument()) == "algorithm") {
2275                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2276                                 break;
2277                         }
2278
2279                         // for figures and tables: only allow in another
2280                         // float or wrap if it is of the same type and
2281                         // not a subfloat already
2282                         if(cur.inset().lyxCode() == code) {
2283                                 InsetFloat const & ins =
2284                                         static_cast<InsetFloat const &>(cur.inset());
2285                                 enable = ins.params().type == to_utf8(cmd.argument())
2286                                         && !ins.params().subfloat;
2287                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
2288                                 InsetWrap const & ins =
2289                                         static_cast<InsetWrap const &>(cur.inset());
2290                                 enable = ins.params().type == to_utf8(cmd.argument());
2291                         }
2292                 }
2293                 break;
2294         case LFUN_WRAP_INSERT:
2295                 code = WRAP_CODE;
2296                 // not allowed in description items
2297                 enable = !inDescriptionItem(cur);
2298                 break;
2299         case LFUN_FLOAT_LIST_INSERT:
2300                 code = FLOAT_LIST_CODE;
2301                 // not allowed in description items
2302                 enable = !inDescriptionItem(cur);
2303                 break;
2304         case LFUN_CAPTION_INSERT:
2305                 code = CAPTION_CODE;
2306                 // not allowed in description items
2307                 enable = !inDescriptionItem(cur);
2308                 break;
2309         case LFUN_NOTE_INSERT:
2310                 code = NOTE_CODE;
2311                 // in commands (sections etc.) and description items,
2312                 // only Notes are allowed
2313                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2314                           (!cur.paragraph().layout().isCommand()
2315                            && !inDescriptionItem(cur)));
2316                 break;
2317         case LFUN_FLEX_INSERT: {
2318                 code = FLEX_CODE;
2319                 string s = cmd.getArg(0);
2320                 InsetLayout il =
2321                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2322                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2323                     il.lyxtype() != InsetLayout::CUSTOM &&
2324                     il.lyxtype() != InsetLayout::ELEMENT &&
2325                     il.lyxtype ()!= InsetLayout::STANDARD)
2326                         enable = false;
2327                 break;
2328                 }
2329         case LFUN_BOX_INSERT:
2330                 code = BOX_CODE;
2331                 break;
2332         case LFUN_BRANCH_INSERT:
2333                 code = BRANCH_CODE;
2334                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2335                     && cur.buffer()->params().branchlist().empty())
2336                         enable = false;
2337                 break;
2338         case LFUN_PHANTOM_INSERT:
2339                 code = PHANTOM_CODE;
2340                 break;
2341         case LFUN_LABEL_INSERT:
2342                 code = LABEL_CODE;
2343                 break;
2344         case LFUN_LINE_INSERT:
2345                 code = LINE_CODE;
2346                 break;
2347         case LFUN_INFO_INSERT:
2348                 code = INFO_CODE;
2349                 break;
2350         case LFUN_OPTIONAL_INSERT:
2351                 code = OPTARG_CODE;
2352                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
2353                         < cur.paragraph().layout().optionalargs;
2354                 break;
2355         case LFUN_INDEX_INSERT:
2356                 code = INDEX_CODE;
2357                 break;
2358         case LFUN_INDEX_PRINT:
2359                 code = INDEX_PRINT_CODE;
2360                 // not allowed in description items
2361                 enable = !inDescriptionItem(cur);
2362                 break;
2363         case LFUN_NOMENCL_INSERT:
2364                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2365                         enable = false;
2366                         break;
2367                 }
2368                 code = NOMENCL_CODE;
2369                 break;
2370         case LFUN_NOMENCL_PRINT:
2371                 code = NOMENCL_PRINT_CODE;
2372                 // not allowed in description items
2373                 enable = !inDescriptionItem(cur);
2374                 break;
2375         case LFUN_TOC_INSERT:
2376                 code = TOC_CODE;
2377                 // not allowed in description items
2378                 enable = !inDescriptionItem(cur);
2379                 break;
2380         case LFUN_HYPERLINK_INSERT:
2381                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2382                         enable = false;
2383                         break;
2384                 }
2385                 code = HYPERLINK_CODE;
2386                 break;
2387         case LFUN_QUOTE_INSERT:
2388                 // always allow this, since we will inset a raw quote
2389                 // if an inset is not allowed.
2390                 break;
2391         case LFUN_SPECIALCHAR_INSERT:
2392                 code = SPECIALCHAR_CODE;
2393                 break;
2394         case LFUN_SPACE_INSERT:
2395                 // slight hack: we know this is allowed in math mode
2396                 if (cur.inTexted())
2397                         code = SPACE_CODE;
2398                 break;
2399
2400         case LFUN_MATH_INSERT:
2401         case LFUN_MATH_AMS_MATRIX:
2402         case LFUN_MATH_MATRIX:
2403         case LFUN_MATH_DELIM:
2404         case LFUN_MATH_BIGDELIM:
2405         case LFUN_MATH_DISPLAY:
2406         case LFUN_MATH_MODE:
2407         case LFUN_MATH_MACRO:
2408         case LFUN_MATH_SUBSCRIPT:
2409         case LFUN_MATH_SUPERSCRIPT:
2410                 code = MATH_HULL_CODE;
2411                 break;
2412
2413         case LFUN_INSET_MODIFY:
2414                 // We need to disable this, because we may get called for a
2415                 // tabular cell via
2416                 // InsetTabular::getStatus() -> InsetText::getStatus()
2417                 // and we don't handle LFUN_INSET_MODIFY.
2418                 enable = false;
2419                 break;
2420
2421         case LFUN_FONT_EMPH:
2422                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2423                 break;
2424
2425         case LFUN_FONT_ITAL:
2426                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2427                 break;
2428
2429         case LFUN_FONT_NOUN:
2430                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2431                 break;
2432
2433         case LFUN_FONT_BOLD:
2434         case LFUN_FONT_BOLDSYMBOL:
2435                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2436                 break;
2437
2438         case LFUN_FONT_SANS:
2439                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2440                 break;
2441
2442         case LFUN_FONT_ROMAN:
2443                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2444                 break;
2445
2446         case LFUN_FONT_TYPEWRITER:
2447                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2448                 break;
2449
2450         case LFUN_CUT:
2451         case LFUN_COPY:
2452                 enable = cur.selection();
2453                 break;
2454
2455         case LFUN_PASTE: {
2456                 if (cmd.argument().empty()) {
2457                         if (theClipboard().isInternal())
2458                                 enable = cap::numberOfSelections() > 0;
2459                         else
2460                                 enable = !theClipboard().empty();
2461                         break;
2462                 }
2463
2464                 // we have an argument
2465                 string const arg = to_utf8(cmd.argument());
2466                 if (isStrUnsignedInt(arg)) {
2467                         // it's a number and therefore means the internal stack
2468                         unsigned int n = convert<unsigned int>(arg);
2469                         enable = cap::numberOfSelections() > n;
2470                         break;
2471                 }
2472
2473                 // explicit graphics type?
2474                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
2475                 if ((arg == "pdf" && (type = Clipboard::PdfGraphicsType))
2476                           || (arg == "png" && (type = Clipboard::PngGraphicsType))
2477                           || (arg == "jpeg" && (type = Clipboard::JpegGraphicsType))
2478                           || (arg == "linkback" &&  (type = Clipboard::LinkBackGraphicsType))
2479                           || (arg == "emf" &&  (type = Clipboard::EmfGraphicsType))
2480                           || (arg == "wmf" &&  (type = Clipboard::WmfGraphicsType))) {
2481                         enable = theClipboard().hasGraphicsContents(type);
2482                         break;
2483                 }
2484
2485                 // unknown argument
2486                 enable = false;
2487                 break;
2488          }
2489
2490         case LFUN_CLIPBOARD_PASTE:
2491                 enable = !theClipboard().empty();
2492                 break;
2493
2494         case LFUN_PRIMARY_SELECTION_PASTE:
2495                 enable = cur.selection() || !theSelection().empty();
2496                 break;
2497
2498         case LFUN_SELECTION_PASTE:
2499                 enable = cap::selection();
2500                 break;
2501
2502         case LFUN_PARAGRAPH_MOVE_UP:
2503                 enable = cur.pit() > 0 && !cur.selection();
2504                 break;
2505
2506         case LFUN_PARAGRAPH_MOVE_DOWN:
2507                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2508                 break;
2509
2510         case LFUN_CHANGE_ACCEPT:
2511         case LFUN_CHANGE_REJECT:
2512                 // In principle, these LFUNs should only be enabled if there
2513                 // is a change at the current position/in the current selection.
2514                 // However, without proper optimizations, this will inevitably
2515                 // result in unacceptable performance - just imagine a user who
2516                 // wants to select the complete content of a long document.
2517                 if (!cur.selection())
2518                         enable = cur.paragraph().isChanged(cur.pos());
2519                 else
2520                         // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2521                         // for selections.
2522                         enable = true;
2523                 break;
2524
2525         case LFUN_OUTLINE_UP:
2526         case LFUN_OUTLINE_DOWN:
2527         case LFUN_OUTLINE_IN:
2528         case LFUN_OUTLINE_OUT:
2529         case LFUN_OUTLINE_DRAGMOVE:
2530                 // FIXME: LyX is not ready for outlining within inset.
2531                 enable = isMainText()
2532                         && cur.paragraph().layout().toclevel != Layout::NOT_IN_TOC;
2533                 break;
2534
2535         case LFUN_NEWLINE_INSERT:
2536                 // LaTeX restrictions (labels or empty par)
2537                 enable = (cur.pos() > cur.paragraph().beginOfBody());
2538                 break;
2539
2540         case LFUN_TAB_INSERT:
2541         case LFUN_TAB_DELETE:
2542                 enable = cur.inset().getLayout().isPassThru();
2543                 break;
2544
2545         case LFUN_SET_GRAPHICS_GROUP: {
2546                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
2547                 if (!ins)
2548                         enable = false;
2549                 else
2550                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
2551                 break;
2552         }
2553
2554         case LFUN_NEWPAGE_INSERT:
2555                 // not allowed in description items
2556                 code = NEWPAGE_CODE;
2557                 enable = !inDescriptionItem(cur);
2558                 break;
2559
2560         case LFUN_DATE_INSERT: {
2561                 string const format = cmd.argument().empty()
2562                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
2563                 enable = support::os::is_valid_strftime(format);
2564                 break;
2565         }
2566
2567         case LFUN_LANGUAGE:
2568                 enable = !cur.inset().getLayout().isPassThru();
2569                 break;
2570
2571         case LFUN_BREAK_PARAGRAPH:
2572                 enable = cur.inset().getLayout().isMultiPar();
2573                 break;
2574
2575         case LFUN_WORD_DELETE_FORWARD:
2576         case LFUN_WORD_DELETE_BACKWARD:
2577         case LFUN_LINE_DELETE:
2578         case LFUN_WORD_FORWARD:
2579         case LFUN_WORD_BACKWARD:
2580         case LFUN_WORD_RIGHT:
2581         case LFUN_WORD_LEFT:
2582         case LFUN_CHAR_FORWARD:
2583         case LFUN_CHAR_FORWARD_SELECT:
2584         case LFUN_CHAR_BACKWARD:
2585         case LFUN_CHAR_BACKWARD_SELECT:
2586         case LFUN_CHAR_LEFT:
2587         case LFUN_CHAR_LEFT_SELECT:
2588         case LFUN_CHAR_RIGHT:
2589         case LFUN_CHAR_RIGHT_SELECT:
2590         case LFUN_UP:
2591         case LFUN_UP_SELECT:
2592         case LFUN_DOWN:
2593         case LFUN_DOWN_SELECT:
2594         case LFUN_PARAGRAPH_UP_SELECT:
2595         case LFUN_PARAGRAPH_DOWN_SELECT:
2596         case LFUN_LINE_BEGIN_SELECT:
2597         case LFUN_LINE_END_SELECT:
2598         case LFUN_WORD_FORWARD_SELECT:
2599         case LFUN_WORD_BACKWARD_SELECT:
2600         case LFUN_WORD_RIGHT_SELECT:
2601         case LFUN_WORD_LEFT_SELECT:
2602         case LFUN_WORD_SELECT:
2603         case LFUN_SECTION_SELECT:
2604         case LFUN_PARAGRAPH_UP:
2605         case LFUN_PARAGRAPH_DOWN:
2606         case LFUN_LINE_BEGIN:
2607         case LFUN_LINE_END:
2608         case LFUN_CHAR_DELETE_FORWARD:
2609         case LFUN_CHAR_DELETE_BACKWARD:
2610         case LFUN_INSET_INSERT:
2611         case LFUN_WORD_UPCASE:
2612         case LFUN_WORD_LOWCASE:
2613         case LFUN_WORD_CAPITALIZE:
2614         case LFUN_CHARS_TRANSPOSE:
2615         case LFUN_SERVER_GET_XY:
2616         case LFUN_SERVER_SET_XY:
2617         case LFUN_SERVER_GET_LAYOUT:
2618         case LFUN_LAYOUT:
2619         case LFUN_SELF_INSERT:
2620         case LFUN_FONT_DEFAULT:
2621         case LFUN_FONT_UNDERLINE:
2622         case LFUN_FONT_STRIKEOUT:
2623         case LFUN_FONT_UULINE:
2624         case LFUN_FONT_UWAVE:
2625         case LFUN_FONT_SIZE:
2626         case LFUN_TEXTSTYLE_APPLY:
2627         case LFUN_TEXTSTYLE_UPDATE:
2628         case LFUN_LAYOUT_PARAGRAPH:
2629         case LFUN_PARAGRAPH_UPDATE:
2630         case LFUN_ACCENT_UMLAUT:
2631         case LFUN_ACCENT_CIRCUMFLEX:
2632         case LFUN_ACCENT_GRAVE:
2633         case LFUN_ACCENT_ACUTE:
2634         case LFUN_ACCENT_TILDE:
2635         case LFUN_ACCENT_CEDILLA:
2636         case LFUN_ACCENT_MACRON:
2637         case LFUN_ACCENT_DOT:
2638         case LFUN_ACCENT_UNDERDOT:
2639         case LFUN_ACCENT_UNDERBAR:
2640         case LFUN_ACCENT_CARON:
2641         case LFUN_ACCENT_BREVE:
2642         case LFUN_ACCENT_TIE:
2643         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2644         case LFUN_ACCENT_CIRCLE:
2645         case LFUN_ACCENT_OGONEK:
2646         case LFUN_THESAURUS_ENTRY:
2647         case LFUN_PARAGRAPH_PARAMS_APPLY:
2648         case LFUN_PARAGRAPH_PARAMS:
2649         case LFUN_ESCAPE:
2650         case LFUN_BUFFER_BEGIN:
2651         case LFUN_BUFFER_END:
2652         case LFUN_BUFFER_BEGIN_SELECT:
2653         case LFUN_BUFFER_END_SELECT:
2654         case LFUN_INSET_BEGIN:
2655         case LFUN_INSET_END:
2656         case LFUN_INSET_BEGIN_SELECT:
2657         case LFUN_INSET_END_SELECT:
2658         case LFUN_INSET_SELECT_ALL:
2659         case LFUN_UNICODE_INSERT:
2660                 // these are handled in our dispatch()
2661                 enable = true;
2662                 break;
2663
2664         default:
2665                 return false;
2666         }
2667
2668         if (code != NO_CODE
2669             && (cur.empty() 
2670                 || !cur.inset().insetAllowed(code)
2671                 || cur.paragraph().layout().pass_thru))
2672                 enable = false;
2673
2674         switch (cmd.action) {
2675         case LFUN_ACCENT_ACUTE:
2676         case LFUN_ACCENT_BREVE:
2677         case LFUN_ACCENT_CARON:
2678         case LFUN_ACCENT_CEDILLA:
2679         case LFUN_ACCENT_CIRCLE:
2680         case LFUN_ACCENT_CIRCUMFLEX:
2681         case LFUN_ACCENT_DOT:
2682         case LFUN_ACCENT_GRAVE:
2683         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2684         case LFUN_ACCENT_MACRON:
2685         case LFUN_ACCENT_OGONEK:
2686         case LFUN_ACCENT_TIE:
2687         case LFUN_ACCENT_TILDE:
2688         case LFUN_ACCENT_UMLAUT:
2689         case LFUN_ACCENT_UNDERBAR:
2690         case LFUN_ACCENT_UNDERDOT:
2691         case LFUN_FONT_BOLD:
2692         case LFUN_FONT_BOLDSYMBOL:
2693         case LFUN_FONT_TYPEWRITER:
2694         case LFUN_FONT_DEFAULT:
2695         case LFUN_FONT_EMPH:
2696         case LFUN_FONT_NOUN:
2697         case LFUN_FONT_ROMAN:
2698         case LFUN_FONT_SANS:
2699         case LFUN_FONT_FRAK:
2700         case LFUN_FONT_ITAL:
2701         case LFUN_FONT_SIZE:
2702         case LFUN_FONT_STATE:
2703         case LFUN_FONT_UNDERLINE:
2704         case LFUN_FONT_STRIKEOUT:
2705         case LFUN_FONT_UULINE:
2706         case LFUN_FONT_UWAVE:
2707         case LFUN_TEXTSTYLE_APPLY:
2708         case LFUN_TEXTSTYLE_UPDATE:
2709                 if (cur.inset().getLayout().isPassThru())
2710                         enable = false;
2711                 break;
2712         default:
2713                 break;
2714         }
2715
2716         flag.setEnabled(enable);
2717         return true;
2718 }
2719
2720
2721 void Text::pasteString(Cursor & cur, docstring const & clip,
2722                 bool asParagraphs)
2723 {
2724         cur.clearSelection();
2725         if (!clip.empty()) {
2726                 cur.recordUndo();
2727                 if (asParagraphs)
2728                         insertStringAsParagraphs(cur, clip, cur.current_font);
2729                 else
2730                         insertStringAsLines(cur, clip, cur.current_font);
2731         }
2732 }
2733
2734
2735 // FIXME: an item inset would make things much easier.
2736 bool Text::inDescriptionItem(Cursor & cur) const
2737 {
2738         Paragraph & par = cur.paragraph();
2739         pos_type const pos = cur.pos();
2740         pos_type const body_pos = par.beginOfBody();
2741
2742         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
2743             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
2744                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
2745                 return false;
2746
2747         return (pos < body_pos
2748                 || (pos == body_pos
2749                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
2750 }
2751
2752 } // namespace lyx