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