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