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