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