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