]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
1333570813675eea4f7ea502f4cdbbcab825b84b
[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()) && cmd.getArg(1) != "ignoresep")
1133                                 cur.posForward();
1134                         breakParagraph(cur, cmd.getArg(0) == "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                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
1411                 docstring layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
1412                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1413
1414                 Paragraph const & para = cur.paragraph();
1415                 docstring const old_layout = para.layout().name();
1416                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1417
1418                 if (layout.empty())
1419                         layout = tclass.defaultLayoutName();
1420
1421                 if (owner_->forcePlainLayout())
1422                         // in this case only the empty layout is allowed
1423                         layout = tclass.plainLayoutName();
1424                 else if (para.usePlainLayout()) {
1425                         // in this case, default layout maps to empty layout
1426                         if (layout == tclass.defaultLayoutName())
1427                                 layout = tclass.plainLayoutName();
1428                 } else {
1429                         // otherwise, the empty layout maps to the default
1430                         if (layout == tclass.plainLayoutName())
1431                                 layout = tclass.defaultLayoutName();
1432                 }
1433
1434                 bool hasLayout = tclass.hasLayout(layout);
1435
1436                 // If the entry is obsolete, use the new one instead.
1437                 if (hasLayout) {
1438                         docstring const & obs = tclass[layout].obsoleted_by();
1439                         if (!obs.empty())
1440                                 layout = obs;
1441                 }
1442
1443                 if (!hasLayout) {
1444                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1445                                 from_utf8(N_(" not known")));
1446                         break;
1447                 }
1448
1449                 bool change_layout = (old_layout != layout);
1450
1451                 if (!change_layout && cur.selection() &&
1452                         cur.selBegin().pit() != cur.selEnd().pit())
1453                 {
1454                         pit_type spit = cur.selBegin().pit();
1455                         pit_type epit = cur.selEnd().pit() + 1;
1456                         while (spit != epit) {
1457                                 if (pars_[spit].layout().name() != old_layout) {
1458                                         change_layout = true;
1459                                         break;
1460                                 }
1461                                 ++spit;
1462                         }
1463                 }
1464
1465                 if (change_layout) {
1466                         setLayout(cur, layout);
1467                         if (cur.pit() > 0 && !ignoreautonests) {
1468                                 set<docstring> const & autonests =
1469                                                 pars_[cur.pit() - 1].layout().autonests();
1470                                 set<docstring> const & autonested =
1471                                                 pars_[cur.pit()].layout().isAutonestedBy();
1472                                 if (autonests.find(layout) != autonests.end()
1473                                                 || autonested.find(old_layout) != autonested.end())
1474                                         lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1475                         }
1476                 }
1477
1478                 Layout::LaTeXArgMap args = tclass[layout].args();
1479                 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1480                 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1481                 for (; lait != laend; ++lait) {
1482                         Layout::latexarg arg = (*lait).second;
1483                         if (arg.autoinsert) {
1484                                 FuncRequest cmd(LFUN_ARGUMENT_INSERT, (*lait).first);
1485                                 lyx::dispatch(cmd);
1486                         }
1487                 }
1488
1489                 break;
1490         }
1491
1492         case LFUN_ENVIRONMENT_SPLIT: {
1493                 bool const outer = cmd.argument() == "outer";
1494                 bool const previous = cmd.argument() == "previous";
1495                 bool const before = cmd.argument() == "before";
1496                 bool const normal = cmd.argument().empty();
1497                 Paragraph const & para = cur.paragraph();
1498                 docstring layout;
1499                 if (para.layout().isEnvironment())
1500                         layout = para.layout().name();
1501                 depth_type split_depth = cur.paragraph().params().depth();
1502                 depth_type nextpar_depth = 0;
1503                 if (outer || previous) {
1504                         // check if we have an environment in our scope
1505                         pit_type pit = cur.pit();
1506                         Paragraph cpar = pars_[pit];
1507                         while (true) {
1508                                 if (pit == 0)
1509                                         break;
1510                                 --pit;
1511                                 cpar = pars_[pit];
1512                                 if (layout.empty() && previous
1513                                     && cpar.layout().isEnvironment()
1514                                     && cpar.params().depth() <= split_depth)
1515                                         layout = cpar.layout().name();
1516                                 if (cpar.params().depth() < split_depth
1517                                     && cpar.layout().isEnvironment()) {
1518                                                 if (!previous)
1519                                                         layout = cpar.layout().name();
1520                                                 split_depth = cpar.params().depth();
1521                                 }
1522                                 if (cpar.params().depth() == 0)
1523                                         break;
1524                         }
1525                 }
1526                 if ((outer || normal) && cur.pit() < cur.lastpit()) {
1527                         // save nesting of following paragraph
1528                         Paragraph cpar = pars_[cur.pit() + 1];
1529                         nextpar_depth = cpar.params().depth();
1530                 }
1531                 if (before)
1532                         cur.top().setPitPos(cur.pit(), 0);
1533                 if (before || cur.pos() > 0)
1534                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK));
1535                 else if (previous && cur.nextInset() && cur.nextInset()->lyxCode() == SEPARATOR_CODE)
1536                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse ignoresep"));
1537                 if (outer) {
1538                         while (cur.paragraph().params().depth() > split_depth)
1539                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_DECREMENT));
1540                 }
1541                 DocumentClass const & tc = bv->buffer().params().documentClass();
1542                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, from_ascii("\"") + tc.plainLayout().name()
1543                                           + from_ascii("\" ignoreautonests")));
1544                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1545                 if (before) {
1546                         cur.backwardPos();
1547                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse ignoresep"));
1548                         while (cur.paragraph().params().depth() < split_depth)
1549                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1550                 }
1551                 else
1552                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1553                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1554                 if ((outer || normal) && nextpar_depth > 0) {
1555                         // restore nesting of following paragraph
1556                         DocIterator scur = cur;
1557                         depth_type const max_depth = cur.paragraph().getMaxDepthAfter();
1558                         cur.forwardPar();
1559                         while (cur.paragraph().params().depth() <= min(nextpar_depth, max_depth))
1560                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1561                         cur.setCursor(scur);
1562                 }
1563
1564                 break;
1565         }
1566
1567         case LFUN_CLIPBOARD_PASTE:
1568                 cap::replaceSelection(cur);
1569                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1570                                cmd.argument() == "paragraph");
1571                 bv->buffer().errors("Paste");
1572                 break;
1573
1574         case LFUN_CLIPBOARD_PASTE_SIMPLE:
1575                 cap::replaceSelection(cur);
1576                 pasteSimpleText(cur, cmd.argument() == "paragraph");
1577                 break;
1578
1579         case LFUN_PRIMARY_SELECTION_PASTE:
1580                 cap::replaceSelection(cur);
1581                 pasteString(cur, theSelection().get(),
1582                             cmd.argument() == "paragraph");
1583                 break;
1584
1585         case LFUN_SELECTION_PASTE:
1586                 // Copy the selection buffer to the clipboard stack,
1587                 // because we want it to appear in the "Edit->Paste
1588                 // recent" menu.
1589                 cap::replaceSelection(cur);
1590                 cap::copySelectionToStack();
1591                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1592                 bv->buffer().errors("Paste");
1593                 break;
1594
1595         case LFUN_UNICODE_INSERT: {
1596                 if (cmd.argument().empty())
1597                         break;
1598                 docstring hexstring = cmd.argument();
1599                 if (isHex(hexstring)) {
1600                         char_type c = hexToInt(hexstring);
1601                         if (c >= 32 && c < 0x10ffff) {
1602                                 lyxerr << "Inserting c: " << c << endl;
1603                                 docstring s = docstring(1, c);
1604                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1605                         }
1606                 }
1607                 break;
1608         }
1609
1610         case LFUN_QUOTE_INSERT: {
1611                 cap::replaceSelection(cur);
1612                 cur.recordUndo();
1613
1614                 Paragraph const & par = cur.paragraph();
1615                 pos_type pos = cur.pos();
1616                 // Ignore deleted text before cursor
1617                 while (pos > 0 && par.isDeleted(pos - 1))
1618                         --pos;
1619
1620                 bool const inner = (cmd.getArg(0) == "single" || cmd.getArg(0) == "inner");
1621
1622                 // Guess quote side.
1623                 // A space triggers an opening quote. This is passed if the preceding
1624                 // char/inset is a space or at paragraph start.
1625                 char_type c = ' ';
1626                 if (pos > 0 && !par.isSpace(pos - 1)) {
1627                         if (cur.prevInset() && cur.prevInset()->lyxCode() == QUOTE_CODE) {
1628                                 // If an opening double quotation mark precedes, and this
1629                                 // is a single quote, make it opening as well
1630                                 InsetQuotes & ins =
1631                                         static_cast<InsetQuotes &>(*cur.prevInset());
1632                                 string const type = ins.getType();
1633                                 if (!suffixIs(type, "ld") || !inner)
1634                                         c = par.getChar(pos - 1);
1635                         }
1636                         else if (!cur.prevInset()
1637                             || (cur.prevInset() && cur.prevInset()->isChar()))
1638                                 // If a char precedes, pass that and let InsetQuote decide
1639                                 c = par.getChar(pos - 1);
1640                         else {
1641                                 while (pos > 0) {
1642                                         if (par.getInset(pos - 1)
1643                                             && !par.getInset(pos - 1)->isPartOfTextSequence()) {
1644                                                 // skip "invisible" insets
1645                                                 --pos;
1646                                                 continue;
1647                                         }
1648                                         c = par.getChar(pos - 1);
1649                                         break;
1650                                 }
1651                         }
1652                 }
1653                 InsetQuotesParams::QuoteLevel const quote_level = inner
1654                                 ? InsetQuotesParams::SecondaryQuotes : InsetQuotesParams::PrimaryQuotes;
1655                 cur.insert(new InsetQuotes(cur.buffer(), c, quote_level, cmd.getArg(1), cmd.getArg(2)));
1656                 cur.buffer()->updateBuffer();
1657                 cur.posForward();
1658                 break;
1659         }
1660
1661         case LFUN_DATE_INSERT: {
1662                 string const format = cmd.argument().empty()
1663                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1664                 string const time = formatted_time(current_time(), format);
1665                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1666                 break;
1667         }
1668
1669         case LFUN_MOUSE_TRIPLE:
1670                 if (cmd.button() == mouse_button::button1) {
1671                         tm->cursorHome(cur);
1672                         cur.resetAnchor();
1673                         tm->cursorEnd(cur);
1674                         cur.setSelection();
1675                         bv->cursor() = cur;
1676                 }
1677                 break;
1678
1679         case LFUN_MOUSE_DOUBLE:
1680                 if (cmd.button() == mouse_button::button1) {
1681                         selectWord(cur, WHOLE_WORD);
1682                         bv->cursor() = cur;
1683                 }
1684                 break;
1685
1686         // Single-click on work area
1687         case LFUN_MOUSE_PRESS: {
1688                 // We are not marking a selection with the keyboard in any case.
1689                 Cursor & bvcur = cur.bv().cursor();
1690                 bvcur.setMark(false);
1691                 switch (cmd.button()) {
1692                 case mouse_button::button1:
1693                         if (!bvcur.selection())
1694                                 // Set the cursor
1695                                 bvcur.resetAnchor();
1696                         if (!bv->mouseSetCursor(cur, cmd.modifier() == ShiftModifier))
1697                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1698                         if (bvcur.wordSelection())
1699                                 selectWord(bvcur, WHOLE_WORD);
1700                         break;
1701
1702                 case mouse_button::button2:
1703                         if (lyxrc.mouse_middlebutton_paste) {
1704                                 // Middle mouse pasting.
1705                                 bv->mouseSetCursor(cur);
1706                                 lyx::dispatch(
1707                                         FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1708                                                     "selection-paste ; primary-selection-paste paragraph"));
1709                         }
1710                         cur.noScreenUpdate();
1711                         break;
1712
1713                 case mouse_button::button3: {
1714                         // Don't do anything if we right-click a
1715                         // selection, a context menu will popup.
1716                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1717                             && cur < bvcur.selectionEnd()) {
1718                                 cur.noScreenUpdate();
1719                                 return;
1720                         }
1721                         if (!bv->mouseSetCursor(cur, false))
1722                                 cur.screenUpdateFlags(Update::FitCursor);
1723                         break;
1724                 }
1725
1726                 default:
1727                         break;
1728                 } // switch (cmd.button())
1729                 break;
1730         }
1731         case LFUN_MOUSE_MOTION: {
1732                 // Mouse motion with right or middle mouse do nothing for now.
1733                 if (cmd.button() != mouse_button::button1) {
1734                         cur.noScreenUpdate();
1735                         return;
1736                 }
1737                 // ignore motions deeper nested than the real anchor
1738                 Cursor & bvcur = cur.bv().cursor();
1739                 if (!bvcur.realAnchor().hasPart(cur)) {
1740                         cur.undispatched();
1741                         break;
1742                 }
1743                 CursorSlice old = bvcur.top();
1744
1745                 int const wh = bv->workHeight();
1746                 int const y = max(0, min(wh - 1, cmd.y()));
1747
1748                 tm->setCursorFromCoordinates(cur, cmd.x(), y);
1749                 cur.setTargetX(cmd.x());
1750                 // Don't allow selecting a separator inset
1751                 if (cur.pos() && cur.paragraph().isEnvSeparator(cur.pos() - 1))
1752                         cur.posBackward();
1753                 if (cmd.y() >= wh)
1754                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1755                 else if (cmd.y() < 0)
1756                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1757                 // This is to allow jumping over large insets
1758                 if (cur.top() == old) {
1759                         if (cmd.y() >= wh)
1760                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1761                         else if (cmd.y() < 0)
1762                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1763                 }
1764                 // We continue with our existing selection or start a new one, so don't
1765                 // reset the anchor.
1766                 bvcur.setCursor(cur);
1767                 bvcur.selection(true);
1768                 bvcur.setCurrentFont();
1769                 if (cur.top() == old) {
1770                         // We didn't move one iota, so no need to update the screen.
1771                         cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1772                         //cur.noScreenUpdate();
1773                         return;
1774                 }
1775                 break;
1776         }
1777
1778         case LFUN_MOUSE_RELEASE:
1779                 switch (cmd.button()) {
1780                 case mouse_button::button1:
1781                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1782                         // If there is a new selection, update persistent selection;
1783                         // otherwise, single click does not clear persistent selection
1784                         // buffer.
1785                         if (cur.selection()) {
1786                                 // Finish selection. If double click,
1787                                 // cur is moved to the end of word by
1788                                 // selectWord but bvcur is current
1789                                 // mouse position.
1790                                 cur.bv().cursor().setSelection();
1791                                 // We might have removed an empty but drawn selection
1792                                 // (probably a margin)
1793                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1794                         } else
1795                                 cur.noScreenUpdate();
1796                         // FIXME: We could try to handle drag and drop of selection here.
1797                         return;
1798
1799                 case mouse_button::button2:
1800                         // Middle mouse pasting is handled at mouse press time,
1801                         // see LFUN_MOUSE_PRESS.
1802                         cur.noScreenUpdate();
1803                         return;
1804
1805                 case mouse_button::button3:
1806                         // Cursor was set at LFUN_MOUSE_PRESS time.
1807                         // FIXME: If there is a selection we could try to handle a special
1808                         // drag & drop context menu.
1809                         cur.noScreenUpdate();
1810                         return;
1811
1812                 case mouse_button::none:
1813                 case mouse_button::button4:
1814                 case mouse_button::button5:
1815                         break;
1816                 } // switch (cmd.button())
1817
1818                 break;
1819
1820         case LFUN_SELF_INSERT: {
1821                 if (cmd.argument().empty())
1822                         break;
1823
1824                 // Automatically delete the currently selected
1825                 // text and replace it with what is being
1826                 // typed in now. Depends on lyxrc settings
1827                 // "auto_region_delete", which defaults to
1828                 // true (on).
1829
1830                 if (lyxrc.auto_region_delete && cur.selection())
1831                         cutSelection(cur, false, false);
1832
1833                 cur.clearSelection();
1834
1835                 docstring::const_iterator cit = cmd.argument().begin();
1836                 docstring::const_iterator const end = cmd.argument().end();
1837                 for (; cit != end; ++cit)
1838                         bv->translateAndInsert(*cit, this, cur);
1839
1840                 cur.resetAnchor();
1841                 moveCursor(cur, false);
1842                 cur.markNewWordPosition();
1843                 bv->bookmarkEditPosition();
1844                 break;
1845         }
1846
1847         case LFUN_HREF_INSERT: {
1848                 docstring content = cmd.argument();
1849                 if (content.empty() && cur.selection())
1850                         content = cur.selectionAsString(false);
1851
1852                 InsetCommandParams p(HYPERLINK_CODE);
1853                 if (!content.empty()){
1854                         // if it looks like a link, we'll put it as target,
1855                         // otherwise as name (bug #8792).
1856
1857                         // We can't do:
1858                         //   regex_match(to_utf8(content), matches, link_re)
1859                         // because smatch stores pointers to the substrings rather
1860                         // than making copies of them. And those pointers become
1861                         // invalid after regex_match returns, since it is then
1862                         // being given a temporary object. (Thanks to Georg for
1863                         // figuring that out.)
1864                         regex const link_re("^([a-z]+):.*");
1865                         smatch matches;
1866                         string const c = to_utf8(lowercase(content));
1867
1868                         if (c.substr(0,7) == "mailto:") {
1869                                 p["target"] = content;
1870                                 p["type"] = from_ascii("mailto:");
1871                         } else if (regex_match(c, matches, link_re)) {
1872                                 p["target"] = content;
1873                                 string protocol = matches.str(1);
1874                                 if (protocol == "file")
1875                                         p["type"] = from_ascii("file:");
1876                         } else
1877                                 p["name"] = content;
1878                 }
1879                 string const data = InsetCommand::params2string(p);
1880
1881                 // we need to have a target. if we already have one, then
1882                 // that gets used at the default for the name, too, which
1883                 // is probably what is wanted.
1884                 if (p["target"].empty()) {
1885                         bv->showDialog("href", data);
1886                 } else {
1887                         FuncRequest fr(LFUN_INSET_INSERT, data);
1888                         dispatch(cur, fr);
1889                 }
1890                 break;
1891         }
1892
1893         case LFUN_LABEL_INSERT: {
1894                 InsetCommandParams p(LABEL_CODE);
1895                 // Try to generate a valid label
1896                 p["name"] = (cmd.argument().empty()) ?
1897                         cur.getPossibleLabel() :
1898                         cmd.argument();
1899                 string const data = InsetCommand::params2string(p);
1900
1901                 if (cmd.argument().empty()) {
1902                         bv->showDialog("label", data);
1903                 } else {
1904                         FuncRequest fr(LFUN_INSET_INSERT, data);
1905                         dispatch(cur, fr);
1906                 }
1907                 break;
1908         }
1909
1910         case LFUN_INFO_INSERT: {
1911                 Inset * inset;
1912                 if (cmd.argument().empty() && cur.selection()) {
1913                         // if command argument is empty use current selection as parameter.
1914                         docstring ds = cur.selectionAsString(false);
1915                         cutSelection(cur, true, false);
1916                         FuncRequest cmd0(cmd, ds);
1917                         inset = createInset(cur.buffer(), cmd0);
1918                 } else {
1919                         inset = createInset(cur.buffer(), cmd);
1920                 }
1921                 if (!inset)
1922                         break;
1923                 cur.recordUndo();
1924                 insertInset(cur, inset);
1925                 cur.posForward();
1926                 break;
1927         }
1928         case LFUN_CAPTION_INSERT:
1929         case LFUN_FOOTNOTE_INSERT:
1930         case LFUN_NOTE_INSERT:
1931         case LFUN_BOX_INSERT:
1932         case LFUN_BRANCH_INSERT:
1933         case LFUN_PHANTOM_INSERT:
1934         case LFUN_ERT_INSERT:
1935         case LFUN_LISTING_INSERT:
1936         case LFUN_MARGINALNOTE_INSERT:
1937         case LFUN_ARGUMENT_INSERT:
1938         case LFUN_INDEX_INSERT:
1939         case LFUN_PREVIEW_INSERT:
1940         case LFUN_SCRIPT_INSERT:
1941         case LFUN_IPA_INSERT:
1942                 // Open the inset, and move the current selection
1943                 // inside it.
1944                 doInsertInset(cur, this, cmd, true, true);
1945                 cur.posForward();
1946                 // Some insets are numbered, others are shown in the outline pane so
1947                 // let's update the labels and the toc backend.
1948                 cur.forceBufferUpdate();
1949                 break;
1950
1951         case LFUN_FLEX_INSERT: {
1952                 // Open the inset, and move the current selection
1953                 // inside it.
1954                 bool const sel = cur.selection();
1955                 doInsertInset(cur, this, cmd, true, true);
1956                 // Insert auto-insert arguments
1957                 bool autoargs = false;
1958                 Layout::LaTeXArgMap args = cur.inset().getLayout().latexargs();
1959                 Layout::LaTeXArgMap::const_iterator lait = args.begin();
1960                 Layout::LaTeXArgMap::const_iterator const laend = args.end();
1961                 for (; lait != laend; ++lait) {
1962                         Layout::latexarg arg = (*lait).second;
1963                         if (arg.autoinsert) {
1964                                 // The cursor might have been invalidated by the replaceSelection.
1965                                 cur.buffer()->changed(true);
1966                                 FuncRequest cmd(LFUN_ARGUMENT_INSERT, (*lait).first);
1967                                 lyx::dispatch(cmd);
1968                                 autoargs = true;
1969                         }
1970                 }
1971                 if (!autoargs) {
1972                         if (sel)
1973                                 cur.leaveInset(cur.inset());
1974                         cur.posForward();
1975                 }
1976                 // Some insets are numbered, others are shown in the outline pane so
1977                 // let's update the labels and the toc backend.
1978                 cur.forceBufferUpdate();
1979                 break;
1980         }
1981
1982         case LFUN_TABULAR_INSERT:
1983                 // if there were no arguments, just open the dialog
1984                 if (doInsertInset(cur, this, cmd, false, true))
1985                         cur.posForward();
1986                 else
1987                         bv->showDialog("tabularcreate");
1988
1989                 break;
1990
1991         case LFUN_FLOAT_INSERT:
1992         case LFUN_FLOAT_WIDE_INSERT:
1993         case LFUN_WRAP_INSERT: {
1994                 // will some content be moved into the inset?
1995                 bool const content = cur.selection();
1996                 // does the content consist of multiple paragraphs?
1997                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
1998
1999                 doInsertInset(cur, this, cmd, true, true);
2000                 cur.posForward();
2001
2002                 // If some single-par content is moved into the inset,
2003                 // doInsertInset puts the cursor outside the inset.
2004                 // To insert the caption we put it back into the inset.
2005                 // FIXME cleanup doInsertInset to avoid such dances!
2006                 if (content && singlepar)
2007                         cur.backwardPos();
2008
2009                 ParagraphList & pars = cur.text()->paragraphs();
2010
2011                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2012
2013                 // add a separate paragraph for the caption inset
2014                 pars.push_back(Paragraph());
2015                 pars.back().setInsetOwner(&cur.text()->inset());
2016                 pars.back().setPlainOrDefaultLayout(tclass);
2017                 int cap_pit = pars.size() - 1;
2018
2019                 // if an empty inset was created, we create an additional empty
2020                 // paragraph at the bottom so that the user can choose where to put
2021                 // the graphics (or table).
2022                 if (!content) {
2023                         pars.push_back(Paragraph());
2024                         pars.back().setInsetOwner(&cur.text()->inset());
2025                         pars.back().setPlainOrDefaultLayout(tclass);
2026                 }
2027
2028                 // reposition the cursor to the caption
2029                 cur.pit() = cap_pit;
2030                 cur.pos() = 0;
2031                 // FIXME: This Text/Cursor dispatch handling is a mess!
2032                 // We cannot use Cursor::dispatch here it needs access to up to
2033                 // date metrics.
2034                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
2035                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
2036                 cur.forceBufferUpdate();
2037                 cur.screenUpdateFlags(Update::Force);
2038                 // FIXME: When leaving the Float (or Wrap) inset we should
2039                 // delete any empty paragraph left above or below the
2040                 // caption.
2041                 break;
2042         }
2043
2044         case LFUN_NOMENCL_INSERT: {
2045                 InsetCommandParams p(NOMENCL_CODE);
2046                 if (cmd.argument().empty())
2047                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
2048                 else
2049                         p["symbol"] = cmd.argument();
2050                 string const data = InsetCommand::params2string(p);
2051                 bv->showDialog("nomenclature", data);
2052                 break;
2053         }
2054
2055         case LFUN_INDEX_PRINT: {
2056                 InsetCommandParams p(INDEX_PRINT_CODE);
2057                 if (cmd.argument().empty())
2058                         p["type"] = from_ascii("idx");
2059                 else
2060                         p["type"] = cmd.argument();
2061                 string const data = InsetCommand::params2string(p);
2062                 FuncRequest fr(LFUN_INSET_INSERT, data);
2063                 dispatch(cur, fr);
2064                 break;
2065         }
2066
2067         case LFUN_NOMENCL_PRINT:
2068         case LFUN_NEWPAGE_INSERT:
2069                 // do nothing fancy
2070                 doInsertInset(cur, this, cmd, false, false);
2071                 cur.posForward();
2072                 break;
2073
2074         case LFUN_SEPARATOR_INSERT: {
2075                 doInsertInset(cur, this, cmd, false, false);
2076                 cur.posForward();
2077                 // remove a following space
2078                 Paragraph & par = cur.paragraph();
2079                 if (cur.pos() != cur.lastpos() && par.isLineSeparator(cur.pos()))
2080                     par.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
2081                 break;
2082         }
2083
2084         case LFUN_DEPTH_DECREMENT:
2085                 changeDepth(cur, DEC_DEPTH);
2086                 break;
2087
2088         case LFUN_DEPTH_INCREMENT:
2089                 changeDepth(cur, INC_DEPTH);
2090                 break;
2091
2092         case LFUN_REGEXP_MODE:
2093                 regexpDispatch(cur, cmd);
2094                 break;
2095
2096         case LFUN_MATH_MODE: {
2097                 if (cmd.argument() == "on" || cmd.argument() == "") {
2098                         // don't pass "on" as argument
2099                         // (it would appear literally in the first cell)
2100                         docstring sel = cur.selectionAsString(false);
2101                         InsetMathMacroTemplate * macro = new InsetMathMacroTemplate(cur.buffer());
2102                         // create a macro template if we see "\\newcommand" somewhere, and
2103                         // an ordinary formula otherwise
2104                         if (!sel.empty()
2105                                 && (sel.find(from_ascii("\\newcommand")) != string::npos
2106                                         || sel.find(from_ascii("\\newlyxcommand")) != string::npos
2107                                         || sel.find(from_ascii("\\def")) != string::npos)
2108                                 && macro->fromString(sel)) {
2109                                 cur.recordUndo();
2110                                 replaceSelection(cur);
2111                                 cur.insert(macro);
2112                         } else {
2113                                 // no meaningful macro template was found
2114                                 delete macro;
2115                                 mathDispatch(cur,FuncRequest(LFUN_MATH_MODE));
2116                         }
2117                 } else
2118                         // The argument is meaningful
2119                         // We replace cmd with LFUN_MATH_INSERT because LFUN_MATH_MODE
2120                         // has a different meaning in math mode
2121                         mathDispatch(cur, FuncRequest(LFUN_MATH_INSERT,cmd.argument()));
2122                 break;
2123         }
2124
2125         case LFUN_MATH_MACRO:
2126                 if (cmd.argument().empty())
2127                         cur.errorMessage(from_utf8(N_("Missing argument")));
2128                 else {
2129                         cur.recordUndo();
2130                         string s = to_utf8(cmd.argument());
2131                         string const s1 = token(s, ' ', 1);
2132                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
2133                         string const s2 = token(s, ' ', 2);
2134                         MacroType type = MacroTypeNewcommand;
2135                         if (s2 == "def")
2136                                 type = MacroTypeDef;
2137                         InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(cur.buffer(),
2138                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
2139                         inset->setBuffer(bv->buffer());
2140                         insertInset(cur, inset);
2141
2142                         // enter macro inset and select the name
2143                         cur.push(*inset);
2144                         cur.top().pos() = cur.top().lastpos();
2145                         cur.resetAnchor();
2146                         cur.selection(true);
2147                         cur.top().pos() = 0;
2148                 }
2149                 break;
2150
2151         case LFUN_MATH_DISPLAY:
2152         case LFUN_MATH_SUBSCRIPT:
2153         case LFUN_MATH_SUPERSCRIPT:
2154         case LFUN_MATH_INSERT:
2155         case LFUN_MATH_AMS_MATRIX:
2156         case LFUN_MATH_MATRIX:
2157         case LFUN_MATH_DELIM:
2158         case LFUN_MATH_BIGDELIM:
2159                 mathDispatch(cur, cmd);
2160                 break;
2161
2162         case LFUN_FONT_EMPH: {
2163                 Font font(ignore_font, ignore_language);
2164                 font.fontInfo().setEmph(FONT_TOGGLE);
2165                 toggleAndShow(cur, this, font);
2166                 break;
2167         }
2168
2169         case LFUN_FONT_ITAL: {
2170                 Font font(ignore_font, ignore_language);
2171                 font.fontInfo().setShape(ITALIC_SHAPE);
2172                 toggleAndShow(cur, this, font);
2173                 break;
2174         }
2175
2176         case LFUN_FONT_BOLD:
2177         case LFUN_FONT_BOLDSYMBOL: {
2178                 Font font(ignore_font, ignore_language);
2179                 font.fontInfo().setSeries(BOLD_SERIES);
2180                 toggleAndShow(cur, this, font);
2181                 break;
2182         }
2183
2184         case LFUN_FONT_NOUN: {
2185                 Font font(ignore_font, ignore_language);
2186                 font.fontInfo().setNoun(FONT_TOGGLE);
2187                 toggleAndShow(cur, this, font);
2188                 break;
2189         }
2190
2191         case LFUN_FONT_TYPEWRITER: {
2192                 Font font(ignore_font, ignore_language);
2193                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
2194                 toggleAndShow(cur, this, font);
2195                 break;
2196         }
2197
2198         case LFUN_FONT_SANS: {
2199                 Font font(ignore_font, ignore_language);
2200                 font.fontInfo().setFamily(SANS_FAMILY);
2201                 toggleAndShow(cur, this, font);
2202                 break;
2203         }
2204
2205         case LFUN_FONT_ROMAN: {
2206                 Font font(ignore_font, ignore_language);
2207                 font.fontInfo().setFamily(ROMAN_FAMILY);
2208                 toggleAndShow(cur, this, font);
2209                 break;
2210         }
2211
2212         case LFUN_FONT_DEFAULT: {
2213                 Font font(inherit_font, ignore_language);
2214                 toggleAndShow(cur, this, font);
2215                 break;
2216         }
2217
2218         case LFUN_FONT_STRIKEOUT: {
2219                 Font font(ignore_font, ignore_language);
2220                 font.fontInfo().setStrikeout(FONT_TOGGLE);
2221                 toggleAndShow(cur, this, font);
2222                 break;
2223         }
2224
2225         case LFUN_FONT_CROSSOUT: {
2226                 Font font(ignore_font, ignore_language);
2227                 font.fontInfo().setXout(FONT_TOGGLE);
2228                 toggleAndShow(cur, this, font);
2229                 break;
2230         }
2231
2232         case LFUN_FONT_UNDERUNDERLINE: {
2233                 Font font(ignore_font, ignore_language);
2234                 font.fontInfo().setUuline(FONT_TOGGLE);
2235                 toggleAndShow(cur, this, font);
2236                 break;
2237         }
2238
2239         case LFUN_FONT_UNDERWAVE: {
2240                 Font font(ignore_font, ignore_language);
2241                 font.fontInfo().setUwave(FONT_TOGGLE);
2242                 toggleAndShow(cur, this, font);
2243                 break;
2244         }
2245
2246         case LFUN_FONT_UNDERLINE: {
2247                 Font font(ignore_font, ignore_language);
2248                 font.fontInfo().setUnderbar(FONT_TOGGLE);
2249                 toggleAndShow(cur, this, font);
2250                 break;
2251         }
2252
2253         case LFUN_FONT_SIZE: {
2254                 Font font(ignore_font, ignore_language);
2255                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
2256                 toggleAndShow(cur, this, font);
2257                 break;
2258         }
2259
2260         case LFUN_LANGUAGE: {
2261                 string const lang_arg = cmd.getArg(0);
2262                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
2263                 Language const * lang =
2264                         reset ? reset_language
2265                               : languages.getLanguage(lang_arg);
2266                 // we allow reset_language, which is 0, but only if it
2267                 // was requested via empty or "reset" arg.
2268                 if (!lang && !reset)
2269                         break;
2270                 bool const toggle = (cmd.getArg(1) != "set");
2271                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
2272                 Font font(ignore_font, lang);
2273                 toggleAndShow(cur, this, font, toggle);
2274                 break;
2275         }
2276
2277         case LFUN_TEXTSTYLE_APPLY:
2278                 toggleAndShow(cur, this, freefont, toggleall);
2279                 cur.message(_("Character set"));
2280                 break;
2281
2282         // Set the freefont using the contents of \param data dispatched from
2283         // the frontends and apply it at the current cursor location.
2284         case LFUN_TEXTSTYLE_UPDATE: {
2285                 Font font;
2286                 bool toggle;
2287                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
2288                         freefont = font;
2289                         toggleall = toggle;
2290                         toggleAndShow(cur, this, freefont, toggleall);
2291                         cur.message(_("Character set"));
2292                 } else {
2293                         lyxerr << "Argument not ok";
2294                 }
2295                 break;
2296         }
2297
2298         case LFUN_FINISHED_LEFT:
2299                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2300                 // We're leaving an inset, going left. If the inset is LTR, we're
2301                 // leaving from the front, so we should not move (remain at --- but
2302                 // not in --- the inset). If the inset is RTL, move left, without
2303                 // entering the inset itself; i.e., move to after the inset.
2304                 if (cur.paragraph().getFontSettings(
2305                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2306                         cursorVisLeft(cur, true);
2307                 break;
2308
2309         case LFUN_FINISHED_RIGHT:
2310                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2311                 // We're leaving an inset, going right. If the inset is RTL, we're
2312                 // leaving from the front, so we should not move (remain at --- but
2313                 // not in --- the inset). If the inset is LTR, move right, without
2314                 // entering the inset itself; i.e., move to after the inset.
2315                 if (!cur.paragraph().getFontSettings(
2316                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2317                         cursorVisRight(cur, true);
2318                 break;
2319
2320         case LFUN_FINISHED_BACKWARD:
2321                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2322                 cur.setCurrentFont();
2323                 break;
2324
2325         case LFUN_FINISHED_FORWARD:
2326                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2327                 ++cur.pos();
2328                 cur.setCurrentFont();
2329                 break;
2330
2331         case LFUN_LAYOUT_PARAGRAPH: {
2332                 string data;
2333                 params2string(cur.paragraph(), data);
2334                 data = "show\n" + data;
2335                 bv->showDialog("paragraph", data);
2336                 break;
2337         }
2338
2339         case LFUN_PARAGRAPH_UPDATE: {
2340                 string data;
2341                 params2string(cur.paragraph(), data);
2342
2343                 // Will the paragraph accept changes from the dialog?
2344                 bool const accept =
2345                         cur.inset().allowParagraphCustomization(cur.idx());
2346
2347                 data = "update " + convert<string>(accept) + '\n' + data;
2348                 bv->updateDialog("paragraph", data);
2349                 break;
2350         }
2351
2352         case LFUN_ACCENT_UMLAUT:
2353         case LFUN_ACCENT_CIRCUMFLEX:
2354         case LFUN_ACCENT_GRAVE:
2355         case LFUN_ACCENT_ACUTE:
2356         case LFUN_ACCENT_TILDE:
2357         case LFUN_ACCENT_PERISPOMENI:
2358         case LFUN_ACCENT_CEDILLA:
2359         case LFUN_ACCENT_MACRON:
2360         case LFUN_ACCENT_DOT:
2361         case LFUN_ACCENT_UNDERDOT:
2362         case LFUN_ACCENT_UNDERBAR:
2363         case LFUN_ACCENT_CARON:
2364         case LFUN_ACCENT_BREVE:
2365         case LFUN_ACCENT_TIE:
2366         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2367         case LFUN_ACCENT_CIRCLE:
2368         case LFUN_ACCENT_OGONEK:
2369                 theApp()->handleKeyFunc(cmd.action());
2370                 if (!cmd.argument().empty())
2371                         // FIXME: Are all these characters encoded in one byte in utf8?
2372                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2373                 cur.screenUpdateFlags(Update::FitCursor);
2374                 break;
2375
2376         case LFUN_FLOAT_LIST_INSERT: {
2377                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2378                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2379                         cur.recordUndo();
2380                         if (cur.selection())
2381                                 cutSelection(cur, true, false);
2382                         breakParagraph(cur);
2383
2384                         if (cur.lastpos() != 0) {
2385                                 cursorBackward(cur);
2386                                 breakParagraph(cur);
2387                         }
2388
2389                         docstring const laystr = cur.inset().usePlainLayout() ?
2390                                 tclass.plainLayoutName() :
2391                                 tclass.defaultLayoutName();
2392                         setLayout(cur, laystr);
2393                         ParagraphParameters p;
2394                         // FIXME If this call were replaced with one to clearParagraphParams(),
2395                         // then we could get rid of this method altogether.
2396                         setParagraphs(cur, p);
2397                         // FIXME This should be simplified when InsetFloatList takes a
2398                         // Buffer in its constructor.
2399                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2400                         ifl->setBuffer(bv->buffer());
2401                         insertInset(cur, ifl);
2402                         cur.posForward();
2403                 } else {
2404                         lyxerr << "Non-existent float type: "
2405                                << to_utf8(cmd.argument()) << endl;
2406                 }
2407                 break;
2408         }
2409
2410         case LFUN_CHANGE_ACCEPT: {
2411                 acceptOrRejectChanges(cur, ACCEPT);
2412                 break;
2413         }
2414
2415         case LFUN_CHANGE_REJECT: {
2416                 acceptOrRejectChanges(cur, REJECT);
2417                 break;
2418         }
2419
2420         case LFUN_THESAURUS_ENTRY: {
2421                 Language const * language = cur.getFont().language();
2422                 docstring arg = cmd.argument();
2423                 if (arg.empty()) {
2424                         arg = cur.selectionAsString(false);
2425                         // FIXME
2426                         if (arg.size() > 100 || arg.empty()) {
2427                                 // Get word or selection
2428                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2429                                 arg = cur.selectionAsString(false);
2430                                 arg += " lang=" + from_ascii(language->lang());
2431                         }
2432                 } else {
2433                         string lang = cmd.getArg(1);
2434                         // This duplicates the code in GuiThesaurus::initialiseParams
2435                         if (prefixIs(lang, "lang=")) {
2436                                 language = languages.getLanguage(lang.substr(5));
2437                                 if (!language)
2438                                         language = cur.getFont().language();
2439                         }
2440                 }
2441                 string lang = language->code();
2442                 if (lyxrc.thesaurusdir_path.empty() && !thesaurus.thesaurusInstalled(from_ascii(lang))) {
2443                         LYXERR(Debug::ACTION, "Command " << cmd << ". Thesaurus not found for language " << lang);
2444                         frontend::Alert::warning(_("Path to thesaurus directory not set!"),
2445                                         _("The path to the thesaurus directory has not been specified.\n"
2446                                           "The thesaurus is not functional.\n"
2447                                           "Please refer to sec. 6.15.1 of the User's Guide for setup\n"
2448                                           "instructions."));
2449                 }
2450                 bv->showDialog("thesaurus", to_utf8(arg));
2451                 break;
2452         }
2453
2454         case LFUN_SPELLING_ADD: {
2455                 Language const * language = getLanguage(cur, cmd.getArg(1));
2456                 docstring word = from_utf8(cmd.getArg(0));
2457                 if (word.empty()) {
2458                         word = cur.selectionAsString(false);
2459                         // FIXME
2460                         if (word.size() > 100 || word.empty()) {
2461                                 // Get word or selection
2462                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2463                                 word = cur.selectionAsString(false);
2464                         }
2465                 }
2466                 WordLangTuple wl(word, language);
2467                 theSpellChecker()->insert(wl);
2468                 break;
2469         }
2470
2471         case LFUN_SPELLING_IGNORE: {
2472                 Language const * language = getLanguage(cur, cmd.getArg(1));
2473                 docstring word = from_utf8(cmd.getArg(0));
2474                 if (word.empty()) {
2475                         word = cur.selectionAsString(false);
2476                         // FIXME
2477                         if (word.size() > 100 || word.empty()) {
2478                                 // Get word or selection
2479                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2480                                 word = cur.selectionAsString(false);
2481                         }
2482                 }
2483                 WordLangTuple wl(word, language);
2484                 theSpellChecker()->accept(wl);
2485                 break;
2486         }
2487
2488         case LFUN_SPELLING_REMOVE: {
2489                 Language const * language = getLanguage(cur, cmd.getArg(1));
2490                 docstring word = from_utf8(cmd.getArg(0));
2491                 if (word.empty()) {
2492                         word = cur.selectionAsString(false);
2493                         // FIXME
2494                         if (word.size() > 100 || word.empty()) {
2495                                 // Get word or selection
2496                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2497                                 word = cur.selectionAsString(false);
2498                         }
2499                 }
2500                 WordLangTuple wl(word, language);
2501                 theSpellChecker()->remove(wl);
2502                 break;
2503         }
2504
2505         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2506                 // Given data, an encoding of the ParagraphParameters
2507                 // generated in the Paragraph dialog, this function sets
2508                 // the current paragraph, or currently selected paragraphs,
2509                 // appropriately.
2510                 // NOTE: This function overrides all existing settings.
2511                 setParagraphs(cur, cmd.argument());
2512                 cur.message(_("Paragraph layout set"));
2513                 break;
2514         }
2515
2516         case LFUN_PARAGRAPH_PARAMS: {
2517                 // Given data, an encoding of the ParagraphParameters as we'd
2518                 // find them in a LyX file, this function modifies the current paragraph,
2519                 // or currently selected paragraphs.
2520                 // NOTE: This function only modifies, and does not override, existing
2521                 // settings.
2522                 setParagraphs(cur, cmd.argument(), true);
2523                 cur.message(_("Paragraph layout set"));
2524                 break;
2525         }
2526
2527         case LFUN_ESCAPE:
2528                 if (cur.selection()) {
2529                         cur.selection(false);
2530                 } else {
2531                         cur.undispatched();
2532                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2533                         // correct, but I'm not 100% sure -- dov, 071019
2534                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2535                 }
2536                 break;
2537
2538         case LFUN_OUTLINE_UP:
2539                 outline(OutlineUp, cur);
2540                 setCursor(cur, cur.pit(), 0);
2541                 cur.forceBufferUpdate();
2542                 needsUpdate = true;
2543                 break;
2544
2545         case LFUN_OUTLINE_DOWN:
2546                 outline(OutlineDown, cur);
2547                 setCursor(cur, cur.pit(), 0);
2548                 cur.forceBufferUpdate();
2549                 needsUpdate = true;
2550                 break;
2551
2552         case LFUN_OUTLINE_IN:
2553                 outline(OutlineIn, cur);
2554                 cur.forceBufferUpdate();
2555                 needsUpdate = true;
2556                 break;
2557
2558         case LFUN_OUTLINE_OUT:
2559                 outline(OutlineOut, cur);
2560                 cur.forceBufferUpdate();
2561                 needsUpdate = true;
2562                 break;
2563
2564         case LFUN_SERVER_GET_STATISTICS:
2565                 {
2566                         DocIterator from, to;
2567                         if (cur.selection()) {
2568                                 from = cur.selectionBegin();
2569                                 to = cur.selectionEnd();
2570                         } else {
2571                                 from = doc_iterator_begin(cur.buffer());
2572                                 to = doc_iterator_end(cur.buffer());
2573                         }
2574
2575                         cur.buffer()->updateStatistics(from, to);
2576                         string const arg0 = cmd.getArg(0);
2577                         if (arg0 == "words") {
2578                                 cur.message(convert<docstring>(cur.buffer()->wordCount()));
2579                         } else if (arg0 == "chars") {
2580                                 cur.message(convert<docstring>(cur.buffer()->charCount(false)));
2581                         } else if (arg0 == "chars-space") {
2582                                 cur.message(convert<docstring>(cur.buffer()->charCount(true)));
2583                         } else {
2584                                 cur.message(convert<docstring>(cur.buffer()->wordCount()) + " "
2585                                 + convert<docstring>(cur.buffer()->charCount(false)) + " "
2586                                 + convert<docstring>(cur.buffer()->charCount(true)));
2587                         }
2588                 }
2589                 break;
2590
2591         default:
2592                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2593                 cur.undispatched();
2594                 break;
2595         }
2596
2597         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2598
2599         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2600                 // Check for misspelled text
2601                 // The redraw is useful because of the painting of
2602                 // misspelled markers depends on the cursor position.
2603                 // Trigger a redraw for cursor moves inside misspelled text.
2604                 if (!cur.inTexted()) {
2605                         // move from regular text to math
2606                         needsUpdate = last_misspelled;
2607                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2608                         // move inside regular text
2609                         needsUpdate = last_misspelled
2610                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2611                 }
2612         }
2613
2614         // FIXME: The cursor flag is reset two lines below
2615         // so we need to check here if some of the LFUN did touch that.
2616         // for now only Text::erase() and Text::backspace() do that.
2617         // The plan is to verify all the LFUNs and then to remove this
2618         // singleParUpdate boolean altogether.
2619         if (cur.result().screenUpdate() & Update::Force) {
2620                 singleParUpdate = false;
2621                 needsUpdate = true;
2622         }
2623
2624         // FIXME: the following code should go in favor of fine grained
2625         // update flag treatment.
2626         if (singleParUpdate) {
2627                 // Inserting characters does not change par height in general. So, try
2628                 // to update _only_ this paragraph. BufferView will detect if a full
2629                 // metrics update is needed anyway.
2630                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2631                 return;
2632         }
2633         if (!needsUpdate
2634             && &oldTopSlice.inset() == &cur.inset()
2635             && oldTopSlice.idx() == cur.idx()
2636             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2637             && !cur.selection())
2638                 // FIXME: it would be better if we could just do this
2639                 //
2640                 //if (cur.result().update() != Update::FitCursor)
2641                 //      cur.noScreenUpdate();
2642                 //
2643                 // But some LFUNs do not set Update::FitCursor when needed, so we
2644                 // do it for all. This is not very harmfull as FitCursor will provoke
2645                 // a full redraw only if needed but still, a proper review of all LFUN
2646                 // should be done and this needsUpdate boolean can then be removed.
2647                 cur.screenUpdateFlags(Update::FitCursor);
2648         else
2649                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2650 }
2651
2652
2653 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2654                         FuncStatus & flag) const
2655 {
2656         LBUFERR(this == cur.text());
2657
2658         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2659         bool enable = true;
2660         bool allow_in_passthru = false;
2661         InsetCode code = NO_CODE;
2662
2663         switch (cmd.action()) {
2664
2665         case LFUN_DEPTH_DECREMENT:
2666                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2667                 break;
2668
2669         case LFUN_DEPTH_INCREMENT:
2670                 enable = changeDepthAllowed(cur, INC_DEPTH);
2671                 break;
2672
2673         case LFUN_APPENDIX:
2674                 // FIXME We really should not allow this to be put, e.g.,
2675                 // in a footnote, or in ERT. But it would make sense in a
2676                 // branch, so I'm not sure what to do.
2677                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2678                 break;
2679
2680         case LFUN_DIALOG_SHOW_NEW_INSET:
2681                 if (cmd.argument() == "bibitem")
2682                         code = BIBITEM_CODE;
2683                 else if (cmd.argument() == "bibtex") {
2684                         code = BIBTEX_CODE;
2685                         // not allowed in description items
2686                         enable = !inDescriptionItem(cur);
2687                 }
2688                 else if (cmd.argument() == "box")
2689                         code = BOX_CODE;
2690                 else if (cmd.argument() == "branch")
2691                         code = BRANCH_CODE;
2692                 else if (cmd.argument() == "citation")
2693                         code = CITE_CODE;
2694                 else if (cmd.argument() == "ert")
2695                         code = ERT_CODE;
2696                 else if (cmd.argument() == "external")
2697                         code = EXTERNAL_CODE;
2698                 else if (cmd.argument() == "float")
2699                         code = FLOAT_CODE;
2700                 else if (cmd.argument() == "graphics")
2701                         code = GRAPHICS_CODE;
2702                 else if (cmd.argument() == "href")
2703                         code = HYPERLINK_CODE;
2704                 else if (cmd.argument() == "include")
2705                         code = INCLUDE_CODE;
2706                 else if (cmd.argument() == "index")
2707                         code = INDEX_CODE;
2708                 else if (cmd.argument() == "index_print")
2709                         code = INDEX_PRINT_CODE;
2710                 else if (cmd.argument() == "listings")
2711                         code = LISTINGS_CODE;
2712                 else if (cmd.argument() == "mathspace")
2713                         code = MATH_HULL_CODE;
2714                 else if (cmd.argument() == "nomenclature")
2715                         code = NOMENCL_CODE;
2716                 else if (cmd.argument() == "nomencl_print")
2717                         code = NOMENCL_PRINT_CODE;
2718                 else if (cmd.argument() == "label")
2719                         code = LABEL_CODE;
2720                 else if (cmd.argument() == "line")
2721                         code = LINE_CODE;
2722                 else if (cmd.argument() == "note")
2723                         code = NOTE_CODE;
2724                 else if (cmd.argument() == "phantom")
2725                         code = PHANTOM_CODE;
2726                 else if (cmd.argument() == "ref")
2727                         code = REF_CODE;
2728                 else if (cmd.argument() == "space")
2729                         code = SPACE_CODE;
2730                 else if (cmd.argument() == "toc")
2731                         code = TOC_CODE;
2732                 else if (cmd.argument() == "vspace")
2733                         code = VSPACE_CODE;
2734                 else if (cmd.argument() == "wrap")
2735                         code = WRAP_CODE;
2736                 break;
2737
2738         case LFUN_ERT_INSERT:
2739                 code = ERT_CODE;
2740                 break;
2741         case LFUN_LISTING_INSERT:
2742                 code = LISTINGS_CODE;
2743                 // not allowed in description items
2744                 enable = !inDescriptionItem(cur);
2745                 break;
2746         case LFUN_FOOTNOTE_INSERT:
2747                 code = FOOT_CODE;
2748                 break;
2749         case LFUN_TABULAR_INSERT:
2750                 code = TABULAR_CODE;
2751                 break;
2752         case LFUN_MARGINALNOTE_INSERT:
2753                 code = MARGIN_CODE;
2754                 break;
2755         case LFUN_FLOAT_INSERT:
2756         case LFUN_FLOAT_WIDE_INSERT:
2757                 // FIXME: If there is a selection, we should check whether there
2758                 // are floats in the selection, but this has performance issues, see
2759                 // LFUN_CHANGE_ACCEPT/REJECT.
2760                 code = FLOAT_CODE;
2761                 if (inDescriptionItem(cur))
2762                         // not allowed in description items
2763                         enable = false;
2764                 else {
2765                         InsetCode const inset_code = cur.inset().lyxCode();
2766
2767                         // algorithm floats cannot be put in another float
2768                         if (to_utf8(cmd.argument()) == "algorithm") {
2769                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2770                                 break;
2771                         }
2772
2773                         // for figures and tables: only allow in another
2774                         // float or wrap if it is of the same type and
2775                         // not a subfloat already
2776                         if(cur.inset().lyxCode() == code) {
2777                                 InsetFloat const & ins =
2778                                         static_cast<InsetFloat const &>(cur.inset());
2779                                 enable = ins.params().type == to_utf8(cmd.argument())
2780                                         && !ins.params().subfloat;
2781                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
2782                                 InsetWrap const & ins =
2783                                         static_cast<InsetWrap const &>(cur.inset());
2784                                 enable = ins.params().type == to_utf8(cmd.argument());
2785                         }
2786                 }
2787                 break;
2788         case LFUN_WRAP_INSERT:
2789                 code = WRAP_CODE;
2790                 // not allowed in description items
2791                 enable = !inDescriptionItem(cur);
2792                 break;
2793         case LFUN_FLOAT_LIST_INSERT: {
2794                 code = FLOAT_LIST_CODE;
2795                 // not allowed in description items
2796                 enable = !inDescriptionItem(cur);
2797                 if (enable) {
2798                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
2799                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
2800                         // make sure we know about such floats
2801                         if (cit == floats.end() ||
2802                                         // and that we know how to generate a list of them
2803                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
2804                                 flag.setUnknown(true);
2805                                 // probably not necessary, but...
2806                                 enable = false;
2807                         }
2808                 }
2809                 break;
2810         }
2811         case LFUN_CAPTION_INSERT: {
2812                 code = CAPTION_CODE;
2813                 string arg = cmd.getArg(0);
2814                 bool varia = arg != "Unnumbered"
2815                         && cur.inset().allowsCaptionVariation(arg);
2816                 // not allowed in description items,
2817                 // and in specific insets
2818                 enable = !inDescriptionItem(cur)
2819                         && (varia || arg.empty() || arg == "Standard");
2820                 break;
2821         }
2822         case LFUN_NOTE_INSERT:
2823                 code = NOTE_CODE;
2824                 // in commands (sections etc.) and description items,
2825                 // only Notes are allowed
2826                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2827                           (!cur.paragraph().layout().isCommand()
2828                            && !inDescriptionItem(cur)));
2829                 break;
2830         case LFUN_FLEX_INSERT: {
2831                 code = FLEX_CODE;
2832                 string s = cmd.getArg(0);
2833                 InsetLayout il =
2834                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2835                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2836                     il.lyxtype() != InsetLayout::CUSTOM &&
2837                     il.lyxtype() != InsetLayout::ELEMENT &&
2838                     il.lyxtype ()!= InsetLayout::STANDARD)
2839                         enable = false;
2840                 break;
2841                 }
2842         case LFUN_BOX_INSERT:
2843                 code = BOX_CODE;
2844                 break;
2845         case LFUN_BRANCH_INSERT:
2846                 code = BRANCH_CODE;
2847                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2848                     && cur.buffer()->params().branchlist().empty())
2849                         enable = false;
2850                 break;
2851         case LFUN_IPA_INSERT:
2852                 code = IPA_CODE;
2853                 break;
2854         case LFUN_PHANTOM_INSERT:
2855                 code = PHANTOM_CODE;
2856                 break;
2857         case LFUN_LABEL_INSERT:
2858                 code = LABEL_CODE;
2859                 break;
2860         case LFUN_INFO_INSERT:
2861                 code = INFO_CODE;
2862                 break;
2863         case LFUN_ARGUMENT_INSERT: {
2864                 code = ARG_CODE;
2865                 allow_in_passthru = true;
2866                 string const arg = cmd.getArg(0);
2867                 if (arg.empty()) {
2868                         enable = false;
2869                         break;
2870                 }
2871                 Layout const & lay = cur.paragraph().layout();
2872                 Layout::LaTeXArgMap args = lay.args();
2873                 Layout::LaTeXArgMap::const_iterator const lait =
2874                                 args.find(arg);
2875                 if (lait != args.end()) {
2876                         enable = true;
2877                         pit_type pit = cur.pit();
2878                         pit_type lastpit = cur.pit();
2879                         if (lay.isEnvironment() && !prefixIs(arg, "item:")) {
2880                                 // In a sequence of "merged" environment layouts, we only allow
2881                                 // non-item arguments once.
2882                                 lastpit = cur.lastpit();
2883                                 // get the first paragraph in sequence with this layout
2884                                 depth_type const current_depth = cur.paragraph().params().depth();
2885                                 while (true) {
2886                                         if (pit == 0)
2887                                                 break;
2888                                         Paragraph cpar = pars_[pit - 1];
2889                                         if (cpar.layout() == lay && cpar.params().depth() == current_depth)
2890                                                 --pit;
2891                                         else
2892                                                 break;
2893                                 }
2894                         }
2895                         for (; pit <= lastpit; ++pit) {
2896                                 if (pars_[pit].layout() != lay)
2897                                         break;
2898                                 for (auto const & table : pars_[pit].insetList())
2899                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
2900                                                 if (ins->name() == arg) {
2901                                                         // we have this already
2902                                                         enable = false;
2903                                                         break;
2904                                                 }
2905                         }
2906                 } else
2907                         enable = false;
2908                 break;
2909         }
2910         case LFUN_INDEX_INSERT:
2911                 code = INDEX_CODE;
2912                 break;
2913         case LFUN_INDEX_PRINT:
2914                 code = INDEX_PRINT_CODE;
2915                 // not allowed in description items
2916                 enable = !inDescriptionItem(cur);
2917                 break;
2918         case LFUN_NOMENCL_INSERT:
2919                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2920                         enable = false;
2921                         break;
2922                 }
2923                 code = NOMENCL_CODE;
2924                 break;
2925         case LFUN_NOMENCL_PRINT:
2926                 code = NOMENCL_PRINT_CODE;
2927                 // not allowed in description items
2928                 enable = !inDescriptionItem(cur);
2929                 break;
2930         case LFUN_HREF_INSERT:
2931                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2932                         enable = false;
2933                         break;
2934                 }
2935                 code = HYPERLINK_CODE;
2936                 break;
2937         case LFUN_IPAMACRO_INSERT: {
2938                 string const arg = cmd.getArg(0);
2939                 if (arg == "deco")
2940                         code = IPADECO_CODE;
2941                 else
2942                         code = IPACHAR_CODE;
2943                 break;
2944         }
2945         case LFUN_QUOTE_INSERT:
2946                 // always allow this, since we will inset a raw quote
2947                 // if an inset is not allowed.
2948                 allow_in_passthru = true;
2949                 break;
2950         case LFUN_SPECIALCHAR_INSERT:
2951                 code = SPECIALCHAR_CODE;
2952                 break;
2953         case LFUN_SPACE_INSERT:
2954                 // slight hack: we know this is allowed in math mode
2955                 if (cur.inTexted())
2956                         code = SPACE_CODE;
2957                 break;
2958         case LFUN_PREVIEW_INSERT:
2959                 code = PREVIEW_CODE;
2960                 break;
2961         case LFUN_SCRIPT_INSERT:
2962                 code = SCRIPT_CODE;
2963                 break;
2964
2965         case LFUN_MATH_INSERT:
2966         case LFUN_MATH_AMS_MATRIX:
2967         case LFUN_MATH_MATRIX:
2968         case LFUN_MATH_DELIM:
2969         case LFUN_MATH_BIGDELIM:
2970         case LFUN_MATH_DISPLAY:
2971         case LFUN_MATH_MODE:
2972         case LFUN_MATH_MACRO:
2973         case LFUN_MATH_SUBSCRIPT:
2974         case LFUN_MATH_SUPERSCRIPT:
2975                 code = MATH_HULL_CODE;
2976                 break;
2977
2978         case LFUN_REGEXP_MODE:
2979                 code = MATH_HULL_CODE;
2980                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
2981                 break;
2982
2983         case LFUN_INSET_MODIFY:
2984                 // We need to disable this, because we may get called for a
2985                 // tabular cell via
2986                 // InsetTabular::getStatus() -> InsetText::getStatus()
2987                 // and we don't handle LFUN_INSET_MODIFY.
2988                 enable = false;
2989                 break;
2990
2991         case LFUN_FONT_EMPH:
2992                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2993                 enable = !cur.paragraph().isPassThru();
2994                 break;
2995
2996         case LFUN_FONT_ITAL:
2997                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2998                 enable = !cur.paragraph().isPassThru();
2999                 break;
3000
3001         case LFUN_FONT_NOUN:
3002                 flag.setOnOff(fontinfo.noun() == FONT_ON);
3003                 enable = !cur.paragraph().isPassThru();
3004                 break;
3005
3006         case LFUN_FONT_BOLD:
3007         case LFUN_FONT_BOLDSYMBOL:
3008                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
3009                 enable = !cur.paragraph().isPassThru();
3010                 break;
3011
3012         case LFUN_FONT_SANS:
3013                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
3014                 enable = !cur.paragraph().isPassThru();
3015                 break;
3016
3017         case LFUN_FONT_ROMAN:
3018                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
3019                 enable = !cur.paragraph().isPassThru();
3020                 break;
3021
3022         case LFUN_FONT_TYPEWRITER:
3023                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
3024                 enable = !cur.paragraph().isPassThru();
3025                 break;
3026
3027         case LFUN_CUT:
3028         case LFUN_COPY:
3029                 enable = cur.selection();
3030                 break;
3031
3032         case LFUN_PASTE: {
3033                 if (cmd.argument().empty()) {
3034                         if (theClipboard().isInternal())
3035                                 enable = cap::numberOfSelections() > 0;
3036                         else
3037                                 enable = !theClipboard().empty();
3038                         break;
3039                 }
3040
3041                 // we have an argument
3042                 string const arg = to_utf8(cmd.argument());
3043                 if (isStrUnsignedInt(arg)) {
3044                         // it's a number and therefore means the internal stack
3045                         unsigned int n = convert<unsigned int>(arg);
3046                         enable = cap::numberOfSelections() > n;
3047                         break;
3048                 }
3049
3050                 // explicit text type?
3051                 if (arg == "html") {
3052                         // Do not enable for PlainTextType, since some tidying in the
3053                         // frontend is needed for HTML, which is too unsafe for plain text.
3054                         enable = theClipboard().hasTextContents(Clipboard::HtmlTextType);
3055                         break;
3056                 } else if (arg == "latex") {
3057                         // LaTeX is usually not available on the clipboard with
3058                         // the correct MIME type, but in plain text.
3059                         enable = theClipboard().hasTextContents(Clipboard::PlainTextType) ||
3060                                  theClipboard().hasTextContents(Clipboard::LaTeXTextType);
3061                         break;
3062                 }
3063
3064                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
3065                 if (arg == "pdf")
3066                         type = Clipboard::PdfGraphicsType;
3067                 else if (arg == "png")
3068                         type = Clipboard::PngGraphicsType;
3069                 else if (arg == "jpeg")
3070                         type = Clipboard::JpegGraphicsType;
3071                 else if (arg == "linkback")
3072                         type = Clipboard::LinkBackGraphicsType;
3073                 else if (arg == "emf")
3074                         type = Clipboard::EmfGraphicsType;
3075                 else if (arg == "wmf")
3076                         type = Clipboard::WmfGraphicsType;
3077                 else {
3078                         // unknown argument
3079                         LYXERR0("Unrecognized graphics type: " << arg);
3080                         // we don't want to assert if the user just mistyped the LFUN
3081                         LATTEST(cmd.origin() != FuncRequest::INTERNAL);
3082                         enable = false;
3083                         break;
3084                 }
3085                 enable = theClipboard().hasGraphicsContents(type);
3086                 break;
3087         }
3088
3089         case LFUN_CLIPBOARD_PASTE:
3090         case LFUN_CLIPBOARD_PASTE_SIMPLE:
3091                 enable = !theClipboard().empty();
3092                 break;
3093
3094         case LFUN_PRIMARY_SELECTION_PASTE:
3095                 enable = cur.selection() || !theSelection().empty();
3096                 break;
3097
3098         case LFUN_SELECTION_PASTE:
3099                 enable = cap::selection();
3100                 break;
3101
3102         case LFUN_PARAGRAPH_MOVE_UP:
3103                 enable = cur.pit() > 0 && !cur.selection();
3104                 break;
3105
3106         case LFUN_PARAGRAPH_MOVE_DOWN:
3107                 enable = cur.pit() < cur.lastpit() && !cur.selection();
3108                 break;
3109
3110         case LFUN_CHANGE_ACCEPT:
3111         case LFUN_CHANGE_REJECT:
3112                 // In principle, these LFUNs should only be enabled if there
3113                 // is a change at the current position/in the current selection.
3114                 // However, without proper optimizations, this will inevitably
3115                 // result in unacceptable performance - just imagine a user who
3116                 // wants to select the complete content of a long document.
3117                 if (!cur.selection())
3118                         enable = cur.paragraph().isChanged(cur.pos());
3119                 else
3120                         // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
3121                         // for selections.
3122                         enable = true;
3123                 break;
3124
3125         case LFUN_OUTLINE_UP:
3126         case LFUN_OUTLINE_DOWN:
3127         case LFUN_OUTLINE_IN:
3128         case LFUN_OUTLINE_OUT:
3129                 // FIXME: LyX is not ready for outlining within inset.
3130                 enable = isMainText()
3131                         && cur.buffer()->text().getTocLevel(cur.pit()) != Layout::NOT_IN_TOC;
3132                 break;
3133
3134         case LFUN_NEWLINE_INSERT:
3135                 // LaTeX restrictions (labels or empty par)
3136                 enable = !cur.paragraph().isPassThru()
3137                         && cur.pos() > cur.paragraph().beginOfBody();
3138                 break;
3139
3140         case LFUN_SEPARATOR_INSERT:
3141                 // Always enabled for now
3142                 enable = true;
3143                 break;
3144
3145         case LFUN_TAB_INSERT:
3146         case LFUN_TAB_DELETE:
3147                 enable = cur.paragraph().isPassThru();
3148                 break;
3149
3150         case LFUN_SET_GRAPHICS_GROUP: {
3151                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
3152                 if (!ins)
3153                         enable = false;
3154                 else
3155                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
3156                 break;
3157         }
3158
3159         case LFUN_NEWPAGE_INSERT:
3160                 // not allowed in description items
3161                 code = NEWPAGE_CODE;
3162                 enable = !inDescriptionItem(cur);
3163                 break;
3164
3165         case LFUN_DATE_INSERT: {
3166                 string const format = cmd.argument().empty()
3167                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
3168                 enable = support::os::is_valid_strftime(format);
3169                 break;
3170         }
3171
3172         case LFUN_LANGUAGE:
3173                 enable = !cur.paragraph().isPassThru();
3174                 flag.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
3175                 break;
3176
3177         case LFUN_PARAGRAPH_BREAK:
3178                 enable = inset().allowMultiPar();
3179                 break;
3180
3181         case LFUN_SPELLING_ADD:
3182         case LFUN_SPELLING_IGNORE:
3183         case LFUN_SPELLING_REMOVE:
3184                 enable = theSpellChecker() != NULL;
3185                 if (enable && !cmd.getArg(1).empty()) {
3186                         // validate explicitly given language
3187                         Language const * const lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
3188                         enable &= lang != NULL;
3189                 }
3190                 break;
3191
3192         case LFUN_LAYOUT: {
3193                 DocumentClass const & tclass = cur.buffer()->params().documentClass();
3194                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
3195                 docstring layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
3196                 if (layout.empty())
3197                         layout = tclass.defaultLayoutName();
3198                 enable = !owner_->forcePlainLayout() && tclass.hasLayout(layout);
3199
3200                 flag.setOnOff(layout == cur.paragraph().layout().name());
3201                 break;
3202         }
3203
3204         case LFUN_ENVIRONMENT_SPLIT: {
3205                 if (cmd.argument() == "outer") {
3206                         // check if we have an environment in our nesting hierarchy
3207                         bool res = false;
3208                         depth_type const current_depth = cur.paragraph().params().depth();
3209                         pit_type pit = cur.pit();
3210                         Paragraph cpar = pars_[pit];
3211                         while (true) {
3212                                 if (pit == 0 || cpar.params().depth() == 0)
3213                                         break;
3214                                 --pit;
3215                                 cpar = pars_[pit];
3216                                 if (cpar.params().depth() < current_depth)
3217                                         res = cpar.layout().isEnvironment();
3218                         }
3219                         enable = res;
3220                         break;
3221                 }
3222                 else if (cmd.argument() == "previous") {
3223                         // look if we have an environment in the previous par
3224                         pit_type pit = cur.pit();
3225                         Paragraph cpar = pars_[pit];
3226                         if (pit > 0) {
3227                                 --pit;
3228                                 cpar = pars_[pit];
3229                                 enable = cpar.layout().isEnvironment();
3230                                 break;
3231                         }
3232                         enable = false;
3233                         break;
3234                 }
3235                 else if (cur.paragraph().layout().isEnvironment()) {
3236                         enable = cmd.argument() == "before"
3237                                 || cur.pos() > 0 || !isFirstInSequence(cur.pit());
3238                         break;
3239                 }
3240                 enable = false;
3241                 break;
3242         }
3243
3244         case LFUN_LAYOUT_PARAGRAPH:
3245         case LFUN_PARAGRAPH_PARAMS:
3246         case LFUN_PARAGRAPH_PARAMS_APPLY:
3247         case LFUN_PARAGRAPH_UPDATE:
3248                 enable = owner_->allowParagraphCustomization();
3249                 break;
3250
3251         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
3252         //  Because they insert COMBINING DIACRITICAL Unicode characters,
3253         //  that cannot be handled by LaTeX but must be converted according
3254         //  to the definition in lib/unicodesymbols?
3255         case LFUN_ACCENT_ACUTE:
3256         case LFUN_ACCENT_BREVE:
3257         case LFUN_ACCENT_CARON:
3258         case LFUN_ACCENT_CEDILLA:
3259         case LFUN_ACCENT_CIRCLE:
3260         case LFUN_ACCENT_CIRCUMFLEX:
3261         case LFUN_ACCENT_DOT:
3262         case LFUN_ACCENT_GRAVE:
3263         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
3264         case LFUN_ACCENT_MACRON:
3265         case LFUN_ACCENT_OGONEK:
3266         case LFUN_ACCENT_TIE:
3267         case LFUN_ACCENT_TILDE:
3268         case LFUN_ACCENT_PERISPOMENI:
3269         case LFUN_ACCENT_UMLAUT:
3270         case LFUN_ACCENT_UNDERBAR:
3271         case LFUN_ACCENT_UNDERDOT:
3272         case LFUN_FONT_DEFAULT:
3273         case LFUN_FONT_FRAK:
3274         case LFUN_FONT_SIZE:
3275         case LFUN_FONT_STATE:
3276         case LFUN_FONT_UNDERLINE:
3277         case LFUN_FONT_STRIKEOUT:
3278         case LFUN_FONT_CROSSOUT:
3279         case LFUN_FONT_UNDERUNDERLINE:
3280         case LFUN_FONT_UNDERWAVE:
3281         case LFUN_TEXTSTYLE_APPLY:
3282         case LFUN_TEXTSTYLE_UPDATE:
3283                 enable = !cur.paragraph().isPassThru();
3284                 break;
3285
3286         case LFUN_WORD_DELETE_FORWARD:
3287         case LFUN_WORD_DELETE_BACKWARD:
3288         case LFUN_LINE_DELETE_FORWARD:
3289         case LFUN_WORD_FORWARD:
3290         case LFUN_WORD_BACKWARD:
3291         case LFUN_WORD_RIGHT:
3292         case LFUN_WORD_LEFT:
3293         case LFUN_CHAR_FORWARD:
3294         case LFUN_CHAR_FORWARD_SELECT:
3295         case LFUN_CHAR_BACKWARD:
3296         case LFUN_CHAR_BACKWARD_SELECT:
3297         case LFUN_CHAR_LEFT:
3298         case LFUN_CHAR_LEFT_SELECT:
3299         case LFUN_CHAR_RIGHT:
3300         case LFUN_CHAR_RIGHT_SELECT:
3301         case LFUN_UP:
3302         case LFUN_UP_SELECT:
3303         case LFUN_DOWN:
3304         case LFUN_DOWN_SELECT:
3305         case LFUN_PARAGRAPH_UP_SELECT:
3306         case LFUN_PARAGRAPH_DOWN_SELECT:
3307         case LFUN_LINE_BEGIN_SELECT:
3308         case LFUN_LINE_END_SELECT:
3309         case LFUN_WORD_FORWARD_SELECT:
3310         case LFUN_WORD_BACKWARD_SELECT:
3311         case LFUN_WORD_RIGHT_SELECT:
3312         case LFUN_WORD_LEFT_SELECT:
3313         case LFUN_WORD_SELECT:
3314         case LFUN_SECTION_SELECT:
3315         case LFUN_BUFFER_BEGIN:
3316         case LFUN_BUFFER_END:
3317         case LFUN_BUFFER_BEGIN_SELECT:
3318         case LFUN_BUFFER_END_SELECT:
3319         case LFUN_INSET_BEGIN:
3320         case LFUN_INSET_END:
3321         case LFUN_INSET_BEGIN_SELECT:
3322         case LFUN_INSET_END_SELECT:
3323         case LFUN_PARAGRAPH_UP:
3324         case LFUN_PARAGRAPH_DOWN:
3325         case LFUN_LINE_BEGIN:
3326         case LFUN_LINE_END:
3327         case LFUN_CHAR_DELETE_FORWARD:
3328         case LFUN_CHAR_DELETE_BACKWARD:
3329         case LFUN_WORD_UPCASE:
3330         case LFUN_WORD_LOWCASE:
3331         case LFUN_WORD_CAPITALIZE:
3332         case LFUN_CHARS_TRANSPOSE:
3333         case LFUN_SERVER_GET_XY:
3334         case LFUN_SERVER_SET_XY:
3335         case LFUN_SERVER_GET_LAYOUT:
3336         case LFUN_SELF_INSERT:
3337         case LFUN_UNICODE_INSERT:
3338         case LFUN_THESAURUS_ENTRY:
3339         case LFUN_ESCAPE:
3340         case LFUN_SERVER_GET_STATISTICS:
3341                 // these are handled in our dispatch()
3342                 enable = true;
3343                 break;
3344
3345         case LFUN_INSET_INSERT: {
3346                 string const type = cmd.getArg(0);
3347                 if (type == "toc") {
3348                         code = TOC_CODE;
3349                         // not allowed in description items
3350                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
3351                         enable = !inDescriptionItem(cur);
3352                 } else {
3353                         enable = true;
3354                 }
3355                 break;
3356         }
3357
3358         default:
3359                 return false;
3360         }
3361
3362         if (code != NO_CODE
3363             && (cur.empty()
3364                 || !cur.inset().insetAllowed(code)
3365                 || (cur.paragraph().layout().pass_thru && !allow_in_passthru)))
3366                 enable = false;
3367
3368         flag.setEnabled(enable);
3369         return true;
3370 }
3371
3372
3373 void Text::pasteString(Cursor & cur, docstring const & clip,
3374                 bool asParagraphs)
3375 {
3376         if (!clip.empty()) {
3377                 cur.recordUndo();
3378                 if (asParagraphs)
3379                         insertStringAsParagraphs(cur, clip, cur.current_font);
3380                 else
3381                         insertStringAsLines(cur, clip, cur.current_font);
3382         }
3383 }
3384
3385
3386 // FIXME: an item inset would make things much easier.
3387 bool Text::inDescriptionItem(Cursor & cur) const
3388 {
3389         Paragraph & par = cur.paragraph();
3390         pos_type const pos = cur.pos();
3391         pos_type const body_pos = par.beginOfBody();
3392
3393         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
3394             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
3395                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
3396                 return false;
3397
3398         return (pos < body_pos
3399                 || (pos == body_pos
3400                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
3401 }
3402
3403 } // namespace lyx