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