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