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