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