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