]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
two patches from john
[lyx.git] / src / BufferView_pimpl.C
1 #include <config.h>
2
3 #ifdef __GNUG__
4 #pragma implementation
5 #endif
6
7 #include "BufferView_pimpl.h"
8 #include "WorkArea.h"
9 #include "lyxscreen.h"
10 #include "lyxtext.h"
11 #include "lyxrow.h"
12 #include "paragraph.h"
13 #include "LyXView.h"
14 #include "commandtags.h"
15 #include "lyxfunc.h"
16 #include "debug.h"
17 #include "font.h"
18 #include "bufferview_funcs.h"
19 #include "TextCache.h"
20 #include "bufferlist.h"
21 #include "lyx_gui_misc.h"
22 #include "lyxrc.h"
23 #include "intl.h"
24 // added for Dispatch functions
25 #include "lyx_cb.h"
26 #include "lyx_main.h"
27 #include "FloatList.h"
28 #include "gettext.h"
29 #include "ParagraphParameters.h"
30 #include "undo_funcs.h"
31 #include "lyxtextclasslist.h"
32
33 #include "frontends/Dialogs.h"
34 #include "frontends/Alert.h"
35 #include "frontends/FileDialog.h"
36
37 #include "insets/insetbib.h"
38 #include "insets/insettext.h"
39 #include "insets/inseturl.h"
40 #include "insets/insetlatexaccent.h"
41 #include "insets/insettoc.h"
42 #include "insets/insetref.h"
43 #include "insets/insetparent.h"
44 #include "insets/insetindex.h"
45 #include "insets/insetnote.h"
46 #include "insets/insetinclude.h"
47 #include "insets/insetcite.h"
48 #include "insets/insetert.h"
49 #include "insets/insetexternal.h"
50 #include "insets/insetgraphics.h"
51 #include "insets/insetfoot.h"
52 #include "insets/insetmarginal.h"
53 #include "insets/insetminipage.h"
54 #include "insets/insetfloat.h"
55 #include "insets/insettabular.h"
56 #if 0
57 #include "insets/insettheorem.h"
58 #include "insets/insetlist.h"
59 #endif
60 #include "insets/insetcaption.h"
61 #include "insets/insetfloatlist.h"
62 #include "insets/insetspecialchar.h"
63
64 #include "mathed/formulabase.h"
65
66 #include "support/LAssert.h"
67 #include "support/lstrings.h"
68 #include "support/filetools.h"
69 #include "support/lyxfunctional.h"
70
71 #include <ctime>
72 #include <unistd.h>
73 #include <sys/wait.h>
74 #include <clocale>
75
76
77 extern lyx::layout_type current_layout;
78
79 using std::vector;
80 using std::find_if;
81 using std::find;
82 using std::pair;
83 using std::endl;
84 using std::make_pair;
85 using std::min;
86 using SigC::slot;
87
88 using lyx::pos_type;
89 using lyx::layout_type;
90 using lyx::textclass_type;
91
92 /* the selection possible is needed, that only motion events are 
93  * used, where the bottom press event was on the drawing area too */
94 bool selection_possible = false;
95
96 extern BufferList bufferlist;
97 extern char ascii_type;
98
99 extern void sigchldchecker(pid_t pid, int * status);
100 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
101
102
103 namespace {
104
105 const unsigned int saved_positions_num = 20;
106
107 inline
108 void waitForX()
109 {
110         XSync(fl_get_display(), 0);
111 }
112
113
114 void SetXtermCursor(Window win)
115 {
116         static Cursor cursor;
117         static bool cursor_undefined = true;
118         if (cursor_undefined){
119                 cursor = XCreateFontCursor(fl_get_display(), XC_xterm);
120                 XFlush(fl_get_display());
121                 cursor_undefined = false;
122         }
123         XDefineCursor(fl_get_display(), win, cursor);
124         XFlush(fl_get_display());
125 }
126
127 } // anon namespace
128
129
130 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
131              int xpos, int ypos, int width, int height)
132         : bv_(b), owner_(o), buffer_(0),
133           current_scrollbar_value(0), cursor_timeout(400),
134           workarea_(xpos, ypos, width, height), using_xterm_cursor(false),
135           inset_slept(false)
136 {
137         // Setup the signals
138         workarea_.scrollCB.connect(slot(this, &BufferView::Pimpl::scrollCB));
139         workarea_.workAreaExpose
140                 .connect(slot(this, &BufferView::Pimpl::workAreaExpose));
141         workarea_.workAreaEnter
142                 .connect(slot(this, &BufferView::Pimpl::enterView));
143         workarea_.workAreaLeave
144                 .connect(slot(this, &BufferView::Pimpl::leaveView));
145         workarea_.workAreaButtonPress
146                 .connect(slot(this, &BufferView::Pimpl::workAreaButtonPress));
147         workarea_.workAreaButtonRelease
148                 .connect(slot(this,
149                               &BufferView::Pimpl::workAreaButtonRelease));
150         workarea_.workAreaMotionNotify
151                 .connect(slot(this, &BufferView::Pimpl::workAreaMotionNotify));
152         workarea_.workAreaDoubleClick
153                 .connect(slot(this, &BufferView::Pimpl::doubleClick));
154         workarea_.workAreaTripleClick
155                 .connect(slot(this, &BufferView::Pimpl::tripleClick));
156         workarea_.workAreaKeyPress
157                 .connect(slot(this, &BufferView::Pimpl::workAreaKeyPress));
158         workarea_.selectionRequested
159                 .connect(slot(this, &BufferView::Pimpl::selectionRequested)); 
160         
161         cursor_timeout.timeout.connect(slot(this,
162                                             &BufferView::Pimpl::cursorToggle));
163         cursor_timeout.start();
164         workarea_.setFocus();
165         saved_positions.resize(saved_positions_num);
166 }
167
168
169 Painter & BufferView::Pimpl::painter() 
170 {
171         return workarea_.getPainter();
172 }
173
174
175 void BufferView::Pimpl::buffer(Buffer * b)
176 {
177         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
178                             << b << ")" << endl;
179         if (buffer_) {
180                 insetSleep();
181                 buffer_->delUser(bv_);
182
183                 // Put the old text into the TextCache, but
184                 // only if the buffer is still loaded.
185                 // Also set the owner of the test to 0
186                 //              bv_->text->owner(0);
187                 textcache.add(buffer_, workarea_.workWidth(), bv_->text);
188                 if (lyxerr.debugging())
189                         textcache.show(lyxerr, "BufferView::buffer");
190                 
191                 bv_->text = 0;
192         }
193
194         // Set current buffer
195         buffer_ = b;
196
197         if (bufferlist.getState() == BufferList::CLOSING) return;
198         
199         // Nuke old image
200         // screen is always deleted when the buffer is changed.
201         screen_.reset(0);
202
203         // If we are closing the buffer, use the first buffer as current
204         if (!buffer_) {
205                 buffer_ = bufferlist.first();
206         }
207
208         if (buffer_) {
209                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
210                 buffer_->addUser(bv_);
211                 // If we don't have a text object for this, we make one
212                 if (bv_->text == 0) {
213                         resizeCurrentBuffer();
214                 } else {
215                         updateScreen();
216                         updateScrollbar();
217                 }
218                 bv_->text->first = screen_->topCursorVisible(bv_->text);
219                 owner_->updateMenubar();
220                 owner_->updateToolbar();
221                 // Similarly, buffer-dependent dialogs should be updated or
222                 // hidden. This should go here because some dialogs (eg ToC)
223                 // require bv_->text.
224                 owner_->getDialogs()->updateBufferDependent(true);
225                 redraw();
226                 insetWakeup();
227         } else {
228                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
229                 owner_->updateMenubar();
230                 owner_->updateToolbar();
231                 owner_->getDialogs()->hideBufferDependent();
232                 updateScrollbar();
233                 workarea_.redraw();
234
235                 // Also remove all remaining text's from the testcache.
236                 // (there should not be any!) (if there is any it is a
237                 // bug!)
238                 if (lyxerr.debugging())
239                         textcache.show(lyxerr, "buffer delete all");
240                 textcache.clear();
241         }
242         // should update layoutchoice even if we don't have a buffer.
243         owner_->updateLayoutChoice();
244
245         owner_->updateWindowTitle();
246 }
247
248
249 void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
250 {
251         workarea_.resize(xpos, ypos, width, height);
252         update(bv_->text, SELECT);
253         redraw();
254 }
255
256
257 void BufferView::Pimpl::resize()
258 {
259         if (buffer_)
260                 resizeCurrentBuffer();
261 }
262
263
264 void BufferView::Pimpl::redraw()
265 {
266         lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
267         workarea_.redraw();
268 }
269
270
271 bool BufferView::Pimpl::fitCursor()
272 {
273         lyx::Assert(screen_.get());
274
275         bool ret;
276
277         if (bv_->theLockingInset()) {
278                 bv_->theLockingInset()->fitInsetCursor(bv_);
279                 ret = true;
280         } else {
281                 ret = screen_->fitCursor(bv_->text, bv_);
282         }
283
284         bv_->owner()->getDialogs()->updateParagraph();
285         if (ret)
286             updateScrollbar();
287         return ret;
288 }
289
290
291 void BufferView::Pimpl::redoCurrentBuffer()
292 {
293         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
294         if (buffer_ && bv_->text) {
295                 resize();
296                 owner_->updateLayoutChoice();
297         }
298 }
299
300
301 int BufferView::Pimpl::resizeCurrentBuffer()
302 {
303         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
304         
305         Paragraph * par = 0;
306         Paragraph * selstartpar = 0;
307         Paragraph * selendpar = 0;
308         UpdatableInset * the_locking_inset = 0;
309         
310         pos_type pos = 0;
311         pos_type selstartpos = 0;
312         pos_type selendpos = 0;
313         bool selection = false;
314         bool mark_set  = false;
315
316         owner_->prohibitInput();
317
318         owner_->message(_("Formatting document..."));
319
320         if (bv_->text) {
321                 par = bv_->text->cursor.par();
322                 pos = bv_->text->cursor.pos();
323                 selstartpar = bv_->text->selection.start.par();
324                 selstartpos = bv_->text->selection.start.pos();
325                 selendpar = bv_->text->selection.end.par();
326                 selendpos = bv_->text->selection.end.pos();
327                 selection = bv_->text->selection.set();
328                 mark_set = bv_->text->selection.mark();
329                 the_locking_inset = bv_->theLockingInset();
330                 delete bv_->text;
331                 bv_->text = new LyXText(bv_);
332                 bv_->text->init(bv_);
333         } else {
334                 // See if we have a text in TextCache that fits
335                 // the new buffer_ with the correct width.
336                 bv_->text = textcache.findFit(buffer_, workarea_.workWidth());
337                 if (bv_->text) {
338                         if (lyxerr.debugging()) {
339                                 lyxerr << "Found a LyXText that fits:\n";
340                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea_.workWidth(), bv_->text)));
341                         }
342                         // Set the owner of the newly found text
343                         //      bv_->text->owner(bv_);
344                         if (lyxerr.debugging())
345                                 textcache.show(lyxerr, "resizeCurrentBuffer");
346                 } else {
347                         bv_->text = new LyXText(bv_);
348                         bv_->text->init(bv_);
349                 }
350         }
351         updateScreen();
352
353         if (par) {
354                 bv_->text->selection.set(true);
355                 /* at this point just to avoid the Delete-Empty-Paragraph
356                  * Mechanism when setting the cursor */
357                 bv_->text->selection.mark(mark_set);
358                 if (selection) {
359                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
360                         bv_->text->selection.cursor = bv_->text->cursor;
361                         bv_->text->setCursor(bv_, selendpar, selendpos);
362                         bv_->text->setSelection(bv_);
363                         bv_->text->setCursor(bv_, par, pos);
364                 } else {
365                         bv_->text->setCursor(bv_, par, pos);
366                         bv_->text->selection.cursor = bv_->text->cursor;
367                         bv_->text->selection.set(false);
368                 }
369                 // remake the inset locking
370                 bv_->theLockingInset(the_locking_inset);
371         }
372         bv_->text->first = screen_->topCursorVisible(bv_->text);
373 #if 0
374         buffer_->resizeInsets(bv_);
375 #endif
376         // this will scroll the screen such that the cursor becomes visible
377         updateScrollbar();
378         redraw();
379
380         setState();
381         owner_->allowInput();
382
383         /// clear the "Formatting Document" message 
384         owner_->message("");
385
386         return 0;
387 }
388
389
390 void BufferView::Pimpl::updateScreen()
391 {
392         // Regenerate the screen.
393         screen_.reset(new LyXScreen(workarea_));
394 }
395
396
397 void BufferView::Pimpl::updateScrollbar()
398 {
399         /* If the text is smaller than the working area, the scrollbar
400          * maximum must be the working area height. No scrolling will 
401          * be possible */
402         if (!bv_->text) {
403                 workarea_.setScrollbar(0, 1.0);
404                 return;
405         }
406
407         long const text_height = bv_->text->height;
408         long const work_height = workarea_.height();
409
410         if (text_height <= work_height) {
411                 workarea_.setScrollbarBounds(0.0, 0.0);
412                 current_scrollbar_value = bv_->text->first;
413                 workarea_.setScrollbar(current_scrollbar_value, 1.0);
414                 return;
415         }
416         
417         double const lineh = bv_->text->defaultHeight();
418         double const slider_size =
419                 (text_height == 0) ? 1.0 : 1.0 / double(text_height);
420         
421         static long old_text_height;
422         static double old_lineh;
423         static double old_slider_size;
424
425         if (text_height != old_text_height) {
426                 workarea_.setScrollbarBounds(0.0,
427                                              text_height - work_height);
428                 old_text_height = text_height;
429         }
430         if (lineh != old_lineh) {
431                 workarea_.setScrollbarIncrements(lineh);
432                 old_lineh = lineh;
433         }
434         if (current_scrollbar_value != bv_->text->first
435             || slider_size != old_slider_size) {
436                 current_scrollbar_value = bv_->text->first;
437                 workarea_.setScrollbar(current_scrollbar_value, slider_size);
438                 old_slider_size = slider_size;
439         }
440 }
441
442
443 // Callback for scrollbar slider
444 void BufferView::Pimpl::scrollCB(double value)
445 {
446         if (!buffer_) return;
447
448         current_scrollbar_value = long(value);
449
450         if (current_scrollbar_value < 0)
451                 current_scrollbar_value = 0;
452    
453         if (!screen_.get())
454                 return;
455
456         screen_->draw(bv_->text, bv_, current_scrollbar_value);
457
458         if (!lyxrc.cursor_follows_scrollbar) {
459                 waitForX();
460                 return;
461         }
462  
463         LyXText * vbt = bv_->text;
464  
465         int const height = vbt->defaultHeight();
466         int const first = static_cast<int>((bv_->text->first + height));
467         int const last = static_cast<int>((bv_->text->first + workarea_.height() - height));
468
469         if (vbt->cursor.y() < first)
470                 vbt->setCursorFromCoordinates(bv_, 0, first);
471         else if (vbt->cursor.y() > last)
472                 vbt->setCursorFromCoordinates(bv_, 0, last);
473
474         waitForX();
475 }
476
477
478 int BufferView::Pimpl::scrollUp(long time)
479 {
480         if (!buffer_) return 0;
481         if (!screen_.get()) return 0;
482    
483         double value = workarea_.getScrollbarValue();
484    
485         if (value == 0) return 0;
486
487         float add_value =  (bv_->text->defaultHeight()
488                             + float(time) * float(time) * 0.125);
489    
490         if (add_value > workarea_.height())
491                 add_value = float(workarea_.height() -
492                                   bv_->text->defaultHeight());
493    
494         value -= add_value;
495
496         if (value < 0)
497                 value = 0;
498    
499         workarea_.setScrollbarValue(value);
500    
501         scrollCB(value); 
502         return 0;
503 }
504
505
506 int BufferView::Pimpl::scrollDown(long time)
507 {
508         if (!buffer_) return 0;
509         if (!screen_.get()) return 0;
510    
511         double value = workarea_.getScrollbarValue();
512         pair<float, float> p = workarea_.getScrollbarBounds();
513         double const max = p.second;
514         
515         if (value == max) return 0;
516
517         float add_value =  (bv_->text->defaultHeight()
518                             + float(time) * float(time) * 0.125);
519    
520         if (add_value > workarea_.height())
521                 add_value = float(workarea_.height() -
522                                   bv_->text->defaultHeight());
523    
524         value += add_value;
525    
526         if (value > max)
527                 value = max;
528
529         workarea_.setScrollbarValue(value);
530         
531         scrollCB(value); 
532         return 0;
533 }
534
535
536 void BufferView::Pimpl::workAreaKeyPress(KeySym keysym, unsigned int state)
537 {
538         bv_->owner()->getLyXFunc()->processKeySym(keysym, state);
539 }
540
541
542 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
543 {
544         // Only use motion with button 1
545         if (!(state & Button1MotionMask))
546                 return;
547
548         if (!buffer_ || !screen_.get()) return;
549
550         // Check for inset locking
551         if (bv_->theLockingInset()) {
552                 LyXCursor cursor = bv_->text->cursor;
553                 LyXFont font = bv_->text->getFont(buffer_,
554                                                   cursor.par(), cursor.pos());
555                 int width = bv_->theLockingInset()->width(bv_, font);
556                 int inset_x = font.isVisibleRightToLeft()
557                         ? cursor.x() - width : cursor.x();
558                 int start_x = inset_x + bv_->theLockingInset()->scroll();
559                 bv_->theLockingInset()->
560                         insetMotionNotify(bv_,
561                                           x - start_x,
562                                           y - cursor.y() + bv_->text->first,
563                                           state);
564                 return;
565         }
566    
567         /* The test for not selection possible is needed, that only motion
568            events are used, where the bottom press event was on
569            the drawing area too */
570         if (!selection_possible)
571                 return;
572  
573         screen_->hideCursor();
574
575         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first);
576       
577         if (!bv_->text->selection.set())
578                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
579       
580         bv_->text->setSelection(bv_);
581         screen_->toggleToggle(bv_->text, bv_);
582         fitCursor();
583         showCursor();
584 }
585
586
587 // Single-click on work area
588 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
589                                             unsigned int button)
590 {
591         if (!buffer_ || !screen_.get()) return;
592
593         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos);
594
595         // ok ok, this is a hack.
596         if (button == 4 || button == 5) {
597                 switch (button) {
598                 case 4:
599                         scrollUp(lyxrc.wheel_jump); // default 100, set in lyxrc
600                         break;
601                 case 5:
602                         scrollDown(lyxrc.wheel_jump);
603                         break;
604                 }
605         }
606         
607         if (bv_->theLockingInset()) {
608                 // We are in inset locking mode
609                 
610                 /* Check whether the inset was hit. If not reset mode,
611                    otherwise give the event to the inset */
612                 if (inset_hit == bv_->theLockingInset()) {
613                         bv_->theLockingInset()->
614                                 insetButtonPress(bv_,xpos, ypos,button);
615                         return;
616                 } else {
617                         bv_->unlockInset(bv_->theLockingInset());
618                 }
619         }
620         
621         if (!inset_hit)
622                 selection_possible = true;
623         screen_->hideCursor();
624
625         int const screen_first = bv_->text->first;
626         
627         // Middle button press pastes if we have a selection
628         bool paste_internally = false;
629         if (button == 2
630             && bv_->text->selection.set()) {
631                 owner_->getLyXFunc()->dispatch(LFUN_COPY);
632                 paste_internally = true;
633         }
634         
635         // Clear the selection
636         screen_->toggleSelection(bv_->text, bv_);
637         bv_->text->clearSelection();
638         bv_->text->fullRebreak(bv_);
639         update();
640         updateScrollbar();
641         
642         // Single left click in math inset?
643         if (isHighlyEditableInset(inset_hit)) {
644                 // Highly editable inset, like math
645                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
646                 selection_possible = false;
647                 owner_->updateLayoutChoice();
648                 owner_->message(inset->editMessage());
649                 inset->insetButtonPress(bv_, xpos, ypos, button);
650                 inset->edit(bv_, xpos, ypos, button);
651                 return;
652         } 
653         
654         // Right click on a footnote flag opens float menu
655         if (button == 3) { 
656                 selection_possible = false;
657                 return;
658         }
659         
660         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
661                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
662         finishUndo();
663         bv_->text->selection.cursor = bv_->text->cursor;
664         bv_->text->cursor.x_fix(bv_->text->cursor.x());
665         
666         owner_->updateLayoutChoice();
667         if (fitCursor()) {
668                 selection_possible = false;
669         }
670         
671         // Insert primary selection with middle mouse
672         // if there is a local selection in the current buffer,
673         // insert this
674         if (button == 2) {
675                 if (paste_internally)
676                         owner_->getLyXFunc()->dispatch(LFUN_PASTE);
677                 else
678                         owner_->getLyXFunc()->dispatch(LFUN_PASTESELECTION,
679                                                        "paragraph");
680                 selection_possible = false;
681                 return;
682         }
683 }
684
685
686 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, unsigned int button) 
687 {
688         // select a word
689         if (!buffer_)
690                 return;
691
692         LyXText * text = bv_->getLyXText();
693
694         if (text->bv_owner && bv_->theLockingInset())
695                 return;
696
697         if (screen_.get() && button == 1) {
698                 if (text->bv_owner) {
699                         screen_->hideCursor();
700                         screen_->toggleSelection(text, bv_);
701                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
702                         screen_->toggleSelection(text, bv_, false);
703                 } else {
704                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
705                 }
706                 /* This will fit the cursor on the screen
707                  * if necessary */
708                 update(text, BufferView::SELECT|BufferView::FITCUR);
709         }
710 }
711
712
713 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
714 {
715         // select a line
716         if (!buffer_)
717                 return;
718
719         LyXText * text = bv_->getLyXText();
720
721         if (text->bv_owner && bv_->theLockingInset())
722             return;
723
724         if (screen_.get() && (button == 1)) {
725                 if (text->bv_owner) {
726                         screen_->hideCursor();
727                         screen_->toggleSelection(text, bv_);
728                 }
729                 text->cursorHome(bv_);
730                 text->selection.cursor = text->cursor;
731                 text->cursorEnd(bv_);
732                 text->setSelection(bv_);
733                 if (text->bv_owner) {
734                         screen_->toggleSelection(text, bv_, false);
735                 }
736                 /* This will fit the cursor on the screen
737                  * if necessary */
738                 update(text, BufferView::SELECT|BufferView::FITCUR);
739         }
740 }
741
742
743 void BufferView::Pimpl::selectionRequested()
744 {
745         if (!available())
746                 return;
747  
748         string const sel(bv_->getLyXText()->selectionAsString(bv_->buffer(),
749                                                               false)); 
750         if (!sel.empty()) {
751                 workarea_.putClipboard(sel);
752         }
753 }
754
755  
756 void BufferView::Pimpl::enterView()
757 {
758         if (active() && available()) {
759                 SetXtermCursor(workarea_.getWin());
760                 using_xterm_cursor = true;
761         }
762 }
763
764
765 void BufferView::Pimpl::leaveView()
766 {
767         if (using_xterm_cursor) {
768                 XUndefineCursor(fl_get_display(), workarea_.getWin());
769                 using_xterm_cursor = false;
770         }
771 }
772
773
774 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
775                                               unsigned int button)
776 {
777         if (!buffer_ || !screen_.get()) return;
778
779         // If we hit an inset, we have the inset coordinates in these
780         // and inset_hit points to the inset.  If we do not hit an
781         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
782         Inset * inset_hit = checkInsetHit(bv_->text, x, y);
783
784         if (bv_->theLockingInset()) {
785                 // We are in inset locking mode.
786
787                 /* LyX does a kind of work-area grabbing for insets.
788                    Only a ButtonPress Event outside the inset will 
789                    force a insetUnlock. */
790                 bv_->theLockingInset()->
791                         insetButtonRelease(bv_, x, y, button);
792                 return;
793         }
794         
795         selection_possible = false;
796         
797         if (button == 2)
798                 return;
799
800         // finish selection
801         if (button == 1) {
802                 workarea_.haveSelection(bv_->getLyXText()->selection.set());
803         }
804  
805         setState();
806         owner_->showState();
807         owner_->updateMenubar();
808         owner_->updateToolbar();
809
810         // Did we hit an editable inset?
811         if (inset_hit) {
812                 // Inset like error, notes and figures
813                 selection_possible = false;
814
815                 // if we reach this point with a selection, it
816                 // must mean we are currently selecting.
817                 // But we don't want to open the inset
818                 // because that is annoying for the user. 
819                 // So just pretend we didn't hit it.
820                 // this is OK because a "kosher" ButtonRelease
821                 // will follow a ButtonPress that clears
822                 // the selection.
823                 // Note this also fixes selection drawing
824                 // problems if we end up opening an inset
825                 if (bv_->getLyXText()->selection.set())
826                         return;
827  
828                 // CHECK fix this proper in 0.13
829                 // well, maybe 13.0 !!!!!!!!!
830
831                 // Following a ref shouldn't issue
832                 // a push on the undo-stack
833                 // anylonger, now that we have
834                 // keybindings for following
835                 // references and returning from
836                 // references.  IMHO though, it
837                 // should be the inset's own business
838                 // to push or not push on the undo
839                 // stack. They don't *have* to
840                 // alter the document...
841                 // (Joacim)
842                 // ...or maybe the SetCursorParUndo()
843                 // below isn't necessary at all anylonger?
844                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
845                         setCursorParUndo(bv_);
846                 }
847
848                 owner_->message(inset_hit->editMessage());
849
850                 if (isHighlyEditableInset(inset_hit)) {
851                         // Highly editable inset, like math
852                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
853                         inset->insetButtonRelease(bv_, x, y, button);
854                 } else {
855                         inset_hit->insetButtonRelease(bv_, x, y, button);
856                         inset_hit->edit(bv_, x, y, button);
857                 }
858                 return;
859         }
860
861         // Maybe we want to edit a bibitem ale970302
862         if (bv_->text->cursor.par()->bibkey && x < 20 + 
863             bibitemMaxWidth(bv_, textclasslist.
864                             TextClass(buffer_->
865                                       params.textclass).defaultfont())) {
866                 bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, 0);
867         }
868
869         return;
870 }
871
872
873 Box BufferView::Pimpl::insetDimensions(LyXText const & text,
874                                        LyXCursor const & cursor) const
875 {
876         Paragraph /*const*/ & par = *cursor.par();
877         pos_type const pos = cursor.pos();
878
879         lyx::Assert(par.getInset(pos));
880  
881         Inset const & inset(*par.getInset(pos));
882
883         LyXFont const & font = text.getFont(buffer_, &par, pos);
884  
885         int const width = inset.width(bv_, font);
886         int const inset_x = font.isVisibleRightToLeft()
887                 ? (cursor.x() - width) : cursor.x();
888  
889         return Box(
890                 inset_x + inset.scroll(),
891                 inset_x + width,
892                 cursor.y() - inset.ascent(bv_, font),
893                 cursor.y() + inset.descent(bv_, font));
894 }
895  
896  
897 Inset * BufferView::Pimpl::checkInset(LyXText const & text,
898                                       LyXCursor const & cursor,
899                                       int & x, int & y) const
900 {
901         pos_type const pos(cursor.pos());
902         Paragraph /*const*/ & par(*cursor.par());
903
904         if (pos >= par.size() || !par.isInset(pos)) {
905                 return 0;
906         }
907
908         Inset /*const*/ * inset = par.getInset(pos);
909  
910         if (!isEditableInset(inset)) {
911                 return 0;
912         }
913
914         Box b(insetDimensions(text, cursor));
915
916         if (!b.contained(x, y)) {
917                 lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y 
918                         << " box " << b << endl;
919                 return 0;
920         }
921  
922         text.setCursor(bv_, &par, pos, true);
923  
924         x -= b.x1;
925         // The origin of an inset is on the baseline
926         y -= (text.cursor.y());
927   
928         return inset;
929 }
930
931  
932 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y)
933 {
934         if (!screen_.get())
935                 return 0;
936   
937         int y_tmp = y + text->first;
938  
939         LyXCursor cursor;
940         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
941  
942         Inset * inset(checkInset(*text, cursor, x, y_tmp));
943
944         if (inset) {
945                 y = y_tmp;
946                 return inset;
947         }
948  
949         // look at previous position
950  
951         if (cursor.pos() == 0) {
952                 return 0;
953         }
954
955         // move back one
956         text->setCursor(bv_, cursor, cursor.par(), cursor.pos() - 1, true);
957
958         inset = checkInset(*text, cursor, x, y_tmp);
959         if (inset) {
960                 y = y_tmp;
961         }
962         return inset;
963 }
964
965
966 void BufferView::Pimpl::workAreaExpose()
967 {
968         static int work_area_width;
969         static unsigned int work_area_height;
970
971         bool const widthChange = workarea_.workWidth() != work_area_width;
972         bool const heightChange = workarea_.height() != work_area_height;
973
974         // update from work area
975         work_area_width = workarea_.workWidth();
976         work_area_height = workarea_.height();
977         if (buffer_ != 0) {
978                 if (widthChange) {
979                         // The visible LyXView need a resize
980                         owner_->resize();
981
982                         // Remove all texts from the textcache
983                         // This is not _really_ what we want to do. What
984                         // we really want to do is to delete in textcache
985                         // that does not have a BufferView with matching
986                         // width, but as long as we have only one BufferView
987                         // deleting all gives the same result.
988                         if (lyxerr.debugging())
989                                 textcache.show(lyxerr, "Expose delete all");
990                         textcache.clear();
991                 } else if (heightChange) {
992                         // Rebuild image of current screen
993                         updateScreen();
994                         // fitCursor() ensures we don't jump back
995                         // to the start of the document on vertical
996                         // resize
997                         fitCursor();
998
999                         // The main window size has changed, repaint most stuff
1000                         redraw();
1001                 } else if (screen_.get())
1002                     screen_->redraw(bv_->text, bv_);
1003         } else {
1004                 // Grey box when we don't have a buffer
1005                 workarea_.greyOut();
1006         }
1007
1008         // always make sure that the scrollbar is sane.
1009         updateScrollbar();
1010         owner_->updateLayoutChoice();
1011         return;
1012 }
1013
1014
1015 void BufferView::Pimpl::update()
1016 {
1017         if (screen_.get() &&
1018                 (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()))
1019         {
1020                 LyXText::text_status st = bv_->text->status();
1021                 screen_->update(bv_->text, bv_);
1022                 bool fitc = false;
1023                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
1024                         if (bv_->text->fullRebreak(bv_)) {
1025                                 st = LyXText::NEED_MORE_REFRESH;
1026                                 bv_->text->setCursor(bv_, bv_->text->cursor.par(),
1027                                                                          bv_->text->cursor.pos());
1028                                 fitc = true;
1029                         }
1030                         bv_->text->status(bv_, st);
1031                         screen_->update(bv_->text, bv_);
1032                 }
1033                 // do this here instead of in the screen::update because of
1034                 // the above loop!
1035                 bv_->text->status(bv_, LyXText::UNCHANGED);
1036                 if (fitc)
1037                         fitCursor();
1038         }
1039 }
1040
1041 // Values used when calling update:
1042 // -3 - update
1043 // -2 - update, move sel_cursor if selection, fitcursor
1044 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
1045 //  0 - update, move sel_cursor if selection, fitcursor 
1046 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
1047 //  3 - update, move sel_cursor if selection
1048 //
1049 // update -
1050 // a simple redraw of the parts that need refresh
1051 //
1052 // move sel_cursor if selection -
1053 // the text's sel_cursor is moved if there is selection is progress
1054 //
1055 // fitcursor -
1056 // fitCursor() is called and the scrollbar updated
1057 //
1058 // mark dirty -
1059 // the buffer is marked dirty.
1060 //
1061 // enum {
1062 //       UPDATE = 0,
1063 //       SELECT = 1,
1064 //       FITCUR = 2,
1065 //       CHANGE = 4 
1066 // };
1067 //
1068 // UPDATE_ONLY = UPDATE;
1069 // UPDATE_SELECT = UPDATE | SELECT;
1070 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1071 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1072 //
1073 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1074 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1075 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1076 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1077 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1078
1079 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1080 {
1081         owner_->updateLayoutChoice();
1082
1083         if (!text->selection.set() && (f & SELECT)) {
1084                 text->selection.cursor = text->cursor;
1085         }
1086
1087         text->fullRebreak(bv_);
1088
1089         if (text->inset_owner) {
1090                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1091             updateInset(text->inset_owner, false);
1092         } else {
1093             update();
1094         }
1095                 
1096         if ((f & FITCUR)) {
1097                 fitCursor();
1098         }
1099
1100         if ((f & CHANGE)) {
1101                 buffer_->markDirty();
1102         }
1103 }
1104
1105
1106 // Callback for cursor timer
1107 void BufferView::Pimpl::cursorToggle()
1108 {
1109         // Quite a nice place for asyncron Inset updating, isn't it?
1110         // Actually no! This is run even if no buffer exist... so (Lgb)
1111         if (!buffer_) {
1112                 cursor_timeout.restart();
1113                 return;
1114         }
1115  
1116         int status = 1;
1117         int const pid = waitpid(static_cast<pid_t>(0), &status, WNOHANG);
1118         if (pid == -1) // error find out what is wrong
1119                 ; // ignore it for now.
1120         else if (pid > 0)
1121                 sigchldchecker(pid, &status);
1122
1123         updatelist.update(bv_);
1124         
1125         if (!screen_.get()) {
1126                 cursor_timeout.restart();
1127                 return;
1128         }
1129
1130         if (!bv_->theLockingInset()) {
1131                 screen_->cursorToggle(bv_);
1132         } else {
1133                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1134         }
1135         
1136         cursor_timeout.restart();
1137 }
1138
1139
1140 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1141 {
1142         if (!text->cursor.row()->previous())
1143                 return;
1144         
1145         int y = text->first;
1146         if (text->inset_owner)
1147                 y += bv_->text->first;
1148         Row * cursorrow = text->cursor.row();
1149         text->setCursorFromCoordinates(bv_, bv_->text->cursor.x_fix(), y);
1150         finishUndo();
1151         // This is to allow jumping over large insets
1152         if ((cursorrow == text->cursor.row()))
1153                 text->cursorUp(bv_);
1154         
1155         if (text->inset_owner ||
1156             text->cursor.row()->height() < workarea_.height())
1157                 screen_->draw(bv_->text, bv_,
1158                               text->cursor.y()
1159                               - text->cursor.row()->baseline()
1160                               + text->cursor.row()->height()
1161                               - workarea_.height() + 1 );
1162         updateScrollbar();
1163 }
1164
1165
1166 void BufferView::Pimpl::cursorNext(LyXText * text)
1167 {
1168         if (!text->cursor.row()->next())
1169                 return;
1170         
1171         int y = text->first + workarea_.height();
1172 //      if (text->inset_owner)
1173 //              y += bv_->text->first;
1174         text->getRowNearY(y);
1175     
1176         Row * cursorrow = text->cursor.row();
1177         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea_->height());
1178         finishUndo();
1179         // This is to allow jumping over large insets
1180         if ((cursorrow == bv_->text->cursor.row()))
1181                 text->cursorDown(bv_);
1182         
1183         if (text->inset_owner ||
1184             text->cursor.row()->height() < workarea_.height())
1185                 screen_->draw(bv_->text, bv_, text->cursor.y() -
1186                               text->cursor.row()->baseline());
1187         updateScrollbar();
1188 }
1189
1190
1191 bool BufferView::Pimpl::available() const
1192 {
1193         if (buffer_ && bv_->text) return true;
1194         return false;
1195 }
1196
1197
1198 void BufferView::Pimpl::beforeChange(LyXText * text)
1199 {
1200         toggleSelection();
1201         text->clearSelection();
1202 }
1203
1204
1205 void BufferView::Pimpl::savePosition(unsigned int i)
1206 {
1207         if (i >= saved_positions_num)
1208                 return;
1209         saved_positions[i] = Position(buffer_->fileName(),
1210                                       bv_->text->cursor.par()->id(),
1211                                       bv_->text->cursor.pos());
1212         if (i > 0) {
1213                 ostringstream str;
1214                 str << _("Saved bookmark") << ' ' << i;
1215                 owner_->message(str.str().c_str());
1216         }
1217 }
1218
1219
1220 void BufferView::Pimpl::restorePosition(unsigned int i)
1221 {
1222         if (i >= saved_positions_num)
1223                 return;
1224
1225         string const fname = saved_positions[i].filename;
1226
1227         beforeChange(bv_->text);
1228
1229         if (fname != buffer_->fileName()) {
1230                 Buffer * b = bufferlist.exists(fname) ?
1231                         bufferlist.getBuffer(fname) :
1232                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1233                 if (b != 0 ) buffer(b);
1234         }
1235
1236         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1237         if (!par)
1238                 return;
1239
1240         bv_->text->setCursor(bv_, par,
1241                              min(par->size(), saved_positions[i].par_pos));
1242
1243         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1244         if (i > 0) {
1245                 ostringstream str;
1246                 str << _("Moved to bookmark") << ' ' << i;
1247                 owner_->message(str.str().c_str());
1248         }
1249 }
1250
1251
1252 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1253 {
1254         if (i >= saved_positions_num)
1255                 return false;
1256
1257         return !saved_positions[i].filename.empty();
1258 }
1259
1260
1261 void BufferView::Pimpl::setState()
1262 {
1263         if (!lyxrc.rtl_support)
1264                 return;
1265
1266         LyXText * text = bv_->getLyXText();
1267         if (text->real_current_font.isRightToLeft()) {
1268                 if (owner_->getIntl()->keymap == Intl::PRIMARY)
1269                         owner_->getIntl()->KeyMapSec();
1270         } else {
1271                 if (owner_->getIntl()->keymap == Intl::SECONDARY)
1272                         owner_->getIntl()->KeyMapPrim();
1273         }
1274 }
1275
1276
1277 void BufferView::Pimpl::insetSleep()
1278 {
1279         if (bv_->theLockingInset() && !inset_slept) {
1280                 bv_->theLockingInset()->getCursorPos(bv_, bv_->slx, bv_->sly);
1281                 bv_->theLockingInset()->insetUnlock(bv_);
1282                 inset_slept = true;
1283         }
1284 }
1285
1286
1287 void BufferView::Pimpl::insetWakeup()
1288 {
1289         if (bv_->theLockingInset() && inset_slept) {
1290                 bv_->theLockingInset()->edit(bv_, bv_->slx, bv_->sly, 0);
1291                 inset_slept = false;
1292         }
1293 }
1294
1295
1296 void BufferView::Pimpl::insetUnlock()
1297 {
1298         if (bv_->theLockingInset()) {
1299                 if (!inset_slept)
1300                         bv_->theLockingInset()->insetUnlock(bv_);
1301                 bv_->theLockingInset(0);
1302                 finishUndo();
1303                 inset_slept = false;
1304         }
1305 }
1306
1307
1308 bool BufferView::Pimpl::focus() const
1309 {
1310         return workarea_.hasFocus();
1311 }
1312
1313
1314 void BufferView::Pimpl::focus(bool f)
1315 {
1316         if (f) workarea_.setFocus();
1317 }
1318
1319
1320 bool BufferView::Pimpl::active() const
1321 {
1322         return workarea_.active();
1323 }
1324
1325
1326 bool BufferView::Pimpl::belowMouse() const 
1327 {
1328         return workarea_.belowMouse();
1329 }
1330
1331
1332 void BufferView::Pimpl::showCursor()
1333 {
1334         if (screen_.get()) {
1335                 if (bv_->theLockingInset())
1336                         bv_->theLockingInset()->showInsetCursor(bv_);
1337                 else
1338                         screen_->showCursor(bv_->text, bv_);
1339         }
1340 }
1341
1342
1343 void BufferView::Pimpl::hideCursor()
1344 {
1345         if (screen_.get()) {
1346                 if (!bv_->theLockingInset())
1347 //                      bv_->theLockingInset()->hideInsetCursor(bv_);
1348 //              else
1349                         screen_->hideCursor();
1350         }
1351 }
1352
1353
1354 void BufferView::Pimpl::toggleSelection(bool b)
1355 {
1356         if (screen_.get()) {
1357                 if (bv_->theLockingInset())
1358                         bv_->theLockingInset()->toggleSelection(bv_, b);
1359                 screen_->toggleSelection(bv_->text, bv_, b);
1360         }
1361 }
1362
1363
1364 void BufferView::Pimpl::toggleToggle()
1365 {
1366         if (screen_.get())
1367                 screen_->toggleToggle(bv_->text, bv_);
1368 }
1369
1370
1371 void BufferView::Pimpl::center() 
1372 {
1373         beforeChange(bv_->text);
1374         if (bv_->text->cursor.y() > static_cast<int>((workarea_.height() / 2))) {
1375                 screen_->draw(bv_->text, bv_, bv_->text->cursor.y() - workarea_.height() / 2);
1376         } else {
1377                 screen_->draw(bv_->text, bv_, 0);
1378         }
1379         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1380         redraw();
1381 }
1382
1383
1384 void BufferView::Pimpl::pasteClipboard(bool asPara) 
1385 {
1386         if (!buffer_) return;
1387
1388         screen_->hideCursor();
1389         beforeChange(bv_->text);
1390         
1391         string const clip(workarea_.getClipboard());
1392         
1393         if (clip.empty()) return;
1394
1395         if (asPara) {
1396                 bv_->getLyXText()->insertStringAsParagraphs(bv_, clip);
1397         } else {
1398                 bv_->getLyXText()->insertStringAsLines(bv_, clip);
1399         }
1400         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1401 }
1402
1403
1404 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1405 {
1406         workarea_.putClipboard(stuff);
1407 }
1408
1409
1410 /*
1411  * Dispatch functions for actions which can be valid for BufferView->text
1412  * and/or InsetText->text!!!
1413  */
1414
1415
1416 inline
1417 void BufferView::Pimpl::moveCursorUpdate(bool selecting)
1418 {
1419         LyXText * lt = bv_->getLyXText();
1420         
1421         if (selecting || lt->selection.mark()) {
1422                 lt->setSelection(bv_);
1423                 if (lt->bv_owner)
1424                         toggleToggle();
1425         }
1426         update(lt, BufferView::SELECT|BufferView::FITCUR);
1427         showCursor();
1428         
1429         /* ---> Everytime the cursor is moved, show the current font state. */
1430         // should this too me moved out of this func?
1431         //owner->showState();
1432         setState();
1433 }
1434
1435
1436 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1437 {
1438         LyXCursor cursor = bv_->getLyXText()->cursor;
1439         Buffer::inset_iterator it =
1440                 find_if(Buffer::inset_iterator(
1441                         cursor.par(), cursor.pos()),
1442                         buffer_->inset_iterator_end(),
1443                         lyx::compare_memfun(&Inset::lyxCode, code));
1444         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1445 }
1446
1447
1448 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1449 {
1450         string filename = filen;
1451
1452         if (filename.empty()) {
1453                 // Launch a file browser
1454                 string initpath = lyxrc.document_path;
1455
1456                 if (available()) {
1457                         string const trypath = owner_->buffer()->filePath();
1458                         // If directory is writeable, use this as default.
1459                         if (IsDirWriteable(trypath))
1460                                 initpath = trypath;
1461                 }
1462
1463                 FileDialog fileDlg(bv_->owner(),
1464                                    _("Select LyX document to insert"),
1465                         LFUN_FILE_INSERT,
1466                         make_pair(string(_("Documents|#o#O")),
1467                                   string(lyxrc.document_path)),
1468                         make_pair(string(_("Examples|#E#e")),
1469                                   string(AddPath(system_lyxdir, "examples"))));
1470
1471                 FileDialog::Result result =
1472                         fileDlg.Select(initpath,
1473                                        _("*.lyx| LyX Documents (*.lyx)"));
1474  
1475                 if (result.first == FileDialog::Later)
1476                         return;
1477
1478                 filename = result.second;
1479
1480                 // check selected filename
1481                 if (filename.empty()) {
1482                         owner_->message(_("Canceled."));
1483                         return;
1484                 }
1485         }
1486
1487         // get absolute path of file and add ".lyx" to the filename if
1488         // necessary
1489         filename = FileSearch(string(), filename, "lyx");
1490
1491         string const disp_fn(MakeDisplayPath(filename));
1492         
1493         ostringstream s1;
1494         s1 << _("Inserting document") << ' '
1495            << disp_fn << " ...";
1496         owner_->message(s1.str().c_str());
1497         bool const res = bv_->insertLyXFile(filename);
1498         if (res) {
1499                 ostringstream str;
1500                 str << _("Document") << ' ' << disp_fn
1501                     << ' ' << _("inserted.");
1502                 owner_->message(str.str().c_str());
1503         } else {
1504                 ostringstream str;
1505                 str << _("Could not insert document") << ' '
1506                     << disp_fn;
1507                 owner_->message(str.str().c_str());
1508         }
1509 }
1510
1511
1512 bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
1513 {
1514         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1515                               << action <<"] arg[" << argument << "]" << endl;
1516         
1517         switch (action) {
1518                 // --- Misc -------------------------------------------
1519         case LFUN_APPENDIX:
1520         {
1521                 if (available()) {
1522                         LyXText * lt = bv_->getLyXText();
1523                         lt->toggleAppendix(bv_);
1524                         update(lt,
1525                                BufferView::SELECT
1526                                | BufferView::FITCUR
1527                                | BufferView::CHANGE);
1528                 }
1529         }
1530         break;
1531
1532         case LFUN_TOC_INSERT:
1533         {
1534                 InsetCommandParams p;
1535                 p.setCmdName("tableofcontents");
1536                 Inset * inset = new InsetTOC(p);
1537                 if (!insertInset(inset, "Standard"))
1538                         delete inset;
1539                 break;
1540         }
1541                 
1542         case LFUN_TABULAR_FEATURE:
1543         case LFUN_SCROLL_INSET:
1544                 // this is not handled here as this funktion is only aktive
1545                 // if we have a locking_inset and that one is (or contains)
1546                 // a tabular-inset
1547                 break;
1548
1549         case LFUN_INSET_GRAPHICS:
1550         {
1551                 Inset * new_inset = new InsetGraphics;
1552                 if (!insertInset(new_inset)) {
1553                         delete new_inset;
1554                 } else {
1555                         // this is need because you don't use a inset->Edit()
1556                         updateInset(new_inset, true);
1557                         new_inset->edit(bv_);
1558                 }
1559                 break;
1560         }
1561                 
1562         case LFUN_PASTE:
1563                 bv_->paste();
1564                 setState();
1565                 break;
1566                 
1567         case LFUN_PASTESELECTION:
1568         {
1569                 bool asPara = false;
1570                 if (argument == "paragraph")
1571                         asPara = true;
1572                 pasteClipboard(asPara);
1573         }
1574         break;
1575         
1576         case LFUN_CUT:
1577                 bv_->cut();
1578                 break;
1579                 
1580         case LFUN_COPY:
1581                 bv_->copy();
1582                 break;
1583                 
1584         case LFUN_LAYOUT_COPY:
1585                 bv_->copyEnvironment();
1586                 break;
1587                 
1588         case LFUN_LAYOUT_PASTE:
1589                 bv_->pasteEnvironment();
1590                 setState();
1591                 break;
1592                 
1593         case LFUN_GOTOERROR:
1594                 gotoInset(Inset::ERROR_CODE, false);
1595                 break;
1596                 
1597         case LFUN_GOTONOTE:
1598                 gotoInset(Inset::IGNORE_CODE, false);
1599                 break;
1600
1601         case LFUN_REFERENCE_GOTO:
1602         {
1603                 vector<Inset::Code> tmp;
1604                 tmp.push_back(Inset::LABEL_CODE);
1605                 tmp.push_back(Inset::REF_CODE);
1606                 gotoInset(tmp, true);
1607                 break;
1608         }
1609
1610         case LFUN_HYPHENATION:
1611                 specialChar(InsetSpecialChar::HYPHENATION);
1612                 break;
1613                 
1614         case LFUN_LIGATURE_BREAK:
1615                 specialChar(InsetSpecialChar::LIGATURE_BREAK);
1616                 break;
1617                 
1618         case LFUN_LDOTS:
1619                 specialChar(InsetSpecialChar::LDOTS);
1620                 break;
1621                 
1622         case LFUN_END_OF_SENTENCE:
1623                 specialChar(InsetSpecialChar::END_OF_SENTENCE);
1624                 break;
1625
1626         case LFUN_MENU_SEPARATOR:
1627                 specialChar(InsetSpecialChar::MENU_SEPARATOR);
1628                 break;
1629                 
1630         case LFUN_HFILL:
1631                 hfill();
1632                 break;
1633                 
1634         case LFUN_DEPTH:
1635                 changeDepth(bv_, bv_->getLyXText(), 0);
1636                 break;
1637                 
1638         case LFUN_DEPTH_MIN:
1639                 changeDepth(bv_, bv_->getLyXText(), -1);
1640                 break;
1641                 
1642         case LFUN_DEPTH_PLUS:
1643                 changeDepth(bv_, bv_->getLyXText(), 1);
1644                 break;
1645                 
1646         case LFUN_FREE:
1647                 owner_->getDialogs()->setUserFreeFont();
1648                 break;
1649
1650         case LFUN_FILE_INSERT:
1651                 MenuInsertLyXFile(argument);
1652                 break;
1653         
1654         case LFUN_FILE_INSERT_ASCII_PARA:
1655                 InsertAsciiFile(bv_, argument, true);
1656                 break;
1657
1658         case LFUN_FILE_INSERT_ASCII:
1659                 InsertAsciiFile(bv_, argument, false);
1660                 break;
1661                 
1662         case LFUN_LAYOUT:
1663         {
1664                 lyxerr[Debug::INFO] << "LFUN_LAYOUT: (arg) "
1665                                     << argument << endl;
1666                 
1667                 // Derive layout number from given argument (string)
1668                 // and current buffer's textclass (number). */    
1669                 textclass_type tclass = buffer_->params.textclass;
1670                 pair <bool, layout_type> layout = 
1671                         textclasslist.NumberOfLayout(tclass, argument);
1672
1673                 // If the entry is obsolete, use the new one instead.
1674                 if (layout.first) {
1675                         string obs = textclasslist.Style(tclass, layout.second)
1676                                 .obsoleted_by();
1677                         if (!obs.empty()) 
1678                                 layout = textclasslist.NumberOfLayout(tclass, obs);
1679                 }
1680
1681                 // see if we found the layout number:
1682                 if (!layout.first) {
1683                         owner_->getLyXFunc()->setErrorMessage(
1684                                 string(N_("Layout ")) + argument +
1685                                 N_(" not known"));
1686                         break;
1687                 }
1688
1689                 if (current_layout != layout.second) {
1690                         LyXText * lt = bv_->getLyXText();
1691                         hideCursor();
1692                         current_layout = layout.second;
1693                         update(lt,
1694                                BufferView::SELECT
1695                                | BufferView::FITCUR);
1696                         lt->setLayout(bv_, layout.second);
1697                         owner_->setLayout(layout.second);
1698                         update(lt,
1699                                BufferView::SELECT
1700                                | BufferView::FITCUR
1701                                | BufferView::CHANGE);
1702                         setState();
1703                 }
1704         }
1705         break;
1706
1707         case LFUN_LANGUAGE:
1708                 lang(bv_, argument);
1709                 setState();
1710                 owner_->showState();
1711                 break;
1712
1713         case LFUN_EMPH:
1714                 emph(bv_);
1715                 owner_->showState();
1716                 break;
1717
1718         case LFUN_BOLD:
1719                 bold(bv_);
1720                 owner_->showState();
1721                 break;
1722                 
1723         case LFUN_NOUN:
1724                 noun(bv_);
1725                 owner_->showState();
1726                 break;
1727                 
1728         case LFUN_CODE:
1729                 code(bv_);
1730                 owner_->showState();
1731                 break;
1732                 
1733         case LFUN_SANS:
1734                 sans(bv_);
1735                 owner_->showState();
1736                 break;
1737                 
1738         case LFUN_ROMAN:
1739                 roman(bv_);
1740                 owner_->showState();
1741                 break;
1742                 
1743         case LFUN_DEFAULT:
1744                 styleReset(bv_);
1745                 owner_->showState();
1746                 break;
1747                 
1748         case LFUN_UNDERLINE:
1749                 underline(bv_);
1750                 owner_->showState();
1751                 break;
1752                 
1753         case LFUN_FONT_SIZE:
1754                 fontSize(bv_, argument);
1755                 owner_->showState();
1756                 break;
1757                 
1758         case LFUN_FONT_STATE:
1759                 owner_->getLyXFunc()->setMessage(currentState(bv_));
1760                 break;
1761                 
1762         case LFUN_UPCASE_WORD:
1763         {
1764                 LyXText * lt = bv_->getLyXText();
1765                 
1766                 update(lt,
1767                        BufferView::SELECT
1768                        | BufferView::FITCUR);
1769                 lt->changeCase(bv_, LyXText::text_uppercase);
1770                 if (lt->inset_owner)
1771                         updateInset(lt->inset_owner, true);
1772                 update(lt,
1773                        BufferView::SELECT
1774                        | BufferView::FITCUR
1775                        | BufferView::CHANGE);
1776         }
1777         break;
1778                 
1779         case LFUN_LOWCASE_WORD:
1780         {
1781                 LyXText * lt = bv_->getLyXText();
1782                 
1783                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1784                 lt->changeCase(bv_, LyXText::text_lowercase);
1785                 if (lt->inset_owner)
1786                         updateInset(lt->inset_owner, true);
1787                 update(lt,
1788                        BufferView::SELECT
1789                        | BufferView::FITCUR
1790                        | BufferView::CHANGE);
1791         }
1792         break;
1793                 
1794         case LFUN_CAPITALIZE_WORD:
1795         {
1796                 LyXText * lt = bv_->getLyXText();
1797                 
1798                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1799                 lt->changeCase(bv_, LyXText::text_capitalization);
1800                 if (lt->inset_owner)
1801                         updateInset(lt->inset_owner, true);
1802                 update(lt,
1803                        BufferView::SELECT
1804                        | BufferView::FITCUR
1805                        | BufferView::CHANGE);
1806         }
1807         break;
1808
1809         case LFUN_TRANSPOSE_CHARS:
1810         {
1811                 LyXText * lt = bv_->getLyXText();
1812                 
1813                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1814                 lt->transposeChars(*bv_);
1815                 if (lt->inset_owner)
1816                         updateInset(lt->inset_owner, true);
1817                 update(lt,
1818                        BufferView::SELECT
1819                        | BufferView::FITCUR
1820                        | BufferView::CHANGE);
1821         }
1822         break;
1823                 
1824                                           
1825         case LFUN_INSERT_LABEL:
1826                 MenuInsertLabel(bv_, argument);
1827                 break;
1828
1829         case LFUN_REF_INSERT:
1830                 if (argument.empty()) {
1831                         InsetCommandParams p("ref");
1832                         owner_->getDialogs()->createRef(p.getAsString());
1833                 } else {
1834                         InsetCommandParams p;
1835                         p.setFromString(argument);
1836
1837                         InsetRef * inset = new InsetRef(p, *buffer_);
1838                         if (!insertInset(inset))
1839                                 delete inset;
1840                         else
1841                                 updateInset(inset, true);
1842                 }
1843                 break;
1844
1845         case LFUN_BOOKMARK_SAVE:
1846                 savePosition(strToUnsignedInt(argument));
1847                 break;
1848
1849         case LFUN_BOOKMARK_GOTO:
1850                 restorePosition(strToUnsignedInt(argument));
1851                 break;
1852
1853         case LFUN_REF_GOTO:
1854         {
1855                 string label(argument);
1856                 if (label.empty()) {
1857                         InsetRef * inset = 
1858                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1859                         if (inset) {
1860                                 label = inset->getContents();
1861                                 savePosition(0);
1862                         }
1863                 }
1864                 
1865                 if (!label.empty()) {
1866                         //bv_->savePosition(0);
1867                         if (!bv_->gotoLabel(label))
1868                                 Alert::alert(_("Error"), 
1869                                            _("Couldn't find this label"), 
1870                                            _("in current document."));
1871                 }
1872         }
1873         break;
1874                 
1875                 // --- Cursor Movements -----------------------------
1876         case LFUN_RIGHT:
1877         {
1878                 LyXText * lt = bv_->getLyXText();
1879                 
1880                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1881                 if (!lt->selection.mark())
1882                         beforeChange(lt);
1883                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1884                 if (is_rtl)
1885                         lt->cursorLeft(bv_, false);
1886                 if (lt->cursor.pos() < lt->cursor.par()->size()
1887                     && lt->cursor.par()->isInset(lt->cursor.pos())
1888                     && isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1889                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1890                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1891                         if (is_rtl)
1892                                 tmpinset->edit(bv_, false);
1893                         else
1894                                 tmpinset->edit(bv_);
1895                         break;
1896                 }
1897                 if (!is_rtl)
1898                         lt->cursorRight(bv_, false);
1899                 finishUndo();
1900                 moveCursorUpdate(false);
1901                 owner_->showState();
1902         }
1903         break;
1904                 
1905         case LFUN_LEFT:
1906         {
1907                 // This is soooo ugly. Isn`t it possible to make
1908                 // it simpler? (Lgb)
1909                 LyXText * lt = bv_->getLyXText();
1910                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1911                 if (!lt->selection.mark())
1912                         beforeChange(lt);
1913                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1914                 LyXCursor const cur = lt->cursor;
1915                 if (!is_rtl)
1916                         lt->cursorLeft(bv_, false);
1917                 if ((is_rtl || cur != lt->cursor) && // only if really moved!
1918                     lt->cursor.pos() < lt->cursor.par()->size() &&
1919                     lt->cursor.par()->isInset(lt->cursor.pos()) &&
1920                     isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1921                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1922                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1923                         if (is_rtl)
1924                                 tmpinset->edit(bv_);
1925                         else
1926                                 tmpinset->edit(bv_, false);
1927                         break;
1928                 }
1929                 if  (is_rtl)
1930                         lt->cursorRight(bv_, false);
1931
1932                 finishUndo();
1933                 moveCursorUpdate(false);
1934                 owner_->showState();
1935         }
1936         break;
1937                 
1938         case LFUN_UP:
1939         {
1940                 LyXText * lt = bv_->getLyXText();
1941                 
1942                 if (!lt->selection.mark())
1943                         beforeChange(lt);
1944                 update(lt, BufferView::UPDATE);
1945                 lt->cursorUp(bv_);
1946                 finishUndo();
1947                 moveCursorUpdate(false);
1948                 owner_->showState();
1949         }
1950         break;
1951                 
1952         case LFUN_DOWN:
1953         {
1954                 LyXText * lt = bv_->getLyXText();
1955                 
1956                 if (!lt->selection.mark())
1957                         beforeChange(lt);
1958                 update(lt, BufferView::UPDATE);
1959                 lt->cursorDown(bv_);
1960                 finishUndo();
1961                 moveCursorUpdate(false);
1962                 owner_->showState();
1963         }
1964         break;
1965
1966         case LFUN_UP_PARAGRAPH:
1967         {
1968                 LyXText * lt = bv_->getLyXText();
1969                 
1970                 if (!lt->selection.mark())
1971                         beforeChange(lt);
1972                 update(lt, BufferView::UPDATE);
1973                 lt->cursorUpParagraph(bv_);
1974                 finishUndo();
1975                 moveCursorUpdate(false);
1976                 owner_->showState();
1977         }
1978         break;
1979                 
1980         case LFUN_DOWN_PARAGRAPH:
1981         {
1982                 LyXText * lt = bv_->getLyXText();
1983                 
1984                 if (!lt->selection.mark())
1985                         beforeChange(lt);
1986                 update(lt, BufferView::UPDATE);
1987                 lt->cursorDownParagraph(bv_);
1988                 finishUndo();
1989                 moveCursorUpdate(false);
1990                 owner_->showState();
1991         }
1992         break;
1993                 
1994         case LFUN_PRIOR:
1995         {
1996                 LyXText * lt = bv_->getLyXText();
1997                 
1998                 if (!lt->selection.mark())
1999                         beforeChange(lt);
2000                 update(lt, BufferView::UPDATE);
2001                 cursorPrevious(lt);
2002                 finishUndo();
2003                 moveCursorUpdate(false);
2004                 owner_->showState();
2005         }
2006         break;
2007                 
2008         case LFUN_NEXT:
2009         {
2010                 LyXText * lt = bv_->getLyXText();
2011                 
2012                 if (!lt->selection.mark())
2013                         beforeChange(lt);
2014                 update(lt, BufferView::UPDATE);
2015                 cursorNext(lt);
2016                 finishUndo();
2017                 moveCursorUpdate(false);
2018                 owner_->showState();
2019         }
2020         break;
2021                 
2022         case LFUN_HOME:
2023         {
2024                 LyXText * lt = bv_->getLyXText();
2025                 
2026                 if (!lt->selection.mark())
2027                         beforeChange(lt);
2028                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2029                 lt->cursorHome(bv_);
2030                 finishUndo();
2031                 moveCursorUpdate(false);
2032                 owner_->showState();
2033         }
2034         break;
2035                 
2036         case LFUN_END:
2037         {
2038                 LyXText * lt = bv_->getLyXText();
2039                 
2040                 if (!lt->selection.mark())
2041                         beforeChange(lt);
2042                 update(lt,
2043                        BufferView::SELECT|BufferView::FITCUR);
2044                 lt->cursorEnd(bv_);
2045                 finishUndo();
2046                 moveCursorUpdate(false);
2047                 owner_->showState();
2048         }
2049         break;
2050                 
2051         case LFUN_SHIFT_TAB:
2052         case LFUN_TAB:
2053         {
2054                 LyXText * lt = bv_->getLyXText();
2055                 
2056                 if (!lt->selection.mark())
2057                         beforeChange(lt);
2058                 update(lt,
2059                        BufferView::SELECT|BufferView::FITCUR);
2060                 lt->cursorTab(bv_);
2061                 finishUndo();
2062                 moveCursorUpdate(false);
2063                 owner_->showState();
2064         }
2065         break;
2066                 
2067         case LFUN_WORDRIGHT:
2068         {
2069                 LyXText * lt = bv_->getLyXText();
2070                 
2071                 if (!lt->selection.mark())
2072                         beforeChange(lt);
2073                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2074                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2075                         lt->cursorLeftOneWord(bv_);
2076                 else
2077                         lt->cursorRightOneWord(bv_);
2078                 finishUndo();
2079                 moveCursorUpdate(false);
2080                 owner_->showState();
2081         }
2082         break;
2083                 
2084         case LFUN_WORDLEFT:
2085         {
2086                 LyXText * lt = bv_->getLyXText();
2087                 
2088                 if (!lt->selection.mark())
2089                         beforeChange(lt);
2090                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2091                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2092                         lt->cursorRightOneWord(bv_);
2093                 else
2094                         lt->cursorLeftOneWord(bv_);
2095                 finishUndo();
2096                 moveCursorUpdate(false);
2097                 owner_->showState();
2098         }
2099         break;
2100                 
2101         case LFUN_BEGINNINGBUF:
2102         {
2103                 LyXText * lt = bv_->getLyXText();
2104                 
2105                 if (!lt->selection.mark())
2106                         beforeChange(lt);
2107                 update(lt,
2108                        BufferView::SELECT|BufferView::FITCUR);
2109                 lt->cursorTop(bv_);
2110                 finishUndo();
2111                 moveCursorUpdate(false);
2112                 owner_->showState();
2113         }
2114         break;
2115                 
2116         case LFUN_ENDBUF:
2117         {
2118                 LyXText * lt = bv_->getLyXText();
2119                 
2120                 if (!lt->selection.mark())
2121                         beforeChange(lt);
2122                 update(lt,
2123                        BufferView::SELECT|BufferView::FITCUR);
2124                 lt->cursorBottom(bv_);
2125                 finishUndo();
2126                 moveCursorUpdate(false);
2127                 owner_->showState();
2128         }
2129         break;
2130       
2131                 /* cursor selection ---------------------------- */
2132         case LFUN_RIGHTSEL:
2133         {
2134                 LyXText * lt = bv_->getLyXText();
2135                 
2136                 update(lt,
2137                        BufferView::SELECT|BufferView::FITCUR);
2138                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2139                         lt->cursorLeft(bv_);
2140                 else
2141                         lt->cursorRight(bv_);
2142                 finishUndo();
2143                 moveCursorUpdate(true);
2144                 owner_->showState();
2145         }
2146         break;
2147                 
2148         case LFUN_LEFTSEL:
2149         {
2150                 LyXText * lt = bv_->getLyXText();
2151                 
2152                 update(lt,
2153                        BufferView::SELECT|BufferView::FITCUR);
2154                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2155                         lt->cursorRight(bv_);
2156                 else
2157                         lt->cursorLeft(bv_);
2158                 finishUndo();
2159                 moveCursorUpdate(true);
2160                 owner_->showState();
2161         }
2162         break;
2163                 
2164         case LFUN_UPSEL:
2165         {
2166                 LyXText * lt = bv_->getLyXText();
2167                 
2168                 update(lt,
2169                        BufferView::SELECT|BufferView::FITCUR);
2170                 lt->cursorUp(bv_);
2171                 finishUndo();
2172                 moveCursorUpdate(true);
2173                 owner_->showState();
2174         }
2175         break;
2176                 
2177         case LFUN_DOWNSEL:
2178         {
2179                 LyXText * lt = bv_->getLyXText();
2180                 
2181                 update(lt,
2182                        BufferView::SELECT|BufferView::FITCUR);
2183                 lt->cursorDown(bv_);
2184                 finishUndo();
2185                 moveCursorUpdate(true);
2186                 owner_->showState();
2187         }
2188         break;
2189
2190         case LFUN_UP_PARAGRAPHSEL:
2191         {
2192                 LyXText * lt = bv_->getLyXText();
2193                 
2194                 update(lt,
2195                        BufferView::SELECT|BufferView::FITCUR);
2196                 lt->cursorUpParagraph(bv_);
2197                 finishUndo();
2198                 moveCursorUpdate(true);
2199                 owner_->showState();
2200         }
2201         break;
2202                 
2203         case LFUN_DOWN_PARAGRAPHSEL:
2204         {
2205                 LyXText * lt = bv_->getLyXText();
2206                 
2207                 update(lt,
2208                        BufferView::SELECT|BufferView::FITCUR);
2209                 lt->cursorDownParagraph(bv_);
2210                 finishUndo();
2211                 moveCursorUpdate(true);
2212                 owner_->showState();
2213         }
2214         break;
2215                 
2216         case LFUN_PRIORSEL:
2217         {
2218                 LyXText * lt = bv_->getLyXText();
2219                 
2220                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2221                 cursorPrevious(lt);
2222                 finishUndo();
2223                 moveCursorUpdate(true);
2224                 owner_->showState();
2225         }
2226         break;
2227                 
2228         case LFUN_NEXTSEL:
2229         {
2230                 LyXText * lt = bv_->getLyXText();
2231                 
2232                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2233                 cursorNext(lt);
2234                 finishUndo();
2235                 moveCursorUpdate(true);
2236                 owner_->showState();
2237         }
2238         break;
2239                 
2240         case LFUN_HOMESEL:
2241         {
2242                 LyXText * lt = bv_->getLyXText();
2243                 
2244                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2245                 lt->cursorHome(bv_);
2246                 finishUndo();
2247                 moveCursorUpdate(true);
2248                 owner_->showState();
2249         }
2250         break;
2251                 
2252         case LFUN_ENDSEL:
2253         {
2254                 LyXText * lt = bv_->getLyXText();
2255                 
2256                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2257                 lt->cursorEnd(bv_);
2258                 finishUndo();
2259                 moveCursorUpdate(true);
2260                 owner_->showState();
2261         }
2262         break;
2263                 
2264         case LFUN_WORDRIGHTSEL:
2265         {
2266                 LyXText * lt = bv_->getLyXText();
2267                 
2268                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2269                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2270                         lt->cursorLeftOneWord(bv_);
2271                 else
2272                         lt->cursorRightOneWord(bv_);
2273                 finishUndo();
2274                 moveCursorUpdate(true);
2275                 owner_->showState();
2276         }
2277         break;
2278                 
2279         case LFUN_WORDLEFTSEL:
2280         {
2281                 LyXText * lt = bv_->getLyXText();
2282                 
2283                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2284                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2285                         lt->cursorRightOneWord(bv_);
2286                 else
2287                         lt->cursorLeftOneWord(bv_);
2288                 finishUndo();
2289                 moveCursorUpdate(true);
2290                 owner_->showState();
2291         }
2292         break;
2293                 
2294         case LFUN_BEGINNINGBUFSEL:
2295         {
2296                 LyXText * lt = bv_->getLyXText();
2297                 
2298                 if (lt->inset_owner)
2299                         break;
2300                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2301                 lt->cursorTop(bv_);
2302                 finishUndo();
2303                 moveCursorUpdate(true);
2304                 owner_->showState();
2305         }
2306         break;
2307                 
2308         case LFUN_ENDBUFSEL:
2309         {
2310                 LyXText * lt = bv_->getLyXText();
2311                 
2312                 if (lt->inset_owner)
2313                         break;
2314                 update(lt,
2315                        BufferView::SELECT|BufferView::FITCUR);
2316                 lt->cursorBottom(bv_);
2317                 finishUndo();
2318                 moveCursorUpdate(true);
2319                 owner_->showState();
2320         }
2321         break;
2322
2323                 // --- text changing commands ------------------------
2324         case LFUN_BREAKLINE:
2325         {
2326                 LyXText * lt = bv_->getLyXText();
2327
2328                 beforeChange(lt);
2329                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
2330                 update(lt,
2331                        BufferView::SELECT
2332                        | BufferView::FITCUR
2333                        | BufferView::CHANGE);
2334                 moveCursorUpdate(false);
2335         }
2336         break;
2337                 
2338         case LFUN_PROTECTEDSPACE:
2339         {
2340                 LyXText * lt = bv_->getLyXText();
2341
2342                 LyXLayout const & style = textclasslist
2343                         .Style(buffer_->params.textclass,
2344                                lt->cursor.par()->getLayout());
2345
2346                 if (style.free_spacing) {
2347                         lt->insertChar(bv_, ' ');
2348                         update(lt,
2349                                BufferView::SELECT
2350                                | BufferView::FITCUR
2351                                | BufferView::CHANGE);
2352                 } else {
2353                         protectedBlank(lt);
2354                 }
2355                 moveCursorUpdate(false);
2356         }
2357         break;
2358                 
2359         case LFUN_SETMARK:
2360         {
2361                 LyXText * lt = bv_->getLyXText();
2362
2363                 if (lt->selection.mark()) {
2364                         beforeChange(lt);
2365                         update(lt,
2366                                BufferView::SELECT
2367                                | BufferView::FITCUR);
2368                         owner_->getLyXFunc()->setMessage(N_("Mark removed"));
2369                 } else {
2370                         beforeChange(lt);
2371                         lt->selection.mark(true);
2372                         update(lt,
2373                                BufferView::SELECT
2374                                | BufferView::FITCUR);
2375                         owner_->getLyXFunc()->setMessage(N_("Mark set"));
2376                 }
2377                 lt->selection.cursor = lt->cursor;
2378         }
2379         break;
2380                 
2381         case LFUN_DELETE:
2382         {
2383                 LyXText * lt = bv_->getLyXText();
2384
2385                 if (!lt->selection.set()) {
2386                         lt->Delete(bv_);
2387                         lt->selection.cursor = lt->cursor;
2388                         update(lt,
2389                                BufferView::SELECT
2390                                | BufferView::FITCUR
2391                                | BufferView::CHANGE);
2392                         // It is possible to make it a lot faster still
2393                         // just comment out the line below...
2394                         showCursor();
2395                 } else {
2396                         bv_->cut(false);
2397                 }
2398                 moveCursorUpdate(false);
2399                 owner_->showState();
2400                 setState();
2401         }
2402         break;
2403
2404         case LFUN_DELETE_SKIP:
2405         {
2406                 LyXText * lt = bv_->getLyXText();
2407
2408                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2409                 
2410                 LyXCursor cursor = lt->cursor;
2411
2412                 if (!lt->selection.set()) {
2413                         if (cursor.pos() == cursor.par()->size()) {
2414                                 lt->cursorRight(bv_);
2415                                 cursor = lt->cursor;
2416                                 if (cursor.pos() == 0
2417                                     && !(cursor.par()->params().spaceTop()
2418                                          == VSpace (VSpace::NONE))) {
2419                                         lt->setParagraph
2420                                                 (bv_,
2421                                                  cursor.par()->params().lineTop(),
2422                                                  cursor.par()->params().lineBottom(),
2423                                                  cursor.par()->params().pagebreakTop(), 
2424                                                  cursor.par()->params().pagebreakBottom(),
2425                                                  VSpace(VSpace::NONE), 
2426                                                  cursor.par()->params().spaceBottom(),
2427                                                  cursor.par()->params().spacing(), 
2428                                                  cursor.par()->params().align(), 
2429                                                  cursor.par()->params().labelWidthString(), 0);
2430                                         lt->cursorLeft(bv_);
2431                                         update(lt, 
2432                                                BufferView::SELECT
2433                                                | BufferView::FITCUR
2434                                                | BufferView::CHANGE);
2435                                 } else {
2436                                         lt->cursorLeft(bv_);
2437                                         lt->Delete(bv_);
2438                                         lt->selection.cursor = lt->cursor;
2439                                         update(lt,
2440                                                BufferView::SELECT
2441                                                | BufferView::FITCUR
2442                                                | BufferView::CHANGE);
2443                                 }
2444                         } else {
2445                                 lt->Delete(bv_);
2446                                 lt->selection.cursor = lt->cursor;
2447                                 update(lt,
2448                                        BufferView::SELECT
2449                                        | BufferView::FITCUR
2450                                        | BufferView::CHANGE);
2451                         }
2452                 } else {
2453                         bv_->cut(false);
2454                 }
2455         }
2456         break;
2457
2458         /* -------> Delete word forward. */
2459         case LFUN_DELETE_WORD_FORWARD:
2460                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
2461                 bv_->getLyXText()->deleteWordForward(bv_);
2462                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2463                 moveCursorUpdate(false);
2464                 owner_->showState();
2465                 break;
2466
2467                 /* -------> Delete word backward. */
2468         case LFUN_DELETE_WORD_BACKWARD:
2469         {
2470                 LyXText * lt = bv_->getLyXText();
2471                 
2472                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2473                 lt->deleteWordBackward(bv_);
2474                 update(lt,
2475                        BufferView::SELECT
2476                        | BufferView::FITCUR
2477                        | BufferView::CHANGE);
2478                 moveCursorUpdate(false);
2479                 owner_->showState();
2480         }
2481         break;
2482                 
2483                 /* -------> Kill to end of line. */
2484         case LFUN_DELETE_LINE_FORWARD:
2485         {
2486                 LyXText * lt = bv_->getLyXText();
2487                 
2488                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2489                 lt->deleteLineForward(bv_);
2490                 update(lt,
2491                        BufferView::SELECT
2492                        | BufferView::FITCUR
2493                        | BufferView::CHANGE);
2494                 moveCursorUpdate(false);
2495         }
2496         break;
2497                 
2498                 /* -------> Set mark off. */
2499         case LFUN_MARK_OFF:
2500         {
2501                 LyXText * lt = bv_->getLyXText();
2502                 
2503                 beforeChange(lt);
2504                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2505                 lt->selection.cursor = lt->cursor;
2506                 owner_->getLyXFunc()->setMessage(N_("Mark off"));
2507         }
2508         break;
2509
2510                 /* -------> Set mark on. */
2511         case LFUN_MARK_ON:
2512         {
2513                 LyXText * lt = bv_->getLyXText();
2514                 
2515                 beforeChange(lt);
2516                 lt->selection.mark(true);
2517                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2518                 lt->selection.cursor = lt->cursor;
2519                 owner_->getLyXFunc()->setMessage(N_("Mark on"));
2520         }
2521         break;
2522                 
2523         case LFUN_BACKSPACE:
2524         {
2525                 LyXText * lt = bv_->getLyXText();
2526                 
2527                 if (!lt->selection.set()) {
2528                         if (owner_->getIntl()->getTrans().backspace()) {
2529                                 lt->backspace(bv_);
2530                                 lt->selection.cursor = lt->cursor;
2531                                 update(lt,
2532                                        BufferView::SELECT
2533                                        | BufferView::FITCUR
2534                                        | BufferView::CHANGE);
2535                                 // It is possible to make it a lot faster still
2536                                 // just comment out the line below...
2537                                 showCursor();
2538                         }
2539                 } else {
2540                         bv_->cut(false);
2541                 }
2542                 owner_->showState();
2543                 setState();
2544         }
2545         break;
2546
2547         case LFUN_BACKSPACE_SKIP:
2548         {
2549                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2550                 LyXText * lt = bv_->getLyXText();
2551                 
2552                 LyXCursor cursor = lt->cursor;
2553                 
2554                 if (!lt->selection.set()) {
2555                         if (cursor.pos() == 0 
2556                             && !(cursor.par()->params().spaceTop() 
2557                                  == VSpace (VSpace::NONE))) {
2558                                 lt->setParagraph 
2559                                         (bv_,
2560                                          cursor.par()->params().lineTop(),      
2561                                          cursor.par()->params().lineBottom(),
2562                                          cursor.par()->params().pagebreakTop(), 
2563                                          cursor.par()->params().pagebreakBottom(),
2564                                          VSpace(VSpace::NONE), cursor.par()->params().spaceBottom(),
2565                                          cursor.par()->params().spacing(), 
2566                                          cursor.par()->params().align(), 
2567                                          cursor.par()->params().labelWidthString(), 0);
2568                                 update(lt,
2569                                        BufferView::SELECT
2570                                        | BufferView::FITCUR
2571                                        | BufferView::CHANGE);
2572                         } else {
2573                                 lt->backspace(bv_);
2574                                 lt->selection.cursor = cursor;
2575                                 update(lt,
2576                                        BufferView::SELECT
2577                                        | BufferView::FITCUR
2578                                        | BufferView::CHANGE);
2579                         }
2580                 } else
2581                         bv_->cut(false);
2582         }
2583         break;
2584
2585         case LFUN_BREAKPARAGRAPH:
2586         {
2587                 LyXText * lt = bv_->getLyXText();
2588                 
2589                 beforeChange(lt);
2590                 lt->breakParagraph(bv_, 0);
2591                 update(lt,
2592                        BufferView::SELECT
2593                        | BufferView::FITCUR
2594                        | BufferView::CHANGE);
2595                 lt->selection.cursor = lt->cursor;
2596                 setState();
2597                 owner_->showState();
2598                 break;
2599         }
2600
2601         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
2602         {
2603                 LyXText * lt = bv_->getLyXText();
2604                 
2605                 beforeChange(lt);
2606                 lt->breakParagraph(bv_, 1);
2607                 update(lt,
2608                        BufferView::SELECT
2609                        | BufferView::FITCUR
2610                        | BufferView::CHANGE);
2611                 lt->selection.cursor = lt->cursor;
2612                 setState();
2613                 owner_->showState();
2614                 break;
2615         }
2616         
2617         case LFUN_BREAKPARAGRAPH_SKIP:
2618         {
2619                 // When at the beginning of a paragraph, remove
2620                 // indentation and add a "defskip" at the top.
2621                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
2622                 LyXText * lt = bv_->getLyXText();
2623                 
2624                 LyXCursor cursor = lt->cursor;
2625                 
2626                 beforeChange(lt);
2627                 if (cursor.pos() == 0) {
2628                         if (cursor.par()->params().spaceTop() == VSpace(VSpace::NONE)) {
2629                                 lt->setParagraph
2630                                         (bv_,
2631                                          cursor.par()->params().lineTop(),
2632                                          cursor.par()->params().lineBottom(),
2633                                          cursor.par()->params().pagebreakTop(),
2634                                          cursor.par()->params().pagebreakBottom(),
2635                                          VSpace(VSpace::DEFSKIP), cursor.par()->params().spaceBottom(),
2636                                          cursor.par()->params().spacing(),
2637                                          cursor.par()->params().align(),
2638                                          cursor.par()->params().labelWidthString(), 1);
2639                                 //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2640                         } 
2641                 }
2642                 else {
2643                         lt->breakParagraph(bv_, 0);
2644                         //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2645                 }
2646
2647                 update(lt,
2648                        BufferView::SELECT
2649                        | BufferView::FITCUR
2650                        | BufferView::CHANGE);
2651                 lt->selection.cursor = cursor;
2652                 setState();
2653                 owner_->showState();
2654         }
2655         break;
2656
2657         case LFUN_PARAGRAPH_SPACING:
2658         {
2659                 LyXText * lt = bv_->getLyXText();
2660                 
2661                 Paragraph * par = lt->cursor.par();
2662                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
2663                 float cur_value = 1.0;
2664                 if (cur_spacing == Spacing::Other) {
2665                         cur_value = par->params().spacing().getValue();
2666                 }
2667                 
2668                 istringstream istr(argument.c_str());
2669
2670                 string tmp;
2671                 istr >> tmp;
2672                 Spacing::Space new_spacing = cur_spacing;
2673                 float new_value = cur_value;
2674                 if (tmp.empty()) {
2675                         lyxerr << "Missing argument to `paragraph-spacing'"
2676                                << endl;
2677                 } else if (tmp == "single") {
2678                         new_spacing = Spacing::Single;
2679                 } else if (tmp == "onehalf") {
2680                         new_spacing = Spacing::Onehalf;
2681                 } else if (tmp == "double") {
2682                         new_spacing = Spacing::Double;
2683                 } else if (tmp == "other") {
2684                         new_spacing = Spacing::Other;
2685                         float tmpval = 0.0;
2686                         istr >> tmpval;
2687                         lyxerr << "new_value = " << tmpval << endl;
2688                         if (tmpval != 0.0)
2689                                 new_value = tmpval;
2690                 } else if (tmp == "default") {
2691                         new_spacing = Spacing::Default;
2692                 } else {
2693                         lyxerr << _("Unknown spacing argument: ")
2694                                << argument << endl;
2695                 }
2696                 if (cur_spacing != new_spacing || cur_value != new_value) {
2697                         par->params().spacing(Spacing(new_spacing, new_value));
2698                         lt->redoParagraph(bv_);
2699                         update(lt,
2700                                BufferView::SELECT
2701                                | BufferView::FITCUR
2702                                | BufferView::CHANGE);
2703                 }
2704         }
2705         break;
2706         
2707         case LFUN_INSET_TOGGLE:
2708         {
2709                 LyXText * lt = bv_->getLyXText();
2710                 hideCursor();
2711                 beforeChange(lt);
2712                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2713                 lt->toggleInset(bv_);
2714                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2715                 setState();
2716         }       
2717                 break;
2718
2719         case LFUN_QUOTE:
2720                 smartQuote();
2721                 break;
2722
2723         case LFUN_HTMLURL:
2724         case LFUN_URL:
2725         {
2726                 InsetCommandParams p;
2727                 if (action == LFUN_HTMLURL)
2728                         p.setCmdName("htmlurl");
2729                 else
2730                         p.setCmdName("url");
2731                 owner_->getDialogs()->createUrl(p.getAsString());
2732         }
2733         break;
2734         
2735         case LFUN_INSERT_URL:
2736         {
2737                 InsetCommandParams p;
2738                 p.setFromString(argument);
2739
2740                 InsetUrl * inset = new InsetUrl(p);
2741                 if (!insertInset(inset))
2742                         delete inset;
2743                 else
2744                         updateInset(inset, true);
2745         }
2746         break;
2747         
2748         case LFUN_INSET_TEXT:
2749                 insertAndEditInset(new InsetText);
2750                 break;
2751         
2752         case LFUN_INSET_ERT:
2753                 insertAndEditInset(new InsetERT);
2754                 break;
2755         
2756         case LFUN_INSET_EXTERNAL:
2757                 insertAndEditInset(new InsetExternal);
2758                 break;
2759         
2760         case LFUN_INSET_FOOTNOTE:
2761                 insertAndEditInset(new InsetFoot);
2762                 break;
2763
2764         case LFUN_INSET_MARGINAL:
2765                 insertAndEditInset(new InsetMarginal);
2766                 break;
2767
2768         case LFUN_INSET_MINIPAGE:
2769                 insertAndEditInset(new InsetMinipage);
2770                 break;
2771
2772         case LFUN_INSERT_NOTE:
2773                 insertAndEditInset(new InsetNote);
2774                 break;
2775
2776         case LFUN_INSET_FLOAT:
2777                 // check if the float type exist
2778                 if (floatList.typeExist(argument)) {
2779                         insertAndEditInset(new InsetFloat(argument));
2780                 } else {
2781                         lyxerr << "Non-existent float type: "
2782                                << argument << endl;
2783                 }
2784                 break;
2785
2786         case LFUN_INSET_WIDE_FLOAT:
2787         {
2788                 // check if the float type exist
2789                 if (floatList.typeExist(argument)) {
2790                         InsetFloat * new_inset = new InsetFloat(argument);
2791                         new_inset->wide(true);
2792                         if (insertInset(new_inset))
2793                                 new_inset->edit(bv_);
2794                         else
2795                                 delete new_inset;
2796                 } else {
2797                         lyxerr << "Non-existent float type: "
2798                                << argument << endl;
2799                 }
2800                 
2801         }
2802         break;
2803
2804 #if 0
2805         case LFUN_INSET_LIST:
2806                 insertAndEditInset(new InsetList);
2807                 break;
2808
2809         case LFUN_INSET_THEOREM:
2810                 insertAndEditInset(new InsetTheorem);
2811                 break;
2812 #endif
2813                 
2814         case LFUN_INSET_CAPTION:
2815         {
2816                 // Do we have a locking inset...
2817                 if (bv_->theLockingInset()) {
2818                         lyxerr << "Locking inset code: "
2819                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
2820                         InsetCaption * new_inset = new InsetCaption;
2821                         new_inset->setOwner(bv_->theLockingInset());
2822                         new_inset->setAutoBreakRows(true);
2823                         new_inset->setDrawFrame(0, InsetText::LOCKED);
2824                         new_inset->setFrameColor(0, LColor::captionframe);
2825                         if (insertInset(new_inset))
2826                                 new_inset->edit(bv_);
2827                         else
2828                                 delete new_inset;
2829                 }
2830         }
2831         break;
2832         
2833         case LFUN_INSET_TABULAR:
2834         {
2835                 int r = 2;
2836                 int c = 2;
2837                 if (!argument.empty())
2838                         ::sscanf(argument.c_str(),"%d%d", &r, &c);
2839                 InsetTabular * new_inset =
2840                         new InsetTabular(*buffer_, r, c);
2841                 bool const rtl =
2842                         bv_->getLyXText()->real_current_font.isRightToLeft();
2843                 if (!open_new_inset(new_inset, rtl))
2844                         delete new_inset;
2845         }
2846         break;
2847
2848         // --- lyxserver commands ----------------------------
2849
2850         case LFUN_CHARATCURSOR:
2851         {
2852                 pos_type pos = bv_->getLyXText()->cursor.pos();
2853                 if (pos < bv_->getLyXText()->cursor.par()->size())
2854                         owner_->getLyXFunc()->setMessage(
2855                                 tostr(bv_->getLyXText()->cursor.par()->getChar(pos)));
2856                 else
2857                         owner_->getLyXFunc()->setMessage("EOF");
2858         }
2859         break;
2860         
2861         case LFUN_GETXY:
2862                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.x())
2863                                                  + ' '
2864                                                  + tostr(bv_->getLyXText()->cursor.y()));
2865                 break;
2866                 
2867         case LFUN_SETXY:
2868         {
2869                 int x = 0;
2870                 int y = 0;
2871                 if (::sscanf(argument.c_str(), " %d %d", &x, &y) != 2) {
2872                         lyxerr << "SETXY: Could not parse coordinates in '"
2873                                << argument << std::endl;
2874                 }
2875                 bv_->getLyXText()->setCursorFromCoordinates(bv_, x, y);
2876         }
2877         break;
2878         
2879         case LFUN_GETLAYOUT:
2880                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.par()->layout));
2881                 break;
2882                         
2883         case LFUN_GETFONT:
2884         {
2885                 LyXFont & font = bv_->getLyXText()->current_font;
2886                 if (font.shape() == LyXFont::ITALIC_SHAPE)
2887                         owner_->getLyXFunc()->setMessage("E");
2888                 else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
2889                         owner_->getLyXFunc()->setMessage("N");
2890                 else
2891                         owner_->getLyXFunc()->setMessage("0");
2892
2893         }
2894         break;
2895
2896         // --- accented characters ---------------------------
2897                 
2898         case LFUN_UMLAUT:
2899         case LFUN_CIRCUMFLEX:
2900         case LFUN_GRAVE:
2901         case LFUN_ACUTE:
2902         case LFUN_TILDE:
2903         case LFUN_CEDILLA:
2904         case LFUN_MACRON:
2905         case LFUN_DOT:
2906         case LFUN_UNDERDOT:
2907         case LFUN_UNDERBAR:
2908         case LFUN_CARON:
2909         case LFUN_SPECIAL_CARON:
2910         case LFUN_BREVE:
2911         case LFUN_TIE:
2912         case LFUN_HUNG_UMLAUT:
2913         case LFUN_CIRCLE:
2914         case LFUN_OGONEK:
2915                 if (argument.empty()) {
2916                         // As always...
2917                         owner_->getLyXFunc()->handleKeyFunc(action);
2918                 } else {
2919                         owner_->getLyXFunc()->handleKeyFunc(action);
2920                         owner_->getIntl()->getTrans()
2921                                 .TranslateAndInsert(argument[0], bv_->getLyXText());
2922                         update(bv_->getLyXText(),
2923                                BufferView::SELECT
2924                                | BufferView::FITCUR
2925                                | BufferView::CHANGE);
2926                 }
2927                 break;
2928         
2929         case LFUN_MATH_MACRO:
2930                 mathDispatchMathMacro(bv_, argument);
2931                 break;
2932
2933         case LFUN_MATH_DELIM:     
2934                 mathDispatchMathDelim(bv_, argument);
2935                 break;
2936
2937         case LFUN_INSERT_MATRIX:
2938                 mathDispatchInsertMatrix(bv_, argument);
2939                 break;
2940
2941         case LFUN_INSERT_MATH:
2942                 mathDispatchInsertMath(bv_, argument);
2943                 break;
2944
2945         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
2946                 mathDispatchMathImportSelection(bv_, argument);
2947                 break;
2948
2949         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
2950                 mathDispatchMathDisplay(bv_, argument);
2951                 break;
2952
2953         case LFUN_MATH_MODE:             // Open or create an inlined math inset 
2954                 mathDispatchMathMode(bv_, argument);
2955                 break;
2956                 
2957         case LFUN_GREEK:                 // Insert a single greek letter
2958                 mathDispatchGreek(bv_, argument);
2959                 break;
2960                 
2961         case LFUN_CITATION_INSERT:
2962         {
2963                 InsetCommandParams p;
2964                 p.setFromString( argument );
2965
2966                 InsetCitation * inset = new InsetCitation( p );
2967                 if (!insertInset(inset))
2968                         delete inset;
2969                 else
2970                         updateInset( inset, true );
2971         }
2972         break;
2973                     
2974         case LFUN_INSERT_BIBTEX:
2975         {   
2976                 // ale970405+lasgoutt970425
2977                 // The argument can be up to two tokens separated 
2978                 // by a space. The first one is the bibstyle.
2979                 string const db       = token(argument, ' ', 0);
2980                 string const bibstyle = token(argument, ' ', 1);
2981
2982                 InsetCommandParams p( "BibTeX", db, bibstyle );
2983                 InsetBibtex * inset = new InsetBibtex(p);
2984                 
2985                 if (insertInset(inset)) {
2986                         if (argument.empty())
2987                                 inset->edit(bv_);
2988                 } else
2989                         delete inset;
2990         }
2991         break;
2992                 
2993         // BibTeX data bases
2994         case LFUN_BIBDB_ADD:
2995         {
2996                 InsetBibtex * inset = 
2997                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2998                 if (inset) {
2999                         inset->addDatabase(argument);
3000                 }
3001         }
3002         break;
3003                     
3004         case LFUN_BIBDB_DEL:
3005         {
3006                 InsetBibtex * inset = 
3007                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3008                 if (inset) {
3009                         inset->delDatabase(argument);
3010                 }
3011         }
3012         break;
3013         
3014         case LFUN_BIBTEX_STYLE:
3015         {
3016                 InsetBibtex * inset = 
3017                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3018                 if (inset) {
3019                         inset->setOptions(argument);
3020                 }
3021         }
3022         break;
3023                 
3024         case LFUN_INDEX_CREATE:
3025         {
3026                 InsetCommandParams p("index");
3027                 if (argument.empty()) {
3028                         string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3029                         p.setContents(idxstring);
3030                 } else {
3031                         p.setContents(argument);
3032                 }
3033
3034                 owner_->getDialogs()->createIndex(p.getAsString());
3035         }
3036         break;
3037                     
3038         case LFUN_INDEX_INSERT:
3039         {
3040                 InsetCommandParams p;
3041                 p.setFromString(argument);
3042                 InsetIndex * inset = new InsetIndex(p);
3043
3044                 if (!insertInset(inset))
3045                         delete inset;
3046                 else
3047                         updateInset(inset, true);
3048         }
3049         break;
3050                     
3051         case LFUN_INDEX_INSERT_LAST:
3052         {
3053                 string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3054                 if (!idxstring.empty()) {
3055                         owner_->message(_("Word `")
3056                                         + idxstring + _(("' indexed.")));
3057                         InsetCommandParams p("index", idxstring);
3058                         InsetIndex * inset = new InsetIndex(p);
3059                         
3060                         if (!insertInset(inset))
3061                                 delete inset;
3062                         else
3063                                 updateInset(inset, true);
3064                 }
3065         }
3066         break;
3067
3068         case LFUN_INDEX_PRINT:
3069         {
3070                 InsetCommandParams p("printindex");
3071                 Inset * inset = new InsetPrintIndex(p);
3072                 if (!insertInset(inset, "Standard"))
3073                         delete inset;
3074         }
3075         break;
3076
3077         case LFUN_PARENTINSERT:
3078         {
3079                 lyxerr << "arg " << argument << endl;
3080                 InsetCommandParams p( "lyxparent", argument );
3081                 Inset * inset = new InsetParent(p, *buffer_);
3082                 if (!insertInset(inset, "Standard"))
3083                         delete inset;
3084         }
3085                  
3086         break;
3087
3088         case LFUN_CHILD_INSERT:
3089         {
3090                 InsetInclude::Params p;
3091                 p.cparams.setFromString(argument);
3092                 p.masterFilename_ = buffer_->fileName();
3093
3094                 InsetInclude * inset = new InsetInclude(p);
3095                 if (!insertInset(inset))
3096                         delete inset;
3097                 else {
3098                         updateInset(inset, true);
3099                         bv_->owner()->getDialogs()->showInclude(inset);
3100                 }
3101         }
3102         break; 
3103
3104         case LFUN_FLOAT_LIST:
3105         {
3106                 // We should check the argument for validity. (Lgb)
3107                 Inset * inset = new InsetFloatList(argument);
3108                 if (!insertInset(inset, "Standard"))
3109                         delete inset;
3110         }
3111         break;
3112         
3113         case LFUN_THESAURUS_ENTRY:
3114         {
3115                 string arg = argument;
3116
3117                 if (arg.empty()) {
3118                         arg = bv_->getLyXText()->selectionAsString(buffer_,
3119                                                                    false);
3120  
3121                         // FIXME
3122                         if (arg.size() > 100 || arg.empty()) {
3123                                 // Get word or selection
3124                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
3125                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
3126                                 // FIXME: where is getLyXText()->unselect(bv_) ?
3127                         }
3128                 }
3129
3130                 bv_->owner()->getDialogs()->showThesaurus(arg);
3131         }
3132                 break;
3133  
3134         case LFUN_SELFINSERT:
3135         {
3136                 if (argument.empty()) break;
3137                 
3138                 /* Automatically delete the currently selected
3139                  * text and replace it with what is being
3140                  * typed in now. Depends on lyxrc settings
3141                  * "auto_region_delete", which defaults to
3142                  * true (on). */
3143
3144                 LyXText * lt = bv_->getLyXText();
3145                 
3146                 if (lyxrc.auto_region_delete) {
3147                         if (lt->selection.set()) {
3148                                 lt->cutSelection(bv_, false, false);
3149                                 bv_->update(lt,
3150                                             BufferView::SELECT
3151                                             | BufferView::FITCUR
3152                                             | BufferView::CHANGE);
3153                         }
3154                 }
3155                 
3156                 beforeChange(lt);
3157                 LyXFont const old_font(lt->real_current_font);
3158                 
3159                 string::const_iterator cit = argument.begin();
3160                 string::const_iterator end = argument.end();
3161                 for (; cit != end; ++cit) {
3162                         owner_->getIntl()->getTrans().TranslateAndInsert(*cit, lt);
3163                 }
3164                 
3165                 bv_->update(lt,
3166                             BufferView::SELECT
3167                             | BufferView::FITCUR
3168                             | BufferView::CHANGE);
3169                 
3170                 lt->selection.cursor = lt->cursor;
3171                 moveCursorUpdate(false);
3172                 
3173                 // real_current_font.number can change so we need to
3174                 // update the minibuffer
3175                 if (old_font != lt->real_current_font)
3176                         owner_->showState();
3177                 //return string();
3178         }
3179         break;
3180
3181         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
3182         {
3183                 time_t now_time_t = time(NULL);
3184                 struct tm * now_tm = localtime(&now_time_t);
3185                 setlocale(LC_TIME, "");
3186                 string arg;
3187                 if (!argument.empty())
3188                         arg = argument;
3189                 else 
3190                         arg = lyxrc.date_insert_format;
3191                 char datetmp[32];
3192                 int const datetmp_len =
3193                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
3194
3195                 LyXText * lt = bv_->getLyXText();
3196                 
3197                 for (int i = 0; i < datetmp_len; i++) {
3198                         lt->insertChar(bv_, datetmp[i]);
3199                         update(lt,
3200                                BufferView::SELECT
3201                                | BufferView::FITCUR
3202                                | BufferView::CHANGE);
3203                 }
3204
3205                 lt->selection.cursor = lt->cursor;
3206                 moveCursorUpdate(false);
3207         }
3208         break;
3209
3210         case LFUN_UNKNOWN_ACTION:
3211                 owner_->getLyXFunc()->setErrorMessage(N_("Unknown function!"));
3212                 break;
3213         
3214         default:
3215                 return false;
3216         } // end of switch
3217
3218         return true;
3219 }
3220
3221
3222 void BufferView::Pimpl::newline()
3223 {
3224         if (available()) {
3225                 LyXText * lt = bv_->getLyXText();
3226                 hideCursor();
3227                 update(lt,
3228                        BufferView::SELECT
3229                        | BufferView::FITCUR);
3230                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
3231                 update(lt,
3232                        BufferView::SELECT
3233                        | BufferView::FITCUR
3234                        | BufferView::CHANGE);
3235         }
3236 }
3237
3238
3239 void BufferView::Pimpl::hfill()
3240 {
3241         if (available()) {
3242                 LyXText * lt = bv_->getLyXText();
3243                 hideCursor();
3244                 update(lt,
3245                        BufferView::SELECT
3246                        | BufferView::FITCUR);
3247                 lt->insertChar(bv_, Paragraph::META_HFILL);
3248                 update(lt,
3249                        BufferView::SELECT
3250                        | BufferView::FITCUR
3251                        | BufferView::CHANGE);
3252         }
3253 }
3254
3255
3256 void BufferView::Pimpl::protectedBlank(LyXText * lt)
3257 {
3258         if (available()) {
3259                 hideCursor();
3260                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3261                 InsetSpecialChar * new_inset =
3262                         new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
3263 #ifdef WITH_WARNINGS
3264 #warning Why is this code different from specialChar() below? (JMarc)
3265 // the code in specialChar is a generic version of what used to exist
3266 // for other special chars. I did not merge this case because of the
3267 // call to updateInset(), but what does it do?
3268 #endif
3269                 if (!insertInset(new_inset))
3270                         delete new_inset;
3271                 else
3272                         updateInset(new_inset, true);
3273         }
3274 }
3275
3276
3277 void BufferView::Pimpl::specialChar(InsetSpecialChar::Kind kind)
3278 {
3279         if (available()) {
3280                 LyXText * lt = bv_->getLyXText();
3281                 
3282                 hideCursor();
3283                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3284                 InsetSpecialChar * new_inset = 
3285                         new InsetSpecialChar(kind);
3286                 if (!insertInset(new_inset))
3287                         delete new_inset;
3288         }
3289 }
3290
3291
3292 void BufferView::Pimpl::smartQuote()
3293 {
3294         LyXText const * lt = bv_->getLyXText();
3295         Paragraph const * par = lt->cursor.par();
3296         pos_type pos = lt->cursor.pos();
3297         char c;
3298
3299         if (!pos
3300             || (par->isInset(pos - 1)
3301                 && par->getInset(pos - 1)->isSpace()))
3302                 c = ' ';
3303         else
3304                 c = par->getChar(pos - 1);
3305                 
3306
3307         hideCursor();
3308
3309         LyXLayout const & style = textclasslist.Style(
3310                 bv_->buffer()->params.textclass, par->getLayout());
3311         
3312         if (style.pass_thru ||
3313                 (!insertInset(new InsetQuotes(c, bv_->buffer()->params))))
3314                 bv_->owner()->getLyXFunc()->dispatch(LFUN_SELFINSERT, "\"");
3315 }
3316
3317
3318 void BufferView::Pimpl::insertAndEditInset(Inset * inset)
3319 {
3320         if (insertInset(inset))
3321                 inset->edit(bv_);
3322         else
3323                 delete inset;
3324 }
3325
3326  
3327 // Open and lock an updatable inset
3328 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
3329 {
3330         LyXText * lt = bv_->getLyXText();
3331         
3332         beforeChange(lt);
3333         finishUndo();
3334         if (!insertInset(new_inset)) {
3335                 delete new_inset;
3336                 return false;
3337         }
3338         new_inset->edit(bv_, !behind);
3339         return true;
3340 }
3341
3342
3343 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
3344 {
3345         // if we are in a locking inset we should try to insert the
3346         // inset there otherwise this is a illegal function now
3347         if (bv_->theLockingInset()) {
3348                 if (bv_->theLockingInset()->insetAllowed(inset))
3349                     return bv_->theLockingInset()->insertInset(bv_, inset);
3350                 return false;
3351         }
3352
3353         // not quite sure if we want this...
3354         setCursorParUndo(bv_);
3355         freezeUndo();
3356         
3357         beforeChange(bv_->text);
3358         if (!lout.empty()) {
3359                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3360                 bv_->text->breakParagraph(bv_);
3361                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3362
3363                 if (bv_->text->cursor.par()->size()) {
3364                         bv_->text->cursorLeft(bv_);
3365                         
3366                         bv_->text->breakParagraph(bv_);
3367                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3368                 }
3369
3370                 pair<bool, layout_type> lres =
3371                         textclasslist.NumberOfLayout(buffer_->params .textclass, lout);
3372                 layout_type lay = 0;
3373                 if (lres.first != false) {
3374                         // layout found
3375                         lay = lres.second;
3376                 } else {
3377                         // layout not fount using default "Standard" (0)
3378                         lay = 0;
3379                 }
3380                  
3381                 bv_->text->setLayout(bv_, lay);
3382                 
3383                 bv_->text->setParagraph(bv_, 0, 0,
3384                                    0, 0,
3385                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3386                                    Spacing(),
3387                                    LYX_ALIGN_LAYOUT, 
3388                                    string(),
3389                                    0);
3390                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3391         }
3392         
3393         bv_->text->insertInset(bv_, inset);
3394         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3395
3396         unFreezeUndo();
3397         return true;
3398 }
3399
3400
3401 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
3402 {
3403         if (!inset)
3404                 return;
3405
3406         // first check for locking insets
3407         if (bv_->theLockingInset()) {
3408                 if (bv_->theLockingInset() == inset) {
3409                         if (bv_->text->updateInset(bv_, inset)) {
3410                                 update();
3411                                 if (mark_dirty) {
3412                                         buffer_->markDirty();
3413                                 }
3414                                 updateScrollbar();
3415                                 return;
3416                         }
3417                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
3418                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
3419                                 update();
3420                                 if (mark_dirty){
3421                                         buffer_->markDirty();
3422                                 }
3423                                 updateScrollbar();
3424                                 return;
3425                         }
3426                 }
3427         }
3428   
3429         // then check the current buffer
3430         if (available()) {
3431                 hideCursor();
3432                 update(bv_->text, BufferView::UPDATE);
3433                 if (bv_->text->updateInset(bv_, inset)) {
3434                         if (mark_dirty) {
3435                                 update(bv_->text,
3436                                        BufferView::SELECT
3437                                        | BufferView::FITCUR
3438                                        | BufferView::CHANGE);
3439                         } else {
3440                                 update(bv_->text, SELECT);
3441                         }
3442                         return;
3443                 }
3444         }
3445 }
3446
3447
3448 void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
3449                                   bool same_content)
3450 {
3451         if (!available()) return;
3452         
3453         hideCursor();
3454         beforeChange(bv_->text);
3455         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3456         
3457         LyXCursor const & cursor = bv_->text->cursor;
3458  
3459         string contents;
3460         if (same_content &&
3461             cursor.par()->isInset(cursor.pos())) {
3462                 Inset const * inset = cursor.par()->getInset(cursor.pos());
3463                 if (find(codes.begin(), codes.end(), inset->lyxCode())
3464                     != codes.end())
3465                         contents =
3466                                 static_cast<InsetCommand const *>(inset)->getContents();
3467         }
3468         
3469  
3470         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3471                 if (bv_->text->cursor.pos() 
3472                     || bv_->text->cursor.par() != bv_->text->ownerParagraph()) {
3473                         LyXCursor tmp = bv_->text->cursor;
3474                         bv_->text->cursor.par(bv_->text->ownerParagraph());
3475                         bv_->text->cursor.pos(0);
3476                         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3477                                 bv_->text->cursor = tmp;
3478                                 bv_->owner()->message(_("No more insets"));
3479                         }
3480                 } else {
3481                         bv_->owner()->message(_("No more insets"));
3482                 }
3483         }
3484         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3485         bv_->text->selection.cursor = bv_->text->cursor;
3486 }
3487
3488
3489 void BufferView::Pimpl::gotoInset(Inset::Code code, bool same_content)
3490 {
3491         gotoInset(vector<Inset::Code>(1, code), same_content);
3492 }