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