]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
Use of div for labels causes validation errors. See #8843.
[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 "BranchList.h"
21 #include "FloatList.h"
22 #include "FuncStatus.h"
23 #include "Buffer.h"
24 #include "buffer_funcs.h"
25 #include "BufferParams.h"
26 #include "BufferView.h"
27 #include "Changes.h"
28 #include "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "ErrorList.h"
32 #include "factory.h"
33 #include "FuncRequest.h"
34 #include "InsetList.h"
35 #include "Intl.h"
36 #include "Language.h"
37 #include "Layout.h"
38 #include "LyXAction.h"
39 #include "LyX.h"
40 #include "Lexer.h"
41 #include "LyXRC.h"
42 #include "Paragraph.h"
43 #include "ParagraphParameters.h"
44 #include "SpellChecker.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "Thesaurus.h"
48 #include "WordLangTuple.h"
49
50 #include "frontends/alert.h"
51 #include "frontends/Application.h"
52 #include "frontends/Clipboard.h"
53 #include "frontends/Selection.h"
54
55 #include "insets/InsetArgument.h"
56 #include "insets/InsetCollapsible.h"
57 #include "insets/InsetCommand.h"
58 #include "insets/InsetExternal.h"
59 #include "insets/InsetFloat.h"
60 #include "insets/InsetFloatList.h"
61 #include "insets/InsetGraphics.h"
62 #include "insets/InsetGraphicsParams.h"
63 #include "insets/InsetIPAMacro.h"
64 #include "insets/InsetNewline.h"
65 #include "insets/InsetQuotes.h"
66 #include "insets/InsetSpecialChar.h"
67 #include "insets/InsetText.h"
68 #include "insets/InsetWrap.h"
69
70 #include "support/convert.h"
71 #include "support/debug.h"
72 #include "support/gettext.h"
73 #include "support/lassert.h"
74 #include "support/lstrings.h"
75 #include "support/lyxalgo.h"
76 #include "support/lyxtime.h"
77 #include "support/os.h"
78 #include "support/regex.h"
79
80 #include "mathed/InsetMathHull.h"
81 #include "mathed/InsetMathMacroTemplate.h"
82
83 #include <clocale>
84 #include <sstream>
85
86 using namespace std;
87 using namespace lyx::support;
88
89 namespace lyx {
90
91 using cap::copySelection;
92 using cap::cutSelection;
93 using cap::cutSelectionToTemp;
94 using cap::pasteFromStack;
95 using cap::pasteFromTemp;
96 using cap::pasteClipboardText;
97 using cap::pasteClipboardGraphics;
98 using cap::replaceSelection;
99 using cap::grabAndEraseSelection;
100 using cap::selClearOrDel;
101 using cap::pasteSimpleText;
102 using frontend::Clipboard;
103
104 // globals...
105 static Font freefont(ignore_font, ignore_language);
106 static bool toggleall = false;
107
108 static void toggleAndShow(Cursor & cur, Text * text,
109         Font const & font, bool toggleall = true)
110 {
111         text->toggleFree(cur, font, toggleall);
112
113         if (font.language() != ignore_language ||
114             font.fontInfo().number() != FONT_IGNORE) {
115                 TextMetrics const & tm = cur.bv().textMetrics(text);
116                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
117                                                        cur.real_current_font))
118                         text->setCursor(cur, cur.pit(), cur.pos(),
119                                         false, !cur.boundary());
120         }
121 }
122
123
124 static void moveCursor(Cursor & cur, bool selecting)
125 {
126         if (selecting || cur.mark())
127                 cur.setSelection();
128 }
129
130
131 static void finishChange(Cursor & cur, bool selecting)
132 {
133         cur.finishUndo();
134         moveCursor(cur, selecting);
135 }
136
137
138 static void mathDispatch(Cursor & cur, FuncRequest const & cmd)
139 {
140         cur.recordUndo();
141         docstring sel = cur.selectionAsString(false);
142
143         // It may happen that sel is empty but there is a selection
144         replaceSelection(cur);
145
146         // Is this a valid formula?
147         bool valid = true;
148
149         if (sel.empty()) {
150 #ifdef ENABLE_ASSERTIONS
151                 const int old_pos = cur.pos();
152 #endif
153                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
154 #ifdef ENABLE_ASSERTIONS
155                 LATTEST(old_pos == cur.pos());
156 #endif
157                 cur.nextInset()->edit(cur, true);
158                 if (cmd.action() != LFUN_MATH_MODE)
159                         // LFUN_MATH_MODE has a different meaning in math mode
160                         cur.dispatch(cmd);
161         } else {
162                 InsetMathHull * formula = new InsetMathHull(cur.buffer());
163                 string const selstr = to_utf8(sel);
164                 istringstream is(selstr);
165                 Lexer lex;
166                 lex.setStream(is);
167                 if (!formula->readQuiet(lex)) {
168                         // No valid formula, let's try with delims
169                         is.str("$" + selstr + "$");
170                         lex.setStream(is);
171                         if (!formula->readQuiet(lex)) {
172                                 // Still not valid, leave it as is
173                                 valid = false;
174                                 delete formula;
175                                 cur.insert(sel);
176                         }
177                 }
178                 if (valid) {
179                         cur.insert(formula);
180                         cur.nextInset()->edit(cur, true);
181                         LASSERT(cur.inMathed(), return);
182                         cur.pos() = 0;
183                         cur.resetAnchor();
184                         cur.selection(true);
185                         cur.pos() = cur.lastpos();
186                         if (cmd.action() != LFUN_MATH_MODE)
187                                 // LFUN_MATH_MODE has a different meaning in math mode
188                                 cur.dispatch(cmd);
189                         cur.clearSelection();
190                         cur.pos() = cur.lastpos();
191                 }
192         }
193         if (valid)
194                 cur.message(from_utf8(N_("Math editor mode")));
195         else
196                 cur.message(from_utf8(N_("No valid math formula")));
197 }
198
199
200 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
201 {
202         LASSERT(cmd.action() == LFUN_REGEXP_MODE, return);
203         if (cur.inRegexped()) {
204                 cur.message(_("Already in regular expression mode"));
205                 return;
206         }
207         cur.recordUndo();
208         docstring sel = cur.selectionAsString(false);
209
210         // It may happen that sel is empty but there is a selection
211         replaceSelection(cur);
212
213         cur.insert(new InsetMathHull(cur.buffer(), hullRegexp));
214         cur.nextInset()->edit(cur, true);
215         cur.niceInsert(sel);
216
217         cur.message(_("Regexp editor mode"));
218 }
219
220
221 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
222 {
223         cur.recordUndo();
224         cap::replaceSelection(cur);
225         cur.insert(new InsetSpecialChar(kind));
226         cur.posForward();
227 }
228
229
230 static void ipaChar(Cursor & cur, InsetIPAChar::Kind kind)
231 {
232         cur.recordUndo();
233         cap::replaceSelection(cur);
234         cur.insert(new InsetIPAChar(kind));
235         cur.posForward();
236 }
237
238
239 static bool doInsertInset(Cursor & cur, Text * text,
240         FuncRequest const & cmd, bool edit, bool pastesel)
241 {
242         Buffer & buffer = cur.bv().buffer();
243         BufferParams const & bparams = buffer.params();
244         Inset * inset = createInset(&buffer, cmd);
245         if (!inset)
246                 return false;
247
248         if (InsetCollapsible * ci = inset->asInsetCollapsible())
249                 ci->setButtonLabel();
250
251         cur.recordUndo();
252         if (cmd.action() == LFUN_INDEX_INSERT) {
253                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
254                 text->insertInset(cur, inset);
255                 if (edit)
256                         inset->edit(cur, true);
257                 // Now put this into inset
258                 Font const f(inherit_font, cur.current_font.language());
259                 if (!ds.empty()) {
260                         cur.text()->insertStringAsLines(cur, ds, f);
261                         cur.leaveInset(*inset);
262                 }
263                 return true;
264         }
265         else if (cmd.action() == LFUN_ARGUMENT_INSERT) {
266                 bool cotextinsert = false;
267                 InsetArgument const * const ia = static_cast<InsetArgument const *>(inset);
268                 Layout const & lay = cur.paragraph().layout();
269                 Layout::LaTeXArgMap args = lay.args();
270                 Layout::LaTeXArgMap::const_iterator const lait = args.find(ia->name());
271                 if (lait != args.end())
272                         cotextinsert = (*lait).second.insertcotext;
273                 else {
274                         InsetLayout const & il = cur.inset().getLayout();
275                         args = il.args();
276                         Layout::LaTeXArgMap::const_iterator const ilait = args.find(ia->name());
277                         if (ilait != args.end())
278                                 cotextinsert = (*ilait).second.insertcotext;
279                 }
280                 // The argument requests to insert a copy of the co-text to the inset
281                 if (cotextinsert) {
282                         docstring ds;
283                         // If we have a selection within a paragraph, use this
284                         if (cur.selection() && cur.selBegin().pit() == cur.selEnd().pit())
285                                 ds = cur.selectionAsString(false);
286                         // else use the whole paragraph
287                         else
288                                 ds = cur.paragraph().asString();
289                         text->insertInset(cur, inset);
290                         if (edit)
291                                 inset->edit(cur, true);
292                         // Now put co-text into inset
293                         Font const f(inherit_font, cur.current_font.language());
294                         if (!ds.empty()) {
295                                 cur.text()->insertStringAsLines(cur, ds, f);
296                                 cur.leaveInset(*inset);
297                         }
298                         return true;
299                 }
300         }
301
302         bool gotsel = false;
303         if (cur.selection()) {
304                 cutSelectionToTemp(cur, false, pastesel);
305                 cur.clearSelection();
306                 gotsel = true;
307         }
308         text->insertInset(cur, inset);
309
310         if (edit)
311                 inset->edit(cur, true);
312
313         if (!gotsel || !pastesel)
314                 return true;
315
316         pasteFromTemp(cur, cur.buffer()->errorList("Paste"));
317         cur.buffer()->errors("Paste");
318         cur.clearSelection(); // bug 393
319         cur.finishUndo();
320         InsetText * inset_text = inset->asInsetText();
321         if (inset_text) {
322                 inset_text->fixParagraphsFont();
323                 if (!inset_text->allowMultiPar() || cur.lastpit() == 0) {
324                         // reset first par to default
325                         cur.text()->paragraphs().begin()
326                                 ->setPlainOrDefaultLayout(bparams.documentClass());
327                         cur.pos() = 0;
328                         cur.pit() = 0;
329                         // Merge multiple paragraphs -- hack
330                         while (cur.lastpit() > 0)
331                                 mergeParagraph(bparams, cur.text()->paragraphs(), 0);
332                         if (cmd.action() == LFUN_FLEX_INSERT)
333                                 return true;
334                         Cursor old = cur;
335                         cur.leaveInset(*inset);
336                         if (cmd.action() == LFUN_PREVIEW_INSERT
337                             || cmd.action() == LFUN_IPA_INSERT)
338                                 // trigger preview
339                                 notifyCursorLeavesOrEnters(old, cur);
340                 }
341         } else {
342                 cur.leaveInset(*inset);
343                 // reset surrounding par to default
344                 DocumentClass const & dc = bparams.documentClass();
345                 docstring const layoutname = inset->usePlainLayout()
346                         ? dc.plainLayoutName()
347                         : dc.defaultLayoutName();
348                 text->setLayout(cur, layoutname);
349         }
350         return true;
351 }
352
353
354 string const freefont2string()
355 {
356         return freefont.toString(toggleall);
357 }
358
359
360 /// the type of outline operation
361 enum OutlineOp {
362         OutlineUp, // Move this header with text down
363         OutlineDown,   // Move this header with text up
364         OutlineIn, // Make this header deeper
365         OutlineOut // Make this header shallower
366 };
367
368
369 static void outline(OutlineOp mode, Cursor & cur)
370 {
371         Buffer & buf = *cur.buffer();
372         pit_type & pit = cur.pit();
373         ParagraphList & pars = buf.text().paragraphs();
374         ParagraphList::iterator const bgn = pars.begin();
375         // The first paragraph of the area to be copied:
376         ParagraphList::iterator start = lyx::next(bgn, pit);
377         // The final paragraph of area to be copied:
378         ParagraphList::iterator finish = start;
379         ParagraphList::iterator const end = pars.end();
380
381         int const thistoclevel = buf.text().getTocLevel(distance(bgn, start));
382         int toclevel;
383
384         // Move out (down) from this section header
385         if (finish != end)
386                 ++finish;
387
388         // Seek the one (on same level) below
389         for (; finish != end; ++finish) {
390                 toclevel = buf.text().getTocLevel(distance(bgn, finish));
391                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
392                         break;
393         }
394
395         switch (mode) {
396                 case OutlineUp: {
397                         if (start == pars.begin())
398                                 // Nothing to move.
399                                 return;
400                         ParagraphList::iterator dest = start;
401                         // Move out (up) from this header
402                         if (dest == bgn)
403                                 return;
404                         // Search previous same-level header above
405                         do {
406                                 --dest;
407                                 toclevel = buf.text().getTocLevel(distance(bgn, dest));
408                         } while(dest != bgn
409                                 && (toclevel == Layout::NOT_IN_TOC
410                                     || toclevel > thistoclevel));
411                         // Not found; do nothing
412                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
413                                 return;
414                         pit_type const newpit = distance(bgn, dest);
415                         pit_type const len = distance(start, finish);
416                         pit_type const deletepit = pit + len;
417                         buf.undo().recordUndo(cur, newpit, deletepit - 1);
418                         pars.splice(dest, start, finish);
419                         cur.pit() = newpit;
420                         break;
421                 }
422                 case OutlineDown: {
423                         if (finish == end)
424                                 // Nothing to move.
425                                 return;
426                         // Go one down from *this* header:
427                         ParagraphList::iterator dest = next(finish, 1);
428                         // Go further down to find header to insert in front of:
429                         for (; dest != end; ++dest) {
430                                 toclevel = buf.text().getTocLevel(distance(bgn, dest));
431                                 if (toclevel != Layout::NOT_IN_TOC
432                                       && toclevel <= thistoclevel)
433                                         break;
434                         }
435                         // One such was found:
436                         pit_type newpit = distance(bgn, dest);
437                         buf.undo().recordUndo(cur, pit, newpit - 1);
438                         pit_type const len = distance(start, finish);
439                         pars.splice(dest, start, finish);
440                         cur.pit() = newpit - len;
441                         break;
442                 }
443                 case OutlineIn:
444                 case OutlineOut: {
445                         pit_type const len = distance(start, finish);
446                         buf.undo().recordUndo(cur, pit, pit + len - 1);
447                         for (; start != finish; ++start) {
448                                 toclevel = buf.text().getTocLevel(distance(bgn, start));
449                                 if (toclevel == Layout::NOT_IN_TOC)
450                                         continue;
451
452                                 DocumentClass const & tc = buf.params().documentClass();
453                                 DocumentClass::const_iterator lit = tc.begin();
454                                 DocumentClass::const_iterator len = tc.end();
455                                 int const newtoclevel =
456                                         (mode == OutlineIn ? toclevel + 1 : toclevel - 1);
457                                 LabelType const oldlabeltype = start->layout().labeltype;
458
459                                 for (; lit != len; ++lit) {
460                                         if (lit->toclevel ==  newtoclevel &&
461                                              lit->labeltype == oldlabeltype) {
462                                                 start->setLayout(*lit);
463                                                 break;
464                                         }
465                                 }
466                         }
467                         break;
468                 }
469         }
470 }
471
472
473 void Text::number(Cursor & cur)
474 {
475         FontInfo font = ignore_font;
476         font.setNumber(FONT_TOGGLE);
477         toggleAndShow(cur, this, Font(font, ignore_language));
478 }
479
480
481 bool Text::isRTL(Paragraph const & par) const
482 {
483         Buffer const & buffer = owner_->buffer();
484         return par.isRTL(buffer.params());
485 }
486
487
488 namespace {
489
490         Language const * getLanguage(Cursor const & cur, string const & lang) {
491                 return lang.empty() ? cur.getFont().language() : languages.getLanguage(lang);
492         }
493
494 } // namespace
495
496
497 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
498 {
499         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
500
501         // Dispatch if the cursor is inside the text. It is not the
502         // case for context menus (bug 5797).
503         if (cur.text() != this) {
504                 cur.undispatched();
505                 return;
506         }
507
508         BufferView * bv = &cur.bv();
509         TextMetrics * tm = &bv->textMetrics(this);
510         if (!tm->contains(cur.pit())) {
511                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
512                 tm = &bv->textMetrics(this);
513         }
514
515         // FIXME: We use the update flag to indicates wether a singlePar or a
516         // full screen update is needed. We reset it here but shall we restore it
517         // at the end?
518         cur.noScreenUpdate();
519
520         LBUFERR(this == cur.text());
521
522         // NOTE: This should NOT be a reference. See commit 94a5481a.
523         CursorSlice const oldTopSlice = cur.top();
524         bool const oldBoundary = cur.boundary();
525         bool const oldSelection = cur.selection();
526         // Signals that, even if needsUpdate == false, an update of the
527         // cursor paragraph is required
528         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action(),
529                 LyXAction::SingleParUpdate);
530         // Signals that a full-screen update is required
531         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action(),
532                 LyXAction::NoUpdate) || singleParUpdate);
533         bool const last_misspelled = lyxrc.spellcheck_continuously
534                 && cur.paragraph().isMisspelled(cur.pos(), true);
535
536         FuncCode const act = cmd.action();
537         switch (act) {
538
539         case LFUN_PARAGRAPH_MOVE_DOWN: {
540                 pit_type const pit = cur.pit();
541                 cur.recordUndo(pit, pit + 1);
542                 cur.finishUndo();
543                 pars_.swap(pit, pit + 1);
544                 needsUpdate = true;
545                 cur.forceBufferUpdate();
546                 ++cur.pit();
547                 break;
548         }
549
550         case LFUN_PARAGRAPH_MOVE_UP: {
551                 pit_type const pit = cur.pit();
552                 cur.recordUndo(pit - 1, pit);
553                 cur.finishUndo();
554                 pars_.swap(pit, pit - 1);
555                 --cur.pit();
556                 needsUpdate = true;
557                 cur.forceBufferUpdate();
558                 break;
559         }
560
561         case LFUN_APPENDIX: {
562                 Paragraph & par = cur.paragraph();
563                 bool start = !par.params().startOfAppendix();
564
565 // FIXME: The code below only makes sense at top level.
566 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
567                 // ensure that we have only one start_of_appendix in this document
568                 // FIXME: this don't work for multipart document!
569                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
570                         if (pars_[tmp].params().startOfAppendix()) {
571                                 cur.recordUndo(tmp, tmp);
572                                 pars_[tmp].params().startOfAppendix(false);
573                                 break;
574                         }
575                 }
576
577                 cur.recordUndo();
578                 par.params().startOfAppendix(start);
579
580                 // we can set the refreshing parameters now
581                 cur.forceBufferUpdate();
582                 break;
583         }
584
585         case LFUN_WORD_DELETE_FORWARD:
586                 if (cur.selection())
587                         cutSelection(cur, true, false);
588                 else
589                         deleteWordForward(cur, cmd.getArg(0) == "force");
590                 finishChange(cur, false);
591                 break;
592
593         case LFUN_WORD_DELETE_BACKWARD:
594                 if (cur.selection())
595                         cutSelection(cur, true, false);
596                 else
597                         deleteWordBackward(cur, cmd.getArg(0) == "force");
598                 finishChange(cur, false);
599                 break;
600
601         case LFUN_LINE_DELETE_FORWARD:
602                 if (cur.selection())
603                         cutSelection(cur, true, false);
604                 else
605                         tm->deleteLineForward(cur);
606                 finishChange(cur, false);
607                 break;
608
609         case LFUN_BUFFER_BEGIN:
610         case LFUN_BUFFER_BEGIN_SELECT:
611                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_BEGIN_SELECT);
612                 if (cur.depth() == 1)
613                         needsUpdate |= cursorTop(cur);
614                 else
615                         cur.undispatched();
616                 cur.screenUpdateFlags(Update::FitCursor);
617                 break;
618
619         case LFUN_BUFFER_END:
620         case LFUN_BUFFER_END_SELECT:
621                 needsUpdate |= cur.selHandle(act == LFUN_BUFFER_END_SELECT);
622                 if (cur.depth() == 1)
623                         needsUpdate |= cursorBottom(cur);
624                 else
625                         cur.undispatched();
626                 cur.screenUpdateFlags(Update::FitCursor);
627                 break;
628
629         case LFUN_INSET_BEGIN:
630         case LFUN_INSET_BEGIN_SELECT:
631                 needsUpdate |= cur.selHandle(act == LFUN_INSET_BEGIN_SELECT);
632                 if (cur.depth() == 1 || !cur.top().at_begin())
633                         needsUpdate |= cursorTop(cur);
634                 else
635                         cur.undispatched();
636                 cur.screenUpdateFlags(Update::FitCursor);
637                 break;
638
639         case LFUN_INSET_END:
640         case LFUN_INSET_END_SELECT:
641                 needsUpdate |= cur.selHandle(act == LFUN_INSET_END_SELECT);
642                 if (cur.depth() == 1 || !cur.top().at_end())
643                         needsUpdate |= cursorBottom(cur);
644                 else
645                         cur.undispatched();
646                 cur.screenUpdateFlags(Update::FitCursor);
647                 break;
648
649         case LFUN_CHAR_FORWARD:
650         case LFUN_CHAR_FORWARD_SELECT: {
651                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
652                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_FORWARD_SELECT);
653                 bool const cur_moved = cursorForward(cur);
654                 needsUpdate |= cur_moved;
655
656                 if (!cur_moved && oldTopSlice == cur.top()
657                                && cur.boundary() == oldBoundary) {
658                         cur.undispatched();
659                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
660
661                         // we will probably be moving out the inset, so we should execute
662                         // the depm-mechanism, but only when the cursor has a place to
663                         // go outside this inset, i.e. in a slice above.
664                         if (cur.depth() > 1 && cur.pos() == cur.lastpos()
665                                   && cur.pit() == cur.lastpit()) {
666                                 // The cursor hasn't changed yet. To give the
667                                 // DEPM the possibility of doing something we must
668                                 // provide it with two different cursors.
669                                 Cursor dummy = cur;
670                                 dummy.pos() = dummy.pit() = 0;
671                                 if (cur.bv().checkDepm(dummy, cur))
672                                         cur.forceBufferUpdate();
673                         }
674                 }
675                 break;
676         }
677
678         case LFUN_CHAR_BACKWARD:
679         case LFUN_CHAR_BACKWARD_SELECT: {
680                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
681                 needsUpdate |= cur.selHandle(act == LFUN_CHAR_BACKWARD_SELECT);
682                 bool const cur_moved = cursorBackward(cur);
683                 needsUpdate |= cur_moved;
684
685                 if (!cur_moved && oldTopSlice == cur.top()
686                                && cur.boundary() == oldBoundary) {
687                         cur.undispatched();
688                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
689
690                         // we will probably be moving out the inset, so we should execute
691                         // the depm-mechanism, but only when the cursor has a place to
692                         // go outside this inset, i.e. in a slice above.
693                         if (cur.depth() > 1 && cur.pos() == 0 && cur.pit() == 0) {
694                                 // The cursor hasn't changed yet. To give the
695                                 // DEPM the possibility of doing something we must
696                                 // provide it with two different cursors.
697                                 Cursor dummy = cur;
698                                 dummy.pos() = cur.lastpos();
699                                 dummy.pit() = cur.lastpit();
700                                 if (cur.bv().checkDepm(dummy, cur))
701                                         cur.forceBufferUpdate();
702                         }
703                 }
704                 break;
705         }
706
707         case LFUN_CHAR_LEFT:
708         case LFUN_CHAR_LEFT_SELECT:
709                 if (lyxrc.visual_cursor) {
710                         needsUpdate |= cur.selHandle(act == LFUN_CHAR_LEFT_SELECT);
711                         bool const cur_moved = cursorVisLeft(cur);
712                         needsUpdate |= cur_moved;
713                         if (!cur_moved && oldTopSlice == cur.top()
714                                        && cur.boundary() == oldBoundary) {
715                                 cur.undispatched();
716                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
717                         }
718                 } else {
719                         if (cur.reverseDirectionNeeded()) {
720                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
721                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
722                         } else {
723                                 cmd.setAction(cmd.action() == LFUN_CHAR_LEFT_SELECT ?
724                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
725                         }
726                         dispatch(cur, cmd);
727                         return;
728                 }
729                 break;
730
731         case LFUN_CHAR_RIGHT:
732         case LFUN_CHAR_RIGHT_SELECT:
733                 if (lyxrc.visual_cursor) {
734                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_CHAR_RIGHT_SELECT);
735                         bool const cur_moved = cursorVisRight(cur);
736                         needsUpdate |= cur_moved;
737                         if (!cur_moved && oldTopSlice == cur.top()
738                                        && cur.boundary() == oldBoundary) {
739                                 cur.undispatched();
740                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
741                         }
742                 } else {
743                         if (cur.reverseDirectionNeeded()) {
744                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
745                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD);
746                         } else {
747                                 cmd.setAction(cmd.action() == LFUN_CHAR_RIGHT_SELECT ?
748                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD);
749                         }
750                         dispatch(cur, cmd);
751                         return;
752                 }
753                 break;
754
755
756         case LFUN_UP_SELECT:
757         case LFUN_DOWN_SELECT:
758         case LFUN_UP:
759         case LFUN_DOWN: {
760                 // stop/start the selection
761                 bool select = cmd.action() == LFUN_DOWN_SELECT ||
762                         cmd.action() == LFUN_UP_SELECT;
763
764                 // move cursor up/down
765                 bool up = cmd.action() == LFUN_UP_SELECT || cmd.action() == LFUN_UP;
766                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
767
768                 if (!atFirstOrLastRow) {
769                         needsUpdate |= cur.selHandle(select);
770                         cur.upDownInText(up, needsUpdate);
771                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
772                 } else {
773                         // if the cursor cannot be moved up or down do not remove
774                         // the selection right now, but wait for the next dispatch.
775                         if (select)
776                                 needsUpdate |= cur.selHandle(select);
777                         cur.upDownInText(up, needsUpdate);
778                         cur.undispatched();
779                 }
780
781                 break;
782         }
783
784         case LFUN_PARAGRAPH_UP:
785         case LFUN_PARAGRAPH_UP_SELECT:
786                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_UP_SELECT);
787                 needsUpdate |= cursorUpParagraph(cur);
788                 break;
789
790         case LFUN_PARAGRAPH_DOWN:
791         case LFUN_PARAGRAPH_DOWN_SELECT:
792                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_PARAGRAPH_DOWN_SELECT);
793                 needsUpdate |= cursorDownParagraph(cur);
794                 break;
795
796         case LFUN_LINE_BEGIN:
797         case LFUN_LINE_BEGIN_SELECT:
798                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_BEGIN_SELECT);
799                 needsUpdate |= tm->cursorHome(cur);
800                 break;
801
802         case LFUN_LINE_END:
803         case LFUN_LINE_END_SELECT:
804                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_LINE_END_SELECT);
805                 needsUpdate |= tm->cursorEnd(cur);
806                 break;
807
808         case LFUN_SECTION_SELECT: {
809                 Buffer const & buf = *cur.buffer();
810                 pit_type const pit = cur.pit();
811                 ParagraphList & pars = buf.text().paragraphs();
812                 ParagraphList::iterator bgn = pars.begin();
813                 // The first paragraph of the area to be selected:
814                 ParagraphList::iterator start = lyx::next(bgn, pit);
815                 // The final paragraph of area to be selected:
816                 ParagraphList::iterator finish = start;
817                 ParagraphList::iterator end = pars.end();
818
819                 int const thistoclevel = buf.text().getTocLevel(distance(bgn, start));
820                 if (thistoclevel == Layout::NOT_IN_TOC)
821                         break;
822
823                 cur.pos() = 0;
824                 Cursor const old_cur = cur;
825                 needsUpdate |= cur.selHandle(true);
826
827                 // Move out (down) from this section header
828                 if (finish != end)
829                         ++finish;
830
831                 // Seek the one (on same level) below
832                 for (; finish != end; ++finish, ++cur.pit()) {
833                         int const toclevel = buf.text().getTocLevel(distance(bgn, finish));
834                         if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
835                                 break;
836                 }
837                 cur.pos() = cur.lastpos();
838                 cur.boundary(false);
839                 cur.setCurrentFont();
840
841                 needsUpdate |= cur != old_cur;
842                 break;
843         }
844
845         case LFUN_WORD_RIGHT:
846         case LFUN_WORD_RIGHT_SELECT:
847                 if (lyxrc.visual_cursor) {
848                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_RIGHT_SELECT);
849                         bool const cur_moved = cursorVisRightOneWord(cur);
850                         needsUpdate |= cur_moved;
851                         if (!cur_moved && oldTopSlice == cur.top()
852                                        && cur.boundary() == oldBoundary) {
853                                 cur.undispatched();
854                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
855                         }
856                 } else {
857                         if (cur.reverseDirectionNeeded()) {
858                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
859                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
860                         } else {
861                                 cmd.setAction(cmd.action() == LFUN_WORD_RIGHT_SELECT ?
862                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
863                         }
864                         dispatch(cur, cmd);
865                         return;
866                 }
867                 break;
868
869         case LFUN_WORD_FORWARD:
870         case LFUN_WORD_FORWARD_SELECT: {
871                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_FORWARD_SELECT);
872                 bool const cur_moved = cursorForwardOneWord(cur);
873                 needsUpdate |= cur_moved;
874
875                 if (!cur_moved && oldTopSlice == cur.top()
876                                && cur.boundary() == oldBoundary) {
877                         cur.undispatched();
878                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
879
880                         // we will probably be moving out the inset, so we should execute
881                         // the depm-mechanism, but only when the cursor has a place to
882                         // go outside this inset, i.e. in a slice above.
883                         if (cur.depth() > 1 && cur.pos() == cur.lastpos()
884                                   && cur.pit() == cur.lastpit()) {
885                                 // The cursor hasn't changed yet. To give the
886                                 // DEPM the possibility of doing something we must
887                                 // provide it with two different cursors.
888                                 Cursor dummy = cur;
889                                 dummy.pos() = dummy.pit() = 0;
890                                 if (cur.bv().checkDepm(dummy, cur))
891                                         cur.forceBufferUpdate();
892                         }
893                 }
894                 break;
895         }
896
897         case LFUN_WORD_LEFT:
898         case LFUN_WORD_LEFT_SELECT:
899                 if (lyxrc.visual_cursor) {
900                         needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_LEFT_SELECT);
901                         bool const cur_moved = cursorVisLeftOneWord(cur);
902                         needsUpdate |= cur_moved;
903                         if (!cur_moved && oldTopSlice == cur.top()
904                                        && cur.boundary() == oldBoundary) {
905                                 cur.undispatched();
906                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
907                         }
908                 } else {
909                         if (cur.reverseDirectionNeeded()) {
910                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
911                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD);
912                         } else {
913                                 cmd.setAction(cmd.action() == LFUN_WORD_LEFT_SELECT ?
914                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD);
915                         }
916                         dispatch(cur, cmd);
917                         return;
918                 }
919                 break;
920
921         case LFUN_WORD_BACKWARD:
922         case LFUN_WORD_BACKWARD_SELECT: {
923                 needsUpdate |= cur.selHandle(cmd.action() == LFUN_WORD_BACKWARD_SELECT);
924                 bool const cur_moved = cursorBackwardOneWord(cur);
925                 needsUpdate |= cur_moved;
926
927                 if (!cur_moved && oldTopSlice == cur.top()
928                                && cur.boundary() == oldBoundary) {
929                         cur.undispatched();
930                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
931
932                         // we will probably be moving out the inset, so we should execute
933                         // the depm-mechanism, but only when the cursor has a place to
934                         // go outside this inset, i.e. in a slice above.
935                         if (cur.depth() > 1 && cur.pos() == 0
936                                   && cur.pit() == 0) {
937                                 // The cursor hasn't changed yet. To give the
938                                 // DEPM the possibility of doing something we must
939                                 // provide it with two different cursors.
940                                 Cursor dummy = cur;
941                                 dummy.pos() = cur.lastpos();
942                                 dummy.pit() = cur.lastpit();
943                                 if (cur.bv().checkDepm(dummy, cur))
944                                         cur.forceBufferUpdate();
945                         }
946                 }
947                 break;
948         }
949
950         case LFUN_WORD_SELECT: {
951                 selectWord(cur, WHOLE_WORD);
952                 finishChange(cur, true);
953                 break;
954         }
955
956         case LFUN_NEWLINE_INSERT: {
957                 InsetNewlineParams inp;
958                 docstring arg = cmd.argument();
959                 if (arg == "linebreak")
960                         inp.kind = InsetNewlineParams::LINEBREAK;
961                 else
962                         inp.kind = InsetNewlineParams::NEWLINE;
963                 cap::replaceSelection(cur);
964                 cur.recordUndo();
965                 cur.insert(new InsetNewline(inp));
966                 cur.posForward();
967                 moveCursor(cur, false);
968                 break;
969         }
970
971         case LFUN_TAB_INSERT: {
972                 bool const multi_par_selection = cur.selection() &&
973                         cur.selBegin().pit() != cur.selEnd().pit();
974                 if (multi_par_selection) {
975                         // If there is a multi-paragraph selection, a tab is inserted
976                         // at the beginning of each paragraph.
977                         cur.recordUndoSelection();
978                         pit_type const pit_end = cur.selEnd().pit();
979                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
980                                 pars_[pit].insertChar(0, '\t',
981                                                       bv->buffer().params().track_changes);
982                                 // Update the selection pos to make sure the selection does not
983                                 // change as the inserted tab will increase the logical pos.
984                                 if (cur.realAnchor().pit() == pit)
985                                         cur.realAnchor().forwardPos();
986                                 if (cur.pit() == pit)
987                                         cur.forwardPos();
988                         }
989                         cur.finishUndo();
990                 } else {
991                         // Maybe we shouldn't allow tabs within a line, because they
992                         // are not (yet) aligned as one might do expect.
993                         FuncRequest cmd(LFUN_SELF_INSERT, from_ascii("\t"));
994                         dispatch(cur, cmd);
995                 }
996                 break;
997         }
998
999         case LFUN_TAB_DELETE: {
1000                 bool const tc = bv->buffer().params().track_changes;
1001                 if (cur.selection()) {
1002                         // If there is a selection, a tab (if present) is removed from
1003                         // the beginning of each paragraph.
1004                         cur.recordUndoSelection();
1005                         pit_type const pit_end = cur.selEnd().pit();
1006                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
1007                                 Paragraph & par = paragraphs()[pit];
1008                                 if (par.empty())
1009                                         continue;
1010                                 char_type const c = par.getChar(0);
1011                                 if (c == '\t' || c == ' ') {
1012                                         // remove either 1 tab or 4 spaces.
1013                                         int const n = (c == ' ' ? 4 : 1);
1014                                         for (int i = 0; i < n
1015                                                   && !par.empty() && par.getChar(0) == c; ++i) {
1016                                                 if (cur.pit() == pit)
1017                                                         cur.posBackward();
1018                                                 if (cur.realAnchor().pit() == pit
1019                                                           && cur.realAnchor().pos() > 0 )
1020                                                         cur.realAnchor().backwardPos();
1021                                                 par.eraseChar(0, tc);
1022                                         }
1023                                 }
1024                         }
1025                         cur.finishUndo();
1026                 } else {
1027                         // If there is no selection, try to remove a tab or some spaces
1028                         // before the position of the cursor.
1029                         Paragraph & par = paragraphs()[cur.pit()];
1030                         pos_type const pos = cur.pos();
1031
1032                         if (pos == 0)
1033                                 break;
1034
1035                         char_type const c = par.getChar(pos - 1);
1036                         cur.recordUndo();
1037                         if (c == '\t') {
1038                                 cur.posBackward();
1039                                 par.eraseChar(cur.pos(), tc);
1040                         } else
1041                                 for (int n_spaces = 0;
1042                                      cur.pos() > 0
1043                                              && par.getChar(cur.pos() - 1) == ' '
1044                                              && n_spaces < 4;
1045                                      ++n_spaces) {
1046                                         cur.posBackward();
1047                                         par.eraseChar(cur.pos(), tc);
1048                                 }
1049                         cur.finishUndo();
1050                 }
1051                 break;
1052         }
1053
1054         case LFUN_CHAR_DELETE_FORWARD:
1055                 if (!cur.selection()) {
1056                         if (cur.pos() == cur.paragraph().size())
1057                                 // Par boundary, force full-screen update
1058                                 singleParUpdate = false;
1059                         else if (cmd.getArg(0) != "force" && cur.confirmDeletion()) {
1060                                 cur.resetAnchor();
1061                                 cur.selection(true);
1062                                 cur.posForward();
1063                                 cur.setSelection();
1064                                 break;
1065                         }
1066                         needsUpdate |= erase(cur);
1067                         cur.resetAnchor();
1068                 } else {
1069                         cutSelection(cur, true, false);
1070                         singleParUpdate = false;
1071                 }
1072                 moveCursor(cur, false);
1073                 break;
1074
1075         case LFUN_CHAR_DELETE_BACKWARD:
1076                 if (!cur.selection()) {
1077                         if (bv->getIntl().getTransManager().backspace()) {
1078                                 bool par_boundary = cur.pos() == 0;
1079                                 bool first_par = cur.pit() == 0;
1080                                 // Par boundary, full-screen update
1081                                 if (par_boundary)
1082                                         singleParUpdate = false;
1083                                 else if (cmd.getArg(0) != "force" && cur.confirmDeletion(true)) {
1084                                         cur.resetAnchor();
1085                                         cur.selection(true);
1086                                         cur.posBackward();
1087                                         cur.setSelection();
1088                                         break;
1089                                 }
1090                                 needsUpdate |= backspace(cur);
1091                                 cur.resetAnchor();
1092                                 if (par_boundary && !first_par && cur.pos() > 0
1093                                     && cur.paragraph().isEnvSeparator(cur.pos() - 1)) {
1094                                         needsUpdate |= backspace(cur);
1095                                         cur.resetAnchor();
1096                                 }
1097                         }
1098                 } else {
1099                         cutSelection(cur, true, false);
1100                         singleParUpdate = false;
1101                 }
1102                 break;
1103
1104         case LFUN_PARAGRAPH_BREAK: {
1105                 cap::replaceSelection(cur);
1106                 pit_type pit = cur.pit();
1107                 Paragraph const & par = pars_[pit];
1108                 bool lastpar = (pit == pit_type(pars_.size() - 1));
1109                 Paragraph const & nextpar = lastpar ? par : pars_[pit + 1];
1110                 pit_type prev = pit > 0 ? depthHook(pit, par.getDepth()) : pit;
1111                 if (prev < pit && cur.pos() == par.beginOfBody()
1112                     && !par.size() && !par.isEnvSeparator(cur.pos())
1113                     && !par.layout().isCommand()
1114                     && pars_[prev].layout() != par.layout()
1115                     && pars_[prev].layout().isEnvironment()
1116                     && !nextpar.isEnvSeparator(nextpar.beginOfBody())) {
1117                         if (par.layout().isEnvironment()
1118                             && pars_[prev].getDepth() == par.getDepth()) {
1119                                 docstring const layout = par.layout().name();
1120                                 DocumentClass const & tc = bv->buffer().params().documentClass();
1121                                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, tc.plainLayout().name()));
1122                                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1123                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1124                                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1125                         } else {
1126                                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1127                                 breakParagraph(cur);
1128                         }
1129                         Font const f(inherit_font, cur.current_font.language());
1130                         pars_[cur.pit() - 1].resetFonts(f);
1131                 } else {
1132                         if (par.isEnvSeparator(cur.pos()))
1133                                 cur.posForward();
1134                         breakParagraph(cur, cmd.argument() == "inverse");
1135                 }
1136                 cur.resetAnchor();
1137                 // If we have a list and autoinsert item insets,
1138                 // insert them now.
1139                 Layout::LaTeXArgMap args = par.layout().args();
1140                 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1141                 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1142                 for (; lait != laend; ++lait) {
1143                         Layout::latexarg arg = (*lait).second;
1144                         if (arg.autoinsert && prefixIs((*lait).first, "item:")) {
1145                                 FuncRequest cmd(LFUN_ARGUMENT_INSERT, (*lait).first);
1146                                 lyx::dispatch(cmd);
1147                         }
1148                 }
1149                 break;
1150         }
1151
1152         case LFUN_INSET_INSERT: {
1153                 cur.recordUndo();
1154
1155                 // We have to avoid triggering InstantPreview loading
1156                 // before inserting into the document. See bug #5626.
1157                 bool loaded = bv->buffer().isFullyLoaded();
1158                 bv->buffer().setFullyLoaded(false);
1159                 Inset * inset = createInset(&bv->buffer(), cmd);
1160                 bv->buffer().setFullyLoaded(loaded);
1161
1162                 if (inset) {
1163                         // FIXME (Abdel 01/02/2006):
1164                         // What follows would be a partial fix for bug 2154:
1165                         //   http://www.lyx.org/trac/ticket/2154
1166                         // This automatically put the label inset _after_ a
1167                         // numbered section. It should be possible to extend the mechanism
1168                         // to any kind of LateX environement.
1169                         // The correct way to fix that bug would be at LateX generation.
1170                         // I'll let the code here for reference as it could be used for some
1171                         // other feature like "automatic labelling".
1172                         /*
1173                         Paragraph & par = pars_[cur.pit()];
1174                         if (inset->lyxCode() == LABEL_CODE
1175                                 && !par.layout().counter.empty()) {
1176                                 // Go to the end of the paragraph
1177                                 // Warning: Because of Change-Tracking, the last
1178                                 // position is 'size()' and not 'size()-1':
1179                                 cur.pos() = par.size();
1180                                 // Insert a new paragraph
1181                                 FuncRequest fr(LFUN_PARAGRAPH_BREAK);
1182                                 dispatch(cur, fr);
1183                         }
1184                         */
1185                         if (cur.selection())
1186                                 cutSelection(cur, true, false);
1187                         cur.insert(inset);
1188                         if (inset->editable() && inset->asInsetText())
1189                                 inset->edit(cur, true);
1190                         else
1191                                 cur.posForward();
1192
1193                         // trigger InstantPreview now
1194                         if (inset->lyxCode() == EXTERNAL_CODE) {
1195                                 InsetExternal & ins =
1196                                         static_cast<InsetExternal &>(*inset);
1197                                 ins.updatePreview();
1198                         }
1199                 }
1200
1201                 break;
1202         }
1203
1204         case LFUN_INSET_DISSOLVE: {
1205                 if (dissolveInset(cur)) {
1206                         needsUpdate = true;
1207                         cur.forceBufferUpdate();
1208                 }
1209                 break;
1210         }
1211
1212         case LFUN_SET_GRAPHICS_GROUP: {
1213                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1214                 if (!ins)
1215                         break;
1216
1217                 cur.recordUndo();
1218
1219                 string id = to_utf8(cmd.argument());
1220                 string grp = graphics::getGroupParams(bv->buffer(), id);
1221                 InsetGraphicsParams tmp, inspar = ins->getParams();
1222
1223                 if (id.empty())
1224                         inspar.groupId = to_utf8(cmd.argument());
1225                 else {
1226                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1227                         tmp.filename = inspar.filename;
1228                         inspar = tmp;
1229                 }
1230
1231                 ins->setParams(inspar);
1232                 break;
1233         }
1234
1235         case LFUN_SPACE_INSERT:
1236                 if (cur.paragraph().layout().free_spacing)
1237                         insertChar(cur, ' ');
1238                 else {
1239                         doInsertInset(cur, this, cmd, false, false);
1240                         cur.posForward();
1241                 }
1242                 moveCursor(cur, false);
1243                 break;
1244
1245         case LFUN_SPECIALCHAR_INSERT: {
1246                 string const name = to_utf8(cmd.argument());
1247                 if (name == "hyphenation")
1248                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1249                 else if (name == "allowbreak")
1250                         specialChar(cur, InsetSpecialChar::ALLOWBREAK);
1251                 else if (name == "ligature-break")
1252                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1253                 else if (name == "slash")
1254                         specialChar(cur, InsetSpecialChar::SLASH);
1255                 else if (name == "nobreakdash")
1256                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1257                 else if (name == "dots")
1258                         specialChar(cur, InsetSpecialChar::LDOTS);
1259                 else if (name == "end-of-sentence")
1260                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1261                 else if (name == "menu-separator")
1262                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1263                 else if (name == "lyx")
1264                         specialChar(cur, InsetSpecialChar::PHRASE_LYX);
1265                 else if (name == "tex")
1266                         specialChar(cur, InsetSpecialChar::PHRASE_TEX);
1267                 else if (name == "latex")
1268                         specialChar(cur, InsetSpecialChar::PHRASE_LATEX);
1269                 else if (name == "latex2e")
1270                         specialChar(cur, InsetSpecialChar::PHRASE_LATEX2E);
1271                 else if (name.empty())
1272                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1273                 else
1274                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1275                 break;
1276         }
1277
1278         case LFUN_IPAMACRO_INSERT: {
1279                 string const arg = cmd.getArg(0);
1280                 if (arg == "deco") {
1281                         // Open the inset, and move the current selection
1282                         // inside it.
1283                         doInsertInset(cur, this, cmd, true, true);
1284                         cur.posForward();
1285                         // Some insets are numbered, others are shown in the outline pane so
1286                         // let's update the labels and the toc backend.
1287                         cur.forceBufferUpdate();
1288                         break;
1289                 }
1290                 if (arg == "tone-falling")
1291                         ipaChar(cur, InsetIPAChar::TONE_FALLING);
1292                 else if (arg == "tone-rising")
1293                         ipaChar(cur, InsetIPAChar::TONE_RISING);
1294                 else if (arg == "tone-high-rising")
1295                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING);
1296                 else if (arg == "tone-low-rising")
1297                         ipaChar(cur, InsetIPAChar::TONE_LOW_RISING);
1298                 else if (arg == "tone-high-rising-falling")
1299                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING_FALLING);
1300                 else if (arg.empty())
1301                         lyxerr << "LyX function 'ipamacro-insert' needs an argument." << endl;
1302                 else
1303                         lyxerr << "Wrong argument for LyX function 'ipamacro-insert'." << endl;
1304                 break;
1305         }
1306
1307         case LFUN_WORD_UPCASE:
1308                 changeCase(cur, text_uppercase, cmd.getArg(0) == "partial");
1309                 break;
1310
1311         case LFUN_WORD_LOWCASE:
1312                 changeCase(cur, text_lowercase, cmd.getArg(0) == "partial");
1313                 break;
1314
1315         case LFUN_WORD_CAPITALIZE:
1316                 changeCase(cur, text_capitalization, cmd.getArg(0) == "partial");
1317                 break;
1318
1319         case LFUN_CHARS_TRANSPOSE:
1320                 charsTranspose(cur);
1321                 break;
1322
1323         case LFUN_PASTE: {
1324                 cur.message(_("Paste"));
1325                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), break);
1326                 cap::replaceSelection(cur);
1327
1328                 // without argument?
1329                 string const arg = to_utf8(cmd.argument());
1330                 if (arg.empty()) {
1331                         bool tryGraphics = true;
1332                         if (theClipboard().isInternal())
1333                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1334                         else if (theClipboard().hasTextContents()) {
1335                                 if (pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1336                                                        true, Clipboard::AnyTextType))
1337                                         tryGraphics = false;
1338                         }
1339                         if (tryGraphics && theClipboard().hasGraphicsContents())
1340                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1341                 } else if (isStrUnsignedInt(arg)) {
1342                         // we have a numerical argument
1343                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1344                                        convert<unsigned int>(arg));
1345                 } else if (arg == "html" || arg == "latex") {
1346                         Clipboard::TextType type = (arg == "html") ?
1347                                 Clipboard::HtmlTextType : Clipboard::LaTeXTextType;
1348                         pasteClipboardText(cur, bv->buffer().errorList("Paste"), true, type);
1349                 } else {
1350                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1351                         if (arg == "pdf")
1352                                 type = Clipboard::PdfGraphicsType;
1353                         else if (arg == "png")
1354                                 type = Clipboard::PngGraphicsType;
1355                         else if (arg == "jpeg")
1356                                 type = Clipboard::JpegGraphicsType;
1357                         else if (arg == "linkback")
1358                                 type = Clipboard::LinkBackGraphicsType;
1359                         else if (arg == "emf")
1360                                 type = Clipboard::EmfGraphicsType;
1361                         else if (arg == "wmf")
1362                                 type = Clipboard::WmfGraphicsType;
1363                         else
1364                                 // we also check in getStatus()
1365                                 LYXERR0("Unrecognized graphics type: " << arg);
1366
1367                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1368                 }
1369
1370                 bv->buffer().errors("Paste");
1371                 cur.clearSelection(); // bug 393
1372                 cur.finishUndo();
1373                 break;
1374         }
1375
1376         case LFUN_CUT:
1377                 cutSelection(cur, true, true);
1378                 cur.message(_("Cut"));
1379                 break;
1380
1381         case LFUN_COPY:
1382                 copySelection(cur);
1383                 cur.message(_("Copy"));
1384                 break;
1385
1386         case LFUN_SERVER_GET_XY:
1387                 cur.message(from_utf8(
1388                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1389                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1390                 break;
1391
1392         case LFUN_SERVER_SET_XY: {
1393                 int x = 0;
1394                 int y = 0;
1395                 istringstream is(to_utf8(cmd.argument()));
1396                 is >> x >> y;
1397                 if (!is)
1398                         lyxerr << "SETXY: Could not parse coordinates in '"
1399                                << to_utf8(cmd.argument()) << endl;
1400                 else
1401                         tm->setCursorFromCoordinates(cur, x, y);
1402                 break;
1403         }
1404
1405         case LFUN_SERVER_GET_LAYOUT:
1406                 cur.message(cur.paragraph().layout().name());
1407                 break;
1408
1409         case LFUN_LAYOUT: {
1410                 docstring layout = cmd.argument();
1411                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1412
1413                 Paragraph const & para = cur.paragraph();
1414                 docstring const old_layout = para.layout().name();
1415                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1416
1417                 if (layout.empty())
1418                         layout = tclass.defaultLayoutName();
1419
1420                 if (owner_->forcePlainLayout())
1421                         // in this case only the empty layout is allowed
1422                         layout = tclass.plainLayoutName();
1423                 else if (para.usePlainLayout()) {
1424                         // in this case, default layout maps to empty layout
1425                         if (layout == tclass.defaultLayoutName())
1426                                 layout = tclass.plainLayoutName();
1427                 } else {
1428                         // otherwise, the empty layout maps to the default
1429                         if (layout == tclass.plainLayoutName())
1430                                 layout = tclass.defaultLayoutName();
1431                 }
1432
1433                 bool hasLayout = tclass.hasLayout(layout);
1434
1435                 // If the entry is obsolete, use the new one instead.
1436                 if (hasLayout) {
1437                         docstring const & obs = tclass[layout].obsoleted_by();
1438                         if (!obs.empty())
1439                                 layout = obs;
1440                 }
1441
1442                 if (!hasLayout) {
1443                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1444                                 from_utf8(N_(" not known")));
1445                         break;
1446                 }
1447
1448                 bool change_layout = (old_layout != layout);
1449
1450                 if (!change_layout && cur.selection() &&
1451                         cur.selBegin().pit() != cur.selEnd().pit())
1452                 {
1453                         pit_type spit = cur.selBegin().pit();
1454                         pit_type epit = cur.selEnd().pit() + 1;
1455                         while (spit != epit) {
1456                                 if (pars_[spit].layout().name() != old_layout) {
1457                                         change_layout = true;
1458                                         break;
1459                                 }
1460                                 ++spit;
1461                         }
1462                 }
1463
1464                 if (change_layout)
1465                         setLayout(cur, layout);
1466
1467                 Layout::LaTeXArgMap args = tclass[layout].args();
1468                 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1469                 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1470                 for (; lait != laend; ++lait) {
1471                         Layout::latexarg arg = (*lait).second;
1472                         if (arg.autoinsert) {
1473                                 FuncRequest cmd(LFUN_ARGUMENT_INSERT, (*lait).first);
1474                                 lyx::dispatch(cmd);
1475                         }
1476                 }
1477
1478                 break;
1479         }
1480
1481         case LFUN_ENVIRONMENT_SPLIT: {
1482                 bool const outer = cmd.argument() == "outer";
1483                 Paragraph const & para = cur.paragraph();
1484                 docstring layout = para.layout().name();
1485                 depth_type split_depth = cur.paragraph().params().depth();
1486                 if (outer) {
1487                         // check if we have an environment in our nesting hierarchy
1488                         pit_type pit = cur.pit();
1489                         Paragraph cpar = pars_[pit];
1490                         while (true) {
1491                                 if (pit == 0 || cpar.params().depth() == 0)
1492                                         break;
1493                                 --pit;
1494                                 cpar = pars_[pit];
1495                                 if (cpar.params().depth() < split_depth
1496                                     && cpar.layout().isEnvironment()) {
1497                                                 layout = cpar.layout().name();
1498                                                 split_depth = cpar.params().depth();
1499                                 }
1500                         }
1501                 }
1502                 if (cur.pos() > 0)
1503                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK));
1504                 if (outer) {
1505                         while (cur.paragraph().params().depth() > split_depth)
1506                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_DECREMENT));
1507                 }
1508                 DocumentClass const & tc = bv->buffer().params().documentClass();
1509                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, tc.plainLayout().name()));
1510                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1511                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1512                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1513
1514                 break;
1515         }
1516
1517         case LFUN_CLIPBOARD_PASTE:
1518                 cap::replaceSelection(cur);
1519                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1520                                cmd.argument() == "paragraph");
1521                 bv->buffer().errors("Paste");
1522                 break;
1523
1524         case LFUN_CLIPBOARD_PASTE_SIMPLE:
1525                 cap::replaceSelection(cur);
1526                 pasteSimpleText(cur, cmd.argument() == "paragraph");
1527                 break;
1528
1529         case LFUN_PRIMARY_SELECTION_PASTE:
1530                 cap::replaceSelection(cur);
1531                 pasteString(cur, theSelection().get(),
1532                             cmd.argument() == "paragraph");
1533                 break;
1534
1535         case LFUN_SELECTION_PASTE:
1536                 // Copy the selection buffer to the clipboard stack,
1537                 // because we want it to appear in the "Edit->Paste
1538                 // recent" menu.
1539                 cap::replaceSelection(cur);
1540                 cap::copySelectionToStack();
1541                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1542                 bv->buffer().errors("Paste");
1543                 break;
1544
1545         case LFUN_UNICODE_INSERT: {
1546                 if (cmd.argument().empty())
1547                         break;
1548                 docstring hexstring = cmd.argument();
1549                 if (isHex(hexstring)) {
1550                         char_type c = hexToInt(hexstring);
1551                         if (c >= 32 && c < 0x10ffff) {
1552                                 lyxerr << "Inserting c: " << c << endl;
1553                                 docstring s = docstring(1, c);
1554                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1555                         }
1556                 }
1557                 break;
1558         }
1559
1560         case LFUN_QUOTE_INSERT: {
1561                 cap::replaceSelection(cur);
1562                 cur.recordUndo();
1563
1564                 Paragraph const & par = cur.paragraph();
1565                 pos_type pos = cur.pos();
1566                 // Ignore deleted text before cursor
1567                 while (pos > 0 && par.isDeleted(pos - 1))
1568                         --pos;
1569
1570                 bool const inner = (cmd.getArg(0) == "single" || cmd.getArg(0) == "inner");
1571
1572                 // Guess quote side.
1573                 // A space triggers an opening quote. This is passed if the preceding
1574                 // char/inset is a space or at paragraph start.
1575                 char_type c = ' ';
1576                 if (pos > 0 && !par.isSpace(pos - 1)) {
1577                         if (cur.prevInset() && cur.prevInset()->lyxCode() == QUOTE_CODE) {
1578                                 // If an opening double quotation mark precedes, and this
1579                                 // is a single quote, make it opening as well
1580                                 InsetQuotes & ins =
1581                                         static_cast<InsetQuotes &>(*cur.prevInset());
1582                                 string const type = ins.getType();
1583                                 if (!suffixIs(type, "ld") || !inner)
1584                                         c = par.getChar(pos - 1);
1585                         }
1586                         else if (!cur.prevInset()
1587                             || (cur.prevInset() && cur.prevInset()->isChar()))
1588                                 // If a char precedes, pass that and let InsetQuote decide
1589                                 c = par.getChar(pos - 1);
1590                         else {
1591                                 while (pos > 0) {
1592                                         if (par.getInset(pos - 1)
1593                                             && !par.getInset(pos - 1)->isPartOfTextSequence()) {
1594                                                 // skip "invisible" insets
1595                                                 --pos;
1596                                                 continue;
1597                                         }
1598                                         c = par.getChar(pos - 1);
1599                                         break;
1600                                 }
1601                         }
1602                 }
1603                 InsetQuotesParams::QuoteLevel const quote_level = inner
1604                                 ? InsetQuotesParams::SecondaryQuotes : InsetQuotesParams::PrimaryQuotes;
1605                 cur.insert(new InsetQuotes(cur.buffer(), c, quote_level, cmd.getArg(1), cmd.getArg(2)));
1606                 cur.buffer()->updateBuffer();
1607                 cur.posForward();
1608                 break;
1609         }
1610
1611         case LFUN_DATE_INSERT: {
1612                 string const format = cmd.argument().empty()
1613                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1614                 string const time = formatted_time(current_time(), format);
1615                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1616                 break;
1617         }
1618
1619         case LFUN_MOUSE_TRIPLE:
1620                 if (cmd.button() == mouse_button::button1) {
1621                         tm->cursorHome(cur);
1622                         cur.resetAnchor();
1623                         tm->cursorEnd(cur);
1624                         cur.setSelection();
1625                         bv->cursor() = cur;
1626                 }
1627                 break;
1628
1629         case LFUN_MOUSE_DOUBLE:
1630                 if (cmd.button() == mouse_button::button1) {
1631                         selectWord(cur, WHOLE_WORD);
1632                         bv->cursor() = cur;
1633                 }
1634                 break;
1635
1636         // Single-click on work area
1637         case LFUN_MOUSE_PRESS: {
1638                 // We are not marking a selection with the keyboard in any case.
1639                 Cursor & bvcur = cur.bv().cursor();
1640                 bvcur.setMark(false);
1641                 switch (cmd.button()) {
1642                 case mouse_button::button1:
1643                         if (!bvcur.selection())
1644                                 // Set the cursor
1645                                 bvcur.resetAnchor();
1646                         if (!bv->mouseSetCursor(cur, cmd.modifier() == ShiftModifier))
1647                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1648                         if (bvcur.wordSelection())
1649                                 selectWord(bvcur, WHOLE_WORD);
1650                         break;
1651
1652                 case mouse_button::button2:
1653                         if (lyxrc.mouse_middlebutton_paste) {
1654                                 // Middle mouse pasting.
1655                                 bv->mouseSetCursor(cur);
1656                                 lyx::dispatch(
1657                                         FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1658                                                     "selection-paste ; primary-selection-paste paragraph"));
1659                         }
1660                         cur.noScreenUpdate();
1661                         break;
1662
1663                 case mouse_button::button3: {
1664                         // Don't do anything if we right-click a
1665                         // selection, a context menu will popup.
1666                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1667                             && cur < bvcur.selectionEnd()) {
1668                                 cur.noScreenUpdate();
1669                                 return;
1670                         }
1671                         if (!bv->mouseSetCursor(cur, false))
1672                                 cur.screenUpdateFlags(Update::FitCursor);
1673                         break;
1674                 }
1675
1676                 default:
1677                         break;
1678                 } // switch (cmd.button())
1679                 break;
1680         }
1681         case LFUN_MOUSE_MOTION: {
1682                 // Mouse motion with right or middle mouse do nothing for now.
1683                 if (cmd.button() != mouse_button::button1) {
1684                         cur.noScreenUpdate();
1685                         return;
1686                 }
1687                 // ignore motions deeper nested than the real anchor
1688                 Cursor & bvcur = cur.bv().cursor();
1689                 if (!bvcur.realAnchor().hasPart(cur)) {
1690                         cur.undispatched();
1691                         break;
1692                 }
1693                 CursorSlice old = bvcur.top();
1694
1695                 int const wh = bv->workHeight();
1696                 int const y = max(0, min(wh - 1, cmd.y()));
1697
1698                 tm->setCursorFromCoordinates(cur, cmd.x(), y);
1699                 cur.setTargetX(cmd.x());
1700                 // Don't allow selecting a separator inset
1701                 if (cur.pos() && cur.paragraph().isEnvSeparator(cur.pos() - 1))
1702                         cur.posBackward();
1703                 if (cmd.y() >= wh)
1704                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1705                 else if (cmd.y() < 0)
1706                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1707                 // This is to allow jumping over large insets
1708                 if (cur.top() == old) {
1709                         if (cmd.y() >= wh)
1710                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1711                         else if (cmd.y() < 0)
1712                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1713                 }
1714                 // We continue with our existing selection or start a new one, so don't
1715                 // reset the anchor.
1716                 bvcur.setCursor(cur);
1717                 bvcur.selection(true);
1718                 bvcur.setCurrentFont();
1719                 if (cur.top() == old) {
1720                         // We didn't move one iota, so no need to update the screen.
1721                         cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1722                         //cur.noScreenUpdate();
1723                         return;
1724                 }
1725                 break;
1726         }
1727
1728         case LFUN_MOUSE_RELEASE:
1729                 switch (cmd.button()) {
1730                 case mouse_button::button1:
1731                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1732                         // If there is a new selection, update persistent selection;
1733                         // otherwise, single click does not clear persistent selection
1734                         // buffer.
1735                         if (cur.selection()) {
1736                                 // Finish selection. If double click,
1737                                 // cur is moved to the end of word by
1738                                 // selectWord but bvcur is current
1739                                 // mouse position.
1740                                 cur.bv().cursor().setSelection();
1741                                 // We might have removed an empty but drawn selection
1742                                 // (probably a margin)
1743                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1744                         } else
1745                                 cur.noScreenUpdate();
1746                         // FIXME: We could try to handle drag and drop of selection here.
1747                         return;
1748
1749                 case mouse_button::button2:
1750                         // Middle mouse pasting is handled at mouse press time,
1751                         // see LFUN_MOUSE_PRESS.
1752                         cur.noScreenUpdate();
1753                         return;
1754
1755                 case mouse_button::button3:
1756                         // Cursor was set at LFUN_MOUSE_PRESS time.
1757                         // FIXME: If there is a selection we could try to handle a special
1758                         // drag & drop context menu.
1759                         cur.noScreenUpdate();
1760                         return;
1761
1762                 case mouse_button::none:
1763                 case mouse_button::button4:
1764                 case mouse_button::button5:
1765                         break;
1766                 } // switch (cmd.button())
1767
1768                 break;
1769
1770         case LFUN_SELF_INSERT: {
1771                 if (cmd.argument().empty())
1772                         break;
1773
1774                 // Automatically delete the currently selected
1775                 // text and replace it with what is being
1776                 // typed in now. Depends on lyxrc settings
1777                 // "auto_region_delete", which defaults to
1778                 // true (on).
1779
1780                 if (lyxrc.auto_region_delete && cur.selection())
1781                         cutSelection(cur, false, false);
1782
1783                 cur.clearSelection();
1784
1785                 docstring::const_iterator cit = cmd.argument().begin();
1786                 docstring::const_iterator const end = cmd.argument().end();
1787                 for (; cit != end; ++cit)
1788                         bv->translateAndInsert(*cit, this, cur);
1789
1790                 cur.resetAnchor();
1791                 moveCursor(cur, false);
1792                 cur.markNewWordPosition();
1793                 bv->bookmarkEditPosition();
1794                 break;
1795         }
1796
1797         case LFUN_HREF_INSERT: {
1798                 docstring content = cmd.argument();
1799                 if (content.empty() && cur.selection())
1800                         content = cur.selectionAsString(false);
1801
1802                 InsetCommandParams p(HYPERLINK_CODE);
1803                 if (!content.empty()){
1804                         // if it looks like a link, we'll put it as target,
1805                         // otherwise as name (bug #8792).
1806
1807                         // We can't do:
1808                         //   regex_match(to_utf8(content), matches, link_re)
1809                         // because smatch stores pointers to the substrings rather
1810                         // than making copies of them. And those pointers become
1811                         // invalid after regex_match returns, since it is then
1812                         // being given a temporary object. (Thanks to Georg for
1813                         // figuring that out.)
1814                         regex const link_re("^([a-z]+):.*");
1815                         smatch matches;
1816                         string const c = to_utf8(lowercase(content));
1817
1818                         if (c.substr(0,7) == "mailto:") {
1819                                 p["target"] = content;
1820                                 p["type"] = from_ascii("mailto:");
1821                         } else if (regex_match(c, matches, link_re)) {
1822                                 p["target"] = content;
1823                                 string protocol = matches.str(1);
1824                                 if (protocol == "file")
1825                                         p["type"] = from_ascii("file:");
1826                         } else
1827                                 p["name"] = content;
1828                 }
1829                 string const data = InsetCommand::params2string(p);
1830
1831                 // we need to have a target. if we already have one, then
1832                 // that gets used at the default for the name, too, which
1833                 // is probably what is wanted.
1834                 if (p["target"].empty()) {
1835                         bv->showDialog("href", data);
1836                 } else {
1837                         FuncRequest fr(LFUN_INSET_INSERT, data);
1838                         dispatch(cur, fr);
1839                 }
1840                 break;
1841         }
1842
1843         case LFUN_LABEL_INSERT: {
1844                 InsetCommandParams p(LABEL_CODE);
1845                 // Try to generate a valid label
1846                 p["name"] = (cmd.argument().empty()) ?
1847                         cur.getPossibleLabel() :
1848                         cmd.argument();
1849                 string const data = InsetCommand::params2string(p);
1850
1851                 if (cmd.argument().empty()) {
1852                         bv->showDialog("label", data);
1853                 } else {
1854                         FuncRequest fr(LFUN_INSET_INSERT, data);
1855                         dispatch(cur, fr);
1856                 }
1857                 break;
1858         }
1859
1860         case LFUN_INFO_INSERT: {
1861                 Inset * inset;
1862                 if (cmd.argument().empty() && cur.selection()) {
1863                         // if command argument is empty use current selection as parameter.
1864                         docstring ds = cur.selectionAsString(false);
1865                         cutSelection(cur, true, false);
1866                         FuncRequest cmd0(cmd, ds);
1867                         inset = createInset(cur.buffer(), cmd0);
1868                 } else {
1869                         inset = createInset(cur.buffer(), cmd);
1870                 }
1871                 if (!inset)
1872                         break;
1873                 cur.recordUndo();
1874                 insertInset(cur, inset);
1875                 cur.posForward();
1876                 break;
1877         }
1878         case LFUN_CAPTION_INSERT:
1879         case LFUN_FOOTNOTE_INSERT:
1880         case LFUN_NOTE_INSERT:
1881         case LFUN_BOX_INSERT:
1882         case LFUN_BRANCH_INSERT:
1883         case LFUN_PHANTOM_INSERT:
1884         case LFUN_ERT_INSERT:
1885         case LFUN_LISTING_INSERT:
1886         case LFUN_MARGINALNOTE_INSERT:
1887         case LFUN_ARGUMENT_INSERT:
1888         case LFUN_INDEX_INSERT:
1889         case LFUN_PREVIEW_INSERT:
1890         case LFUN_SCRIPT_INSERT:
1891         case LFUN_IPA_INSERT:
1892                 // Open the inset, and move the current selection
1893                 // inside it.
1894                 doInsertInset(cur, this, cmd, true, true);
1895                 cur.posForward();
1896                 // Some insets are numbered, others are shown in the outline pane so
1897                 // let's update the labels and the toc backend.
1898                 cur.forceBufferUpdate();
1899                 break;
1900
1901         case LFUN_FLEX_INSERT: {
1902                 // Open the inset, and move the current selection
1903                 // inside it.
1904                 bool const sel = cur.selection();
1905                 doInsertInset(cur, this, cmd, true, true);
1906                 // Insert auto-insert arguments
1907                 bool autoargs = false;
1908                 Layout::LaTeXArgMap args = cur.inset().getLayout().latexargs();
1909                 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1910                 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1911                 for (; lait != laend; ++lait) {
1912                         Layout::latexarg arg = (*lait).second;
1913                         if (arg.autoinsert) {
1914                                 // The cursor might have been invalidated by the replaceSelection.
1915                                 cur.buffer()->changed(true);
1916                                 FuncRequest cmd(LFUN_ARGUMENT_INSERT, (*lait).first);
1917                                 lyx::dispatch(cmd);
1918                                 autoargs = true;
1919                         }
1920                 }
1921                 if (!autoargs) {
1922                         if (sel)
1923                                 cur.leaveInset(cur.inset());
1924                         cur.posForward();
1925                 }
1926                 // Some insets are numbered, others are shown in the outline pane so
1927                 // let's update the labels and the toc backend.
1928                 cur.forceBufferUpdate();
1929                 break;
1930         }
1931
1932         case LFUN_TABULAR_INSERT:
1933                 // if there were no arguments, just open the dialog
1934                 if (doInsertInset(cur, this, cmd, false, true))
1935                         cur.posForward();
1936                 else
1937                         bv->showDialog("tabularcreate");
1938
1939                 break;
1940
1941         case LFUN_FLOAT_INSERT:
1942         case LFUN_FLOAT_WIDE_INSERT:
1943         case LFUN_WRAP_INSERT: {
1944                 // will some content be moved into the inset?
1945                 bool const content = cur.selection();
1946                 // does the content consist of multiple paragraphs?
1947                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
1948
1949                 doInsertInset(cur, this, cmd, true, true);
1950                 cur.posForward();
1951
1952                 // If some single-par content is moved into the inset,
1953                 // doInsertInset puts the cursor outside the inset.
1954                 // To insert the caption we put it back into the inset.
1955                 // FIXME cleanup doInsertInset to avoid such dances!
1956                 if (content && singlepar)
1957                         cur.backwardPos();
1958
1959                 ParagraphList & pars = cur.text()->paragraphs();
1960
1961                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1962
1963                 // add a separate paragraph for the caption inset
1964                 pars.push_back(Paragraph());
1965                 pars.back().setInsetOwner(&cur.text()->inset());
1966                 pars.back().setPlainOrDefaultLayout(tclass);
1967                 int cap_pit = pars.size() - 1;
1968
1969                 // if an empty inset was created, we create an additional empty
1970                 // paragraph at the bottom so that the user can choose where to put
1971                 // the graphics (or table).
1972                 if (!content) {
1973                         pars.push_back(Paragraph());
1974                         pars.back().setInsetOwner(&cur.text()->inset());
1975                         pars.back().setPlainOrDefaultLayout(tclass);
1976                 }
1977
1978                 // reposition the cursor to the caption
1979                 cur.pit() = cap_pit;
1980                 cur.pos() = 0;
1981                 // FIXME: This Text/Cursor dispatch handling is a mess!
1982                 // We cannot use Cursor::dispatch here it needs access to up to
1983                 // date metrics.
1984                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1985                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
1986                 cur.forceBufferUpdate();
1987                 cur.screenUpdateFlags(Update::Force);
1988                 // FIXME: When leaving the Float (or Wrap) inset we should
1989                 // delete any empty paragraph left above or below the
1990                 // caption.
1991                 break;
1992         }
1993
1994         case LFUN_NOMENCL_INSERT: {
1995                 InsetCommandParams p(NOMENCL_CODE);
1996                 if (cmd.argument().empty())
1997                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1998                 else
1999                         p["symbol"] = cmd.argument();
2000                 string const data = InsetCommand::params2string(p);
2001                 bv->showDialog("nomenclature", data);
2002                 break;
2003         }
2004
2005         case LFUN_INDEX_PRINT: {
2006                 InsetCommandParams p(INDEX_PRINT_CODE);
2007                 if (cmd.argument().empty())
2008                         p["type"] = from_ascii("idx");
2009                 else
2010                         p["type"] = cmd.argument();
2011                 string const data = InsetCommand::params2string(p);
2012                 FuncRequest fr(LFUN_INSET_INSERT, data);
2013                 dispatch(cur, fr);
2014                 break;
2015         }
2016
2017         case LFUN_NOMENCL_PRINT:
2018         case LFUN_NEWPAGE_INSERT:
2019                 // do nothing fancy
2020                 doInsertInset(cur, this, cmd, false, false);
2021                 cur.posForward();
2022                 break;
2023
2024         case LFUN_SEPARATOR_INSERT: {
2025                 doInsertInset(cur, this, cmd, false, false);
2026                 cur.posForward();
2027                 // remove a following space
2028                 Paragraph & par = cur.paragraph();
2029                 if (cur.pos() != cur.lastpos() && par.isLineSeparator(cur.pos()))
2030                     par.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
2031                 break;
2032         }
2033
2034         case LFUN_DEPTH_DECREMENT:
2035                 changeDepth(cur, DEC_DEPTH);
2036                 break;
2037
2038         case LFUN_DEPTH_INCREMENT:
2039                 changeDepth(cur, INC_DEPTH);
2040                 break;
2041
2042         case LFUN_REGEXP_MODE:
2043                 regexpDispatch(cur, cmd);
2044                 break;
2045
2046         case LFUN_MATH_MODE: {
2047                 if (cmd.argument() == "on" || cmd.argument() == "") {
2048                         // don't pass "on" as argument
2049                         // (it would appear literally in the first cell)
2050                         docstring sel = cur.selectionAsString(false);
2051                         InsetMathMacroTemplate * macro = new InsetMathMacroTemplate(cur.buffer());
2052                         // create a macro template if we see "\\newcommand" somewhere, and
2053                         // an ordinary formula otherwise
2054                         if (!sel.empty()
2055                                 && (sel.find(from_ascii("\\newcommand")) != string::npos
2056                                         || sel.find(from_ascii("\\newlyxcommand")) != string::npos
2057                                         || sel.find(from_ascii("\\def")) != string::npos)
2058                                 && macro->fromString(sel)) {
2059                                 cur.recordUndo();
2060                                 replaceSelection(cur);
2061                                 cur.insert(macro);
2062                         } else {
2063                                 // no meaningful macro template was found
2064                                 delete macro;
2065                                 mathDispatch(cur,FuncRequest(LFUN_MATH_MODE));
2066                         }
2067                 } else
2068                         // The argument is meaningful
2069                         // We replace cmd with LFUN_MATH_INSERT because LFUN_MATH_MODE
2070                         // has a different meaning in math mode
2071                         mathDispatch(cur, FuncRequest(LFUN_MATH_INSERT,cmd.argument()));
2072                 break;
2073         }
2074
2075         case LFUN_MATH_MACRO:
2076                 if (cmd.argument().empty())
2077                         cur.errorMessage(from_utf8(N_("Missing argument")));
2078                 else {
2079                         cur.recordUndo();
2080                         string s = to_utf8(cmd.argument());
2081                         string const s1 = token(s, ' ', 1);
2082                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
2083                         string const s2 = token(s, ' ', 2);
2084                         MacroType type = MacroTypeNewcommand;
2085                         if (s2 == "def")
2086                                 type = MacroTypeDef;
2087                         InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(cur.buffer(),
2088                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
2089                         inset->setBuffer(bv->buffer());
2090                         insertInset(cur, inset);
2091
2092                         // enter macro inset and select the name
2093                         cur.push(*inset);
2094                         cur.top().pos() = cur.top().lastpos();
2095                         cur.resetAnchor();
2096                         cur.selection(true);
2097                         cur.top().pos() = 0;
2098                 }
2099                 break;
2100
2101         case LFUN_MATH_DISPLAY:
2102         case LFUN_MATH_SUBSCRIPT:
2103         case LFUN_MATH_SUPERSCRIPT:
2104         case LFUN_MATH_INSERT:
2105         case LFUN_MATH_AMS_MATRIX:
2106         case LFUN_MATH_MATRIX:
2107         case LFUN_MATH_DELIM:
2108         case LFUN_MATH_BIGDELIM:
2109                 mathDispatch(cur, cmd);
2110                 break;
2111
2112         case LFUN_FONT_EMPH: {
2113                 Font font(ignore_font, ignore_language);
2114                 font.fontInfo().setEmph(FONT_TOGGLE);
2115                 toggleAndShow(cur, this, font);
2116                 break;
2117         }
2118
2119         case LFUN_FONT_ITAL: {
2120                 Font font(ignore_font, ignore_language);
2121                 font.fontInfo().setShape(ITALIC_SHAPE);
2122                 toggleAndShow(cur, this, font);
2123                 break;
2124         }
2125
2126         case LFUN_FONT_BOLD:
2127         case LFUN_FONT_BOLDSYMBOL: {
2128                 Font font(ignore_font, ignore_language);
2129                 font.fontInfo().setSeries(BOLD_SERIES);
2130                 toggleAndShow(cur, this, font);
2131                 break;
2132         }
2133
2134         case LFUN_FONT_NOUN: {
2135                 Font font(ignore_font, ignore_language);
2136                 font.fontInfo().setNoun(FONT_TOGGLE);
2137                 toggleAndShow(cur, this, font);
2138                 break;
2139         }
2140
2141         case LFUN_FONT_TYPEWRITER: {
2142                 Font font(ignore_font, ignore_language);
2143                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
2144                 toggleAndShow(cur, this, font);
2145                 break;
2146         }
2147
2148         case LFUN_FONT_SANS: {
2149                 Font font(ignore_font, ignore_language);
2150                 font.fontInfo().setFamily(SANS_FAMILY);
2151                 toggleAndShow(cur, this, font);
2152                 break;
2153         }
2154
2155         case LFUN_FONT_ROMAN: {
2156                 Font font(ignore_font, ignore_language);
2157                 font.fontInfo().setFamily(ROMAN_FAMILY);
2158                 toggleAndShow(cur, this, font);
2159                 break;
2160         }
2161
2162         case LFUN_FONT_DEFAULT: {
2163                 Font font(inherit_font, ignore_language);
2164                 toggleAndShow(cur, this, font);
2165                 break;
2166         }
2167
2168         case LFUN_FONT_STRIKEOUT: {
2169                 Font font(ignore_font, ignore_language);
2170                 font.fontInfo().setStrikeout(FONT_TOGGLE);
2171                 toggleAndShow(cur, this, font);
2172                 break;
2173         }
2174
2175         case LFUN_FONT_CROSSOUT: {
2176                 Font font(ignore_font, ignore_language);
2177                 font.fontInfo().setXout(FONT_TOGGLE);
2178                 toggleAndShow(cur, this, font);
2179                 break;
2180         }
2181
2182         case LFUN_FONT_UNDERUNDERLINE: {
2183                 Font font(ignore_font, ignore_language);
2184                 font.fontInfo().setUuline(FONT_TOGGLE);
2185                 toggleAndShow(cur, this, font);
2186                 break;
2187         }
2188
2189         case LFUN_FONT_UNDERWAVE: {
2190                 Font font(ignore_font, ignore_language);
2191                 font.fontInfo().setUwave(FONT_TOGGLE);
2192                 toggleAndShow(cur, this, font);
2193                 break;
2194         }
2195
2196         case LFUN_FONT_UNDERLINE: {
2197                 Font font(ignore_font, ignore_language);
2198                 font.fontInfo().setUnderbar(FONT_TOGGLE);
2199                 toggleAndShow(cur, this, font);
2200                 break;
2201         }
2202
2203         case LFUN_FONT_SIZE: {
2204                 Font font(ignore_font, ignore_language);
2205                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
2206                 toggleAndShow(cur, this, font);
2207                 break;
2208         }
2209
2210         case LFUN_LANGUAGE: {
2211                 string const lang_arg = cmd.getArg(0);
2212                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
2213                 Language const * lang =
2214                         reset ? reset_language
2215                               : languages.getLanguage(lang_arg);
2216                 // we allow reset_language, which is 0, but only if it
2217                 // was requested via empty or "reset" arg.
2218                 if (!lang && !reset)
2219                         break;
2220                 bool const toggle = (cmd.getArg(1) != "set");
2221                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
2222                 Font font(ignore_font, lang);
2223                 toggleAndShow(cur, this, font, toggle);
2224                 break;
2225         }
2226
2227         case LFUN_TEXTSTYLE_APPLY:
2228                 toggleAndShow(cur, this, freefont, toggleall);
2229                 cur.message(_("Character set"));
2230                 break;
2231
2232         // Set the freefont using the contents of \param data dispatched from
2233         // the frontends and apply it at the current cursor location.
2234         case LFUN_TEXTSTYLE_UPDATE: {
2235                 Font font;
2236                 bool toggle;
2237                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
2238                         freefont = font;
2239                         toggleall = toggle;
2240                         toggleAndShow(cur, this, freefont, toggleall);
2241                         cur.message(_("Character set"));
2242                 } else {
2243                         lyxerr << "Argument not ok";
2244                 }
2245                 break;
2246         }
2247
2248         case LFUN_FINISHED_LEFT:
2249                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2250                 // We're leaving an inset, going left. If the inset is LTR, we're
2251                 // leaving from the front, so we should not move (remain at --- but
2252                 // not in --- the inset). If the inset is RTL, move left, without
2253                 // entering the inset itself; i.e., move to after the inset.
2254                 if (cur.paragraph().getFontSettings(
2255                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2256                         cursorVisLeft(cur, true);
2257                 break;
2258
2259         case LFUN_FINISHED_RIGHT:
2260                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2261                 // We're leaving an inset, going right. If the inset is RTL, we're
2262                 // leaving from the front, so we should not move (remain at --- but
2263                 // not in --- the inset). If the inset is LTR, move right, without
2264                 // entering the inset itself; i.e., move to after the inset.
2265                 if (!cur.paragraph().getFontSettings(
2266                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2267                         cursorVisRight(cur, true);
2268                 break;
2269
2270         case LFUN_FINISHED_BACKWARD:
2271                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2272                 cur.setCurrentFont();
2273                 break;
2274
2275         case LFUN_FINISHED_FORWARD:
2276                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2277                 ++cur.pos();
2278                 cur.setCurrentFont();
2279                 break;
2280
2281         case LFUN_LAYOUT_PARAGRAPH: {
2282                 string data;
2283                 params2string(cur.paragraph(), data);
2284                 data = "show\n" + data;
2285                 bv->showDialog("paragraph", data);
2286                 break;
2287         }
2288
2289         case LFUN_PARAGRAPH_UPDATE: {
2290                 string data;
2291                 params2string(cur.paragraph(), data);
2292
2293                 // Will the paragraph accept changes from the dialog?
2294                 bool const accept =
2295                         cur.inset().allowParagraphCustomization(cur.idx());
2296
2297                 data = "update " + convert<string>(accept) + '\n' + data;
2298                 bv->updateDialog("paragraph", data);
2299                 break;
2300         }
2301
2302         case LFUN_ACCENT_UMLAUT:
2303         case LFUN_ACCENT_CIRCUMFLEX:
2304         case LFUN_ACCENT_GRAVE:
2305         case LFUN_ACCENT_ACUTE:
2306         case LFUN_ACCENT_TILDE:
2307         case LFUN_ACCENT_PERISPOMENI:
2308         case LFUN_ACCENT_CEDILLA:
2309         case LFUN_ACCENT_MACRON:
2310         case LFUN_ACCENT_DOT:
2311         case LFUN_ACCENT_UNDERDOT:
2312         case LFUN_ACCENT_UNDERBAR:
2313         case LFUN_ACCENT_CARON:
2314         case LFUN_ACCENT_BREVE:
2315         case LFUN_ACCENT_TIE:
2316         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2317         case LFUN_ACCENT_CIRCLE:
2318         case LFUN_ACCENT_OGONEK:
2319                 theApp()->handleKeyFunc(cmd.action());
2320                 if (!cmd.argument().empty())
2321                         // FIXME: Are all these characters encoded in one byte in utf8?
2322                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2323                 cur.screenUpdateFlags(Update::FitCursor);
2324                 break;
2325
2326         case LFUN_FLOAT_LIST_INSERT: {
2327                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2328                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2329                         cur.recordUndo();
2330                         if (cur.selection())
2331                                 cutSelection(cur, true, false);
2332                         breakParagraph(cur);
2333
2334                         if (cur.lastpos() != 0) {
2335                                 cursorBackward(cur);
2336                                 breakParagraph(cur);
2337                         }
2338
2339                         docstring const laystr = cur.inset().usePlainLayout() ?
2340                                 tclass.plainLayoutName() :
2341                                 tclass.defaultLayoutName();
2342                         setLayout(cur, laystr);
2343                         ParagraphParameters p;
2344                         // FIXME If this call were replaced with one to clearParagraphParams(),
2345                         // then we could get rid of this method altogether.
2346                         setParagraphs(cur, p);
2347                         // FIXME This should be simplified when InsetFloatList takes a
2348                         // Buffer in its constructor.
2349                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2350                         ifl->setBuffer(bv->buffer());
2351                         insertInset(cur, ifl);
2352                         cur.posForward();
2353                 } else {
2354                         lyxerr << "Non-existent float type: "
2355                                << to_utf8(cmd.argument()) << endl;
2356                 }
2357                 break;
2358         }
2359
2360         case LFUN_CHANGE_ACCEPT: {
2361                 acceptOrRejectChanges(cur, ACCEPT);
2362                 break;
2363         }
2364
2365         case LFUN_CHANGE_REJECT: {
2366                 acceptOrRejectChanges(cur, REJECT);
2367                 break;
2368         }
2369
2370         case LFUN_THESAURUS_ENTRY: {
2371                 Language const * language = cur.getFont().language();
2372                 docstring arg = cmd.argument();
2373                 if (arg.empty()) {
2374                         arg = cur.selectionAsString(false);
2375                         // FIXME
2376                         if (arg.size() > 100 || arg.empty()) {
2377                                 // Get word or selection
2378                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2379                                 arg = cur.selectionAsString(false);
2380                                 arg += " lang=" + from_ascii(language->lang());
2381                         }
2382                 } else {
2383                         string lang = cmd.getArg(1);
2384                         // This duplicates the code in GuiThesaurus::initialiseParams
2385                         if (prefixIs(lang, "lang=")) {
2386                                 language = languages.getLanguage(lang.substr(5));
2387                                 if (!language)
2388                                         language = cur.getFont().language();
2389                         }
2390                 }
2391                 string lang = language->code();
2392                 if (lyxrc.thesaurusdir_path.empty() && !thesaurus.thesaurusInstalled(from_ascii(lang))) {
2393                         LYXERR(Debug::ACTION, "Command " << cmd << ". Thesaurus not found for language " << lang);
2394                         frontend::Alert::warning(_("Path to thesaurus directory not set!"),
2395                                         _("The path to the thesaurus directory has not been specified.\n"
2396                                           "The thesaurus is not functional.\n"
2397                                           "Please refer to sec. 6.15.1 of the User's Guide for setup\n"
2398                                           "instructions."));
2399                 }
2400                 bv->showDialog("thesaurus", to_utf8(arg));
2401                 break;
2402         }
2403
2404         case LFUN_SPELLING_ADD: {
2405                 Language const * language = getLanguage(cur, cmd.getArg(1));
2406                 docstring word = from_utf8(cmd.getArg(0));
2407                 if (word.empty()) {
2408                         word = cur.selectionAsString(false);
2409                         // FIXME
2410                         if (word.size() > 100 || word.empty()) {
2411                                 // Get word or selection
2412                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2413                                 word = cur.selectionAsString(false);
2414                         }
2415                 }
2416                 WordLangTuple wl(word, language);
2417                 theSpellChecker()->insert(wl);
2418                 break;
2419         }
2420
2421         case LFUN_SPELLING_IGNORE: {
2422                 Language const * language = getLanguage(cur, cmd.getArg(1));
2423                 docstring word = from_utf8(cmd.getArg(0));
2424                 if (word.empty()) {
2425                         word = cur.selectionAsString(false);
2426                         // FIXME
2427                         if (word.size() > 100 || word.empty()) {
2428                                 // Get word or selection
2429                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2430                                 word = cur.selectionAsString(false);
2431                         }
2432                 }
2433                 WordLangTuple wl(word, language);
2434                 theSpellChecker()->accept(wl);
2435                 break;
2436         }
2437
2438         case LFUN_SPELLING_REMOVE: {
2439                 Language const * language = getLanguage(cur, cmd.getArg(1));
2440                 docstring word = from_utf8(cmd.getArg(0));
2441                 if (word.empty()) {
2442                         word = cur.selectionAsString(false);
2443                         // FIXME
2444                         if (word.size() > 100 || word.empty()) {
2445                                 // Get word or selection
2446                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2447                                 word = cur.selectionAsString(false);
2448                         }
2449                 }
2450                 WordLangTuple wl(word, language);
2451                 theSpellChecker()->remove(wl);
2452                 break;
2453         }
2454
2455         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2456                 // Given data, an encoding of the ParagraphParameters
2457                 // generated in the Paragraph dialog, this function sets
2458                 // the current paragraph, or currently selected paragraphs,
2459                 // appropriately.
2460                 // NOTE: This function overrides all existing settings.
2461                 setParagraphs(cur, cmd.argument());
2462                 cur.message(_("Paragraph layout set"));
2463                 break;
2464         }
2465
2466         case LFUN_PARAGRAPH_PARAMS: {
2467                 // Given data, an encoding of the ParagraphParameters as we'd
2468                 // find them in a LyX file, this function modifies the current paragraph,
2469                 // or currently selected paragraphs.
2470                 // NOTE: This function only modifies, and does not override, existing
2471                 // settings.
2472                 setParagraphs(cur, cmd.argument(), true);
2473                 cur.message(_("Paragraph layout set"));
2474                 break;
2475         }
2476
2477         case LFUN_ESCAPE:
2478                 if (cur.selection()) {
2479                         cur.selection(false);
2480                 } else {
2481                         cur.undispatched();
2482                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2483                         // correct, but I'm not 100% sure -- dov, 071019
2484                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2485                 }
2486                 break;
2487
2488         case LFUN_OUTLINE_UP:
2489                 outline(OutlineUp, cur);
2490                 setCursor(cur, cur.pit(), 0);
2491                 cur.forceBufferUpdate();
2492                 needsUpdate = true;
2493                 break;
2494
2495         case LFUN_OUTLINE_DOWN:
2496                 outline(OutlineDown, cur);
2497                 setCursor(cur, cur.pit(), 0);
2498                 cur.forceBufferUpdate();
2499                 needsUpdate = true;
2500                 break;
2501
2502         case LFUN_OUTLINE_IN:
2503                 outline(OutlineIn, cur);
2504                 cur.forceBufferUpdate();
2505                 needsUpdate = true;
2506                 break;
2507
2508         case LFUN_OUTLINE_OUT:
2509                 outline(OutlineOut, cur);
2510                 cur.forceBufferUpdate();
2511                 needsUpdate = true;
2512                 break;
2513
2514         case LFUN_SERVER_GET_STATISTICS:
2515                 {
2516                         DocIterator from, to;
2517                         if (cur.selection()) {
2518                                 from = cur.selectionBegin();
2519                                 to = cur.selectionEnd();
2520                         } else {
2521                                 from = doc_iterator_begin(cur.buffer());
2522                                 to = doc_iterator_end(cur.buffer());
2523                         }
2524
2525                         cur.buffer()->updateStatistics(from, to);
2526                         string const arg0 = cmd.getArg(0);
2527                         if (arg0 == "words") {
2528                                 cur.message(convert<docstring>(cur.buffer()->wordCount()));
2529                         } else if (arg0 == "chars") {
2530                                 cur.message(convert<docstring>(cur.buffer()->charCount(false)));
2531                         } else if (arg0 == "chars-space") {
2532                                 cur.message(convert<docstring>(cur.buffer()->charCount(true)));
2533                         } else {
2534                                 cur.message(convert<docstring>(cur.buffer()->wordCount()) + " "
2535                                 + convert<docstring>(cur.buffer()->charCount(false)) + " "
2536                                 + convert<docstring>(cur.buffer()->charCount(true)));
2537                         }
2538                 }
2539                 break;
2540
2541         default:
2542                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2543                 cur.undispatched();
2544                 break;
2545         }
2546
2547         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2548
2549         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2550                 // Check for misspelled text
2551                 // The redraw is useful because of the painting of
2552                 // misspelled markers depends on the cursor position.
2553                 // Trigger a redraw for cursor moves inside misspelled text.
2554                 if (!cur.inTexted()) {
2555                         // move from regular text to math
2556                         needsUpdate = last_misspelled;
2557                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2558                         // move inside regular text
2559                         needsUpdate = last_misspelled
2560                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2561                 }
2562         }
2563
2564         // FIXME: The cursor flag is reset two lines below
2565         // so we need to check here if some of the LFUN did touch that.
2566         // for now only Text::erase() and Text::backspace() do that.
2567         // The plan is to verify all the LFUNs and then to remove this
2568         // singleParUpdate boolean altogether.
2569         if (cur.result().screenUpdate() & Update::Force) {
2570                 singleParUpdate = false;
2571                 needsUpdate = true;
2572         }
2573
2574         // FIXME: the following code should go in favor of fine grained
2575         // update flag treatment.
2576         if (singleParUpdate) {
2577                 // Inserting characters does not change par height in general. So, try
2578                 // to update _only_ this paragraph. BufferView will detect if a full
2579                 // metrics update is needed anyway.
2580                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2581                 return;
2582         }
2583         if (!needsUpdate
2584             && &oldTopSlice.inset() == &cur.inset()
2585             && oldTopSlice.idx() == cur.idx()
2586             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2587             && !cur.selection())
2588                 // FIXME: it would be better if we could just do this
2589                 //
2590                 //if (cur.result().update() != Update::FitCursor)
2591                 //      cur.noScreenUpdate();
2592                 //
2593                 // But some LFUNs do not set Update::FitCursor when needed, so we
2594                 // do it for all. This is not very harmfull as FitCursor will provoke
2595                 // a full redraw only if needed but still, a proper review of all LFUN
2596                 // should be done and this needsUpdate boolean can then be removed.
2597                 cur.screenUpdateFlags(Update::FitCursor);
2598         else
2599                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2600 }
2601
2602
2603 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2604                         FuncStatus & flag) const
2605 {
2606         LBUFERR(this == cur.text());
2607
2608         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2609         bool enable = true;
2610         bool allow_in_passthru = false;
2611         InsetCode code = NO_CODE;
2612
2613         switch (cmd.action()) {
2614
2615         case LFUN_DEPTH_DECREMENT:
2616                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2617                 break;
2618
2619         case LFUN_DEPTH_INCREMENT:
2620                 enable = changeDepthAllowed(cur, INC_DEPTH);
2621                 break;
2622
2623         case LFUN_APPENDIX:
2624                 // FIXME We really should not allow this to be put, e.g.,
2625                 // in a footnote, or in ERT. But it would make sense in a
2626                 // branch, so I'm not sure what to do.
2627                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2628                 break;
2629
2630         case LFUN_DIALOG_SHOW_NEW_INSET:
2631                 if (cmd.argument() == "bibitem")
2632                         code = BIBITEM_CODE;
2633                 else if (cmd.argument() == "bibtex") {
2634                         code = BIBTEX_CODE;
2635                         // not allowed in description items
2636                         enable = !inDescriptionItem(cur);
2637                 }
2638                 else if (cmd.argument() == "box")
2639                         code = BOX_CODE;
2640                 else if (cmd.argument() == "branch")
2641                         code = BRANCH_CODE;
2642                 else if (cmd.argument() == "citation")
2643                         code = CITE_CODE;
2644                 else if (cmd.argument() == "ert")
2645                         code = ERT_CODE;
2646                 else if (cmd.argument() == "external")
2647                         code = EXTERNAL_CODE;
2648                 else if (cmd.argument() == "float")
2649                         code = FLOAT_CODE;
2650                 else if (cmd.argument() == "graphics")
2651                         code = GRAPHICS_CODE;
2652                 else if (cmd.argument() == "href")
2653                         code = HYPERLINK_CODE;
2654                 else if (cmd.argument() == "include")
2655                         code = INCLUDE_CODE;
2656                 else if (cmd.argument() == "index")
2657                         code = INDEX_CODE;
2658                 else if (cmd.argument() == "index_print")
2659                         code = INDEX_PRINT_CODE;
2660                 else if (cmd.argument() == "listings")
2661                         code = LISTINGS_CODE;
2662                 else if (cmd.argument() == "mathspace")
2663                         code = MATH_HULL_CODE;
2664                 else if (cmd.argument() == "nomenclature")
2665                         code = NOMENCL_CODE;
2666                 else if (cmd.argument() == "nomencl_print")
2667                         code = NOMENCL_PRINT_CODE;
2668                 else if (cmd.argument() == "label")
2669                         code = LABEL_CODE;
2670                 else if (cmd.argument() == "line")
2671                         code = LINE_CODE;
2672                 else if (cmd.argument() == "note")
2673                         code = NOTE_CODE;
2674                 else if (cmd.argument() == "phantom")
2675                         code = PHANTOM_CODE;
2676                 else if (cmd.argument() == "ref")
2677                         code = REF_CODE;
2678                 else if (cmd.argument() == "space")
2679                         code = SPACE_CODE;
2680                 else if (cmd.argument() == "toc")
2681                         code = TOC_CODE;
2682                 else if (cmd.argument() == "vspace")
2683                         code = VSPACE_CODE;
2684                 else if (cmd.argument() == "wrap")
2685                         code = WRAP_CODE;
2686                 break;
2687
2688         case LFUN_ERT_INSERT:
2689                 code = ERT_CODE;
2690                 break;
2691         case LFUN_LISTING_INSERT:
2692                 code = LISTINGS_CODE;
2693                 // not allowed in description items
2694                 enable = !inDescriptionItem(cur);
2695                 break;
2696         case LFUN_FOOTNOTE_INSERT:
2697                 code = FOOT_CODE;
2698                 break;
2699         case LFUN_TABULAR_INSERT:
2700                 code = TABULAR_CODE;
2701                 break;
2702         case LFUN_MARGINALNOTE_INSERT:
2703                 code = MARGIN_CODE;
2704                 break;
2705         case LFUN_FLOAT_INSERT:
2706         case LFUN_FLOAT_WIDE_INSERT:
2707                 // FIXME: If there is a selection, we should check whether there
2708                 // are floats in the selection, but this has performance issues, see
2709                 // LFUN_CHANGE_ACCEPT/REJECT.
2710                 code = FLOAT_CODE;
2711                 if (inDescriptionItem(cur))
2712                         // not allowed in description items
2713                         enable = false;
2714                 else {
2715                         InsetCode const inset_code = cur.inset().lyxCode();
2716
2717                         // algorithm floats cannot be put in another float
2718                         if (to_utf8(cmd.argument()) == "algorithm") {
2719                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2720                                 break;
2721                         }
2722
2723                         // for figures and tables: only allow in another
2724                         // float or wrap if it is of the same type and
2725                         // not a subfloat already
2726                         if(cur.inset().lyxCode() == code) {
2727                                 InsetFloat const & ins =
2728                                         static_cast<InsetFloat const &>(cur.inset());
2729                                 enable = ins.params().type == to_utf8(cmd.argument())
2730                                         && !ins.params().subfloat;
2731                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
2732                                 InsetWrap const & ins =
2733                                         static_cast<InsetWrap const &>(cur.inset());
2734                                 enable = ins.params().type == to_utf8(cmd.argument());
2735                         }
2736                 }
2737                 break;
2738         case LFUN_WRAP_INSERT:
2739                 code = WRAP_CODE;
2740                 // not allowed in description items
2741                 enable = !inDescriptionItem(cur);
2742                 break;
2743         case LFUN_FLOAT_LIST_INSERT: {
2744                 code = FLOAT_LIST_CODE;
2745                 // not allowed in description items
2746                 enable = !inDescriptionItem(cur);
2747                 if (enable) {
2748                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
2749                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
2750                         // make sure we know about such floats
2751                         if (cit == floats.end() ||
2752                                         // and that we know how to generate a list of them
2753                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
2754                                 flag.setUnknown(true);
2755                                 // probably not necessary, but...
2756                                 enable = false;
2757                         }
2758                 }
2759                 break;
2760         }
2761         case LFUN_CAPTION_INSERT: {
2762                 code = CAPTION_CODE;
2763                 string arg = cmd.getArg(0);
2764                 bool varia = arg != "Unnumbered"
2765                         && cur.inset().allowsCaptionVariation(arg);
2766                 // not allowed in description items,
2767                 // and in specific insets
2768                 enable = !inDescriptionItem(cur)
2769                         && (varia || arg.empty() || arg == "Standard");
2770                 break;
2771         }
2772         case LFUN_NOTE_INSERT:
2773                 code = NOTE_CODE;
2774                 // in commands (sections etc.) and description items,
2775                 // only Notes are allowed
2776                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2777                           (!cur.paragraph().layout().isCommand()
2778                            && !inDescriptionItem(cur)));
2779                 break;
2780         case LFUN_FLEX_INSERT: {
2781                 code = FLEX_CODE;
2782                 string s = cmd.getArg(0);
2783                 InsetLayout il =
2784                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2785                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2786                     il.lyxtype() != InsetLayout::CUSTOM &&
2787                     il.lyxtype() != InsetLayout::ELEMENT &&
2788                     il.lyxtype ()!= InsetLayout::STANDARD)
2789                         enable = false;
2790                 break;
2791                 }
2792         case LFUN_BOX_INSERT:
2793                 code = BOX_CODE;
2794                 break;
2795         case LFUN_BRANCH_INSERT:
2796                 code = BRANCH_CODE;
2797                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2798                     && cur.buffer()->params().branchlist().empty())
2799                         enable = false;
2800                 break;
2801         case LFUN_IPA_INSERT:
2802                 code = IPA_CODE;
2803                 break;
2804         case LFUN_PHANTOM_INSERT:
2805                 code = PHANTOM_CODE;
2806                 break;
2807         case LFUN_LABEL_INSERT:
2808                 code = LABEL_CODE;
2809                 break;
2810         case LFUN_INFO_INSERT:
2811                 code = INFO_CODE;
2812                 break;
2813         case LFUN_ARGUMENT_INSERT: {
2814                 code = ARG_CODE;
2815                 allow_in_passthru = true;
2816                 string const arg = cmd.getArg(0);
2817                 if (arg.empty()) {
2818                         enable = false;
2819                         break;
2820                 }
2821                 Layout const & lay = cur.paragraph().layout();
2822                 Layout::LaTeXArgMap args = lay.args();
2823                 Layout::LaTeXArgMap::const_iterator const lait =
2824                                 args.find(arg);
2825                 if (lait != args.end()) {
2826                         enable = true;
2827                         pit_type pit = cur.pit();
2828                         pit_type lastpit = cur.pit();
2829                         if (lay.isEnvironment() && !prefixIs(arg, "item:")) {
2830                                 // In a sequence of "merged" environment layouts, we only allow
2831                                 // non-item arguments once.
2832                                 lastpit = cur.lastpit();
2833                                 // get the first paragraph in sequence with this layout
2834                                 depth_type const current_depth = cur.paragraph().params().depth();
2835                                 while (true) {
2836                                         if (pit == 0)
2837                                                 break;
2838                                         Paragraph cpar = pars_[pit - 1];
2839                                         if (cpar.layout() == lay && cpar.params().depth() == current_depth)
2840                                                 --pit;
2841                                         else
2842                                                 break;
2843                                 }
2844                         }
2845                         for (; pit <= lastpit; ++pit) {
2846                                 if (pars_[pit].layout() != lay)
2847                                         break;
2848                                 for (auto const & table : pars_[pit].insetList())
2849                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
2850                                                 if (ins->name() == arg) {
2851                                                         // we have this already
2852                                                         enable = false;
2853                                                         break;
2854                                                 }
2855                         }
2856                 } else
2857                         enable = false;
2858                 break;
2859         }
2860         case LFUN_INDEX_INSERT:
2861                 code = INDEX_CODE;
2862                 break;
2863         case LFUN_INDEX_PRINT:
2864                 code = INDEX_PRINT_CODE;
2865                 // not allowed in description items
2866                 enable = !inDescriptionItem(cur);
2867                 break;
2868         case LFUN_NOMENCL_INSERT:
2869                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2870                         enable = false;
2871                         break;
2872                 }
2873                 code = NOMENCL_CODE;
2874                 break;
2875         case LFUN_NOMENCL_PRINT:
2876                 code = NOMENCL_PRINT_CODE;
2877                 // not allowed in description items
2878                 enable = !inDescriptionItem(cur);
2879                 break;
2880         case LFUN_HREF_INSERT:
2881                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2882                         enable = false;
2883                         break;
2884                 }
2885                 code = HYPERLINK_CODE;
2886                 break;
2887         case LFUN_IPAMACRO_INSERT: {
2888                 string const arg = cmd.getArg(0);
2889                 if (arg == "deco")
2890                         code = IPADECO_CODE;
2891                 else
2892                         code = IPACHAR_CODE;
2893                 break;
2894         }
2895         case LFUN_QUOTE_INSERT:
2896                 // always allow this, since we will inset a raw quote
2897                 // if an inset is not allowed.
2898                 allow_in_passthru = true;
2899                 break;
2900         case LFUN_SPECIALCHAR_INSERT:
2901                 code = SPECIALCHAR_CODE;
2902                 break;
2903         case LFUN_SPACE_INSERT:
2904                 // slight hack: we know this is allowed in math mode
2905                 if (cur.inTexted())
2906                         code = SPACE_CODE;
2907                 break;
2908         case LFUN_PREVIEW_INSERT:
2909                 code = PREVIEW_CODE;
2910                 break;
2911         case LFUN_SCRIPT_INSERT:
2912                 code = SCRIPT_CODE;
2913                 break;
2914
2915         case LFUN_MATH_INSERT:
2916         case LFUN_MATH_AMS_MATRIX:
2917         case LFUN_MATH_MATRIX:
2918         case LFUN_MATH_DELIM:
2919         case LFUN_MATH_BIGDELIM:
2920         case LFUN_MATH_DISPLAY:
2921         case LFUN_MATH_MODE:
2922         case LFUN_MATH_MACRO:
2923         case LFUN_MATH_SUBSCRIPT:
2924         case LFUN_MATH_SUPERSCRIPT:
2925                 code = MATH_HULL_CODE;
2926                 break;
2927
2928         case LFUN_REGEXP_MODE:
2929                 code = MATH_HULL_CODE;
2930                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
2931                 break;
2932
2933         case LFUN_INSET_MODIFY:
2934                 // We need to disable this, because we may get called for a
2935                 // tabular cell via
2936                 // InsetTabular::getStatus() -> InsetText::getStatus()
2937                 // and we don't handle LFUN_INSET_MODIFY.
2938                 enable = false;
2939                 break;
2940
2941         case LFUN_FONT_EMPH:
2942                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2943                 enable = !cur.paragraph().isPassThru();
2944                 break;
2945
2946         case LFUN_FONT_ITAL:
2947                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2948                 enable = !cur.paragraph().isPassThru();
2949                 break;
2950
2951         case LFUN_FONT_NOUN:
2952                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2953                 enable = !cur.paragraph().isPassThru();
2954                 break;
2955
2956         case LFUN_FONT_BOLD:
2957         case LFUN_FONT_BOLDSYMBOL:
2958                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2959                 enable = !cur.paragraph().isPassThru();
2960                 break;
2961
2962         case LFUN_FONT_SANS:
2963                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2964                 enable = !cur.paragraph().isPassThru();
2965                 break;
2966
2967         case LFUN_FONT_ROMAN:
2968                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2969                 enable = !cur.paragraph().isPassThru();
2970                 break;
2971
2972         case LFUN_FONT_TYPEWRITER:
2973                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2974                 enable = !cur.paragraph().isPassThru();
2975                 break;
2976
2977         case LFUN_CUT:
2978         case LFUN_COPY:
2979                 enable = cur.selection();
2980                 break;
2981
2982         case LFUN_PASTE: {
2983                 if (cmd.argument().empty()) {
2984                         if (theClipboard().isInternal())
2985                                 enable = cap::numberOfSelections() > 0;
2986                         else
2987                                 enable = !theClipboard().empty();
2988                         break;
2989                 }
2990
2991                 // we have an argument
2992                 string const arg = to_utf8(cmd.argument());
2993                 if (isStrUnsignedInt(arg)) {
2994                         // it's a number and therefore means the internal stack
2995                         unsigned int n = convert<unsigned int>(arg);
2996                         enable = cap::numberOfSelections() > n;
2997                         break;
2998                 }
2999
3000                 // explicit text type?
3001                 if (arg == "html") {
3002                         // Do not enable for PlainTextType, since some tidying in the
3003                         // frontend is needed for HTML, which is too unsafe for plain text.
3004                         enable = theClipboard().hasTextContents(Clipboard::HtmlTextType);
3005                         break;
3006                 } else if (arg == "latex") {
3007                         // LaTeX is usually not available on the clipboard with
3008                         // the correct MIME type, but in plain text.
3009                         enable = theClipboard().hasTextContents(Clipboard::PlainTextType) ||
3010                                  theClipboard().hasTextContents(Clipboard::LaTeXTextType);
3011                         break;
3012                 }
3013
3014                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
3015                 if (arg == "pdf")
3016                         type = Clipboard::PdfGraphicsType;
3017                 else if (arg == "png")
3018                         type = Clipboard::PngGraphicsType;
3019                 else if (arg == "jpeg")
3020                         type = Clipboard::JpegGraphicsType;
3021                 else if (arg == "linkback")
3022                         type = Clipboard::LinkBackGraphicsType;
3023                 else if (arg == "emf")
3024                         type = Clipboard::EmfGraphicsType;
3025                 else if (arg == "wmf")
3026                         type = Clipboard::WmfGraphicsType;
3027                 else {
3028                         // unknown argument
3029                         LYXERR0("Unrecognized graphics type: " << arg);
3030                         // we don't want to assert if the user just mistyped the LFUN
3031                         LATTEST(cmd.origin() != FuncRequest::INTERNAL);
3032                         enable = false;
3033                         break;
3034                 }
3035                 enable = theClipboard().hasGraphicsContents(type);
3036                 break;
3037         }
3038
3039         case LFUN_CLIPBOARD_PASTE:
3040         case LFUN_CLIPBOARD_PASTE_SIMPLE:
3041                 enable = !theClipboard().empty();
3042                 break;
3043
3044         case LFUN_PRIMARY_SELECTION_PASTE:
3045                 enable = cur.selection() || !theSelection().empty();
3046                 break;
3047
3048         case LFUN_SELECTION_PASTE:
3049                 enable = cap::selection();
3050                 break;
3051
3052         case LFUN_PARAGRAPH_MOVE_UP:
3053                 enable = cur.pit() > 0 && !cur.selection();
3054                 break;
3055
3056         case LFUN_PARAGRAPH_MOVE_DOWN:
3057                 enable = cur.pit() < cur.lastpit() && !cur.selection();
3058                 break;
3059
3060         case LFUN_CHANGE_ACCEPT:
3061         case LFUN_CHANGE_REJECT:
3062                 // In principle, these LFUNs should only be enabled if there
3063                 // is a change at the current position/in the current selection.
3064                 // However, without proper optimizations, this will inevitably
3065                 // result in unacceptable performance - just imagine a user who
3066                 // wants to select the complete content of a long document.
3067                 if (!cur.selection())
3068                         enable = cur.paragraph().isChanged(cur.pos());
3069                 else
3070                         // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
3071                         // for selections.
3072                         enable = true;
3073                 break;
3074
3075         case LFUN_OUTLINE_UP:
3076         case LFUN_OUTLINE_DOWN:
3077         case LFUN_OUTLINE_IN:
3078         case LFUN_OUTLINE_OUT:
3079                 // FIXME: LyX is not ready for outlining within inset.
3080                 enable = isMainText()
3081                         && cur.buffer()->text().getTocLevel(cur.pit()) != Layout::NOT_IN_TOC;
3082                 break;
3083
3084         case LFUN_NEWLINE_INSERT:
3085                 // LaTeX restrictions (labels or empty par)
3086                 enable = !cur.paragraph().isPassThru()
3087                         && cur.pos() > cur.paragraph().beginOfBody();
3088                 break;
3089
3090         case LFUN_SEPARATOR_INSERT:
3091                 // Always enabled for now
3092                 enable = true;
3093                 break;
3094
3095         case LFUN_TAB_INSERT:
3096         case LFUN_TAB_DELETE:
3097                 enable = cur.paragraph().isPassThru();
3098                 break;
3099
3100         case LFUN_SET_GRAPHICS_GROUP: {
3101                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
3102                 if (!ins)
3103                         enable = false;
3104                 else
3105                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
3106                 break;
3107         }
3108
3109         case LFUN_NEWPAGE_INSERT:
3110                 // not allowed in description items
3111                 code = NEWPAGE_CODE;
3112                 enable = !inDescriptionItem(cur);
3113                 break;
3114
3115         case LFUN_DATE_INSERT: {
3116                 string const format = cmd.argument().empty()
3117                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
3118                 enable = support::os::is_valid_strftime(format);
3119                 break;
3120         }
3121
3122         case LFUN_LANGUAGE:
3123                 enable = !cur.paragraph().isPassThru();
3124                 flag.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
3125                 break;
3126
3127         case LFUN_PARAGRAPH_BREAK:
3128                 enable = inset().allowMultiPar();
3129                 break;
3130
3131         case LFUN_SPELLING_ADD:
3132         case LFUN_SPELLING_IGNORE:
3133         case LFUN_SPELLING_REMOVE:
3134                 enable = theSpellChecker() != NULL;
3135                 if (enable && !cmd.getArg(1).empty()) {
3136                         // validate explicitly given language
3137                         Language const * const lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
3138                         enable &= lang != NULL;
3139                 }
3140                 break;
3141
3142         case LFUN_LAYOUT: {
3143                 DocumentClass const & tclass = cur.buffer()->params().documentClass();
3144                 docstring layout = cmd.argument();
3145                 if (layout.empty())
3146                         layout = tclass.defaultLayoutName();
3147                 enable = !owner_->forcePlainLayout() && tclass.hasLayout(layout);
3148
3149                 flag.setOnOff(layout == cur.paragraph().layout().name());
3150                 break;
3151         }
3152
3153         case LFUN_ENVIRONMENT_SPLIT: {
3154                 if (cmd.argument() == "outer") {
3155                         // check if we have an environment in our nesting hierarchy
3156                         bool res = false;
3157                         depth_type const current_depth = cur.paragraph().params().depth();
3158                         pit_type pit = cur.pit();
3159                         Paragraph cpar = pars_[pit];
3160                         while (true) {
3161                                 if (pit == 0 || cpar.params().depth() == 0)
3162                                         break;
3163                                 --pit;
3164                                 cpar = pars_[pit];
3165                                 if (cpar.params().depth() < current_depth)
3166                                         res = cpar.layout().isEnvironment();
3167                         }
3168                         enable = res;
3169                         break;
3170                 }
3171                 else if (cur.paragraph().layout().isEnvironment()) {
3172                         enable = true;
3173                         break;
3174                 }
3175                 enable = false;
3176                 break;
3177         }
3178
3179         case LFUN_LAYOUT_PARAGRAPH:
3180         case LFUN_PARAGRAPH_PARAMS:
3181         case LFUN_PARAGRAPH_PARAMS_APPLY:
3182         case LFUN_PARAGRAPH_UPDATE:
3183                 enable = owner_->allowParagraphCustomization();
3184                 break;
3185
3186         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
3187         //  Because they insert COMBINING DIACRITICAL Unicode characters,
3188         //  that cannot be handled by LaTeX but must be converted according
3189         //  to the definition in lib/unicodesymbols?
3190         case LFUN_ACCENT_ACUTE:
3191         case LFUN_ACCENT_BREVE:
3192         case LFUN_ACCENT_CARON:
3193         case LFUN_ACCENT_CEDILLA:
3194         case LFUN_ACCENT_CIRCLE:
3195         case LFUN_ACCENT_CIRCUMFLEX:
3196         case LFUN_ACCENT_DOT:
3197         case LFUN_ACCENT_GRAVE:
3198         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
3199         case LFUN_ACCENT_MACRON:
3200         case LFUN_ACCENT_OGONEK:
3201         case LFUN_ACCENT_TIE:
3202         case LFUN_ACCENT_TILDE:
3203         case LFUN_ACCENT_PERISPOMENI:
3204         case LFUN_ACCENT_UMLAUT:
3205         case LFUN_ACCENT_UNDERBAR:
3206         case LFUN_ACCENT_UNDERDOT:
3207         case LFUN_FONT_DEFAULT:
3208         case LFUN_FONT_FRAK:
3209         case LFUN_FONT_SIZE:
3210         case LFUN_FONT_STATE:
3211         case LFUN_FONT_UNDERLINE:
3212         case LFUN_FONT_STRIKEOUT:
3213         case LFUN_FONT_CROSSOUT:
3214         case LFUN_FONT_UNDERUNDERLINE:
3215         case LFUN_FONT_UNDERWAVE:
3216         case LFUN_TEXTSTYLE_APPLY:
3217         case LFUN_TEXTSTYLE_UPDATE:
3218                 enable = !cur.paragraph().isPassThru();
3219                 break;
3220
3221         case LFUN_WORD_DELETE_FORWARD:
3222         case LFUN_WORD_DELETE_BACKWARD:
3223         case LFUN_LINE_DELETE_FORWARD:
3224         case LFUN_WORD_FORWARD:
3225         case LFUN_WORD_BACKWARD:
3226         case LFUN_WORD_RIGHT:
3227         case LFUN_WORD_LEFT:
3228         case LFUN_CHAR_FORWARD:
3229         case LFUN_CHAR_FORWARD_SELECT:
3230         case LFUN_CHAR_BACKWARD:
3231         case LFUN_CHAR_BACKWARD_SELECT:
3232         case LFUN_CHAR_LEFT:
3233         case LFUN_CHAR_LEFT_SELECT:
3234         case LFUN_CHAR_RIGHT:
3235         case LFUN_CHAR_RIGHT_SELECT:
3236         case LFUN_UP:
3237         case LFUN_UP_SELECT:
3238         case LFUN_DOWN:
3239         case LFUN_DOWN_SELECT:
3240         case LFUN_PARAGRAPH_UP_SELECT:
3241         case LFUN_PARAGRAPH_DOWN_SELECT:
3242         case LFUN_LINE_BEGIN_SELECT:
3243         case LFUN_LINE_END_SELECT:
3244         case LFUN_WORD_FORWARD_SELECT:
3245         case LFUN_WORD_BACKWARD_SELECT:
3246         case LFUN_WORD_RIGHT_SELECT:
3247         case LFUN_WORD_LEFT_SELECT:
3248         case LFUN_WORD_SELECT:
3249         case LFUN_SECTION_SELECT:
3250         case LFUN_BUFFER_BEGIN:
3251         case LFUN_BUFFER_END:
3252         case LFUN_BUFFER_BEGIN_SELECT:
3253         case LFUN_BUFFER_END_SELECT:
3254         case LFUN_INSET_BEGIN:
3255         case LFUN_INSET_END:
3256         case LFUN_INSET_BEGIN_SELECT:
3257         case LFUN_INSET_END_SELECT:
3258         case LFUN_PARAGRAPH_UP:
3259         case LFUN_PARAGRAPH_DOWN:
3260         case LFUN_LINE_BEGIN:
3261         case LFUN_LINE_END:
3262         case LFUN_CHAR_DELETE_FORWARD:
3263         case LFUN_CHAR_DELETE_BACKWARD:
3264         case LFUN_WORD_UPCASE:
3265         case LFUN_WORD_LOWCASE:
3266         case LFUN_WORD_CAPITALIZE:
3267         case LFUN_CHARS_TRANSPOSE:
3268         case LFUN_SERVER_GET_XY:
3269         case LFUN_SERVER_SET_XY:
3270         case LFUN_SERVER_GET_LAYOUT:
3271         case LFUN_SELF_INSERT:
3272         case LFUN_UNICODE_INSERT:
3273         case LFUN_THESAURUS_ENTRY:
3274         case LFUN_ESCAPE:
3275         case LFUN_SERVER_GET_STATISTICS:
3276                 // these are handled in our dispatch()
3277                 enable = true;
3278                 break;
3279
3280         case LFUN_INSET_INSERT: {
3281                 string const type = cmd.getArg(0);
3282                 if (type == "toc") {
3283                         code = TOC_CODE;
3284                         // not allowed in description items
3285                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
3286                         enable = !inDescriptionItem(cur);
3287                 } else {
3288                         enable = true;
3289                 }
3290                 break;
3291         }
3292
3293         default:
3294                 return false;
3295         }
3296
3297         if (code != NO_CODE
3298             && (cur.empty()
3299                 || !cur.inset().insetAllowed(code)
3300                 || (cur.paragraph().layout().pass_thru && !allow_in_passthru)))
3301                 enable = false;
3302
3303         flag.setEnabled(enable);
3304         return true;
3305 }
3306
3307
3308 void Text::pasteString(Cursor & cur, docstring const & clip,
3309                 bool asParagraphs)
3310 {
3311         if (!clip.empty()) {
3312                 cur.recordUndo();
3313                 if (asParagraphs)
3314                         insertStringAsParagraphs(cur, clip, cur.current_font);
3315                 else
3316                         insertStringAsLines(cur, clip, cur.current_font);
3317         }
3318 }
3319
3320
3321 // FIXME: an item inset would make things much easier.
3322 bool Text::inDescriptionItem(Cursor & cur) const
3323 {
3324         Paragraph & par = cur.paragraph();
3325         pos_type const pos = cur.pos();
3326         pos_type const body_pos = par.beginOfBody();
3327
3328         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
3329             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
3330                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
3331                 return false;
3332
3333         return (pos < body_pos
3334                 || (pos == body_pos
3335                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
3336 }
3337
3338 } // namespace lyx