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