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